Initial commit

This commit is contained in:
Evert Prants 2020-05-08 19:19:21 +03:00
commit d7698684be
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
9 changed files with 662 additions and 0 deletions

14
.editorconfig Normal file
View File

@ -0,0 +1,14 @@
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# Matches multiple files with brace expansion notation
# Set default charset
[*.js]
charset = utf-8
indent_style = space
indent_size = 2

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
/node_modules/
/dist/
/package-lock.json
/**/dna.txt
*.db
*.sqlite3

56
demo.html Normal file
View File

@ -0,0 +1,56 @@
<!DOCTYPE html>
<html>
<head>
<title>qplanets demo</title>
<script type="text/javascript" src="./node_modules/three/build/three.js"></script>
<script type="text/javascript" src="./node_modules/three/examples/js/controls/OrbitControls.js"></script>
<script type="text/javascript" src="./lib/qplanets.js"></script>
<style type="text/css">body{margin:0;}</style>
</head>
<body>
<script type="text/javascript">
/* global THREE, requestAnimationFrame */
(function () {
var scene = new THREE.Scene()
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000)
var renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
var controls = new THREE.OrbitControls(camera, renderer.domElement)
document.body.appendChild(renderer.domElement)
var atmosphereSize = 25
var light = { position: new THREE.Vector3(0, 100, 10) }
var planetgen = new THREE.Extras.Planet.PlanetGenerator(1000)
var planet = new THREE.Extras.Planet.CubePlanet(new THREE.Vector3(0, 0, 0), planetgen)
var attnShader = THREE.Extras.Planet.ScatterShader.newAttenuate(planet.radius, planet.radius + atmosphereSize)
attnShader.uniforms.color = { value: new THREE.Color(0x001100), type: 'v3' }
attnShader.uniforms.planetPosition = { value: planet.position, type: 'v3' }
attnShader.uniforms.lightDirection = { value: light.position.sub(planet.position).normalize(), type: 'v3' }
attnShader.wireframe = true
planet.setMaterial(attnShader)
scene.add(planet)
var atmosGeom = new THREE.SphereGeometry(planet.radius + atmosphereSize, 100, 100)
var atmosShader = THREE.Extras.Planet.ScatterShader.newAtmosphere(planet.radius, planet.radius + atmosphereSize)
var atmos = new THREE.Mesh(atmosGeom, atmosShader)
atmosShader.uniforms.planetPosition = { value: planet.position, type: 'v3' }
atmosShader.uniforms.lightDirection = { value: light.position.sub(planet.position).normalize(), type: 'v3' }
scene.add(atmos)
camera.position.x = -100
camera.position.z = 1800
function animate () {
requestAnimationFrame(animate)
planet.update(camera)
controls.update()
renderer.render(scene, camera)
}
animate()
})()
</script>
</body>
</html>

1
lib/qplanets.js Normal file

File diff suppressed because one or more lines are too long

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "qplanets.js",
"version": "0.0.1",
"description": "THREE.js extension for procedural planets",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p",
"watch": "webpack -w --mode=development"
},
"keywords": [],
"private": true,
"author": "Evert \"Diamond\" Prants <evert@lunasqu.ee>",
"license": "MIT",
"devDependencies": {
"express": "^4.16.4",
"standard": "^14.3.3",
"three": "^0.116.1",
"webpack": "^4.26.0",
"webpack-command": "^0.5.0"
}
}

View File

