Răsfoiți Sursa

Initial commit.

simondevyoutube 5 ani în urmă
părinte
comite
a17dc9ed4c
46 a modificat fișierele cu 3716 adăugiri și 0 ștergeri
  1. 47 0
      base.css
  2. 12 0
      index.html
  3. 3 0
      resources/README.txt
  4. BIN
      resources/dirt_01_diffuse-1024.png
  5. BIN
      resources/dirt_01_normal-1024.jpg
  6. BIN
      resources/grass1-albedo-512.jpg
  7. BIN
      resources/grass1-albedo3-1024.png
  8. BIN
      resources/grass1-normal-1024.jpg
  9. BIN
      resources/rock-snow-ice-albedo-1024.png
  10. BIN
      resources/rock-snow-ice-normal-1024.jpg
  11. BIN
      resources/rough-wet-cobble-albedo-1024.png
  12. BIN
      resources/rough-wet-cobble-normal-1024.jpg
  13. BIN
      resources/sandy-rocks1-albedo-1024.png
  14. BIN
      resources/sandy-rocks1-normal-1024.jpg
  15. BIN
      resources/sandyground-albedo-1024.png
  16. BIN
      resources/sandyground-normal-1024.jpg
  17. BIN
      resources/simplex-noise.png
  18. BIN
      resources/snow-packed-albedo-1024.png
  19. BIN
      resources/snow-packed-normal-1024.jpg
  20. BIN
      resources/space-negx.jpg
  21. BIN
      resources/space-negy.jpg
  22. BIN
      resources/space-negz.jpg
  23. BIN
      resources/space-posx.jpg
  24. BIN
      resources/space-posy.jpg
  25. BIN
      resources/space-posz.jpg
  26. BIN
      resources/worn-bumpy-rock-albedo-1024.png
  27. BIN
      resources/worn-bumpy-rock-albedo-512.jpg
  28. BIN
      resources/worn-bumpy-rock-normal-1024.jpg
  29. 39 0
      src/camera-track.js
  30. 438 0
      src/controls.js
  31. 82 0
      src/demo.js
  32. 60 0
      src/game.js
  33. 212 0
      src/graphics.js
  34. 108 0
      src/main.js
  35. 38 0
      src/math.js
  36. 48 0
      src/noise.js
  37. 550 0
      src/perlin-noise.js
  38. 187 0
      src/quadtree.js
  39. 418 0
      src/scattering-shader.js
  40. 115 0
      src/sky.js
  41. 76 0
      src/spline.js
  42. 309 0
      src/terrain-chunk.js
  43. 317 0
      src/terrain-shader.js
  44. 552 0
      src/terrain.js
  45. 84 0
      src/textures.js
  46. 21 0
      src/utils.js

+ 47 - 0
base.css

@@ -0,0 +1,47 @@
+.header {
+  font-size: 3em;
+  color: white;
+  background: #404040;
+  text-align: center;
+  height: 2.5em;
+  text-shadow: 4px 4px 4px black;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+
+#error {
+  font-size: 2em;
+  color: red;
+  height: 50px;
+  text-shadow: 2px 2px 2px black;
+  margin: 2em;
+  display: none;
+}
+
+.container {
+  width: 100% !important;
+  height: 100% !important;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+  flex-direction: column;
+  position: absolute;
+}
+
+.visible {
+  display: block;
+}
+
+#target {
+  width: 100% !important;
+  height: 100% !important;
+  position: absolute;
+}
+
+body {
+  background: #000000;
+  margin: 0;
+  padding: 0;
+  overscroll-behavior: none;
+}

+ 12 - 0
index.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Procedural Planet</title>
+  <link rel="stylesheet" type="text/css" href="base.css">
+</head>
+<body>
+  <div id="target"></div>
+  <script src="./src/main.js" type="module">
+  </script>
+</body>
+</html>

+ 3 - 0
resources/README.txt

@@ -0,0 +1,3 @@
+Most of these textures were taken from freepbr.com or https://opengameart.org/content/36-free-ground-textures-diffuse-normals.
+
+They were all 2kx2k so they've been resaved as 1k.

BIN
resources/dirt_01_diffuse-1024.png


BIN
resources/dirt_01_normal-1024.jpg


BIN
resources/grass1-albedo-512.jpg


BIN
resources/grass1-albedo3-1024.png


BIN
resources/grass1-normal-1024.jpg


BIN
resources/rock-snow-ice-albedo-1024.png


BIN
resources/rock-snow-ice-normal-1024.jpg


BIN
resources/rough-wet-cobble-albedo-1024.png


BIN
resources/rough-wet-cobble-normal-1024.jpg


BIN
resources/sandy-rocks1-albedo-1024.png


BIN
resources/sandy-rocks1-normal-1024.jpg


BIN
resources/sandyground-albedo-1024.png


BIN
resources/sandyground-normal-1024.jpg


BIN
resources/simplex-noise.png


BIN
resources/snow-packed-albedo-1024.png


BIN
resources/snow-packed-normal-1024.jpg


BIN
resources/space-negx.jpg


BIN
resources/space-negy.jpg


BIN
resources/space-negz.jpg


BIN
resources/space-posx.jpg


BIN
resources/space-posy.jpg


BIN
resources/space-posz.jpg


BIN
resources/worn-bumpy-rock-albedo-1024.png


BIN
resources/worn-bumpy-rock-albedo-512.jpg


BIN
resources/worn-bumpy-rock-normal-1024.jpg


+ 39 - 0
src/camera-track.js

@@ -0,0 +1,39 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+import {spline} from './spline.js';
+
+
+export const camera_track = (function() {
+
+  class _CameraTrack {
+    constructor(params) {
+      this._params = params;
+      this._currentTime = 0.0;
+      
+      const lerp = (t, p1, p2) => {
+        const p = new THREE.Vector3().lerpVectors(p1.pos, p2.pos, t);
+        const q = p1.rot.clone().slerp(p2.rot, t);
+
+        return {pos: p, rot: q};
+      };
+      this._spline = new spline.LinearSpline(lerp);
+
+      for (let p of params.points) {
+        this._spline.AddPoint(p.time, p.data);
+      }
+    }
+
+    Update(timeInSeconds) {
+      this._currentTime += timeInSeconds;
+
+      const r = this._spline.Get(this._currentTime);
+
+      this._params.camera.position.copy(r.pos);
+      this._params.camera.quaternion.copy(r.rot);
+    }
+  };
+
+  return {
+    CameraTrack: _CameraTrack,
+  };
+})();

+ 438 - 0
src/controls.js

@@ -0,0 +1,438 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+import {PointerLockControls} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/PointerLockControls.js';
+import {OrbitControls} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
+
+
+export const controls = (function() {
+
+  class _OrbitControls {
+    constructor(params) {
+      this._params = params;
+      this._Init(params);
+    }
+
+    _Init(params) {
+      this._controls = new OrbitControls(params.camera, params.domElement);
+      this._controls.target.set(0, 0, 0);
+      this._controls.update();
+    }
+
+    Update() {
+    }
+  }
+
+  // FPSControls was adapted heavily from a threejs example. Movement control
+  // and collision detection was completely rewritten, but credit to original
+  // class for the setup code.
+  class _FPSControls {
+    constructor(params) {
+      this._cells = params.cells;
+      this._Init(params);
+    }
+
+    _Init(params) {
+      this._params = params;
+      this._radius = 2;
+      this._enabled = false;
+      this._move = {
+        forward: false,
+        backward: false,
+        left: false,
+        right: false,
+        up: false,
+        down: false,
+      };
+      this._standing = true;
+      this._velocity = new THREE.Vector3(0, 0, 0);
+      this._decceleration = new THREE.Vector3(-10, -10, -10);
+      this._acceleration = new THREE.Vector3(50000, 50000, 50000);
+
+      this._SetupPointerLock();
+
+      this._controls = new PointerLockControls(
+          params.camera, document.body);
+      params.scene.add(this._controls.getObject());
+
+      document.addEventListener('keydown', (e) => this._onKeyDown(e), false);
+      document.addEventListener('keyup', (e) => this._onKeyUp(e), false);
+
+      this._InitGUI();
+    }
+
+    _InitGUI() {
+      this._params.guiParams.camera = {
+        acceleration_x: 50000,
+      };
+
+      const rollup = this._params.gui.addFolder('Camera.FPS');
+      rollup.add(this._params.guiParams.camera, "acceleration_x", 50.0, 50000.0).onChange(
+        () => {
+          this._acceleration.set(
+            this._params.guiParams.camera.acceleration_x,
+            this._params.guiParams.camera.acceleration_x,
+            this._params.guiParams.camera.acceleration_x);
+        });
+    }
+
+    _onKeyDown(event) {
+      switch (event.keyCode) {
+        case 38: // up
+        case 87: // w
+          this._move.forward = true;
+          break;
+        case 37: // left
+        case 65: // a
+          this._move.left = true;
+          break;
+        case 40: // down
+        case 83: // s
+          this._move.backward = true;
+          break;
+        case 39: // right
+        case 68: // d
+          this._move.right = true;
+          break;
+        case 33: // PG_UP
+          this._move.up = true;
+          break;
+        case 34: // PG_DOWN
+          this._move.down = true;
+          break;
+      }
+    }
+
+    _onKeyUp(event) {
+      switch(event.keyCode) {
+        case 38: // up
+        case 87: // w
+          this._move.forward = false;
+          break;
+        case 37: // left
+        case 65: // a
+          this._move.left = false;
+          break;
+        case 40: // down
+        case 83: // s
+          this._move.backward = false;
+          break;
+        case 39: // right
+        case 68: // d
+          this._move.right = false;
+          break;
+        case 33: // PG_UP
+          this._move.up = false;
+          break;
+        case 34: // PG_DOWN
+          this._move.down = false;
+          break;
+      }
+    }
+
+    _SetupPointerLock() {
+      const hasPointerLock = (
+          'pointerLockElement' in document ||
+          'mozPointerLockElement' in document ||
+          'webkitPointerLockElement' in document);
+      if (hasPointerLock) {
+        const lockChange = (event) => {
+          if (document.pointerLockElement === document.body ||
+              document.mozPointerLockElement === document.body ||
+              document.webkitPointerLockElement === document.body ) {
+            this._enabled = true;
+            this._controls.enabled = true;
+          } else {
+            this._controls.enabled = false;
+          }
+        };
+        const lockError = (event) => {
+          console.log(event);
+        };
+
+        document.addEventListener('pointerlockchange', lockChange, false);
+        document.addEventListener('webkitpointerlockchange', lockChange, false);
+        document.addEventListener('mozpointerlockchange', lockChange, false);
+        document.addEventListener('pointerlockerror', lockError, false);
+        document.addEventListener('mozpointerlockerror', lockError, false);
+        document.addEventListener('webkitpointerlockerror', lockError, false);
+
+        document.getElementById('target').addEventListener('click', (event) => {
+          document.body.requestPointerLock = (
+              document.body.requestPointerLock ||
+              document.body.mozRequestPointerLock ||
+              document.body.webkitRequestPointerLock);
+
+          if (/Firefox/i.test(navigator.userAgent)) {
+            const fullScreenChange = (event) => {
+              if (document.fullscreenElement === document.body ||
+                  document.mozFullscreenElement === document.body ||
+                  document.mozFullScreenElement === document.body) {
+                document.removeEventListener('fullscreenchange', fullScreenChange);
+                document.removeEventListener('mozfullscreenchange', fullScreenChange);
+                document.body.requestPointerLock();
+              }
+            };
+            document.addEventListener(
+                'fullscreenchange', fullScreenChange, false);
+            document.addEventListener(
+                'mozfullscreenchange', fullScreenChange, false);
+            document.body.requestFullscreen = (
+                document.body.requestFullscreen ||
+                document.body.mozRequestFullscreen ||
+                document.body.mozRequestFullScreen ||
+                document.body.webkitRequestFullscreen);
+            document.body.requestFullscreen();
+          } else {
+            document.body.requestPointerLock();
+          }
+        }, false);
+      }
+    }
+
+    _FindIntersections(boxes, position) {
+      const sphere = new THREE.Sphere(position, this._radius);
+
+      const intersections = boxes.filter(b => {
+        return sphere.intersectsBox(b);
+      });
+
+      return intersections;
+    }
+
+    Update(timeInSeconds) {
+      if (!this._enabled) {
+        return;
+      }
+
+      const frameDecceleration = new THREE.Vector3(
+          this._velocity.x * this._decceleration.x,
+          this._velocity.y * this._decceleration.y,
+          this._velocity.z * this._decceleration.z
+      );
+      frameDecceleration.multiplyScalar(timeInSeconds);
+
+      this._velocity.add(frameDecceleration);
+
+      if (this._move.forward) {
+        this._velocity.z -= this._acceleration.z * timeInSeconds;
+      }
+      if (this._move.backward) {
+        this._velocity.z += this._acceleration.z * timeInSeconds;
+      }
+      if (this._move.left) {
+        this._velocity.x -= this._acceleration.x * timeInSeconds;
+      }
+      if (this._move.right) {
+        this._velocity.x += this._acceleration.x * timeInSeconds;
+      }
+      if (this._move.up) {
+        this._velocity.y += this._acceleration.y * timeInSeconds;
+      }
+      if (this._move.down) {
+        this._velocity.y -= this._acceleration.y * timeInSeconds;
+      }
+
+      const controlObject = this._controls.getObject();
+
+      const oldPosition = new THREE.Vector3();
+      oldPosition.copy(controlObject.position);
+
+      const forward = new THREE.Vector3(0, 0, 1);
+      forward.applyQuaternion(controlObject.quaternion);
+      forward.normalize();
+
+      const updown = new THREE.Vector3(0, 1, 0);
+
+      const sideways = new THREE.Vector3(1, 0, 0);
+      sideways.applyQuaternion(controlObject.quaternion);
+      sideways.normalize();
+
+      sideways.multiplyScalar(this._velocity.x * timeInSeconds);
+      updown.multiplyScalar(this._velocity.y * timeInSeconds);
+      forward.multiplyScalar(this._velocity.z * timeInSeconds);
+
+      controlObject.position.add(forward);
+      controlObject.position.add(sideways);
+      controlObject.position.add(updown);
+
+      oldPosition.copy(controlObject.position);
+    }
+  };
+
+  class _ShipControls {
+    constructor(params) {
+      this._Init(params);
+    }
+
+    _Init(params) {
+      this._params = params;
+      this._radius = 2;
+      this._enabled = false;
+      this._move = {
+        forward: false,
+        backward: false,
+        left: false,
+        right: false,
+        up: false,
+        down: false,
+        rocket: false,
+      };
+      this._velocity = new THREE.Vector3(0, 0, 0);
+      this._decceleration = new THREE.Vector3(-0.001, -0.0001, -1);
+      this._acceleration = new THREE.Vector3(100, 0.1, 25000);
+
+      document.addEventListener('keydown', (e) => this._onKeyDown(e), false);
+      document.addEventListener('keyup', (e) => this._onKeyUp(e), false);
+
+      this._InitGUI();
+    }
+
+    _InitGUI() {
+      this._params.guiParams.camera = {
+        acceleration_x: 100,
+        acceleration_y: 0.1,
+      };
+
+      const rollup = this._params.gui.addFolder('Camera.Ship');
+      rollup.add(this._params.guiParams.camera, "acceleration_x", 50.0, 25000.0).onChange(
+        () => {
+          this._acceleration.x = this._params.guiParams.camera.acceleration_x;
+        });
+      rollup.add(this._params.guiParams.camera, "acceleration_y", 0.001, 0.1).onChange(
+        () => {
+          this._acceleration.y = this._params.guiParams.camera.acceleration_y;
+        });
+    }
+
+    _onKeyDown(event) {
+      switch (event.keyCode) {
+        case 87: // w
+          this._move.forward = true;
+          break;
+        case 65: // a
+          this._move.left = true;
+          break;
+        case 83: // s
+          this._move.backward = true;
+          break;
+        case 68: // d
+          this._move.right = true;
+          break;
+        case 33: // PG_UP
+          this._acceleration.x *= 1.1;
+          break;
+        case 34: // PG_DOWN
+          this._acceleration.x *= 0.9;
+          break;
+        case 32: // SPACE
+          this._move.rocket = true;
+          break;
+        case 38: // up
+        case 37: // left
+        case 40: // down
+        case 39: // right
+          break;
+      }
+    }
+
+    _onKeyUp(event) {
+      switch(event.keyCode) {
+        case 87: // w
+          this._move.forward = false;
+          break;
+        case 65: // a
+          this._move.left = false;
+          break;
+        case 83: // s
+          this._move.backward = false;
+          break;
+        case 68: // d
+          this._move.right = false;
+          break;
+        case 33: // PG_UP
+          break;
+        case 34: // PG_DOWN
+          break;
+        case 32: // SPACE
+          this._move.rocket = false;
+          break;
+        case 38: // up
+        case 37: // left
+        case 40: // down
+        case 39: // right
+          break;
+      }
+    }
+
+    Update(timeInSeconds) {
+      const frameDecceleration = new THREE.Vector3(
+          this._velocity.x * this._decceleration.x,
+          this._velocity.y * this._decceleration.y,
+          this._velocity.z * this._decceleration.z
+      );
+      frameDecceleration.multiplyScalar(timeInSeconds);
+
+      this._velocity.add(frameDecceleration);
+
+      const controlObject = this._params.camera;
+      const _Q = new THREE.Quaternion();
+      const _A = new THREE.Vector3();
+      const _R = controlObject.quaternion.clone();
+
+      if (this._move.forward) {
+        _A.set(1, 0, 0);
+        _Q.setFromAxisAngle(_A, -Math.PI * timeInSeconds * this._acceleration.y);
+        _R.multiply(_Q);
+      }
+      if (this._move.backward) {
+        _A.set(1, 0, 0);
+        _Q.setFromAxisAngle(_A, Math.PI * timeInSeconds * this._acceleration.y);
+        _R.multiply(_Q);
+      }
+      if (this._move.left) {
+        _A.set(0, 0, 1);
+        _Q.setFromAxisAngle(_A, Math.PI * timeInSeconds * this._acceleration.y);
+        _R.multiply(_Q);
+      }
+      if (this._move.right) {
+        _A.set(0, 0, 1);
+        _Q.setFromAxisAngle(_A, -Math.PI * timeInSeconds * this._acceleration.y);
+        _R.multiply(_Q);
+      }
+      if (this._move.rocket) {
+        this._velocity.z -= this._acceleration.x * timeInSeconds;
+      }
+
+      controlObject.quaternion.copy(_R);
+
+      const oldPosition = new THREE.Vector3();
+      oldPosition.copy(controlObject.position);
+
+      const forward = new THREE.Vector3(0, 0, 1);
+      forward.applyQuaternion(controlObject.quaternion);
+      //forward.y = 0;
+      forward.normalize();
+
+      const updown = new THREE.Vector3(0, 1, 0);
+
+      const sideways = new THREE.Vector3(1, 0, 0);
+      sideways.applyQuaternion(controlObject.quaternion);
+      sideways.normalize();
+
+      sideways.multiplyScalar(this._velocity.x * timeInSeconds);
+      updown.multiplyScalar(this._velocity.y * timeInSeconds);
+      forward.multiplyScalar(this._velocity.z * timeInSeconds);
+
+      controlObject.position.add(forward);
+      controlObject.position.add(sideways);
+      controlObject.position.add(updown);
+
+      oldPosition.copy(controlObject.position);
+    }
+  };
+
+  return {
+    ShipControls: _ShipControls,
+    FPSControls: _FPSControls,
+    OrbitControls: _OrbitControls,
+  };
+})();

