roamwright 0.1.0 → 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 (116) 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/builder.js +11 -14
  9. package/geometry/creased-sheet.js +127 -0
  10. package/geometry/ear.js +97 -0
  11. package/geometry/erosion.js +106 -0
  12. package/geometry/face-grid.js +143 -0
  13. package/geometry/garment-tags.js +11 -0
  14. package/geometry/hair-gathers.js +174 -0
  15. package/geometry/hair-locks.js +156 -0
  16. package/geometry/hair-patch.js +42 -0
  17. package/geometry/hair-shell.js +186 -0
  18. package/geometry/hair-tags.js +6 -0
  19. package/geometry/head-profile.js +138 -0
  20. package/geometry/head-shape.js +499 -0
  21. package/geometry/heightfield.js +68 -0
  22. package/geometry/outline-grid.js +46 -0
  23. package/geometry/path-field.js +65 -0
  24. package/geometry/sagging-tube.js +58 -0
  25. package/geometry/sampled-surface.js +101 -0
  26. package/geometry/scatter-grid.js +32 -0
  27. package/geometry/sculpt.js +263 -0
  28. package/geometry/shore-grid.js +67 -0
  29. package/geometry/strata-field.js +339 -0
  30. package/geometry/strata-tiles.js +215 -0
  31. package/geometry/stream.js +94 -0
  32. package/geometry/terrain-chunks.js +300 -0
  33. package/geometry/terrain-extension.js +44 -0
  34. package/math/cell-edge.js +44 -0
  35. package/math/cloth-textures.js +83 -0
  36. package/math/cloud-textures.js +112 -0
  37. package/math/color.js +29 -0
  38. package/math/curve.js +3 -4
  39. package/math/mountain-ranges.js +463 -0
  40. package/math/particle-noise.js +48 -0
  41. package/math/periodic.js +20 -0
  42. package/math/rock-texture.js +56 -0
  43. package/math/surface-textures.js +241 -0
  44. package/motion/arm-reach.js +74 -0
  45. package/motion/biped-stride.js +276 -0
  46. package/motion/crowd-alarms.js +127 -0
  47. package/motion/crowd-routine.js +183 -0
  48. package/motion/daily-clock.js +59 -0
  49. package/motion/instance-sight.js +84 -0
  50. package/motion/quadruped.js +332 -0
  51. package/motion/weather.js +59 -0
  52. package/motion/wind.js +27 -0
  53. package/package.json +6 -4
  54. package/rendering/caster-motion.js +79 -0
  55. package/rendering/cell-lod.js +175 -0
  56. package/rendering/cloud-dome.js +371 -0
  57. package/rendering/cloud-field.js +83 -0
  58. package/rendering/compilation-schedule.js +34 -0
  59. package/rendering/contact-shadows.js +79 -0
  60. package/rendering/crowd-skinning.js +133 -0
  61. package/rendering/crust.js +28 -0
  62. package/rendering/daylight.js +50 -0
  63. package/rendering/far-shadow.js +186 -0
  64. package/rendering/flocks.js +323 -0
  65. package/rendering/garment-material.js +110 -0
  66. package/rendering/glow-lines.js +74 -0
  67. package/rendering/glow-shell.js +90 -0
  68. package/rendering/hair-strands.js +67 -0
  69. package/rendering/height-haze.js +129 -0
  70. package/rendering/height-probe.js +91 -0
  71. package/rendering/interior-mapping.js +19 -0
  72. package/rendering/light-budget.js +222 -0
  73. package/rendering/light-points.js +51 -0
  74. package/rendering/light-shafts.js +131 -0
  75. package/rendering/local-lights.js +28 -0
  76. package/rendering/low-light.js +13 -0
  77. package/rendering/material-lod.js +110 -0
  78. package/rendering/particle-emitters.js +223 -0
  79. package/rendering/particles.js +297 -0
  80. package/rendering/planar-reflection.js +175 -0
  81. package/rendering/post-shaders.js +21 -1
  82. package/rendering/post.js +8 -5
  83. package/rendering/rain-rings.js +22 -0
  84. package/rendering/road-surface.js +63 -0
  85. package/rendering/sea-shaders.js +230 -0
  86. package/rendering/shader-warmup.js +197 -0
  87. package/rendering/shadow-alignment.js +28 -0
  88. package/rendering/shadow-depth.js +129 -0
  89. package/rendering/sky-occlusion.js +187 -0
  90. package/rendering/sky.js +169 -0
  91. package/rendering/stage-lights.js +209 -0
  92. package/rendering/static-point-shadow.js +119 -0
  93. package/rendering/still-casters.js +6 -11
  94. package/rendering/strata-material.js +93 -0
  95. package/rendering/stream-flow.js +36 -0
  96. package/rendering/surface-light.js +22 -0
  97. package/rendering/surface-projection.js +69 -0
  98. package/rendering/talus.js +26 -0
  99. package/rendering/terrain-rock.js +48 -0
  100. package/rendering/texture-fills.js +68 -0
  101. package/rendering/viewport.js +9 -0
  102. package/rendering/wakes.js +99 -0
  103. package/rendering/water-material.js +288 -0
  104. package/rendering/world-matrices.js +4 -6
  105. package/runtime/device-quality.js +27 -0
  106. package/runtime/diagnostic-log.js +80 -0
  107. package/runtime/events.js +14 -0
  108. package/runtime/first-use.js +3 -1
  109. package/runtime/frame-yield.js +14 -0
  110. package/runtime/grid-cache.js +88 -0
  111. package/runtime/grid-rows.js +9 -0
  112. package/runtime/module-preload.js +15 -0
  113. package/runtime/quality-fit.js +5 -9
  114. package/runtime/search.js +69 -0
  115. package/runtime/spatial-audio.js +57 -0
  116. package/scripts/serve.py +26 -0