@ -0,0 +1,198 @@
const ATMOSPHERE = {
vertexUniforms: `
#define M_PI 3.1415926535897932384626433832795
uniform vec3 planetPosition; // Position of the planet
uniform vec3 lightDirection; // The direction vector to the light source
uniform vec3 invWavelength; // 1 / pow(wavelength, 4) for the red, green, and blue channels
uniform float outerRadius; // The outer (atmosphere) radius
uniform float innerRadius; // The inner (planetary) radius
uniform float ESun; // ESun
uniform float Km; // Km
uniform float Kr; // Kr
uniform float scale; // 1 / (outerRadius - innerRadius)
uniform float scaleDepth; // The scale depth (i.e. the altitude at which the atmosphere's average density is found)
const int nSamples = 2;
const float fSamples = 1.0;
varying vec3 v3Direction;
varying vec3 c0;
varying vec3 c1;
`,
vertexFunctions: `
float dscale(float fCos) {
float x = 1.0 - fCos;
return scaleDepth * exp(-0.00287 + x * (0.459 + x * (3.83 + x * (-6.80 + x * 5.25))));
}
float calculateNearScatter(vec3 v3CameraPosition, vec3 v3Ray, float fCameraHeight, float fOuterRadius) {
float B = 2.0 * dot(v3CameraPosition, v3Ray);
float C = pow(fCameraHeight, 2.0) - pow(fOuterRadius, 2.0);
float fDet = max(0.0, B * B - 4.0 * C);
return 0.5 * (-B - sqrt(fDet));
}
`,
vertexAtmosphere: `
void main(void) {
// Initialize variables
float cameraHeight = length(planetPosition - cameraPosition);
float KmESun = Km * ESun;
float KrESun = Kr * ESun;
float Kr4PI = Kr * 4.0 * M_PI;
float Km4PI = Km * 4.0 * M_PI;
float scaleOverScaleDepth = scale / scaleDepth;
// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)
vec3 v3Ray = position - cameraPosition;
float fFar = length(v3Ray);
v3Ray /= fFar;
vec3 v3Start;
float fStartAngle;
float fStartDepth;
float fStartOffset;
if (cameraHeight > outerRadius) {
// Sky from space
// Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere)
float fNear = calculateNearScatter(cameraPosition, v3Ray, cameraHeight, outerRadius);
// Calculate the ray's starting position, then calculate its scattering offset
v3Start = cameraPosition + v3Ray * fNear;
fFar -= fNear;
fStartAngle = dot(v3Ray, v3Start) / outerRadius;
fStartDepth = exp(-1.0 / scaleDepth);
fStartOffset = fStartDepth * dscale(fStartAngle);
} else {
// Sky from within the atmosphere
v3Start = cameraPosition;
fStartDepth = exp(scaleOverScaleDepth * (innerRadius - cameraHeight));
fStartAngle = dot(v3Ray, v3Start) / length(v3Start);
fStartOffset = fStartDepth * dscale(fStartAngle);
}
// Initialize the scattering loop variables
float fSampleLength = fFar / fSamples;
float scaledLength = fSampleLength * scale;
vec3 v3SampleRay = v3Ray * fSampleLength;
vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;
// Now loop through the sample rays
vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
for(int i=0; i<nSamples; i++)
{
float fHeight = length(v3SamplePoint);
float fDepth = exp(scaleOverScaleDepth * (innerRadius - fHeight));
float fLightAngle = dot(lightDirection, v3SamplePoint) / fHeight;
float fCameraAngle = dot(v3Ray, v3SamplePoint) / fHeight;
float fScatter = (fStartOffset + fDepth * (dscale(fLightAngle) - dscale(fCameraAngle)));
vec3 v3Attenuate = exp(-fScatter * (invWavelength * Kr4PI + Km4PI));
v3FrontColor += v3Attenuate * (fDepth * scaledLength);
v3SamplePoint += v3SampleRay;
}
// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1);
c0 = v3FrontColor * (invWavelength * KrESun);
c1 = v3FrontColor * KmESun;
v3Direction = cameraPosition - position;
}
`,
vertexGround: `
void main(void) {
// Initialize variables
float cameraHeight = length(planetPosition - cameraPosition);
float KmESun = Km * ESun;
float KrESun = Kr * ESun;
float Kr4PI = Kr * 4.0 * M_PI;
float Km4PI = Km * 4.0 * M_PI;
float scaleOverScaleDepth = scale / scaleDepth;
// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)
vec3 v3Ray = position - cameraPosition;
float fFar = length(v3Ray);
v3Ray /= fFar;
// Calculate the closest intersection of the ray with the outer atmosphere (which is the near point of the ray passing through the atmosphere)
float fNear = calculateNearScatter(cameraPosition, v3Ray, cameraHeight, outerRadius);
// Calculate the ray's starting position, then calculate its scattering offset
vec3 v3Start = cameraPosition + v3Ray * fNear;
fFar -= fNear;
float fDepth = exp((innerRadius - outerRadius) / scaleDepth);
float fCameraAngle = dot(-v3Ray, position) / length(position);
float fLightAngle = dot(lightDirection, position) / length(position);
float fCameraScale = dscale(fCameraAngle);
float fLightScale = dscale(fLightAngle);
float fCameraOffset = fDepth*fCameraScale;
float fTemp = (fLightScale + fCameraScale);
// Initialize the scattering loop variables
float fSampleLength = fFar / fSamples;
float fScaledLength = fSampleLength * scale;
vec3 v3SampleRay = v3Ray * fSampleLength;
vec3 v3SamplePoint = v3Start + v3SampleRay * 0.5;
// Now loop through the sample rays
vec3 v3FrontColor = vec3(0.0, 0.0, 0.0);
vec3 v3Attenuate;
for(int i=0; i<nSamples; i++)
{
float fHeight = length(v3SamplePoint);
float fDepth = exp(scaleOverScaleDepth * (innerRadius - fHeight));
float fScatter = fDepth*fTemp - fCameraOffset;
v3Attenuate = exp(-fScatter * (invWavelength * Kr4PI + Km4PI));
v3FrontColor += v3Attenuate * (fDepth * fScaledLength);
v3SamplePoint += v3SampleRay;
}
// Calculate the attenuation factor for the ground
c0 = v3Attenuate;
c1 = v3FrontColor * (invWavelength * KrESun + KmESun);
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position,1);
}
`,
fragmentAtmosphere: `
uniform vec3 lightDirection;
uniform float g;
varying vec3 v3Direction;
varying vec3 c0;
varying vec3 c1;
// Calculates the Mie phase function
float getMiePhase(float fCos, float fCos2, float g, float g2){
return 1.5 * ((1.0 - g2) / (2.0 + g2)) * (1.0 + fCos2) / pow(1.0 + g2 - 2.0 * g * fCos, 1.5);
}
// Calculates the Rayleigh phase function
float getRayleighPhase(float fCos2) {
// return 0.75 + 0.75 * fCos2;
return 0.75 * (2.0 + 0.5 * fCos2);
}
void main (void) {
float fCos = dot(lightDirection, v3Direction) / length(v3Direction);
float fCos2 = fCos * fCos;
vec3 color = getRayleighPhase(fCos2) * c0 +
getMiePhase(fCos, fCos2, g, pow(g, 2.0)) * c1;
gl_FragColor = vec4(color, 1.0);
gl_FragColor.a = gl_FragColor.b;
}
`,
fragmentGround: `
uniform vec3 color;
varying vec3 c0;
varying vec3 c1;
void main (void) {
gl_FragColor = vec4(c1, 1.0) + vec4(color * c0, 1.0);
}
`
}
module.exports = ATMOSPHERE