+ 82 - 0
src/demo.js

@@ -0,0 +1,82 @@
+import {game} from './game.js';
+import {graphics} from './graphics.js';
+import {math} from './math.js';
+import {noise} from './noise.js';
+
+
+window.onload = function() {
+  function _Perlin() {
+    const canvas = document.getElementById("canvas"); 
+    const context = canvas.getContext("2d");
+  
+    const imgData = context.createImageData(canvas.width, canvas.height);
+  
+    const params = {
+      scale: 32,
+      noiseType: 'simplex',
+      persistence: 0.5,
+      octaves: 1,
+      lacunarity: 1,
+      exponentiation: 1,
+      height: 255
+    };
+    const noiseGen = new noise.Noise(params);
+
+    for (let x = 0; x < canvas.width; x++) {
+      for (let y = 0; y < canvas.height; y++) {
+        const pixelIndex = (y * canvas.width + x) * 4;
+
+        const n = noiseGen.Get(x, y);
+
+        imgData.data[pixelIndex] = n;
+        imgData.data[pixelIndex+1] = n;
+        imgData.data[pixelIndex+2] = n;
+        imgData.data[pixelIndex+3] = 255;
+      }
+    }
+  
+    context.putImageData(imgData, 0, 0);
+}
+
+
+function _Randomness() {
+  const canvas = document.getElementById("canvas"); 
+  const context = canvas.getContext("2d");
+
+  const imgData = context.createImageData(canvas.width, canvas.height);
+
+  const params = {
+    scale: 32,
+    noiseType: 'simplex',
+    persistence: 0.5,
+    octaves: 1,
+    lacunarity: 2,
+    exponentiation: 1,
+    height: 1
+  };
+  const noiseGen = new noise.Noise(params);
+  let foo = '';
+
+  for (let x = 0; x < canvas.width; x++) {
+    for (let y = 0; y < canvas.height; y++) {
+      const pixelIndex = (y * canvas.width + x) * 4;
+
+      const n = noiseGen.Get(x, y);
+      if (x == 0) {
+        foo += n + '\n';
+      }
+
+      imgData.data[pixelIndex] = n;
+      imgData.data[pixelIndex+1] = n;
+      imgData.data[pixelIndex+2] = n;
+      imgData.data[pixelIndex+3] = 255;
+    }
+  }
+  console.log(foo);
+
+  context.putImageData(imgData, 0, 0);
+}
+
+_Randomness();
+  
+};

+ 60 - 0
src/game.js

@@ -0,0 +1,60 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+import {WEBGL} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/WebGL.js';
+import {graphics} from './graphics.js';
+
+
+export const game = (function() {
+  return {
+    Game: class {
+      constructor() {
+        this._Initialize();
+      }
+
+      _Initialize() {
+        this._graphics = new graphics.Graphics(this);
+        if (!this._graphics.Initialize()) {
+          this._DisplayError('WebGL2 is not available.');
+          return;
+        }
+
+        this._previousRAF = null;
+        this._minFrameTime = 1.0 / 10.0;
+        this._entities = {};
+
+        this._OnInitialize();
+        this._RAF();
+      }
+
+      _DisplayError(errorText) {
+        const error = document.getElementById('error');
+        error.innerText = errorText;
+      }
+
+      _RAF() {
+        requestAnimationFrame((t) => {
+          if (this._previousRAF === null) {
+            this._previousRAF = t;
+          }
+          this._Render(t - this._previousRAF);
+          this._previousRAF = t;
+        });
+      }
+
+      _StepEntities(timeInSeconds) {
+        for (let k in this._entities) {
+          this._entities[k].Update(timeInSeconds);
+        }
+      }
+
+      _Render(timeInMS) {
+        const timeInSeconds = Math.min(timeInMS * 0.001, this._minFrameTime);
+
+        this._OnStep(timeInSeconds);
+        this._StepEntities(timeInSeconds);
+        this._graphics.Render(timeInSeconds);
+
+        this._RAF();
+      }
+    }
+  };
+})();

+ 212 - 0
src/graphics.js

@@ -0,0 +1,212 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+import Stats from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/stats.module.js';
+import {WEBGL} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/WebGL.js';
+
+import {RenderPass} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/RenderPass.js';
+import {ShaderPass} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/ShaderPass.js';
+import {CopyShader} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/shaders/CopyShader.js';
+import {FXAAShader} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/shaders/FXAAShader.js';
+import {EffectComposer} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/EffectComposer.js';
+
+import {scattering_shader} from './scattering-shader.js';
+
+
+export const graphics = (function() {
+
+  function _GetImageData(image) {
+    const canvas = document.createElement('canvas');
+    canvas.width = image.width;
+    canvas.height = image.height;
+
+    const context = canvas.getContext( '2d' );
+    context.drawImage(image, 0, 0);
+
+    return context.getImageData(0, 0, image.width, image.height);
+  }
+
+  function _GetPixel(imagedata, x, y) {
+    const position = (x + imagedata.width * y) * 4;
+    const data = imagedata.data;
+    return {
+        r: data[position],
+        g: data[position + 1],
+        b: data[position + 2],
+        a: data[position + 3]
+    };
+  }
+
+  class _Graphics {
+    constructor(game) {
+    }
+
+    Initialize() {
+      if (!WEBGL.isWebGL2Available()) {
+        return false;
+      }
+
+      const canvas = document.createElement('canvas');
+      const context = canvas.getContext('webgl2', {alpha: false});
+
+      this._threejs = new THREE.WebGLRenderer({
+        canvas: canvas,
+        context: context,
+      });
+      this._threejs.setPixelRatio(window.devicePixelRatio);
+      this._threejs.setSize(window.innerWidth, window.innerHeight);
+      this._threejs.autoClear = false;
+
+      const target = document.getElementById('target');
+      target.appendChild(this._threejs.domElement);
+
+      this._stats = new Stats();
+      // target.appendChild(this._stats.dom);
+
+      window.addEventListener('resize', () => {
+        this._OnWindowResize();
+      }, false);
+
+      const fov = 60;
+      const aspect = 1920 / 1080;
+      const near = 0.1;
+      const far = 100000.0;
+      this._camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
+      this._camera.position.set(75, 20, 0);
+
+      this._scene = new THREE.Scene();
+      this._scene.background = new THREE.Color(0xaaaaaa);
+
+      const renderPass = new RenderPass(this._scene, this._camera);
+      const fxaaPass = new ShaderPass(FXAAShader);
+      // const depthPass = new ShaderPass(scattering_shader.Shader);
+
+      // this._depthPass = depthPass;
+
+      this._composer = new EffectComposer(this._threejs);
+      this._composer.addPass(renderPass);
+      this._composer.addPass(fxaaPass);
+      //this._composer.addPass(depthPass);
+
+      this._target = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight);
+      this._target.texture.format = THREE.RGBFormat;
+      this._target.texture.minFilter = THREE.NearestFilter;
+      this._target.texture.magFilter = THREE.NearestFilter;
+      this._target.texture.generateMipmaps = false;
+      this._target.stencilBuffer = false;
+      this._target.depthBuffer = true;
+      this._target.depthTexture = new THREE.DepthTexture();
+      this._target.depthTexture.format = THREE.DepthFormat;
+      this._target.depthTexture.type = THREE.FloatType;
+
+      this._threejs.setRenderTarget(this._target);
+
+      this._postCamera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
+      this._depthPass = new THREE.ShaderMaterial( {
+        vertexShader: scattering_shader.VS,
+        fragmentShader: scattering_shader.PS,
+        uniforms: {
+          cameraNear: { value: this.Camera.near },
+          cameraFar: { value: this.Camera.far },
+          cameraPosition: { value: this.Camera.position },
+          cameraForward: { value: null },
+          tDiffuse: { value: null },
+          tDepth: { value: null },
+          inverseProjection: { value: null },
+          inverseView: { value: null },
+          planetPosition: { value: null },
+          planetRadius: { value: null },
+          atmosphereRadius: { value: null },
+        }
+      } );
+      var postPlane = new THREE.PlaneBufferGeometry( 2, 2 );
+      var postQuad = new THREE.Mesh( postPlane, this._depthPass );
+      this._postScene = new THREE.Scene();
+      this._postScene.add( postQuad );
+
+      this._CreateLights();
+
+      return true;
+    }
+
+
+    _CreateLights() {
+      let light = new THREE.DirectionalLight(0xFFFFFF, 1);
+      light.position.set(100, 100, -100);
+      light.target.position.set(0, 0, 0);
+      light.castShadow = false;
+      this._scene.add(light);
+
+      light = new THREE.DirectionalLight(0x404040, 1);
+      light.position.set(100, 100, -100);
+      light.target.position.set(0, 0, 0);
+      light.castShadow = false;
+      this._scene.add(light);
+
+      light = new THREE.DirectionalLight(0x404040, 1);
+      light.position.set(100, 100, -100);
+      light.target.position.set(0, 0, 0);
+      light.castShadow = false;
+      this._scene.add(light);
+
+      light = new THREE.DirectionalLight(0x202040, 1);
+      light.position.set(100, -100, 100);
+      light.target.position.set(0, 0, 0);
+      light.castShadow = false;
+      this._scene.add(light);
+
+      light = new THREE.AmbientLight(0xFFFFFF, 1.0);
+      this._scene.add(light);
+    }
+
+    _OnWindowResize() {
+      this._camera.aspect = window.innerWidth / window.innerHeight;
+      this._camera.updateProjectionMatrix();
+      this._threejs.setSize(window.innerWidth, window.innerHeight);
+      this._composer.setSize(window.innerWidth, window.innerHeight);
+      this._target.setSize(window.innerWidth, window.innerHeight);
+    }
+
+    get Scene() {
+      return this._scene;
+    }
+
+    get Camera() {
+      return this._camera;
+    }
+
+    Render(timeInSeconds) {
+      this._threejs.setRenderTarget(this._target);
+
+      this._threejs.clear();
+      this._threejs.render(this._scene, this._camera);
+      //this._composer.render();
+
+      this._threejs.setRenderTarget( null );
+
+      const forward = new THREE.Vector3();
+      this._camera.getWorldDirection(forward);
+
+      this._depthPass.uniforms.inverseProjection.value = this._camera.projectionMatrixInverse;
+      this._depthPass.uniforms.inverseView.value = this._camera.matrixWorld;
+      this._depthPass.uniforms.tDiffuse.value = this._target.texture;
+      this._depthPass.uniforms.tDepth.value = this._target.depthTexture;
+      this._depthPass.uniforms.cameraNear.value = this._camera.near;
+      this._depthPass.uniforms.cameraFar.value = this._camera.far;
+      this._depthPass.uniforms.cameraPosition.value = this._camera.position;
+      this._depthPass.uniforms.cameraForward.value = forward;
+      this._depthPass.uniforms.planetPosition.value = new THREE.Vector3(0, 0, 0);
+      this._depthPass.uniforms.planetRadius.value = 4000.0;
+      this._depthPass.uniforms.atmosphereRadius.value = 6000.0;
+      this._depthPass.uniformsNeedUpdate = true;
+
+      this._threejs.render( this._postScene, this._postCamera );
+
+      this._stats.update();
+    }
+  }
+
+  return {
+    Graphics: _Graphics,
+    GetPixel: _GetPixel,
+    GetImageData: _GetImageData,
+  };
+})();

+ 108 - 0
src/main.js

