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
package/motion/weather.js CHANGED
@@ -1,5 +1,39 @@
1
+ /**
2
+ * Advance regional rain, dampness, dust and dawn mist for a world clock.
3
+ * @module
4
+ */
5
+
1
6
  import { sstep } from '../math/scalar.js';
2
7
 
8
+ /**
9
+ * Create an independent weather clock. The returned function advances the region’s
10
+ * spell timer and writes atmospheric intensities into a caller-owned state object.
11
+ * Keep that object between frames so cloud cover can build before rain and the
12
+ * ground can dry after it stops. Changing the region identity restarts its timer.
13
+ * @param {object} [options] - Weather timing and random source.
14
+ * @param {() => number} [options.random] - Random stream in [0, 1). Supply a seeded generator for repeatable spell timing.
15
+ * @param {number} [options.dawn] - Time of peak morning mist as a fraction of the day.
16
+ * @param {number} [options.mistWidth] - Width of the dawn mist curve in fractions of a day.
17
+ * @param {number} [options.fullReach] - Fraction of a local spell’s radius inside which it has full strength.
18
+ * @param {number} [options.dustRise] - Seconds for storm dust to rise from zero to full strength.
19
+ * @param {number} [options.dustSettle] - Seconds for storm dust to settle from full strength to zero.
20
+ * @example
21
+ * ```js
22
+ * import { mulberry32 } from 'roamwright';
23
+ * import { createWeather } from 'roamwright/motion/weather.js';
24
+ * import { createWind } from 'roamwright/motion/wind.js';
25
+ *
26
+ * const updateWeather = createWeather({ random: mulberry32(42) });
27
+ * const wind = createWind({ speed: 3 });
28
+ * const state = { wet: 0, rain: 0, damp: 0, gust: 0, dust: 0, dustStorm: 0, mist: 0, storm: -1 };
29
+ * const coast = { spell: 'squall', every: [30, 60], lasts: [15, 25], mist: true };
30
+ * function frame(elapsedSeconds, deltaSeconds, dayFraction) {
31
+ * updateWeather(state, deltaSeconds, dayFraction, { region: 'coast', weather: coast, x: 0, z: 0 });
32
+ * wind.update(elapsedSeconds, state.gust);
33
+ * }
34
+ * frame(1, 1, 0.25);
35
+ * ```
36
+ */
3
37
  export function createWeather({
4
38
  random = Math.random,
5
39
  dawn: DAWN = 0.25,
@@ -13,47 +47,62 @@ export function createWeather({
13
47
  // v moved toward goal by at most step.
14
48
  const toward = (v, goal, step) => (v < goal ? Math.min(goal, v + step) : Math.max(goal, v - step));
15
49
 
16
- // Each frame: env's weather (wet, rain, damp, gust, dust, mist) moved on by dt seconds; hour is the clock, 0 to 1.
17
- function updateWeather(env, dt, hour, { region, weather: w, x, z, running = true, quiet = false, ambientDust = 0 }) {
18
- if (!w) {
19
- env.wet = env.rain = env.damp = env.gust = env.dustStorm = env.mist = 0;
20
- env.dust = ambientDust;
50
+ /**
51
+ * @param {{wet: number, rain: number, damp: number, gust: number, dust: number, dustStorm: number, mist: number, storm?: number}} weatherState -
52
+ * Mutable intensities. Use storm = -1 for the region’s automatic cycle, or 0–1 to override the spell strength.
53
+ * @param {number} deltaSeconds - Seconds since the previous update.
54
+ * @param {number} hour - Fraction of one day, from 0 to 1.
55
+ * @param {object} location - Observer and region for this frame.
56
+ * @param {unknown} location.region - Stable identity for the current region.
57
+ * @param {{spell?: string, every?: [number, number], lasts?: [number, number], mist?: boolean, reach?: number, x?: number, z?: number} | null} location.weather -
58
+ * Set spell to rain, squall or dust and supply minimum/maximum seconds in every and lasts.
59
+ * For a local spell, set its centre (x, z) and reach in world units. Null clears the weather.
60
+ * @param {number} location.x - Observer’s world X.
61
+ * @param {number} location.z - Observer’s world Z.
62
+ * @param {boolean} [location.running] - Advance the spell timer while true.
63
+ * @param {boolean} [location.quiet] - Suppress spells and dawn mist while true.
64
+ * @param {number} [location.ambientDust] - Local background dust intensity.
65
+ */
66
+ function updateWeather(weatherState, deltaSeconds, hour, { region, weather: regionWeather, x, z, running = true, quiet = false, ambientDust = 0 }) {
67
+ if (!regionWeather) {
68
+ weatherState.wet = weatherState.rain = weatherState.damp = weatherState.gust = weatherState.dustStorm = weatherState.mist = 0;
69
+ weatherState.dust = ambientDust;
21
70
  return;
22
71
  }
23
72
  if (clock.land !== region) {
24
73
  // a land just come to: its first spell is a while off
25
74
  clock.land = region;
26
75
  clock.on = false;
27
- clock.next = w.spell ? between(w.every) * (0.5 + 0.5 * random()) : 0;
76
+ clock.next = regionWeather.spell ? between(regionWeather.every) * (0.5 + 0.5 * random()) : 0;
28
77
  }
29
- if (w.spell && running) {
30
- clock.next -= dt;
78
+ if (regionWeather.spell && running) {
79
+ clock.next -= deltaSeconds;
31
80
  if (clock.next <= 0) {
32
81
  clock.on = !clock.on;
33
- clock.next = between(clock.on ? w.lasts : w.every);
82
+ clock.next = between(clock.on ? regionWeather.lasts : regionWeather.every);
34
83
  }
35
84
  }
36
- let spell = !w.spell || quiet ? 0 : env.storm >= 0 ? env.storm : clock.on ? 1 : 0;
37
- if (spell && w.reach) spell *= sstep(w.reach, w.reach * SPELL_FADE, Math.hypot(x - w.x, z - w.z));
38
- const dusty = w.spell === 'dust',
39
- squall = w.spell === 'squall',
85
+ let spell = !regionWeather.spell || quiet ? 0 : weatherState.storm >= 0 ? weatherState.storm : clock.on ? 1 : 0;
86
+ if (spell && regionWeather.reach) spell *= sstep(regionWeather.reach, regionWeather.reach * SPELL_FADE, Math.hypot(x - regionWeather.x, z - regionWeather.z));
87
+ const dusty = regionWeather.spell === 'dust',
88
+ squall = regionWeather.spell === 'squall',
40
89
  wetGoal = dusty ? 0 : spell,
41
- raining = wetGoal > 0.5 && env.wet > 0.75;
90
+ raining = wetGoal > 0.5 && weatherState.wet > 0.75;
42
91
  // clouds gather in under a minute (a squall's sooner) and break up more slowly; the rain waits for the cloud, and stops before it breaks
43
- env.wet = toward(env.wet, wetGoal, dt / (wetGoal > env.wet ? (squall ? 22 : 40) : 70));
44
- env.rain = toward(env.rain, raining ? 1 : 0, dt / (raining ? 14 : 8));
45
- env.damp = toward(env.damp, env.rain > 0.3 ? 1 : 0, dt / (env.rain > 0.3 ? 45 : 240));
46
- env.gust = squall ? env.wet : 0;
92
+ weatherState.wet = toward(weatherState.wet, wetGoal, deltaSeconds / (wetGoal > weatherState.wet ? (squall ? 22 : 40) : 70));
93
+ weatherState.rain = toward(weatherState.rain, raining ? 1 : 0, deltaSeconds / (raining ? 14 : 8));
94
+ weatherState.damp = toward(weatherState.damp, weatherState.rain > 0.3 ? 1 : 0, deltaSeconds / (weatherState.rain > 0.3 ? 45 : 240));
95
+ weatherState.gust = squall ? weatherState.wet : 0;
47
96
  // dust: the storm's, what the viewer stands in already (local airborne dust), or a scene's own
48
- env.dustStorm = toward(
49
- env.dustStorm,
97
+ weatherState.dustStorm = toward(
98
+ weatherState.dustStorm,
50
99
  dusty ? spell : 0,
51
- dt / (dusty && spell > env.dustStorm ? DUST_RISES : DUST_SETTLES),
100
+ deltaSeconds / (dusty && spell > weatherState.dustStorm ? DUST_RISES : DUST_SETTLES),
52
101
  );
53
- env.dust = Math.max(env.dustStorm, ambientDust);
54
- const clear = (1 - env.wet) * (1 - env.dust),
102
+ weatherState.dust = Math.max(weatherState.dustStorm, ambientDust);
103
+ const clear = (1 - weatherState.wet) * (1 - weatherState.dust),
55
104
  apart = (hour - DAWN) / MIST_HOURS;
56
- env.mist = toward(env.mist, w.mist && !quiet ? Math.exp(-apart * apart) * clear : 0, dt / 6);
105
+ weatherState.mist = toward(weatherState.mist, regionWeather.mist && !quiet ? Math.exp(-apart * apart) * clear : 0, deltaSeconds / 6);
57
106
  }
58
107
  return updateWeather;
59
108
  }
package/motion/wind.js CHANGED
@@ -1,6 +1,23 @@
1
+ /**
2
+ * Share the same horizontal wind between simulation code and shader effects.
3
+ * @module
4
+ */
5
+
1
6
  import { Vector2, Vector3 } from 'three';
2
7
  import { clamp } from '../math/scalar.js';
3
8
 
9
+ /**
10
+ * Create a wind field with a slowly varying heading and gust strength. The
11
+ * returned wind state and uniforms keep their identity across updates. Bind the
12
+ * uniforms to materials once, then call `update(elapsedSeconds, squall)` per frame.
13
+ * @param {object} [options] - Prevailing wind and its variation.
14
+ * @param {number} [options.speed] - Base speed in metres per second.
15
+ * @param {number} [options.direction] - Heading in radians from +X toward +Z.
16
+ * @param {number} [options.swing] - Maximum angular deviation from the heading in radians.
17
+ * @param {number} [options.squallGain] - Fractional speed increase at full squall strength.
18
+ * @returns `wind` holds a unit direction (x, z), speed and gust. In the shader,
19
+ * `uWind.xy` is X/Z velocity, `uWind.z` is gust, and `uWindDrift` is accumulated displacement in metres.
20
+ */
4
21
  export function createWind({ speed: BREEZE = 1, swing: SWING = 0.16, direction: QUARTER = 0, squallGain: SQUALL = 1 } = {}) {
5
22
  const wind = { x: 1, z: 0, speed: BREEZE, gust: 0.5 }; // (x, z): the way it blows, a unit vector; speed in metres a second; gust 0 to 1
6
23
  // For shaders: xy the wind's velocity in metres a second (world x, z), z its gust from 0 to 1
@@ -8,20 +25,22 @@ export function createWind({ speed: BREEZE = 1, swing: SWING = 0.16, direction:
8
25
  const windU = { uWind: { value: new Vector3(BREEZE, 0, 0.5) }, uWindDrift: { value: new Vector2() } };
9
26
  let lastT = 0;
10
27
 
11
- // Each frame, from the time elapsed in seconds and how hard a squall blows (0 to 1). The gust is handed in, not read
12
- // from the environment, so that the materials the pool's workers load with a job's module do not bring the renderer with them.
13
- function updateWind(t, squall) {
14
- const a = QUARTER + SWING * Math.sin(t * 0.071),
15
- g = clamp(0.5 + 0.22 * Math.sin(t * 0.21) + 0.18 * Math.sin(t * 0.077 + 1.3) + 0.1 * Math.sin(t * 0.53 + 2.1), 0, 1);
16
- wind.x = Math.cos(a);
17
- wind.z = Math.sin(a);
18
- wind.gust = Math.max(g, squall);
19
- wind.speed = BREEZE * (0.75 + 0.5 * g) * (1 + SQUALL * squall);
28
+ /**
29
+ * @param {number} elapsedSeconds - Total elapsed simulation time in seconds. Drift advances by at most 0.25 seconds per update.
30
+ * @param {number} squall - Squall strength from 0 to 1. Pass zero for fair weather.
31
+ */
32
+ function updateWind(elapsedSeconds, squall) {
33
+ const heading = QUARTER + SWING * Math.sin(elapsedSeconds * 0.071),
34
+ gustStrength = clamp(0.5 + 0.22 * Math.sin(elapsedSeconds * 0.21) + 0.18 * Math.sin(elapsedSeconds * 0.077 + 1.3) + 0.1 * Math.sin(elapsedSeconds * 0.53 + 2.1), 0, 1);
35
+ wind.x = Math.cos(heading);
36
+ wind.z = Math.sin(heading);
37
+ wind.gust = Math.max(gustStrength, squall);
38
+ wind.speed = BREEZE * (0.75 + 0.5 * gustStrength) * (1 + SQUALL * squall);
20
39
  windU.uWind.value.set(wind.x * wind.speed, wind.z * wind.speed, wind.gust);
21
- const dt = Math.min(0.25, Math.max(0, t - lastT)); // a long pause carries nothing far
22
- lastT = t;
23
- windU.uWindDrift.value.x += wind.x * wind.speed * dt;
24
- windU.uWindDrift.value.y += wind.z * wind.speed * dt;
40
+ const deltaSeconds = Math.min(0.25, Math.max(0, elapsedSeconds - lastT)); // a long pause carries nothing far
41
+ lastT = elapsedSeconds;
42
+ windU.uWindDrift.value.x += wind.x * wind.speed * deltaSeconds;
43
+ windU.uWindDrift.value.y += wind.z * wind.speed * deltaSeconds;
25
44
  }
26
45
  return { wind, uniforms: windU, update: updateWind };
27
46
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.4.0",
3
+ "version": "0.20.1",
4
4
  "description": "A procedural worldbuilding engine built on top of Three.js. Generate landscapes with rivers and changing weather, animate crowds, and explore on foot or in flight.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -35,14 +35,18 @@
35
35
  "test": "node --test test/*.test.js",
36
36
  "demo": "python3 scripts/serve.py",
37
37
  "test:browser": "node test/browser.mjs",
38
- "test:package": "node test/package.mjs"
38
+ "test:package": "node test/package.mjs",
39
+ "docs": "typedoc"
39
40
  },
40
41
  "peerDependencies": {
41
42
  "three": "0.170.0 || 0.187.0"
42
43
  },
43
44
  "devDependencies": {
45
+ "@types/three": "0.187.0",
44
46
  "playwright": "1.65.1",
45
- "three": "0.187.0"
47
+ "three": "0.187.0",
48
+ "typedoc": "0.28.20",
49
+ "typescript": "5.9.3"
46
50
  },
47
51
  "publishConfig": {
48
52
  "access": "public"
@@ -59,18 +59,18 @@ export function createCasterMotion({ scene, elapsed, listInterval = 2, skinnedRa
59
59
  // One mesh's share: its instances within reach, each by its place in the world (by the mesh's own matrix, mostly none) and turn.
60
60
  function shareOf(o, w, x, y, z, reach) {
61
61
  if (!o.geometry.boundingSphere) o.geometry.computeBoundingSphere();
62
- const a = o.instanceMatrix.array,
62
+ const instanceMatrices = o.instanceMatrix.array,
63
63
  r = reach + o.geometry.boundingSphere.radius;
64
64
  let sum = 0;
65
65
  for (let k = 0; k < o.count; k++) {
66
66
  const j = k * 16,
67
- px = a[j + 12],
68
- py = a[j + 13],
69
- pz = a[j + 14],
67
+ px = instanceMatrices[j + 12],
68
+ py = instanceMatrices[j + 13],
69
+ pz = instanceMatrices[j + 14],
70
70
  wx = w[0] * px + w[4] * py + w[8] * pz + w[12],
71
71
  wy = w[1] * px + w[5] * py + w[9] * pz + w[13],
72
72
  wz = w[2] * px + w[6] * py + w[10] * pz + w[14];
73
- if ((wx - x) ** 2 + (wy - y) ** 2 + (wz - z) ** 2 < r * r) sum += (k + 1) * (wx + 3 * wy + 7 * wz + a[j] + 5 * a[j + 2]);
73
+ if ((wx - x) ** 2 + (wy - y) ** 2 + (wz - z) ** 2 < r * r) sum += (k + 1) * (wx + 3 * wy + 7 * wz + instanceMatrices[j] + 5 * instanceMatrices[j + 2]);
74
74
  }
75
75
  return sum;
76
76
  }
@@ -14,104 +14,121 @@ import * as THREE from 'three';
14
14
  *
15
15
  * @param {object} [options]
16
16
  * @param {number} [options.square=500] Metres: far copies are batched by kind within squares of this side.
17
+ * @param {boolean} [options.compact=false] Pack only visible transforms and colours when a cell changes.
18
+ * Use for static cells whose materials depend on their transform and colour, not their instance index or other instance attributes.
17
19
  * @param {number} [options.tableWidth=64] Texels across the table of what each cell shows.
18
20
  * @param {number} [options.thinFrom=0.45] Beyond this share of the drawing distance a thinned cell keeps `thinTo` of its instances.
19
21
  * @param {number} [options.thinTo=0.55]
20
22
  */
21
- export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45, thinTo = 0.55 } = {}) {
23
+ export function createCellLod({ square = 500, compact = false, tableWidth = 64, thinFrom = 0.45, thinTo = 0.55 } = {}) {
22
24
  const table = { data: null, tex: null },
23
25
  shown = { value: null }, // the table, as the uniform the far materials and the far shadow body share
24
- batches = [];
25
- let batchShows = null,
26
- depth = null, distanceMaterial = null;
26
+ batches = [],
27
+ members = [];
28
+ let drawEnds = null,
29
+ dirty = null,
30
+ depth = null,
31
+ distanceMaterial = null;
27
32
 
28
33
  // Hides, in the vertex shader, a copy whose cell is not showing its far copy or that lies past the cell's `count`.
29
- function hideUnshown(sh) {
30
- sh.uniforms.uFarShown = shown;
31
- sh.vertexShader = sh.vertexShader
34
+ function hideUnshown(shader) {
35
+ shader.uniforms.uFarShown = shown;
36
+ shader.vertexShader = shader.vertexShader
32
37
  .replace('#include <common>', '#include <common>\nattribute vec2 aFar; uniform sampler2D uFarShown;')
33
- .replace(
34
- '#include <project_vertex>',
35
- `/* glsl */
36
- #include <project_vertex>
37
- if (aFar.y >= texelFetch(uFarShown, ivec2(int(aFar.x) % ${tableWidth}, int(aFar.x) / ${tableWidth}), 0).r) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);`,
38
- );
38
+ .replace(/void\s+main\s*\(\s*(?:void)?\s*\)\s*\{/, match => `${match}
39
+ if (aFar.y >= texelFetch(uFarShown, ivec2(int(aFar.x) % ${tableWidth}, int(aFar.x) / ${tableWidth}), 0).r) {
40
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
41
+ return;
42
+ }`);
39
43
  }
40
44
  // A far copy's material: the cell's own, cloned once per material, with its own patch kept and the hiding added.
41
45
  function farMaterial(base, cache) {
42
46
  if (cache.has(base)) return cache.get(base);
43
- const m = base.clone(),
47
+ const material = base.clone(),
44
48
  inner = base.onBeforeCompile,
45
49
  key = base.customProgramCacheKey();
46
- m.onBeforeCompile = (sh, r) => {
47
- inner.call(base, sh, r);
48
- hideUnshown(sh);
50
+ material.onBeforeCompile = (shader, r) => {
51
+ inner.call(base, shader, r);
52
+ hideUnshown(shader);
49
53
  };
50
- m.customProgramCacheKey = () => key + ':far-batch';
51
- cache.set(base, m);
52
- return m;
54
+ material.customProgramCacheKey = () => key + ':far-batch';
55
+ cache.set(base, material);
56
+ return material;
53
57
  }
54
58
  // The shadow body of far copies that cast: the far shape itself, hidden as in the picture, so a cell casts what it shows.
55
59
  function depthMaterial() {
56
60
  if (depth) return depth;
57
61
  depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });
58
- depth.onBeforeCompile = hideUnshown;
59
- depth.customProgramCacheKey = () => 'far-batch-depth';
62
+ if (!compact) {
63
+ depth.onBeforeCompile = hideUnshown;
64
+ depth.customProgramCacheKey = () => 'far-batch-depth';
65
+ }
60
66
  return depth;
61
67
  }
62
68
 
63
69
  /** Batches the far copies of `cells` (taken out of their parents) into `parent`; returns the batches. */
64
70
  function batch(cellList, parent) {
65
- const cells = cellList.filter(t => t.lo && t.lo.isInstancedMesh),
71
+ const cells = cellList.filter(cell => cell.lo && cell.lo.isInstancedMesh),
66
72
  groups = new Map(),
67
73
  materials = new Map();
68
74
  table.data = new Float32Array(tableWidth * Math.ceil(cells.length / tableWidth));
69
- table.tex = new THREE.DataTexture(table.data, tableWidth, table.data.length / tableWidth, THREE.RedFormat, THREE.FloatType);
70
- table.tex.needsUpdate = true;
71
- shown.value = table.tex;
72
- cells.forEach((t, slot) => {
73
- const lo = t.lo,
75
+ if (!compact) {
76
+ table.tex = new THREE.DataTexture(table.data, tableWidth, table.data.length / tableWidth, THREE.RedFormat, THREE.FloatType);
77
+ table.tex.needsUpdate = true;
78
+ shown.value = table.tex;
79
+ }
80
+ cells.forEach((cell, slot) => {
81
+ const lo = cell.lo,
74
82
  key = [
75
83
  lo.geometry.uuid,
76
84
  lo.material.uuid,
77
85
  lo.layers.mask,
78
86
  lo.receiveShadow,
79
- t.mesh.castShadow,
80
- Math.floor(t.cx / square),
81
- Math.floor(t.cz / square),
87
+ cell.mesh.castShadow,
88
+ Math.floor(cell.cx / square),
89
+ Math.floor(cell.cz / square),
82
90
  ].join('|');
83
- let g = groups.get(key);
84
- if (!g) groups.set(key, (g = { lo, casts: t.mesh.castShadow, cells: [] }));
85
- g.cells.push(t);
86
- t.far = slot;
87
- t.farN = lo.instanceMatrix.count;
88
- t.lo = null;
91
+ let group = groups.get(key);
92
+ if (!group) groups.set(key, (group = { lo, casts: cell.mesh.castShadow, cells: [] }));
93
+ group.cells.push(cell);
94
+ cell.far = slot;
95
+ cell.farN = lo.instanceMatrix.count;
96
+ cell.lo = null;
89
97
  lo.removeFromParent();
90
98
  });
91
99
  for (const { lo, casts, cells: list } of groups.values()) {
92
- for (const t of list) t.farBatch = batches.length;
93
- const n = list.reduce((s, t) => s + t.farN, 0),
94
- geo = new THREE.BufferGeometry();
95
- for (const name in lo.geometry.attributes) geo.setAttribute(name, lo.geometry.attributes[name]);
96
- geo.setIndex(lo.geometry.index);
97
- geo.boundingSphere = lo.geometry.boundingSphere;
98
- geo.boundingBox = lo.geometry.boundingBox;
99
- const ids = new Float32Array(n * 2),
100
- mesh = new THREE.InstancedMesh(geo, farMaterial(lo.material, materials), n);
101
- if (lo.instanceColor) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(n * 3), 3);
100
+ const instanceCount = list.reduce((total, cell) => total + cell.farN, 0),
101
+ geometry = new THREE.BufferGeometry();
102
+ for (const name in lo.geometry.attributes) geometry.setAttribute(name, lo.geometry.attributes[name]);
103
+ geometry.setIndex(lo.geometry.index);
104
+ geometry.boundingSphere = lo.geometry.boundingSphere;
105
+ geometry.boundingBox = lo.geometry.boundingBox;
106
+ const ids = compact ? null : new Float32Array(instanceCount * 2),
107
+ mesh = new THREE.InstancedMesh(geometry, compact ? lo.material : farMaterial(lo.material, materials), instanceCount);
108
+ if (lo.instanceColor) mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(instanceCount * 3), 3);
102
109
  let at = 0;
103
- for (const t of list) {
104
- const src = t.mesh.instanceMatrix.array,
105
- col = t.mesh.instanceColor?.array;
106
- mesh.instanceMatrix.array.set(src.subarray(0, t.farN * 16), at * 16);
107
- if (col && mesh.instanceColor) mesh.instanceColor.array.set(col.subarray(0, t.farN * 3), at * 3);
108
- for (let i = 0; i < t.farN; i++) {
109
- ids[(at + i) * 2] = t.far;
110
- ids[(at + i) * 2 + 1] = i;
110
+ for (const cell of list) {
111
+ cell.farBatch = batches.length;
112
+ cell.farStart = at;
113
+ if (cell.lod) cell.lod.batch = cell.farBatch;
114
+ const src = cell.mesh.instanceMatrix.array,
115
+ col = cell.mesh.instanceColor?.array;
116
+ mesh.instanceMatrix.array.set(src.subarray(0, cell.farN * 16), at * 16);
117
+ if (col && mesh.instanceColor) mesh.instanceColor.array.set(col.subarray(0, cell.farN * 3), at * 3);
118
+ if (ids) {
119
+ for (let i = 0; i < cell.farN; i++) {
120
+ ids[(at + i) * 2] = cell.far;
121
+ ids[(at + i) * 2 + 1] = i;
122
+ }
111
123
  }
112
- at += t.farN;
124
+ at += cell.farN;
125
+ }
126
+ if (ids) geometry.setAttribute('aFar', new THREE.InstancedBufferAttribute(ids, 2));
127
+ if (compact) {
128
+ mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
129
+ mesh.instanceColor?.setUsage(THREE.DynamicDrawUsage);
130
+ members.push(list);
113
131
  }
114
- geo.setAttribute('aFar', new THREE.InstancedBufferAttribute(ids, 2));
115
132
  mesh.layers.mask = lo.layers.mask;
116
133
  mesh.receiveShadow = lo.receiveShadow;
117
134
  mesh.castShadow = casts; // as the near copies do
@@ -119,8 +136,10 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
119
136
  mesh.customDepthMaterial = depthMaterial();
120
137
  if (!distanceMaterial) {
121
138
  distanceMaterial = new THREE.MeshDistanceMaterial();
122
- distanceMaterial.onBeforeCompile = hideUnshown;
123
- distanceMaterial.customProgramCacheKey = () => 'far-batch-distance';
139
+ if (!compact) {
140
+ distanceMaterial.onBeforeCompile = hideUnshown;
141
+ distanceMaterial.customProgramCacheKey = () => 'far-batch-distance';
142
+ }
124
143
  }
125
144
  mesh.customDistanceMaterial = distanceMaterial;
126
145
  mesh.userData.partShown = true; // a pass drawing heights with a plain depth material would show every copy
@@ -130,14 +149,41 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
130
149
  parent.add(mesh);
131
150
  batches.push(mesh);
132
151
  }
133
- batchShows = new Int32Array(batches.length);
152
+ drawEnds = new Int32Array(batches.length);
153
+ if (compact) dirty = new Uint8Array(batches.length).fill(1);
134
154
  return batches;
135
155
  }
136
156
 
157
+ // Near cells own the immutable source records. Keep their order so overlapping
158
+ // surfaces and transparent instances blend exactly as in the original batch.
159
+ function packVisible(batchIndex) {
160
+ const mesh = batches[batchIndex];
161
+ let end = 0;
162
+ for (const cell of members[batchIndex]) {
163
+ const visibleCount = Math.min(table.data[cell.far], cell.farN);
164
+ if (!visibleCount) continue;
165
+ mesh.instanceMatrix.array.set(cell.mesh.instanceMatrix.array.subarray(0, visibleCount * 16), end * 16);
166
+ if (mesh.instanceColor) {
167
+ const colour = cell.mesh.instanceColor;
168
+ if (colour) mesh.instanceColor.array.set(colour.array.subarray(0, visibleCount * 3), end * 3);
169
+ else mesh.instanceColor.array.fill(0, end * 3, (end + visibleCount) * 3);
170
+ }
171
+ end += visibleCount;
172
+ }
173
+ mesh.count = end;
174
+ if (!end) return;
175
+ for (const attribute of [mesh.instanceMatrix, mesh.instanceColor]) {
176
+ if (!attribute) continue;
177
+ attribute.clearUpdateRanges();
178
+ attribute.addUpdateRange(0, end * attribute.itemSize);
179
+ attribute.needsUpdate = true;
180
+ }
181
+ }
182
+
137
183
  // Where a cell lies and how far it is drawn, kept on it in a record of one shape: cells come from builders of many shapes,
138
184
  // and a number read from objects of so many shapes is made anew at every read. A cell does not move.
139
- const lodOf = t =>
140
- (t.lod ??= { cx: t.cx, cy: t.cy ?? 0, cz: t.cz, r: t.r, until: t.until ?? Infinity, near: t.near ?? Infinity, batch: t.farBatch ?? -1 });
185
+ const lodOf = cell =>
186
+ (cell.lod ??= { cx: cell.cx, cy: cell.cy ?? 0, cz: cell.cz, r: cell.r, until: cell.until ?? Infinity, near: cell.near ?? Infinity, batch: cell.farBatch ?? -1 });
141
187
 
142
188
  /**
143
189
  * Each frame: near cells show their detailed mesh, far ones their batched copy, thinned beyond `thinFrom` of the drawing
@@ -147,37 +193,47 @@ export function createCellLod({ square = 500, tableWidth = 64, thinFrom = 0.45,
147
193
  */
148
194
  function update(cells, cx, cz, distance, detail, density, cy, rangeScale = 1) {
149
195
  let changed = false;
150
- if (batchShows) batchShows.fill(0);
196
+ if (drawEnds) drawEnds.fill(0);
151
197
  for (let i = 0; i < cells.length; i++) {
152
- const t = cells[i],
153
- at = lodOf(t),
198
+ const cell = cells[i],
199
+ at = lodOf(cell),
154
200
  dx = cx - at.cx,
155
201
  dz = cz - at.cz,
156
202
  horizontalSq = dx * dx + dz * dz,
157
- d = Math.sqrt(horizontalSq) / rangeScale - at.r,
158
- hasFar = t.lo || t.far !== undefined;
159
- const vis = d < Math.min(distance, at.until),
160
- nearDistance = cy === undefined ? d : Math.sqrt(horizontalSq + (cy - at.cy) ** 2) / rangeScale - at.r,
203
+ detailDistance = Math.sqrt(horizontalSq) / rangeScale - at.r,
204
+ hasFar = cell.lo || cell.far !== undefined;
205
+ const vis = detailDistance < Math.min(distance, at.until),
206
+ nearDistance = cy === undefined ? detailDistance : Math.sqrt(horizontalSq + (cy - at.cy) ** 2) / rangeScale - at.r,
161
207
  hi = !hasFar || nearDistance < Math.min(detail, at.near);
162
- t.mesh.visible = vis && hi;
163
- if (t.lo) t.lo.visible = vis && !hi;
164
- let count = t.farN;
165
- if (t.full !== undefined) {
166
- count = Math.max(1, (t.full * (d < distance * thinFrom ? 1 : thinTo) * density) | 0);
167
- t.mesh.count = count;
168
- if (t.lo) t.lo.count = count;
208
+ cell.mesh.visible = vis && hi;
209
+ if (cell.lo) cell.lo.visible = vis && !hi;
210
+ let count = cell.farN;
211
+ if (cell.full !== undefined) {
212
+ count = Math.max(1, (cell.full * (detailDistance < distance * thinFrom ? 1 : thinTo) * density) | 0);
213
+ cell.mesh.count = count;
214
+ if (cell.lo) cell.lo.count = count;
169
215
  }
170
- if (t.far !== undefined) {
216
+ if (cell.far !== undefined) {
171
217
  const v = vis && !hi ? count : 0;
172
- if (v > 0) batchShows[at.batch]++;
173
- if (table.data[t.far] !== v) {
174
- table.data[t.far] = v;
218
+ // A single draw preserves gl_InstanceID and the order of overlapping instances.
219
+ // Omit its invisible tail; the shader clips gaps before doing any vertex work.
220
+ if (v > 0) drawEnds[at.batch] = Math.max(drawEnds[at.batch], cell.farStart + Math.min(cell.farN, v));
221
+ if (table.data[cell.far] !== v) {
222
+ table.data[cell.far] = v;
223
+ if (compact) dirty[at.batch] = 1;
175
224
  changed = true;
176
225
  }
177
226
  }
178
227
  }
179
- if (changed) table.tex.needsUpdate = true;
180
- for (let i = 0; i < batches.length; i++) batches[i].visible = batchShows[i] > 0;
228
+ if (changed && table.tex) table.tex.needsUpdate = true;
229
+ for (let i = 0; i < batches.length; i++) {
230
+ if (!compact) batches[i].count = drawEnds[i];
231
+ else if (dirty[i]) {
232
+ packVisible(i);
233
+ dirty[i] = 0;
234
+ }
235
+ batches[i].visible = drawEnds[i] > 0;
236
+ }
181
237
  }
182
238
 
183
239
  return { batch, update, batches };