281
src/cubeplanet.js Normal file
View File

@ -0,0 +1,281 @@
/* global THREE */
const CubePlanetRes = 15
const blankGeom = new THREE.BufferGeometry()
class PlanetGenerator {
constructor (radius) {
this.radius = radius
}
getHeight (v) {
return 0
}
getBiome (v) {
return 0
}
}
class CubePlanetIndexBuffer {
constructor (fanTop = false, fanRight = false, fanLeft = false, fanBottom = false) {
const indices = []
for (let y = 0; y < CubePlanetRes - 1; y++) {
let slantLeft = (y % 2) === 0
for (let x = 0; x < CubePlanetRes - 1; x++) {
const topLeft = (y * CubePlanetRes) + x
const topRight = topLeft + 1
const bottomLeft = ((y + 1) * CubePlanetRes) + x
const bottomRight = bottomLeft + 1
let tri1 = slantLeft ? [topLeft, bottomLeft, bottomRight] : [topLeft, bottomLeft, topRight]
let tri2 = slantLeft ? [topLeft, bottomRight, topRight] : [bottomLeft, bottomRight, topRight]
if (fanTop && y === 0) {
if (x % 2 === 0) {
tri2 = [topLeft, bottomRight, topRight + 1]
} else {
tri1 = null
}
}
if (fanRight && x === CubePlanetRes - 2) {
if (y % 2 === 0) {
tri2 = [topRight, bottomLeft, bottomRight + CubePlanetRes]
} else {
tri2 = null
}
}
if (fanBottom && y === CubePlanetRes - 2) {
if (x % 2 === 0) {
tri2 = [bottomLeft, bottomRight + 1, topRight]
} else {
tri1 = null
}
}
if (fanLeft && x === 0) {
if (y % 2 === 0) {
tri1 = [topLeft, bottomLeft + CubePlanetRes, bottomRight]
} else {
tri1 = null
}
}
// faster than concat :p
if (tri1) indices.push(tri1[0], tri1[1], tri1[2])
if (tri2) indices.push(tri2[0], tri2[1], tri2[2])
slantLeft = !slantLeft
}
}
this.length = indices.length
this.indices = new THREE.Uint16BufferAttribute(indices, 1)
}
}
const CubePlanetIndexBuffers = {
base: new CubePlanetIndexBuffer(),
fixT: new CubePlanetIndexBuffer(true, false, false, false),
fixTR: new CubePlanetIndexBuffer(true, true, false, false),
fixTL: new CubePlanetIndexBuffer(true, false, true, false),
fixB: new CubePlanetIndexBuffer(false, false, false, true),
fixBR: new CubePlanetIndexBuffer(false, true, false, true),
fixBL: new CubePlanetIndexBuffer(false, false, true, true),
fixR: new CubePlanetIndexBuffer(false, true, false, false),
fixL: new CubePlanetIndexBuffer(false, false, true, false)
}
class CubePlanetBufferGeometry extends THREE.BufferGeometry {
constructor (fnode) {
super()
const vertices = []
const normals = []
const uvs = []
const radius = fnode.root.generator.radius
const divisionLevel = Math.pow(2, fnode.level)
for (let i = 0, vertexPointer = 0; i < CubePlanetRes; i++) {
for (let j = 0; j < CubePlanetRes; j++, vertexPointer++) {
// Vertex index (0 - 1)
const iindex = i / (CubePlanetRes - 1)
const jindex = j / (CubePlanetRes - 1)
// From the left and forward vectors, we can calculate an oriented vertex
const iv = fnode.left.clone().multiplyScalar(iindex).multiplyScalar(radius).divideScalar(divisionLevel)
const jv = fnode.forward.clone().multiplyScalar(jindex).multiplyScalar(radius).divideScalar(divisionLevel)
// Add the scaled left and forward to the centered origin
const vertex = fnode.relPos.clone().add(iv.add(jv))
// Normalize and multiply by radius to create a spherical mesh
const normal = vertex.normalize()
const pointHeight = fnode.root.generator.getHeight(normal)
const pos = normal.clone().multiplyScalar(pointHeight * 10 + radius)
// const pointBiome = fnode.root.generator.getBiome(pointHeight, normal)
vertices[vertexPointer * 3] = pos.x
vertices[vertexPointer * 3 + 1] = pos.y
vertices[vertexPointer * 3 + 2] = pos.z
normals[vertexPointer * 3] = normal.x
normals[vertexPointer * 3 + 1] = normal.y
normals[vertexPointer * 3 + 2] = normal.z
uvs[vertexPointer * 2] = i * (1 / CubePlanetRes)
uvs[vertexPointer * 2 + 1] = j * (1 / CubePlanetRes)
if (i === Math.floor(CubePlanetRes / 2) && j === Math.floor(CubePlanetRes / 2)) {
fnode.center = pos
}
}
}
this.setIndex(CubePlanetIndexBuffers.base.indices)
this.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3))
this.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3))
this.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 3))
}
}
class CubePlanetNode extends THREE.Mesh {
constructor (root, index, level, position, normal) {
super()
this.root = root
this.index = index
this.level = level
this.relPos = position
this.normal = normal
this.left = new THREE.Vector3(normal.y, normal.z, normal.x)
this.forward = normal.clone().cross(this.left)
if (level === 0) {
this.relPos.sub(this.left.clone().multiplyScalar(root.generator.radius / 2))
this.relPos.sub(this.forward.clone().multiplyScalar(root.generator.radius / 2))
}
if (root.material) this.material = root.material
this.generated = false
this.generate()
}
generate () {
if (this.generated) return
this.geometry = new CubePlanetBufferGeometry(this)
this.generated = true
}
isLeaf () {
return !this.children.length
}
merge () {
if (this.isLeaf()) return
for (const i in this.children) {
const ch = this.children[i]
ch.merge()
ch.dispose()
}
this.children = []
this.generate()
}
subdivide () {
if (this.level === (this.root.generator.maxLOD || 8)) return
const lv = this.level + 1
const stepLeft = this.left.clone().multiplyScalar(this.root.generator.radius / Math.pow(2, lv))
const stepForward = this.forward.clone().multiplyScalar(this.root.generator.radius / Math.pow(2, lv))
// Top left corner
this.add(new CubePlanetNode(this.root, 0, lv, this.relPos.clone(), this.normal))
// Top right corner
this.add(new CubePlanetNode(this.root, 1, lv, this.relPos.clone().add(stepForward), this.normal))
// Bottom right corner
this.add(new CubePlanetNode(this.root, 2, lv, this.relPos.clone().add(stepLeft.clone().add(stepForward)), this.normal))
// Bottom left corner
this.add(new CubePlanetNode(this.root, 3, lv, this.relPos.clone().add(stepLeft), this.normal))
this.dispose()
}
dispose () {
if (!this.generated) return
this.geometry.dispose()
this.geometry = blankGeom
this.generated = false
}
setMaterial (mat) {
this.material = mat
for (const i in this.children) {
this.children[i].setMaterial(mat)
}
}
update (camera, dt) {
if (!this.center) return
const camToOrigin = camera.position.clone().distanceTo(this.center)
const divisionLevel = Math.pow(2, this.level)
const splitDistance = this.root.generator.radius / divisionLevel
if (camToOrigin < splitDistance * 5 && this.children.length === 0) {
this.subdivide()
return
} else if (camToOrigin > splitDistance * 5.5 && this.children.length > 0) {
this.merge()
return
}
if (this.children.length > 0) {
for (const i in this.children) {
this.children[i].update(camera, dt)
}
}
}
}
class CubePlanet extends THREE.Object3D {
constructor (origin, generator) {
super()
this.position.copy(origin)
this.generator = generator
this.radius = generator.radius
const hs = generator.radius / 2
this.add(new CubePlanetNode(this, 0, 0, new THREE.Vector3(0, 0, -hs), new THREE.Vector3(0, 0, -1)))
this.add(new CubePlanetNode(this, 1, 0, new THREE.Vector3(0, 0, hs), new THREE.Vector3(0, 0, 1)))
this.add(new CubePlanetNode(this, 2, 0, new THREE.Vector3(-hs, 0, 0), new THREE.Vector3(-1, 0, 0)))
this.add(new CubePlanetNode(this, 3, 0, new THREE.Vector3(hs, 0, 0), new THREE.Vector3(1, 0, 0)))
this.add(new CubePlanetNode(this, 4, 0, new THREE.Vector3(0, hs, 0), new THREE.Vector3(0, 1, 0)))
this.add(new CubePlanetNode(this, 5, 0, new THREE.Vector3(0, -hs, 0), new THREE.Vector3(0, -1, 0)))
}
update (camera, dt) {
for (const i in this.children) {
this.children[i].update(camera, dt)
}
}
setMaterial (mat) {
this.material = mat
for (const i in this.children) {
this.children[i].setMaterial(mat)
}
}
}
module.exports = { PlanetGenerator, CubePlanet, CubePlanetNode }