@@ -0,0 +1,108 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+import {GUI} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/dat.gui.module.js';
+import {controls} from './controls.js';
+import {game} from './game.js';
+import {terrain} from './terrain.js';
+
+
+let _APP = null;
+
+
+
+class ProceduralTerrain_Demo extends game.Game {
+  constructor() {
+    super();
+  }
+
+  _OnInitialize() {
+    this._CreateGUI();
+
+    this._userCamera = new THREE.Object3D();
+    this._userCamera.position.set(4100, 0, 0);
+    this._graphics.Camera.position.set(3853, -609, -1509);
+    this._graphics.Camera.quaternion.set(0.403, 0.59, -0.549, 0.432);
+
+    this._graphics.Camera.position.set(1412, -1674, -3848);
+    this._graphics.Camera.quaternion.set(0.1004, 0.7757, -0.6097, 0.1278);
+
+    this._entities['_terrain'] = new terrain.TerrainChunkManager({
+      camera: this._graphics.Camera,
+      scene: this._graphics.Scene,
+      gui: this._gui,
+      guiParams: this._guiParams,
+      game: this
+    });
+
+    // this._entities['_controls'] = new controls.OrbitControls({
+    //   camera: this._graphics.Camera,
+    //   scene: this._graphics.Scene,
+    //   domElement: this._graphics._threejs.domElement,
+    //   gui: this._gui,
+    //   guiParams: this._guiParams,
+    // });
+
+    // this._entities['_controls'] = new controls.ShipControls({
+    //   camera: this._graphics.Camera,
+    //   scene: this._graphics.Scene,
+    //   domElement: this._graphics._threejs.domElement,
+    //   gui: this._gui,
+    //   guiParams: this._guiParams,
+    // });
+
+    this._entities['_controls'] = new controls.FPSControls({
+        camera: this._graphics.Camera,
+        scene: this._graphics.Scene,
+        domElement: this._graphics._threejs.domElement,
+        gui: this._gui,
+        guiParams: this._guiParams,
+    });
+
+    // this._focusMesh = new THREE.Mesh(
+    //   new THREE.SphereGeometry(25, 32, 32),
+    //   new THREE.MeshBasicMaterial({
+    //       color: 0xFFFFFF
+    //   }));
+    // this._focusMesh.castShadow = true;
+    // this._focusMesh.receiveShadow = true;
+    //this._graphics.Scene.add(this._focusMesh);
+
+    this._totalTime = 0;
+
+    this._LoadBackground();
+  }
+
+  _CreateGUI() {
+    this._guiParams = {
+      general: {
+      },
+    };
+    this._gui = new GUI();
+
+    const generalRollup = this._gui.addFolder('General');
+    this._gui.close();
+  }
+
+  _LoadBackground() {
+    this._graphics.Scene.background = new THREE.Color(0x000000);
+    const loader = new THREE.CubeTextureLoader();
+    const texture = loader.load([
+        './resources/space-posx.jpg',
+        './resources/space-negx.jpg',
+        './resources/space-posy.jpg',
+        './resources/space-negy.jpg',
+        './resources/space-posz.jpg',
+        './resources/space-negz.jpg',
+    ]);
+    this._graphics._scene.background = texture;
+  }
+
+  _OnStep(timeInSeconds) {
+  }
+}
+
+
+function _Main() {
+  _APP = new ProceduralTerrain_Demo();
+}
+
+_Main();

+ 38 - 0
src/math.js

@@ -0,0 +1,38 @@
+export const math = (function() {
+  return {
+    rand_range: function(a, b) {
+      return Math.random() * (b - a) + a;
+    },
+
+    rand_normalish: function() {
+      const r = Math.random() + Math.random() + Math.random() + Math.random();
+      return (r / 4.0) * 2.0 - 1;
+    },
+
+    rand_int: function(a, b) {
+      return Math.round(Math.random() * (b - a) + a);
+    },
+
+    lerp: function(x, a, b) {
+      return x * (b - a) + a;
+    },
+
+    smoothstep: function(x, a, b) {
+      x = x * x * (3.0 - 2.0 * x);
+      return x * (b - a) + a;
+    },
+
+    smootherstep: function(x, a, b) {
+      x = x * x * x * (x * (x * 6 - 15) + 10);
+      return x * (b - a) + a;
+    },
+
+    clamp: function(x, a, b) {
+      return Math.min(Math.max(x, a), b);
+    },
+
+    sat: function(x) {
+      return Math.min(Math.max(x, 0.0), 1.0);
+    },
+  };
+})();

+ 48 - 0
src/noise.js

@@ -0,0 +1,48 @@
+import 'https://cdn.jsdelivr.net/npm/[email protected]/simplex-noise.js';
+//import perlin from 'https://cdn.jsdelivr.net/gh/mikechambers/es6-perlin-module/perlin.js';
+import perlin from './perlin-noise.js';
+
+import {math} from './math.js';
+
+export const noise = (function() {
+
+  class _NoiseGenerator {
+    constructor(params) {
+      this._params = params;
+      this._Init();
+    }
+
+    _Init() {
+      this._noise = new SimplexNoise(this._params.seed);
+    }
+
+    Get(x, y, z) {
+      const G = 2.0 ** (-this._params.persistence);
+      const xs = x / this._params.scale;
+      const ys = y / this._params.scale;
+      const zs = z / this._params.scale;
+      const noiseFunc = this._noise;
+
+      let amplitude = 1.0;
+      let frequency = 1.0;
+      let normalization = 0;
+      let total = 0;
+      for (let o = 0; o < this._params.octaves; o++) {
+        const noiseValue = noiseFunc.noise3D(
+          xs * frequency, ys * frequency, zs * frequency) * 0.5 + 0.5;
+
+        total += noiseValue * amplitude;
+        normalization += amplitude;
+        amplitude *= G;
+        frequency *= this._params.lacunarity;
+      }
+      total /= normalization;
+      return Math.pow(
+          total, this._params.exponentiation) * this._params.height;
+    }
+  }
+
+  return {
+    Noise: _NoiseGenerator
+  }
+})();

+ 550 - 0
src/perlin-noise.js

@@ -0,0 +1,550 @@
+// noise1234
+//
+// Author: Stefan Gustavson, 2003-2005
+// Contact: [email protected]
+//
+// This code was GPL licensed until February 2011.
+// As the original author of this code, I hereby
+// release it into the public domain.
+// Please feel free to use it for whatever you want.
+// Credit is appreciated where appropriate, and I also
+// appreciate being told where this code finds any use,
+// but you may do as you like.
+
+//Ported to JavaScript by Mike mikechambers
+//http://www.mikechambers.com
+//
+// Note, all return values are scaled to be between 0 and 1
+//
+//From original C at:
+//https://github.com/stegu/perlin-noise
+//https://github.com/stegu/perlin-noise/blob/master/src/noise1234.c
+
+/*
+ * This implementation is "Improved Noise" as presented by
+ * Ken Perlin at Siggraph 2002. The 3D function is a direct port
+ * of his Java reference code which was once publicly available
+ * on www.noisemachine.com (although I cleaned it up, made it
+ * faster and made the code more readable), but the 1D, 2D and
+ * 4D functions were implemented from scratch by me.
+ *
+ * This is a backport to C of my improved noise class in C++
+ * which was included in the Aqsis renderer project.
+ * It is highly reusable without source code modifications.
+ *
+ */
+
+// This is the new and improved, C(2) continuous interpolant
+function fade(t) {
+	return ( t * t * t * ( t * ( t * 6 - 15 ) + 10 ) );
+}
+
+function lerp(t, a, b) {
+	return ((a) + (t)*((b)-(a)));
+}
+
+
+//---------------------------------------------------------------------
+// Static data
+
+/*
+ * Permutation table. This is just a random jumble of all numbers 0-255,
+ * repeated twice to avoid wrapping the index at 255 for each lookup.
+ * This needs to be exactly the same for all instances on all platforms,
+ * so it's easiest to just keep it as static explicit data.
+ * This also removes the need for any initialisation of this class.
+ *
+ * Note that making this an int[] instead of a char[] might make the
+ * code run faster on platforms with a high penalty for unaligned single
+ * byte addressing. Intel x86 is generally single-byte-friendly, but
+ * some other CPUs are faster with 4-aligned reads.
+ * However, a char[] is smaller, which avoids cache trashing, and that
+ * is probably the most important aspect on most architectures.
+ * This array is accessed a *lot* by the noise functions.
+ * A vector-valued noise over 3D accesses it 96 times, and a
+ * float-valued 4D noise 64 times. We want this to fit in the cache!
+ */
+const perm = [151,160,137,91,90,15,
+  131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
+  190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
+  88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
+  77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
+  102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
+  135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
+  5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
+  223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
+  129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
+  251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
+  49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
+  138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
+  151,160,137,91,90,15,
+  131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
+  190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
+  88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
+  77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
+  102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
+  135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
+  5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
+  223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
+  129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
+  251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
+  49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
+  138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180
+];
+
+//---------------------------------------------------------------------
+
+/*
+ * Helper functions to compute gradients-dot-residualvectors (1D to 4D)
+ * Note that these generate gradients of more than unit length. To make
+ * a close match with the value range of classic Perlin noise, the final
+ * noise values need to be rescaled. To match the RenderMan noise in a
+ * statistical sense, the approximate scaling values (empirically
+ * determined from test renderings) are:
+ * 1D noise needs rescaling with 0.188
+ * 2D noise needs rescaling with 0.507
+ * 3D noise needs rescaling with 0.936
+ * 4D noise needs rescaling with 0.87
+ */
+
+function grad1( hash, x ) {
+    let h = hash & 15;
+    let grad = 1.0 + (h & 7);  // Gradient value 1.0, 2.0, ..., 8.0
+    if (h&8) grad = -grad;         // and a random sign for the gradient
+    return ( grad * x );           // Multiply the gradient with the distance
+}
+
+function grad2(  hash,  x,  y ) {
+    let h = hash & 7;      // Convert low 3 bits of hash code
+    let u = h<4 ? x : y;  // into 8 simple gradient directions,
+    let v = h<4 ? y : x;  // and compute the dot product with (x,y).
+    return ((h&1)? -u : u) + ((h&2)? -2.0*v : 2.0*v);
+}
+
+function grad3(  hash,  x,  y ,  z ) {
+    let h = hash & 15;     // Convert low 4 bits of hash code into 12 simple
+    let u = h<8 ? x : y; // gradient directions, and compute dot product.
+    let v = h<4 ? y : h==12||h==14 ? x : z; // Fix repeats at h = 12 to 15
+    return ((h&1)? -u : u) + ((h&2)? -v : v);
+}
+
+function grad4(  hash,  x,  y,  z,  t ) {
+    let h = hash & 31;      // Convert low 5 bits of hash code into 32 simple
+    let u = h<24 ? x : y; // gradient directions, and compute dot product.
+    let v = h<16 ? y : z;
+    let w = h<8 ? z : t;
+    return ((h&1)? -u : u) + ((h&2)? -v : v) + ((h&4)? -w : w);
+}
+
+//---------------------------------------------------------------------
+/** 1D float Perlin noise, SL "noise()"
+ */
+export function noise1(  x )
+{
+    let ix0, ix1;
+    let fx0, fx1;
+    let s, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    fx0 = x - ix0;       // Fractional part of x
+    fx1 = fx0 - 1.0;
+    ix1 = ( ix0+1 ) & 0xff;
+    ix0 = ix0 & 0xff;    // Wrap to 0..255
+
+    s = fade( fx0 );
+
+    n0 = grad1( perm[ ix0 ], fx0 );
+    n1 = grad1( perm[ ix1 ], fx1 );
+    return scale(0.188 * ( lerp( s, n0, n1 ) ));
+}
+
+//---------------------------------------------------------------------
+/** 1D float Perlin periodic noise, SL "pnoise()"
+ */
+export function pnoise1(  x,  px )
+{
+    let ix0, ix1;
+    let fx0, fx1;
+    let s, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    fx0 = x - ix0;       // Fractional part of x
+    fx1 = fx0 - 1.0;
+    ix1 = (( ix0 + 1 ) % px) & 0xff; // Wrap to 0..px-1 *and* wrap to 0..255
+    ix0 = ( ix0 % px ) & 0xff;      // (because px might be greater than 256)
+
+    s = fade( fx0 );
+
+    n0 = grad1( perm[ ix0 ], fx0 );
+    n1 = grad1( perm[ ix1 ], fx1 );
+    return scale(0.188 * ( lerp( s, n0, n1 ) ));
+}
+
+
+//---------------------------------------------------------------------
+/** 2D float Perlin noise.
+ */
+export function noise2( x, y )
+{
+    let ix0, iy0, ix1, iy1;
+    let fx0, fy0, fx1, fy1;
+    let s, t, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    ix1 = (ix0 + 1) & 0xff;  // Wrap to 0..255
+    iy1 = (iy0 + 1) & 0xff;
+    ix0 = ix0 & 0xff;
+    iy0 = iy0 & 0xff;
+
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nx0 = grad2(perm[ix0 + perm[iy0]], fx0, fy0);
+    nx1 = grad2(perm[ix0 + perm[iy1]], fx0, fy1);
+    n0 = lerp( t, nx0, nx1 );
+
+    nx0 = grad2(perm[ix1 + perm[iy0]], fx1, fy0);
+    nx1 = grad2(perm[ix1 + perm[iy1]], fx1, fy1);
+    n1 = lerp(t, nx0, nx1);
+
+    return scale(0.507 * ( lerp( s, n0, n1 ) ));
+}
+
+//---------------------------------------------------------------------
+/** 2D float Perlin periodic noise.
+ */
+export function pnoise2(  x,  y,  px,  py )
+{
+    let ix0, iy0, ix1, iy1;
+    let fx0, fy0, fx1, fy1;
+    let s, t, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    ix1 = (( ix0 + 1 ) % px) & 0xff;  // Wrap to 0..px-1 and wrap to 0..255
+    iy1 = (( iy0 + 1 ) % py) & 0xff;  // Wrap to 0..py-1 and wrap to 0..255
+    ix0 = ( ix0 % px ) & 0xff;
+    iy0 = ( iy0 % py ) & 0xff;
+
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nx0 = grad2(perm[ix0 + perm[iy0]], fx0, fy0);
+    nx1 = grad2(perm[ix0 + perm[iy1]], fx0, fy1);
+    n0 = lerp( t, nx0, nx1 );
+
+    nx0 = grad2(perm[ix1 + perm[iy0]], fx1, fy0);
+    nx1 = grad2(perm[ix1 + perm[iy1]], fx1, fy1);
+    n1 = lerp(t, nx0, nx1);
+
+    return scale(0.507 * ( lerp( s, n0, n1 ) ));
+}
+
+
+//---------------------------------------------------------------------
+/** 3D float Perlin noise.
+ */
+export function noise3(  x,  y,  z )
+{
+    let ix0, iy0, ix1, iy1, iz0, iz1;
+    let fx0, fy0, fz0, fx1, fy1, fz1;
+    let s, t, r;
+    let nxy0, nxy1, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    iz0 = Math.floor( z ); // Integer part of z
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fz0 = z - iz0;        // Fractional part of z
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    fz1 = fz0 - 1.0;
+    ix1 = ( ix0 + 1 ) & 0xff; // Wrap to 0..255
+    iy1 = ( iy0 + 1 ) & 0xff;
+    iz1 = ( iz0 + 1 ) & 0xff;
+    ix0 = ix0 & 0xff;
+    iy0 = iy0 & 0xff;
+    iz0 = iz0 & 0xff;
+
+    r = fade( fz0 );
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nxy0 = grad3(perm[ix0 + perm[iy0 + perm[iz0]]], fx0, fy0, fz0);
+    nxy1 = grad3(perm[ix0 + perm[iy0 + perm[iz1]]], fx0, fy0, fz1);
+    nx0 = lerp( r, nxy0, nxy1 );
+
+    nxy0 = grad3(perm[ix0 + perm[iy1 + perm[iz0]]], fx0, fy1, fz0);
+    nxy1 = grad3(perm[ix0 + perm[iy1 + perm[iz1]]], fx0, fy1, fz1);
+    nx1 = lerp( r, nxy0, nxy1 );
+
+    n0 = lerp( t, nx0, nx1 );
+
+    nxy0 = grad3(perm[ix1 + perm[iy0 + perm[iz0]]], fx1, fy0, fz0);
+    nxy1 = grad3(perm[ix1 + perm[iy0 + perm[iz1]]], fx1, fy0, fz1);
+    nx0 = lerp( r, nxy0, nxy1 );
+
+    nxy0 = grad3(perm[ix1 + perm[iy1 + perm[iz0]]], fx1, fy1, fz0);
+    nxy1 = grad3(perm[ix1 + perm[iy1 + perm[iz1]]], fx1, fy1, fz1);
+    nx1 = lerp( r, nxy0, nxy1 );
+
+    n1 = lerp( t, nx0, nx1 );
+
+    return scale(0.936 * ( lerp( s, n0, n1 ) ));
+}
+
+//---------------------------------------------------------------------
+/** 3D float Perlin periodic noise.
+ */
+export function pnoise3(  x,  y,  z,  px,  py,  pz )
+{
+    let ix0, iy0, ix1, iy1, iz0, iz1;
+    let fx0, fy0, fz0, fx1, fy1, fz1;
+    let s, t, r;
+    let nxy0, nxy1, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    iz0 = Math.floor( z ); // Integer part of z
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fz0 = z - iz0;        // Fractional part of z
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    fz1 = fz0 - 1.0;
+    ix1 = (( ix0 + 1 ) % px ) & 0xff; // Wrap to 0..px-1 and wrap to 0..255
+    iy1 = (( iy0 + 1 ) % py ) & 0xff; // Wrap to 0..py-1 and wrap to 0..255
+    iz1 = (( iz0 + 1 ) % pz ) & 0xff; // Wrap to 0..pz-1 and wrap to 0..255
+    ix0 = ( ix0 % px ) & 0xff;
+    iy0 = ( iy0 % py ) & 0xff;
+    iz0 = ( iz0 % pz ) & 0xff;
+
+    r = fade( fz0 );
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nxy0 = grad3(perm[ix0 + perm[iy0 + perm[iz0]]], fx0, fy0, fz0);
+    nxy1 = grad3(perm[ix0 + perm[iy0 + perm[iz1]]], fx0, fy0, fz1);
+    nx0 = lerp( r, nxy0, nxy1 );
+
+    nxy0 = grad3(perm[ix0 + perm[iy1 + perm[iz0]]], fx0, fy1, fz0);
+    nxy1 = grad3(perm[ix0 + perm[iy1 + perm[iz1]]], fx0, fy1, fz1);
+    nx1 = lerp( r, nxy0, nxy1 );
+
+    n0 = lerp( t, nx0, nx1 );
+
+    nxy0 = grad3(perm[ix1 + perm[iy0 + perm[iz0]]], fx1, fy0, fz0);
+    nxy1 = grad3(perm[ix1 + perm[iy0 + perm[iz1]]], fx1, fy0, fz1);
+    nx0 = lerp( r, nxy0, nxy1 );
+
+    nxy0 = grad3(perm[ix1 + perm[iy1 + perm[iz0]]], fx1, fy1, fz0);
+    nxy1 = grad3(perm[ix1 + perm[iy1 + perm[iz1]]], fx1, fy1, fz1);
+    nx1 = lerp( r, nxy0, nxy1 );
+
+    n1 = lerp( t, nx0, nx1 );
+
+    return scale(0.936 * ( lerp( s, n0, n1 ) ));
+}
+
+
+//---------------------------------------------------------------------
+/** 4D float Perlin noise.
+ */
+
+export function noise4(  x,  y,  z,  w )
+{
+    let ix0, iy0, iz0, iw0, ix1, iy1, iz1, iw1;
+    let fx0, fy0, fz0, fw0, fx1, fy1, fz1, fw1;
+    let s, t, r, q;
+    let nxyz0, nxyz1, nxy0, nxy1, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    iz0 = Math.floor( z ); // Integer part of y
+    iw0 = Math.floor( w ); // Integer part of w
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fz0 = z - iz0;        // Fractional part of z
+    fw0 = w - iw0;        // Fractional part of w
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    fz1 = fz0 - 1.0;
+    fw1 = fw0 - 1.0;
+    ix1 = ( ix0 + 1 ) & 0xff;  // Wrap to 0..255
+    iy1 = ( iy0 + 1 ) & 0xff;
+    iz1 = ( iz0 + 1 ) & 0xff;
+    iw1 = ( iw0 + 1 ) & 0xff;
+    ix0 = ix0 & 0xff;
+    iy0 = iy0 & 0xff;
+    iz0 = iz0 & 0xff;
+    iw0 = iw0 & 0xff;
+
+    q = fade( fw0 );
+    r = fade( fz0 );
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx0, fy0, fz0, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx0, fy0, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx0, fy0, fz1, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx0, fy0, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx0 = lerp ( r, nxy0, nxy1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx0, fy1, fz0, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx0, fy1, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx0, fy1, fz1, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx0, fy1, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx1 = lerp ( r, nxy0, nxy1 );
+
+    n0 = lerp( t, nx0, nx1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx1, fy0, fz0, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx1, fy0, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx1, fy0, fz1, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx1, fy0, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx0 = lerp ( r, nxy0, nxy1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx1, fy1, fz0, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx1, fy1, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx1, fy1, fz1, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx1, fy1, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx1 = lerp ( r, nxy0, nxy1 );
+
+    n1 = lerp( t, nx0, nx1 );
+
+    return scale(0.87 * ( lerp( s, n0, n1 ) ));
+}
+
+//---------------------------------------------------------------------
+/** 4D float Perlin periodic noise.
+ */
+
+export function pnoise4(  x,  y,  z,  w,
+                             px,  py,  pz,  pw )
+{
+    let ix0, iy0, iz0, iw0, ix1, iy1, iz1, iw1;
+    let fx0, fy0, fz0, fw0, fx1, fy1, fz1, fw1;
+    let s, t, r, q;
+    let nxyz0, nxyz1, nxy0, nxy1, nx0, nx1, n0, n1;
+
+    ix0 = Math.floor( x ); // Integer part of x
+    iy0 = Math.floor( y ); // Integer part of y
+    iz0 = Math.floor( z ); // Integer part of y
+    iw0 = Math.floor( w ); // Integer part of w
+    fx0 = x - ix0;        // Fractional part of x
+    fy0 = y - iy0;        // Fractional part of y
+    fz0 = z - iz0;        // Fractional part of z
+    fw0 = w - iw0;        // Fractional part of w
+    fx1 = fx0 - 1.0;
+    fy1 = fy0 - 1.0;
+    fz1 = fz0 - 1.0;
+    fw1 = fw0 - 1.0;
+    ix1 = (( ix0 + 1 ) % px ) & 0xff;  // Wrap to 0..px-1 and wrap to 0..255
+    iy1 = (( iy0 + 1 ) % py ) & 0xff;  // Wrap to 0..py-1 and wrap to 0..255
+    iz1 = (( iz0 + 1 ) % pz ) & 0xff;  // Wrap to 0..pz-1 and wrap to 0..255
+    iw1 = (( iw0 + 1 ) % pw ) & 0xff;  // Wrap to 0..pw-1 and wrap to 0..255
+    ix0 = ( ix0 % px ) & 0xff;
+    iy0 = ( iy0 % py ) & 0xff;
+    iz0 = ( iz0 % pz ) & 0xff;
+    iw0 = ( iw0 % pw ) & 0xff;
+
+    q = fade( fw0 );
+    r = fade( fz0 );
+    t = fade( fy0 );
+    s = fade( fx0 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx0, fy0, fz0, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx0, fy0, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx0, fy0, fz1, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx0, fy0, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx0 = lerp ( r, nxy0, nxy1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx0, fy1, fz0, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx0, fy1, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx0, fy1, fz1, fw0);
+    nxyz1 = grad4(perm[ix0 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx0, fy1, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx1 = lerp ( r, nxy0, nxy1 );
+
+    n0 = lerp( t, nx0, nx1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw0]]]], fx1, fy0, fz0, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy0 + perm[iz0 + perm[iw1]]]], fx1, fy0, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw0]]]], fx1, fy0, fz1, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy0 + perm[iz1 + perm[iw1]]]], fx1, fy0, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx0 = lerp ( r, nxy0, nxy1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw0]]]], fx1, fy1, fz0, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy1 + perm[iz0 + perm[iw1]]]], fx1, fy1, fz0, fw1);
+    nxy0 = lerp( q, nxyz0, nxyz1 );
+
+    nxyz0 = grad4(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw0]]]], fx1, fy1, fz1, fw0);
+    nxyz1 = grad4(perm[ix1 + perm[iy1 + perm[iz1 + perm[iw1]]]], fx1, fy1, fz1, fw1);
+    nxy1 = lerp( q, nxyz0, nxyz1 );
+
+    nx1 = lerp ( r, nxy0, nxy1 );
+
+    n1 = lerp( t, nx0, nx1 );
+
+    return scale(0.87 * ( lerp( s, n0, n1 ) ));
+}
+
+function scale(n) {
+	return (1 + n) / 2;
+}
+
+export default function noise(x, y, z, w) {
+
+	switch(arguments.length) {
+		case 1:
+		  return noise1(x); //todo: move these to perlin functions
+		break;
+		case 2:
+		  return noise2(x, y); //todo: move these to perlin functions
+		break;
+		case 3:
+		  return noise3(x, y, z);
+	  case 3:
+		return noise4(x, y, z, w);
+		break;
+	}
+}
+
+//---------------------------------------------------------------------

