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,197 @@
1
+ import * as THREE from 'three';
2
+
3
+ // WebGLPrograms also selects variants by object and geometry, independently of material identity.
4
+ function meshKind(object) {
5
+ const { morphAttributes: morph = {}, attributes = {} } = object.geometry ?? {};
6
+ let key = '';
7
+ if (object.isSkinnedMesh) key += ':skin';
8
+ if (object.isInstancedMesh) {
9
+ key += ':instances';
10
+ if (object.instanceColor) key += ':instanceColor';
11
+ if (object.morphTexture) key += ':instanceMorph';
12
+ }
13
+ if (object.isBatchedMesh) key += object._colorsTexture ? ':batchColor' : ':batch';
14
+ if (object.isPoints) key += attributes.uv ? ':pointUV' : ':points';
15
+ if (object.isLine) key += ':line';
16
+ if (object.isSprite) key += object.center ? ':spriteCenter' : ':sprite';
17
+ if (morph.position?.length || morph.normal?.length || morph.color?.length) {
18
+ key += ':morph:' + (morph.position?.length ?? 0) + ':' + (morph.normal?.length ?? 0) + ':' + (morph.color?.length ?? 0);
19
+ }
20
+ if (attributes.uv1) key += ':uv1';
21
+ if (attributes.uv2) key += ':uv2';
22
+ if (attributes.uv3) key += ':uv3';
23
+ if (attributes.tangent) key += ':tangent';
24
+ if (attributes.color?.itemSize === 4) key += ':rgba';
25
+ return key;
26
+ }
27
+
28
+ function representatives(root) {
29
+ const picked = new Map();
30
+ root.traverse(object => {
31
+ if (!(object.isMesh || object.isPoints || object.isLine || object.isSprite) || !object.material) return;
32
+ const materials = Array.isArray(object.material) ? object.material.map(m => m.uuid).join(',') : object.material.uuid;
33
+ const key = materials + ':' + meshKind(object);
34
+ if (!picked.has(key)) picked.set(key, object);
35
+ });
36
+ return [...picked.values()];
37
+ }
38
+
39
+ const shadowSide = [THREE.BackSide, THREE.FrontSide, THREE.DoubleSide];
40
+
41
+ // Compile a group in its lighting environment, including material overrides and offscreen passes.
42
+ // All scratch resources and readiness polling belong to this renderer instance.
43
+ export function createShaderWarmup({renderer, scene, camera, postMaterials = () => [], pollIntervalMs = 10}) {
44
+ const target = new THREE.WebGLRenderTarget(1, 1);
45
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), []);
46
+ const twins = new Map();
47
+ const pending = new Set();
48
+ const ready = new WeakSet();
49
+ let timer;
50
+
51
+ function poll() {
52
+ const live = new Set(renderer.info.programs);
53
+ for (const entry of pending) {
54
+ for (const program of entry.programs) {
55
+ if (!live.has(program)) entry.programs.delete(program);
56
+ else if (ready.has(program) || program.isReady()) {
57
+ ready.add(program);
58
+ entry.programs.delete(program);
59
+ }
60
+ }
61
+ if (entry.programs.size) continue;
62
+ pending.delete(entry);
63
+ entry.resolve();
64
+ }
65
+ timer = pending.size ? setTimeout(poll, pollIntervalMs) : undefined;
66
+ }
67
+
68
+ function begin(traverse, root, view, lit, yieldIfReady = false) {
69
+ const materials = renderer.compile({
70
+ traverse,
71
+ traverseVisible: visit => { if (lit !== root) root.traverseVisible(visit); }
72
+ }, view, lit);
73
+ const programs = new Set();
74
+ for (const m of materials) {
75
+ const variants = renderer.properties.get(m).programs;
76
+ if (variants) for (const program of variants.values()) {
77
+ if (!ready.has(program)) programs.add(program);
78
+ }
79
+ }
80
+ if (!programs.size && !yieldIfReady) return Promise.resolve();
81
+ return new Promise(resolve => {
82
+ pending.add({programs, resolve});
83
+ if (timer === undefined) timer = setTimeout(poll, 0);
84
+ });
85
+ }
86
+
87
+ function withTarget(into, work) {
88
+ const previous = renderer.getRenderTarget();
89
+ const face = renderer.getActiveCubeFace();
90
+ const level = renderer.getActiveMipmapLevel();
91
+ renderer.setRenderTarget(into);
92
+ try { return work(); }
93
+ finally { renderer.setRenderTarget(previous, face, level); }
94
+ }
95
+
96
+ function compiled(root, view = camera, lit = root) {
97
+ const objects = representatives(root);
98
+ return begin(visit => objects.forEach(visit), root, view, lit);
99
+ }
100
+
101
+ async function compiledInTurn(root, view = camera, lit = scene, into = null) {
102
+ for (const object of representatives(root)) {
103
+ await withTarget(into, () => begin(visit => visit(object), root, view, lit, true));
104
+ }
105
+ }
106
+
107
+ function warmStandIns(root, standIn, view, into = target, fog, includeMaterialArrays = false) {
108
+ const picked = new Map();
109
+ root.traverse(object => {
110
+ if (!(object.isMesh || object.isPoints || object.isLine) || !object.material) return;
111
+ if (!includeMaterialArrays && Array.isArray(object.material)) return;
112
+ const m = standIn(object);
113
+ if (!m) return;
114
+ const key = [m.uuid, m.side, !!m.map, !!m.alphaMap, m.alphaTest > 0, meshKind(object)].join(':');
115
+ if (!picked.has(key)) picked.set(key, object);
116
+ });
117
+ return withTarget(into, () => {
118
+ const previousFog = scene.fog;
119
+ scene.fog = fog;
120
+ try {
121
+ // Three gathers the target scene's lights once per compile. Submit the entire override pass
122
+ // together, applying mutable stand-ins only while Three prepares their representative.
123
+ return begin(visit => {
124
+ for (const object of picked.values()) {
125
+ const material = object.material;
126
+ try {
127
+ object.material = standIn(object);
128
+ visit(object);
129
+ } finally { object.material = material; }
130
+ }
131
+ }, scene, view, scene);
132
+ } finally { scene.fog = previousFog; }
133
+ });
134
+ }
135
+
136
+ function shadowMaterial(object, point) {
137
+ const material = object.material;
138
+ const side = material.shadowSide ?? (renderer.shadowMap.type === THREE.VSMShadowMap ? material.side : shadowSide[material.side]);
139
+ const key = [point, side, !!material.map, !!material.alphaMap, material.alphaTest > 0].join(':');
140
+ let twin = point ? object.customDistanceMaterial : object.customDepthMaterial;
141
+ if (!twin) {
142
+ twin = twins.get(key);
143
+ if (!twin) {
144
+ twin = point ? new THREE.MeshDistanceMaterial() : new THREE.MeshDepthMaterial(
145
+ Number(THREE.REVISION) <= 170 ? {depthPacking: THREE.RGBADepthPacking} : {}
146
+ );
147
+ twins.set(key, twin);
148
+ }
149
+ }
150
+ twin.side = side;
151
+ twin.map = material.map;
152
+ twin.alphaMap = material.alphaMap;
153
+ twin.alphaTest = material.alphaToCoverage ? 0.5 : material.alphaTest;
154
+ twin.displacementMap = material.displacementMap;
155
+ twin.clippingPlanes = material.clippingPlanes;
156
+ twin.clipIntersection = material.clipIntersection;
157
+ twin.clipShadows = material.clipShadows;
158
+ return twin;
159
+ }
160
+
161
+ function warmShadowPass(root, {waitForPoint = true} = {}) {
162
+ if (!renderer.shadowMap.enabled) return Promise.resolve();
163
+ const depth = warmStandIns(root, o => o.castShadow && shadowMaterial(o, false), camera, target, null);
164
+ let point;
165
+ scene.traverseVisible(o => { if (o.isPointLight && o.castShadow) point = true; });
166
+ const distance = point && warmStandIns(root, o => o.castShadow && shadowMaterial(o, true), camera, target, null);
167
+ for (const twin of twins.values()) {
168
+ twin.map = twin.alphaMap = twin.displacementMap = twin.clippingPlanes = null;
169
+ }
170
+ return waitForPoint ? Promise.all([depth, distance]) : depth;
171
+ }
172
+
173
+ function warmPostPasses() {
174
+ const screen = [], offscreen = [];
175
+ for (const [material, into] of postMaterials()) (into === null ? screen : offscreen).push(material);
176
+ // Three prepares each material in a material array against the same render target.
177
+ const compilePass = (materials, into) => {
178
+ if (!materials.length) return;
179
+ quad.material = materials;
180
+ return withTarget(into, () => compiled(quad, camera));
181
+ };
182
+ try { return Promise.all([compilePass(offscreen, target), compilePass(screen, null)]); }
183
+ finally { quad.material = []; }
184
+ }
185
+
186
+ function dispose() {
187
+ clearTimeout(timer);
188
+ timer = undefined;
189
+ for (const entry of pending) entry.resolve();
190
+ pending.clear();
191
+ quad.geometry.dispose();
192
+ target.dispose();
193
+ for (const twin of twins.values()) twin.dispose();
194
+ twins.clear();
195
+ }
196
+ return {compiled, compiledInTurn, compilingNow: () => pending.size > 0, warmStandIns, warmShadowPass, warmPostPasses, dispose};
197
+ }
@@ -0,0 +1,28 @@
1
+ import { Vector3 } from 'three';
2
+
3
+ // The snapped center keeps its original depth and moves by whole texels across the shadow map.
4
+ export function createShadowSnap() {
5
+ const worldUp = new Vector3(0, 1, 0);
6
+ const right = new Vector3();
7
+ const up = new Vector3();
8
+ return (out, x, y, z, direction, texelWidth, texelHeight = texelWidth) => {
9
+ right.crossVectors(worldUp, direction);
10
+ if (right.lengthSq() < 1e-8) right.set(1, 0, 0);
11
+ right.normalize();
12
+ up.crossVectors(direction, right);
13
+ const a = Math.round((x * right.x + y * right.y + z * right.z) / texelWidth) * texelWidth;
14
+ const u = Math.round((x * up.x + y * up.y + z * up.z) / texelHeight) * texelHeight;
15
+ const d = x * direction.x + y * direction.y + z * direction.z;
16
+ return out.set(0, 0, 0).addScaledVector(right, a).addScaledVector(up, u).addScaledVector(direction, d);
17
+ };
18
+ }
19
+
20
+ export function fitOrthographicShadow(camera, extent, near, far) {
21
+ camera.left = -extent;
22
+ camera.right = extent;
23
+ camera.top = extent;
24
+ camera.bottom = -extent;
25
+ camera.near = near;
26
+ camera.far = far;
27
+ camera.updateProjectionMatrix();
28
+ }
@@ -0,0 +1,129 @@
1
+ import * as THREE from 'three';
2
+ import {isStill, keptAway, placeOf, still, STILL_LAYER} from './still-casters.js';
3
+
4
+ const handlers = new WeakMap();
5
+ let installed = 0;
6
+ let previousBefore, previousAfter;
7
+
8
+ // Delegating to previous hooks also preserves application hooks installed before this extension.
9
+ function before(renderer, object, camera, shadowCamera, geometry, material, group) {
10
+ previousBefore.call(this, renderer, object, camera, shadowCamera, geometry, material, group);
11
+ handlers.get(renderer)?.begin(this, shadowCamera, geometry, material);
12
+ }
13
+ function after(renderer, object, camera, shadowCamera, geometry, material, group) {
14
+ handlers.get(renderer)?.end(this, geometry);
15
+ previousAfter.call(this, renderer, object, camera, shadowCamera, geometry, material, group);
16
+ }
17
+
18
+ function kindOf(o) {
19
+ const morph = o.geometry.morphAttributes;
20
+ if (morph.position || morph.normal || morph.color) return null;
21
+ if (o.isSkinnedMesh) return 'skinned';
22
+ if (o.isInstancedMesh) return o.instanceColor ? 'tinted' : 'instanced';
23
+ return null;
24
+ }
25
+
26
+ // Opt in one renderer. Meshes with their own shadow hooks continue to use them.
27
+ export function installShadowDepth(renderer) {
28
+ if (handlers.has(renderer)) throw new Error('Shadow depth hooks already installed for this renderer');
29
+ const materials = {customDepthMaterial: {}, customDistanceMaterial: {}}, entries = new WeakMap();
30
+ const world = new THREE.Matrix4(), instance = new THREE.Matrix4(), sphere = new THREE.Sphere();
31
+ function noneNear(object, at, reach, entry) {
32
+ const matrix = object.instanceMatrix;
33
+ const geometry = object.geometry;
34
+ if (!geometry.boundingSphere) geometry.computeBoundingSphere();
35
+ const bounds = geometry.boundingSphere;
36
+ if (entry.matrix === matrix && entry.version === matrix.version && entry.count === object.count &&
37
+ entry.reach === reach && entry.x === at.x && entry.y === at.y && entry.z === at.z &&
38
+ entry.bounds.equals(bounds) && entry.world.equals(object.matrixWorld)) return entry.away;
39
+ entry.matrix = matrix;
40
+ entry.version = matrix.version;
41
+ entry.count = object.count;
42
+ entry.reach = reach;
43
+ entry.x = at.x; entry.y = at.y; entry.z = at.z;
44
+ (entry.world ??= new THREE.Matrix4()).copy(object.matrixWorld);
45
+ (entry.bounds ??= new THREE.Sphere()).copy(bounds);
46
+ entry.away = true;
47
+ for (let i = 0; i < object.count; ++i) {
48
+ object.getMatrixAt(i, instance);
49
+ world.multiplyMatrices(object.matrixWorld, instance);
50
+ sphere.copy(bounds).applyMatrix4(world);
51
+ if (sphere.center.distanceToSquared(at) <= (reach + sphere.radius) ** 2) {
52
+ entry.away = false;
53
+ break;
54
+ }
55
+ }
56
+ return entry.away;
57
+ }
58
+ function begin(object, shadowCamera, geometry, material) {
59
+ const point = material.isMeshDistanceMaterial;
60
+ let entry = entries.get(object);
61
+ if (point && isStill(object)) {
62
+ const at = placeOf(object.matrixWorld.elements);
63
+ if (still.kept && object.keptIn === still.round && object.keptAs !== at) object.layers.disable(STILL_LAYER);
64
+ if (keptAway(object, at)) {
65
+ if (!entry) entries.set(object, entry = {});
66
+ entry.range = geometry.drawRange.count;
67
+ geometry.drawRange.count = -1;
68
+ }
69
+ return;
70
+ }
71
+ if (!(object.isInstancedMesh || object.isSkinnedMesh)) return;
72
+ if (!entry) entries.set(object, entry = {});
73
+ if (object.isInstancedMesh && point && noneNear(object, shadowCamera.position, shadowCamera.far, entry)) {
74
+ entry.countAside = object.count;
75
+ object.count = 0;
76
+ }
77
+ const field = point ? 'customDistanceMaterial' : 'customDepthMaterial';
78
+ if (object[field] !== undefined && object[field] !== entry[field]) return;
79
+ const skin = object.material;
80
+ const kind = kindOf(object);
81
+ if (!kind || Array.isArray(skin) || skin.alphaTest > 0 || skin.alphaToCoverage || skin.displacementMap || skin.clippingPlanes?.length) {
82
+ if (entry[field] && object[field] === entry[field]) object[field] = undefined;
83
+ return;
84
+ }
85
+ let shared = materials[field][kind];
86
+ if (!shared) {
87
+ shared = point ? new THREE.MeshDistanceMaterial() : new THREE.MeshDepthMaterial(
88
+ Number(THREE.REVISION) <= 170 ? {depthPacking: THREE.RGBADepthPacking} : {}
89
+ );
90
+ materials[field][kind] = shared;
91
+ }
92
+ object[field] = entry[field] = shared;
93
+ }
94
+ function end(object, geometry) {
95
+ const entry = entries.get(object);
96
+ if (!entry) return;
97
+ if (entry.range !== undefined) {
98
+ geometry.drawRange.count = entry.range;
99
+ entry.range = undefined;
100
+ }
101
+ if (entry.countAside !== undefined) {
102
+ object.count = entry.countAside;
103
+ entry.countAside = undefined;
104
+ }
105
+ }
106
+ if (installed++ === 0) {
107
+ previousBefore = THREE.Object3D.prototype.onBeforeShadow;
108
+ previousAfter = THREE.Object3D.prototype.onAfterShadow;
109
+ THREE.Object3D.prototype.onBeforeShadow = before;
110
+ THREE.Object3D.prototype.onAfterShadow = after;
111
+ }
112
+ handlers.set(renderer, {begin, end});
113
+ function dispose(root) {
114
+ if (!handlers.delete(renderer)) return;
115
+ root?.traverse(o => {
116
+ const entry = entries.get(o);
117
+ if (!entry) return;
118
+ for (const field of ['customDepthMaterial','customDistanceMaterial']) {
119
+ if (entry[field] && o[field] === entry[field]) o[field] = undefined;
120
+ }
121
+ });
122
+ for (const group of Object.values(materials)) for (const material of Object.values(group)) material.dispose();
123
+ if (--installed === 0) {
124
+ if (THREE.Object3D.prototype.onBeforeShadow === before) THREE.Object3D.prototype.onBeforeShadow = previousBefore;
125
+ if (THREE.Object3D.prototype.onAfterShadow === after) THREE.Object3D.prototype.onAfterShadow = previousAfter;
126
+ }
127
+ }
128
+ return {dispose};
129
+ }
@@ -0,0 +1,187 @@
1
+ import * as THREE from 'three';
2
+
3
+ // Shared uniforms and shader hook for standard materials sampling a local sky visibility map.
4
+ export function createSkyOcclusionShader({minimum, underCover}) {
5
+ const uniforms = {
6
+ uSkyOpen: { value: null },
7
+ uSkyR: { value: new THREE.Vector4(0, 0, 0, 0) },
8
+ uSkyOn: { value: 0 },
9
+ };
10
+
11
+ const SKY_OPEN = /* glsl */ `
12
+ uniform sampler2D uSkyOpen; uniform vec4 uSkyR; uniform float uSkyOn;
13
+ float skyOpen(vec3 viewNormal) {
14
+ if (uSkyOn <= 0.0) return 1.0;
15
+ vec3 wp = cameraPosition - vViewPosition * mat3(viewMatrix), wn = viewNormal * mat3(viewMatrix);
16
+ vec2 uv = (wp.xz + wn.xz * 0.6 - uSkyR.xy) * vec2(uSkyR.z, -uSkyR.z), off = abs(uv - 0.5);
17
+ float reach = 1.0 - smoothstep(0.36, 0.48, max(off.x, off.y));
18
+ if (reach <= 0.0) return 1.0;
19
+ vec4 s = texture2D(uSkyOpen, uv);
20
+ float up = wp.y - uSkyR.w - s.g;
21
+ float open = up < -0.6 ? ${underCover.toFixed(2)} : mix(s.r, 1.0, clamp(up / max(s.b - s.g, 0.5), 0.0, 1.0));
22
+ return mix(1.0, ${minimum.toFixed(2)} + ${(1 - minimum).toFixed(2)} * open, uSkyOn * reach);
23
+ }
24
+ `;
25
+ function patch(sh, more = '') {
26
+ Object.assign(sh.uniforms, uniforms);
27
+ sh.fragmentShader = sh.fragmentShader
28
+ .replace('#include <common>', '#include <common>\n' + SKY_OPEN)
29
+ .replace(
30
+ '#include <lights_fragment_begin>',
31
+ `#include <lights_fragment_begin>\n#if defined( RE_IndirectDiffuse )\n ${more}\n irradiance *= skyOpen(geometryNormal);\n#endif`,
32
+ );
33
+ }
34
+ return {uniforms, patch};
35
+ }
36
+
37
+ // Two passes: record overhead caster height, then integrate the horizon in eight directions.
38
+ // The first map is available immediately. Subsequent height and horizon passes alternate frames.
39
+ export function createSkyOcclusion({renderer, scene, camera, uniforms, config, samples, ground, strength,
40
+ occludes = o => o.isMesh && o.castShadow, warmup}) {
41
+ const {compiled, warmStandIns, compilingNow} = warmup;
42
+ const heights = new THREE.WebGLRenderTarget(config.size, config.size, { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter });
43
+ const openness = new THREE.WebGLRenderTarget(config.size, config.size, {
44
+ type: THREE.HalfFloatType,
45
+ minFilter: THREE.LinearFilter,
46
+ magFilter: THREE.LinearFilter,
47
+ depthBuffer: false,
48
+ });
49
+ uniforms.uSkyOpen.value = openness.texture;
50
+ const above = new THREE.OrthographicCamera(-config.half, config.half, config.half, -config.half, 1, config.depth);
51
+ above.rotation.set(-Math.PI / 2, 0, 0);
52
+ const depthOf = {
53
+ plain: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
54
+ instanced: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
55
+ tinted: new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide }),
56
+ };
57
+
58
+ const openPass = new THREE.Mesh(
59
+ new THREE.PlaneGeometry(2, 2),
60
+ new THREE.ShaderMaterial({
61
+ depthTest: false,
62
+ depthWrite: false,
63
+ uniforms: { tHeights: { value: heights.texture }, uTexel: { value: (2 * config.half) / config.size } },
64
+ vertexShader: /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }`,
65
+ fragmentShader: /* glsl */ `
66
+ #include <packing>
67
+ uniform sampler2D tHeights; uniform float uTexel; varying vec2 vUv;
68
+ float heightAt(vec2 uv) { return ${config.above.toFixed(1)} - mix(1.0, ${config.depth.toFixed(1)}, unpackRGBAToDepth(texture2D(tHeights, uv))); }
69
+ void main() {
70
+ float h0 = heightAt(vUv), sky = 0.0, tops = 0.0;
71
+ for (int i = 0; i < 8; i++) {
72
+ float a = float(i) * 0.7853982;
73
+ vec2 dir = vec2(cos(a), sin(a)) / (uTexel * ${config.size.toFixed(1)});
74
+ float rise = 0.0, top = h0;
75
+ ${samples.map(d => `{ float h = heightAt(vUv + dir * ${d.toFixed(2)}); rise = max(rise, (h - h0) / ${d.toFixed(2)}); top = max(top, h); }`).join('\n ')}
76
+ sky += 1.0 / (1.0 + rise * rise);
77
+ tops += top;
78
+ }
79
+ gl_FragColor = vec4(sky / 8.0, h0, tops / 8.0, 1.0);
80
+ }`,
81
+ }),
82
+ );
83
+ openPass.frustumCulled = false;
84
+ const passScene = new THREE.Scene().add(openPass),
85
+ passCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
86
+
87
+ const depthFor = o => (!occludes(o) ? null : o.isInstancedMesh ? (o.instanceColor ? depthOf.tinted : depthOf.instanced) : depthOf.plain);
88
+ const pending = Object.assign(new THREE.Vector4(), { due: false }),
89
+ hidden = [],
90
+ dressed = [],
91
+ worn = [],
92
+ _clear = new THREE.Color();
93
+ function drawHeights(atX, atZ) {
94
+ const texel = (2 * config.half) / config.size,
95
+ x = Math.round(atX / texel) * texel,
96
+ z = Math.round(atZ / texel) * texel,
97
+ y = ground(x, z);
98
+ above.position.set(x, y + config.above, z);
99
+ above.updateMatrixWorld();
100
+ const previousTarget = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
101
+ const shadows = renderer.shadowMap.autoUpdate, clearAlpha = renderer.getClearAlpha(), fog = scene.fog;
102
+ renderer.getClearColor(_clear);
103
+ try {
104
+ scene.traverse(o => {
105
+ if (!o.visible || !(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;
106
+ const depth = depthFor(o);
107
+ if (!depth) {
108
+ o.visible = false;
109
+ hidden.push(o);
110
+ return;
111
+ }
112
+ dressed.push(o);
113
+ worn.push(o.material);
114
+ o.material = depth;
115
+ });
116
+ renderer.shadowMap.autoUpdate = false;
117
+ renderer.setRenderTarget(heights);
118
+ renderer.setClearColor(0xffffff, 1);
119
+ renderer.clear();
120
+ scene.fog = null;
121
+ renderer.render(scene, above);
122
+ } finally {
123
+ scene.fog = fog;
124
+ for (let i = 0; i < dressed.length; i++) dressed[i].material = worn[i];
125
+ for (let i = 0; i < hidden.length; i++) hidden[i].visible = true;
126
+ dressed.length = worn.length = hidden.length = 0;
127
+ renderer.setClearColor(_clear, clearAlpha);
128
+ renderer.setRenderTarget(previousTarget, face, level);
129
+ renderer.shadowMap.autoUpdate = shadows;
130
+ }
131
+ pending.set(x - config.half, z + config.half, 1 / (2 * config.half), y);
132
+ pending.due = true;
133
+ }
134
+ function workOutOpenness() {
135
+ const target = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
136
+ renderer.setRenderTarget(openness);
137
+ try { renderer.render(passScene, passCamera); }
138
+ finally { renderer.setRenderTarget(target, face, level); }
139
+ uniforms.uSkyR.value.copy(pending);
140
+ pending.due = false;
141
+ }
142
+
143
+ function warm(root) {
144
+ const done = [warmStandIns(root, depthFor, above, heights, null)];
145
+ if (root === scene) {
146
+ const target = renderer.getRenderTarget(), face = renderer.getActiveCubeFace(), level = renderer.getActiveMipmapLevel();
147
+ renderer.setRenderTarget(openness);
148
+ try { done.push(compiled(passScene, passCamera)); }
149
+ finally { renderer.setRenderTarget(target, face, level); }
150
+ }
151
+ return Promise.all(done);
152
+ }
153
+
154
+ const drawn = { x: NaN, z: NaN, age: 0 };
155
+ function update(dt) {
156
+ const x = camera.position.x,
157
+ z = camera.position.z,
158
+ high = camera.position.y - ground(x, z),
159
+ on = strength(high);
160
+ uniforms.uSkyOn.value = on;
161
+ if (on <= 0 || compilingNow()) return;
162
+ if (pending.due) {
163
+ workOutOpenness();
164
+ return;
165
+ }
166
+ drawn.age += dt;
167
+ if (Math.hypot(x - drawn.x, z - drawn.z) < config.step && drawn.age < config.every) return;
168
+ const first = Number.isNaN(drawn.x);
169
+ drawHeights(x, z);
170
+ if (first) workOutOpenness();
171
+ drawn.x = x;
172
+ drawn.z = z;
173
+ drawn.age = 0;
174
+ }
175
+ function dispose() {
176
+ heights.dispose();
177
+ openness.dispose();
178
+ for (const depth of Object.values(depthOf)) depth.dispose();
179
+ openPass.geometry.dispose();
180
+ openPass.material.dispose();
181
+ if (uniforms.uSkyOpen.value === openness.texture) {
182
+ uniforms.uSkyOpen.value = null;
183
+ uniforms.uSkyOn.value = 0;
184
+ }
185
+ }
186
+ return {update, warm, dispose};
187
+ }