roamwright 0.4.0 → 0.20.1

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 (139) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +11 -34
  3. package/geometry/bedding.js +141 -0
  4. package/geometry/builder-cells.js +42 -0
  5. package/geometry/builder-frame.js +47 -0
  6. package/geometry/builder.js +189 -177
  7. package/geometry/cell-mask.js +25 -0
  8. package/geometry/creased-sheet.js +34 -34
  9. package/geometry/ear.js +36 -36
  10. package/geometry/erosion.js +65 -42
  11. package/geometry/face-grid.js +65 -65
  12. package/geometry/foliage.js +10 -10
  13. package/geometry/hair-gathers.js +41 -41
  14. package/geometry/hair-locks.js +41 -41
  15. package/geometry/hair-patch.js +18 -18
  16. package/geometry/hair-shell.js +31 -31
  17. package/geometry/head-profile.js +15 -15
  18. package/geometry/head-shape.js +77 -77
  19. package/geometry/heightfield.js +27 -18
  20. package/geometry/index-parts.js +2 -2
  21. package/geometry/instance-visibility.js +12 -12
  22. package/geometry/instances.js +15 -15
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +3 -3
  25. package/geometry/path-field.js +63 -33
  26. package/geometry/placement.js +52 -52
  27. package/geometry/point-buckets.js +50 -0
  28. package/geometry/primitives.js +63 -47
  29. package/geometry/sagging-tube.js +27 -27
  30. package/geometry/sampled-surface.js +109 -77
  31. package/geometry/scatter-grid.js +46 -6
  32. package/geometry/sculpt.js +93 -93
  33. package/geometry/shore-grid.js +77 -34
  34. package/geometry/strata-field.js +92 -92
  35. package/geometry/strata-tiles.js +91 -91
  36. package/geometry/stream.js +70 -48
  37. package/geometry/terrain-chunks.js +87 -82
  38. package/geometry/terrain-extension.js +6 -6
  39. package/index.js +5 -0
  40. package/math/cell-edge.js +16 -16
  41. package/math/cell-key.js +6 -0
  42. package/math/circle-clearances.js +19 -0
  43. package/math/cloth-textures.js +6 -6
  44. package/math/cloud-textures.js +20 -20
  45. package/math/color.js +14 -14
  46. package/math/curve.js +22 -22
  47. package/math/mountain-ranges.js +216 -165
  48. package/math/noise.js +101 -49
  49. package/math/particle-noise.js +28 -28
  50. package/math/periodic.js +5 -5
  51. package/math/random.js +24 -15
  52. package/math/rectangles.js +52 -0
  53. package/math/rock-texture.js +7 -7
  54. package/math/scalar.js +5 -5
  55. package/math/surface-textures.js +54 -54
  56. package/motion/arm-reach.js +24 -24
  57. package/motion/ballistic-arc.js +11 -0
  58. package/motion/biped-cycle.js +44 -0
  59. package/motion/biped-leg.js +37 -0
  60. package/motion/biped-stride.js +98 -122
  61. package/motion/contact-transition.js +33 -0
  62. package/motion/crowd-alarms.js +39 -39
  63. package/motion/crowd-routine.js +94 -65
  64. package/motion/daily-clock.js +9 -9
  65. package/motion/deck-surface.js +38 -0
  66. package/motion/ground-lookahead.js +5 -5
  67. package/motion/instance-sight.js +8 -8
  68. package/motion/player.js +36 -28
  69. package/motion/quadruped.js +155 -155
  70. package/motion/spaces.js +32 -32
  71. package/motion/weather.js +73 -24
  72. package/motion/wind.js +32 -13
  73. package/package.json +7 -3
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +138 -82
  76. package/rendering/cloud-dome.js +28 -28
  77. package/rendering/cloud-field.js +2 -2
  78. package/rendering/compilation-schedule.js +68 -11
  79. package/rendering/contact-shadows.js +2 -2
  80. package/rendering/context.js +12 -0
  81. package/rendering/crowd-skinning.js +13 -13
  82. package/rendering/crust.js +18 -12
  83. package/rendering/daylight.js +3 -3
  84. package/rendering/detail-range.js +28 -0
  85. package/rendering/dispose-meshes.js +18 -0
  86. package/rendering/dof.js +9 -9
  87. package/rendering/eye-adapt.js +14 -14
  88. package/rendering/far-shadow.js +8 -8
  89. package/rendering/flocks.js +78 -78
  90. package/rendering/garment-material.js +17 -17
  91. package/rendering/glow-lines.js +13 -13
  92. package/rendering/hair-strands.js +20 -20
  93. package/rendering/height-probe.js +149 -19
  94. package/rendering/label-layout.js +46 -0
  95. package/rendering/label-range.js +38 -0
  96. package/rendering/light-budget.js +52 -52
  97. package/rendering/light-shafts.js +23 -23
  98. package/rendering/local-lights.js +15 -4
  99. package/rendering/material-lod.js +49 -49
  100. package/rendering/particle-emitters.js +90 -90
  101. package/rendering/particles.js +78 -67
  102. package/rendering/piece-batch.js +17 -6
  103. package/rendering/planar-reflection.js +38 -38
  104. package/rendering/post-shaders.js +17 -13
  105. package/rendering/post.js +71 -71
  106. package/rendering/rain-streaks.js +67 -0
  107. package/rendering/road-surface.js +11 -11
  108. package/rendering/sea-shaders.js +11 -11
  109. package/rendering/shader-warmup.js +29 -16
  110. package/rendering/shadow-alignment.js +4 -4
  111. package/rendering/shadow-depth.js +7 -7
  112. package/rendering/sky-occlusion.js +16 -16
  113. package/rendering/sky.js +16 -6
  114. package/rendering/stage-lights.js +6 -6
  115. package/rendering/static-point-shadow.js +3 -3
  116. package/rendering/still-casters.js +1 -1
  117. package/rendering/strata-material.js +10 -10
  118. package/rendering/stream-flow.js +10 -10
  119. package/rendering/taa.js +26 -26
  120. package/rendering/talus.js +15 -15
  121. package/rendering/terrain-rock.js +7 -7
  122. package/rendering/texture-fills.js +8 -8
  123. package/rendering/textures.js +28 -28
  124. package/rendering/wakes.js +24 -24
  125. package/rendering/water-material.js +36 -23
  126. package/rendering/world-matrices.js +38 -38
  127. package/runtime/diagnostic-log.js +2 -2
  128. package/runtime/first-use.js +33 -28
  129. package/runtime/frame-pacing.js +33 -0
  130. package/runtime/gpu-timing.js +7 -7
  131. package/runtime/grid-cache.js +1 -1
  132. package/runtime/grid-rows.js +44 -5
  133. package/runtime/hand-over.js +41 -23
  134. package/runtime/pool.js +58 -16
  135. package/runtime/quality-fit.js +1 -1
  136. package/runtime/search.js +22 -22
  137. package/runtime/spatial-audio.js +13 -13
  138. package/runtime/withdrawable-task.js +35 -0
  139. package/runtime/worker.js +7 -0