+ 187 - 0
src/quadtree.js

@@ -0,0 +1,187 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+
+export const quadtree = (function() {
+
+  class CubeQuadTree {
+    constructor(params) {
+      this._params = params;
+      this._sides = [];
+
+      const r = params.radius;
+      let m;
+
+      const transforms = [];
+
+      // +Y
+      m = new THREE.Matrix4();
+      m.makeRotationX(-Math.PI / 2);
+      m.premultiply(new THREE.Matrix4().makeTranslation(0, r, 0));
+      transforms.push(m);
+
+      // -Y
+      m = new THREE.Matrix4();
+      m.makeRotationX(Math.PI / 2);
+      m.premultiply(new THREE.Matrix4().makeTranslation(0, -r, 0));
+      transforms.push(m);
+
+      // +X
+      m = new THREE.Matrix4();
+      m.makeRotationY(Math.PI / 2);
+      m.premultiply(new THREE.Matrix4().makeTranslation(r, 0, 0));
+      transforms.push(m);
+
+      // -X
+      m = new THREE.Matrix4();
+      m.makeRotationY(-Math.PI / 2);
+      m.premultiply(new THREE.Matrix4().makeTranslation(-r, 0, 0));
+      transforms.push(m);
+
+      // +Z
+      m = new THREE.Matrix4();
+      m.premultiply(new THREE.Matrix4().makeTranslation(0, 0, r));
+      transforms.push(m);
+      
+      // -Z
+      m = new THREE.Matrix4();
+      m.makeRotationY(Math.PI);
+      m.premultiply(new THREE.Matrix4().makeTranslation(0, 0, -r));
+      transforms.push(m);
+
+      for (let t of transforms) {
+        this._sides.push({
+          transform: t.clone(),
+          worldToLocal: t.clone().getInverse(t),
+          quadtree: new QuadTree({
+            size: r,
+            min_node_size: params.min_node_size,
+            localToWorld: t
+          }),
+        });
+      }
+   }
+
+    GetChildren() {
+      const children = [];
+
+      for (let s of this._sides) {
+        const side = {
+          transform: s.transform,
+          children: s.quadtree.GetChildren(),
+        }
+        children.push(side);
+      }
+      return children;
+    }
+
+    Insert(pos) {
+      for (let s of this._sides) {
+        s.quadtree.Insert(pos);
+      }
+    }
+  }
+
+  class QuadTree {
+    constructor(params) {
+      const s = params.size;
+      const b = new THREE.Box3(
+        new THREE.Vector3(-s, -s, 0),
+        new THREE.Vector3(s, s, 0));
+      this._root = {
+        bounds: b,
+        children: [],
+        center: b.getCenter(new THREE.Vector3()),
+        sphereCenter: b.getCenter(new THREE.Vector3()),
+        size: b.getSize(new THREE.Vector3()),
+        root: true,
+      };
+
+      this._params = params;
+      this._root.sphereCenter = this._root.center.clone();
+      this._root.sphereCenter.applyMatrix4(this._params.localToWorld);
+      this._root.sphereCenter.normalize();
+      this._root.sphereCenter.multiplyScalar(this._params.size);
+    }
+
+    GetChildren() {
+      const children = [];
+      this._GetChildren(this._root, children);
+      return children;
+    }
+
+    _GetChildren(node, target) {
+      if (node.children.length == 0) {
+        target.push(node);
+        return;
+      }
+
+      for (let c of node.children) {
+        this._GetChildren(c, target);
+      }
+  }
+
+    Insert(pos) {
+      this._Insert(this._root, pos);
+    }
+
+    _Insert(child, pos) {
+      const distToChild = this._DistanceToChild(child, pos);
+
+      if (distToChild < child.size.x * 1.0 && child.size.x > this._params.min_node_size) {
+        child.children = this._CreateChildren(child);
+
+        for (let c of child.children) {
+          this._Insert(c, pos);
+        }
+      }
+    }
+
+    _DistanceToChild(child, pos) {
+      return child.sphereCenter.distanceTo(pos);
+    }
+
+    _CreateChildren(child) {
+      const midpoint = child.bounds.getCenter(new THREE.Vector3());
+
+      // Bottom left
+      const b1 = new THREE.Box3(child.bounds.min, midpoint);
+
+      // Bottom right
+      const b2 = new THREE.Box3(
+        new THREE.Vector3(midpoint.x, child.bounds.min.y, 0),
+        new THREE.Vector3(child.bounds.max.x, midpoint.y, 0));
+
+      // Top left
+      const b3 = new THREE.Box3(
+        new THREE.Vector3(child.bounds.min.x, midpoint.y, 0),
+        new THREE.Vector3(midpoint.x, child.bounds.max.y, 0));
+
+      // Top right
+      const b4 = new THREE.Box3(midpoint, child.bounds.max);
+
+      const children = [b1, b2, b3, b4].map(
+          b => {
+            return {
+              bounds: b,
+              children: [],
+              center: b.getCenter(new THREE.Vector3()),
+              size: b.getSize(new THREE.Vector3())
+            };
+          });
+
+      for (let c of children) {
+        c.sphereCenter = c.center.clone();
+        c.sphereCenter.applyMatrix4(this._params.localToWorld);
+        c.sphereCenter.normalize()
+        c.sphereCenter.multiplyScalar(this._params.size);
+      }
+
+      return children;
+    }
+  }
+
+  return {
+    QuadTree: QuadTree,
+    CubeQuadTree: CubeQuadTree,
+  }
+})();

+ 418 - 0
src/scattering-shader.js

