roamwright 0.1.1 → 0.4.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 (120) hide show
  1. package/CONTRIBUTING.md +39 -8
  2. package/README.md +74 -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/foliage.js +47 -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/index-parts.js +60 -0
  23. package/geometry/instance-visibility.js +41 -0
  24. package/geometry/instances.js +23 -0
  25. package/geometry/outline-grid.js +46 -0
  26. package/geometry/part-ranges.js +18 -0
  27. package/geometry/path-field.js +65 -0
  28. package/geometry/sagging-tube.js +58 -0
  29. package/geometry/sampled-surface.js +101 -0
  30. package/geometry/scatter-grid.js +32 -0
  31. package/geometry/sculpt.js +263 -0
  32. package/geometry/shore-grid.js +67 -0
  33. package/geometry/strata-field.js +339 -0
  34. package/geometry/strata-tiles.js +215 -0
  35. package/geometry/stream.js +94 -0
  36. package/geometry/terrain-chunks.js +304 -0
  37. package/geometry/terrain-extension.js +44 -0
  38. package/math/cell-edge.js +44 -0
  39. package/math/cloth-textures.js +83 -0
  40. package/math/cloud-textures.js +112 -0
  41. package/math/color.js +29 -0
  42. package/math/mountain-ranges.js +463 -0
  43. package/math/particle-noise.js +48 -0
  44. package/math/periodic.js +20 -0
  45. package/math/rock-texture.js +56 -0
  46. package/math/surface-textures.js +241 -0
  47. package/motion/arm-reach.js +74 -0
  48. package/motion/biped-stride.js +276 -0
  49. package/motion/crowd-alarms.js +127 -0
  50. package/motion/crowd-routine.js +183 -0
  51. package/motion/daily-clock.js +59 -0
  52. package/motion/ground-lookahead.js +29 -0
  53. package/motion/instance-sight.js +84 -0
  54. package/motion/quadruped.js +332 -0
  55. package/motion/weather.js +59 -0
  56. package/motion/wind.js +27 -0
  57. package/package.json +6 -4
  58. package/rendering/caster-motion.js +79 -0
  59. package/rendering/cell-lod.js +184 -0
  60. package/rendering/cloud-dome.js +371 -0
  61. package/rendering/cloud-field.js +83 -0
  62. package/rendering/compilation-schedule.js +34 -0
  63. package/rendering/contact-shadows.js +79 -0
  64. package/rendering/crowd-skinning.js +133 -0
  65. package/rendering/crust.js +28 -0
  66. package/rendering/daylight.js +50 -0
  67. package/rendering/far-shadow.js +186 -0
  68. package/rendering/flocks.js +323 -0
  69. package/rendering/garment-material.js +110 -0
  70. package/rendering/glow-lines.js +74 -0
  71. package/rendering/glow-shell.js +90 -0
  72. package/rendering/hair-strands.js +67 -0
  73. package/rendering/height-haze.js +129 -0
  74. package/rendering/height-probe.js +91 -0
  75. package/rendering/interior-mapping.js +19 -0
  76. package/rendering/light-budget.js +222 -0
  77. package/rendering/light-points.js +51 -0
  78. package/rendering/light-shafts.js +131 -0
  79. package/rendering/local-lights.js +28 -0
  80. package/rendering/low-light.js +13 -0
  81. package/rendering/material-lod.js +110 -0
  82. package/rendering/particle-emitters.js +223 -0
  83. package/rendering/particles.js +297 -0
  84. package/rendering/piece-batch.js +74 -20
  85. package/rendering/planar-reflection.js +175 -0
  86. package/rendering/post-shaders.js +21 -1
  87. package/rendering/post.js +4 -0
  88. package/rendering/rain-rings.js +22 -0
  89. package/rendering/road-surface.js +63 -0
  90. package/rendering/sea-shaders.js +230 -0
  91. package/rendering/shader-warmup.js +197 -0
  92. package/rendering/shadow-alignment.js +28 -0
  93. package/rendering/shadow-depth.js +129 -0
  94. package/rendering/sky-occlusion.js +187 -0
  95. package/rendering/sky.js +169 -0
  96. package/rendering/stage-lights.js +209 -0
  97. package/rendering/static-point-shadow.js +119 -0
  98. package/rendering/strata-material.js +93 -0
  99. package/rendering/stream-flow.js +36 -0
  100. package/rendering/surface-light.js +22 -0
  101. package/rendering/surface-projection.js +69 -0
  102. package/rendering/talus.js +26 -0
  103. package/rendering/terrain-rock.js +48 -0
  104. package/rendering/texture-fills.js +68 -0
  105. package/rendering/viewport.js +9 -0
  106. package/rendering/wakes.js +99 -0
  107. package/rendering/water-material.js +288 -0
  108. package/runtime/device-quality.js +27 -0
  109. package/runtime/diagnostic-log.js +80 -0
  110. package/runtime/events.js +14 -0
  111. package/runtime/first-use.js +3 -1
  112. package/runtime/frame-budget.js +49 -0
  113. package/runtime/frame-yield.js +14 -0
  114. package/runtime/gpu-timing.js +6 -3
  115. package/runtime/grid-cache.js +88 -0
  116. package/runtime/grid-rows.js +9 -0
  117. package/runtime/module-preload.js +15 -0
  118. package/runtime/search.js +69 -0
  119. package/runtime/spatial-audio.js +57 -0
  120. package/scripts/serve.py +26 -0
