roamwright 0.2.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 (140) hide show
  1. package/CONTRIBUTING.md +3 -1
  2. package/README.md +19 -21
  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 +47 -0
  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 +60 -0
  21. package/geometry/instance-visibility.js +41 -0
  22. package/geometry/instances.js +35 -12
  23. package/geometry/outline-grid.js +7 -7
  24. package/geometry/part-ranges.js +18 -0
  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 +101 -92
  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 +29 -0
  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 +8 -4
  74. package/rendering/caster-motion.js +5 -5
  75. package/rendering/cell-lod.js +147 -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 +91 -26
  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-budget.js +49 -0
  130. package/runtime/frame-pacing.js +33 -0
  131. package/runtime/gpu-timing.js +13 -10
  132. package/runtime/grid-cache.js +1 -1
  133. package/runtime/grid-rows.js +44 -5
  134. package/runtime/hand-over.js +41 -23
  135. package/runtime/pool.js +58 -16
  136. package/runtime/quality-fit.js +1 -1
  137. package/runtime/search.js +22 -22
  138. package/runtime/spatial-audio.js +13 -13
  139. package/runtime/withdrawable-task.js +35 -0
  140. package/runtime/worker.js +7 -0
@@ -37,7 +37,7 @@ export function createCrowdAlarms({
37
37
 
38
38
  // Raises an alarm at (x, z) at clock t, or renews the one already there.
39
39
  function raise(x, z, t, r = reach) {
40
- const near = alarms.find(a => Math.hypot(a.x - x, a.z - z) < merge);
40
+ const near = alarms.find(alarm => Math.hypot(alarm.x - x, alarm.z - z) < merge);
41
41
  if (near) {
42
42
  near.t = t;
43
43
  near.r = Math.max(near.r, r);
@@ -60,66 +60,66 @@ export function createCrowdAlarms({
60
60
  if (!stage.on) return;
61
61
  const dx = stage.x - at.x,
62
62
  dz = stage.z - at.z,
63
- d = Math.sqrt(dx * dx + dz * dz);
64
- if (d < watchWithin && d > watchBeyond) at.yaw = Math.atan2(dx, dz);
63
+ distance = Math.sqrt(dx * dx + dz * dz);
64
+ if (distance < watchWithin && distance > watchBeyond) at.yaw = Math.atan2(dx, dz);
65
65
  }
66
- // Whether g may be in flight: an alarm is up, or g is still away from their routine.
67
- const alarmed = g => alarms.length > 0 || !!g.fx || !!g.fz;
66
+ // An agent may flee while an alarm is active or while returning to their routine.
67
+ const alarmed = agent => alarms.length > 0 || !!agent.fx || !!agent.fz;
68
68
 
69
- // One step of g at clock t: `at` ({ x, z, yaw, speed, travel, focus }) holds where g's routine puts them, and is moved to where
69
+ // One step of the agent at clock t: `at` ({ x, z, yaw, speed, travel, focus }) holds where the agent’s routine puts them, and is moved to where
70
70
  // their flight has them. False when they stand where their routine puts them.
71
- function flee(g, at, t) {
71
+ function flee(agent, at, t) {
72
72
  const hx = at.x,
73
73
  hz = at.z,
74
- dt = g.ft < 0 ? 0 : Math.min(0.1, Math.max(0, t - g.ft));
75
- g.ft = t;
76
- const x = hx + (g.fx || 0),
77
- z = hz + (g.fz || 0);
74
+ deltaSeconds = agent.ft < 0 ? 0 : Math.min(0.1, Math.max(0, t - agent.ft));
75
+ agent.ft = t;
76
+ const x = hx + (agent.fx || 0),
77
+ z = hz + (agent.fz || 0);
78
78
  let near = null,
79
79
  nd = Infinity;
80
80
  for (let i = 0; i < alarms.length; i++) {
81
- const a = alarms[i],
82
- ax = x - a.x,
83
- az = z - a.z,
84
- d = Math.sqrt(ax * ax + az * az);
85
- if (d < a.r && d < nd) {
86
- nd = d;
87
- near = a;
81
+ const alarm = alarms[i],
82
+ ax = x - alarm.x,
83
+ az = z - alarm.z,
84
+ distance = Math.sqrt(ax * ax + az * az);
85
+ if (distance < alarm.r && distance < nd) {
86
+ nd = distance;
87
+ near = alarm;
88
88
  }
89
89
  }
90
90
  let speed;
91
91
  if (near) {
92
- const away = nd < 0.01 ? g.ph || 1 : Math.atan2(x - near.x, z - near.z);
93
- const k = sstep(0, 0.6, t - near.t + 0.6 - (g.ph % 1) * 0.5); // each starts at their own moment, not all on one beat
94
- speed = go(g, x, z, hx, hz, away, run * k * dt, run * k);
92
+ const away = nd < 0.01 ? agent.ph || 1 : Math.atan2(x - near.x, z - near.z);
93
+ const k = sstep(0, 0.6, t - near.t + 0.6 - (agent.ph % 1) * 0.5); // each starts at their own moment, not all on one beat
94
+ speed = go(agent, x, z, hx, hz, away, run * k * deltaSeconds, run * k);
95
95
  } else {
96
- const fx = g.fx || 0,
97
- fz = g.fz || 0,
96
+ const fx = agent.fx || 0,
97
+ fz = agent.fz || 0,
98
98
  o = Math.sqrt(fx * fx + fz * fz);
99
99
  if (o < 0.02) {
100
- g.fx = g.fz = 0;
100
+ agent.fx = agent.fz = 0;
101
101
  return false;
102
102
  }
103
- speed = go(g, x, z, hx, hz, Math.atan2(-g.fx, -g.fz), Math.min(o, walkBack * dt), walkBack);
103
+ speed = go(agent, x, z, hx, hz, Math.atan2(-agent.fx, -agent.fz), Math.min(o, walkBack * deltaSeconds), walkBack);
104
104
  }
105
- if (!speed && !g.fx && !g.fz) return false; // hemmed in away from their routine, they stand there rather than leap back to it
106
- at.x += g.fx;
107
- at.z += g.fz;
108
- at.yaw = g.fy;
105
+ if (!speed && !agent.fx && !agent.fz) return false; // hemmed in away from their routine, they stand there rather than leap back to it
106
+ at.x += agent.fx;
107
+ at.z += agent.fz;
108
+ at.yaw = agent.fy;
109
109
  at.speed = speed;
110
- at.travel = t * speed + g.ph;
110
+ at.travel = t * speed + agent.ph;
111
111
  at.focus = undefined;
112
112
  return true;
113
113
  }
114
- function go(g, x, z, hx, hz, want, step, speed) {
115
- const a = steer(x, z, want, step, body, g.lean);
116
- g.fy = a ?? want;
117
- if (a === undefined) return 0; // hemmed in: they stand where they are
118
- const turn = Math.sin(a - want);
119
- if (turn > 0.1) g.lean = 1;
120
- else if (turn < -0.1) g.lean = -1;
121
- g.fx = x + Math.sin(a) * step - hx;
122
- g.fz = z + Math.cos(a) * step - hz;
114
+ function go(agent, x, z, hx, hz, want, step, speed) {
115
+ const escapeAngle = steer(x, z, want, step, body, agent.lean);
116
+ agent.fy = escapeAngle ?? want;
117
+ if (escapeAngle === undefined) return 0; // hemmed in: they stand where they are
118
+ const turn = Math.sin(escapeAngle - want);
119
+ if (turn > 0.1) agent.lean = 1;
120
+ else if (turn < -0.1) agent.lean = -1;
121
+ agent.fx = x + Math.sin(escapeAngle) * step - hx;
122
+ agent.fz = z + Math.cos(escapeAngle) * step - hz;
123
123
  return speed;
124
124
  }
125
125
 
@@ -5,7 +5,7 @@ import { sstep } from '../math/scalar.js';
5
5
  * fro; and those routines fitted to the colliders of their space as the walls they stand among are built. A person is a plain
6
6
  * record their crowd keeps; no frame allocates.
7
7
  *
8
- * Routine fields on a person `g`:
8
+ * Routine fields on a walker:
9
9
  * - `legs`: [{ t0, tw, x0, z0, dx, dz, dir, len, travel, start, stop, hide, yaw, role, rest }], walked over `T` seconds from
10
10
  * phase `ph` at `walkSpeed`, each eased in where it `start`s and out where it `stop`s; a leg that `hide`s ends indoors.
11
11
  * - `speed`: moved by a keeper of its own, which sets `speed`, `travel` and `sway` (a turn off the line) each frame.
@@ -15,25 +15,64 @@ import { sstep } from '../math/scalar.js';
15
15
  */
16
16
 
17
17
  /**
18
- * Where g's routine puts them at clock t, into `at` ({ x, z, yaw, speed, travel, focus, head, rest }). False while they are
18
+ * Compile waypoints into a timed loop for followRoutine. Each point has x and z in
19
+ * metres and may have a wait w in seconds, a facing yaw, a role, or a hide flag.
20
+ * retrace returns through the intermediate points in reverse order.
21
+ * clearAt(x, z), when supplied, must allow both endpoints and samples at most
22
+ * half a metre apart on every leg. A blocked route returns null before drawing
23
+ * from rng. A supplied rng draws a phase and a size in [size, size + spread).
24
+ */
25
+ export function walkRound(points, speed, { retrace = false, clearAt, rng: random, size = 1, spread = 0 } = {}) {
26
+ if (!points.length || !Number.isFinite(speed) || speed <= 0) throw new RangeError('Expected waypoints and a positive walking speed');
27
+ const seq = retrace ? points.concat(points.slice(1, -1).reverse()) : points;
28
+ const legs = [];
29
+ let time = 0, distance = 0;
30
+ for (let i = 0; i < seq.length; i++) {
31
+ const startPoint = seq[i], endPoint = seq[(i + 1) % seq.length];
32
+ if (!Number.isFinite(startPoint.x) || !Number.isFinite(startPoint.z) || !Number.isFinite(endPoint.x) || !Number.isFinite(endPoint.z)
33
+ || !Number.isFinite(endPoint.w ?? 0) || (endPoint.w ?? 0) < 0) throw new RangeError('Invalid waypoint');
34
+ const dx = endPoint.x - startPoint.x, dz = endPoint.z - startPoint.z;
35
+ const len = Math.hypot(dx, dz), tw = len / speed;
36
+ if (clearAt) {
37
+ const steps = Math.max(1, Math.ceil(len / 0.5));
38
+ for (let j = 0; j <= steps; j++) {
39
+ if (!clearAt(startPoint.x + dx * (j / steps), startPoint.z + dz * (j / steps))) return null;
40
+ }
41
+ }
42
+ legs.push({
43
+ x0: startPoint.x, z0: startPoint.z, dx, dz, len, travel: distance, t0: time, tw,
44
+ dir: Math.atan2(dx, dz), yaw: endPoint.yaw, hide: endPoint.hide, start: startPoint.w > 0, stop: endPoint.w > 0, role: endPoint.role,
45
+ });
46
+ time += tw + (endPoint.w || 0);
47
+ distance += len;
48
+ }
49
+ const { x, z } = seq[0];
50
+ return {
51
+ ax: x, az: z, bx: x, bz: z, sp: 0, walkSpeed: speed, legs: time ? legs : null,
52
+ distance, T: time, ph: random ? random() * time : 0, s: random ? size + random() * spread : size,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Where the walker’s routine puts them at clock t, into `at` ({ x, z, yaw, speed, travel, focus, head, rest }). False while they are
19
58
  * indoors at the end of a leg. `headAtHalt(leg, held, left)` gives a beast's head at a halt (1 down), from the seconds it has
20
59
  * been held there and those left before the next leg; without it the head is down while grazing.
21
60
  */
22
- export function followRoutine(g, t, at, headAtHalt) {
23
- at.x = g.ax;
24
- at.z = g.az;
25
- at.yaw = g.yaw || 0;
61
+ export function followRoutine(walker, t, at, headAtHalt) {
62
+ at.x = walker.ax;
63
+ at.z = walker.az;
64
+ at.yaw = walker.yaw || 0;
26
65
  at.travel = 0;
27
66
  at.speed = 0;
28
- at.focus = g.role;
29
- at.head = g.graze ? 1 : 0;
67
+ at.focus = walker.role;
68
+ at.head = walker.graze ? 1 : 0;
30
69
  at.rest = 0;
31
- if (g.legs) {
32
- const tt = (t + g.ph) % g.T;
33
- let l = g.legs[0],
70
+ if (walker.legs) {
71
+ const tt = (t + walker.ph) % walker.T;
72
+ let l = walker.legs[0],
34
73
  next = null;
35
- for (let i = 0; i < g.legs.length; i++) {
36
- const q = g.legs[i];
74
+ for (let i = 0; i < walker.legs.length; i++) {
75
+ const q = walker.legs[i];
37
76
  if (q.t0 <= tt) l = q;
38
77
  else {
39
78
  next = q;
@@ -45,7 +84,7 @@ export function followRoutine(g, t, at, headAtHalt) {
45
84
  let u = Math.min(1, local / Math.max(l.tw, 1e-3));
46
85
  if (u === 1 && l.hide) return false;
47
86
  if (u < 1) {
48
- let speed = g.walkSpeed;
87
+ let speed = walker.walkSpeed;
49
88
  if (ease > 0 && l.start && local < ease) {
50
89
  const f = local / ease;
51
90
  u *= f * (2 - f);
@@ -58,34 +97,34 @@ export function followRoutine(g, t, at, headAtHalt) {
58
97
  at.speed = speed;
59
98
  } else {
60
99
  if (l.role) at.focus = l.role;
61
- if (headAtHalt) at.head = headAtHalt(l, local - l.tw, (next ? next.t0 : g.T) - tt);
100
+ if (headAtHalt) at.head = headAtHalt(l, local - l.tw, (next ? next.t0 : walker.T) - tt);
62
101
  at.rest = l.rest | 0;
63
102
  }
64
103
  at.x = l.x0 + l.dx * u;
65
104
  at.z = l.z0 + l.dz * u;
66
105
  at.yaw = l.yaw !== undefined && u === 1 ? l.yaw : l.dir;
67
106
  at.travel = l.travel + l.len * u;
68
- } else if (g.speed) {
69
- at.speed = g.speed;
70
- at.travel = g.travel;
71
- at.yaw += g.sway || 0;
72
- } else if (g.r) {
73
- const a = t * g.w + g.ph,
74
- speed = Math.abs(g.w) * g.r;
75
- at.x = g.ax + Math.cos(a) * g.r;
76
- at.z = g.az + Math.sin(a) * g.r;
77
- at.yaw = -a + (g.w > 0 ? 0 : Math.PI);
107
+ } else if (walker.speed) {
108
+ at.speed = walker.speed;
109
+ at.travel = walker.travel;
110
+ at.yaw += walker.sway || 0;
111
+ } else if (walker.r) {
112
+ const phaseAngle = t * walker.w + walker.ph,
113
+ speed = Math.abs(walker.w) * walker.r;
114
+ at.x = walker.ax + Math.cos(phaseAngle) * walker.r;
115
+ at.z = walker.az + Math.sin(phaseAngle) * walker.r;
116
+ at.yaw = -phaseAngle + (walker.w > 0 ? 0 : Math.PI);
78
117
  at.speed = speed;
79
- at.travel = t * speed + g.ph;
80
- } else if (g.sp > 0 && g.len > 0.5) {
81
- const travel = t * g.sp + g.ph,
82
- f = (travel / g.len) % 2,
118
+ at.travel = t * speed + walker.ph;
119
+ } else if (walker.sp > 0 && walker.len > 0.5) {
120
+ const travel = t * walker.sp + walker.ph,
121
+ f = (travel / walker.len) % 2,
83
122
  u = f < 1 ? f : 2 - f;
84
123
  at.travel = travel;
85
- at.x += g.dx * u;
86
- at.z += g.dz * u;
87
- at.yaw = g.pathYaw + (f < 1 ? 0 : Math.PI);
88
- at.speed = g.sp * sstep(0, 0.23, Math.min(u, 1 - u) * g.len);
124
+ at.x += walker.dx * u;
125
+ at.z += walker.dz * u;
126
+ at.yaw = walker.pathYaw + (f < 1 ? 0 : Math.PI);
127
+ at.speed = walker.sp * sstep(0, 0.23, Math.min(u, 1 - u) * walker.len);
89
128
  }
90
129
  return true;
91
130
  }
@@ -101,7 +140,7 @@ export function followRoutine(g, t, at, headAtHalt) {
101
140
  * @param {number} [options.step=0.5] Metres between the spots tested along a way.
102
141
  * @param {number} [options.short=0.9] Metres short of a wall a walker turns back.
103
142
  * @param {number} [options.least=0.5] Metres: a way shorter than this is no walk, and they stand.
104
- * @returns {(g: object, space: object) => void} Fits g, whose builder gave it (ox, oz) and, for a walker, the way's far end
143
+ * @returns {(walker: object, space: object) => void} Fits a walker, whose builder gave it (ox, oz) and, for a walker, the way's far end
105
144
  * (bx, bz), to the colliders of `space` as they stand now: sets ax, az, dx, dz, len, pathYaw or yaw, and `fit` (the
106
145
  * space's collider count it was fitted to). People on decks or roofs, on a keeper's leash (`steady`), on legs or circles keep
107
146
  * what their builder gave them.
@@ -112,9 +151,9 @@ export function createWalkFit({ collideIn, hit, onDeck, worldSpace }, { body = 0
112
151
  function clearRun(grid, x, z, ux, uz, len) {
113
152
  let free = len;
114
153
  for (let t = step; t < len + step; t += step) {
115
- const d = Math.min(t, len);
116
- if (collideIn(grid, x + ux * d, z + uz * d, body)) {
117
- free = Math.max(0, d - step - short);
154
+ const distanceAlong = Math.min(t, len);
155
+ if (collideIn(grid, x + ux * distanceAlong, z + uz * distanceAlong, body)) {
156
+ free = Math.max(0, distanceAlong - step - short);
118
157
  break;
119
158
  }
120
159
  }
@@ -122,22 +161,22 @@ export function createWalkFit({ collideIn, hit, onDeck, worldSpace }, { body = 0
122
161
  end.x = ux * free;
123
162
  end.z = uz * free;
124
163
  }
125
- return function fitWalk(g, sp) {
126
- g.fit = sp.colliders;
127
- if (!sp.grid || g.steady || g.legs || g.r || (g.ground !== undefined && !g.onGround)) return;
128
- let x = g.ox,
129
- z = g.oz;
164
+ return function fitWalk(walker, sp) {
165
+ walker.fit = sp.colliders;
166
+ if (!sp.grid || walker.steady || walker.legs || walker.r || (walker.ground !== undefined && !walker.onGround)) return;
167
+ let x = walker.ox,
168
+ z = walker.oz;
130
169
  if (sp === worldSpace && onDeck(x, z)) return;
131
170
  if (collideIn(sp.grid, x, z, body)) {
132
171
  x = hit.x;
133
172
  z = hit.z;
134
173
  }
135
- g.ax = x;
136
- g.az = z;
137
- if (g.onGround) g.ground = sp.ground(x, z);
138
- if (!(g.sp > 0)) return;
139
- const dx = g.bx - x,
140
- dz = g.bz - z,
174
+ walker.ax = x;
175
+ walker.az = z;
176
+ if (walker.onGround) walker.ground = sp.ground(x, z);
177
+ if (!(walker.sp > 0)) return;
178
+ const dx = walker.bx - x,
179
+ dz = walker.bz - z,
141
180
  len = Math.hypot(dx, dz);
142
181
  if (len < least) return;
143
182
  const ux = dx / len,
@@ -154,26 +193,16 @@ export function createWalkFit({ collideIn, hit, onDeck, worldSpace }, { body = 0
154
193
  sz = end.z;
155
194
  }
156
195
  }
157
- g.dx = sx;
158
- g.dz = sz;
159
- g.len = run;
160
- if (run >= least) g.pathYaw = Math.atan2(sx, sz);
161
- else g.yaw = Math.atan2(dx, dz); // no room to walk: they stand, facing the way they would have gone
196
+ walker.dx = sx;
197
+ walker.dz = sz;
198
+ walker.len = run;
199
+ if (run >= least) walker.pathYaw = Math.atan2(sx, sz);
200
+ else walker.yaw = Math.atan2(dx, dz); // no room to walk: they stand, facing the way they would have gone
162
201
  };
163
202
  }
164
203
 
165
- /**
166
- * A level of detail chosen with hysteresis: 3 near, 2 medium, 1 light, 0 past them. `near`, `medium` and `light` are each level's
167
- * outer edge in metres at a lens of 1, as [for one outside it, for one already inside it]: an edge lies a little further out for
168
- * one inside, so that nobody standing on it changes every frame. `d2` is the distance squared, `previous` the level last frame,
169
- * `lens` how much nearer the lens brings things (edges move out with it).
170
- */
171
- export function detailLevel(d2, previous, lens, near, medium, light) {
172
- const n = (previous === 3 ? near[1] : near[0]) * lens,
173
- m = (previous >= 2 ? medium[1] : medium[0]) * lens,
174
- l = (previous >= 1 ? light[1] : light[0]) * lens;
175
- return d2 < n * n ? 3 : d2 < m * m ? 2 : d2 < l * l ? 1 : 0;
176
- }
204
+ // Kept for applications importing the crowd selector from its original module.
205
+ export { detailLevel } from '../rendering/detail-range.js';
177
206
 
178
207
  /** Turns a heading `dir` towards `want` at `rate` a second over `gap` seconds, at once after a gap of more than `snap` seconds. */
179
208
  export function easeHeading(dir, want, gap, rate, snap = 0.2) {
@@ -21,13 +21,13 @@ export function createDailyClock({ getFrame, getHour, jumpHours = 0.05 }) {
21
21
  // A span of the day from one ramp to another, as the hours of the one that comes first and goes first (rank 0) and of the last
22
22
  // (rank 1); one that runs over midnight is counted on into the next day.
23
23
  function spanOf(from, to, h, rank) {
24
- const a = from[0] + rank * (from[1] - from[0]);
25
- let b = to[0] + rank * (to[1] - to[0]);
26
- if (b < a) {
27
- b += 24;
28
- if (h < a) h += 24;
24
+ const startHour = from[0] + rank * (from[1] - from[0]);
25
+ let endHour = to[0] + rank * (to[1] - to[0]);
26
+ if (endHour < startHour) {
27
+ endHour += 24;
28
+ if (h < startHour) h += 24;
29
29
  }
30
- return h >= a && h < b;
30
+ return h >= startHour && h < endHour;
31
31
  }
32
32
  // Whether one of rank `rank` is out now in a span [from, to] of ramps, and will still be out `ahead` hours from now (one that
33
33
  // needs that long to get in goes in so much sooner).
@@ -51,9 +51,9 @@ export function createDailyClock({ getFrame, getHour, jumpHours = 0.05 }) {
51
51
  }
52
52
 
53
53
  // The hours between two hours of the day, the short way round.
54
- const hoursApart = (a, b) => {
55
- const d = Math.abs(a - b) % 24;
56
- return d > 12 ? 24 - d : d;
54
+ const hoursApart = (firstHour, secondHour) => {
55
+ const separation = Math.abs(firstHour - secondHour) % 24;
56
+ return separation > 12 ? 24 - separation : separation;
57
57
  };
58
58
  return { hourNow, clockTurned, isOut, shareOut, hoursApart };
59
59
  }
@@ -0,0 +1,38 @@
1
+ import { deckTop } from './spaces.js';
2
+
3
+ /**
4
+ * Return a height query over an append-only list of fixed decks in deckTop format.
5
+ * Supply the terrain height function, the square's minimum x and z, its size, and
6
+ * its cell size in world units. The grid rounds up to whole cells. Queries outside
7
+ * it return the terrain height. The query indexes appended decks on first use.
8
+ */
9
+ export function createDeckSurface(decks, terrain, x0, z0, size, cellSize) {
10
+ if (!(Number.isFinite(size) && size > 0 && Number.isFinite(cellSize) && cellSize > 0))
11
+ throw new RangeError('Surface and cell sizes must be positive and finite');
12
+ const side = Math.ceil(size / cellSize),
13
+ count = side * side,
14
+ indices = count <= 65535 ? new Uint16Array(count) : new Uint32Array(count),
15
+ lists = [];
16
+ let filed = 0;
17
+ const cell = distance => Math.min(side - 1, Math.max(0, Math.floor(distance / cellSize)));
18
+
19
+ function fileNewDecks() {
20
+ while (filed < decks.length) {
21
+ const deck = decks[filed++], radius = Math.hypot(deck.hx, deck.hz);
22
+ for (let row = cell(deck.z - radius - z0); row <= cell(deck.z + radius - z0); row++)
23
+ for (let column = cell(deck.x - radius - x0); column <= cell(deck.x + radius - x0); column++) {
24
+ const key = row * side + column;
25
+ if (!indices[key]) indices[key] = lists.push([]);
26
+ lists[indices[key] - 1].push(deck);
27
+ }
28
+ }
29
+ }
30
+
31
+ return (x, z) => {
32
+ if (filed < decks.length) fileNewDecks();
33
+ const i = Math.floor((x - x0) / cellSize), j = Math.floor((z - z0) / cellSize),
34
+ index = i >= 0 && j >= 0 && i < side && j < side ? indices[j * side + i] : 0,
35
+ ground = terrain(x, z);
36
+ return index ? Math.max(ground, deckTop(lists[index - 1], x, z)) : ground;
37
+ };
38
+ }
@@ -0,0 +1,29 @@
1
+ // Predict planar motion in metres, reusing the returned point between updates.
2
+ export function createGroundLookahead({ seconds, maxDistance, smoothing, jumpDistance, maxGap }) {
3
+ let lastX,
4
+ lastZ,
5
+ lastTime,
6
+ vx = 0,
7
+ vz = 0;
8
+ const point = { x: 0, z: 0, jumped: false };
9
+ return function predict(x, z, time) {
10
+ const deltaSeconds = time - lastTime,
11
+ dx = x - lastX,
12
+ dz = z - lastZ;
13
+ point.jumped = lastTime === undefined || Math.hypot(dx, dz) > jumpDistance;
14
+ if (point.jumped || !(deltaSeconds > 0 && deltaSeconds < maxGap)) vx = vz = 0;
15
+ else {
16
+ const velocityBlend = Math.min(1, deltaSeconds * smoothing);
17
+ vx += (dx / deltaSeconds - vx) * velocityBlend;
18
+ vz += (dz / deltaSeconds - vz) * velocityBlend;
19
+ }
20
+ const speed = Math.hypot(vx, vz);
21
+ const lead = speed ? Math.min(seconds, maxDistance / speed) : seconds;
22
+ point.x = x + vx * lead;
23
+ point.z = z + vz * lead;
24
+ lastX = x;
25
+ lastZ = z;
26
+ lastTime = time;
27
+ return point;
28
+ };
29
+ }
@@ -19,8 +19,8 @@ export function createInstanceSight({ widthFraction = 0.7, nearSubject = 0.6 } =
19
19
  max: { x: x1, y: y1, z: z1 },
20
20
  } = geometry.boundingBox);
21
21
  } else {
22
- const { center: c, radius: r } = geometry.boundingSphere;
23
- [x0, x1, y0, y1, z0, z1] = [c.x - r * 0.7, c.x + r * 0.7, 0, c.y + r * 0.7, c.z - r * 0.7, c.z + r * 0.7];
22
+ const { center: localCenter, radius: localRadius } = geometry.boundingSphere;
23
+ [x0, x1, y0, y1, z0, z1] = [localCenter.x - localRadius * 0.7, localCenter.x + localRadius * 0.7, 0, localCenter.y + localRadius * 0.7, localCenter.z - localRadius * 0.7, localCenter.z + localRadius * 0.7];
24
24
  }
25
25
  const top = Math.max(y1, 0),
26
26
  body = {
@@ -62,17 +62,17 @@ export function createInstanceSight({ widthFraction = 0.7, nearSubject = 0.6 } =
62
62
  const { mesh, body } = list[k],
63
63
  s = mesh.boundingSphere;
64
64
  if (Math.hypot(s.center.x - mx, s.center.y - my, s.center.z - mz) > s.radius + reach * (0.5 + spread)) continue; // the batch is nowhere near
65
- const m = mesh.instanceMatrix.array;
65
+ const matrices = mesh.instanceMatrix.array;
66
66
  for (let i = 0; i < mesh.count * 16; i += 16) {
67
- const wide = Math.hypot(m[i], m[i + 1], m[i + 2]),
68
- tall = Math.hypot(m[i + 4], m[i + 5], m[i + 6]),
69
- x = m[i + 12] + m[i] * body.x + m[i + 8] * body.z,
70
- z = m[i + 14] + m[i + 2] * body.x + m[i + 10] * body.z,
67
+ const wide = Math.hypot(matrices[i], matrices[i + 1], matrices[i + 2]),
68
+ tall = Math.hypot(matrices[i + 4], matrices[i + 5], matrices[i + 6]),
69
+ x = matrices[i + 12] + matrices[i] * body.x + matrices[i + 8] * body.z,
70
+ z = matrices[i + 14] + matrices[i + 2] * body.x + matrices[i + 10] * body.z,
71
71
  u = flat2 > 1e-6 ? Math.min(1, Math.max(0, ((x - p.x) * dx + (z - p.z) * dz) / flat2)) : 0;
72
72
  if ((1 - u) * flat < nearSubject) continue;
73
73
  const room = u * flat * spread, // how far the middle of the picture reaches round the line of sight there, in metres
74
74
  aside = Math.hypot(p.x + dx * u - x, p.z + dz * u - z) - room,
75
- rise = p.y + dy * u - m[i + 13], // the line's height over the plant's foot where it passes nearest
75
+ rise = p.y + dy * u - matrices[i + 13], // the line's height over the plant's foot where it passes nearest
76
76
  crown = body.from * tall;
77
77
  if (aside < body.r * wide && rise + room > crown && rise - room < body.top * tall) return true;
78
78
  if (aside < body.trunk * wide && rise - room < crown && rise + room > 0) return true;
package/motion/player.js CHANGED
@@ -1,10 +1,18 @@
1
+ /**
2
+ * First-person walking and flight over terrain, water and raised surfaces.
3
+ * @module
4
+ */
5
+
1
6
  import { clamp } from '../math/scalar.js';
2
7
 
3
8
  /**
4
9
  * A first-person controller for a createSpaces registry. Distances are metres,
5
10
  * speeds are metres per second, angles are radians, and update takes seconds.
6
11
  * Set input.right, forward and up to signed axes, and run, jump and fly to booleans.
7
- * Camera application accepts a Three.js camera with YXZ rotation order.
12
+ * After updating, call `applyCamera(camera)` to copy the eye position and view
13
+ * angles to a Three.js camera with YXZ rotation order.
14
+ * @param spatial - Registry returned by `createSpaces`.
15
+ * @param options - Movement, collision and camera settings, with optional initial player state in `start`.
8
16
  */
9
17
  export function createPlayer(spatial, options = {}) {
10
18
  const {
@@ -54,29 +62,29 @@ export function createPlayer(spatial, options = {}) {
54
62
  const feet = player.y - eye,
55
63
  ceiling = feet + obstacleScan;
56
64
  const rock = overhead.ground(nx, nz, ceiling),
57
- g = Math.max(space.ground(nx, nz), rock);
58
- if ((g === rock && g - feet > overheadStep) || overhead.wall(player.x, player.z, nx, nz, feet)) return false;
59
- if (space.water && g < space.waterLevel - wadingDepth) return false;
60
- if (g - feet > stepHeight) {
65
+ groundHeight = Math.max(space.ground(nx, nz), rock);
66
+ if ((groundHeight === rock && groundHeight - feet > overheadStep) || overhead.wall(player.x, player.z, nx, nz, feet)) return false;
67
+ if (space.water && groundHeight < space.waterLevel - wadingDepth) return false;
68
+ if (groundHeight - feet > stepHeight) {
61
69
  const x2 = nx + dirx * stepProbe,
62
70
  z2 = nz + dirz * stepProbe;
63
71
  const g2 = Math.max(space.ground(x2, z2), overhead.ground(x2, z2, ceiling));
64
- return (g2 - feet) / stepProbe <= stepSlope && g - feet <= maxStep;
72
+ return (g2 - feet) / stepProbe <= stepSlope && groundHeight - feet <= maxStep;
65
73
  }
66
74
  const x2 = nx + dirx * slopeProbe,
67
75
  z2 = nz + dirz * slopeProbe;
68
76
  const g2 = Math.max(space.ground(x2, z2), overhead.ground(x2, z2, ceiling));
69
- return (g2 - g) / slopeProbe <= maxSlope;
77
+ return (g2 - groundHeight) / slopeProbe <= maxSlope;
70
78
  }
71
79
 
72
80
  function keepWithin(space) {
73
81
  if (space.round) {
74
82
  const rx = player.x - space.cx,
75
83
  rz = player.z - space.cz,
76
- r = Math.hypot(rx, rz);
77
- if (r > space.bound) {
78
- player.x = space.cx + (rx / r) * space.bound;
79
- player.z = space.cz + (rz / r) * space.bound;
84
+ radialDistance = Math.hypot(rx, rz);
85
+ if (radialDistance > space.bound) {
86
+ player.x = space.cx + (rx / radialDistance) * space.bound;
87
+ player.z = space.cz + (rz / radialDistance) * space.bound;
80
88
  }
81
89
  } else {
82
90
  const bx = space.bx ?? space.bound,
@@ -86,7 +94,7 @@ export function createPlayer(spatial, options = {}) {
86
94
  }
87
95
  }
88
96
 
89
- function flyStep(space, dt, mx, mz, sinYaw, cosYaw) {
97
+ function flyStep(space, deltaSeconds, mx, mz, sinYaw, cosYaw) {
90
98
  const flight = space.flight;
91
99
  let speed = input.run ? flySetFast : flySet;
92
100
  if (space.flyable) speed = input.run ? flyFast : fly;
@@ -97,14 +105,14 @@ export function createPlayer(spatial, options = {}) {
97
105
  const wantX = (-sinYaw * cosPitch * mz + cosYaw * mx) * speed,
98
106
  wantZ = (-cosYaw * cosPitch * mz - sinYaw * mx) * speed,
99
107
  wantY = (sinPitch * mz + input.up) * speed;
100
- const ease = 1 - Math.exp(-dt * flyEase);
108
+ const ease = 1 - Math.exp(-deltaSeconds * flyEase);
101
109
  player.vx += (wantX - player.vx) * ease;
102
110
  player.vy += (wantY - player.vy) * ease;
103
111
  player.vz += (wantZ - player.vz) * ease;
104
112
  const previousFeet = player.y - eye;
105
- player.x += player.vx * dt;
106
- player.y += player.vy * dt;
107
- player.z += player.vz * dt;
113
+ player.x += player.vx * deltaSeconds;
114
+ player.y += player.vy * deltaSeconds;
115
+ player.z += player.vz * deltaSeconds;
108
116
  const cx = flight?.cx ?? space.cx,
109
117
  cz = flight?.cz ?? space.cz;
110
118
  const bx = flight?.bx ?? (space.bx ?? space.bound) + flightMargin,
@@ -138,15 +146,15 @@ export function createPlayer(spatial, options = {}) {
138
146
  player.grounded = false;
139
147
  }
140
148
 
141
- function walkStep(space, dt, mx, mz, sinYaw, cosYaw) {
149
+ function walkStep(space, deltaSeconds, mx, mz, sinYaw, cosYaw) {
142
150
  const speed = input.run ? run : walk;
143
151
  const wantX = (-sinYaw * mz + cosYaw * mx) * speed,
144
152
  wantZ = (-cosYaw * mz - sinYaw * mx) * speed;
145
- const ease = 1 - Math.exp(-dt * walkEase);
153
+ const ease = 1 - Math.exp(-deltaSeconds * walkEase);
146
154
  player.vx += (wantX - player.vx) * ease;
147
155
  player.vz += (wantZ - player.vz) * ease;
148
- const stepx = player.vx * dt,
149
- stepz = player.vz * dt,
156
+ const stepx = player.vx * deltaSeconds,
157
+ stepz = player.vz * deltaSeconds,
150
158
  stepLength = Math.hypot(stepx, stepz);
151
159
  if (stepLength > 1e-5) {
152
160
  let nx = player.x + stepx,
@@ -179,11 +187,11 @@ export function createPlayer(spatial, options = {}) {
179
187
  } else if (player.y - eyes > dropHeight) {
180
188
  player.grounded = false;
181
189
  player.vy = 0;
182
- } else player.y += (eyes - player.y) * Math.min(1, dt * groundEase);
190
+ } else player.y += (eyes - player.y) * Math.min(1, deltaSeconds * groundEase);
183
191
  }
184
192
  if (!player.grounded) {
185
- player.vy -= gravity * dt;
186
- player.y += player.vy * dt;
193
+ player.vy -= gravity * deltaSeconds;
194
+ player.y += player.vy * deltaSeconds;
187
195
  if (player.y <= eyes) {
188
196
  player.y = eyes;
189
197
  player.vy = 0;
@@ -191,11 +199,11 @@ export function createPlayer(spatial, options = {}) {
191
199
  }
192
200
  }
193
201
  const pace = Math.hypot(player.vx, player.vz);
194
- player.moved += pace * dt;
195
- if (player.grounded && pace > bobStart) player.bob += dt * pace * bobRate;
202
+ player.moved += pace * deltaSeconds;
203
+ if (player.grounded && pace > bobStart) player.bob += deltaSeconds * pace * bobRate;
196
204
  }
197
205
 
198
- function update(dt) {
206
+ function update(deltaSeconds) {
199
207
  let mx = input.right,
200
208
  mz = input.forward;
201
209
  const magnitude = Math.hypot(mx, mz);
@@ -205,8 +213,8 @@ export function createPlayer(spatial, options = {}) {
205
213
  }
206
214
  const sinYaw = Math.sin(player.yaw),
207
215
  cosYaw = Math.cos(player.yaw);
208
- if (input.fly) flyStep(spatial.space, dt, mx, mz, sinYaw, cosYaw);
209
- else walkStep(spatial.space, dt, mx, mz, sinYaw, cosYaw);
216
+ if (input.fly) flyStep(spatial.space, deltaSeconds, mx, mz, sinYaw, cosYaw);
217
+ else walkStep(spatial.space, deltaSeconds, mx, mz, sinYaw, cosYaw);
210
218
  player.pitch = clamp(player.pitch, -pitchLimit, pitchLimit);
211
219
  }
212
220