@@ -0,0 +1,418 @@
+export const scattering_shader = (function() {
+
+  const _VS = `#version 300 es
+
+  #define saturate(a) clamp( a, 0.0, 1.0 )
+
+  out vec2 vUv;
+
+  void main() {
+    vUv = uv;
+    gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+  }
+  `;
+  
+
+  const _PS = `#version 300 es
+  #include <packing>
+
+  #define saturate(a) clamp( a, 0.0, 1.0 )
+
+  #define PI 3.141592
+  #define PRIMARY_STEP_COUNT 16
+  #define LIGHT_STEP_COUNT 8
+
+
+  in vec2 vUv;
+  out vec4 out_FragColor;
+
+  uniform sampler2D tDiffuse;
+  uniform sampler2D tDepth;
+  uniform float cameraNear;
+  uniform float cameraFar;
+  uniform vec3 cameraForward;
+  uniform mat4 inverseProjection;
+  uniform mat4 inverseView;
+
+  uniform vec3 planetPosition;
+  uniform float planetRadius;
+  uniform float atmosphereRadius;
+  
+
+  vec3 _ScreenToWorld(vec3 pos) {
+    vec4 posP = vec4(pos.xyz * 2.0 - 1.0, 1.0);
+
+    vec4 posVS = inverseProjection * posP;
+    vec4 posWS = inverseView * vec4((posVS.xyz / posVS.w), 1.0);
+
+    return posWS.xyz;
+  }
+
+
+  float _SoftLight(float a, float b) {
+    return (b < 0.5 ?
+        (2.0 * a * b + a * a * (1.0 - 2.0 * b)) :
+        (2.0 * a * (1.0 - b) + sqrt(a) * (2.0 * b - 1.0))
+    );
+  }
+
+  vec3 _SoftLight(vec3 a, vec3 b) {
+    return vec3(
+        _SoftLight(a.x, b.x),
+        _SoftLight(a.y, b.y),
+        _SoftLight(a.z, b.z)
+    );
+  }
+
+  bool _RayIntersectsSphere(
+      vec3 rayStart, vec3 rayDir, vec3 sphereCenter, float sphereRadius, out float t0, out float t1) {
+    vec3 oc = rayStart - sphereCenter;
+    float a = dot(rayDir, rayDir);
+    float b = 2.0 * dot(oc, rayDir);
+    float c = dot(oc, oc) - sphereRadius * sphereRadius;
+    float d =  b * b - 4.0 * a * c;
+
+    // Also skip single point of contact
+    if (d <= 0.0) {
+      return false;
+    }
+
+    float r0 = (-b - sqrt(d)) / (2.0 * a);
+    float r1 = (-b + sqrt(d)) / (2.0 * a);
+
+    t0 = min(r0, r1);
+    t1 = max(r0, r1);
+
+    return (t1 >= 0.0);
+  }
+
+
+  vec3 _SampleLightRay(
+      vec3 origin, vec3 sunDir, float planetScale, float planetRadius, float totalRadius,
+      float rayleighScale, float mieScale, float absorptionHeightMax, float absorptionFalloff) {
+
+    float t0, t1;
+    _RayIntersectsSphere(origin, sunDir, planetPosition, totalRadius, t0, t1);
+
+    float actualLightStepSize = (t1 - t0) / float(LIGHT_STEP_COUNT);
+    float virtualLightStepSize = actualLightStepSize * planetScale;
+    float lightStepPosition = 0.0;
+
+    vec3 opticalDepthLight = vec3(0.0);
+
+    for (int j = 0; j < LIGHT_STEP_COUNT; j++) {
+      vec3 currentLightSamplePosition = origin + sunDir * (lightStepPosition + actualLightStepSize * 0.5);
+
+      // Calculate the optical depths and accumulate
+      float currentHeight = length(currentLightSamplePosition) - planetRadius;
+      float currentOpticalDepthRayleigh = exp(-currentHeight / rayleighScale) * virtualLightStepSize;
+      float currentOpticalDepthMie = exp(-currentHeight / mieScale) * virtualLightStepSize;
+      float currentOpticalDepthOzone = (1.0 / cosh((absorptionHeightMax - currentHeight) / absorptionFalloff));
+      currentOpticalDepthOzone *= currentOpticalDepthRayleigh * virtualLightStepSize;
+
+      opticalDepthLight += vec3(
+          currentOpticalDepthRayleigh,
+          currentOpticalDepthMie,
+          currentOpticalDepthOzone);
+
+      lightStepPosition += actualLightStepSize;
+    }
+
+    return opticalDepthLight;
+  }
+
+  void _ComputeScattering(
+      vec3 worldSpacePos, vec3 rayDirection, vec3 rayOrigin, vec3 sunDir,
+      out vec3 scatteringColour, out vec3 scatteringOpacity) {
+
+    vec3 betaRayleigh = vec3(5.5e-6, 13.0e-6, 22.4e-6);
+    float betaMie = 21e-6;
+    vec3 betaAbsorption = vec3(2.04e-5, 4.97e-5, 1.95e-6);
+    float g = 0.76;
+    float sunIntensity = 40.0;
+
+    float planetRadius = planetRadius;
+    float atmosphereRadius = atmosphereRadius - planetRadius;
+    float totalRadius = planetRadius + atmosphereRadius;
+
+    float referencePlanetRadius = 6371000.0;
+    float referenceAtmosphereRadius = 100000.0;
+    float referenceTotalRadius = referencePlanetRadius + referenceAtmosphereRadius;
+    float referenceRatio = referencePlanetRadius / referenceAtmosphereRadius;
+
+    float scaleRatio = planetRadius / atmosphereRadius;
+    float planetScale = referencePlanetRadius / planetRadius;
+    float atmosphereScale = scaleRatio / referenceRatio;
+    float maxDist = distance(worldSpacePos, rayOrigin);
+
+    float rayleighScale = 8500.0 / (planetScale * atmosphereScale);
+    float mieScale = 1200.0 / (planetScale * atmosphereScale);
+    float absorptionHeightMax = 32000.0 * (planetScale * atmosphereScale);
+    float absorptionFalloff = 3000.0 / (planetScale * atmosphereScale);;
+
+    float mu = dot(rayDirection, sunDir);
+    float mumu = mu * mu;
+    float gg = g * g;
+    float phaseRayleigh = 3.0 / (16.0 * PI) * (1.0 + mumu);
+    float phaseMie = 3.0 / (8.0 * PI) * ((1.0 - gg) * (mumu + 1.0)) / (pow(1.0 + gg - 2.0 * mu * g, 1.5) * (2.0 + gg));
+
+    // Early out if ray doesn't intersect atmosphere.
+    float t0, t1;
+    if (!_RayIntersectsSphere(rayOrigin, rayDirection, planetPosition, totalRadius, t0, t1)) {
+      scatteringOpacity = vec3(1.0);
+      return;
+    }
+
+    // Clip the ray between the camera and potentially the planet surface.
+    t0 = max(0.0, t0);
+    t1 = min(maxDist, t1);
+
+    float actualPrimaryStepSize = (t1 - t0) / float(PRIMARY_STEP_COUNT);
+    float virtualPrimaryStepSize = actualPrimaryStepSize * planetScale;
+    float primaryStepPosition = 0.0;
+
+    vec3 accumulatedRayleigh = vec3(0.0);
+    vec3 accumulatedMie = vec3(0.0);
+    vec3 opticalDepth = vec3(0.0);
+
+    // Take N steps along primary ray
+    for (int i = 0; i < PRIMARY_STEP_COUNT; i++) {
+      vec3 currentPrimarySamplePosition = rayOrigin + rayDirection * (
+          primaryStepPosition + actualPrimaryStepSize * 0.5);
+
+      float currentHeight = max(0.0, length(currentPrimarySamplePosition) - planetRadius);
+
+      float currentOpticalDepthRayleigh = exp(-currentHeight / rayleighScale) * virtualPrimaryStepSize;
+      float currentOpticalDepthMie = exp(-currentHeight / mieScale) * virtualPrimaryStepSize;
+
+      // Taken from https://www.shadertoy.com/view/wlBXWK
+      float currentOpticalDepthOzone = (1.0 / cosh((absorptionHeightMax - currentHeight) / absorptionFalloff));
+      currentOpticalDepthOzone *= currentOpticalDepthRayleigh * virtualPrimaryStepSize;
+
+      opticalDepth += vec3(currentOpticalDepthRayleigh, currentOpticalDepthMie, currentOpticalDepthOzone);
+
+      // Sample light ray and accumulate optical depth.
+      vec3 opticalDepthLight = _SampleLightRay(
+          currentPrimarySamplePosition, sunDir,
+          planetScale, planetRadius, totalRadius,
+          rayleighScale, mieScale, absorptionHeightMax, absorptionFalloff);
+
+      vec3 r = (
+          betaRayleigh * (opticalDepth.x + opticalDepthLight.x) +
+          betaMie * (opticalDepth.y + opticalDepthLight.y) + 
+          betaAbsorption * (opticalDepth.z + opticalDepthLight.z));
+      vec3 attn = exp(-r);
+
+      accumulatedRayleigh += currentOpticalDepthRayleigh * attn;
+      accumulatedMie += currentOpticalDepthMie * attn;
+
+      primaryStepPosition += actualPrimaryStepSize;
+    }
+
+    scatteringColour = sunIntensity * (phaseRayleigh * betaRayleigh * accumulatedRayleigh + phaseMie * betaMie * accumulatedMie);
+    scatteringOpacity = exp(
+        -(betaMie * opticalDepth.y + betaRayleigh * opticalDepth.x + betaAbsorption * opticalDepth.z));
+  }
+
+  vec3 _ApplyGroundFog(
+      in vec3 rgb,
+      float distToPoint,
+      float height,
+      in vec3 worldSpacePos,
+      in vec3 rayOrigin,
+      in vec3 rayDir,
+      in vec3 sunDir)
+  {
+    vec3 up = normalize(rayOrigin);
+
+    float skyAmt = dot(up, rayDir) * 0.25 + 0.75;
+    skyAmt = saturate(skyAmt);
+    skyAmt *= skyAmt;
+
+    vec3 DARK_BLUE = vec3(0.1, 0.2, 0.3);
+    vec3 LIGHT_BLUE = vec3(0.5, 0.6, 0.7);
+    vec3 DARK_ORANGE = vec3(0.7, 0.4, 0.05);
+    vec3 BLUE = vec3(0.5, 0.6, 0.7);
+    vec3 YELLOW = vec3(1.0, 0.9, 0.7);
+
+    vec3 fogCol = mix(DARK_BLUE, LIGHT_BLUE, skyAmt);
+    float sunAmt = max(dot(rayDir, sunDir), 0.0);
+    fogCol = mix(fogCol, YELLOW, pow(sunAmt, 16.0));
+
+    float be = 0.0025;
+    float fogAmt = (1.0 - exp(-distToPoint * be));
+
+    // Sun
+    sunAmt = 0.5 * saturate(pow(sunAmt, 256.0));
+
+    return mix(rgb, fogCol, fogAmt) + sunAmt * YELLOW;
+  }
+
+  vec3 _ApplySpaceFog(
+      in vec3 rgb,
+      in float distToPoint,
+      in float height,
+      in vec3 worldSpacePos,
+      in vec3 rayOrigin,
+      in vec3 rayDir,
+      in vec3 sunDir)
+  {
+    float atmosphereThickness = (atmosphereRadius - planetRadius);
+
+    float t0 = -1.0;
+    float t1 = -1.0;
+
+    // This is a hack since the world mesh has seams that we haven't fixed yet.
+    if (_RayIntersectsSphere(
+        rayOrigin, rayDir, planetPosition, planetRadius, t0, t1)) {
+      if (distToPoint > t0) {
+        distToPoint = t0;
+        worldSpacePos = rayOrigin + t0 * rayDir;
+      }
+    }
+
+    if (!_RayIntersectsSphere(
+        rayOrigin, rayDir, planetPosition, planetRadius + atmosphereThickness * 5.0, t0, t1)) {
+      return rgb * 0.5;
+    }
+
+    // Figure out a better way to do this
+    float silhouette = saturate((distToPoint - 10000.0) / 10000.0);
+
+    // Glow around planet
+    float scaledDistanceToSurface = 0.0;
+
+    // Calculate the closest point between ray direction and planet. Use a point in front of the
+    // camera to force differences as you get closer to planet.
+    vec3 fakeOrigin = rayOrigin + rayDir * atmosphereThickness;
+    float t = max(0.0, dot(rayDir, planetPosition - fakeOrigin) / dot(rayDir, rayDir));
+    vec3 pb = fakeOrigin + t * rayDir;
+
+    scaledDistanceToSurface = saturate((distance(pb, planetPosition) - planetRadius) / atmosphereThickness);
+    scaledDistanceToSurface = smoothstep(0.0, 1.0, 1.0 - scaledDistanceToSurface);
+    //scaledDistanceToSurface = smoothstep(0.0, 1.0, scaledDistanceToSurface);
+
+    float scatteringFactor = scaledDistanceToSurface * silhouette;
+
+    // Fog on surface
+    t0 = max(0.0, t0);
+    t1 = min(distToPoint, t1);
+
+    vec3 intersectionPoint = rayOrigin + t1 * rayDir;
+    vec3 normalAtIntersection = normalize(intersectionPoint);
+
+    float distFactor = exp(-distToPoint * 0.0005 / (atmosphereThickness));
+    float fresnel = 1.0 - saturate(dot(-rayDir, normalAtIntersection));
+    fresnel = smoothstep(0.0, 1.0, fresnel);
+
+    float extinctionFactor = saturate(fresnel * distFactor) * (1.0 - silhouette);
+
+    // Front/Back Lighting
+    vec3 BLUE = vec3(0.5, 0.6, 0.75);
+    vec3 YELLOW = vec3(1.0, 0.9, 0.7);
+    vec3 RED = vec3(0.035, 0.0, 0.0);
+
+    float NdotL = dot(normalAtIntersection, sunDir);
+    float wrap = 0.5;
+    float NdotL_wrap = max(0.0, (NdotL + wrap) / (1.0 + wrap));
+    float RdotS = max(0.0, dot(rayDir, sunDir));
+    float sunAmount = RdotS;
+
+    vec3 backLightingColour = YELLOW * 0.1;
+    vec3 frontLightingColour = mix(BLUE, YELLOW, pow(sunAmount, 32.0));
+
+    vec3 fogColour = mix(backLightingColour, frontLightingColour, NdotL_wrap);
+
+    extinctionFactor *= NdotL_wrap;
+
+    // Sun
+    float specular = pow((RdotS + 0.5) / (1.0 + 0.5), 64.0);
+
+    fresnel = 1.0 - saturate(dot(-rayDir, normalAtIntersection));
+    fresnel *= fresnel;
+
+    float sunFactor = (length(pb) - planetRadius) / (atmosphereThickness * 5.0);
+    sunFactor = (1.0 - saturate(sunFactor));
+    sunFactor *= sunFactor;
+    sunFactor *= sunFactor;
+    sunFactor *= specular * fresnel;
+
+    vec3 baseColour = mix(rgb, fogColour, extinctionFactor);
+    vec3 litColour = baseColour + _SoftLight(fogColour * scatteringFactor + YELLOW * sunFactor, baseColour);
+    vec3 blendedColour = mix(baseColour, fogColour, scatteringFactor);
+    blendedColour += blendedColour + _SoftLight(YELLOW * sunFactor, blendedColour);
+    return mix(litColour, blendedColour, scaledDistanceToSurface * 0.25);
+  }
+
+  vec3 _ApplyFog(
+    in vec3 rgb,
+    in float distToPoint,
+    in float height,
+    in vec3 worldSpacePos,
+    in vec3 rayOrigin,
+    in vec3 rayDir,
+    in vec3 sunDir)
+  {
+    float distToPlanet = max(0.0, length(rayOrigin) - planetRadius);
+    float atmosphereThickness = (atmosphereRadius - planetRadius);
+
+    vec3 groundCol = _ApplyGroundFog(
+      rgb, distToPoint, height, worldSpacePos, rayOrigin, rayDir, sunDir);
+    vec3 spaceCol = _ApplySpaceFog(
+      rgb, distToPoint, height, worldSpacePos, rayOrigin, rayDir, sunDir);
+
+    float blendFactor = saturate(distToPlanet / (atmosphereThickness * 0.5));
+
+    blendFactor = smoothstep(0.0, 1.0, blendFactor);
+    blendFactor = smoothstep(0.0, 1.0, blendFactor);
+
+    return mix(groundCol, spaceCol, blendFactor);
+  }
+
+  void main() {
+    float z = texture2D(tDepth, vUv).x;
+    vec3 posWS = _ScreenToWorld(vec3(vUv, z));
+    float dist = length(posWS - cameraPosition);
+    float height = max(0.0, length(cameraPosition) - planetRadius);
+    vec3 cameraDirection = normalize(posWS - cameraPosition);
+
+    vec3 diffuse = texture2D(tDiffuse, vUv).xyz;
+    vec3 lightDir = normalize(vec3(1, 1, -1));
+
+    diffuse = _ApplyFog(diffuse, dist, height, posWS, cameraPosition, cameraDirection, lightDir);
+
+    // vec3 scatteringColour = vec3(0.0);
+    // vec3 scatteringOpacity = vec3(1.0, 1.0, 1.0);
+    // _ComputeScattering(
+    //     posWS, cameraDirection, cameraPosition,
+    //     lightDir, scatteringColour, scatteringOpacity
+    // );
+
+    // diffuse = diffuse * scatteringOpacity + scatteringColour;
+
+    diffuse = ACESFilmicToneMapping(diffuse);
+
+    out_FragColor.rgb = diffuse;
+    out_FragColor.a = 1.0;
+  }
+  `;
+  
+
+  const _Shader = {
+    uniforms: {
+      "tDiffuse": { value: null },
+      "tDepth": { value: null },
+      "cameraNear": { value: 0.0 },
+      "cameraFar": { value: 0.0 },
+    },
+    vertexShader: _VS,
+    fragmentShader: _PS,
+  };
+
+  return {
+    Shader: _Shader,
+    VS: _VS,
+    PS: _PS,
+  };
+})();
+  

+ 115 - 0
src/sky.js