@@ -0,0 +1,79 @@
1
+ import * as THREE from 'three';
2
+
3
+ // Soft contact shadows on horizontal receivers. Supply the height of the receiving
4
+ // surface in mesh-local coordinates. One quad per contact, in one draw.
5
+ export class ContactShadows {
6
+ constructor({ capacity, opacity = 0.4, lift = 0.015 }) {
7
+ if (!Number.isInteger(capacity) || capacity < 1) throw new RangeError('capacity must be a positive integer');
8
+ this.capacity = capacity;
9
+ this.count = 0;
10
+ this.contacts = new THREE.InstancedBufferAttribute(new Float32Array(capacity * 4), 4).setUsage(THREE.DynamicDrawUsage);
11
+ const quad = new THREE.PlaneGeometry(2, 2).rotateX(-Math.PI / 2);
12
+ const geometry = new THREE.InstancedBufferGeometry();
13
+ geometry.setAttribute('position', quad.getAttribute('position'));
14
+ geometry.setIndex(quad.index);
15
+ geometry.setAttribute('contact', this.contacts);
16
+ geometry.setAttribute('intensity', new THREE.InstancedBufferAttribute(new Float32Array(capacity), 1).setUsage(THREE.DynamicDrawUsage));
17
+ geometry.instanceCount = 0;
18
+ const material = new THREE.ShaderMaterial({
19
+ transparent: true, depthWrite: false, polygonOffset: true,
20
+ polygonOffsetFactor: -2, polygonOffsetUnits: -6,
21
+ uniforms: { opacityScale: { value: opacity }, lift: { value: lift } },
22
+ vertexShader: `
23
+ attribute vec4 contact;
24
+ attribute float intensity;
25
+ uniform float lift;
26
+ varying vec2 offset;
27
+ varying float weight;
28
+ void main() {
29
+ offset = position.xz;
30
+ weight = intensity;
31
+ vec3 p = contact.xyz + vec3(position.x * contact.w, lift, position.z * contact.w);
32
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
33
+ }`,
34
+ fragmentShader: `
35
+ uniform float opacityScale;
36
+ varying vec2 offset;
37
+ varying float weight;
38
+ void main() {
39
+ float fall = 1.0 - smoothstep(0.0, 1.0, length(offset));
40
+ gl_FragColor = vec4(0.0, 0.0, 0.0, opacityScale * weight * fall * fall);
41
+ }`,
42
+ });
43
+ this.mesh = new THREE.Mesh(geometry, material);
44
+ this.mesh.frustumCulled = false;
45
+ }
46
+
47
+ begin() {
48
+ this.count = 0;
49
+ }
50
+
51
+ add(x, y, z, radius, intensity = 1) {
52
+ if (this.count >= this.capacity) return false;
53
+ this.contacts.setXYZW(this.count, x, y, z, radius);
54
+ this.mesh.geometry.attributes.intensity.setX(this.count, intensity);
55
+ this.count++;
56
+ return true;
57
+ }
58
+
59
+ end() {
60
+ const geometry = this.mesh.geometry;
61
+ geometry.instanceCount = this.count;
62
+ this.mesh.visible = this.count > 0;
63
+ if (!this.count) return;
64
+ this.updateRange(this.contacts);
65
+ this.updateRange(geometry.attributes.intensity);
66
+ }
67
+
68
+ updateRange(attribute) {
69
+ attribute.clearUpdateRanges();
70
+ attribute.addUpdateRange(0, this.count * attribute.itemSize);
71
+ attribute.needsUpdate = true;
72
+ }
73
+
74
+ dispose() {
75
+ this.mesh.removeFromParent();
76
+ this.mesh.geometry.dispose();
77
+ this.mesh.material.dispose();
78
+ }
79
+ }
@@ -0,0 +1,133 @@
1
+ import * as THREE from 'three';
2
+ import { lerp } from '../math/scalar.js';
3
+
4
+ // Texture-backed bone rows and pre-baked motion feed the same meshes in every render pass.
5
+ export function applyCrowdSkinning(shader, { poseUniform, walk = null, depth = false, paletteOffset = 0 }) {
6
+ const distant = !!walk;
7
+ shader.uniforms.uCrowdPose = poseUniform;
8
+ if (distant) shader.uniforms.uCrowdWalk = { value: walk };
9
+ const common = `/* glsl */
10
+ uniform highp sampler2D uCrowdPose;
11
+ attribute vec2 aCrowdRows;
12
+ ${depth ? '' : 'attribute float aPalette;'}`;
13
+ const animated = `/* glsl */
14
+ attribute float aWeight;
15
+ attribute vec2 aJoints;
16
+ mat4x3 crowdBone(int bone) {
17
+ int b = bone * 3, row = int(aCrowdRows.x);
18
+ vec4 x = texelFetch(uCrowdPose, ivec2(b, row), 0);
19
+ vec4 y = texelFetch(uCrowdPose, ivec2(b + 1, row), 0);
20
+ vec4 z = texelFetch(uCrowdPose, ivec2(b + 2, row), 0);
21
+ return mat4x3(vec3(x.x, y.x, z.x), vec3(x.y, y.y, z.y), vec3(x.z, y.z, z.z), vec3(x.w, y.w, z.w));
22
+ }
23
+ mat4x3 crowdTransform() {
24
+ mat4x3 a = crowdBone(int(aJoints.x));
25
+ if (aWeight > 0.999) return a;
26
+ return a * aWeight + crowdBone(int(aJoints.y)) * (1.0 - aWeight);
27
+ }`;
28
+ const baked = `/* glsl */
29
+ uniform highp sampler2D uCrowdWalk;
30
+ vec4 crowdVertex() { return texelFetch(uCrowdWalk, ivec2(gl_VertexID, int(aCrowdRows.x)), 0); }
31
+ vec3 crowdNormal(float data) {
32
+ vec2 u = vec2(floor(data * (1.0 / 4096.0)), mod(data, 4096.0)) * (2.0 / 4095.0) - 1.0;
33
+ vec3 n = vec3(u, 1.0 - abs(u.x) - abs(u.y));
34
+ if (n.z < 0.0) n.xy = (1.0 - abs(n.yx)) * (step(0.0, n.xy) * 2.0 - 1.0);
35
+ return normalize(n);
36
+ }`;
37
+ shader.vertexShader = shader.vertexShader.replace('#include <common>', '#include <common>\n' + common + (distant ? baked : animated));
38
+ if (depth) {
39
+ shader.vertexShader = shader.vertexShader.replace(
40
+ '#include <begin_vertex>',
41
+ distant ? 'vec3 transformed = crowdVertex().xyz;' : 'vec3 transformed = crowdTransform() * vec4(position, 1.0);',
42
+ );
43
+ } else {
44
+ const normals = distant
45
+ ? 'vec4 crowdPose = crowdVertex(); objectNormal = crowdNormal(crowdPose.w);'
46
+ : 'mat4x3 crowdPose = crowdTransform(); objectNormal = crowdPose * vec4(objectNormal, 0.0);';
47
+ const position = distant ? 'crowdPose.xyz' : 'crowdPose * vec4(position, 1.0)';
48
+ shader.vertexShader = shader.vertexShader
49
+ .replace(
50
+ '#include <color_vertex>',
51
+ `/* glsl */
52
+ #include <color_vertex>
53
+ if (aPalette > 0.5) vColor.rgb *= texelFetch(uCrowdPose, ivec2(${paletteOffset} + int(aPalette) - 1, int(aCrowdRows.y)), 0).rgb;`,
54
+ )
55
+ .replace('#include <beginnormal_vertex>', '#include <beginnormal_vertex>\n' + normals)
56
+ .replace('#include <begin_vertex>', `/* glsl */ vec3 transformed = ${position};`);
57
+ }
58
+ }
59
+
60
+ export function createCrowdBatch(scene, geo, max, mat, [depth, distance], name, casts = true) {
61
+ const mesh = new THREE.InstancedMesh(geo, mat, max);
62
+ const rows = new THREE.InstancedBufferAttribute(new Float32Array(max * 2), 2).setUsage(THREE.DynamicDrawUsage);
63
+ geo.setAttribute('aCrowdRows', rows);
64
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
65
+ mesh.name = name;
66
+ mesh.frustumCulled = false;
67
+ mesh.castShadow = casts;
68
+ mesh.receiveShadow = true;
69
+ mesh.count = 0;
70
+ mesh.customDepthMaterial = depth;
71
+ mesh.customDistanceMaterial = distance;
72
+ scene.add(mesh);
73
+ return { mesh, rows, count: 0, shadow: null };
74
+ }
75
+
76
+ export function castCrowdShadow(scene, near, geo, [depth, distance]) {
77
+ const mesh = new THREE.InstancedMesh(geo, near.mesh.material, 0);
78
+ let held = 0;
79
+ geo.setAttribute('aCrowdRows', near.rows);
80
+ mesh.instanceMatrix = near.mesh.instanceMatrix;
81
+ mesh.name = near.mesh.name + ' shadow';
82
+ mesh.frustumCulled = false;
83
+ mesh.castShadow = true;
84
+ mesh.customDepthMaterial = depth;
85
+ mesh.customDistanceMaterial = distance;
86
+ mesh.onBeforeRender = () => {
87
+ held = mesh.count; // a colour pass draws none of them (the card is given no instances), the shadow pass all
88
+ mesh.count = 0;
89
+ };
90
+ mesh.onAfterRender = () => (mesh.count = held);
91
+ near.mesh.castShadow = false;
92
+ near.shadow = mesh;
93
+ scene.add(mesh);
94
+ }
95
+
96
+ // One frame of a faraway figure's walk: each vertex bent by the walker's bones as posed now (row 0 of the pose texture), with its
97
+ // normal packed, appended to the walk's texels.
98
+ export function bakeCrowdFrame(walk, bones) {
99
+ const { position, normal, aJoints, aWeight } = walk.geo.attributes,
100
+ vertices = walk.vertices;
101
+ let k = walk.k;
102
+ for (let i = 0; i < position.count; i++) {
103
+ const a = aJoints.getX(i) * 12,
104
+ b = aJoints.getY(i) * 12,
105
+ w = aWeight.getX(i);
106
+ const x = position.getX(i),
107
+ y = position.getY(i),
108
+ z = position.getZ(i);
109
+ const nx = normal.getX(i),
110
+ ny = normal.getY(i),
111
+ nz = normal.getZ(i);
112
+ const m = j => lerp(bones[b + j], bones[a + j], w);
113
+ const after = (v, u, q, j) => m(j) * v + m(j + 1) * u + m(j + 2) * q;
114
+ vertices[k++] = after(x, y, z, 0) + m(3);
115
+ vertices[k++] = after(x, y, z, 4) + m(7);
116
+ vertices[k++] = after(x, y, z, 8) + m(11);
117
+ let vx = after(nx, ny, nz, 0),
118
+ vy = after(nx, ny, nz, 4);
119
+ const vz = after(nx, ny, nz, 8),
120
+ scale = Math.abs(vx) + Math.abs(vy) + Math.abs(vz) || 1;
121
+ vx /= scale;
122
+ vy /= scale;
123
+ if (vz < 0) {
124
+ const u = (1 - Math.abs(vy)) * (vx < 0 ? -1 : 1);
125
+ vy = (1 - Math.abs(vx)) * (vy < 0 ? -1 : 1);
126
+ vx = u;
127
+ }
128
+ // Octahedral normals use two twelve-bit values in a float's exact integer range.
129
+ vertices[k++] = Math.round((vx * 0.5 + 0.5) * 4095) * 4096 + Math.round((vy * 0.5 + 0.5) * 4095);
130
+ }
131
+ walk.k = k;
132
+ }
133
+
@@ -0,0 +1,28 @@
1
+ // Derivative-filtered drying plates. Coordinates count plates and warp is a smooth signed vector.
2
+ export const crustGLSL = /* glsl */ `
3
+ // a cell's number is wrapped before it is hashed: far from the world's middle it ran to tens of thousands, sin() was asked
4
+ // for the sine of millions, and a graphics card that takes sines quickly and roughly (iOS) laid the cells out in fans and rows
5
+ const float CELL_WRAP = 289.0;
6
+ vec2 cellPoint(vec2 c) { c = mod(c, CELL_WRAP); return fract(sin(vec2(dot(c, vec2(127.1, 311.7)), dot(c, vec2(269.5, 183.3)))) * 43758.5453); }
7
+ // the cells nearest q: x and y the nearest two distances, zw the nearest cell
8
+ vec4 nearestCells(vec2 q) {
9
+ vec2 ci = floor(q), cf = fract(q), near = ci; float f1 = 9.0, f2 = 9.0;
10
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
11
+ vec2 o = vec2(float(i), float(j)), r = o + cellPoint(ci + o) - cf; float dd = dot(r, r);
12
+ if (dd < f1) { f2 = f1; f1 = dd; near = ci + o; } else if (dd < f2) f2 = dd;
13
+ }
14
+ return vec4(sqrt(f1), sqrt(f2), near);
15
+ }
16
+ // the crust at q (in plates: a plate is about one across), warped by w (-1 to 1, smooth): x its seams, y the plates' curled
17
+ // rims, z the finer seams within a plate
18
+ vec3 crustCracks(vec2 q, vec2 w) {
19
+ q += w * 0.45;
20
+ vec4 c = nearestCells(q); float blur = length(fwidth(q)), edge = c.y - c.x;
21
+ vec2 own = cellPoint(c.zw + 7.0); // the plate's own numbers: how wide its seams gape, whether it splits
22
+ float gape = mix(0.022, 0.07, own.x);
23
+ float seam = (1.0 - smoothstep(gape * 0.4, gape + blur, edge)) * (1.0 - smoothstep(0.2, 0.6, blur));
24
+ float rim = (1.0 - smoothstep(gape, gape + 0.22, edge)) * (1.0 - seam) * (1.0 - smoothstep(0.3, 0.8, blur));
25
+ vec2 s = q * 2.3 + 3.7; vec4 f = nearestCells(s); float sBlur = length(fwidth(s));
26
+ float fine = (1.0 - smoothstep(0.015, 0.045 + sBlur, f.y - f.x)) * (1.0 - smoothstep(0.15, 0.45, sBlur)) * step(0.45, own.y) * (1.0 - seam);
27
+ return vec3(seam, rim, fine);
28
+ }`;
@@ -0,0 +1,50 @@
1
+ import { TAU } from '../math/scalar.js';
2
+
3
+ export const moonShine = lit => lit * Math.sqrt(lit);
4
+
5
+ // Write both normalized directions to caller-owned vectors and return the illuminated lunar fraction.
6
+ export function createSunMoonCycle({
7
+ month = 29.5,
8
+ sunRise = 1,
9
+ sunOffset = 0,
10
+ sunTilt = 0,
11
+ moonEast = 1,
12
+ moonRise = 1,
13
+ moonOffset = 0,
14
+ moonTilt = 0,
15
+ } = {}) {
16
+ return (hour, days, moonTurn, sun, moon) => {
17
+ const sunAngle = (hour - 0.25) * TAU;
18
+ sun.set(Math.cos(sunAngle), Math.sin(sunAngle) * sunRise, sunOffset + sunTilt * Math.sin(sunAngle)).normalize();
19
+ const elongation = (((days + hour) / month) % 1) * TAU;
20
+ const moonAngle = sunAngle - elongation;
21
+ moon
22
+ .set(Math.cos(moonAngle) * moonEast, Math.sin(moonAngle) * moonRise, moonOffset + moonTilt * Math.sin(moonAngle))
23
+ .normalize();
24
+ if (moonTurn) {
25
+ const c = Math.cos(moonTurn),
26
+ s = Math.sin(moonTurn);
27
+ const { x, z } = moon;
28
+ moon.x = x * c + z * s;
29
+ moon.z = z * c - x * s;
30
+ }
31
+ return (1 - Math.cos(elongation)) / 2;
32
+ };
33
+ }
34
+
35
+ // A continuous haze layer trails the terrain as the eye moves; a cut or a region change resets it immediately.
36
+ export function createHazeFollower({ fixedHeight = 0, seconds = 1.2, cutDistance = 60 } = {}) {
37
+ let base = fixedHeight,
38
+ lastX,
39
+ lastZ,
40
+ lastRegion;
41
+ return (dt, x, z, ground, region) => {
42
+ if (region == null) base = fixedHeight;
43
+ else if (region !== lastRegion || Math.hypot(x - lastX, z - lastZ) > cutDistance) base = ground;
44
+ else base += (ground - base) * (1 - Math.exp(-dt / seconds));
45
+ lastRegion = region;
46
+ lastX = x;
47
+ lastZ = z;
48
+ return base;
49
+ };
50
+ }
@@ -0,0 +1,186 @@
1
+ import * as THREE from 'three';
2
+ import { createShadowSnap } from './shadow-alignment.js';
3
+
4
+ // Opt in before compiling standard materials. The first shadow-casting directional light provides
5
+ // direct light, and the second carries its far shadow map. The fragment float sunSeen is available
6
+ // to additional lighting code after lights_fragment_begin.
7
+ export function installFarShadowShader({nearDepth: NEAR_DEPTH, farDepth: FAR_DEPTH, chunks = THREE.ShaderChunk}) {
8
+ if (chunks.shadowmap_pars_fragment.includes('float sunShadow()')) throw Error('Far shadow shader already installed');
9
+ const SUN_SHADOW = /* glsl */ `
10
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 1
11
+ float farSunShadow( out float gap ) {
12
+ DirectionalLightShadow fs = directionalLightShadows[ 1 ];
13
+ vec3 c = vDirectionalShadowCoord[ 1 ].xyz / vDirectionalShadowCoord[ 1 ].w;
14
+ c.z += fs.shadowBias;
15
+ gap = 0.0;
16
+ if ( any( lessThan( c, vec3( 0.0 ) ) ) || any( greaterThan( c, vec3( 1.0 ) ) ) ) return 1.0;
17
+ vec2 t = c.xy * fs.shadowMapSize - 0.5, b = floor( t ), k = t - b, px = 1.0 / fs.shadowMapSize, uv = ( b + 0.5 ) * px;
18
+ vec4 d = vec4(
19
+ unpackRGBAToDepth( texture2D( directionalShadowMap[ 1 ], uv ) ),
20
+ unpackRGBAToDepth( texture2D( directionalShadowMap[ 1 ], uv + vec2( px.x, 0.0 ) ) ),
21
+ unpackRGBAToDepth( texture2D( directionalShadowMap[ 1 ], uv + vec2( 0.0, px.y ) ) ),
22
+ unpackRGBAToDepth( texture2D( directionalShadowMap[ 1 ], uv + px ) ) );
23
+ vec4 lit = step( vec4( c.z ), d );
24
+ gap = ( c.z - min( min( d.x, d.y ), min( d.z, d.w ) ) ) * ${FAR_DEPTH.toFixed(1)};
25
+ return mix( 1.0, mix( mix( lit.x, lit.y, k.x ), mix( lit.z, lit.w, k.x ), k.y ), fs.shadowIntensity );
26
+ }
27
+ float sunShadow() {
28
+ float gap, farS = farSunShadow( gap );
29
+ vec4 nc = vDirectionalShadowCoord[ 0 ];
30
+ vec2 edge = abs( nc.xy / nc.w - 0.5 ) * 2.0;
31
+ float inner = ( 1.0 - smoothstep( 0.8, 0.97, max( edge.x, edge.y ) ) ) * step( nc.z, 1.0 );
32
+ if ( inner <= 0.0 ) return farS;
33
+ DirectionalLightShadow ns = directionalLightShadows[ 0 ];
34
+ float nearS = getShadow( directionalShadowMap[ 0 ], ns.shadowMapSize, ns.shadowIntensity, ns.shadowBias, ns.shadowRadius, nc );
35
+ float reach = nc.z * ${NEAR_DEPTH.toFixed(1)};
36
+ return mix( farS, min( nearS, mix( 1.0, farS, smoothstep( reach - 25.0, reach, gap ) ) ), inner );
37
+ }
38
+ #elif defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
39
+ float sunShadow() {
40
+ DirectionalLightShadow ns = directionalLightShadows[ 0 ];
41
+ return getShadow( directionalShadowMap[ 0 ], ns.shadowMapSize, ns.shadowIntensity, ns.shadowBias, ns.shadowRadius, vDirectionalShadowCoord[ 0 ] );
42
+ }
43
+ #endif
44
+ `;
45
+ const nativeDepth = /* glsl */ `
46
+ #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 1
47
+ float farVisibility(vec4 coord) {
48
+ DirectionalLightShadow farLight = directionalLightShadows[1];
49
+ return getShadow(directionalShadowMap[1], farLight.shadowMapSize, farLight.shadowIntensity,
50
+ farLight.shadowBias, farLight.shadowRadius, coord);
51
+ }
52
+ float sunShadow() {
53
+ vec4 nearCoord = vDirectionalShadowCoord[0], farCoord = vDirectionalShadowCoord[1];
54
+ vec3 nd = nearCoord.xyz / nearCoord.w;
55
+ vec2 edge = abs(nd.xy - 0.5) * 2.0;
56
+ float inside = (1.0 - smoothstep(0.8, 0.97, max(edge.x, edge.y))) * step(0.0,nd.z) * step(nd.z,1.0);
57
+ float distant = farVisibility(farCoord);
58
+ if (inside <= 0.0) return distant;
59
+ DirectionalLightShadow ns = directionalLightShadows[0];
60
+ float close = getShadow(directionalShadowMap[0], ns.shadowMapSize, ns.shadowIntensity, ns.shadowBias, ns.shadowRadius, nearCoord);
61
+ // A second depth comparison sees only blockers beyond the near camera's first plane. Native
62
+ // comparison samplers support this test without exposing the stored depth.
63
+ #ifdef USE_REVERSED_DEPTH_BUFFER
64
+ farCoord.z += farCoord.w * (1.0 - nd.z) * ${NEAR_DEPTH.toFixed(1)} / ${FAR_DEPTH.toFixed(1)};
65
+ #else
66
+ farCoord.z -= farCoord.w * nd.z * ${NEAR_DEPTH.toFixed(1)} / ${FAR_DEPTH.toFixed(1)};
67
+ #endif
68
+ return mix(distant, min(close, farVisibility(farCoord)), inside);
69
+ }
70
+ #elif defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
71
+ float sunShadow() {
72
+ DirectionalLightShadow ns = directionalLightShadows[0];
73
+ return getShadow(directionalShadowMap[0], ns.shadowMapSize, ns.shadowIntensity, ns.shadowBias, ns.shadowRadius, vDirectionalShadowCoord[0]);
74
+ }
75
+ #endif
76
+ `;
77
+ const OWN_LOOP = /* glsl */ `float sunSeen = 1.0;
78
+ #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
79
+ DirectionalLight directionalLight;
80
+ #pragma unroll_loop_start
81
+ for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
82
+ #if NUM_DIR_LIGHT_SHADOWS < 2 || UNROLLED_LOOP_INDEX != 1
83
+ directionalLight = directionalLights[ i ];
84
+ getDirectionalLightInfo( directionalLight, directLight );
85
+ #if defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX == 0 && NUM_DIR_LIGHT_SHADOWS > 0
86
+ sunSeen = ( directLight.visible && receiveShadow && dot( geometryNormal, directLight.direction ) > 0.0 ) ? sunShadow() : 1.0;
87
+ directLight.color *= sunSeen;
88
+ #endif
89
+ RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
90
+ #endif
91
+ }
92
+ #pragma unroll_loop_end
93
+ #endif
94
+ #if ( NUM_RECT_AREA_LIGHTS > 0 )`;
95
+ const dirLoop = /#if \( NUM_DIR_LIGHTS > 0 \) && defined\( RE_Direct \)[\s\S]*?#if \( NUM_RECT_AREA_LIGHTS > 0 \)/;
96
+ if (!dirLoop.test(chunks.lights_fragment_begin)) throw new Error('far-shadow: Three.js lighting chunk not as expected');
97
+ chunks.lights_fragment_begin = chunks.lights_fragment_begin.replace(dirLoop, OWN_LOOP);
98
+ chunks.shadowmap_pars_fragment += Number(THREE.REVISION) <= 170 ? SUN_SHADOW : nativeDepth;
99
+
100
+ }
101
+
102
+ // Fit a coarse, texel-aligned directional shadow volume over sampled terrain ahead of the camera.
103
+ export function createFarShadow({scene, camera, direction, ground, config: FAR, mapSize, active = () => true}) {
104
+ const FAR_DEPTH = FAR.lift + FAR.back - 1;
105
+ const farSun = new THREE.DirectionalLight(0x000000, 0);
106
+ farSun.castShadow = true;
107
+ farSun.shadow.mapSize.set(mapSize, mapSize);
108
+ farSun.shadow.autoUpdate = false;
109
+ farSun.shadow.bias = -FAR.bias / FAR_DEPTH;
110
+ farSun.shadow.normalBias = FAR.normalBias;
111
+ farSun.shadow.camera.near = 1;
112
+ farSun.shadow.camera.far = FAR_DEPTH + 1;
113
+ scene.add(farSun);
114
+ scene.add(farSun.target);
115
+
116
+ const drawn = { x: NaN, z: NaN, dir: new THREE.Vector3(), age: 0 };
117
+ function setFarShadow(size) {
118
+ const on = size > 0;
119
+ if (farSun.castShadow !== on) farSun.castShadow = on;
120
+ if (on && farSun.shadow.mapSize.x !== size) {
121
+ farSun.shadow.mapSize.set(size, size);
122
+ if (farSun.shadow.map) {
123
+ farSun.shadow.map.dispose();
124
+ farSun.shadow.map = null;
125
+ }
126
+ }
127
+ drawn.x = NaN;
128
+ }
129
+ const RELIEF_STEPS = 8,
130
+ SPAN_STEP = FAR.range / 4;
131
+ const snapToTexels = createShadowSnap();
132
+ function fitFar(x, z) {
133
+ const L = direction,
134
+ sinE = Math.max(0.05, L.y),
135
+ cosE = Math.sqrt(1 - sinE * sinE),
136
+ R = FAR.range,
137
+ baseHeight = ground(x, z),
138
+ y0 = Number.isFinite(baseHeight) ? baseHeight : 0;
139
+ let low = y0,
140
+ high = y0;
141
+ for (let i = 0; i <= RELIEF_STEPS; i++)
142
+ for (let j = 0; j <= RELIEF_STEPS; j++) {
143
+ const h = ground(x + R * ((2 * i) / RELIEF_STEPS - 1), z + R * ((2 * j) / RELIEF_STEPS - 1));
144
+ if (!Number.isFinite(h)) continue;
145
+ if (h < low) low = h;
146
+ else if (h > high) high = h;
147
+ }
148
+ const bottom = Math.max(-R, -R * sinE + (low - y0) * cosE - 10),
149
+ top = Math.min(R, R * sinE + (high + FAR.above - y0) * cosE),
150
+ span = Math.min(2 * R, Math.ceil((top - bottom) / SPAN_STEP) * SPAN_STEP),
151
+ size = farSun.shadow.mapSize.x,
152
+ across = (2 * R) / size,
153
+ upward = span / size;
154
+ const c = farSun.shadow.camera;
155
+ c.left = -R;
156
+ c.right = R;
157
+ c.bottom = Math.round((top + bottom - span) / 2 / upward) * upward;
158
+ c.top = c.bottom + span;
159
+ c.updateProjectionMatrix();
160
+ snapToTexels(farSun.target.position, x, y0, z, L, across, upward);
161
+ farSun.position.copy(farSun.target.position).addScaledVector(L, FAR.lift);
162
+ }
163
+ function updateFarShadow(dt) {
164
+ if (!farSun.castShadow || !active()) return;
165
+ drawn.age += dt;
166
+ const yaw = camera.rotation.y,
167
+ x = camera.position.x - Math.sin(yaw) * FAR.range * FAR.lead,
168
+ z = camera.position.z - Math.cos(yaw) * FAR.range * FAR.lead;
169
+ const moved = !(Math.hypot(x - drawn.x, z - drawn.z) < FAR.step),
170
+ turned = direction.dot(drawn.dir) < FAR.turn;
171
+ if (!moved && !turned && drawn.age < FAR.every) return;
172
+ fitFar(x, z);
173
+ drawn.x = x;
174
+ drawn.z = z;
175
+ drawn.dir.copy(direction);
176
+ drawn.age = 0;
177
+ farSun.shadow.needsUpdate = true;
178
+ }
179
+
180
+ function dispose() {
181
+ farSun.removeFromParent();
182
+ farSun.target.removeFromParent();
183
+ farSun.shadow.dispose();
184
+ }
185
+ return {light: farSun, setSize: setFarShadow, update: updateFarShadow, dispose};
186
+ }