@@ -1,6 +1,14 @@
1
+ /**
2
+ * Measure the distance to a path or bake a sampled route into row-major terrain grids.
3
+ * @module
4
+ */
5
+
1
6
  import { clamp } from '../math/scalar.js';
2
7
 
3
- // The box round a line of [x, z] points: [x0, x1, z0, z1].
8
+ /**
9
+ * @param {[number, number][]} line - Ordered X/Z points in world units.
10
+ * @returns {[number, number, number, number]} Bounds in the order [minX, maxX, minZ, maxZ].
11
+ */
4
12
  function pathBox(line) {
5
13
  const box = [Infinity, -Infinity, Infinity, -Infinity];
6
14
  for (const [x, z] of line) {
@@ -12,24 +20,34 @@ function pathBox(line) {
12
20
  return box;
13
21
  }
14
22
 
15
- // Whether (x, z) lies within `reach` of the path ({ line, box }); on a hit, fill the caller’s result.
16
- function nearestPathPoint(c, x, z, reach, near) {
17
- const b = c.box;
18
- if (x < b[0] - reach || x > b[1] + reach || z < b[2] - reach || z > b[3] + reach) return false;
23
+ /**
24
+ * Find the closest point on a path strictly inside the search radius.
25
+ * @param {{line: [number, number][], box: ReturnType<typeof pathBox>}} path - Polyline with its current bounds.
26
+ * @param {number} x - Query X in world units.
27
+ * @param {number} z - Query Z in world units.
28
+ * @param {number} reach - Maximum search distance in the same units.
29
+ * @param {{d?: number, t?: number, side?: number}} near - Caller-owned result. On a hit, d is the distance,
30
+ * t is the fractional segment index divided by the segment count, and side is the sign of the X/Z
31
+ * cross product of the segment direction with the query offset (positive for a point on the line).
32
+ * @returns True on a hit. A miss leaves the result intact.
33
+ */
34
+ function nearestPathPoint(path, x, z, reach, near) {
35
+ const bounds = path.box;
36
+ if (x < bounds[0] - reach || x > bounds[1] + reach || z < bounds[2] - reach || z > bounds[3] + reach) return false;
19
37
  let best = reach * reach,
20
38
  at = -1;
21
- for (let i = 0; i < c.line.length - 1; i++) {
22
- const p = c.line[i],
23
- q = c.line[i + 1],
24
- dx = q[0] - p[0],
25
- dz = q[1] - p[1],
26
- px = x - p[0],
27
- pz = z - p[1],
28
- t = clamp((px * dx + pz * dz) / (dx * dx + dz * dz), 0, 1),
29
- d = (px - dx * t) ** 2 + (pz - dz * t) ** 2;
30
- if (d < best) {
31
- best = d;
32
- at = (i + t) / (c.line.length - 1);
39
+ for (let i = 0; i < path.line.length - 1; i++) {
40
+ const segmentStart = path.line[i],
41
+ segmentEnd = path.line[i + 1],
42
+ dx = segmentEnd[0] - segmentStart[0],
43
+ dz = segmentEnd[1] - segmentStart[1],
44
+ px = x - segmentStart[0],
45
+ pz = z - segmentStart[1],
46
+ segmentFraction = clamp((px * dx + pz * dz) / (dx * dx + dz * dz), 0, 1),
47
+ distanceSquared = (px - dx * segmentFraction) ** 2 + (pz - dz * segmentFraction) ** 2;
48
+ if (distanceSquared < best) {
49
+ best = distanceSquared;
50
+ at = (i + segmentFraction) / (path.line.length - 1);
33
51
  near.side = dx * pz - dz * px < 0 ? -1 : 1;
34
52
  }
35
53
  }
@@ -39,23 +57,35 @@ function nearestPathPoint(c, x, z, reach, near) {
39
57
  return true;
40
58
  }
41
59
 
42
- // Stamp samples onto an XZ grid. The radius bounds the square of cells visited around each sample.
43
- function stampPath({ x0, z0, width, height, spacing }, pts, radius, grid, valueGrid, valueFn) {
60
+ /**
61
+ * Update the grid around each path sample with the smallest distance seen so far.
62
+ * Initialise a fresh distance grid with Infinity. The radius bounds a square of candidate
63
+ * cells, so a written distance near a corner can exceed the radius. Densify long
64
+ * segments before stamping if intermediate positions should also contribute.
65
+ * @param {{x0: number, z0: number, width: number, height: number, spacing: number}} layout -
66
+ * Origin in world units, dimensions in samples and spacing in world units.
67
+ * @param {[number, number][]} points - Path samples in world X/Z.
68
+ * @param {number} radius - Nonnegative search extent in world units.
69
+ * @param {Float32Array | Float64Array | number[]} grid - Writable row-major nearest distances.
70
+ * @param {Float32Array | Float64Array | number[] | null} [valueGrid] - Optional companion grid updated when a sample wins.
71
+ * @param {(t: number) => number} [valueFn] - Value at the normalized point index. Defaults to zero.
72
+ */
73
+ function stampPath({ x0, z0, width, height, spacing }, points, radius, grid, valueGrid, valueFn) {
44
74
  if (!(spacing > 0) || !Number.isFinite(spacing) || !Number.isFinite(radius) || radius < 0) throw new RangeError('Expected positive spacing and a nonnegative radius');
45
- const rc = Math.ceil(radius / spacing);
46
- for (let s = 0; s < pts.length; s++) {
47
- const px = pts[s][0],
48
- pz = pts[s][1],
49
- ci = Math.round((px - x0) / spacing),
50
- cj = Math.round((pz - z0) / spacing);
51
- const val = valueFn ? valueFn(pts.length > 1 ? s / (pts.length - 1) : 0) : 0;
52
- for (let j = Math.max(0, cj - rc); j <= Math.min(height - 1, cj + rc); j++) {
53
- for (let i = Math.max(0, ci - rc); i <= Math.min(width - 1, ci + rc); i++) {
54
- const d = Math.hypot(i * spacing + x0 - px, j * spacing + z0 - pz),
55
- k = j * width + i;
56
- if (d < grid[k]) {
57
- grid[k] = d;
58
- if (valueGrid) valueGrid[k] = val;
75
+ const cellRadius = Math.ceil(radius / spacing);
76
+ for (let sampleIndex = 0; sampleIndex < points.length; sampleIndex++) {
77
+ const px = points[sampleIndex][0],
78
+ pz = points[sampleIndex][1],
79
+ centreColumn = Math.round((px - x0) / spacing),
80
+ centreRow = Math.round((pz - z0) / spacing);
81
+ const sampleValue = valueFn ? valueFn(points.length > 1 ? sampleIndex / (points.length - 1) : 0) : 0;
82
+ for (let j = Math.max(0, centreRow - cellRadius); j <= Math.min(height - 1, centreRow + cellRadius); j++) {
83
+ for (let i = Math.max(0, centreColumn - cellRadius); i <= Math.min(width - 1, centreColumn + cellRadius); i++) {
84
+ const distance = Math.hypot(i * spacing + x0 - px, j * spacing + z0 - pz),
85
+ cellIndex = j * width + i;
86
+ if (distance < grid[cellIndex]) {
87
+ grid[cellIndex] = distance;
88
+ if (valueGrid) valueGrid[cellIndex] = sampleValue;
59
89
  }
60
90
  }
61
91
  }
@@ -1,6 +1,6 @@
1
1
  // ════════════════════════════════════════════════════════════════════════
2
- // An instance's matrix written straight into an instanced mesh's matrices (16 numbers from `at`), for code that places
3
- // thousands of instances a frame (crowds, herds, flocks). A placement p says where: at (x, y, z), of size s, turned by ry about
2
+ // An instance's matrix written straight into an instanced mesh's matrices (16 numbers starting at `offset`), for code that places
3
+ // thousands of instances a frame (crowds, herds, flocks). The transform places each instance at (x, y, z), of size s, turned by ry about
4
4
  // the vertical and then rx and rz in Three.js's 'YXZ' order, as TRS(x, y, z, s, s, s, ry, rx, rz) composes it, without its
5
5
  // Euler angles and quaternion on the way. The placement is an object the caller makes once and fills in for each instance:
6
6
  // numbers handed over one by one to a function the engine does not take into its caller whole are made anew at every call.
@@ -8,58 +8,58 @@
8
8
  const placement = () => ({ x: 0, y: 0, z: 0, s: 1, ry: 0, rx: 0, rz: 0 });
9
9
 
10
10
  // Turned and tipped (rx), not rolled: a person of a crowd, standing or fallen, a beast of a herd.
11
- function placeAt(matrices, at, p) {
12
- const s = p.s,
13
- a = Math.cos(p.rx) * s,
14
- b = Math.sin(p.rx),
15
- c = Math.cos(p.ry),
16
- d = Math.sin(p.ry);
17
- matrices[at] = c * s;
18
- matrices[at + 1] = 0;
19
- matrices[at + 2] = -d * s;
20
- matrices[at + 3] = 0;
21
- matrices[at + 4] = d * b * s;
22
- matrices[at + 5] = a;
23
- matrices[at + 6] = c * b * s;
24
- matrices[at + 7] = 0;
25
- matrices[at + 8] = a * d;
26
- matrices[at + 9] = -b * s;
27
- matrices[at + 10] = a * c;
28
- matrices[at + 11] = 0;
29
- matrices[at + 12] = p.x;
30
- matrices[at + 13] = p.y;
31
- matrices[at + 14] = p.z;
32
- matrices[at + 15] = 1;
11
+ function placeAt(matrices, offset, transform) {
12
+ const scale = transform.s,
13
+ scaledCosPitch = Math.cos(transform.rx) * scale,
14
+ sinPitch = Math.sin(transform.rx),
15
+ cosYaw = Math.cos(transform.ry),
16
+ sinYaw = Math.sin(transform.ry);
17
+ matrices[offset] = cosYaw * scale;
18
+ matrices[offset + 1] = 0;
19
+ matrices[offset + 2] = -sinYaw * scale;
20
+ matrices[offset + 3] = 0;
21
+ matrices[offset + 4] = sinYaw * sinPitch * scale;
22
+ matrices[offset + 5] = scaledCosPitch;
23
+ matrices[offset + 6] = cosYaw * sinPitch * scale;
24
+ matrices[offset + 7] = 0;
25
+ matrices[offset + 8] = scaledCosPitch * sinYaw;
26
+ matrices[offset + 9] = -sinPitch * scale;
27
+ matrices[offset + 10] = scaledCosPitch * cosYaw;
28
+ matrices[offset + 11] = 0;
29
+ matrices[offset + 12] = transform.x;
30
+ matrices[offset + 13] = transform.y;
31
+ matrices[offset + 14] = transform.z;
32
+ matrices[offset + 15] = 1;
33
33
  }
34
34
  // Turned, tipped and rolled (rz): a bird banking into its turn.
35
- function placeBankedAt(matrices, at, p) {
36
- const s = p.s,
37
- a = Math.cos(p.rx),
38
- b = Math.sin(p.rx),
39
- c = Math.cos(p.ry),
40
- d = Math.sin(p.ry),
41
- e = Math.cos(p.rz),
42
- f = Math.sin(p.rz),
43
- ce = c * e,
44
- cf = c * f,
45
- de = d * e,
46
- df = d * f;
47
- matrices[at] = (ce + df * b) * s;
48
- matrices[at + 1] = a * f * s;
49
- matrices[at + 2] = (cf * b - de) * s;
50
- matrices[at + 3] = 0;
51
- matrices[at + 4] = (de * b - cf) * s;
52
- matrices[at + 5] = a * e * s;
53
- matrices[at + 6] = (df + ce * b) * s;
54
- matrices[at + 7] = 0;
55
- matrices[at + 8] = a * d * s;
56
- matrices[at + 9] = -b * s;
57
- matrices[at + 10] = a * c * s;
58
- matrices[at + 11] = 0;
59
- matrices[at + 12] = p.x;
60
- matrices[at + 13] = p.y;
61
- matrices[at + 14] = p.z;
62
- matrices[at + 15] = 1;
35
+ function placeBankedAt(matrices, offset, transform) {
36
+ const scale = transform.s,
37
+ cosPitch = Math.cos(transform.rx),
38
+ sinPitch = Math.sin(transform.rx),
39
+ cosYaw = Math.cos(transform.ry),
40
+ sinYaw = Math.sin(transform.ry),
41
+ cosRoll = Math.cos(transform.rz),
42
+ sinRoll = Math.sin(transform.rz),
43
+ yawRollCosines = cosYaw * cosRoll,
44
+ cosYawSinRoll = cosYaw * sinRoll,
45
+ sinYawCosRoll = sinYaw * cosRoll,
46
+ yawRollSines = sinYaw * sinRoll;
47
+ matrices[offset] = (yawRollCosines + yawRollSines * sinPitch) * scale;
48
+ matrices[offset + 1] = cosPitch * sinRoll * scale;
49
+ matrices[offset + 2] = (cosYawSinRoll * sinPitch - sinYawCosRoll) * scale;
50
+ matrices[offset + 3] = 0;
51
+ matrices[offset + 4] = (sinYawCosRoll * sinPitch - cosYawSinRoll) * scale;
52
+ matrices[offset + 5] = cosPitch * cosRoll * scale;
53
+ matrices[offset + 6] = (yawRollSines + yawRollCosines * sinPitch) * scale;
54
+ matrices[offset + 7] = 0;
55
+ matrices[offset + 8] = cosPitch * sinYaw * scale;
56
+ matrices[offset + 9] = -sinPitch * scale;
57
+ matrices[offset + 10] = cosPitch * cosYaw * scale;
58
+ matrices[offset + 11] = 0;
59
+ matrices[offset + 12] = transform.x;
60
+ matrices[offset + 13] = transform.y;
61
+ matrices[offset + 14] = transform.z;
62
+ matrices[offset + 15] = 1;
63
63
  }
64
64
 
65
65
  export { placeAt, placeBankedAt, placement };
@@ -0,0 +1,50 @@
1
+ import { cellKey } from '../math/cell-key.js';
2
+
3
+ // Index points of an append-only list. Filed x, z and radius are immutable.
4
+ export class PointBuckets {
5
+ // `list`: the things, an array that only grows; `cell`: metres to a side of a cell; `radius(item)`: how far the thing reaches
6
+ // beyond its point, if it has a size (the largest is kept, so a test can widen its reach by it).
7
+ constructor(list, cell, radius = () => 0) {
8
+ if (!(Number.isFinite(cell) && cell > 0)) throw new RangeError('Cell size must be positive and finite');
9
+ this.list = list;
10
+ this.cell = cell;
11
+ this.radius = radius;
12
+ this.widest = 0; // the largest radius filed
13
+ this.filed = 0; // how many of the list are filed
14
+ this.cells = new Map();
15
+ }
16
+ // Files what has been pushed onto the list since the last test.
17
+ catchUp() {
18
+ const { list, cell, cells } = this;
19
+ for (; this.filed < list.length; this.filed++) {
20
+ const item = list[this.filed],
21
+ key = cellKey(Math.floor(item.x / cell), Math.floor(item.z / cell));
22
+ this.widest = Math.max(this.widest, this.radius(item));
23
+ const held = cells.get(key);
24
+ if (held) held.push(item);
25
+ else cells.set(key, [item]);
26
+ }
27
+ }
28
+ // Visit candidate cells in column, row and insertion order. The predicate performs
29
+ // the exact distance or footprint test. widen extends reach by the largest filed radius.
30
+ find(x, z, reach, test, widen = false) {
31
+ this.catchUp();
32
+ const { cell, cells } = this,
33
+ searchRadius = reach + (widen ? this.widest : 0),
34
+ i1 = Math.floor((x + searchRadius) / cell),
35
+ j0 = Math.floor((z - searchRadius) / cell),
36
+ j1 = Math.floor((z + searchRadius) / cell),
37
+ i0 = Math.floor((x - searchRadius) / cell);
38
+ if (!Number.isSafeInteger(i0) || !Number.isSafeInteger(i1) || !Number.isSafeInteger(j0) || !Number.isSafeInteger(j1))
39
+ throw new RangeError('Query exceeds the supported grid coordinates');
40
+ for (let column = i0; column <= i1; column++)
41
+ for (let row = j0; row <= j1; row++) {
42
+ const held = cells.get(cellKey(column, row));
43
+ if (held) for (const item of held) if (test(item)) return item;
44
+ }
45
+ return undefined;
46
+ }
47
+ some(x, z, reach, test, widen = false) {
48
+ return this.find(x, z, reach, test, widen) !== undefined;
49
+ }
50
+ }
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Unit meshes, transforms and colour helpers for assembling models with a geometry builder.
3
+ * @module
4
+ */
5
+
1
6
  import * as THREE from 'three';
2
7
  import { TAU } from '../math/scalar.js';
3
8
  import { createNoise } from '../math/noise.js';
@@ -7,58 +12,65 @@ import { createNoise } from '../math/noise.js';
7
12
  // between two points (stick)
8
13
  // ════════════════════════════════════════════════════════════════════════
9
14
  const _m4 = new THREE.Matrix4(),
10
- _q = new THREE.Quaternion(),
11
- _eu = new THREE.Euler(),
12
- _sc = new THREE.Vector3(),
13
- _ps = new THREE.Vector3(),
14
- _cc = new THREE.Color();
15
+ rotationScratch = new THREE.Quaternion(),
16
+ eulerScratch = new THREE.Euler(),
17
+ scaleScratch = new THREE.Vector3(),
18
+ positionScratch = new THREE.Vector3(),
19
+ colorScratch = new THREE.Color();
15
20
  function TRS(x, y, z, sx = 1, sy = 1, sz = 1, ry = 0, rx = 0, rz = 0) {
16
21
  // returns a shared matrix: use it immediately
17
- _eu.set(rx, ry, rz, 'YXZ');
18
- _q.setFromEuler(_eu);
19
- return _m4.compose(_ps.set(x, y, z), _q, _sc.set(sx, sy, sz));
22
+ eulerScratch.set(rx, ry, rz, 'YXZ');
23
+ rotationScratch.setFromEuler(eulerScratch);
24
+ return _m4.compose(positionScratch.set(x, y, z), rotationScratch, scaleScratch.set(sx, sy, sz));
20
25
  }
21
26
  // A unit triangular prism, the shape of a gable roof.
22
27
  function prismGeometry() {
23
- const a = [-0.5, 0, -0.5],
24
- b = [0.5, 0, -0.5],
25
- c = [0.5, 0, 0.5],
26
- d = [-0.5, 0, 0.5],
27
- e = [0, 1, -0.5],
28
- f = [0, 1, 0.5];
29
- const g = new THREE.BufferGeometry();
30
- g.setAttribute('position', new THREE.Float32BufferAttribute([a, d, f, a, f, e, b, e, f, b, f, c, d, c, f, b, a, e].flat(), 3));
31
- g.computeVertexNormals();
32
- return g;
28
+ const backLeft = [-0.5, 0, -0.5],
29
+ backRight = [0.5, 0, -0.5],
30
+ frontRight = [0.5, 0, 0.5],
31
+ frontLeft = [-0.5, 0, 0.5],
32
+ backRidge = [0, 1, -0.5],
33
+ frontRidge = [0, 1, 0.5];
34
+ const geometry = new THREE.BufferGeometry();
35
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute([
36
+ backLeft, frontLeft, frontRidge,
37
+ backLeft, frontRidge, backRidge,
38
+ backRight, backRidge, frontRidge,
39
+ backRight, frontRidge, frontRight,
40
+ frontLeft, frontRight, frontRidge,
41
+ backRight, backLeft, backRidge,
42
+ ].flat(), 3));
43
+ geometry.computeVertexNormals();
44
+ return geometry;
33
45
  }
34
46
  // The two triangular ends of that prism alone: a gable's wall, under a roof drawn without them.
35
47
  function gableGeometry() {
36
- const g = new THREE.BufferGeometry();
37
- g.setAttribute(
48
+ const geometry = new THREE.BufferGeometry();
49
+ geometry.setAttribute(
38
50
  'position',
39
51
  new THREE.Float32BufferAttribute([-0.5, 0, 0.5, 0.5, 0, 0.5, 0, 1, 0.5, 0.5, 0, -0.5, -0.5, 0, -0.5, 0, 1, -0.5], 3),
40
52
  );
41
- g.computeVertexNormals();
42
- return g;
53
+ geometry.computeVertexNormals();
54
+ return geometry;
43
55
  }
44
56
  // The ways a face can look, as [axis, sign]
45
57
  const WAYS = { '+x': [0, 1], '-x': [0, -1], '+y': [1, 1], '-y': [1, -1], '+z': [2, 1], '-z': [2, -1] };
46
58
  // A unit shape without its flat faces that look the ways named ('+x', '-y', ...), the rest in their order: for a part whose faces
47
59
  // lie against something, where no one can see them (the back of a box fixed to a wall, the foot of a rod set in one)
48
60
  function without(shape, ...ways) {
49
- const g = shape.index ? shape.toNonIndexed() : shape,
50
- p = g.attributes.position.array,
51
- n = g.attributes.normal.array,
61
+ const sourceGeometry = shape.index ? shape.toNonIndexed() : shape,
62
+ positions = sourceGeometry.attributes.position.array,
63
+ n = sourceGeometry.attributes.normal.array,
52
64
  away = t => ways.some(w => [0, 3, 6].every(k => n[t + k + WAYS[w][0]] * WAYS[w][1] > 0.99)),
53
65
  kept = [];
54
- for (let t = 0; t < p.length; t += 9) if (!away(t)) kept.push(t);
55
- const pick = a => {
66
+ for (let t = 0; t < positions.length; t += 9) if (!away(t)) kept.push(t);
67
+ const pick = attribute => {
56
68
  const out = new Float32Array(kept.length * 9);
57
- kept.forEach((t, i) => out.set(a.subarray(t, t + 9), i * 9));
69
+ kept.forEach((t, i) => out.set(attribute.subarray(t, t + 9), i * 9));
58
70
  return new THREE.BufferAttribute(out, 3);
59
71
  },
60
72
  q = new THREE.BufferGeometry();
61
- q.setAttribute('position', pick(p));
73
+ q.setAttribute('position', pick(positions));
62
74
  q.setAttribute('normal', pick(n));
63
75
  return q;
64
76
  }
@@ -72,9 +84,9 @@ const _dir = new THREE.Vector3(),
72
84
  _a = new THREE.Vector3(),
73
85
  _b = new THREE.Vector3();
74
86
  function lump(fineness, shape) {
75
- const g = new THREE.IcosahedronGeometry(1, fineness),
76
- position = g.attributes.position.array,
77
- normal = g.attributes.normal.array,
87
+ const geometry = new THREE.IcosahedronGeometry(1, fineness),
88
+ position = geometry.attributes.position.array,
89
+ normal = geometry.attributes.normal.array,
78
90
  near = 0.03; // how far round the sphere the shape is sampled to find which way it faces
79
91
  for (let i = 0; i < position.length; i += 3) {
80
92
  _dir.set(position[i], position[i + 1], position[i + 2]).normalize();
@@ -90,7 +102,7 @@ function lump(fineness, shape) {
90
102
  position.set([_here.x, _here.y, _here.z], i);
91
103
  normal.set([_a.x, _a.y, _a.z], i);
92
104
  }
93
- return g;
105
+ return geometry;
94
106
  }
95
107
  // A stone broken from the rock, about a metre across and a little lower than it is wide: worn round by the weather, with three
96
108
  // faces where it split along its joints, and flat where it lies; shaded round where it is worn and flat on its broken faces
@@ -99,23 +111,27 @@ const STONE_JOINTS = [
99
111
  [0.62, 0.5, 0.6, 0.37],
100
112
  [-0.74, 0.18, 0.64, 0.39],
101
113
  [0.12, 0.3, -0.95, 0.4],
102
- ].map(([x, y, z, d]) => [x / Math.hypot(x, y, z), y / Math.hypot(x, y, z), z / Math.hypot(x, y, z), d]); // [the face's normal, its distance from the middle]
114
+ ].map(([x, y, z, planeDistance]) => [x / Math.hypot(x, y, z), y / Math.hypot(x, y, z), z / Math.hypot(x, y, z), planeDistance]); // [the face's normal, its distance from the middle]
103
115
  const box = new THREE.BoxGeometry(1, 1, 1).translate(0, 0.5, 0),
104
116
  cyl6 = new THREE.CylinderGeometry(0.5, 0.5, 1, 6).translate(0, 0.5, 0);
117
+ /**
118
+ * Build a library of reusable unit geometries for scenery, roofs and figures.
119
+ * @param fbm - Fractal noise sampler used to shape the rock. Pass the world’s seeded sampler to reproduce it.
120
+ */
105
121
  export function createUnitShapes(fbm = createNoise().fbm) {
106
122
  function stonePoint(dir, out) {
107
123
  let r = 0.5 * (0.8 + 0.4 * fbm(dir.x * 1.7 + 3, dir.z * 1.7 + dir.y * 1.3, 2, 190));
108
- for (const [nx, ny, nz, d] of STONE_JOINTS) {
124
+ for (const [nx, ny, nz, planeDistance] of STONE_JOINTS) {
109
125
  const towards = dir.x * nx + dir.y * ny + dir.z * nz;
110
- if (towards > 0.05) r = Math.min(r, d / towards);
126
+ if (towards > 0.05) r = Math.min(r, planeDistance / towards);
111
127
  }
112
128
  return out.set(dir.x * r, Math.max(dir.y * r * 0.82, -0.3), dir.z * r);
113
129
  }
114
130
  function brokenStone() {
115
- const g = lump(1, stonePoint);
131
+ const geometry = lump(1, stonePoint);
116
132
  // white vertex colours: an instanced rock on a material that reads vertex colours would otherwise be drawn black
117
- g.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(g.attributes.position.count * 3).fill(1), 3));
118
- return g;
133
+ geometry.setAttribute('color', new THREE.Float32BufferAttribute(new Float32Array(geometry.attributes.position.count * 3).fill(1), 3));
134
+ return geometry;
119
135
  }
120
136
  return {
121
137
  box,
@@ -145,14 +161,14 @@ export function createUnitShapes(fbm = createNoise().fbm) {
145
161
  dome16: new THREE.SphereGeometry(0.5, 20, 8, 0, TAU, 0, Math.PI / 2),
146
162
  };
147
163
  }
148
- function C(hex, jitter = 0, rng) {
164
+ function C(hex, jitter = 0, random) {
149
165
  // sRGB hex -> linear [r,g,b], optionally brightness-jittered
150
- _cc.setHex(hex);
151
- const k = jitter && rng ? 1 + (rng() - 0.5) * 2 * jitter : 1;
152
- return [_cc.r * k, _cc.g * k, _cc.b * k];
166
+ colorScratch.setHex(hex);
167
+ const k = jitter && random ? 1 + (random() - 0.5) * 2 * jitter : 1;
168
+ return [colorScratch.r * k, colorScratch.g * k, colorScratch.b * k];
153
169
  }
154
170
 
155
- // A rod of radius r from point a to point b ([x, y, z]), added to the builder gb.
171
+ // Append a rod of the given radius between the start and end points, both [x, y, z].
156
172
  const _rod = {
157
173
  m: new THREE.Matrix4(),
158
174
  at: new THREE.Vector3(),
@@ -161,12 +177,12 @@ const _rod = {
161
177
  way: new THREE.Vector3(),
162
178
  },
163
179
  UP = new THREE.Vector3(0, 1, 0);
164
- function stick(gb, a, b, r, col, geo = cyl6) {
180
+ function stick(builder, start, end, radius, color, geometry = cyl6) {
165
181
  const { m, at, turn, size, way } = _rod;
166
- way.set(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
182
+ way.set(end[0] - start[0], end[1] - start[1], end[2] - start[2]);
167
183
  const len = way.length();
168
184
  turn.setFromUnitVectors(UP, way.divideScalar(len));
169
- gb.add(geo, col, m.compose(at.set(a[0], a[1], a[2]), turn, size.set(r, len, r)));
185
+ builder.add(geometry, color, m.compose(at.set(start[0], start[1], start[2]), turn, size.set(radius, len, radius)));
170
186
  }
171
187
 
172
188
  export { box, C, TRS, lump, stick, without };
@@ -13,12 +13,12 @@ export function createSaggingTube({ spanSegments, radialSegments, radius, slack
13
13
  if (![radius, slack, extraLength].every(Number.isFinite) || radius <= 0 || slack < 1 || extraLength < 0) {
14
14
  throw new RangeError('Expected a positive radius, slack of at least one and nonnegative extra length');
15
15
  }
16
- const _p = new THREE.Vector3(),
17
- _t = new THREE.Vector3(),
18
- _n = new THREE.Vector3(),
19
- _b = new THREE.Vector3(),
16
+ const pointScratch = new THREE.Vector3(),
17
+ tangentScratch = new THREE.Vector3(),
18
+ normalScratch = new THREE.Vector3(),
19
+ binormalScratch = new THREE.Vector3(),
20
20
  UP = new THREE.Vector3(0, 1, 0);
21
- return function update(anchors, count, pos, nor) {
21
+ return function update(anchors, count, positions, normals) {
22
22
  let ring = 0;
23
23
  for (let s = 0; s < count - 1; s++) {
24
24
  const from = anchors[s],
@@ -28,29 +28,29 @@ export function createSaggingTube({ spanSegments, radialSegments, radius, slack
28
28
  sag = Math.sqrt((3 * span * Math.max(0, length - span)) / 8); // a parabola of that length over that span
29
29
  for (let j = s ? 1 : 0; j <= spanSegments; j++, ring++) {
30
30
  const u = j / spanSegments;
31
- _p.lerpVectors(from, to, u);
32
- _p.y -= sag * 4 * u * (1 - u);
33
- _t.subVectors(to, from);
34
- _t.y -= sag * 4 * (1 - 2 * u);
35
- _t.normalize();
36
- _n.crossVectors(_t, UP);
37
- if (_n.lengthSq() < 1e-6) _n.set(1, 0, 0);
38
- _n.normalize();
39
- _b.crossVectors(_n, _t);
31
+ pointScratch.lerpVectors(from, to, u);
32
+ pointScratch.y -= sag * 4 * u * (1 - u);
33
+ tangentScratch.subVectors(to, from);
34
+ tangentScratch.y -= sag * 4 * (1 - 2 * u);
35
+ tangentScratch.normalize();
36
+ normalScratch.crossVectors(tangentScratch, UP);
37
+ if (normalScratch.lengthSq() < 1e-6) normalScratch.set(1, 0, 0);
38
+ normalScratch.normalize();
39
+ binormalScratch.crossVectors(normalScratch, tangentScratch);
40
40
  for (let k = 0; k < radialSegments; k++) {
41
- const a = (k / radialSegments) * Math.PI * 2,
42
- c = Math.cos(a),
43
- d = Math.sin(a),
44
- o = (ring * radialSegments + k) * 3,
45
- nx = _n.x * c + _b.x * d,
46
- ny = _n.y * c + _b.y * d,
47
- nz = _n.z * c + _b.z * d;
48
- nor[o] = nx;
49
- nor[o + 1] = ny;
50
- nor[o + 2] = nz;
51
- pos[o] = _p.x + nx * radius;
52
- pos[o + 1] = _p.y + ny * radius;
53
- pos[o + 2] = _p.z + nz * radius;
41
+ const ringAngle = (k / radialSegments) * Math.PI * 2,
42
+ cosAngle = Math.cos(ringAngle),
43
+ sinAngle = Math.sin(ringAngle),
44
+ positionOffset = (ring * radialSegments + k) * 3,
45
+ nx = normalScratch.x * cosAngle + binormalScratch.x * sinAngle,
46
+ ny = normalScratch.y * cosAngle + binormalScratch.y * sinAngle,
47
+ nz = normalScratch.z * cosAngle + binormalScratch.z * sinAngle;
48
+ normals[positionOffset] = nx;
49
+ normals[positionOffset + 1] = ny;
50
+ normals[positionOffset + 2] = nz;
51
+ positions[positionOffset] = pointScratch.x + nx * radius;
52
+ positions[positionOffset + 1] = pointScratch.y + ny * radius;
53
+ positions[positionOffset + 2] = pointScratch.z + nz * radius;
54
54
  }
55
55
  }
56
56
  }