@@ -0,0 +1,115 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+import {Sky} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/objects/Sky.js';
+import {Water} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/objects/Water.js';
+
+
+export const sky = (function() {
+
+  class TerrainSky {
+    constructor(params) {
+      this._params = params;
+      this._Init(params);
+    }
+
+    _Init(params) {
+      const waterGeometry = new THREE.PlaneBufferGeometry(10000, 10000, 100, 100);
+
+      this._water = new Water(
+        waterGeometry,
+        {
+          textureWidth: 2048,
+          textureHeight: 2048,
+          waterNormals: new THREE.TextureLoader().load( 'resources/waternormals.jpg', function ( texture ) {
+            texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
+          } ),
+          alpha: 0.5,
+          sunDirection: new THREE.Vector3(1, 0, 0),
+          sunColor: 0xffffff,
+          waterColor: 0x001e0f,
+          distortionScale: 0.0,
+          fog: undefined
+        }
+      );
+      // this._water.rotation.x = - Math.PI / 2;
+      // this._water.position.y = 4;
+
+      this._sky = new Sky();
+      this._sky.scale.setScalar(10000);
+
+      this._group = new THREE.Group();
+      //this._group.add(this._water);
+      this._group.add(this._sky);
+
+      params.scene.add(this._group);
+
+      params.guiParams.sky = {
+        turbidity: 10.0,
+        rayleigh: 2,
+        mieCoefficient: 0.005,
+        mieDirectionalG: 0.8,
+        luminance: 1,
+      };
+
+      params.guiParams.sun = {
+        inclination: 0.31,
+        azimuth: 0.25,
+      };
+
+      const onShaderChange = () => {
+        for (let k in params.guiParams.sky) {
+          this._sky.material.uniforms[k].value = params.guiParams.sky[k];
+        }
+        for (let k in params.guiParams.general) {
+          this._sky.material.uniforms[k].value = params.guiParams.general[k];
+        }
+      };
+
+      const onSunChange = () => {
+        var theta = Math.PI * (params.guiParams.sun.inclination - 0.5);
+        var phi = 2 * Math.PI * (params.guiParams.sun.azimuth - 0.5);
+
+        const sunPosition = new THREE.Vector3();
+        sunPosition.x = Math.cos(phi);
+        sunPosition.y = Math.sin(phi) * Math.sin(theta);
+        sunPosition.z = Math.sin(phi) * Math.cos(theta);
+
+        this._sky.material.uniforms['sunPosition'].value.copy(sunPosition);
+        this._water.material.uniforms['sunDirection'].value.copy(sunPosition.normalize());
+      };
+
+      const skyRollup = params.gui.addFolder('Sky');
+      skyRollup.add(params.guiParams.sky, "turbidity", 0.1, 30.0).onChange(
+          onShaderChange);
+      skyRollup.add(params.guiParams.sky, "rayleigh", 0.1, 4.0).onChange(
+          onShaderChange);
+      skyRollup.add(params.guiParams.sky, "mieCoefficient", 0.0001, 0.1).onChange(
+          onShaderChange);
+      skyRollup.add(params.guiParams.sky, "mieDirectionalG", 0.0, 1.0).onChange(
+          onShaderChange);
+      skyRollup.add(params.guiParams.sky, "luminance", 0.0, 2.0).onChange(
+          onShaderChange);
+
+      const sunRollup = params.gui.addFolder('Sun');
+      sunRollup.add(params.guiParams.sun, "inclination", 0.0, 1.0).onChange(
+          onSunChange);
+      sunRollup.add(params.guiParams.sun, "azimuth", 0.0, 1.0).onChange(
+          onSunChange);
+
+      onShaderChange();
+      onSunChange();
+    }
+
+    Update(timeInSeconds) {
+      this._water.material.uniforms['time'].value += timeInSeconds;
+
+      this._group.position.x = this._params.camera.position.x;
+      this._group.position.z = this._params.camera.position.z;
+    }
+  }
+
+
+  return {
+    TerrainSky: TerrainSky
+  }
+})();

+ 76 - 0
src/spline.js

@@ -0,0 +1,76 @@
+export const spline = (function() {
+
+  class _CubicHermiteSpline {
+    constructor(lerp) {
+      this._points = [];
+      this._lerp = lerp;
+    }
+
+    AddPoint(t, d) {
+      this._points.push([t, d]);
+    }
+
+    Get(t) {
+      let p1 = 0;
+
+      for (let i = 0; i < this._points.length; i++) {
+        if (this._points[i][0] >= t) {
+          break;
+        }
+        p1 = i;
+      }
+
+      const p0 = Math.max(0, p1 - 1);
+      const p2 = Math.min(this._points.length - 1, p1 + 1);
+      const p3 = Math.min(this._points.length - 1, p1 + 2);
+
+      if (p1 == p2) {
+        return this._points[p1][1];
+      }
+
+      return this._lerp(
+          (t - this._points[p1][0]) / (
+              this._points[p2][0] - this._points[p1][0]),
+          this._points[p0][1], this._points[p1][1],
+          this._points[p2][1], this._points[p3][1]);
+    }
+  };
+
+  class _LinearSpline {
+    constructor(lerp) {
+      this._points = [];
+      this._lerp = lerp;
+    }
+
+    AddPoint(t, d) {
+      this._points.push([t, d]);
+    }
+
+    Get(t) {
+      let p1 = 0;
+
+      for (let i = 0; i < this._points.length; i++) {
+        if (this._points[i][0] >= t) {
+          break;
+        }
+        p1 = i;
+      }
+
+      const p2 = Math.min(this._points.length - 1, p1 + 1);
+
+      if (p1 == p2) {
+        return this._points[p1][1];
+      }
+
+      return this._lerp(
+          (t - this._points[p1][0]) / (
+              this._points[p2][0] - this._points[p1][0]),
+          this._points[p1][1], this._points[p2][1]);
+    }
+  }
+
+  return {
+    CubicHermiteSpline: _CubicHermiteSpline,
+    LinearSpline: _LinearSpline,
+  };
+})();

+ 309 - 0
src/terrain-chunk.js

@@ -0,0 +1,309 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+
+export const terrain_chunk = (function() {
+
+  class TerrainChunk {
+    constructor(params) {
+      this._params = params;
+      this._Init(params);
+    }
+    
+    Destroy() {
+      this._params.group.remove(this._plane);
+    }
+
+    Hide() {
+      this._plane.visible = false;
+    }
+
+    Show() {
+      this._plane.visible = true;
+    }
+
+    _Init(params) {
+      this._geometry = new THREE.BufferGeometry();
+      this._plane = new THREE.Mesh(this._geometry, params.material);
+      this._plane.castShadow = false;
+      this._plane.receiveShadow = true;
+      this._params.group.add(this._plane);
+    }
+
+    _GenerateHeight(v) {
+      return this._params.heightGenerators[0].Get(v.x, v.y, v.z)[0];
+    }
+
+    *_Rebuild() {
+      const _D = new THREE.Vector3();
+      const _D1 = new THREE.Vector3();
+      const _D2 = new THREE.Vector3();
+      const _P = new THREE.Vector3();
+      const _H = new THREE.Vector3();
+      const _W = new THREE.Vector3();
+      const _C = new THREE.Vector3();
+      const _S = new THREE.Vector3();
+
+      const _N = new THREE.Vector3();
+      const _N1 = new THREE.Vector3();
+      const _N2 = new THREE.Vector3();
+      const _N3 = new THREE.Vector3();
+
+      const positions = [];
+      const colors = [];
+      const normals = [];
+      const tangents = [];
+      const uvs = [];
+      const weights1 = [];
+      const weights2 = [];
+      const indices = [];
+      const wsPositions = [];
+
+      const localToWorld = this._params.group.matrix;
+      const resolution = this._params.resolution;
+      const radius = this._params.radius;
+      const offset = this._params.offset;
+      const width = this._params.width;
+      const half = width / 2;
+
+      for (let x = 0; x < resolution + 1; x++) {
+        const xp = width * x / resolution;
+        for (let y = 0; y < resolution + 1; y++) {
+          const yp = width * y / resolution;
+
+          // Compute position
+          _P.set(xp - half, yp - half, radius);
+          _P.add(offset);
+          _P.normalize();
+          _D.copy(_P);
+          _P.multiplyScalar(radius);
+          _P.z -= radius;
+
+          // Compute a world space position to sample noise
+          _W.copy(_P);
+          _W.applyMatrix4(localToWorld);
+
+          const height = this._GenerateHeight(_W);
+
+          // Purturb height along z-vector
+          _H.copy(_D);
+          _H.multiplyScalar(height);
+          _P.add(_H);
+
+          positions.push(_P.x, _P.y, _P.z);
+
+          _S.set(_W.x, _W.y, height);
+
+          const color = this._params.colourGenerator.GetColour(_S);
+          colors.push(color.r, color.g, color.b);
+          normals.push(_D.x, _D.y, _D.z);
+          tangents.push(1, 0, 0, 1);
+          wsPositions.push(_W.x, _W.y, height);
+          // TODO GUI
+          uvs.push(_P.x / 200.0, _P.y / 200.0);
+        }
+      }
+      yield;
+
+      for (let i = 0; i < resolution; i++) {
+        for (let j = 0; j < resolution; j++) {
+          indices.push(
+              i * (resolution + 1) + j,
+              (i + 1) * (resolution + 1) + j + 1,
+              i * (resolution + 1) + j + 1);
+          indices.push(
+              (i + 1) * (resolution + 1) + j,
+              (i + 1) * (resolution + 1) + j + 1,
+              i * (resolution + 1) + j);
+        }
+      }
+      yield;
+
+      const up = [...normals];
+
+      for (let i = 0, n = indices.length; i < n; i+= 3) {
+        const i1 = indices[i] * 3;
+        const i2 = indices[i+1] * 3;
+        const i3 = indices[i+2] * 3;
+
+        _N1.fromArray(positions, i1);
+        _N2.fromArray(positions, i2);
+        _N3.fromArray(positions, i3);
+
+        _D1.subVectors(_N3, _N2);
+        _D2.subVectors(_N1, _N2);
+        _D1.cross(_D2);
+
+        normals[i1] += _D1.x;
+        normals[i2] += _D1.x;
+        normals[i3] += _D1.x;
+
+        normals[i1+1] += _D1.y;
+        normals[i2+1] += _D1.y;
+        normals[i3+1] += _D1.y;
+
+        normals[i1+2] += _D1.z;
+        normals[i2+2] += _D1.z;
+        normals[i3+2] += _D1.z;
+      }
+      yield;
+
+      for (let i = 0, n = normals.length; i < n; i+=3) {
+        _N.fromArray(normals, i);
+        _N.normalize();
+        normals[i] = _N.x;
+        normals[i+1] = _N.y;
+        normals[i+2] = _N.z;
+      }
+      yield;
+
+      let count = 0;
+      for (let i = 0, n = indices.length; i < n; i+=3) {
+        const splats = [];
+        const i1 = indices[i] * 3;
+        const i2 = indices[i+1] * 3;
+        const i3 = indices[i+2] * 3;
+        const indexes = [i1, i2, i3];
+        for (let j = 0; j < 3; j++) {
+          const j1 = indexes[j];
+          _P.fromArray(wsPositions, j1);
+          _N.fromArray(normals, j1);
+          _D.fromArray(up, j1);
+          const s = this._params.colourGenerator.GetSplat(_P, _N, _D);
+          splats.push(s);
+        }
+
+        const splatStrengths = {};
+        for (let k in splats[0]) {
+          splatStrengths[k] = {key: k, strength: 0.0};
+        }
+        for (let curSplat of splats) {
+          for (let k in curSplat) {
+            splatStrengths[k].strength += curSplat[k].strength;
+          }
+        }
+
+        let typeValues = Object.values(splatStrengths);
+        typeValues.sort((a, b) => {
+          if (a.strength < b.strength) {
+            return 1;
+          }
+          if (a.strength > b.strength) {
+            return -1;
+          }
+          return 0;
+        });
+
+        const w1 = indices[i] * 4;
+        const w2 = indices[i+1] * 4;
+        const w3 = indices[i+2] * 4;
+
+        for (let s = 0; s < 3; s++) {
+          let total = (
+              splats[s][typeValues[0].key].strength +
+              splats[s][typeValues[1].key].strength +
+              splats[s][typeValues[2].key].strength +
+              splats[s][typeValues[3].key].strength);
+          const normalization = 1.0 / total;
+
+          splats[s][typeValues[0].key].strength *= normalization;
+          splats[s][typeValues[1].key].strength *= normalization;
+          splats[s][typeValues[2].key].strength *= normalization;
+          splats[s][typeValues[3].key].strength *= normalization;
+        }
+ 
+        weights1.push(splats[0][typeValues[3].key].index);
+        weights1.push(splats[0][typeValues[2].key].index);
+        weights1.push(splats[0][typeValues[1].key].index);
+        weights1.push(splats[0][typeValues[0].key].index);
+
+        weights1.push(splats[1][typeValues[3].key].index);
+        weights1.push(splats[1][typeValues[2].key].index);
+        weights1.push(splats[1][typeValues[1].key].index);
+        weights1.push(splats[1][typeValues[0].key].index);
+
+        weights1.push(splats[2][typeValues[3].key].index);
+        weights1.push(splats[2][typeValues[2].key].index);
+        weights1.push(splats[2][typeValues[1].key].index);
+        weights1.push(splats[2][typeValues[0].key].index);
+
+        weights2.push(splats[0][typeValues[3].key].strength);
+        weights2.push(splats[0][typeValues[2].key].strength);
+        weights2.push(splats[0][typeValues[1].key].strength);
+        weights2.push(splats[0][typeValues[0].key].strength);
+
+        weights2.push(splats[1][typeValues[3].key].strength);
+        weights2.push(splats[1][typeValues[2].key].strength);
+        weights2.push(splats[1][typeValues[1].key].strength);
+        weights2.push(splats[1][typeValues[0].key].strength);
+
+        weights2.push(splats[2][typeValues[3].key].strength);
+        weights2.push(splats[2][typeValues[2].key].strength);
+        weights2.push(splats[2][typeValues[1].key].strength);
+        weights2.push(splats[2][typeValues[0].key].strength);
+
+        count++;
+        if ((count % 10000) == 0) {
+          yield;
+        }
+      }
+      yield;
+
+      function _Unindex(src, stride) {
+        const dst = [];
+        for (let i = 0, n = indices.length; i < n; i+= 3) {
+          const i1 = indices[i] * stride;
+          const i2 = indices[i+1] * stride;
+          const i3 = indices[i+2] * stride;
+
+          for (let j = 0; j < stride; j++) {
+            dst.push(src[i1 + j]);
+          }
+          for (let j = 0; j < stride; j++) {
+            dst.push(src[i2 + j]);
+          }
+          for (let j = 0; j < stride; j++) {
+            dst.push(src[i3 + j]);
+          }
+        }
+        return dst;
+      }
+
+      const uiPositions = _Unindex(positions, 3);
+      yield;
+
+      const uiColours = _Unindex(colors, 3);
+      yield;
+
+      const uiNormals = _Unindex(normals, 3);
+      yield;
+
+      const uiTangents = _Unindex(tangents, 4);
+      yield;
+
+      const uiUVs = _Unindex(uvs, 2);
+      yield;
+
+      const uiWeights1 = weights1;
+      const uiWeights2 = weights2;
+
+      this._geometry.setAttribute(
+        'position', new THREE.Float32BufferAttribute(uiPositions, 3));
+      this._geometry.setAttribute(
+          'color', new THREE.Float32BufferAttribute(uiColours, 3));
+      this._geometry.setAttribute(
+          'normal', new THREE.Float32BufferAttribute(uiNormals, 3));
+      this._geometry.setAttribute(
+          'tangent', new THREE.Float32BufferAttribute(uiTangents, 4));
+      this._geometry.setAttribute(
+          'weights1', new THREE.Float32BufferAttribute(uiWeights1, 4));
+      this._geometry.setAttribute(
+          'weights2', new THREE.Float32BufferAttribute(uiWeights2, 4));
+      this._geometry.setAttribute(
+          'uv', new THREE.Float32BufferAttribute(uiUVs, 2));
+    }
+  }
+
+  return {
+    TerrainChunk: TerrainChunk
+  }
+})();

+ 317 - 0
src/terrain-shader.js

