roamwright 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +53 -24
  3. package/examples/viaduct-camera.js +40 -0
  4. package/examples/viaduct-landscape.js +81 -0
  5. package/examples/viaduct.css +75 -0
  6. package/examples/viaduct.html +47 -0
  7. package/examples/viaduct.js +332 -0
  8. package/geometry/creased-sheet.js +127 -0
  9. package/geometry/ear.js +97 -0
  10. package/geometry/erosion.js +106 -0
  11. package/geometry/face-grid.js +143 -0
  12. package/geometry/garment-tags.js +11 -0
  13. package/geometry/hair-gathers.js +174 -0
  14. package/geometry/hair-locks.js +156 -0
  15. package/geometry/hair-patch.js +42 -0
  16. package/geometry/hair-shell.js +186 -0
  17. package/geometry/hair-tags.js +6 -0
  18. package/geometry/head-profile.js +138 -0
  19. package/geometry/head-shape.js +499 -0
  20. package/geometry/heightfield.js +68 -0
  21. package/geometry/outline-grid.js +46 -0
  22. package/geometry/path-field.js +65 -0
  23. package/geometry/sagging-tube.js +58 -0
  24. package/geometry/sampled-surface.js +101 -0
  25. package/geometry/scatter-grid.js +32 -0
  26. package/geometry/sculpt.js +263 -0
  27. package/geometry/shore-grid.js +67 -0
  28. package/geometry/strata-field.js +339 -0
  29. package/geometry/strata-tiles.js +215 -0
  30. package/geometry/stream.js +94 -0
  31. package/geometry/terrain-chunks.js +300 -0
  32. package/geometry/terrain-extension.js +44 -0
  33. package/math/cell-edge.js +44 -0
  34. package/math/cloth-textures.js +83 -0
  35. package/math/cloud-textures.js +112 -0
  36. package/math/color.js +29 -0
  37. package/math/mountain-ranges.js +463 -0
  38. package/math/particle-noise.js +48 -0
  39. package/math/periodic.js +20 -0
  40. package/math/rock-texture.js +56 -0
  41. package/math/surface-textures.js +241 -0
  42. package/motion/arm-reach.js +74 -0
  43. package/motion/biped-stride.js +276 -0
  44. package/motion/crowd-alarms.js +127 -0
  45. package/motion/crowd-routine.js +183 -0
  46. package/motion/daily-clock.js +59 -0
  47. package/motion/instance-sight.js +84 -0
  48. package/motion/quadruped.js +332 -0
  49. package/motion/weather.js +59 -0
  50. package/motion/wind.js +27 -0
  51. package/package.json +6 -4
  52. package/rendering/caster-motion.js +79 -0
  53. package/rendering/cell-lod.js +175 -0
  54. package/rendering/cloud-dome.js +371 -0
  55. package/rendering/cloud-field.js +83 -0
  56. package/rendering/compilation-schedule.js +34 -0
  57. package/rendering/contact-shadows.js +79 -0
  58. package/rendering/crowd-skinning.js +133 -0
  59. package/rendering/crust.js +28 -0
  60. package/rendering/daylight.js +50 -0
  61. package/rendering/far-shadow.js +186 -0
  62. package/rendering/flocks.js +323 -0
  63. package/rendering/garment-material.js +110 -0
  64. package/rendering/glow-lines.js +74 -0
  65. package/rendering/glow-shell.js +90 -0
  66. package/rendering/hair-strands.js +67 -0
  67. package/rendering/height-haze.js +129 -0
  68. package/rendering/height-probe.js +91 -0
  69. package/rendering/interior-mapping.js +19 -0
  70. package/rendering/light-budget.js +222 -0
  71. package/rendering/light-points.js +51 -0
  72. package/rendering/light-shafts.js +131 -0
  73. package/rendering/local-lights.js +28 -0
  74. package/rendering/low-light.js +13 -0
  75. package/rendering/material-lod.js +110 -0
  76. package/rendering/particle-emitters.js +223 -0
  77. package/rendering/particles.js +297 -0
  78. package/rendering/planar-reflection.js +175 -0
  79. package/rendering/post-shaders.js +21 -1
  80. package/rendering/post.js +4 -0
  81. package/rendering/rain-rings.js +22 -0
  82. package/rendering/road-surface.js +63 -0
  83. package/rendering/sea-shaders.js +230 -0
  84. package/rendering/shader-warmup.js +197 -0
  85. package/rendering/shadow-alignment.js +28 -0
  86. package/rendering/shadow-depth.js +129 -0
  87. package/rendering/sky-occlusion.js +187 -0
  88. package/rendering/sky.js +169 -0
  89. package/rendering/stage-lights.js +209 -0
  90. package/rendering/static-point-shadow.js +119 -0
  91. package/rendering/strata-material.js +93 -0
  92. package/rendering/stream-flow.js +36 -0
  93. package/rendering/surface-light.js +22 -0
  94. package/rendering/surface-projection.js +69 -0
  95. package/rendering/talus.js +26 -0
  96. package/rendering/terrain-rock.js +48 -0
  97. package/rendering/texture-fills.js +68 -0
  98. package/rendering/viewport.js +9 -0
  99. package/rendering/wakes.js +99 -0
  100. package/rendering/water-material.js +288 -0
  101. package/runtime/device-quality.js +27 -0
  102. package/runtime/diagnostic-log.js +80 -0
  103. package/runtime/events.js +14 -0
  104. package/runtime/first-use.js +3 -1
  105. package/runtime/frame-yield.js +14 -0
  106. package/runtime/grid-cache.js +88 -0
  107. package/runtime/grid-rows.js +9 -0
  108. package/runtime/module-preload.js +15 -0
  109. package/runtime/search.js +69 -0
  110. package/runtime/spatial-audio.js +57 -0
  111. package/scripts/serve.py +26 -0
