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,300 @@
1
+ import * as THREE from 'three';
2
+ import { SRGB2LIN } from '../math/color.js';
3
+ import { clamp } from '../math/scalar.js';
4
+
5
+ const _normal = [0, 0, 0]; // scratch of buildChunkGeometry
6
+
7
+ // A land's normal at grid point k, into out: from its normals, or worked out (normalAt) by a land that has let them go.
8
+ function normalOf(land, k, out) {
9
+ const n = land.normals;
10
+ if (!n) return land.normalAt(k, out);
11
+ out[0] = n[k * 3];
12
+ out[1] = n[k * 3 + 1];
13
+ out[2] = n[k * 3 + 2];
14
+ return out;
15
+ }
16
+ // Sample one chunk's grid, with skirts below its edges to hide cracks between resolutions.
17
+ // A land may draw its mesh lower at some points (`sunkAt(k)`, metres), under an overlaid higher-resolution mesh.
18
+ function buildChunkGeometry(land, ci, cj, lod) {
19
+ const { cells, stride, spacing, x0, z0, heights, colors, bedY, sunkAt } = land;
20
+ const step = 1 << lod,
21
+ n = cells / step,
22
+ m = n + 3;
23
+ const pos = new Float32Array(m * m * 3),
24
+ nor = new Float32Array(m * m * 3),
25
+ col = new Float32Array(m * m * 3),
26
+ uv = new Float32Array(m * m * 2);
27
+ let p = 0;
28
+ for (let b = 0; b < m; b++) {
29
+ const jj = clamp(b - 1, 0, n),
30
+ sb = b === 0 || b === m - 1;
31
+ for (let a = 0; a < m; a++, p++) {
32
+ const ii = clamp(a - 1, 0, n),
33
+ skirt = sb || a === 0 || a === m - 1;
34
+ const gi = ci * cells + ii * step,
35
+ gj = cj * cells + jj * step,
36
+ k = gj * stride + gi;
37
+ const x = x0 + gi * spacing,
38
+ z = z0 + gj * spacing;
39
+ pos[p * 3] = x;
40
+ pos[p * 3 + 1] = heights[k] - (skirt ? 5 + 5 * lod : 0) - (sunkAt ? sunkAt(k) : 0);
41
+ pos[p * 3 + 2] = z;
42
+ normalOf(land, k, _normal);
43
+ nor[p * 3] = _normal[0];
44
+ nor[p * 3 + 1] = _normal[1];
45
+ nor[p * 3 + 2] = _normal[2];
46
+ col[p * 3] = SRGB2LIN[colors[k * 3]];
47
+ col[p * 3 + 1] = SRGB2LIN[colors[k * 3 + 1]];
48
+ col[p * 3 + 2] = SRGB2LIN[colors[k * 3 + 2]];
49
+ uv[p * 2] = x / 9;
50
+ uv[p * 2 + 1] = z / 9;
51
+ }
52
+ }
53
+ return chunkGeometry(pos, nor, col, uv, m, bedY);
54
+ }
55
+ // A chunk's geometry from its m x m points: two triangles to a cell, the deep lake bed's (below bedY) in a group of their own.
56
+ function chunkGeometry(pos, nor, col, uv, m, bedY) {
57
+ const Index = m * m > 65536 ? Uint32Array : Uint16Array;
58
+ const idx = new Index((m - 1) * (m - 1) * 6);
59
+ let q = 0,
60
+ e = idx.length; // land from the front, deep lake bed (group 1, the plain bed material) from the back
61
+ const deep = (i, j, k) => pos[i * 3 + 1] < bedY && pos[j * 3 + 1] < bedY && pos[k * 3 + 1] < bedY;
62
+ const tri = (i, j, k) => {
63
+ if (deep(i, j, k)) {
64
+ idx[--e] = k;
65
+ idx[--e] = j;
66
+ idx[--e] = i;
67
+ } else {
68
+ idx[q++] = i;
69
+ idx[q++] = j;
70
+ idx[q++] = k;
71
+ }
72
+ };
73
+ for (let b = 0; b < m - 1; b++)
74
+ for (let a = 0; a < m - 1; a++) {
75
+ const i00 = b * m + a,
76
+ i10 = i00 + 1,
77
+ i01 = i00 + m,
78
+ i11 = i01 + 1;
79
+ tri(i00, i01, i10);
80
+ tri(i10, i01, i11);
81
+ }
82
+ const g = new THREE.BufferGeometry();
83
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
84
+ g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
85
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3));
86
+ g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
87
+ g.setIndex(new THREE.BufferAttribute(idx, 1));
88
+ if (bedY !== undefined) {
89
+ // a chunk with no deep bed (or nothing but bed) has one group: an empty one would still be a draw call
90
+ if (q) g.addGroup(0, q, 0);
91
+ if (q < idx.length) g.addGroup(q, idx.length - q, 1);
92
+ }
93
+ g.computeBoundingSphere();
94
+ g.computeBoundingBox();
95
+ return g;
96
+ }
97
+ // The finest level, drawn only near the viewer over a land with fine relief with a relief function: each cell of
98
+ // the grid split FINE times each way, the baked heights read as the coarser levels' triangles have them, the relief added, the
99
+ // colours read between the grid's points, and the normals the grid's own, tilted by the relief's slope.
100
+ const FINE = 3; // parts each cell is split into (3.9 m cells: 1.3 m between the fine level's points)
101
+ function buildFineGeometry(land, ci, cj) {
102
+ const { cells, stride, spacing, x0, z0, heights, colors, bedY, relief } = land,
103
+ n = cells * FINE,
104
+ m = n + 3,
105
+ step = spacing / FINE,
106
+ last = stride - 1;
107
+ // the heights and relief over the chunk and a ring round it (for the relief's slope at its edge): r = n + 3 points a side
108
+ const r = n + 3,
109
+ base = new Float32Array(r * r),
110
+ rel = new Float32Array(r * r),
111
+ weights = [0, 0, 0, 0],
112
+ corner = [0, 0, 0, 0];
113
+ const place = (a, b) => {
114
+ // the grid cell and the place in it of fine point (a, b) of this chunk, clamped to the land
115
+ const fa = Math.min(Math.max(ci * cells * FINE + a, 0), last * FINE),
116
+ fb = Math.min(Math.max(cj * cells * FINE + b, 0), last * FINE),
117
+ i = Math.min((fa / FINE) | 0, last - 1),
118
+ j = Math.min((fb / FINE) | 0, last - 1),
119
+ u = fa / FINE - i,
120
+ v = fb / FINE - j,
121
+ k = j * stride + i;
122
+ corner[0] = k;
123
+ corner[1] = k + 1;
124
+ corner[2] = k + stride;
125
+ corner[3] = k + stride + 1;
126
+ weights[0] = (1 - u) * (1 - v);
127
+ weights[1] = u * (1 - v);
128
+ weights[2] = (1 - u) * v;
129
+ weights[3] = u * v;
130
+ // as the coarser levels' triangles have it: split along the diagonal from (1, 0) to (0, 1)
131
+ return u + v <= 1
132
+ ? heights[k] + u * (heights[k + 1] - heights[k]) + v * (heights[k + stride] - heights[k])
133
+ : heights[k + stride + 1] +
134
+ (1 - u) * (heights[k + stride] - heights[k + stride + 1]) +
135
+ (1 - v) * (heights[k + 1] - heights[k + stride + 1]);
136
+ };
137
+ for (let b = 0; b < r; b++)
138
+ for (let a = 0; a < r; a++) {
139
+ const h = place(a - 1, b - 1),
140
+ x = x0 + (ci * cells * FINE + a - 1) * step,
141
+ z = z0 + (cj * cells * FINE + b - 1) * step;
142
+ base[b * r + a] = h;
143
+ rel[b * r + a] = relief(x, z, h);
144
+ }
145
+ const pos = new Float32Array(m * m * 3),
146
+ nor = new Float32Array(m * m * 3),
147
+ col = new Float32Array(m * m * 3),
148
+ uv = new Float32Array(m * m * 2);
149
+ let p = 0;
150
+ for (let b = 0; b < m; b++) {
151
+ const jj = clamp(b - 1, 0, n),
152
+ sb = b === 0 || b === m - 1;
153
+ for (let a = 0; a < m; a++, p++) {
154
+ const ii = clamp(a - 1, 0, n),
155
+ skirt = sb || a === 0 || a === m - 1,
156
+ q = (jj + 1) * r + ii + 1,
157
+ x = x0 + (ci * cells * FINE + ii) * step,
158
+ z = z0 + (cj * cells * FINE + jj) * step;
159
+ place(ii, jj);
160
+ pos[p * 3] = x;
161
+ pos[p * 3 + 1] = base[q] + rel[q] - (skirt ? 5 : 0);
162
+ pos[p * 3 + 2] = z;
163
+ // the grid's normal between its points, as the slope of a height field, plus the relief's slope
164
+ let nx = 0,
165
+ ny = 0,
166
+ nz = 0,
167
+ cr = 0,
168
+ cg = 0,
169
+ cb = 0;
170
+ for (let c = 0; c < 4; c++) {
171
+ normalOf(land, corner[c], _normal);
172
+ nx += _normal[0] * weights[c];
173
+ ny += _normal[1] * weights[c];
174
+ nz += _normal[2] * weights[c];
175
+ cr += SRGB2LIN[colors[corner[c] * 3]] * weights[c];
176
+ cg += SRGB2LIN[colors[corner[c] * 3 + 1]] * weights[c];
177
+ cb += SRGB2LIN[colors[corner[c] * 3 + 2]] * weights[c];
178
+ }
179
+ const gx = -nx / ny + (rel[q + 1] - rel[q - 1]) / (2 * step),
180
+ gz = -nz / ny + (rel[q + r] - rel[q - r]) / (2 * step),
181
+ len = Math.hypot(gx, 1, gz);
182
+ nor[p * 3] = -gx / len;
183
+ nor[p * 3 + 1] = 1 / len;
184
+ nor[p * 3 + 2] = -gz / len;
185
+ col[p * 3] = cr;
186
+ col[p * 3 + 1] = cg;
187
+ col[p * 3 + 2] = cb;
188
+ uv[p * 2] = x / 9;
189
+ uv[p * 2 + 1] = z / 9;
190
+ }
191
+ }
192
+ return chunkGeometry(pos, nor, col, uv, m, bedY);
193
+ }
194
+ // Builds the ground at its coarsest and returns an updater that shows finer levels as the viewer approaches. `materials` is the pair
195
+ // every chunk is drawn with (ground, deep bed), or a function giving the pair (or the one material) for the chunk that covers
196
+ // (x0, z0) to (x1, z1). `held`: [{ box: [x0, z0, x1, z1], range, level }], ground over which something finer is laid on the mesh
197
+ // at a level of detail or finer, a list that may fill later: within `range` metres of its box
198
+ // the chunks under it are kept at `level` (0 the finest) or finer, and the updater sets its `fine` once they all stand so. A land
199
+ // with fine relief (`relief`, `groundAt`) has a level finer still near the eye (buildFineGeometry). All chunks of one material
200
+ // are one batch of geometry pieces: those in view are drawn together, and a
201
+ // chunk's vertices are on the card only, at the one level it is shown at.
202
+ export function terrainChunks(parent, land, materials, {
203
+ camera, createBatch, lodScale = () => 1, distances = [330, 680, 1250], held = [],
204
+ fineRange = 70, fineHeight = 90, altitudeStart = 120, altitudeWeight = 0.6, checksPerFrame = 8,
205
+ }) {
206
+ const width = land.cells * land.spacing,
207
+ count = (land.stride - 1) / land.cells;
208
+ const batches = new Map(); // material -> the batch of every chunk drawn in it
209
+ const batchOf = material => {
210
+ if (!batches.has(material)) {
211
+ const batch = createBatch(material);
212
+ parent.add(batch);
213
+ batches.set(material, batch);
214
+ }
215
+ return batches.get(material);
216
+ };
217
+ // Puts a chunk on the card at a level of detail, in place of the level it was at
218
+ const show = (chunk, lod) => {
219
+ for (const [batch, id] of chunk.pieces) batch.remove(id);
220
+ const geometry = lod < 0 ? buildFineGeometry(land, chunk.ci, chunk.cj) : buildChunkGeometry(land, chunk.ci, chunk.cj, lod),
221
+ whole = [{ start: 0, count: geometry.index.count, materialIndex: 0 }],
222
+ paired = Array.isArray(chunk.materials) && geometry.groups.length > 0, // ground and deep bed, each in its own material
223
+ own = [].concat(chunk.materials);
224
+ chunk.pieces = (paired ? geometry.groups : whole).map(part => {
225
+ const batch = batchOf(own[part.materialIndex]);
226
+ return [batch, batch.add(geometry, part.start, part.count)];
227
+ });
228
+ chunk.lod = lod;
229
+ };
230
+ const chunks = [];
231
+ for (let cj = 0; cj < count; cj++)
232
+ for (let ci = 0; ci < count; ci++) {
233
+ const x0 = land.x0 + ci * width,
234
+ z0 = land.z0 + cj * width,
235
+ chunk = {
236
+ ci,
237
+ cj,
238
+ cx: land.x0 + (ci + 0.5) * width,
239
+ cz: land.z0 + (cj + 0.5) * width,
240
+ materials: typeof materials === 'function' ? materials(x0, z0, x0 + width, z0 + width) : materials,
241
+ pieces: [],
242
+ lod: 3,
243
+ holds: null, // the ground held over this chunk (`held`), once seen
244
+ };
245
+ show(chunk, chunk.lod);
246
+ chunks.push(chunk);
247
+ }
248
+ const boxOf = c => [c.cx - width / 2, c.cz - width / 2, c.cx + width / 2, c.cz + width / 2],
249
+ overlaps = (a, b) => a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3],
250
+ nearBox = (box, range) =>
251
+ Math.hypot(
252
+ Math.max(box[0] - camera.position.x, 0, camera.position.x - box[2]),
253
+ Math.max(box[1] - camera.position.z, 0, camera.position.z - box[3]),
254
+ ) <
255
+ range * lodScale();
256
+ // the chunks under ground held at a level, found when it is first seen (the list may fill later)
257
+ const holdUnder = h => {
258
+ h.chunks = chunks.filter(c => overlaps(boxOf(c), h.box));
259
+ h.fine = false;
260
+ for (const c of h.chunks) (c.holds ??= []).push(h);
261
+ };
262
+ // the level a chunk wants, `want` by its distance, or finer where ground over it is held within range
263
+ const heldLevel = (c, want) => {
264
+ if (c.holds)
265
+ for (let i = 0; i < c.holds.length; i++) if (nearBox(c.holds[i].box, c.holds[i].range)) want = Math.min(want, c.holds[i].level);
266
+ return want;
267
+ };
268
+ // whether every chunk under held ground stands at its level or finer
269
+ const standsAt = h => {
270
+ for (let i = 0; i < h.chunks.length; i++) if (h.chunks[i].lod > h.level) return false;
271
+ return true;
272
+ };
273
+ let chunkCursor = 0;
274
+ return force => {
275
+ for (let i = 0; i < held.length; i++) if (!held[i].chunks) holdUnder(held[i]);
276
+ // Re-evaluate a few chunks per frame; put at most one at another level per frame. The fine level is drawn only near the eye.
277
+ const low = !!land.relief && camera.position.y < land.groundAt(camera.position.x, camera.position.z) + fineHeight;
278
+ let built = false;
279
+ const count = force ? chunks.length : checksPerFrame;
280
+ for (let n = 0; n < count; n++) {
281
+ const c = chunks[chunkCursor];
282
+ chunkCursor = (chunkCursor + 1) % chunks.length;
283
+ const dx = Math.max(Math.abs(camera.position.x - c.cx) - width * 0.5, 0),
284
+ dz = Math.max(Math.abs(camera.position.z - c.cz) - width * 0.5, 0);
285
+ const d = Math.hypot(dx, dz, Math.max(0, camera.position.y - altitudeStart) * altitudeWeight);
286
+ const fine = low && Math.hypot(dx, dz) < fineRange;
287
+ const want = fine
288
+ ? -1
289
+ : heldLevel(
290
+ c,
291
+ d < distances[0] * lodScale() ? 0 : d < distances[1] * lodScale() ? 1 : d < distances[2] * lodScale() ? 2 : 3,
292
+ );
293
+ if (want === c.lod || (built && !force)) continue;
294
+ show(c, want);
295
+ built = true;
296
+ }
297
+ for (let i = 0; i < held.length; i++) held[i].fine = nearBox(held[i].box, held[i].range) && standsAt(held[i]);
298
+ };
299
+ }
300
+
@@ -0,0 +1,44 @@
1
+ // Concentric square rings for extending a regular XZ heightfield. Row zero of the
2
+ // source grid runs east along its minimum Z. All returned buffers are transferable.
3
+ export function terrainExtension({ centerX = 0, centerZ = 0, size, segments, reach, growth = 1.3 }) {
4
+ const half = size / 2;
5
+ if (![centerX, centerZ, size, reach, growth].every(Number.isFinite)
6
+ || size <= 0 || !Number.isSafeInteger(segments) || segments < 1 || reach <= half || growth <= 1) {
7
+ throw new RangeError('Expected a square grid, a reach beyond its edge and growth greater than one');
8
+ }
9
+ const rows = Math.ceil(Math.log(reach / half) / Math.log(growth));
10
+ const perimeter = 4 * segments;
11
+ const vertices = perimeter * (rows + 1);
12
+ const positions = new Float32Array(vertices * 3);
13
+ const Index = vertices > 65535 ? Uint32Array : Uint16Array;
14
+ const indices = new Index(perimeter * rows * 6);
15
+ const boundary = new Uint32Array(perimeter);
16
+ for (let ring = 0; ring <= rows; ring++) {
17
+ const radius = half * growth ** ring;
18
+ for (let t = 0; t < perimeter; t++) {
19
+ const side = Math.floor(t / segments);
20
+ const along = t % segments;
21
+ let col = along, row = 0;
22
+ switch (side) {
23
+ case 1: col = segments; row = along; break;
24
+ case 2: col = segments - along; row = segments; break;
25
+ case 3: col = 0; row = segments - along; break;
26
+ }
27
+ if (ring === 0) boundary[t] = row * (segments + 1) + col;
28
+ const vertex = ring * perimeter + t;
29
+ const axis = -radius + 2 * radius * along / segments;
30
+ positions[3 * vertex] = centerX + (side === 0 ? axis : side === 1 ? radius : side === 2 ? -axis : -radius);
31
+ positions[3 * vertex + 2] = centerZ + (side === 0 ? -radius : side === 1 ? axis : side === 2 ? radius : -axis);
32
+ if (ring === rows) continue;
33
+ const next = ring * perimeter + (t + 1) % perimeter;
34
+ const offset = 6 * vertex;
35
+ indices[offset] = vertex;
36
+ indices[offset + 1] = next;
37
+ indices[offset + 2] = next + perimeter;
38
+ indices[offset + 3] = vertex;
39
+ indices[offset + 4] = next + perimeter;
40
+ indices[offset + 5] = vertex + perimeter;
41
+ }
42
+ }
43
+ return { positions, indices, boundary };
44
+ }
@@ -0,0 +1,44 @@
1
+ // Distance (in texture units) from (u, v) to the nearest edge of a tileable pattern of `per` x `per` jittered cells; `site`, when
2
+ // given, is told which cell (u, v) lies in, wrapped to the tile.
3
+ export function cellEdge(hash2, u, v, per, seed, site) {
4
+ const gx = u * per,
5
+ gz = v * per,
6
+ ix = Math.floor(gx),
7
+ iz = Math.floor(gz);
8
+ let d1 = 9,
9
+ d2 = 9,
10
+ ax = 0,
11
+ az = 0,
12
+ bx = 0,
13
+ bz = 0;
14
+ for (let b = -1; b <= 1; b++)
15
+ for (let a = -1; a <= 1; a++) {
16
+ const cx = ix + a,
17
+ cz = iz + b,
18
+ wx = ((cx % per) + per) % per,
19
+ wz = ((cz % per) + per) % per;
20
+ const sx = cx + 0.15 + 0.7 * hash2(wx, wz, seed),
21
+ sz = cz + 0.15 + 0.7 * hash2(wx, wz, seed + 1),
22
+ d = (sx - gx) ** 2 + (sz - gz) ** 2;
23
+ if (d < d1) {
24
+ if (site) {
25
+ site[0] = wx;
26
+ site[1] = wz;
27
+ }
28
+ d2 = d1;
29
+ bx = ax;
30
+ bz = az;
31
+ d1 = d;
32
+ ax = sx;
33
+ az = sz;
34
+ } else if (d < d2) {
35
+ d2 = d;
36
+ bx = sx;
37
+ bz = sz;
38
+ }
39
+ }
40
+ const ex = bx - ax,
41
+ ez = bz - az,
42
+ l = Math.hypot(ex, ez) || 1;
43
+ return (((ax + bx) * 0.5 - gx) * ex + ((az + bz) * 0.5 - gz) * ez) / l / per;
44
+ }
@@ -0,0 +1,83 @@
1
+ import { clamp } from './scalar.js';
2
+ import { createNoise } from './noise.js';
3
+ import { createHash, mulberry32 } from './random.js';
4
+
5
+ const FOLD_SLOPES = [110, 30];
6
+ // The long folds: how many, and each one's half-width, how far it wanders, how tall it is, and how much of the tile's height
7
+ // it lasts, all as [least, most] (widths and wanders in tiles: shares of the way round the body); and the shade at a fold's
8
+ // foot: how far out from the fold it reaches (of its half-width) and how much of it lies on the fold's own flanks.
9
+ const PIPES = { n: 46, half: [0.009, 0.024], wander: [0.005, 0.016], tall: [0.45, 1], lasts: [0.07, 0.2], foot: 2.3, flank: 0.5 },
10
+ CRUMPLE = { per: 6, octaves: 2, seed: 83, full: 1.6 }, // the crumple's noise: cells a tile, and how far from its middle value it is at its full height
11
+ STEP = 1 / 512; // how far apart a field is read to find its slope (tiles)
12
+ const around = d => d - Math.round(d), // the nearest way round a tile
13
+ byte = slope => clamp(127.5 + 127.5 * slope, 0, 255);
14
+ // The long folds' fill: a pixel's bytes from its place in the tile.
15
+ function garmentFolds(foldSeed) {
16
+ const rand = mulberry32(foldSeed),
17
+ between = ([a, b]) => a + (b - a) * rand(),
18
+ pipes = [];
19
+ for (let k = 0; k < PIPES.n; k++)
20
+ pipes.push({
21
+ u: (k + 0.15 + 0.7 * rand()) / PIPES.n,
22
+ v: rand(),
23
+ half: between(PIPES.half),
24
+ wander: between(PIPES.wander),
25
+ turns: 2 + Math.floor(rand() * 4),
26
+ phase: rand() * Math.PI * 2,
27
+ tall: between(PIPES.tall),
28
+ lasts: between(PIPES.lasts),
29
+ });
30
+ // the folds' height at a place, or (shaded) how much of its light their feet and flanks take there
31
+ const field = (u, v, shaded) => {
32
+ let sum = 0;
33
+ for (const p of pipes) {
34
+ const along = Math.abs(around(v - p.v)) / p.lasts;
35
+ if (along >= 1) continue;
36
+ const t = Math.abs(around(u - p.u - p.wander * Math.sin(Math.PI * 2 * p.turns * v + p.phase)) / p.half),
37
+ full = p.tall * (1 - along * along);
38
+ if (!shaded) sum += t < 1 ? full * (1 - t * t) * (1 - t * t) : 0;
39
+ else if (t < 1) sum += full * PIPES.flank * t * t;
40
+ else if (t < PIPES.foot) sum += full * (PIPES.flank + (1 - PIPES.flank) * (1 - (t - 1) / (PIPES.foot - 1)) ** 2);
41
+ }
42
+ return Math.min(1, sum);
43
+ };
44
+ return (u, v, o) => {
45
+ o[0] = byte((field(u + STEP, v) - field(u - STEP, v)) / (2 * STEP) / FOLD_SLOPES[0]);
46
+ o[1] = 255 * (1 - field(u, v, true));
47
+ o[2] = 0;
48
+ };
49
+ }
50
+ // The crumple's fill.
51
+ function garmentCrumple(tfbm) {
52
+ const crumple = (u, v) => Math.min(1, CRUMPLE.full * Math.abs(2 * tfbm(u, v, CRUMPLE.per, CRUMPLE.octaves, CRUMPLE.seed) - 1));
53
+ return (u, v, o) => {
54
+ o[0] = byte((crumple(u + STEP, v) - crumple(u - STEP, v)) / (2 * STEP) / FOLD_SLOPES[1]);
55
+ o[1] = byte((crumple(u, v + STEP) - crumple(u, v - STEP)) / (2 * STEP) / FOLD_SLOPES[1]);
56
+ o[2] = 255 * crumple(u, v);
57
+ };
58
+ }
59
+
60
+ const cloth = (threads, hash2, tfbm) => (u, v, o) => {
61
+ const i = Math.floor(u * threads),
62
+ j = Math.floor(v * threads),
63
+ over = (i + j) % 2, // which thread lies on top at this crossing
64
+ along = over ? (v * threads) % 1 : (u * threads) % 1,
65
+ thread = Math.sin(Math.PI * along), // round across the thread on top, darker where it dips under
66
+ tone = over ? hash2(i, 0, 69) : hash2(j, 1, 69), // one thread spun a little thicker or paler than the next
67
+ wear = tfbm(u, v, 4, 4, 70);
68
+ const c = clamp(158 + wear * 56 + (thread - 0.64) * 20 + (tone - 0.5) * 12, 0, 255);
69
+ o[0] = c;
70
+ o[1] = c * 0.99;
71
+ o[2] = c * 0.975;
72
+ };
73
+
74
+ function createClothTextures({ seed = 0, foldSeed = seed, threads = 64 } = {}) {
75
+ const { tfbm } = createNoise(seed);
76
+ const hash2 = createHash(seed);
77
+ return {
78
+ weave: () => cloth(threads, hash2, tfbm),
79
+ folds: () => garmentFolds(foldSeed),
80
+ crumple: () => garmentCrumple(tfbm),
81
+ };
82
+ }
83
+ export { FOLD_SLOPES, createClothTextures };
@@ -0,0 +1,112 @@
1
+ import { clamp } from './scalar.js';
2
+ import { createNoise } from './noise.js';
3
+ import { createHash, mulberry32 } from './random.js';
4
+
5
+ export function createCloudTextures({
6
+ seed = 0,
7
+ noise = createNoise(seed),
8
+ hash2 = createHash(seed),
9
+ volumeSeed = seed,
10
+ } = {}) {
11
+ const { tfbm, tnoise } = noise;
12
+ // A sheet of round domes, one over each of `per` x `per` jittered cells (it tiles): 1 at a dome's middle, 0 where it meets
13
+ // its neighbours in a crease.
14
+ function domes(u, v, per, seed) {
15
+ const gx = u * per,
16
+ gz = v * per,
17
+ ix = Math.floor(gx),
18
+ iz = Math.floor(gz);
19
+ let near = 9;
20
+ for (let b = -1; b <= 1; b++)
21
+ for (let a = -1; a <= 1; a++) {
22
+ const cx = ix + a,
23
+ cz = iz + b,
24
+ wx = ((cx % per) + per) % per,
25
+ wz = ((cz % per) + per) % per,
26
+ d = (cx + 0.15 + 0.7 * hash2(wx, wz, seed) - gx) ** 2 + (cz + 0.15 + 0.7 * hash2(wx, wz, seed + 1) - gz) ** 2;
27
+ if (d < near) near = d;
28
+ }
29
+ return Math.max(0, 1 - near * 2.2);
30
+ }
31
+ // Rounded lumps with creases between them, as a cloud's top is made of: domes at three sizes, from `per` to a sheet.
32
+ function lumps(u, v, per, seed) {
33
+ let s = 0,
34
+ a = 0.5,
35
+ n = 0;
36
+ for (let i = 0; i < 3; i++) {
37
+ s += a * domes(u, v, per, seed + i * 13);
38
+ n += a;
39
+ a *= 0.5;
40
+ per *= 2;
41
+ }
42
+ return s / n;
43
+ }
44
+ // Streaks four times as long as they are wide, at three scales.
45
+ function wisps(u, v) {
46
+ let s = 0,
47
+ a = 0.5,
48
+ n = 0;
49
+ for (let i = 0, per = 3; i < 3; i++, per *= 2, a *= 0.5) {
50
+ s += a * tnoise(u * per, v * per * 4, per, 1259 + i * 13, per * 4);
51
+ n += a;
52
+ }
53
+ return s / n;
54
+ }
55
+ // How much cloud stands at (u, v) of the sheet, 0 to 1, spread as the sky's threshold expects: half the sheet over 0.49, a
56
+ // tenth over 0.63. Everything is bent by one slow noise (bendU, bendV), so no two masses run alike.
57
+ function cloudAmount(u, v, bendU, bendV) {
58
+ const bu = u + bendU * 0.08,
59
+ bv = v + bendV * 0.08;
60
+ return clamp(0.485 + (tfbm(bu, bv, 5, 3, 1223) - 0.5) * 0.63 + (lumps(bu, bv, 11, 1237) - 0.68) * 0.42, 0, 1);
61
+ }
62
+ const cloudBend = (u, v, seed) => tfbm(u, v, 4, 3, seed) - 0.5;
63
+ const cloudField = () => (u, v, o) => {
64
+ const bendU = cloudBend(u, v, 1201),
65
+ bendV = cloudBend(u, v, 1213),
66
+ field = 255 * cloudAmount(u, v, bendU, bendV),
67
+ whole = Math.round(field);
68
+ o[0] = whole;
69
+ o[3] = (field - whole + 0.5) * 255;
70
+ o[1] = 255 * lumps(u + bendV * 0.02, v - bendU * 0.02, 40, 1249);
71
+ o[2] = 255 * clamp(wisps(u + bendU * 0.03, v + bendV * 0.03) * 1.5 - 0.25, 0, 1);
72
+ };
73
+ // The clouds' billows (the cloud dome): a block of round lumps with creases between them, in three dimensions, which
74
+ // repeats every way. A cloud's smooth body, cut from the field, is eaten back in the creases and left standing in the lumps,
75
+ // so its sides and top swell like a cauliflower's. R, G, B: lumps a quarter, an eighth and a sixteenth of the block across;
76
+ // A: broad ones, half the block.
77
+ const CLOUD_VOLUME_LUMPS = [4, 8, 16, 2];
78
+ // Round lumps, one in each of `per` x `per` x `per` jittered cells: 1 at a lump's middle, 0 where it meets its neighbours.
79
+ function lumpBlock(per, seed) {
80
+ const R = mulberry32(seed),
81
+ middles = new Float32Array(per * per * per * 3).map(() => 0.12 + 0.76 * R()),
82
+ wrap = i => ((i % per) + per) % per;
83
+ return (u, v, w) => {
84
+ const x = u * per,
85
+ y = v * per,
86
+ z = w * per,
87
+ ix = Math.floor(x),
88
+ iy = Math.floor(y),
89
+ iz = Math.floor(z);
90
+ let near = 9;
91
+ for (let c = -1; c <= 1; c++)
92
+ for (let b = -1; b <= 1; b++)
93
+ for (let a = -1; a <= 1; a++) {
94
+ const k = ((wrap(iz + c) * per + wrap(iy + b)) * per + wrap(ix + a)) * 3,
95
+ d = (ix + a + middles[k] - x) ** 2 + (iy + b + middles[k + 1] - y) ** 2 + (iz + c + middles[k + 2] - z) ** 2;
96
+ if (d < near) near = d;
97
+ }
98
+ return Math.max(0, 1 - near * 1.7);
99
+ };
100
+ }
101
+ function cloudVolume() {
102
+ const blocks = CLOUD_VOLUME_LUMPS.map((per, i) => lumpBlock(per, volumeSeed + i * 7));
103
+ return (u, v, o, w) => {
104
+ for (let i = 0; i < 4; i++) o[i] = 255 * blocks[i](u, v, w);
105
+ };
106
+ }
107
+ return {
108
+ field: cloudField,
109
+ volume: cloudVolume,
110
+ coverage: (u, v) => cloudAmount(u, v, cloudBend(u, v, 1201), cloudBend(u, v, 1213)),
111
+ };
112
+ }
package/math/color.js ADDED
@@ -0,0 +1,29 @@
1
+ import { clamp } from './scalar.js';
2
+
3
+ const dim = (c, k) => [c[0] * k, c[1] * k, c[2] * k];
4
+
5
+ const SRGB2LIN = new Float32Array(256);
6
+ for (let i = 0; i < 256; i++) {
7
+ const c = i / 255;
8
+ SRGB2LIN[i] = c < 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
9
+ }
10
+ // Three.js ACES filmic fit (see licenses/three.txt and licenses/baking-lab.txt).
11
+ // Mutates a linear RGB color so fog applied after tone mapping can match the sky.
12
+ function acesToColor(c, exposure) {
13
+ const r = (c.r * exposure) / 0.6,
14
+ g = (c.g * exposure) / 0.6,
15
+ b = (c.b * exposure) / 0.6;
16
+ let r2 = 0.59719 * r + 0.35458 * g + 0.04823 * b,
17
+ g2 = 0.076 * r + 0.90834 * g + 0.01566 * b,
18
+ b2 = 0.0284 * r + 0.13383 * g + 0.83777 * b;
19
+ const f = v => (v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.432951) + 0.238081);
20
+ r2 = f(r2);
21
+ g2 = f(g2);
22
+ b2 = f(b2);
23
+ c.r = clamp(1.60475 * r2 - 0.53108 * g2 - 0.07367 * b2, 0, 1);
24
+ c.g = clamp(-0.10208 * r2 + 1.10813 * g2 - 0.00605 * b2, 0, 1);
25
+ c.b = clamp(-0.00327 * r2 - 0.07276 * g2 + 1.07602 * b2, 0, 1);
26
+ return c;
27
+ }
28
+
29
+ export { acesToColor, dim, SRGB2LIN };
package/math/curve.js CHANGED
@@ -1,10 +1,9 @@
1
1
  // ════════════════════════════════════════════════════════════════════════
2
2
  // A smooth curve through a line of [x, z] points: a centripetal Catmull-Rom spline, walked at even steps of its length.
3
3
  //
4
- // It is Three.js's CatmullRomCurve3 (open, centripetal) and its getSpacedPoints, written out in plain numbers so that the
5
- // ground's model needs no Three.js and can run in a worker. Every sum is done in the order Three.js does it: roads, rivers
6
- // and the baked ground come out the same to the last bit, which is also why a two-point line keeps Three.js's quirk of
7
- // using the far end's extension for both ends.
4
+ // Matches Three.js CatmullRomCurve3.getSpacedPoints for open centripetal curves,
5
+ // using scalar arithmetic suitable for workers. The evaluation order and the
6
+ // extrapolation used at the ends of two-point curves match Three.js.
8
7
  // ════════════════════════════════════════════════════════════════════════
9
8
  const ARC_STEPS = 200, // the pieces the curve's length is measured in
10
9
  REPEATED = 1e-4; // points closer than this (to the power the knots are spaced by) count as one