@@ -0,0 +1,317 @@
+export const terrain_shader = (function() {
+
+  const _VS = `#version 300 es
+
+precision highp float;
+
+uniform mat4 modelMatrix;
+uniform mat4 modelViewMatrix;
+uniform mat4 projectionMatrix;
+uniform vec3 cameraPosition;
+uniform float fogDensity;
+uniform vec3 cloudScale;
+
+// Attributes
+in vec3 position;
+in vec3 normal;
+in vec4 tangent;
+in vec3 color;
+in vec2 uv;
+in vec4 weights1;
+in vec4 weights2;
+
+// Outputs
+out vec2 vUV;
+out vec4 vColor;
+out vec3 vNormal;
+out vec4 vTangent;
+out vec3 vPosition;
+out vec4 vWeights1;
+out vec4 vWeights2;
+
+#define saturate(a) clamp( a, 0.0, 1.0 )
+
+void main(){
+  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+
+  vUV = uv;
+  vNormal = normal;
+  vTangent = tangent;
+
+  vColor = vec4(color, 1);
+  vPosition = position.xyz;
+  vWeights1 = weights1;
+  vWeights2 = weights2;
+}
+  `;
+  
+
+  const _PS = `#version 300 es
+
+precision highp float;
+precision highp int;
+precision highp sampler2DArray;
+
+uniform sampler2DArray normalMap;
+uniform sampler2DArray diffuseMap;
+uniform sampler2D noiseMap;
+
+uniform mat4 modelMatrix;
+uniform mat4 modelViewMatrix;
+uniform vec3 cameraPosition;
+
+in vec2 vUV;
+in vec4 vColor;
+in vec3 vNormal;
+in vec4 vTangent;
+in vec3 vPosition;
+in vec4 vWeights1;
+in vec4 vWeights2;
+
+out vec4 out_FragColor;
+
+#define saturate(a) clamp( a, 0.0, 1.0 )
+
+const float _TRI_SCALE = 2000.0;
+
+float sum( vec3 v ) { return v.x+v.y+v.z; }
+
+vec4 hash4( vec2 p ) {
+  return fract(
+    sin(vec4(1.0+dot(p,vec2(37.0,17.0)), 
+              2.0+dot(p,vec2(11.0,47.0)),
+              3.0+dot(p,vec2(41.0,29.0)),
+              4.0+dot(p,vec2(23.0,31.0))))*103.0);
+}
+
+
+vec3 _ACESFilmicToneMapping(vec3 x) {
+  float a = 2.51;
+  float b = 0.03;
+  float c = 2.43;
+  float d = 0.59;
+  float e = 0.14;
+  return saturate((x*(a*x+b))/(x*(c*x+d)+e));
+}
+
+vec4 _CalculateLighting(
+    vec3 lightDirection, vec3 lightColour, vec3 worldSpaceNormal, vec3 viewDirection) {
+  float diffuse = saturate(dot(worldSpaceNormal, lightDirection));
+
+  vec3 H = normalize(lightDirection + viewDirection);
+  float NdotH = dot(worldSpaceNormal, H);
+  float specular = saturate(pow(NdotH, 8.0));
+
+  return vec4(lightColour * (diffuse + diffuse * specular), 0);
+}
+
+vec4 _ComputeLighting(vec3 worldSpaceNormal, vec3 sunDir, vec3 viewDirection) {
+  // Hardcoded, whee!
+  vec4 lighting;
+  
+  lighting += _CalculateLighting(
+      sunDir, vec3(1.0, 1.0, 1.0), worldSpaceNormal, viewDirection);
+  // lighting += _CalculateLighting(
+  //     -sunDir, vec3(0.1, 0.1, 0.15), worldSpaceNormal, viewDirection);
+  lighting += _CalculateLighting(
+      vec3(0, 1, 0), vec3(0.25, 0.25, 0.25), worldSpaceNormal, viewDirection);
+
+  lighting += vec4(0.15, 0.15, 0.15, 0.0);
+  
+  return lighting;
+}
+
+vec4 _TerrainBlend_4(vec4 samples[4]) {
+  float depth = 0.2;
+  float ma = max(
+      samples[0].w,
+      max(
+          samples[1].w,
+          max(samples[2].w, samples[3].w))) - depth;
+
+  float b1 = max(samples[0].w - ma, 0.0);
+  float b2 = max(samples[1].w - ma, 0.0);
+  float b3 = max(samples[2].w - ma, 0.0);
+  float b4 = max(samples[3].w - ma, 0.0);
+
+  vec4 numer = (
+      samples[0] * b1 + samples[1] * b2 +
+      samples[2] * b3 + samples[3] * b4);
+  float denom = (b1 + b2 + b3 + b4);
+  return numer / denom;
+}
+
+vec4 _TerrainBlend_4_lerp(vec4 samples[4]) {
+  return (
+      samples[0] * samples[0].w + samples[1] * samples[1].w +
+      samples[2] * samples[2].w + samples[3] * samples[3].w);
+}
+
+// Lifted from https://www.shadertoy.com/view/Xtl3zf
+vec4 texture_UV(in sampler2DArray srcTexture, in vec3 x) {
+  float k = texture(noiseMap, 0.0025*x.xy).x; // cheap (cache friendly) lookup
+  float l = k*8.0;
+  float f = fract(l);
+  
+  float ia = floor(l+0.5); // suslik's method (see comments)
+  float ib = floor(l);
+  f = min(f, 1.0-f)*2.0;
+
+  vec2 offa = sin(vec2(3.0,7.0)*ia); // can replace with any other hash
+  vec2 offb = sin(vec2(3.0,7.0)*ib); // can replace with any other hash
+
+  vec4 cola = texture(srcTexture, vec3(x.xy + offa, x.z));
+  vec4 colb = texture(srcTexture, vec3(x.xy + offb, x.z));
+
+  return mix(cola, colb, smoothstep(0.2,0.8,f-0.1*sum(cola.xyz-colb.xyz)));
+}
+
+vec4 _Triplanar_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) {
+  vec4 dx = texture_UV(tex, vec3(pos.zy / _TRI_SCALE, texSlice));
+  vec4 dy = texture_UV(tex, vec3(pos.xz / _TRI_SCALE, texSlice));
+  vec4 dz = texture_UV(tex, vec3(pos.xy / _TRI_SCALE, texSlice));
+
+  vec3 weights = abs(normal.xyz);
+  weights = weights / (weights.x + weights.y + weights.z);
+
+  return dx * weights.x + dy * weights.y + dz * weights.z;
+}
+
+vec4 _TriplanarN_UV(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) {
+  // Tangent Reconstruction
+  // Triplanar uvs
+  vec2 uvX = pos.zy; // x facing plane
+  vec2 uvY = pos.xz; // y facing plane
+  vec2 uvZ = pos.xy; // z facing plane
+  // Tangent space normal maps
+  vec3 tx = texture_UV(tex, vec3(uvX / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+  vec3 ty = texture_UV(tex, vec3(uvY / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+  vec3 tz = texture_UV(tex, vec3(uvZ / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+
+  vec3 weights = abs(normal.xyz);
+  weights = weights / (weights.x + weights.y + weights.z);
+
+  // Get the sign (-1 or 1) of the surface normal
+  vec3 axis = sign(normal);
+  // Construct tangent to world matrices for each axis
+  vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0)));
+  vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x;
+  mat3 tbnX = mat3(tangentX, bitangentX, normal);
+
+  vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y)));
+  vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y;
+  mat3 tbnY = mat3(tangentY, bitangentY, normal);
+
+  vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0)));
+  vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z;
+  mat3 tbnZ = mat3(tangentZ, bitangentZ, normal);
+
+  // Apply tangent to world matrix and triblend
+  // Using clamp() because the cross products may be NANs
+  vec3 worldNormal = normalize(
+      clamp(tbnX * tx, -1.0, 1.0) * weights.x +
+      clamp(tbnY * ty, -1.0, 1.0) * weights.y +
+      clamp(tbnZ * tz, -1.0, 1.0) * weights.z
+      );
+  return vec4(worldNormal, 0.0);
+}
+
+vec4 _Triplanar(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) {
+  vec4 dx = texture(tex, vec3(pos.zy / _TRI_SCALE, texSlice));
+  vec4 dy = texture(tex, vec3(pos.xz / _TRI_SCALE, texSlice));
+  vec4 dz = texture(tex, vec3(pos.xy / _TRI_SCALE, texSlice));
+
+  vec3 weights = abs(normal.xyz);
+  weights = weights / (weights.x + weights.y + weights.z);
+
+  return dx * weights.x + dy * weights.y + dz * weights.z;
+}
+
+vec4 _TriplanarN(vec3 pos, vec3 normal, float texSlice, sampler2DArray tex) {
+  vec2 uvx = pos.zy;
+  vec2 uvy = pos.xz;
+  vec2 uvz = pos.xy;
+  vec3 tx = texture(tex, vec3(uvx / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+  vec3 ty = texture(tex, vec3(uvy / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+  vec3 tz = texture(tex, vec3(uvz / _TRI_SCALE, texSlice)).xyz * vec3(2,2,2) - vec3(1,1,1);
+
+  vec3 weights = abs(normal.xyz);
+  weights *= weights;
+  weights = weights / (weights.x + weights.y + weights.z);
+
+  vec3 axis = sign(normal);
+  vec3 tangentX = normalize(cross(normal, vec3(0.0, axis.x, 0.0)));
+  vec3 bitangentX = normalize(cross(tangentX, normal)) * axis.x;
+  mat3 tbnX = mat3(tangentX, bitangentX, normal);
+
+  vec3 tangentY = normalize(cross(normal, vec3(0.0, 0.0, axis.y)));
+  vec3 bitangentY = normalize(cross(tangentY, normal)) * axis.y;
+  mat3 tbnY = mat3(tangentY, bitangentY, normal);
+
+  vec3 tangentZ = normalize(cross(normal, vec3(0.0, -axis.z, 0.0)));
+  vec3 bitangentZ = normalize(-cross(tangentZ, normal)) * axis.z;
+  mat3 tbnZ = mat3(tangentZ, bitangentZ, normal);
+
+  vec3 worldNormal = normalize(
+      clamp(tbnX * tx, -1.0, 1.0) * weights.x +
+      clamp(tbnY * ty, -1.0, 1.0) * weights.y +
+      clamp(tbnZ * tz, -1.0, 1.0) * weights.z);
+  return vec4(worldNormal, 0.0);
+}
+
+void main() {
+  vec3 worldPosition = (modelMatrix * vec4(vPosition, 1)).xyz;
+  vec3 eyeDirection = normalize(worldPosition - cameraPosition);
+  vec3 sunDir = normalize(vec3(1, 1, -1));
+
+  float weightIndices[4] = float[4](vWeights1.x, vWeights1.y, vWeights1.z, vWeights1.w);
+  float weightValues[4] = float[4](vWeights2.x, vWeights2.y, vWeights2.z, vWeights2.w);
+
+  // TRIPLANAR SPLATTING w/ NORMALS & UVS
+  vec3 worldSpaceNormal = (modelMatrix * vec4(vNormal, 0.0)).xyz;
+  vec4 diffuseSamples[4];
+  vec4 normalSamples[4];
+
+  for (int i = 0; i < 4; ++i) {
+    vec4 d = vec4(0.0);
+    vec4 n = vec4(0.0);
+    if (weightValues[i] > 0.0) {
+      d = _Triplanar_UV(
+          worldPosition, worldSpaceNormal, weightIndices[i], diffuseMap);
+      n = _TriplanarN_UV(
+          worldPosition, worldSpaceNormal, weightIndices[i], normalMap);
+
+      d.w *= weightValues[i];
+      n.w = d.w;
+    }
+
+    diffuseSamples[i] = d;
+    normalSamples[i] = n;
+  }
+
+  vec4 diffuseBlended = _TerrainBlend_4(diffuseSamples);
+  vec4 normalBlended = _TerrainBlend_4(normalSamples);
+
+  vec3 diffuse = diffuseBlended.xyz;
+  worldSpaceNormal = normalize(normalBlended.xyz);
+
+  // Bit of a hack to remove lighting on dark side of planet
+  vec3 planetNormal = normalize(worldPosition);
+  float planetLighting = saturate(dot(planetNormal, sunDir));
+
+  vec4 lighting = _ComputeLighting(worldSpaceNormal, sunDir, -eyeDirection);
+  vec3 finalColour = mix(vec3(1.0, 1.0, 1.0), vColor.xyz, 0.25) * diffuse;
+
+  finalColour *= lighting.xyz * planetLighting;
+
+  out_FragColor = vec4(_ACESFilmicToneMapping(finalColour), 1);
+}
+
+  `;
+  
+    return {
+      VS: _VS,
+      PS: _PS,
+    };
+  })();
+  

+ 552 - 0
src/terrain.js