@@ -0,0 +1,175 @@
1
+ import * as THREE from 'three';
2
+
3
+ /**
4
+ * Level of detail for scattered things laid out in cells (trees, scrub, rocks, reeds). Each cell has a detailed instanced mesh for
5
+ * near and, most of them, a low-detail instanced copy for far. Hundreds of far cells hold a handful of instances each, and each would
6
+ * be a draw call in every pass, so the far copies are batched: one instanced mesh per kind and square of ground. In a batch every
7
+ * instance knows its cell and its place in it, and the vertex shader hides it unless its cell shows its far copy and it is among the
8
+ * cell's first `count` (the far thinning), read from a small table written each frame. What is drawn is exactly what the cells drew
9
+ * one by one, and a batch none of whose cells shows is hidden, so no pass runs its vertices only to drop them.
10
+ *
11
+ * A cell is a record: `mesh` (its near InstancedMesh), `lo` (its far InstancedMesh, or none), `cx`, `cz`, `r` (where it lies and its
12
+ * radius, metres), optionally `until` (metres past which it is not drawn at all), `near` (metres past which it shows its far copy
13
+ * sooner than the caller's), `full` (its instances before thinning). The batching writes `far`, `farN`, `farBatch` and `lod` on it.
14
+ *
15
+ * @param {object} [options]
16
+ * @param {number} [options.square=500] Metres: far copies are batched by kind within squares of this side.
17
+ * @param {number} [options.tableWidth=64] Texels across the table of what each cell shows.
18
+ * @param {number} [options.thinFrom=0.45] Beyond this share of the drawing distance a thinned cell keeps `thinTo` of its instances.
19
+ * @param {number} [options.thinTo=0.55]
20
+ */
21
+ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45, thinTo = 0.55 } = {}) {
22
+ const table = { data: null, tex: null },
23
+ shown = { value: null }, // the table, as the uniform the far materials and the far shadow body share
24
+ batches = [];
25
+ let batchShows = null,
26
+ depth = null;
27
+
28
+ // Hides, in the vertex shader, a copy whose cell is not showing its far copy or that lies past the cell's `count`.
29
+ function hideUnshown(sh) {
30
+ sh.uniforms.uFarShown = shown;
31
+ sh.vertexShader = sh.vertexShader
32
+ .replace('#include <common>', '#include <common>\nattribute vec2 aFar; uniform sampler2D uFarShown;')
33
+ .replace(
34
+ '#include <project_vertex>',
35
+ `/* glsl */
36
+ #include <project_vertex>
37
+ if (aFar.y >= texelFetch(uFarShown, ivec2(int(aFar.x) % ${tableWidth}, int(aFar.x) / ${tableWidth}), 0).r) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
38
+ );
39
+ }
40
+ // A far copy's material: the cell's own, cloned once per material, with its own patch kept and the hiding added.
41
+ function farMaterial(base, cache) {
42
+ if (cache.has(base)) return cache.get(base);
43
+ const m = base.clone(),
44
+ inner = base.onBeforeCompile,
45
+ key = base.customProgramCacheKey();
46
+ m.onBeforeCompile = (sh, r) => {
47
+ inner.call(base, sh, r);
48
+ hideUnshown(sh);
49
+ };
50
+ m.customProgramCacheKey = () => key + ':far-batch';
51
+ cache.set(base, m);
52
+ return m;
53
+ }
54
+ // The shadow body of far copies that cast: the far shape itself, hidden as in the picture, so a cell casts what it shows.
55
+ function depthMaterial() {
56
+ if (depth) return depth;
57
+ depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });
58
+ depth.onBeforeCompile = hideUnshown;
59
+ depth.customProgramCacheKey = () => 'far-batch-depth';
60
+ return depth;
61
+ }
62
+
63
+ /** Batches the far copies of `cells` (taken out of their parents) into `parent`; returns the batches. */
64
+ function batch(cellList, parent) {
65
+ const cells = cellList.filter(t => t.lo && t.lo.isInstancedMesh),
66
+ groups = new Map(),
67
+ materials = new Map();
68
+ table.data = new Float32Array(tableWidth * Math.ceil(cells.length / tableWidth));
69
+ table.tex = new THREE.DataTexture(table.data, tableWidth, table.data.length / tableWidth, THREE.RedFormat, THREE.FloatType);
70
+ table.tex.needsUpdate = true;
71
+ shown.value = table.tex;
72
+ cells.forEach((t, slot) => {
73
+ const lo = t.lo,
74
+ key = [
75
+ lo.geometry.uuid,
76
+ lo.material.uuid,
77
+ lo.layers.mask,
78
+ lo.receiveShadow,
79
+ t.mesh.castShadow,
80
+ Math.floor(t.cx / square),
81
+ Math.floor(t.cz / square),
82
+ ].join('|');
83
+ let g = groups.get(key);
84
+ if (!g) groups.set(key, (g = { lo, casts: t.mesh.castShadow, cells: [] }));
85
+ g.cells.push(t);
86
+ t.far = slot;
87
+ t.farN = lo.instanceMatrix.count;
88
+ t.lo = null;
89
+ lo.removeFromParent();
90
+ });
91
+ for (const { lo, casts, cells: list } of groups.values()) {
92
+ for (const t of list) t.farBatch = batches.length;
93
+ const n = list.reduce((s, t) => s + t.farN, 0),
94
+ geo = new THREE.BufferGeometry();
95
+ for (const name in lo.geometry.attributes) geo.setAttribute(name, lo.geometry.attributes[name]);
96
+ geo.setIndex(lo.geometry.index);
97
+ geo.boundingSphere = lo.geometry.boundingSphere;
98
+ geo.boundingBox = lo.geometry.boundingBox;
99
+ const ids = new Float32Array(n * 2),
100
+ mesh = new THREE.InstancedMesh(geo, farMaterial(lo.material, materials), n);
101
+ if (lo.instanceColor) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3);
102
+ let at = 0;
103
+ for (const t of list) {
104
+ const src = t.mesh.instanceMatrix.array,
105
+ col = t.mesh.instanceColor?.array;
106
+ mesh.instanceMatrix.array.set(src.subarray(0, t.farN * 16), at * 16);
107
+ if (col && mesh.instanceColor) mesh.instanceColor.array.set(col.subarray(0, t.farN * 3), at * 3);
108
+ for (let i = 0; i < t.farN; i++) {
109
+ ids[(at + i) * 2] = t.far;
110
+ ids[(at + i) * 2 + 1] = i;
111
+ }
112
+ at += t.farN;
113
+ }
114
+ geo.setAttribute('aFar', new THREE.InstancedBufferAttribute(ids, 2));
115
+ mesh.layers.mask = lo.layers.mask;
116
+ mesh.receiveShadow = lo.receiveShadow;
117
+ mesh.castShadow = casts; // as the near copies do
118
+ if (casts) {
119
+ mesh.customDepthMaterial = depthMaterial();
120
+ mesh.userData.partShown = true; // a pass drawing heights with a plain depth material would show every copy
121
+ }
122
+ mesh.matrixAutoUpdate = false;
123
+ mesh.computeBoundingSphere();
124
+ parent.add(mesh);
125
+ batches.push(mesh);
126
+ }
127
+ batchShows = new Int32Array(batches.length);
128
+ return batches;
129
+ }
130
+
131
+ // Where a cell lies and how far it is drawn, kept on it in a record of one shape: cells come from builders of many shapes,
132
+ // and a number read from objects of so many shapes is made anew at every read. A cell does not move.
133
+ const lodOf = t =>
134
+ (t.lod ??= { cx: t.cx, cz: t.cz, r: t.r, until: t.until ?? Infinity, near: t.near ?? Infinity, batch: t.farBatch ?? -1 });
135
+
136
+ /**
137
+ * Each frame: near cells show their detailed mesh, far ones their batched copy, thinned beyond `thinFrom` of the drawing
138
+ * distance. (cx, cz): the eye; `distance` metres past which nothing is drawn, `detail` metres within which the near mesh is,
139
+ * `density` the share of a thinned cell's instances kept.
140
+ */
141
+ function update(cells, cx, cz, distance, detail, density) {
142
+ let changed = false;
143
+ if (batchShows) batchShows.fill(0);
144
+ for (let i = 0; i < cells.length; i++) {
145
+ const t = cells[i],
146
+ at = lodOf(t),
147
+ dx = cx - at.cx,
148
+ dz = cz - at.cz,
149
+ d = Math.sqrt(dx * dx + dz * dz) - at.r,
150
+ hasFar = t.lo || t.far !== undefined;
151
+ const vis = d < Math.min(distance, at.until),
152
+ hi = !hasFar || d < Math.min(detail, at.near);
153
+ t.mesh.visible = vis && hi;
154
+ if (t.lo) t.lo.visible = vis && !hi;
155
+ let count = t.farN;
156
+ if (t.full !== undefined) {
157
+ count = Math.max(1, (t.full * (d < distance * thinFrom ? 1 : thinTo) * density) | 0);
158
+ t.mesh.count = count;
159
+ if (t.lo) t.lo.count = count;
160
+ }
161
+ if (t.far !== undefined) {
162
+ const v = vis && !hi ? count : 0;
163
+ if (v > 0) batchShows[at.batch]++;
164
+ if (table.data[t.far] !== v) {
165
+ table.data[t.far] = v;
166
+ changed = true;
167
+ }
168
+ }
169
+ }
170
+ if (changed) table.tex.needsUpdate = true;
171
+ for (let i = 0; i < batches.length; i++) batches[i].visible = batchShows[i] > 0;
172
+ }
173
+
174
+ return { batch, update, batches };
175
+ }
@@ -0,0 +1,371 @@
1
+ import * as THREE from 'three';
2
+ import { QUAD_VS } from './post-shaders.js';
3
+
4
+ export function createCloudDome({ renderer, field, warmProgram }) {
5
+ const {
6
+ fieldGLSL: CLOUD_FIELD_PARS,
7
+ dip: DIP,
8
+ projection: FLARE,
9
+ fadeStart: LOWEST,
10
+ span: SPAN,
11
+ thickness: THICK,
12
+ billows: cloudBillows,
13
+ uniforms: cloudU,
14
+ overhead,
15
+ sheetSpan: CLOUD_SHEET,
16
+ } = field;
17
+ const RIM = 1.02, // the map's rim, where the horizon lies at 1: a little below the horizon is drawn too
18
+ DEPTH = FLARE * THICK, // the layer's depth in the field's units
19
+ SEEN_AT = FLARE * (1 + 0.3 * THICK), // the height in the layer, in the field's units, at which a map is moved to follow the viewer
20
+ BLOCKS = 12 / CLOUD_SHEET, // blocks of billows to a unit of the field: a whole number to the sheet, so the two repeat together
21
+ TEXELS = field.textureSize / CLOUD_SHEET, // the sheet's texels to a unit of the field
22
+ FADE = 0.14, // seconds a finished map takes to fade in
23
+ RISE = 0.0018, // blocks a second the billows rise through the clouds (about 3 m/s), and
24
+ SIDLE = 0.0006, // drift against them
25
+ JUMP = 0.6, // the viewer carried further than this in one frame (the field's units) is a cut: the clouds are drawn whole at once
26
+ TURNED = 0.96, // and so is a light that turned by more than this cosine,
27
+ CHANGED = 0.1; // or a sky whose threshold moved by more
28
+ const f = (v, digits = 4) => v.toFixed(digits);
29
+
30
+ const DOME_FS = `/* glsl */
31
+ precision highp float; precision highp sampler3D;
32
+ uniform sampler3D uBillows;
33
+ uniform vec2 uAt; // the sheet over the viewer
34
+ uniform vec3 uLight; // towards the light
35
+ uniform vec3 uChurn; // how far the billows have risen and drifted, in blocks
36
+ uniform float uCloud; // the field's value where cloud begins
37
+ ${CLOUD_FIELD_PARS}
38
+ varying vec2 vUv;
39
+ const float SIGMA = 32.0; // how much light a unit of the field's length of full cloud takes, as an optical depth
40
+ const float SOFT = 0.022; // how far into a cloud's body (in the field's value) its edge thickens to full cloud
41
+ const float BASE_SOFT = 0.05; // and how far up from its flat base, as a share of the layer
42
+ const float BASE_HOLLOW = 0.07, BASE_HOLLOW_CLOSED = 0.2; // how far up the hollows of a cloud's base reach, as a share of the layer: under a fair sky, and that much more under a closed one
43
+ const float ERODE = 0.12; // how far the creases between billows eat into the body, and
44
+ const float FINER = 0.42; // the finer ones, as a share of that
45
+ // Where a point lies in the block of billows: p from the viewer in the field's units, h its height in the layer.
46
+ vec3 inBlock(vec2 p, float h) { return vec3(uAt * ${f(CLOUD_SHEET, 1)} + p, h * ${f(DEPTH)}).xzy * ${f(BLOCKS)}; }
47
+ // How far inside a cloud's body a point lies, in the field's value: 0 at its edge, SOFT and more in full cloud, below 0 in
48
+ // clear air. p: from the viewer in the field's units; h: its height in the layer (0 the base, 1 the top). over: how far the
49
+ // field stands over the threshold there; base: what the cloud's underside leaves of it there (0 below it, 1 well above);
50
+ // rough: how far the billows eat into it there.
51
+ float bodyAt(vec2 p, float h, float lod, out float over, out float base, out float rough) {
52
+ vec4 texel = textureLod(uCloudField, uAt + p * ${f(1 / CLOUD_SHEET, 6)}, lod);
53
+ over = cloudField(texel) - uCloud;
54
+ float h2 = h * h, body = over - ${f(SPAN)} * h2 * h2;
55
+ rough = ERODE * (0.45 + 0.55 * smoothstep(0.0, 0.3, h)); // a cloud's base is smoother than its sides and top
56
+ // the base is level but for shallow hollows between hanging bulges (the sheet's finer lumps), deeper under a closed sky
57
+ base = smoothstep(0.0, BASE_SOFT, h - (BASE_HOLLOW + BASE_HOLLOW_CLOSED * smoothstep(0.25, 0.6, over)) * (1.0 - texel.g));
58
+ if (body <= 0.0 || base <= 0.0) return min(body, 0.0) - rough * 0.55; // clear air: as far out as the billows are eaten back on the whole
59
+ return body - rough * (1.0 - dot(textureLod(uBillows, inBlock(p, h) + uChurn, lod).rgb, vec3(0.38, 0.38, 0.24)));
60
+ }
61
+ // The share of a stretch that is cloud when its two ends lie a and b inside the body, the body taken to change evenly between
62
+ // them: a cloud's edge is found where it lies between two steps, not at the nearer step (which drew it in terraces).
63
+ float filled(float a, float b) {
64
+ vec2 e = max(vec2(a, b), 0.0), sum = mix(e * e * ${f(0.5)} / SOFT, e - 0.5 * SOFT, step(SOFT, e));
65
+ return abs(b - a) > 1e-4 ? clamp((sum.y - sum.x) / (b - a), 0.0, 1.0) : clamp(a / SOFT, 0.0, 1.0);
66
+ }
67
+ void main() {
68
+ vec2 r = (vUv - 0.5) * ${f(2 * RIM)};
69
+ float r2 = dot(r, r);
70
+ if (r2 >= ${f(RIM * RIM)}) { gl_FragColor = vec4(0.0); return; }
71
+ float up = (1.0 - r2) / (1.0 + r2); // the direction's height: 1 overhead, 0 at the horizon
72
+ if (up < ${f(LOWEST - 0.012)}) { gl_FragColor = vec4(0.0); return; } // no cloud is drawn that low in the sky (cloud-field.js)
73
+ vec2 q = r * (1.0 + up) / (max(up, 0.0) + ${f(DIP)}); // how far the ray runs level for each unit it climbs
74
+ float reach = length(q), slope = sqrt(1.0 + reach * reach);
75
+ int steps = int(min(float(STEPS) + 9.0 * reach, float(MAX_STEPS))); // a ray near the horizon runs long through the layer
76
+ float dh = 1.0 / float(steps);
77
+ // the sheet's level of detail: a step is not finer than the way it travels, or a far cloud showed as a stack of slivers
78
+ float lod = clamp(log2(max(reach * dh * ${f(DEPTH * TEXELS)}, 0.01)) - 0.5, 0.0, 3.0);
79
+ float finer = FINER * (1.0 - lod / 1.5); // the finer billows fade out where a step is too long to show them
80
+ // each ray's steps stand a little higher or lower than its neighbours', so what is left of the layer's levels in a cloud's
81
+ // shading does not run on as lines
82
+ float shift = 0.33 + 0.34 * fract(52.9829189 * fract(dot(gl_FragCoord.yx, vec2(0.06711056, 0.00583715))));
83
+ float seen = 1.0, was = -1.0, wasFine = -1.0, over, base, rough, none;
84
+ vec3 sum = vec3(0.0);
85
+ for (int i = 0; i < MAX_STEPS; i++) {
86
+ if (i >= steps) break;
87
+ float h = (float(i) + shift) * dh;
88
+ vec2 p = q * (${f(FLARE)} * (1.0 + h * ${f(THICK)}));
89
+ float body = bodyAt(p, h, lod, over, base, rough), cloud;
90
+ #if FINE
91
+ if (finer > 0.0 && max(was, body) > 0.0) {
92
+ // the stretch since the last step in three parts, the finer billows read in each: they are smaller than a step
93
+ cloud = 0.0;
94
+ for (int k = 1; k <= 3; k++) {
95
+ float t = float(k) / 3.0, hk = h - (1.0 - t) * dh, part = mix(was, body, t);
96
+ if (part > 0.0) {
97
+ vec3 small = textureLod(uBillows, inBlock(q * (${f(FLARE)} * (1.0 + hk * ${f(THICK)})), hk) * 4.0 + uChurn.zxy * 3.0, lod).rgb;
98
+ part -= rough * finer * (1.0 - dot(small, vec3(0.5, 0.3, 0.2)));
99
+ }
100
+ cloud += filled(wasFine, part);
101
+ wasFine = part;
102
+ }
103
+ cloud *= base / 3.0;
104
+ } else
105
+ #endif
106
+ {
107
+ cloud = filled(was, body) * base;
108
+ wasFine = body;
109
+ }
110
+ // the light is found at the middle of the part of the stretch that is cloud, not at the step: a cloud's face lit at the
111
+ // steps' own levels, a little inside it or far, showed those levels as lines in its shading
112
+ float enters = was < 0.0 && body > 0.0 ? was / (was - body) : 0.0, leaves = was > 0.0 && body < 0.0 ? was / (was - body) : 1.0;
113
+ float lit = h - (1.0 - 0.5 * (enters + leaves)) * dh;
114
+ was = body;
115
+ if (cloud < 0.003) continue;
116
+ // the cloud between this point and the light, in steps that lengthen
117
+ float between = 0.0, gone = 0.0, span = float(L_FIRST);
118
+ vec2 from = q * (${f(FLARE)} * (1.0 + lit * ${f(THICK)}));
119
+ for (int j = 0; j < LIGHT_STEPS; j++) {
120
+ float l = gone + 0.5 * span, hl = lit + uLight.y * l * ${f(1 / DEPTH)};
121
+ if (hl <= 0.0 || hl >= 1.0) break;
122
+ between += clamp(bodyAt(from + uLight.xz * l, hl, max(lod, 0.5) + 0.5 * float(j), none, base, rough) / SOFT, 0.0, 1.0) * base * span;
123
+ gone += span; span *= float(L_GROW);
124
+ }
125
+ between *= SIGMA;
126
+ float once = exp(-between); // light that comes straight through
127
+ float many = 0.7 * exp(-between * 0.3) + 0.3 * exp(-between * 0.1); // and light passed on from drop to drop, which reaches deeper
128
+ float top = sqrt(sqrt(clamp(over * ${f(1 / SPAN)}, 0.0, 1.0)));
129
+ // the sky's light: from above, less the deeper under the cloud's top, and a little from below on its base
130
+ float sky = 0.84 * exp(-3.0 * max(top - lit, 0.0)) * (0.5 + 0.5 * lit) + 0.16 * exp(-5.0 * lit);
131
+ float a = 1.0 - exp(-cloud * (SIGMA * ${f(DEPTH)}) * dh * slope);
132
+ sum += seen * a * vec3(many, once, sky);
133
+ seen *= 1.0 - a;
134
+ if (seen < 0.02) break;
135
+ }
136
+ // each is kept in a byte: a grain of half a step of it hides the steps between
137
+ float grain = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))) - 0.5;
138
+ gl_FragColor = vec4(sum, min((1.0 - seen) * ${f(1 / 0.98)}, 1.0)) + grain * ${f(1 / 255, 6)};
139
+ }`;
140
+
141
+ // For the sky's shader: declares cloudDome(d), the clouds' picture in a direction above the horizon (r, g, b, a as above).
142
+ const DOME_PARS = `/* glsl */
143
+ uniform sampler2D uDome, uDomeNext; uniform vec4 uDomeShift; uniform float uDomeMix;
144
+ // where a ray that runs q level for each unit it climbs lies in a map
145
+ vec2 domeUv(vec2 q) {
146
+ float Q = dot(q, q), up = (sqrt(1.0 + Q * ${f(1 - DIP * DIP, 6)}) - Q * ${f(DIP)}) / (1.0 + Q);
147
+ return 0.5 + q * ((up + ${f(DIP)}) / (1.0 + up) * ${f(0.5 / RIM, 6)});
148
+ }
149
+ vec4 cloudDome(vec3 d) {
150
+ vec2 q = d.xz / (max(d.y, 0.0) + ${f(DIP)});
151
+ vec4 c = textureLod(uDome, domeUv(q + uDomeShift.xy), 0.0);
152
+ if (uDomeMix > 0.0) c = mix(c, textureLod(uDomeNext, domeUv(q + uDomeShift.zw), 0.0), uDomeMix);
153
+ return c;
154
+ }`;
155
+ // What the sky's shader reads: the map on show, the one fading in over it and how far it has; xy and zw how far each is moved.
156
+ const domeU = {
157
+ uDome: { value: null },
158
+ uDomeNext: { value: null },
159
+ uDomeShift: { value: new THREE.Vector4() },
160
+ uDomeMix: { value: 0 },
161
+ };
162
+
163
+ const domeMat = new THREE.ShaderMaterial({
164
+ depthTest: false,
165
+ depthWrite: false,
166
+ uniforms: {
167
+ uCloudField: cloudU.uCloudField,
168
+ uBillows: cloudBillows,
169
+ uAt: { value: new THREE.Vector2() },
170
+ uLight: { value: new THREE.Vector3(0, 1, 0) },
171
+ uChurn: { value: new THREE.Vector3() },
172
+ uCloud: { value: 0.5 },
173
+ },
174
+ defines: { STEPS: 36, MAX_STEPS: 104, LIGHT_STEPS: 5, L_FIRST: '0.04', L_GROW: '1.7', FINE: 1 },
175
+ vertexShader: QUAD_VS,
176
+ fragmentShader: DOME_FS,
177
+ });
178
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), domeMat),
179
+ quadScene = new THREE.Scene().add(quad),
180
+ quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
181
+ quad.frustumCulled = false;
182
+
183
+ // The two maps: `shown` is whole and on show, `next` is being drawn (its bands below `band` are done) or fading in (`mix`).
184
+ // (x, z): where the field lay over the viewer when each was begun. `last`: what the frame before saw, to know a cut by.
185
+ const dome = {
186
+ level: null,
187
+ shown: null,
188
+ next: null,
189
+ shownAt: { x: 0, z: 0 },
190
+ nextAt: { x: 0, z: 0 },
191
+ bands: null, // the rows the map's bands begin at (equalBands)
192
+ band: 0,
193
+ fading: false,
194
+ mix: 0,
195
+ whole: false, // a whole map is on show
196
+ last: { x: 0, z: 0, threshold: 0, light: new THREE.Vector3(), space: null },
197
+ };
198
+ // The rows at which a map is cut into `bands` bands that hold equal shares of the dome's circle: a frame draws one, and so
199
+ // about as much sky as any other frame (a band of equal height at the map's middle held far more than one at its edge).
200
+ function equalBands(size, bands) {
201
+ const below = y => 0.5 + (y * Math.sqrt(1 - y * y) + Math.asin(y)) / Math.PI, // the share of a circle below y (-1 its foot, 1 its top)
202
+ rows = [0];
203
+ for (let k = 1; k < bands; k++) {
204
+ let low = -1,
205
+ high = 1;
206
+ for (let i = 0; i < 30; i++) {
207
+ const mid = (low + high) / 2;
208
+ if (below(mid) < k / bands) low = mid;
209
+ else high = mid;
210
+ }
211
+ rows.push(Math.round(((low + 1) / 2) * size));
212
+ }
213
+ rows.push(size);
214
+ return rows;
215
+ }
216
+ const makeMap = size => {
217
+ const map = new THREE.WebGLRenderTarget(size, size, {
218
+ depthBuffer: false,
219
+ minFilter: THREE.LinearFilter,
220
+ magFilter: THREE.LinearFilter,
221
+ });
222
+ map.scissorTest = true;
223
+ return map;
224
+ };
225
+ // Sets the preset's level of cloud detail (3, 4 or 5): the maps' size and the steps of their drawing.
226
+ let pending = Promise.resolve(),
227
+ disposed = false;
228
+ function setCloudDetail(level) {
229
+ if (disposed) throw new Error('Cloud dome has been disposed');
230
+ if (dome.level === level) return pending;
231
+ dome.level = level;
232
+ dome.bands = equalBands(level.size, level.frames);
233
+ if (!dome.shown || dome.shown.width !== level.size) {
234
+ dome.shown?.dispose();
235
+ dome.next?.dispose();
236
+ dome.shown = makeMap(level.size);
237
+ dome.next = makeMap(level.size);
238
+ }
239
+ dome.whole = false;
240
+ Object.assign(domeMat.defines, {
241
+ STEPS: level.steps,
242
+ MAX_STEPS: level.most,
243
+ LIGHT_STEPS: level.light,
244
+ L_FIRST: f(level.first),
245
+ L_GROW: f(level.grow),
246
+ FINE: level.fine,
247
+ });
248
+ domeMat.needsUpdate = true;
249
+ const previous = renderer.getRenderTarget();
250
+ const face = previous ? renderer.getActiveCubeFace() : 0;
251
+ const mip = previous ? renderer.getActiveMipmapLevel() : 0;
252
+ renderer.setRenderTarget(dome.shown);
253
+ // compiled on the driver's threads before the first map is drawn, and put to its first use as soon as it is: used at that first
254
+ // draw instead, it waited there behind every program begun since (30 to 50 ms of a later visit's "Setting the scenes")
255
+ try {
256
+ if (warmProgram) {
257
+ const compilation = renderer.compileAsync(quad, quadCam).then(() => (disposed ? undefined : warmProgram(domeMat)));
258
+ pending = Promise.all([pending, compilation]).then(() => undefined);
259
+ }
260
+ } finally {
261
+ renderer.setRenderTarget(previous, face, mip);
262
+ }
263
+ return pending;
264
+ }
265
+ const wrap = v => v - Math.floor(v);
266
+ // Begins a map: the clouds as they stand now, seen from where the viewer is, lit from `light`.
267
+ function begin(at, light, threshold, seconds) {
268
+ const u = domeMat.uniforms;
269
+ at.x = overhead.x;
270
+ at.z = overhead.z;
271
+ u.uAt.value.set(wrap(at.x / CLOUD_SHEET), wrap(at.z / CLOUD_SHEET));
272
+ u.uLight.value.copy(light);
273
+ u.uCloud.value = threshold;
274
+ u.uChurn.value.set(wrap(seconds * SIDLE), wrap(-seconds * RISE), wrap(seconds * -SIDLE * 0.7)); // read lower as time passes: the billows rise
275
+ }
276
+ // Draws `rows` rows of a map from `row` up, as the clouds stood when it was begun.
277
+ function draw(map, row, rows) {
278
+ const clears = renderer.autoClear;
279
+ const previous = renderer.getRenderTarget();
280
+ const face = previous ? renderer.getActiveCubeFace() : 0;
281
+ const mip = previous ? renderer.getActiveMipmapLevel() : 0;
282
+ map.scissor.set(0, row, map.width, rows);
283
+ renderer.autoClear = false;
284
+ renderer.setRenderTarget(map);
285
+ try {
286
+ renderer.render(quadScene, quadCam);
287
+ } finally {
288
+ renderer.setRenderTarget(previous, face, mip);
289
+ renderer.autoClear = clears;
290
+ }
291
+ }
292
+ // Each frame, after the field is placed: draws a little more of the next map of the clouds, or fades it in, and tells the
293
+ // sky where the maps lie. light: towards the sun or the moon, whichever lights the clouds; threshold: the field's value
294
+ // where cloud begins; seconds: the world's time; bright: how strong that light is now (a dark one may turn unseen, as when
295
+ // the moon takes over from the sun that has set).
296
+ function updateCloudDome(dt, light, threshold, seconds, bright, region) {
297
+ const { level, last } = dome,
298
+ sheet = cloudU.uCloudField.value,
299
+ billows = cloudBillows.value;
300
+ if (!level || !sheet?.version || !billows?.version) return; // no preset yet, or the workers have not filled the sheet and the block
301
+ const cut =
302
+ !dome.whole ||
303
+ last.space !== region ||
304
+ Math.hypot(overhead.x - last.x, overhead.z - last.z) > JUMP ||
305
+ Math.abs(threshold - last.threshold) > CHANGED ||
306
+ (light.dot(last.light) < TURNED && bright > 0.01);
307
+ last.space = region;
308
+ last.x = overhead.x;
309
+ last.z = overhead.z;
310
+ last.threshold = threshold;
311
+ last.light.copy(light);
312
+ if (cut) {
313
+ // nothing on show can be kept: the whole sky at once, and the next map begun from the same moment
314
+ begin(dome.shownAt, light, threshold, seconds);
315
+ draw(dome.shown, 0, level.size);
316
+ dome.nextAt.x = dome.shownAt.x;
317
+ dome.nextAt.z = dome.shownAt.z;
318
+ dome.whole = true;
319
+ dome.fading = false;
320
+ dome.band = 0;
321
+ dome.mix = 0;
322
+ } else if (dome.fading) {
323
+ dome.mix += dt / FADE;
324
+ if (dome.mix >= 1) {
325
+ const shown = dome.next,
326
+ at = dome.nextAt;
327
+ dome.next = dome.shown;
328
+ dome.nextAt = dome.shownAt;
329
+ dome.shown = shown;
330
+ dome.shownAt = at;
331
+ dome.fading = false;
332
+ dome.mix = 0;
333
+ }
334
+ } else {
335
+ if (dome.band === 0) begin(dome.nextAt, light, threshold, seconds);
336
+ const row = dome.bands[dome.band];
337
+ draw(dome.next, row, dome.bands[++dome.band] - row);
338
+ if (dome.band >= level.frames) {
339
+ dome.band = 0;
340
+ dome.fading = true;
341
+ }
342
+ }
343
+ domeU.uDome.value = dome.shown.texture;
344
+ domeU.uDomeNext.value = dome.next.texture;
345
+ domeU.uDomeMix.value = dome.fading ? dome.mix : 0;
346
+ domeU.uDomeShift.value.set(
347
+ (overhead.x - dome.shownAt.x) / SEEN_AT,
348
+ (overhead.z - dome.shownAt.z) / SEEN_AT,
349
+ (overhead.x - dome.nextAt.x) / SEEN_AT,
350
+ (overhead.z - dome.nextAt.z) / SEEN_AT,
351
+ );
352
+ }
353
+ return {
354
+ uniforms: domeU,
355
+ sampleGLSL: DOME_PARS,
356
+ setDetail: setCloudDetail,
357
+ update: updateCloudDome,
358
+ async dispose() {
359
+ if (disposed) return;
360
+ disposed = true;
361
+ try {
362
+ await pending;
363
+ } finally {
364
+ dome.shown?.dispose();
365
+ dome.next?.dispose();
366
+ quad.geometry.dispose();
367
+ domeMat.dispose();
368
+ }
369
+ },
370
+ };
371
+ }
@@ -0,0 +1,83 @@
1
+ import { Vector4 } from 'three';
2
+
3
+ export function createCloudField({
4
+ textureSize = 512,
5
+ height: CLOUD_HEIGHT = 1500,
6
+ projection: FLARE = 1.15,
7
+ horizonDip: DIP = 0.04,
8
+ fadeStart: LOWEST = 0.05,
9
+ fadeEnd: WHOLE = 0.14,
10
+ thickness: THICK = 0.75,
11
+ span: SPAN = 1.2,
12
+ sheetSpan: CLOUD_SHEET = 16,
13
+ windFactor: ALOFT = 4.5,
14
+ shadowHeight: SHADOW_AT = 0.15,
15
+ shadowThreshold: SHADOW_FROM = 0.02,
16
+ shadowEdge: SHADOW_EDGE = 0.05,
17
+ shadowStrength: SHADOW_DEPTH = 0.42,
18
+ } = {}) {
19
+ const FIELD_PER_METRE = FLARE / CLOUD_HEIGHT,
20
+ SHEET_PER_METRE = FIELD_PER_METRE / CLOUD_SHEET;
21
+ const cloudU = {
22
+ uCloudField: { value: null },
23
+ uCloudSh: { value: new Vector4(0, 0, 0.5, 0) },
24
+ };
25
+ // The block of billows the clouds' sides and tops are shaped by of the procedural volume texture.
26
+ const cloudBillows = { value: null };
27
+ // Where the field lies over the viewer, in its own units and not wrapped to the sheet: what the clouds' picture is taken from
28
+ // and moved by (the cloud dome).
29
+ const overhead = { x: 0, z: 0 };
30
+ // Declares the sheet and cloudField(texel): the field's value from a texel of it, its coarse part and its fine part
31
+ // added.
32
+ const CLOUD_FIELD_PARS = `/* glsl */
33
+ uniform sampler2D uCloudField;
34
+ float cloudField(vec4 texel) { return texel.r + (texel.a - 0.5) * ${(1 / 255).toFixed(8)}; }`;
35
+ // Declares cloudShade(xz): what is left of the light at a point of the land (1 in the open, less under a cloud).
36
+ const CLOUD_SHADE_PARS = `/* glsl */
37
+ ${CLOUD_FIELD_PARS}
38
+ uniform vec4 uCloudSh;
39
+ float cloudShade(vec2 xz) { return 1.0 - uCloudSh.w * smoothstep(uCloudSh.z, uCloudSh.z + ${SHADOW_EDGE}, cloudField(texture2D(uCloudField, xz * ${SHEET_PER_METRE.toExponential(6)} + uCloudSh.xy))); }`;
40
+ // The same for a material whose fragment shader has no texture unit to spare for the sheet and whose `map` is the ground's
41
+ // grain, which carries a copy of the field in its alpha. A macro, since Three
42
+ // declares `map` after the place this is spliced in.
43
+ const CLOUD_SHADE_FROM_GRAIN = `/* glsl */
44
+ uniform vec4 uCloudSh;
45
+ #define cloudShade(xz) (1.0 - uCloudSh.w * smoothstep(uCloudSh.z, uCloudSh.z + ${SHADOW_EDGE}, texture2D(map, (xz) * ${SHEET_PER_METRE.toExponential(6)} + uCloudSh.xy).a))`;
46
+
47
+ const wrap = v => v - Math.floor(v);
48
+ // Each frame: where the sheet lies. Over the viewer at (x, z) it is `overhead`; the shadows' place is the same drift moved by
49
+ // the light's slant (`light` points at the sun or moon). drift (a Vector2): how far the wind near the ground has carried the
50
+ // air, in metres; threshold: the field's value where cloud begins; shade: 0 to 1, how much of a shadow's full depth shows
51
+ // (none at night, under a closed sky, or indoors).
52
+ function placeCloudField(x, z, drift, light, threshold, shade) {
53
+ const driftX = drift.x * ALOFT * FIELD_PER_METRE,
54
+ driftZ = drift.y * ALOFT * FIELD_PER_METRE,
55
+ slant = (FLARE * (1 + SHADOW_AT * THICK)) / (Math.max(light.y, 0) + DIP),
56
+ sh = cloudU.uCloudSh.value;
57
+ overhead.x = x * FIELD_PER_METRE + driftX;
58
+ overhead.z = z * FIELD_PER_METRE + driftZ;
59
+ sh.set(
60
+ wrap((driftX + light.x * slant) / CLOUD_SHEET),
61
+ wrap((driftZ + light.z * slant) / CLOUD_SHEET),
62
+ threshold + SHADOW_FROM,
63
+ SHADOW_DEPTH * shade,
64
+ );
65
+ }
66
+ return {
67
+ textureSize,
68
+ projection: FLARE,
69
+ dip: DIP,
70
+ fadeStart: LOWEST,
71
+ fadeEnd: WHOLE,
72
+ thickness: THICK,
73
+ span: SPAN,
74
+ sheetSpan: CLOUD_SHEET,
75
+ fieldGLSL: CLOUD_FIELD_PARS,
76
+ shadowGLSL: CLOUD_SHADE_PARS,
77
+ packedShadowGLSL: CLOUD_SHADE_FROM_GRAIN,
78
+ uniforms: cloudU,
79
+ billows: cloudBillows,
80
+ overhead,
81
+ place: placeCloudField,
82
+ };
83
+ }
@@ -0,0 +1,34 @@
1
+ // Coordinate early, whole-scene and incremental program warmup. The application supplies its pass
2
+ // graph and decides how newly linked programs enter the renderer's first-use queue.
3
+ export function createCompilationSchedule({renderer, scene, beginCompiles, putToUse, useProgram, timeoutMs = 20000, onError = () => {}}) {
4
+ let warmed = false;
5
+ const programs = () => renderer.info.programs;
6
+ const addedSince = known => programs().filter(program => !known.has(program));
7
+ function beginWarm() {
8
+ if (warmed) return;
9
+ const known = new Set(programs());
10
+ try {
11
+ const done = beginCompiles(scene, warmed);
12
+ const added = addedSince(known);
13
+ return Promise.resolve(done).then(() => putToUse(added.filter(p => programs().includes(p)))).catch(onError);
14
+ } catch (error) { onError(error); }
15
+ }
16
+ async function warmShaders(root = scene) {
17
+ const known = new Set(programs());
18
+ let timer;
19
+ try {
20
+ const done = beginCompiles(root, warmed);
21
+ if (root !== scene && !warmed) {
22
+ Promise.resolve(done).catch(onError);
23
+ return;
24
+ }
25
+ await Promise.race([done, new Promise(resolve => { timer = setTimeout(resolve, timeoutMs); })]);
26
+ if (root === scene) {
27
+ for (const program of programs()) useProgram(program);
28
+ warmed = true;
29
+ } else await putToUse(addedSince(known));
30
+ } catch (error) { onError(error); }
31
+ finally { clearTimeout(timer); }
32
+ }
33
+ return {beginWarm, warmShaders};
34
+ }