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,332 @@
1
+ import * as THREE from 'three';
2
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
3
+ import { createNoise, createRenderContext, createUnitShapes, GeometryBuilder, mulberry32 } from 'roamwright';
4
+ import { heightfieldSampler } from 'roamwright/geometry/heightfield.js';
5
+ import { createCameraGuard } from './viaduct-camera.js';
6
+ import { alpineRiver, branchWhorl, valleySky } from './viaduct-landscape.js';
7
+ import { C, stick, TRS } from 'roamwright/geometry/primitives.js';
8
+
9
+ const canvas = document.querySelector('canvas');
10
+ const { renderer, camera, scene, worldGroup } = createRenderContext(canvas, { fov: 41 });
11
+ const seed = Number(new URL(location.href).searchParams.get('seed') ?? 42) | 0;
12
+ const noise = createNoise(seed);
13
+ const { fbm, ridged } = noise;
14
+ const random = mulberry32(seed);
15
+ const shapes = createUnitShapes(fbm);
16
+ const material = new THREE.MeshStandardMaterial({ vertexColors: true, flatShading: true });
17
+ const smoothstep = THREE.MathUtils.smoothstep;
18
+ const peaks = [
19
+ // x, z, summit elevation and horizontal radius
20
+ [-144, -112, 61, 86], [-91, -122, 78, 87], [-42, -142, 58, 76],
21
+ [12, -119, 73, 65], [54, -134, 79, 76], [105, -107, 62, 74], [152, -138, 74, 79],
22
+ ];
23
+ const channel = z => 8 * Math.sin(z * 0.067) + 5 * Math.sin(z * 0.029);
24
+
25
+ function elevation(x, z) {
26
+ const bank = Math.abs(x - channel(z));
27
+ const roughness = fbm(x * 0.065, z * 0.065, 4, 12);
28
+ const foothills = smoothstep(bank, 5, 66) * (15 + 15 * roughness);
29
+ let summit = 0;
30
+ for (const [cx, cz, top, radius] of peaks) {
31
+ const dx = x - cx, dz = z - cz;
32
+ const angle = Math.atan2(dz, dx);
33
+ const spine = 1 + 0.19 * Math.cos(angle * 3 + cx) + 0.12 * Math.sin(angle * 5 + cz);
34
+ summit = Math.max(summit, top * (1 - Math.hypot(dx, dz) / (radius * spine)));
35
+ }
36
+ const folds = ridged(x * 0.045, z * 0.045, 4, 8);
37
+ const mountains = summit + smoothstep(summit, 2, 28) * (21 * folds - 13);
38
+ const valley = -2 + smoothstep(bank, 3, 15) * (3 + roughness * 4) + foothills;
39
+ let height = Math.max(valley, mountains - 3);
40
+ // A level rail cutting ends at the two tunnel mouths. Rock covers the train beyond them.
41
+ const end = Math.abs(x);
42
+ const corridor = smoothstep(end, 35, 46) * (1 - smoothstep(Math.abs(z), 3.1, 9));
43
+ const cutting = THREE.MathUtils.lerp(18, 29, smoothstep(end, 52, 57));
44
+ height += (cutting - height) * corridor;
45
+ return height;
46
+ }
47
+
48
+ // Color the same height field by elevation and slope. Steep faces retain exposed rock near the snowline.
49
+ const ground = new THREE.PlaneGeometry(390, 385, 320, 330).rotateX(-Math.PI / 2).translate(0, 0, -24.5);
50
+ const positions = ground.attributes.position;
51
+ for (let i = 0; i < positions.count; i++) positions.setY(i, elevation(positions.getX(i), positions.getZ(i)));
52
+ ground.computeVertexNormals();
53
+ const colors = new Float32Array(positions.count * 3);
54
+ const grass = new THREE.Color(0x839062), gravel = new THREE.Color(0xc6b690);
55
+ const rock = new THREE.Color(0x6d7377), snow = new THREE.Color(0xf3efe4);
56
+ const tint = new THREE.Color();
57
+ for (let i = 0; i < positions.count; i++) {
58
+ const x = positions.getX(i), y = positions.getY(i), z = positions.getZ(i);
59
+ const grain = fbm(x * 0.16, z * 0.16, 3, 91);
60
+ const bedding = Math.cos(y * 1.8 + x * 0.44 + 5 * grain);
61
+ const up = ground.attributes.normal.getY(i);
62
+ tint.copy(gravel).lerp(grass, smoothstep(y + grain * 2, 1, 6));
63
+ tint.lerp(rock, Math.max(1 - smoothstep(up, 0.59, 0.84), smoothstep(y + grain * 6, 27, 40)));
64
+ tint.multiplyScalar(1 - 0.24 * smoothstep(y, 28, 41) * smoothstep(bedding, 0.1, 0.94));
65
+ tint.lerp(snow, smoothstep(y + 36 * up + grain * 14, 80, 89));
66
+ tint.multiplyScalar(0.78 + 0.35 * grain).toArray(colors, i * 3);
67
+ }
68
+ ground.setAttribute('color', new THREE.BufferAttribute(colors, 3));
69
+ const hillside = new THREE.Mesh(ground, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.94 }));
70
+ hillside.receiveShadow = true;
71
+ worldGroup.add(hillside);
72
+
73
+ worldGroup.add(alpineRiver(channel, elevation, noise));
74
+
75
+ const structures = new GeometryBuilder();
76
+ const deck = 18, span = 12, radius = 4.7, spring = 10;
77
+ function extrude(shape, depth) {
78
+ return new THREE.ExtrudeGeometry(shape, { depth, bevelEnabled: false, curveSegments: 12 }).translate(0, 0, -depth / 2);
79
+ }
80
+
81
+ // Reuse one arch profile in every span. A projecting ring of wedge stones follows its inner curve.
82
+ const arch = new THREE.Shape();
83
+ arch.moveTo(-span / 2, -3);
84
+ arch.lineTo(-radius, -3);
85
+ arch.absarc(0, spring, radius, Math.PI, 0, true);
86
+ arch.lineTo(radius, -3);
87
+ arch.lineTo(span / 2, -3);
88
+ arch.lineTo(span / 2, deck);
89
+ arch.lineTo(-span / 2, deck);
90
+ arch.closePath();
91
+ const archShape = extrude(arch, 4);
92
+ const wedge = new THREE.Shape();
93
+ const angle = Math.PI / 15;
94
+ wedge.moveTo(radius, 0);
95
+ wedge.lineTo(radius + 0.7, 0);
96
+ wedge.absarc(0, 0, radius + 0.7, 0, angle - 0.006, false);
97
+ wedge.absarc(0, 0, radius, angle - 0.006, 0, true);
98
+ wedge.closePath();
99
+ const wedgeShape = extrude(wedge, 4.2);
100
+ // Fit short courses around the arch opening, staggering the joints on each course.
101
+ function facing(x, row, left, right) {
102
+ const bottom = row * 0.83;
103
+ const offset = row % 2 === 0 ? 0 : 1.1;
104
+ for (let joint = -span / 2 - offset; joint < right; joint += 2.2) {
105
+ const a = Math.max(left, joint), b = Math.min(right, joint + 2.2);
106
+ if (b - a < 0.12) continue;
107
+ structures.box(x + (a + b) / 2, bottom, 0, b - a - 0.035, 0.79, 4.04, C(0xbca68b, 0.07, random));
108
+ }
109
+ }
110
+ for (let x = -42; x <= 42; x += span) {
111
+ structures.add(archShape, C(0xb19c7d), TRS(x, 0, 0));
112
+ for (let row = 0; (row + 1) * 0.83 <= deck; row++) {
113
+ const rise = Math.max(0, row * 0.83 - spring);
114
+ const opening = Math.sqrt(Math.max(0, (radius + 0.5) ** 2 - rise ** 2));
115
+ facing(x, row, -span / 2, -opening);
116
+ facing(x, row, opening, span / 2);
117
+ }
118
+ for (let i = 0; i < 15; i++) {
119
+ structures.add(wedgeShape, C(0xd0b99a, 0.12, random), TRS(x, spring, 0, 1, 1, 1, 0, 0, i * angle));
120
+ }
121
+ }
122
+ structures.box(0, deck, 0, 96, 0.45, 4.6, C(0xd8c5a4));
123
+ for (const z of [-2, 2]) structures.box(0, deck + 0.45, z, 96, 0.55, 0.3, C(0x9d8972));
124
+ structures.box(0, deck + 0.42, 0, 112, 0.13, 3, C(0x776554));
125
+ for (let x = -55; x <= 55; x += 0.9) structures.box(x, deck + 0.55, 0, 0.21, 0.11, 2.35, C(0x624e3c));
126
+ for (const z of [-0.8, 0.8]) structures.box(0, deck + 0.66, z, 112, 0.18, 0.12, C(0x414342));
127
+
128
+ const tunnel = new THREE.Shape();
129
+ tunnel.moveTo(-radius, -3);
130
+ tunnel.absarc(0, spring, radius, Math.PI, 0, true);
131
+ tunnel.lineTo(radius, -3);
132
+ tunnel.closePath();
133
+ const tunnelInterior = extrude(tunnel, 0.25);
134
+ const portalBase = deck - 4.5;
135
+ // Scale a copy of the stone arch around each tunnel entrance, perpendicular to the bridge.
136
+ for (const side of [-1, 1]) {
137
+ structures.add(tunnelInterior, C(0x252a27), TRS(side * 55, portalBase, 0, 0.59, 0.77, 1, side * Math.PI / 2));
138
+ structures.add(archShape, C(0x917d67), TRS(side * 53, portalBase, 0, 0.59, 0.77, 1, side * Math.PI / 2));
139
+ for (let i = 0; i < 15; i++) {
140
+ const matrix = TRS(side * 53, portalBase + spring * 0.77, 0, 0.59, 0.77, 1, side * Math.PI / 2).clone();
141
+ matrix.multiply(new THREE.Matrix4().makeRotationZ(i * angle));
142
+ structures.add(wedgeShape, C(0xbda884), matrix);
143
+ }
144
+ }
145
+ // Cantilevers keep the contact wire above the track. Only the upper cable sags.
146
+ const iron = C(0x475550), copper = C(0x554634);
147
+ for (let x = -48; x <= 48; x += 16) {
148
+ const foot = deck + 1;
149
+ structures.box(x, foot, -2, 0.19, 6.4, 0.19, iron);
150
+ stick(structures, [x, foot + 5.45, -2], [x, foot + 6.2, 0.5], 0.105, iron);
151
+ stick(structures, [x, foot + 4.7, -2], [x, foot + 6.12, 0.25], 0.08, iron);
152
+ if (x === 48) continue;
153
+ stick(structures, [x, foot + 5.35, 0], [x + 16, foot + 5.35, 0], 0.042, copper);
154
+ stick(structures, [x, foot + 6.08, 0], [x + 8, foot + 5.68, 0], 0.05, copper);
155
+ stick(structures, [x + 8, foot + 5.68, 0], [x + 16, foot + 6.08, 0], 0.05, copper);
156
+ stick(structures, [x + 8, foot + 5.35, 0], [x + 8, foot + 5.68, 0], 0.035, iron);
157
+ }
158
+ structures.mesh(material, worldGroup);
159
+
160
+ // The four cars travel together as one mesh, independently of the cached bridge shadows.
161
+ const carriages = new GeometryBuilder();
162
+ const roofProfile = new THREE.Shape();
163
+ roofProfile.moveTo(-1.48, 0);
164
+ roofProfile.lineTo(1.48, 0);
165
+ roofProfile.quadraticCurveTo(1.43, 0.38, 0.95, 0.4);
166
+ roofProfile.lineTo(-0.95, 0.4);
167
+ roofProfile.quadraticCurveTo(-1.43, 0.38, -1.48, 0);
168
+ const roof = extrude(roofProfile, 8.8).rotateY(Math.PI / 2);
169
+ for (const x of [-14, -5, 4, 13]) {
170
+ carriages.box(x, deck + 0.66, 0, 7.8, 0.52, 2.4, C(0x343a3a));
171
+ carriages.box(x, deck + 1.18, 0, 8.6, 2.65, 2.8, C(0x9e2824));
172
+ carriages.box(x, deck + 2.22, 0, 8.62, 1.22, 2.82, C(0xf4d9a5));
173
+ for (let offset = -3; offset <= 3; offset += 1.5) {
174
+ carriages.box(x + offset, deck + 2.36, 0, 1.1, 0.85, 2.86, C(0x344e54));
175
+ carriages.box(x + offset, deck + 2.96, 0, 1.10, 0.22, 2.865, C(0x6c878b));
176
+ }
177
+ carriages.add(roof, C(0x646b68), TRS(x, deck + 3.83, 0));
178
+ for (const end of [-3, 3]) {
179
+ carriages.box(x + end, deck + 4.18, 0, 0.9, 0.16, 1.2, C(0x45494a));
180
+ carriages.add(shapes.cyl, C(0x252b30), TRS(x + end, deck + 0.95, -1.23, 0.71, 2.46, 0.71, 0, Math.PI / 2));
181
+ }
182
+ for (const door of [-3.92, 3.92]) {
183
+ carriages.box(x + door, deck + 1.27, 0, 0.58, 2.37, 2.84, C(0x872c28));
184
+ carriages.box(x + door, deck + 2.47, 0, 0.36, 0.78, 2.87, C(0x33484a));
185
+ }
186
+ carriages.box(x, deck + 1.43, 0, 8.62, 0.12, 2.84, C(0xe3bc83));
187
+ }
188
+ carriages.box(17.32, deck + 2.42, 0, 0.12, 0.92, 2.1, C(0x34494c));
189
+ for (const z of [-1, 1]) carriages.box(17.34, deck + 1.66, z, 0.15, 0.32, 0.32, C(0xffda89));
190
+ // A sprung pickup connects the leading car to the contact wire.
191
+ for (const z of [-0.32, 0.32]) {
192
+ stick(carriages, [10.9, deck + 4.24, z], [12.25, deck + 5.28, z], 0.10, iron);
193
+ stick(carriages, [12.25, deck + 5.28, z], [11.4, deck + 6.30, z], 0.085, iron);
194
+ }
195
+ carriages.box(11.4, deck + 6.28, 0, 0.22, 0.07, 1.45, C(0x383c39));
196
+ const train = carriages.mesh(material, worldGroup, false);
197
+
198
+ // Reuse the terrain sampler for placement so trees and boulders follow each new seed.
199
+ const woodland = new GeometryBuilder();
200
+ const groundAt = heightfieldSampler(ground);
201
+ const treeCrowns = [];
202
+ const whorl = branchWhorl();
203
+ for (let i = 0; i < 3300; i++) {
204
+ const x = random() * 220 - 110, z = random() * 162 - 111;
205
+ const y = groundAt(x, z);
206
+ if (y < 2 || y > 35 || (Math.abs(z) < 4 && Math.abs(x) < 58)) continue;
207
+ const size = 2.2 + random() * 4.2;
208
+ const yaw = random() * Math.PI;
209
+ const larch = noise.vnoise(x * 0.09, z * 0.09, 93) + random() * 0.30 > 0.92;
210
+ const needles = larch ? 0xa88938 : 0x325b4b;
211
+ const halfTrunk = size * 0.065 / 2;
212
+ const root = Math.min(groundAt(x - halfTrunk, z - halfTrunk), groundAt(x - halfTrunk, z + halfTrunk),
213
+ groundAt(x + halfTrunk, z - halfTrunk), groundAt(x + halfTrunk, z + halfTrunk), y) - 0.25;
214
+ woodland.box(x, root, z, halfTrunk * 2, y + size * 0.7 - root, halfTrunk * 2, C(0x5b4738));
215
+ treeCrowns.push({ x, z, top: y + size * 1.09, radius: size * 0.28 });
216
+ for (let tier = 0; tier < 3; tier++) {
217
+ const width = size * (0.54 - tier * 0.105);
218
+ woodland.add(whorl, C(needles, 0.18, random), TRS(x, y + size * (0.12 + tier * 0.23), z, width, size * 0.51, width, yaw + tier * 0.71));
219
+ }
220
+ }
221
+ for (let i = 0; i < 520; i++) {
222
+ const z = random() * 155 - 100, x = channel(z) + (random() - 0.5) * 29;
223
+ const bed = groundAt(x, z);
224
+ if (bed > 5) continue;
225
+ const size = 0.4 + random() * 2.05;
226
+ woodland.add(shapes.rock, C(0x858884, 0.22, random), TRS(x, bed, z, size * 1.4, size, size, random() * Math.PI));
227
+ }
228
+ woodland.mesh(material, worldGroup);
229
+
230
+ scene.background = valleySky(noise);
231
+ scene.fog = new THREE.FogExp2(0xcac8bb, 0.0042);
232
+ scene.add(new THREE.HemisphereLight(0xffefda, 0x9eafba, 1.55));
233
+ const sun = new THREE.DirectionalLight(0xffdfb2, 2.45);
234
+ sun.position.set(-65, 53, 37);
235
+ sun.castShadow = true;
236
+ sun.shadow.mapSize.set(2048, 2048);
237
+ Object.assign(sun.shadow.camera, { left: -75, right: 75, top: 72, bottom: -72, near: 1, far: 195 });
238
+ sun.shadow.camera.updateProjectionMatrix();
239
+ sun.shadow.normalBias = 0.055;
240
+ // Trees and masonry cast the static shadow map once.
241
+ renderer.shadowMap.autoUpdate = false;
242
+ renderer.shadowMap.needsUpdate = true;
243
+ scene.add(sun);
244
+
245
+ const controls = new OrbitControls(camera, canvas);
246
+ controls.enablePan = false;
247
+ controls.maxPolarAngle = Math.PI * 0.49;
248
+ controls.minDistance = 6;
249
+ controls.maxDistance = 135;
250
+
251
+ const viewpoints = {
252
+ valley: { eye: [31, 29, 82], target: [0, 17, -9] },
253
+ trackside: { eye: [29, 25, 14], target: [1, 20.5, 0] },
254
+ riverbank: { eye: [13, 5.3, 38], target: [-2, 11.8, -6] },
255
+ };
256
+ const viewButtons = document.querySelectorAll('[data-view]');
257
+ function draw() {
258
+ renderer.render(scene, camera);
259
+ }
260
+ const guardCamera = createCameraGuard(ground, treeCrowns);
261
+ function drawCamera() {
262
+ guardCamera(camera);
263
+ camera.lookAt(controls.target);
264
+ draw();
265
+ }
266
+ controls.addEventListener('change', drawCamera);
267
+ function selectView(name) {
268
+ const { eye, target } = viewpoints[name];
269
+ controls.target.fromArray(target);
270
+ camera.position.fromArray(eye);
271
+ controls.update();
272
+ viewButtons.forEach(button => button.setAttribute('aria-pressed', String(button.dataset.view === name)));
273
+ draw();
274
+ }
275
+ viewButtons.forEach(button => button.addEventListener('click', () => selectView(button.dataset.view)));
276
+ document.querySelector('#seed').value = seed;
277
+
278
+ // Give keyboard explorers the same orbit and zoom gestures as pointer users.
279
+ canvas.addEventListener('keydown', event => {
280
+ const offset = camera.position.clone().sub(controls.target);
281
+ const orbit = new THREE.Spherical().setFromVector3(offset);
282
+ switch (event.key) {
283
+ case 'ArrowLeft': orbit.theta -= 0.10; break;
284
+ case 'ArrowRight': orbit.theta += 0.10; break;
285
+ case 'ArrowUp': orbit.phi -= 0.08; break;
286
+ case 'ArrowDown': orbit.phi += 0.08; break;
287
+ case '+': case '=': orbit.radius *= 0.88; break;
288
+ case '-': orbit.radius /= 0.88; break;
289
+ default: return;
290
+ }
291
+ event.preventDefault();
292
+ camera.position.setFromSpherical(orbit.makeSafe()).add(controls.target);
293
+ controls.update();
294
+ });
295
+
296
+ const trainButton = document.querySelector('#train');
297
+ const trainLabel = document.querySelector('#train-label');
298
+ let running = false, frame = 0, lastTime = 0;
299
+ function moveTrain(time) {
300
+ const elapsed = lastTime ? Math.min((time - lastTime) / 1000, 0.1) : 0;
301
+ lastTime = time;
302
+ train.position.x += elapsed * 6;
303
+ if (train.position.x >= 80) train.position.x -= 160;
304
+ train.updateMatrix();
305
+ draw();
306
+ frame = requestAnimationFrame(moveTrain);
307
+ }
308
+ function scheduleTrain() {
309
+ cancelAnimationFrame(frame);
310
+ lastTime = 0;
311
+ if (running && !document.hidden) frame = requestAnimationFrame(moveTrain);
312
+ }
313
+ trainButton.addEventListener('click', () => {
314
+ running = !running;
315
+ trainLabel.textContent = running ? 'Pause train' : 'Run train';
316
+ trainButton.firstElementChild.textContent = running ? 'Ⅱ' : '▶';
317
+ scheduleTrain();
318
+ });
319
+ document.addEventListener('visibilitychange', scheduleTrain);
320
+
321
+ function resize() {
322
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
323
+ renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
324
+ camera.aspect = canvas.clientWidth / canvas.clientHeight;
325
+ // Keep the train and several arches in frame on a narrow screen.
326
+ camera.fov = THREE.MathUtils.clamp(41 / Math.min(camera.aspect, 1), 41, 69);
327
+ camera.updateProjectionMatrix();
328
+ drawCamera();
329
+ }
330
+ window.addEventListener('resize', resize);
331
+ selectView('valley');
332
+ resize();
@@ -9,8 +9,8 @@ import { box, TRS } from './primitives.js';
9
9
  const _n3 = new THREE.Matrix3(),