@@ -0,0 +1,552 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+import {graphics} from './graphics.js';
+import {math} from './math.js';
+import {noise} from './noise.js';
+import {quadtree} from './quadtree.js';
+import {spline} from './spline.js';
+import {terrain_chunk} from './terrain-chunk.js';
+import {terrain_shader} from './terrain-shader.js';
+import {textures} from './textures.js';
+import {utils} from './utils.js';
+
+export const terrain = (function() {
+
+  const _WHITE = new THREE.Color(0x808080);
+
+  const _DEEP_OCEAN = new THREE.Color(0x20020FF);
+  const _SHALLOW_OCEAN = new THREE.Color(0x8080FF);
+  const _BEACH = new THREE.Color(0xd9d592);
+  const _SNOW = new THREE.Color(0xFFFFFF);
+  const _ApplyWeightsOREST_TROPICAL = new THREE.Color(0x4f9f0f);
+  const _ApplyWeightsOREST_TEMPERATE = new THREE.Color(0x2b960e);
+  const _ApplyWeightsOREST_BOREAL = new THREE.Color(0x29c100);
+  
+  const _GREEN = new THREE.Color(0x80FF80);
+  const _RED = new THREE.Color(0xFF8080);
+  const _BLACK = new THREE.Color(0x000000);
+  
+  const _MIN_CELL_SIZE = 500;
+  const _MIN_CELL_RESOLUTION = 64;
+  const _PLANET_RADIUS = 4000;
+
+
+  class HeightGenerator {
+    constructor(generator, position, minRadius, maxRadius) {
+      this._position = position.clone();
+      this._radius = [minRadius, maxRadius];
+      this._generator = generator;
+    }
+  
+    Get(x, y, z) {
+      return [this._generator.Get(x, y, z), 1];
+    }
+  }
+  
+  
+  class FixedHeightGenerator {
+    constructor() {}
+  
+    Get() {
+      return [50, 1];
+    }
+  }
+   
+
+  class TextureSplatter {
+    constructor(params) {
+      const _colourLerp = (t, p0, p1) => {
+        const c = p0.clone();
+  
+        return c.lerp(p1, t);
+      };
+      this._colourSpline = [
+        new spline.LinearSpline(_colourLerp),
+        new spline.LinearSpline(_colourLerp)
+      ];
+
+      // Arid
+      this._colourSpline[0].AddPoint(0.0, new THREE.Color(0xb7a67d));
+      this._colourSpline[0].AddPoint(0.5, new THREE.Color(0xf1e1bc));
+      this._colourSpline[0].AddPoint(1.0, _SNOW);
+  
+      // Humid
+      this._colourSpline[1].AddPoint(0.0, _ApplyWeightsOREST_BOREAL);
+      this._colourSpline[1].AddPoint(0.5, new THREE.Color(0xcee59c));
+      this._colourSpline[1].AddPoint(1.0, _SNOW);
+
+      this._oceanSpline = new spline.LinearSpline(_colourLerp);
+      this._oceanSpline.AddPoint(0, _DEEP_OCEAN);
+      this._oceanSpline.AddPoint(0.03, _SHALLOW_OCEAN);
+      this._oceanSpline.AddPoint(0.05, _SHALLOW_OCEAN);
+
+      this._params = params;
+    }
+  
+    _BaseColour(x, y, z) {
+      const m = this._params.biomeGenerator.Get(x, y, z);
+      const h = math.sat(z / 100.0);
+  
+      const c1 = this._colourSpline[0].Get(h);
+      const c2 = this._colourSpline[1].Get(h);
+  
+      let c = c1.lerp(c2, m);
+
+      if (h < 0.1) {
+        c = c.lerp(new THREE.Color(0x54380e), 1.0 - math.sat(h / 0.05));
+      }
+      return c;      
+    }
+
+    _Colour(x, y, z) {
+      const c = this._BaseColour(x, y, z);
+      const r = this._params.colourNoise.Get(x, y, z) * 2.0 - 1.0;
+
+      c.offsetHSL(0.0, 0.0, r * 0.01);
+      return c;
+    }
+
+    _GetTextureWeights(p, n, up) {
+      const m = this._params.biomeGenerator.Get(p.x, p.y, p.z);
+      const h = p.z / 100.0;
+
+      const types = {
+        dirt: {index: 0, strength: 0.0},
+        grass: {index: 1, strength: 0.0},
+        gravel: {index: 2, strength: 0.0},
+        rock: {index: 3, strength: 0.0},
+        snow: {index: 4, strength: 0.0},
+        snowrock: {index: 5, strength: 0.0},
+        cobble: {index: 6, strength: 0.0},
+        sandyrock: {index: 7, strength: 0.0},
+      };
+
+      function _ApplyWeights(dst, v, m) {
+        for (let k in types) {
+          types[k].strength *= m;
+        }
+        types[dst].strength = v;
+      };
+
+      types.grass.strength = 1.0;
+      _ApplyWeights('gravel', 1.0 - m, m);
+
+      if (h < 0.2) {
+        const s = 1.0 - math.sat((h - 0.1) / 0.05);
+        _ApplyWeights('cobble', s, 1.0 - s);
+
+        if (h < 0.1) {
+          const s = 1.0 - math.sat((h - 0.05) / 0.05);
+          _ApplyWeights('sandyrock', s, 1.0 - s);
+        }
+      } else {
+        if (h > 0.125) {
+          const s = (math.sat((h - 0.125) / 1.25));
+          _ApplyWeights('rock', s, 1.0 - s);
+        }
+
+        if (h > 1.5) {
+          const s = math.sat((h - 0.75) / 2.0);
+          _ApplyWeights('snow', s, 1.0 - s);
+        }
+      }
+
+      // In case nothing gets set.
+      types.dirt.strength = 0.01;
+
+      let total = 0.0;
+      for (let k in types) {
+        total += types[k].strength;
+      }
+      if (total < 0.01) {
+        const a = 0;
+      }
+      const normalization = 1.0 / total;
+
+      for (let k in types) {
+        types[k].strength / normalization;
+      }
+
+      return types;
+    }
+
+    GetColour(position) {
+      return this._Colour(position.x, position.y, position.z);
+    }
+
+    GetSplat(position, normal, up) {
+      return this._GetTextureWeights(position, normal, up);
+    }
+  }
+
+  
+  class FixedColourGenerator {
+    constructor(params) {
+      this._params = params;
+    }
+  
+    Get() {
+      return this._params.colour;
+    }
+  }
+  
+  
+
+  class TerrainChunkRebuilder {
+    constructor(params) {
+      this._pool = {};
+      this._params = params;
+      this._Reset();
+    }
+
+    AllocateChunk(params) {
+      const w = params.width;
+
+      if (!(w in this._pool)) {
+        this._pool[w] = [];
+      }
+
+      let c = null;
+      if (this._pool[w].length > 0) {
+        c = this._pool[w].pop();
+        c._params = params;
+      } else {
+        c = new terrain_chunk.TerrainChunk(params);
+      }
+
+      c.Hide();
+
+      this._queued.push(c);
+
+      return c;    
+    }
+
+    _RecycleChunks(chunks) {
+      for (let c of chunks) {
+        if (!(c.chunk._params.width in this._pool)) {
+          this._pool[c.chunk._params.width] = [];
+        }
+
+        c.chunk.Destroy();
+      }
+    }
+
+    _Reset() {
+      this._active = null;
+      this._queued = [];
+      this._old = [];
+      this._new = [];
+    }
+
+    get Busy() {
+      return this._active || this._queued.length > 0;
+    }
+
+    Rebuild(chunks) {
+      if (this.Busy) {
+        return;
+      }
+      for (let k in chunks) {
+        this._queued.push(chunks[k].chunk);
+      }
+    }
+
+    Update() {
+      if (this._active) {
+        const r = this._active.next();
+        if (r.done) {
+          this._active = null;
+        }
+      } else {
+        const b = this._queued.pop();
+        if (b) {
+          this._active = b._Rebuild();
+          this._new.push(b);
+        }
+      }
+
+      if (this._active) {
+        return;
+      }
+
+      if (!this._queued.length) {
+        this._RecycleChunks(this._old);
+        for (let b of this._new) {
+          b.Show();
+        }
+        this._Reset();
+      }
+    }
+  }
+
+  class TerrainChunkManager {
+    constructor(params) {
+      this._Init(params);
+    }
+
+    _Init(params) {
+      this._params = params;
+
+      const loader = new THREE.TextureLoader();
+
+      const noiseTexture = loader.load('./resources/simplex-noise.png');
+      noiseTexture.wrapS = THREE.RepeatWrapping;
+      noiseTexture.wrapT = THREE.RepeatWrapping;
+
+      const diffuse = new textures.TextureAtlas(params);
+      diffuse.Load('diffuse', [
+        './resources/dirt_01_diffuse-1024.png',
+        './resources/grass1-albedo3-1024.png',
+        './resources/sandyground-albedo-1024.png',
+        './resources/worn-bumpy-rock-albedo-1024.png',
+        './resources/rock-snow-ice-albedo-1024.png',
+        './resources/snow-packed-albedo-1024.png',
+        './resources/rough-wet-cobble-albedo-1024.png',
+        './resources/sandy-rocks1-albedo-1024.png',
+      ]);
+      diffuse.onLoad = () => {     
+        this._material.uniforms.diffuseMap.value = diffuse.Info['diffuse'].atlas;
+      };
+
+      const normal = new textures.TextureAtlas(params);
+      normal.Load('normal', [
+        './resources/dirt_01_normal-1024.jpg',
+        './resources/grass1-normal-1024.jpg',
+        './resources/sandyground-normal-1024.jpg',
+        './resources/worn-bumpy-rock-normal-1024.jpg',
+        './resources/rock-snow-ice-normal-1024.jpg',
+        './resources/snow-packed-normal-1024.jpg',
+        './resources/rough-wet-cobble-normal-1024.jpg',
+        './resources/sandy-rocks1-normal-1024.jpg',
+      ]);
+      normal.onLoad = () => {     
+        this._material.uniforms.normalMap.value = normal.Info['normal'].atlas;
+      };
+
+      this._material = new THREE.MeshStandardMaterial({
+        wireframe: false,
+        wireframeLinewidth: 1,
+        color: 0xFFFFFF,
+        side: THREE.FrontSide,
+        vertexColors: THREE.VertexColors,
+        // normalMap: texture,
+      });
+
+      this._material = new THREE.RawShaderMaterial({
+        uniforms: {
+          diffuseMap: {
+          },
+          normalMap: {
+          },
+          noiseMap: {
+            value: noiseTexture
+          },
+        },
+        vertexShader: terrain_shader.VS,
+        fragmentShader: terrain_shader.PS,
+        side: THREE.FrontSide
+      });
+
+      this._builder = new TerrainChunkRebuilder();
+
+      this._InitNoise(params);
+      this._InitBiomes(params);
+      this._InitTerrain(params);
+    }
+
+    _InitNoise(params) {
+      params.guiParams.noise = {
+        octaves: 10,
+        persistence: 0.5,
+        lacunarity: 1.6,
+        exponentiation: 7.5,
+        height: 900.0,
+        scale: 1800.0,
+        seed: 1
+      };
+
+      const onNoiseChanged = () => {
+        this._builder.Rebuild(this._chunks);
+      };
+
+      const noiseRollup = params.gui.addFolder('Terrain.Noise');
+      noiseRollup.add(params.guiParams.noise, "scale", 32.0, 4096.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.noise, "octaves", 1, 20, 1).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.noise, "persistence", 0.25, 1.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.noise, "lacunarity", 0.01, 4.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.noise, "exponentiation", 0.1, 10.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.noise, "height", 0, 20000).onChange(
+          onNoiseChanged);
+
+      this._noise = new noise.Noise(params.guiParams.noise);
+
+      params.guiParams.heightmap = {
+        height: 16,
+      };
+
+      const heightmapRollup = params.gui.addFolder('Terrain.Heightmap');
+      heightmapRollup.add(params.guiParams.heightmap, "height", 0, 128).onChange(
+          onNoiseChanged);
+    }
+
+    _InitBiomes(params) {
+      params.guiParams.biomes = {
+        octaves: 2,
+        persistence: 0.5,
+        lacunarity: 2.0,
+        scale: 2048.0,
+        noiseType: 'simplex',
+        seed: 2,
+        exponentiation: 1,
+        height: 1.0
+      };
+
+      const onNoiseChanged = () => {
+        this._builder.Rebuild(this._chunks);
+      };
+
+      const noiseRollup = params.gui.addFolder('Terrain.Biomes');
+      noiseRollup.add(params.guiParams.biomes, "scale", 64.0, 4096.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.biomes, "octaves", 1, 20, 1).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.biomes, "persistence", 0.01, 1.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.biomes, "lacunarity", 0.01, 4.0).onChange(
+          onNoiseChanged);
+      noiseRollup.add(params.guiParams.biomes, "exponentiation", 0.1, 10.0).onChange(
+          onNoiseChanged);
+
+      this._biomes = new noise.Noise(params.guiParams.biomes);
+
+      const colourParams = {
+        octaves: 1,
+        persistence: 0.5,
+        lacunarity: 2.0,
+        exponentiation: 1.0,
+        scale: 256.0,
+        noiseType: 'simplex',
+        seed: 2,
+        height: 1.0,
+      };
+      this._colourNoise = new noise.Noise(colourParams);
+    }
+
+    _InitTerrain(params) {
+      params.guiParams.terrain= {
+        wireframe: false,
+      };
+
+      this._groups = [...new Array(6)].map(_ => new THREE.Group());
+      params.scene.add(...this._groups);
+
+      const terrainRollup = params.gui.addFolder('Terrain');
+      terrainRollup.add(params.guiParams.terrain, "wireframe").onChange(() => {
+        for (let k in this._chunks) {
+          this._chunks[k].chunk._plane.material.wireframe = params.guiParams.terrain.wireframe;
+        }
+      });
+
+      this._chunks = {};
+      this._params = params;
+    }
+
+    _CellIndex(p) {
+      const xp = p.x + _MIN_CELL_SIZE * 0.5;
+      const yp = p.z + _MIN_CELL_SIZE * 0.5;
+      const x = Math.floor(xp / _MIN_CELL_SIZE);
+      const z = Math.floor(yp / _MIN_CELL_SIZE);
+      return [x, z];
+    }
+
+    _CreateTerrainChunk(group, offset, width, resolution) {
+      const params = {
+        group: group,
+        material: this._material,
+        width: width,
+        offset: offset,
+        radius: _PLANET_RADIUS,
+        resolution: resolution,
+        biomeGenerator: this._biomes,
+        colourGenerator: new TextureSplatter({biomeGenerator: this._biomes, colourNoise: this._colourNoise}),
+        heightGenerators: [new HeightGenerator(this._noise, offset, 100000, 100000 + 1)],
+      };
+
+      return this._builder.AllocateChunk(params);
+    }
+
+    Update(_) {
+      this._builder.Update();
+      if (!this._builder.Busy) {
+        this._UpdateVisibleChunks_Quadtree();
+      }
+    }
+
+    _UpdateVisibleChunks_Quadtree() {
+      function _Key(c) {
+        return c.position[0] + '/' + c.position[1] + ' [' + c.size + ']' + ' [' + c.index + ']';
+      }
+
+      const q = new quadtree.CubeQuadTree({
+        radius: _PLANET_RADIUS,
+        min_node_size: _MIN_CELL_SIZE,
+      });
+      q.Insert(this._params.camera.position);
+
+      const sides = q.GetChildren();
+
+      let newTerrainChunks = {};
+      const center = new THREE.Vector3();
+      const dimensions = new THREE.Vector3();
+      for (let i = 0; i < sides.length; i++) {
+        this._groups[i].matrix = sides[i].transform;
+        this._groups[i].matrixAutoUpdate = false;
+        for (let c of sides[i].children) {
+          c.bounds.getCenter(center);
+          c.bounds.getSize(dimensions);
+  
+          const child = {
+            index: i,
+            group: this._groups[i],
+            position: [center.x, center.y, center.z],
+            bounds: c.bounds,
+            size: dimensions.x,
+          };
+  
+          const k = _Key(child);
+          newTerrainChunks[k] = child;
+        }
+      }
+
+      const intersection = utils.DictIntersection(this._chunks, newTerrainChunks);
+      const difference = utils.DictDifference(newTerrainChunks, this._chunks);
+      const recycle = Object.values(utils.DictDifference(this._chunks, newTerrainChunks));
+
+      this._builder._old.push(...recycle);
+
+      newTerrainChunks = intersection;
+
+      for (let k in difference) {
+        const [xp, yp, zp] = difference[k].position;
+
+        const offset = new THREE.Vector3(xp, yp, zp);
+        newTerrainChunks[k] = {
+          position: [xp, zp],
+          chunk: this._CreateTerrainChunk(
+              difference[k].group, offset, difference[k].size, _MIN_CELL_RESOLUTION),
+        };
+      }
+
+      this._chunks = newTerrainChunks;
+    }
+  }
+
+  return {
+    TerrainChunkManager: TerrainChunkManager
+  }
+})();

+ 84 - 0
src/textures.js

@@ -0,0 +1,84 @@
+import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+
+
+export const textures = (function() {
+
+  // Taken from https://github.com/mrdoob/three.js/issues/758
+  function _GetImageData( image ) {
+    var canvas = document.createElement('canvas');
+    canvas.width = image.width;
+    canvas.height = image.height;
+
+    var context = canvas.getContext('2d');
+    context.drawImage( image, 0, 0 );
+
+    return context.getImageData( 0, 0, image.width, image.height );
+  }
+
+  return {
+    TextureAtlas: class {
+      constructor(params) {
+        this._game = params.game;
+        this._Create();
+        this.onLoad = () => {};
+      }
+
+      Load(atlas, names) {
+        this._LoadAtlas(atlas, names);
+      }
+
+      _Create() {
+        this._manager = new THREE.LoadingManager();
+        this._loader = new THREE.TextureLoader(this._manager);
+        this._textures = {};
+
+        this._manager.onLoad = () => {
+          this._OnLoad();
+        };
+      }
+
+      get Info() {
+        return this._textures;
+      }
+
+      _OnLoad() {
+        for (let k in this._textures) {
+          const atlas = this._textures[k];
+          const data = new Uint8Array(atlas.textures.length * 4 * 1024 * 1024);
+
+          for (let t = 0; t < atlas.textures.length; t++) {
+            const curTexture = atlas.textures[t];
+            const curData = _GetImageData(curTexture.image);
+            const offset = t * (4 * 1024 * 1024);
+
+            data.set(curData.data, offset);
+          }
+    
+          const diffuse = new THREE.DataTexture2DArray(data, 1024, 1024, atlas.textures.length);
+          diffuse.format = THREE.RGBAFormat;
+          diffuse.type = THREE.UnsignedByteType;
+          diffuse.minFilter = THREE.LinearMipMapLinearFilter;
+          diffuse.magFilter = THREE.NearestFilter;
+          diffuse.wrapS = THREE.RepeatWrapping;
+          diffuse.wrapT = THREE.RepeatWrapping;
+          diffuse.generateMipmaps = true;
+
+          const caps = this._game._graphics._threejs.capabilities;
+          const aniso = caps.getMaxAnisotropy();
+
+          diffuse.anisotropy = 4;
+
+          atlas.atlas = diffuse;
+        }
+
+        this.onLoad();
+      }
+
+      _LoadAtlas(atlas, names) {
+        this._textures[atlas] = {
+          textures: names.map(n => this._loader.load(n))
+        };
+      }
+    }
+  };
+})();

+ 21 - 0
src/utils.js

@@ -0,0 +1,21 @@
+export const utils = (function() {
+  return {
+    DictIntersection: function(dictA, dictB) {
+      const intersection = {};
+      for (let k in dictB) {
+        if (k in dictA) {
+          intersection[k] = dictA[k];
+        }
+      }
+      return intersection
+    },
+
+    DictDifference: function(dictA, dictB) {
+      const diff = {...dictA};
+      for (let k in dictB) {
+        delete diff[k];
+      }
+      return diff;
+    }
+  };
+})();