72
src/index.js Normal file
View File

@ -0,0 +1,72 @@
/* global THREE */
THREE.Extras = THREE.Extras || {}
THREE.Extras.Planet = {}
const atmosShader = require('./builtin/atmosphere.glsl.js')
const cubePlanet = require('./cubeplanet.js')
class ScatterShader {
static _compose (iR, oR, vS, fS, p) {
const st = new THREE.ShaderMaterial({
uniforms: {},
vertexShader: vS,
fragmentShader: fS
})
ScatterShader.scatterUniforms(st, iR, oR, p)
return st
}
static newAtmosphere (innerRadius, outerRadius, params) {
const st = ScatterShader._compose(
innerRadius,
outerRadius,
atmosShader.vertexUniforms + atmosShader.vertexFunctions + atmosShader.vertexAtmosphere,
atmosShader.fragmentAtmosphere,
params
)
st.side = THREE.BackSide
st.transparent = true
return st
}
static newAttenuate (innerRadius, outerRadius, params) {
return ScatterShader._compose(
innerRadius,
outerRadius,
atmosShader.vertexUniforms + atmosShader.vertexFunctions + atmosShader.vertexGround,
atmosShader.fragmentGround,
params
)
}
static scatterUniforms (shader, innerRadius, outerRadius, custom = {}) {
const Kr = custom.Kr || 0.0025
const Km = custom.Km || 0.0015
const ESun = custom.ESun || 15.0
const Scale = custom.scale || (1 / (outerRadius - innerRadius))
const ScaleDepth = custom.scaleDepth || 0.25
const G = custom.g || -0.950
const Wavelength = custom.wavelength || [0.650, 0.570, 0.475]
shader.uniforms.invWavelength = {
value: [1 / Math.pow(Wavelength[0], 4), 1 / Math.pow(Wavelength[1], 4), 1 / Math.pow(Wavelength[2], 4)],
type: 'v3'
}
shader.uniforms.outerRadius = { value: outerRadius, type: 'f' }
shader.uniforms.innerRadius = { value: innerRadius, type: 'f' }
shader.uniforms.Kr = { value: Kr, type: 'f' }
shader.uniforms.Km = { value: Km, type: 'f' }
shader.uniforms.ESun = { value: ESun, type: 'f' }
shader.uniforms.scale = { value: Scale, type: 'f' }
shader.uniforms.scaleDepth = { value: ScaleDepth, type: 'f' }
shader.uniforms.g = { value: G, type: 'f' }
}
}
for (const o in cubePlanet) {
THREE.Extras.Planet[o] = cubePlanet[o]
}
THREE.Extras.Planet.ScatterShader = ScatterShader
module.exports = THREE.Extras.Planet

13
webpack.config.js Normal file
View File

@ -0,0 +1,13 @@
const path = require('path')
module.exports = (env) => {
return {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'lib'),
filename: 'qplanets.js'
},
module: {},
devtool: env.mode === 'development' ? 'inline-source-map' : ''
}
}