10
10
  _v = new THREE.Vector3(),
11
11
  _m5 = new THREE.Matrix4();
12
- // A built geometry is never changed again, so once it is on the graphics card the copy of its arrays kept here is let go: together
13
- // they are several hundred megabytes, which a phone does not have. (Three.js calls this with the attribute as `this`.)
12
+ // Three.js calls this upload callback with the attribute as its receiver. Static
13
+ // geometry can release its CPU copy once the GPU owns the buffer.
14
14
  function releaseArray() {
15
15
  this.bytes = this.array.byteLength; // what stands on the card, for the reckoning of memory
16
16
  this.array = null;
@@ -71,8 +71,8 @@ function geometryOf(parts, sphere = null) {
71
71
  if (!sphere && points instanceof Float32Array && points.length) sphere = sphereOf(points);
72
72
  if (sphere) g.boundingSphere = new THREE.Sphere(new THREE.Vector3(sphere[0], sphere[1], sphere[2]), sphere[3]);
73
73
  else g.computeBoundingSphere();
74
- // a skinned mesh works out its own bounds the first time it is drawn, from the positions and the bones each follows, and
75
- // several meshes may share one geometry (the riders' horses): a skinned geometry keeps those three
74
+ // Skinned meshes compute bounds on the CPU. Keep their positions, joint indices
75
+ // and weights available, including when several meshes share the geometry.
76
76
  for (const name in g.attributes) if (!(parts.skinIndex && SKIN_BOUNDS.includes(name))) g.attributes[name].onUpload(releaseArray);
77
77
  return g;
78
78
  }
@@ -92,10 +92,8 @@ function stillMesh(geometry, material, shadow) {
92
92
  if (shadow) markStill(m);
93
93
  return m;
94
94
  }
95
- // A geometry of its own over another's attributes and index: the same buffers on the card, and the source's bounds (worked out
96
- // first, while its arrays are there). For instanced meshes that would share one geometry with instances of their own each: the
97
- // renderer keeps the binding of a mesh's attributes by geometry and program, so each draw of such a mesh bound every attribute
98
- // anew and made garbage doing it (hundreds a frame over a land's cover).
95
+ // Share GPU buffers and bounds while giving each instanced mesh a geometry identity
96
+ // of its own. Three.js can then reuse the vertex bindings for each mesh.
99
97
  function geometryView(source) {
100
98
  if (!source.boundingSphere) source.computeBoundingSphere();
101
99
  const view = new THREE.BufferGeometry();
@@ -104,8 +102,8 @@ function geometryView(source) {
104
102
  view.boundingSphere = source.boundingSphere.clone();
105
103
  return view;
106
104
  }
107
- const ROOM = 768, // the numbers a builder has room for when it is first filled,
108
- GROWTH = 2, // and how much more room it takes each time it runs out (doubling copies each number once on average: Aren's pass copied 15.5 million numbers growing by half)
105
+ const ROOM = 768, // initial capacity in scalar components
106
+ GROWTH = 2, // geometric growth keeps the total copying cost linear
109
107
  NO_FLOATS = new Float32Array(0),
110
108
  NO_NORMAL_BYTES = new Int8Array(0),
111
109
  NO_COLOUR_BYTES = new Uint8Array(0);
@@ -152,8 +150,8 @@ class GB {
152
150
  this.spent = false; // true once release has let the parts go
153
151
  this.wide = false; // true once a colour outside 0..1 or a normal's number outside -1..1 is put in: bytes cannot hold it
154
152
  this.skw = null;
155
- // Set `pb` to [] before filling to have each part's start noted in it (kitCells cuts a town's kit into cells by its parts);
156
- // `bounds` then holds each part's box, six numbers a part, measured before the positions are rounded to floats.
153
+ // Set pb to [] to record the start of each part. Its six bounding-box components
154
+ // are measured before vertex positions are rounded to floats.
157
155
  this.bounds = [];
158
156
  }
159
157
  // What has been filled so far, for whoever looks at it: positions, normals and colours, three numbers to a vertex.
@@ -519,8 +517,7 @@ class GB {
519
517
  build(compact = !this.wide) {
520
518
  return geometryOf(this.parts(compact));
521
519
  }
522
- // Lets go of the parts once they have been built into a geometry. A builder that stays in reach afterwards (in a closure of
523
- // the function that filled it, as in a town's builder) would otherwise hold tens of megabytes of plain numbers for good.
520
+ // Drop the backing arrays after the geometry has taken ownership of its buffers.
524
521
  release() {
525
522
  this.positions = this.normals = this.colours = NO_FLOATS;
526
523
  this.normalBytes = NO_NORMAL_BYTES;
@@ -0,0 +1,127 @@
1
+ import { sstep } from '../math/scalar.js';
2
+
3
+ /**
4
+ * `creasedSheet(builder, rows, colors, options)` triangulates a rectangular grid of XYZ points with matching linear
5
+ * RGB triples. Corner normals are area weighted over adjoining faces whose cosine is at least `crease` (default −1).
6
+ * Pass `wrap` for a closed column seam, `inside` to reverse winding, and `tint, slopeFrom, slopeTo` for optional
7
+ * upward-facing color. Degenerate triangles emit no vertices.
8
+ */
9
+ export function creasedSheet(
10
+ builder,
11
+ rows,
12
+ tones,
13
+ { wrap = false, inside = false, crease = -1, tint = null, slopeFrom = 0, slopeTo = 1 } = {},
14
+ ) {
15
+ if (rows.length < 2 || rows[0].length < 2) return;
16
+ const nv = rows.length - 1,
17
+ cols = rows[0].length,
18
+ nu = wrap ? cols : cols - 1,
19
+ faces = new Float64Array(nv * nu * 6), // each cell's two triangles' normals, as long as twice their areas
20
+ side = inside ? -1 : 1,
21
+ next = i => (wrap && i === cols - 1 ? 0 : i + 1);
22
+ const cross = (o, a, b, c, at) => {
23
+ const ux = b[0] - a[0],
24
+ uy = b[1] - a[1],
25
+ uz = b[2] - a[2],
26
+ vx = c[0] - a[0],
27
+ vy = c[1] - a[1],
28
+ vz = c[2] - a[2];
29
+ o[at] = (uy * vz - uz * vy) * side;
30
+ o[at + 1] = (uz * vx - ux * vz) * side;
31
+ o[at + 2] = (ux * vy - uy * vx) * side;
32
+ };
33
+ for (let j = 0; j < nv; j++)
34
+ for (let i = 0; i < nu; i++) {
35
+ const a = rows[j][i],
36
+ b = rows[j][next(i)],
37
+ c = rows[j + 1][next(i)],
38
+ d = rows[j + 1][i],
39
+ at = (j * nu + i) * 6;
40
+ cross(faces, a, b, c, at);
41
+ cross(faces, a, c, d, at + 3);
42
+ }
43
+ const length = at => Math.hypot(faces[at], faces[at + 1], faces[at + 2]);
44
+ // The normal at point (j, i) for the triangle whose normal starts at `own` in faces: the triangles round the point that lie
45
+ // within the crease of it, summed by their areas.
46
+ const normal = [0, 0, 0],
47
+ pointNormal = (j, i, own) => {
48
+ const ol = length(own) || 1;
49
+ normal[0] = normal[1] = normal[2] = 0;
50
+ for (let qj = j - 1; qj <= j; qj++) {
51
+ if (qj < 0 || qj >= nv) continue;
52
+ for (let s = -1; s <= 0; s++) {
53
+ let qi = i + s;
54
+ if (qi < 0) {
55
+ if (!wrap) continue;
56
+ qi += cols;
57
+ }
58
+ if (qi >= nu) continue;
59
+ // which of the cell's two triangles (a b c and a c d) have this point as a corner: b is in the first only, d in the second
60
+ const lower = qj === j,
61
+ left = qi === i,
62
+ isB = lower && !left,
63
+ isD = !lower && left;
64
+ for (let t = 0; t < 2; t++) {
65
+ if ((t === 0 && isD) || (t === 1 && isB)) continue;
66
+ const at = (qj * nu + qi) * 6 + t * 3,
67
+ l = length(at);
68
+ if (l < 1e-12) continue;
69
+ if ((faces[at] * faces[own] + faces[at + 1] * faces[own + 1] + faces[at + 2] * faces[own + 2]) / (l * ol) < crease) continue;
70
+ normal[0] += faces[at];
71
+ normal[1] += faces[at + 1];
72
+ normal[2] += faces[at + 2];
73
+ }
74
+ }
75
+ }
76
+ const l = Math.hypot(normal[0], normal[1], normal[2]);
77
+ if (l < 1e-12) {
78
+ normal[0] = faces[own] / ol;
79
+ normal[1] = faces[own + 1] / ol;
80
+ normal[2] = faces[own + 2] / ol;
81
+ } else for (let k = 0; k < 3; k++) normal[k] /= l;
82
+ return normal;
83
+ };
84
+ const corner = (j, i, own) => {
85
+ const p = rows[j][i],
86
+ n = pointNormal(j, i, own),
87
+ tone = tones[j][i],
88
+ lay = tint ? sstep(slopeFrom, slopeTo, n[1]) : 0;
89
+ builder.raw(
90
+ p[0],
91
+ p[1],
92
+ p[2],
93
+ n[0],
94
+ n[1],
95
+ n[2],
96
+ tone[0] + (tint ? (tint[0] - tone[0]) * lay : 0),
97
+ tone[1] + (tint ? (tint[1] - tone[1]) * lay : 0),
98
+ tone[2] + (tint ? (tint[2] - tone[2]) * lay : 0),
99
+ );
100
+ };
101
+ for (let j = 0; j < nv; j++)
102
+ for (let i = 0; i < nu; i++) {
103
+ const at = (j * nu + i) * 6,
104
+ i1 = next(i);
105
+ // a b c, then a c d; seen from inside, a c b and a d c
106
+ if (length(at) > 1e-12) {
107
+ corner(j, i, at);
108
+ if (inside) {
109
+ corner(j + 1, i1, at);
110
+ corner(j, i1, at);
111
+ } else {
112
+ corner(j, i1, at);
113
+ corner(j + 1, i1, at);
114
+ }
115
+ }
116
+ if (length(at + 3) > 1e-12) {
117
+ corner(j, i, at + 3);
118
+ if (inside) {
119
+ corner(j + 1, i, at + 3);
120
+ corner(j + 1, i1, at + 3);
121
+ } else {
122
+ corner(j + 1, i1, at + 3);
123
+ corner(j + 1, i, at + 3);
124
+ }
125
+ }
126
+ }
127
+ }
@@ -0,0 +1,97 @@
1
+ import { Vector3 } from 'three';
2
+ import { triangle } from './sculpt.js';
3
+ import { dim } from '../math/color.js';
4
+ import { clamp, lerp, sstep, TAU } from '../math/scalar.js';
5
+
6
+ const MM = 0.001,
7
+ ATTACH_REACH = 0.91, // the ear's foot sinks under the sampled skull to cover gaps in the rendered grid
8
+ ATTACH_SPAN = [0.63, 0.38]; // the foot is taller than it is deep, relative to the rim
9
+ const _a = new Vector3(), _b = new Vector3(), _c = new Vector3();
10
+
11
+ // Model a pinna around the sampled ear root. Height is the head's origin in the builder's frame, in metres.
12
+ function buildEar(body, head, s, height, skin, bone) {
13
+ const RINGS = [0, 0.2, 0.4, 0.58, 0.76, 0.9, 1],
14
+ SPOKES = 14,
15
+ warm = clamp(skin[0] * 2.2, 0, 1),
16
+ root = new Vector3();
17
+ head.point(-8, s * 1.72, root, null);
18
+ const at = (i, j) => {
19
+ const r = RINGS[i],
20
+ a = (j / SPOKES) * TAU,
21
+ up = Math.sin(a),
22
+ back = (15.5 * Math.cos(a) * (1 + 0.14 * up) + 1) * r - 2 * (1 - r),
23
+ high = 31 * up * r + 2 * (1 - r),
24
+ rim = sstep(-0.8, -0.45, up) + sstep(-0.45, -0.8, up) * 0.3,
25
+ relief =
26
+ 3 * rim * sstep(0.72, 0.9, r) * (1 - 0.4 * sstep(0.92, 1, r)) +
27
+ 2 * sstep(-0.9, -0.3, Math.cos(a)) * sstep(-0.75, -0.2, up) * Math.exp(-((r - 0.5) * (r - 0.5)) / 0.012) -
28
+ 7 * sstep(0.42, 0.1, r) +
29
+ 3 * Math.exp(-((a - Math.PI) * (a - Math.PI)) / 0.16 - ((r - 0.8) * (r - 0.8)) / 0.04),
30
+ out = 1 + (back + 16) * 0.42 + relief;
31
+ return [
32
+ root.x + s * out * MM,
33
+ root.y + height + high * MM,
34
+ root.z - (back + high * 0.18) * MM,
35
+ s,
36
+ 0,
37
+ 0,
38
+ dim(skin, (1 - 0.4 * sstep(0.45, 0.1, r)) * (1 + 0.08 * warm)),
39
+ ];
40
+ };
41
+ const P = [];
42
+ for (let i = 0; i < RINGS.length; i++) for (let j = 0; j <= SPOKES; j++) P.push(at(i, j % SPOKES));
43
+ const p = (i, j) => P[i * (SPOKES + 1) + j];
44
+ // normals from the neighbours round and across the shell, kept pointing away from the head
45
+ for (let i = 0; i < RINGS.length; i++)
46
+ for (let j = 0; j <= SPOKES; j++) {
47
+ const a = p(i, (j + 1) % SPOKES),
48
+ b = p(i, (j + SPOKES - 1) % SPOKES),
49
+ c = p(Math.min(RINGS.length - 1, i + 1), j),
50
+ d = p(Math.max(0, i - 1), j);
51
+ _a.set(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
52
+ _b.set(c[0] - d[0], c[1] - d[1], c[2] - d[2]);
53
+ _c.crossVectors(_a, _b).normalize();
54
+ if (!(_c.lengthSq() > 0.5)) _c.set(s, 0, 0);
55
+ if (_c.x * s < 0) _c.negate();
56
+ const v = p(i, j);
57
+ v[3] = _c.x;
58
+ v[4] = _c.y;
59
+ v[5] = _c.z;
60
+ }
61
+ for (let i = 0; i < RINGS.length - 1; i++)
62
+ for (let j = 0; j < SPOKES; j++) {
63
+ if (i) triangle(body, p(i, j), p(i, j + 1), p(i + 1, j + 1), null, bone);
64
+ triangle(body, p(i, j), p(i + 1, j + 1), p(i + 1, j), null, bone);
65
+ }
66
+
67
+ // Turn the rim into the side of the skull. A single unbacked shell opens against the sky from behind.
68
+ const rim = P.slice(-(SPOKES + 1), -1).map(point => point.slice());
69
+ const foot = rim.map(point => {
70
+ const y = lerp(root.y, point[1] - height, ATTACH_SPAN[0]),
71
+ z = lerp(root.z, point[2], ATTACH_SPAN[1]);
72
+ let inside = 0, outside = Math.abs(point[0]);
73
+ for (let i = 0; i < 12; i++) {
74
+ const x = (inside + outside) / 2;
75
+ if (head.reach(x, y, z) < ATTACH_REACH) inside = x;
76
+ else outside = x;
77
+ }
78
+ return [s * inside, height + y, z, 0, 0, 0, point[6]];
79
+ });
80
+ for (let j = 0; j < SPOKES; j++) {
81
+ const before = rim[(j + SPOKES - 1) % SPOKES], after = rim[(j + 1) % SPOKES],
82
+ edge = rim[j], base = foot[j];
83
+ _a.set(after[0] - before[0], after[1] - before[1], after[2] - before[2]);
84
+ _b.set(base[0] - edge[0], base[1] - edge[1], base[2] - edge[2]);
85
+ _c.crossVectors(_b, _a).normalize().multiplyScalar(s);
86
+ edge[3] = base[3] = _c.x;
87
+ edge[4] = base[4] = _c.y;
88
+ edge[5] = base[5] = _c.z;
89
+ }
90
+ for (let j = 0; j < SPOKES; j++) {
91
+ const next = (j + 1) % SPOKES;
92
+ triangle(body, rim[j], rim[next], foot[next], null, bone);
93
+ triangle(body, rim[j], foot[next], foot[j], null, bone);
94
+ }
95
+ }
96
+
97
+ export { buildEar };