@@ -0,0 +1,288 @@
1
+ import * as THREE from 'three';
2
+ import { FOAM_GLSL, SEA_BODY, SEA_OPACITY, SEA_WAVES } from './sea-shaders.js';
3
+ import { RAIN_GLSL, RAIN_PARS } from './rain-rings.js';
4
+ import { STREAM_FLOW_GLSL } from './stream-flow.js';
5
+ import { DEEP, FAR } from '../geometry/stream.js';
6
+
7
+ export function createWaterMaterials({ depthRect, level, seaParameters, wakes, cloudShader = 'float cloudShade(vec2 p) { return 1.0; }', cloudUniforms = {} }) {
8
+ const { WAKE_GLSL, WAKE_PARS, wakeUniforms } = wakes;
9
+ const waterMat = new THREE.ShaderMaterial({
10
+ transparent: true,
11
+ depthWrite: false,
12
+ fog: true,
13
+ uniforms: THREE.UniformsUtils.merge([
14
+ THREE.UniformsLib.fog,
15
+ {
16
+ uTime: { value: 0 },
17
+ uSunDir: { value: new THREE.Vector3() },
18
+ uSunCol: { value: new THREE.Color() },
19
+ uHorizon: { value: new THREE.Color() },
20
+ uZenith: { value: new THREE.Color() },
21
+ uDeep: { value: new THREE.Color() },
22
+ uHasDepth: { value: 1 },
23
+ uGust: { value: 0 }, // how hard a squall's wind blows: it raises the waves
24
+ uLum: { value: 1 },
25
+ uRefl: { value: null },
26
+ uReflM: { value: new THREE.Matrix4() },
27
+ uReflOn: { value: 0 },
28
+ uHarbour: { value: Array.from({ length: 3 }, () => new THREE.Vector4()) },
29
+ uDepthR: { value: depthRect.clone() }, // where the depth map lies: uv = xy + world.xz * zw
30
+ uLevel: { value: level }, // still water, which a stream's ribbon fades into
31
+ uRain: { value: 0 }, // the rain falling where the viewer is, 0 to 1
32
+ uTint: { value: new THREE.Color(1, 1, 1) }, // the water's own colour over the light's (a lake's `tint`: lime-white water is turquoise)
33
+ },
34
+ ]),
35
+ vertexShader: `/* glsl */
36
+ #include <common>
37
+ #include <fog_pars_vertex>
38
+ attribute vec2 aCurrent; attribute vec3 aFlow; attribute vec4 aBank;
39
+ varying vec3 vW, vFlow; varying vec2 vCurrent; varying vec4 vBank;
40
+ void main(){
41
+ vec4 wp = modelMatrix * vec4(position, 1.0); vW = wp.xyz;
42
+ vFlow = aFlow; vCurrent = aCurrent; vBank = aBank;
43
+ vec4 mvPosition = viewMatrix * wp; gl_Position = projectionMatrix * mvPosition;
44
+ #include <fog_vertex>
45
+ }`,
46
+ fragmentShader: `/* glsl */
47
+ uniform float uTime, uHasDepth, uLum, uReflOn, uGust; uniform vec3 uSunDir, uSunCol, uHorizon, uZenith, uDeep; uniform sampler2D uDepth, uRefl; uniform mat4 uReflM;
48
+ uniform vec4 uHarbour[3], uDepthR; uniform float uLevel; uniform vec3 uTint;
49
+ varying vec3 vW, vFlow; varying vec2 vCurrent; varying vec4 vBank;
50
+ #include <common>
51
+ #include <fog_pars_fragment>
52
+ ${cloudShader}
53
+ ${FOAM_GLSL}
54
+ ${WAKE_PARS}
55
+ ${RAIN_PARS}
56
+ #ifdef STREAM_RIFFLES
57
+ uniform vec2 uStreamSpeed;
58
+ ${STREAM_FLOW_GLSL}
59
+ #endif
60
+ #ifdef SEA
61
+ ${seaParameters}
62
+ #endif
63
+ vec2 wv(vec2 p, vec2 d, float f, float s, float a){ return d * (f * a * cos(dot(d, p) * f + uTime * s)); }
64
+ vec2 ripple(vec2 offset, vec2 stretch, float range, float phase) {
65
+ vec2 q = offset * stretch;
66
+ float d = length(q), amp = smoothstep(0.04, 0.45, d) * (1.0 - smoothstep(0.4, range, d));
67
+ return q * stretch * (amp * cos(d * 8.0 - uTime * 3.1 + phase) / max(d, 0.04));
68
+ }
69
+ void main(){
70
+ vec3 V = cameraPosition - vW; float dist = max(length(V), 0.001); V /= dist;
71
+ vec2 depthUv = uDepthR.xy + vW.xz * uDepthR.zw;
72
+ vec3 bed = texture2D(uDepth, depthUv).rgb;
73
+ float dep = mix(vBank.x, bed.r * 10.0 - 2.0, uHasDepth);
74
+ #ifdef SEA
75
+ // past the depth map's edge, whose last row its lookup repeats, the sea's depth is the one its sheet carries at each
76
+ // vertex, over the ground carried out there; and what the map says
77
+ // of its bed (calm water, a shore) is let go there, or a cape's calm shallows ran on past the edge as a band to the horizon
78
+ vec2 pastUv = max(-depthUv, depthUv - 1.0);
79
+ float pastEdge = smoothstep(0.0, 300.0, max(pastUv.x, pastUv.y) / uDepthR.z) * uHasDepth;
80
+ dep = mix(dep, vBank.x, pastEdge);
81
+ bed.gb *= 1.0 - pastEdge;
82
+ #endif
83
+ float waterline = max(dep, 0.0);
84
+ float flow = clamp(length(vCurrent), 0.0, 1.0);
85
+ vec2 p = vW.xz; p += 1.7 * vec2(sin(p.y * 0.071 + uTime * 0.09) + 0.6 * sin(p.y * 0.23 - p.x * 0.11), cos(p.x * 0.063 - uTime * 0.07) + 0.6 * cos(p.x * 0.19 + p.y * 0.13)); // bend the wave trains so they never line up
86
+ // the size of a pixel on the water, along its longer side (at a grazing look, the way the eye looks): waves finer than that
87
+ // are left out, or they shimmer as the eye moves; read from the picture itself, so a smaller picture or a lower look leaves out more
88
+ float fp = max(dist * 0.0016 / max(V.y, 0.04), max(length(dFdx(vW.xz)), length(dFdy(vW.xz))));
89
+ #define OW(f) (1.0 - smoothstep(1.5, 3.6, fp * f))
90
+ vec2 g = wv(p, vec2(0.8,0.6), 0.33, 1.0, 0.24) * OW(0.33) + wv(p, vec2(-0.5,0.866), 0.61, 1.45, 0.13) * OW(0.61)
91
+ + wv(p, vec2(0.2,-0.98), 1.37, 2.2, 0.055) * OW(1.37) + wv(p, vec2(-0.93,-0.36), 2.9, 3.0, 0.024) * OW(2.9)
92
+ + wv(p, vec2(0.6,-0.8), 6.3, 4.4, 0.009) * OW(6.3);
93
+ float nearW = 1.0 / (1.0 + dist * 0.03);
94
+ g += (wv(p, vec2(0.36,0.93), 11.0, 5.6, 0.005) * OW(11.0) + wv(p, vec2(-0.86,0.5), 17.0, 7.1, 0.0032) * OW(17.0) + wv(p, vec2(0.97,-0.24), 27.0, 9.0, 0.002) * OW(27.0) + wv(p, vec2(-0.3,-0.95), 43.0, 12.0, 0.0012) * OW(43.0)) * nearW;
95
+ float gust = sin(p.x * 0.013 + uTime * 0.05) * sin(p.y * 0.017 - uTime * 0.04) + 0.5 * sin(dot(p, vec2(0.031, -0.022)) + uTime * 0.07);
96
+ g *= (0.5 + 0.6 * smoothstep(-0.8, 0.9, gust)) * (1.0 + 1.3 * uGust); // calm slicks and wind-roughened patches; a squall's wind raises it all
97
+ g *= mix(0.39, 1.0, smoothstep(0.0, 2.9, waterline)) * (1.0 - uHasDepth * bed.b * 0.55);
98
+ float currentFleck = 0.0, rapid = 0.0;
99
+ if (flow > 0.01) {
100
+ vec2 downstream = vCurrent / flow, transverse = vec2(-downstream.y, downstream.x);
101
+ #ifdef STREAM_RIFFLES
102
+ vec4 motion = streamFlow(vFlow, vBank.w, dep, uTime * mix(uStreamSpeed.x, uStreamSpeed.y, vFlow.z), dist, fp);
103
+ g = mix(downstream * motion.y + transverse * motion.x, g, 0.22);
104
+ currentFleck = motion.z;
105
+ rapid = motion.w;
106
+ #else
107
+ float speed = mix(1.4, 4.5, vFlow.z), run = vFlow.y, crossRun = vFlow.x;
108
+ float drift = sin(crossRun * 2.1) * 0.18 + cos(crossRun * 4.1) * 0.1;
109
+ float phase = run * 3.6 - uTime * speed * (2.4 + drift) + sin(crossRun * 2.8 + run * 0.14) * 1.7;
110
+ float moving = run - uTime * speed;
111
+ float crease = moving * 1.15 + cos(crossRun * 9.5 + moving * 0.17) * 1.3;
112
+ float threads = sin(crossRun * 7.5 + cos(moving * 0.43)) * cos(moving * 0.68 + crossRun * 8.1);
113
+ vec2 current = downstream * (0.06 * cos(phase) * OW(3.6) + 0.09 * cos(crease) * OW(1.15))
114
+ + transverse * (0.052 * threads + 0.055 * cos(phase) * OW(3.6));
115
+ g = mix(current, g, 0.16);
116
+ currentFleck = smoothstep(0.61, 0.99, sin(crease)) * smoothstep(0.35, 0.9, threads) * (0.08 + 0.32 * vFlow.z) * OW(3.6);
117
+ // white water where the bed falls steeply: streaks of foam racing downstream, thickest in the fast middle, with darker
118
+ // tongues of smooth water between them and quieter water along the edges
119
+ float steep = smoothstep(0.28, 0.8, vFlow.z);
120
+ float streak = 0.5 + 0.5 * sin(crossRun * 11.0 + 2.0 * cos(moving * 0.9));
121
+ // the churn's bands wander (their phase bent by slower waves), or from the air they lay across the river as even stripes
122
+ float churn = 0.5 + 0.5 * sin(moving * 2.3 + crossRun * 5.0 + 1.6 * sin(moving * 0.37 + crossRun * 1.9))
123
+ * cos(moving * 0.7 - crossRun * 3.0 + 0.9 * sin(moving * 0.21 - crossRun * 0.8));
124
+ float banded = smoothstep(0.42, 0.95, streak * 0.55 + churn * 0.7) * mix(0.6, 1.0, OW(2.3));
125
+ // far off, or once the bands are finer than a pixel, the foam is drawn as the share of the water it covers
126
+ float even = max(smoothstep(45.0, 220.0, dist), 1.0 - OW(2.3));
127
+ rapid = steep * mix(banded, 0.38, even) * max(1.0 - 0.5 * crossRun * crossRun, 0.0) * smoothstep(0.3, 1.6, dep);
128
+ #endif
129
+ // a spring: rings spreading from the eye of its pool, where the water wells up
130
+ float eye = length(vBank.zw);
131
+ g += (downstream * vBank.z + transverse * vBank.w) * (exp(-eye * 0.8) * 0.2 * cos(eye * 5.2 - uTime * 3.3) / max(eye, 0.08) * OW(5.2));
132
+ }
133
+ if (uHasDepth > 0.5 && dist < 160.0) {
134
+ vec2 harbourRipples = vec2(0.0);
135
+ for (int i = 0; i < 3; i++) {
136
+ vec4 pier = uHarbour[i]; vec2 d = vec2(cos(pier.w - 10.0), sin(pier.w - 10.0)), r = vW.xz - pier.xy, q = vec2(dot(r, d), d.x * r.y - d.y * r.x);
137
+ if (pier.w < 0.5 || abs(q.y) > 12.0 || q.x < -13.0 || q.x > 41.0) continue;
138
+ float pile = clamp(floor((q.x - 3.0) / 6.0 + 0.5), 0.0, 5.0);
139
+ harbourRipples += ripple(q - vec2(3.0 + 6.0 * pile, sign(q.y) * 1.9), vec2(1.0), 3.8, pile);
140
+ harbourRipples += ripple(q - vec2(6.0, pier.z * 4.2), vec2(0.45, 1.0), 5.5, 1.9);
141
+ harbourRipples += ripple(q - vec2(21.0, -pier.z * 3.6), vec2(0.6, 1.0), 4.5, 3.6);
142
+ }
143
+ g += harbourRipples * 0.19 * OW(8.0);
144
+ }
145
+ #ifdef SEA
146
+ ${SEA_WAVES}
147
+ #endif
148
+ ${WAKE_GLSL}
149
+ ${RAIN_GLSL}
150
+ float fade = 1.0 / (1.0 + dist * 0.011);
151
+ vec3 N = normalize(vec3(-g.x * fade, 1.0, -g.y * fade));
152
+ float fres = 0.03 + 0.97 * pow(1.0 - max(dot(N, V), 0.0), 5.0);
153
+ vec3 R = reflect(-V, N); R.y = abs(R.y);
154
+ vec3 sky = mix(uHorizon, uZenith, pow(R.y, 0.5));
155
+ if (uReflOn > 0.01) { // the mirrored view of shore, city and sky, bent by the waves
156
+ vec4 rc = uReflM * vec4(vW, 1.0);
157
+ if (rc.w > 0.0001) {
158
+ // far off and at a grazing look the waves average out and the shore's thin band of reflection must stay where it is
159
+ float bend = clamp(V.y * 4.0, 0.15, 1.0) / (1.0 + dist * 0.02);
160
+ vec3 rf = texture2D(uRefl, clamp(rc.xy / rc.w + N.xz * vec2(0.12, 0.2) * bend, 0.003, 0.997)).rgb;
161
+ if (rf.r >= 0.0 && rf.g >= 0.0 && rf.b >= 0.0) sky = mix(sky, min(rf, vec3(24.0)), uReflOn);
162
+ }
163
+ }
164
+ float rs = max(dot(R, uSunDir), 0.0);
165
+ float lap = dep + 0.17 * sin(uTime * 1.25 + p.x * 0.29 + p.y * 0.21);
166
+ float breaks = sin(p.x * 0.53 + p.y * 0.73 - uTime * 1.15) * sin(p.y * 0.94 - p.x * 0.32) + 0.33 * gust;
167
+ float foam = uHasDepth * smoothstep(0.06, 0.22, lap) * (1.0 - smoothstep(0.27, 0.64, lap))
168
+ * smoothstep(0.24, 0.74, breaks) * bed.g * (1.0 - bed.b * 0.85) * OW(2.9);
169
+ #ifdef SEA
170
+ foam = 0.0; // the sea's white water is its own (rapid)
171
+ #endif
172
+ float shallow = 1.0 - smoothstep(0.0, 4.2, waterline);
173
+ vec3 silt = mix(vec3(0.045, 0.057, 0.030), vec3(0.043, 0.103, 0.082), bed.g);
174
+ vec3 body = mix(uDeep, silt * uLum + uDeep * 0.60, shallow);
175
+ body = mix(body, vec3(0.064, 0.084, 0.069) * uLum, flow * 0.82 * (1.0 - smoothstep(1.5, 6.0, waterline))); // running water is clouded by what it carries, but a channel's deep middle takes the depth's colour as still water does: a river was one flat grey-green beside the lake it ran into
176
+ #ifdef SEA
177
+ ${SEA_BODY}
178
+ #endif
179
+ body *= uTint;
180
+ float lit = cloudShade(vW.xz); // under a cloud the water lies darker, and the sun's glitter all but goes out
181
+ body *= lit;
182
+ float far = max(smoothstep(30.0, 700.0, dist), smoothstep(0.02, 0.5, fp));
183
+ vec3 col = mix(body, sky, fres) + uSunCol * (lit * lit * lit) * (pow(rs, mix(900.0, 70.0, far)) * mix(10.0, 1.3, far) + pow(rs, 14.0) * 0.12) + vec3(0.58, 0.66, 0.61) * (foam * 0.47 + currentFleck * 0.47) * uLum;
184
+ col = mix(col, vec3(0.78, 0.84, 0.82) * uLum, rapid * 0.86);
185
+ float opacity = mix(0.16, 0.92, 1.0 - exp(-waterline * 0.51 / max(V.y, 0.32)));
186
+ #ifdef SEA
187
+ ${SEA_OPACITY}
188
+ #endif
189
+ float edge = mix(1.0, smoothstep(-0.11, 0.21, dep), uHasDepth);
190
+ #ifdef SEA
191
+ // the sea's sheet lies under the whole land: where the map's A says the water over the bed is a lake's, only the lake's own
192
+ // sheet is drawn, or a pit's lake whose bed sinks below the sea showed the sea's level through it as a patch
193
+ if (vW.y < uLevel + 0.5) edge *= texture2D(uDepth, depthUv).a;
194
+ #endif
195
+ float riverEdge = vBank.y * smoothstep(0.1, 1.0, vBank.x) * mix(1.0, 0.83, flow * shallow); // a ribbon thins out over its banks and at its head, and its running shallows show their bed
196
+ float riverMouth = 1.0 - flow * (1.0 - smoothstep(uLevel + 0.02, uLevel + 0.5, vW.y)) * smoothstep(2.15, 2.8, bed.r * 10.0);
197
+ gl_FragColor = vec4(col, mix(opacity, 1.0, max(max(fres, foam * 0.45), rapid)) * edge * riverEdge * riverMouth);
198
+ #include <tonemapping_fragment>
199
+ #include <colorspace_fragment>
200
+ #include <fog_fragment>
201
+ }`,
202
+ });
203
+ Object.assign(waterMat.uniforms, wakeUniforms, cloudUniforms); // after the merge, which would copy them: shared, not copied
204
+ const streamMat = waterMat.clone(); // streams and open sea: no bed to read
205
+ Object.assign(streamMat.uniforms, wakeUniforms, cloudUniforms);
206
+ streamMat.uniforms.uHasDepth.value = 0;
207
+ streamMat.uniforms.uRefl = { value: null };
208
+ for (const material of [waterMat, streamMat]) stillByDefault(material);
209
+ return { waterMat, streamMat };
210
+ }
211
+ // Preserve the live lighting, clock and wake uniforms when specializing a water material.
212
+ function waterVariant(material) {
213
+ const m = material.clone();
214
+ Object.assign(m.defaultAttributeValues, material.defaultAttributeValues);
215
+ Object.assign(m.uniforms, material.uniforms);
216
+ return m;
217
+ }
218
+
219
+ export function tintedWater(material, tint) {
220
+ const m = waterVariant(material);
221
+ m.uniforms.uTint = { value: new THREE.Color(...tint) };
222
+ return m;
223
+ }
224
+
225
+ // Speeds are metres per second on level and steep reaches, respectively.
226
+ export function rippledStream(material, { speed, rapidSpeed = speed }) {
227
+ const m = waterVariant(material);
228
+ m.defines = { ...m.defines, STREAM_RIFFLES: '' };
229
+ m.uniforms.uStreamSpeed = { value: new THREE.Vector2(speed, rapidSpeed) };
230
+ return m;
231
+ }
232
+ // A sheet of open water has no current, banks or spring of its own.
233
+ function stillByDefault(material) {
234
+ material.defaultAttributeValues.aCurrent = [0, 0];
235
+ material.defaultAttributeValues.aFlow = [0, 0, 0];
236
+ material.defaultAttributeValues.aBank = [DEEP, 1, FAR, FAR];
237
+ }
238
+ // A sheet of open water that shows only in part: at each of its vertices, shareAt(x, z) of it (0 to 1, x and z its own).
239
+ export function partSheet(geometry, shareAt) {
240
+ const pos = geometry.attributes.position,
241
+ bank = new Float32Array(pos.count * 4);
242
+ for (let v = 0; v < pos.count; v++) bank.set([DEEP, shareAt(pos.getX(v), pos.getZ(v)), FAR, FAR], v * 4);
243
+ geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
244
+ return geometry;
245
+ }
246
+ // A sheet of open water that knows the depth of the bed under each of its vertices past its depth map (depthAt(index), in
247
+ // metres, or null where the map tells it).
248
+ export function sheetDepths(geometry, depthAt) {
249
+ const count = geometry.attributes.position.count,
250
+ bank = new Float32Array(count * 4);
251
+ for (let v = 0; v < count; v++) bank.set([depthAt(v) ?? DEEP, 1, FAR, FAR], v * 4);
252
+ geometry.setAttribute('aBank', new THREE.BufferAttribute(bank, 4));
253
+ return geometry;
254
+ }
255
+ const SHARED = [
256
+ 'uTime',
257
+ 'uSunDir',
258
+ 'uSunCol',
259
+ 'uHorizon',
260
+ 'uZenith',
261
+ 'uLum',
262
+ 'uDeep',
263
+ 'uGust',
264
+ 'uCloudField',
265
+ 'uCloudSh',
266
+ 'uWake',
267
+ 'uWakeS',
268
+ 'uRain',
269
+ ];
270
+ export function landWater(waterMat, depth, rect, level, sea = null) {
271
+ const make = (hasDepth, own) => {
272
+ const m = waterMat.clone();
273
+ for (const k of SHARED) if (waterMat.uniforms[k]) m.uniforms[k] = waterMat.uniforms[k];
274
+ m.uniforms.uDepth = { value: depth };
275
+ m.uniforms.uDepthR.value.copy(rect);
276
+ m.uniforms.uLevel.value = level;
277
+ m.uniforms.uHasDepth.value = hasDepth;
278
+ m.uniforms.uRefl = { value: null };
279
+ if (own) {
280
+ Object.assign(m.uniforms, own);
281
+ m.defines = { SEA: '' };
282
+ }
283
+ stillByDefault(m);
284
+ return m;
285
+ };
286
+ return { open: make(1, sea), stream: make(0) };
287
+ }
288
+
@@ -0,0 +1,27 @@
1
+ const SOFTWARE = /swiftshader|llvmpipe|software|basic render/i;
2
+ const INTEGRATED = /intel|mali|adreno|powervr/i;
3
+
4
+ export function createDeviceQuality({
5
+ renderer, handheld = () => false, memoryGB = () => undefined, cores = () => undefined,
6
+ smallMemory = 2, phoneMemory = 4, desktopMemory = 8, desktopCores = 8,
7
+ }) {
8
+ // The first renderer query can block on outstanding GPU work. Cache its result for future quality changes.
9
+ let card = null;
10
+ function cardName() {
11
+ if (card !== null) return card;
12
+ const gl = renderer.getContext(),
13
+ info = gl.getExtension('WEBGL_debug_renderer_info');
14
+ return (card = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER)));
15
+ }
16
+ // True where the browser draws in software, with no graphics card: hardware acceleration is switched off, or the card is refused.
17
+ const drawnInSoftware = () => SOFTWARE.test(cardName());
18
+ function deviceQuality() {
19
+ const gpu = cardName(),
20
+ memory = memoryGB() ?? Infinity,
21
+ threads = cores() ?? desktopCores;
22
+ if (SOFTWARE.test(gpu) || memory <= smallMemory) return 'low';
23
+ if (handheld()) return memory <= phoneMemory ? 'low' : 'medium';
24
+ return threads < desktopCores || memory < desktopMemory || INTEGRATED.test(gpu) ? 'medium' : 'high';
25
+ }
26
+ return { deviceQuality, drawnInSoftware };
27
+ }
@@ -0,0 +1,80 @@
1
+ /** Bounded diagnostic entries, scoped to a page, visit and storage key. */
2
+ export function createDiagnosticLog({
3
+ storageKey, page = globalThis, capacity = 300, saveDelayMs = 1500,
4
+ idleMs = 5000, textLimit = 600, perSecond = 20, visit = Date.now().toString(36),
5
+ }) {
6
+ let placeOf = () => '';
7
+ function stored() {
8
+ try {
9
+ const list = JSON.parse(page.localStorage.getItem(storageKey));
10
+ return Array.isArray(list) ? list : [];
11
+ } catch {
12
+ return []; // storage refused (a private window) or spoilt: start afresh
13
+ }
14
+ }
15
+ const entries = stored();
16
+ let saving = 0,
17
+ burstAt = 0,
18
+ burst = 0,
19
+ dropped = 0;
20
+ const whenIdle = page.requestIdleCallback ? fn => page.requestIdleCallback(fn, { timeout: idleMs }) : fn => page.setTimeout(fn, 0);
21
+ const saveSoon = () => whenIdle(save);
22
+ function save() {
23
+ saving = 0;
24
+ try {
25
+ page.localStorage.setItem(storageKey, JSON.stringify(entries));
26
+ } catch {
27
+ // storage full or refused: the log lives on in this visit
28
+ }
29
+ }
30
+
31
+ function noteLog(kind, text) {
32
+ const second = Math.floor(page.performance.now() / 1000);
33
+ if (second !== burstAt) {
34
+ burstAt = second;
35
+ burst = 0;
36
+ }
37
+ if (++burst > perSecond) {
38
+ dropped++;
39
+ return;
40
+ }
41
+ if (dropped) {
42
+ const left = dropped;
43
+ dropped = 0;
44
+ noteLog('warn', `${left} entries of the page's log left out: more than ${perSecond} came in one second`);
45
+ }
46
+ const words = String(text).slice(0, textLimit),
47
+ last = entries[entries.length - 1];
48
+ if (last && last.visit === visit && last.kind === kind && last.text === words) last.n = (last.n || 1) + 1;
49
+ else {
50
+ const entry = { t: new Date().toISOString(), kind, text: words, at: page.location.pathname + page.location.search, visit };
51
+ if (kind !== 'note') entry.ctx = where();
52
+ entries.push(entry);
53
+ if (entries.length > capacity) entries.splice(0, entries.length - capacity);
54
+ }
55
+ if (!saving) saving = page.setTimeout(saveSoon, saveDelayMs);
56
+ }
57
+
58
+ function where() {
59
+ try {
60
+ return placeOf();
61
+ } catch {
62
+ return ''; // asked while the modules that know are still loading
63
+ }
64
+ }
65
+ function setLogPlace(say) {
66
+ placeOf = say;
67
+ }
68
+
69
+ const flushes = [];
70
+ const beforeLogRead = flush => flushes.push(flush);
71
+ function readLog(kind) {
72
+ for (let i = 0; i < flushes.length; i++) flushes[i]();
73
+ return kind ? entries.filter(e => e.kind === kind) : entries.slice();
74
+ }
75
+ function clearLog() {
76
+ entries.length = 0;
77
+ save();
78
+ }
79
+ return { beforeLogRead, clearLog, noteLog, readLog, save, setLogPlace };
80
+ }
@@ -0,0 +1,14 @@
1
+ // Independent synchronous event channels. Listeners run in registration order.
2
+ export function createEvents() {
3
+ const listeners = new Map();
4
+ function on(name, listener) {
5
+ const list = listeners.get(name);
6
+ if (list) list.push(listener);
7
+ else listeners.set(name, [listener]);
8
+ }
9
+ function emit(name, ...args) {
10
+ const list = listeners.get(name);
11
+ if (list) for (const listener of list) listener(...args);
12
+ }
13
+ return { on, emit };
14
+ }
@@ -4,17 +4,19 @@
4
4
  * a timeout drains requests that would otherwise never resolve.
5
5
  */
6
6
  export function createFirstUse({ renderer, waitMs = 250, now = () => performance.now() }) {
7
+ const initialized = new WeakSet();
7
8
  const waiting = [];
8
9
  const asked = [];
9
10
  let frameBegan = -Infinity;
10
11
 
11
12
  function useProgram(program) {
12
- if (!program.program) return;
13
+ if (!program.program || initialized.has(program.program)) return;
13
14
  const gl = renderer.getContext();
14
15
  const previous = renderer.debug.checkShaderErrors;
15
16
  try {
16
17
  renderer.debug.checkShaderErrors = previous && !gl.getProgramParameter(program.program, gl.LINK_STATUS);
17
18
  program.getUniforms();
19
+ initialized.add(program.program);
18
20
  } finally {
19
21
  renderer.debug.checkShaderErrors = previous;
20
22
  }
@@ -0,0 +1,49 @@
1
+ // Register synchronous, indivisible steps once. The caller retains its queue, priorities and
2
+ // cancellation policy. A rejected step did no work and can be tried again next frame.
3
+ export function createFrameBudget({ frameMs = 1000 / 60, workMs = 3, reserveMs = 6, maxWaitMs = 100, now = () => performance.now() } = {}) {
4
+ if (!(frameMs > 0 && workMs > 0 && reserveMs >= 0 && reserveMs < frameMs && maxWaitMs >= 0)) throw new RangeError('Invalid frame budget');
5
+ let previous,
6
+ deadline = Infinity,
7
+ remaining = Infinity,
8
+ allowance = workMs;
9
+ let reserved,
10
+ next,
11
+ oldest = Infinity;
12
+ function begin(timestamp = now()) {
13
+ if (previous !== undefined && timestamp - previous > 1.5 * frameMs) allowance = Math.max(workMs / 4, allowance / 2);
14
+ else allowance = Math.min(workMs, allowance + workMs / 8);
15
+ previous = timestamp;
16
+ deadline = timestamp + frameMs - reserveMs;
17
+ remaining = allowance;
18
+ reserved = next;
19
+ next = undefined;
20
+ oldest = Infinity;
21
+ }
22
+ function task(step) {
23
+ let waitingSince;
24
+ return function tryStep(...args) {
25
+ const start = now();
26
+ if (remaining <= 0 || start >= deadline) {
27
+ waitingSince ??= start;
28
+ // Give the longest-waiting producer from the previous frame one turn. If its
29
+ // work disappears, callers simply stop retrying and the reservation expires.
30
+ if (reserved !== tryStep || start - waitingSince < maxWaitMs) {
31
+ if (waitingSince < oldest) {
32
+ oldest = waitingSince;
33
+ next = tryStep;
34
+ }
35
+ return false;
36
+ }
37
+ }
38
+ if (reserved === tryStep) reserved = undefined;
39
+ waitingSince = undefined;
40
+ try {
41
+ step.apply(this, args);
42
+ } finally {
43
+ remaining -= now() - start;
44
+ }
45
+ return true;
46
+ };
47
+ }
48
+ return { begin, task };
49
+ }
@@ -0,0 +1,14 @@
1
+ // A timer also releases the caller when animation frames are suspended.
2
+ export const nextFrame = (maxWaitMs = 50) =>
3
+ new Promise(resolve => {
4
+ const done = () => {
5
+ clearTimeout(timer);
6
+ cancelAnimationFrame(frame);
7
+ resolve();
8
+ };
9
+ const timer = setTimeout(done, maxWaitMs),
10
+ frame = requestAnimationFrame(done);
11
+ });
12
+ // A promise kept once the next frame has been painted: a task queued from the frame's own callback runs after its paint. What
13
+ // was just put on the page is then on the screen before a long job begins.
14
+ export const painted = (maxWaitMs = 50) => nextFrame(maxWaitMs).then(() => new Promise(resolve => setTimeout(resolve, 0)));
@@ -31,15 +31,18 @@ export function createGpuTiming(renderer) {
31
31
  return new Promise(resolve => {
32
32
  const ask = () => {
33
33
  const at = performance.now(),
34
- waiting = gl.clientWaitSync(fence, 0, 0) === gl.TIMEOUT_EXPIRED;
34
+ status = gl.clientWaitSync(fence, 0, 0),
35
+ waiting = status === gl.TIMEOUT_EXPIRED;
35
36
  if (waiting && at - since < GIVE_UP_MS) {
36
37
  asked++;
37
- nextTask(ask);
38
+ // A queued GPU frame can take tens of milliseconds. Leave the page thread
39
+ // free between observations. The channel resets nested timer clamping.
40
+ setTimeout(() => nextTask(ask), 1);
38
41
  return;
39
42
  }
40
43
  gl.deleteSync(fence);
41
44
  if (waiting && !globalThis.document?.hidden) blocks = true; // not passed in all that time on a page that is being shown: fences do not work here
42
- resolve({ at, prompt: asked === 0, gaveUp: waiting });
45
+ resolve({ at, prompt: asked === 0, gaveUp: waiting || status === gl.WAIT_FAILED });
43
46
  };
44
47
  nextTask(ask);
45
48
  });
@@ -0,0 +1,88 @@
1
+ // Persist typed grid arrays in IndexedDB. A synchronous hint lets a consumer
2
+ // start computing immediately on a cold visit. A missing hint is always safe.
3
+ export function createGridCache({ database, store, build, revisions, hintPrefix }) {
4
+ const revisionOf = name => revisions ? Object.hasOwn(revisions, name) && revisions[name] : build;
5
+ const recordKey = (name, revision) => revisions ? [name, revision] : revision + ' ' + name;
6
+
7
+ function obsolete(key, name, revision) {
8
+ if (!revisions) return !String(key).startsWith(build + ' ');
9
+ // Drop legacy build-wide records. With individual revisions, retire only this grid's older copies.
10
+ return !Array.isArray(key) || (key[0] === name && key[1] !== revision);
11
+ }
12
+
13
+ function open() {
14
+ return new Promise(resolve => {
15
+ try {
16
+ const request = indexedDB.open(database, 1);
17
+ let blocked = false;
18
+ request.onupgradeneeded = () => request.result.createObjectStore(store);
19
+ request.onblocked = () => { blocked = true; resolve(null); };
20
+ request.onerror = () => resolve(null);
21
+ request.onsuccess = () => {
22
+ if (blocked) request.result.close();
23
+ else resolve(request.result);
24
+ };
25
+ } catch {
26
+ resolve(null);
27
+ }
28
+ });
29
+ }
30
+
31
+ function hasKept(name) {
32
+ try {
33
+ const revision = revisionOf(name);
34
+ return !!revision && localStorage.getItem(hintPrefix + name) === revision;
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ async function takeKept(name, arrays) {
41
+ const revision = revisionOf(name);
42
+ if (!revision) return false;
43
+ const db = await open();
44
+ if (!db) return false;
45
+ try {
46
+ const kept = await new Promise((resolve, reject) => {
47
+ const request = db.transaction(store).objectStore(store).get(recordKey(name, revision));
48
+ request.onsuccess = () => resolve(request.result);
49
+ request.onerror = () => reject(request.error);
50
+ });
51
+ if (!Array.isArray(kept) || kept.length !== arrays.length ||
52
+ !kept.every((a,i) => ArrayBuffer.isView(a) && a.constructor === arrays[i].constructor && a.length === arrays[i].length)) return false;
53
+ arrays.forEach((array,i) => array.set(kept[i]));
54
+ return true;
55
+ } catch {
56
+ return false;
57
+ } finally {
58
+ db.close();
59
+ }
60
+ }
61
+
62
+ async function keep(name, arrays) {
63
+ const revision = revisionOf(name);
64
+ if (!revision) return;
65
+ const db = await open();
66
+ if (!db) return;
67
+ try {
68
+ await new Promise((resolve, reject) => {
69
+ const transaction = db.transaction(store, 'readwrite');
70
+ transaction.oncomplete = resolve;
71
+ transaction.onabort = () => reject(transaction.error);
72
+ const records = transaction.objectStore(store);
73
+ const keys = records.getAllKeys();
74
+ keys.onsuccess = () => {
75
+ for (const key of keys.result) if (obsolete(key, name, revision)) records.delete(key);
76
+ };
77
+ records.put(arrays, recordKey(name, revision));
78
+ });
79
+ localStorage.setItem(hintPrefix + name, revision);
80
+ } catch {
81
+ // A refused or full store can be retried on the next visit.
82
+ } finally {
83
+ db.close();
84
+ }
85
+ }
86
+
87
+ return { hasKept, takeKept, keep };
88
+ }
@@ -0,0 +1,9 @@
1
+ // Rows of baked grids, cut out to be sent from a worker and put back in their place on the page. A grid is a typed array of
2
+ // `rows` rows, with any number of values to a row (a height, three of a normal, four of a cover).
3
+
4
+ // Copy the half-open row interval [j0, j1) from each grid.
5
+ const cutRows = (grids, rows, j0, j1) => grids.map(grid => grid.slice((j0 * grid.length) / rows, (j1 * grid.length) / rows));
6
+ // Puts what cutRows cut back into grids of the same shapes, from row j0 on.
7
+ const pasteRows = (grids, rows, j0, cut) => grids.forEach((grid, i) => grid.set(cut[i], (j0 * grid.length) / rows));
8
+
9
+ export { cutRows, pasteRows };
@@ -0,0 +1,15 @@
1
+ /** Preload dependency URLs once per loader, relative to the caller's module. */
2
+ export function createModulePreloader(base, document = globalThis.document) {
3
+ const requested = new Set();
4
+ return files => {
5
+ for (const file of files) {
6
+ const url = new URL(file, base).href;
7
+ if (requested.has(url)) continue;
8
+ const link = document.createElement('link');
9
+ link.rel = 'modulepreload';
10
+ link.href = url;
11
+ document.head.appendChild(link);
12
+ requested.add(url);
13
+ }
14
+ };
15
+ }