roamwright 0.54.0 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/examples/animals.js +27 -15
  2. package/examples/crowds.js +28 -18
  3. package/examples/effects.js +13 -11
  4. package/examples/figure-motion.js +17 -5
  5. package/examples/figure.js +12 -8
  6. package/examples/fliers.js +16 -12
  7. package/examples/fortification.js +31 -18
  8. package/examples/house-kit.js +17 -10
  9. package/examples/island.js +25 -12
  10. package/examples/land.js +14 -8
  11. package/examples/props-and-plants.js +21 -32
  12. package/examples/rooms.js +2 -2
  13. package/examples/ships.js +33 -15
  14. package/examples/small-world-land.js +3 -3
  15. package/examples/small-world-life.js +13 -5
  16. package/examples/small-world-town.js +8 -11
  17. package/examples/small-world.js +26 -19
  18. package/examples/soundscape.js +18 -18
  19. package/examples/stage-kits.js +5 -133
  20. package/examples/stage.js +1 -324
  21. package/examples/towns.js +25 -18
  22. package/examples/viaduct-landscape.js +1 -1
  23. package/examples/viaduct.js +3 -4
  24. package/geometry/builder.js +8 -18
  25. package/geometry/plant-broadleaf.js +10 -4
  26. package/geometry/plant-trees.js +15 -9
  27. package/geometry/still-mesh.js +35 -0
  28. package/index.js +11 -1
  29. package/motion/cast-actors.js +379 -0
  30. package/motion/cast-manager.js +321 -0
  31. package/motion/figure-mount.js +1 -0
  32. package/package.json +20 -1
  33. package/rendering/cast-stage.js +299 -0
  34. package/rendering/crowd-system.js +239 -0
  35. package/rendering/daylight-sky.js +212 -0
  36. package/rendering/house-kit-meshes.js +65 -16
  37. package/rendering/nameplate-groups.js +84 -0
  38. package/rendering/nameplates.js +386 -0
  39. package/rendering/orbit-camera.js +216 -0
  40. package/rendering/water-simple.js +112 -0
@@ -11,7 +11,7 @@ import { between, direction, lifted, moved } from './plant-shrub.js';
11
11
  * @param {Function} o.barkTint - The kit's bark tint (`createPlantTints`).
12
12
  * @param {Function} o.crownBlob - The kit's crown lump (`createPlantTints`).
13
13
  * @param {Function} o.crownTint - The kit's foliage tint (`createPlantTints`).
14
- * @returns {{broadleaf: Function, broadleafArrays: Function}} `broadleaf(far = false)`: the tree's parts for
14
+ * @returns {{broadleaf: Function, broadleafArrays: Function}} `broadleaf()`: `{ near, far }` parts for
15
15
  * `partsGeometry`, its foot at the origin; `broadleafArrays()`: the near tree as transferable arrays (`partsArrays`).
16
16
  */
17
17
  export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
@@ -214,10 +214,10 @@ export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
214
214
 
215
215
  // A broadleaf: its near version, or with `far` its far one, which keeps the trunk and the boughs and gathers each bough's
216
216
  // clumps into one, a fifth of the near tree's triangles.
217
- function broadleaf(far = false) {
217
+ function buildBroadleaf(far, plan = broadleafPlan()) {
218
218
  const parts = shapeParts(),
219
219
  bark = barkTint(BROAD_BARK),
220
- { limbs, clumps, sprays } = broadleafPlan(),
220
+ { limbs, clumps, sprays } = plan,
221
221
  sides = far ? [5, 3, 0, 0] : [8, 6, 4, 3];
222
222
  for (const [from, to, foot, tip, rank] of limbs) if (sides[rank]) addLimb(parts, from, to, foot, tip, sides[rank], bark);
223
223
  const putClump = (at, size, flat, turn, hex, seed, detail) => {
@@ -261,8 +261,14 @@ export function createBroadleaf({ barkTint, crownBlob, crownTint }) {
261
261
  return parts;
262
262
  }
263
263
 
264
+ // Returns both detail levels from one shared scaffold plan, matching every other tree builder's `{ near, far }` shape.
265
+ function broadleaf() {
266
+ const plan = broadleafPlan();
267
+ return { near: buildBroadleaf(false, plan), far: buildBroadleaf(true, plan) };
268
+ }
269
+
264
270
  // The broadleaf as the arrays of its geometry (foliage.js's partsArrays), for the pool's workers to hand over: the model is
265
271
  // too large to build in one frame on a page that draws.
266
- const broadleafArrays = () => partsArrays(broadleaf());
272
+ const broadleafArrays = () => partsArrays(buildBroadleaf(false));
267
273
  return { broadleaf, broadleafArrays };
268
274
  }
@@ -1,25 +1,27 @@
1
- // Trees of the plant kit, near and, for most, far: the conifer, the burnt tree, the thorn tree, the park acacia and the cedar.
2
- // Each is a set of parts for `partsGeometry`, its foot at the origin. Worker-safe.
1
+ // Trees of the plant kit, each returning `{ near, far }` parts for `partsGeometry`, with its foot at the origin:
2
+ // the broadleaf, conifer, burnt tree, thorn tree, park acacia and cedar. Worker-safe.
3
3
  import * as THREE from 'three';
4
4
  import { lerp, TAU } from '../math/scalar.js';
5
5
  import { mulberry32 } from '../math/random.js';
6
6
  import { C, TRS } from './primitives.js';
7
7
  import { addShape, shapeParts } from './foliage.js';
8
+ import { createBroadleaf } from './plant-broadleaf.js';
8
9
 
9
10
  /**
10
11
  * The kit's trees bound to a world's hash, seed and the kit's tints.
12
+ * Every species builder returns `{ near, far }` parts suitable for `partsGeometry`.
13
+ *
11
14
  * @param {object} o
12
15
  * @param {Function} o.hash - A seeded integer hash (`createHash`), which mottles needles and char.
13
16
  * @param {Function} o.barkTint - The kit's bark tint (`createPlantTints`).
14
17
  * @param {Function} o.crownBlob - The kit's crown lump (`createPlantTints`).
15
18
  * @param {Function} o.crownTint - The kit's foliage tint (`createPlantTints`).
16
19
  * @param {number} [o.seed=0] - The world's seed: the burnt, thorn, acacia and cedar trees grow from streams counted from it.
17
- * @returns {{conifer: Function, farConifer: Function, burntTree: Function, farBurntTree: Function, thornTree: Function,
18
- * acacia: Function, cedar: Function}} `conifer()`, `farConifer()`, `burntTree()` and `farBurntTree()`: one set of
19
- * parts each (about 10, 9.5 and 5 m tall); `thornTree()`, `acacia()` and `cedar(variant = 0)`: `{ near, far }`, the cedar
20
- * about fourteen metres tall and each `variant` a tree of its own.
20
+ * @returns {{broadleaf: Function, conifer: Function, burntTree: Function, thornTree: Function, acacia: Function, cedar: Function}}
21
+ * Every tree builder returns `{ near, far }`; `cedar(variant = 0)` builds an upland cedar about fourteen metres tall where each `variant` is a tree of its own.
21
22
  */
22
23
  export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed = 0 }) {
24
+ const { broadleaf } = createBroadleaf({ barkTint, crownBlob, crownTint });
23
25
  const LIMB_NEAR = new THREE.CylinderGeometry(0.62, 1, 1, 7, 1, true).translate(0, 0.5, 0), // a limb of radius 1 at its foot, a metre long
24
26
  LIMB_FAR = new THREE.CylinderGeometry(0.62, 1, 1, 4, 1, true).translate(0, 0.5, 0),
25
27
  FAR_PLATE = new THREE.Vector3(1.3, 1, 1.3), // a far cedar's plates, one to a limb, stand for the near tree's three
@@ -36,7 +38,7 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
36
38
  }
37
39
 
38
40
  // A conifer: a tapering trunk to the top, and whorl after whorl of separate drooping boughs, long at the base and short at the leader.
39
- function conifer() {
41
+ function nearConifer() {
40
42
  const near = shapeParts();
41
43
  const boughGeo = (() => {
42
44
  // one bough along +z: a tapered spray, thicker above than below, its tip hanging
@@ -142,7 +144,7 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
142
144
  }
143
145
 
144
146
  // A burnt tree: a fire-killed trunk, bent and blackened, its top snapped off; charred limbs forking into bare twigs, some burnt back to stubs.
145
- function burntTree() {
147
+ function nearBurntTree() {
146
148
  const near = shapeParts();
147
149
  const R = mulberry32(seed + 611),
148
150
  up = new THREE.Vector3(0, 1, 0),
@@ -449,5 +451,9 @@ export function createTrees({ hash: hash2, barkTint, crownBlob, crownTint, seed
449
451
  }
450
452
  return parts;
451
453
  }
452
- return { conifer, farConifer, burntTree, farBurntTree, thornTree, acacia, cedar };
454
+
455
+ const conifer = () => ({ near: nearConifer(), far: farConifer() });
456
+ const burntTree = () => ({ near: nearBurntTree(), far: farBurntTree() });
457
+
458
+ return { broadleaf, conifer, burntTree, thornTree, acacia, cedar };
453
459
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Helper creating a mesh with shadow defaults, optional static-caster layer marking, and
3
+ * configurable `matrixAutoUpdate` (enabled by default so subsequent `position`/`rotation`/`scale`
4
+ * edits take effect without manual `updateMatrix()` calls).
5
+ * @module
6
+ */
7
+
8
+ import * as THREE from 'three';
9
+ import { markStill } from '../rendering/still-casters.js';
10
+
11
+ /**
12
+ * Builds a `THREE.Mesh` configured for static or repositionable world geometry, enabling shadow
13
+ * reception, optional shadow casting and static-caster registration (`markStill`).
14
+ *
15
+ * `matrixAutoUpdate` defaults to `true` so callers can position or move the returned mesh without
16
+ * remembering a manual `updateMatrix()` call; pass `{ matrixAutoUpdate: false }` to freeze the
17
+ * local matrix immediately at the origin.
18
+ *
19
+ * @param {THREE.BufferGeometry} geometry Geometry to render.
20
+ * @param {THREE.Material} material Material applied to the mesh.
21
+ * @param {boolean} [shadow=true] Whether the mesh casts shadows (and joins the static-caster layer).
22
+ * @param {object} [options]
23
+ * @param {boolean} [options.matrixAutoUpdate=true] Keep Three.js automatic local-matrix updates enabled.
24
+ * @param {boolean} [options.receiveShadow=true] Whether the mesh receives shadows.
25
+ * @returns {THREE.Mesh}
26
+ */
27
+ export function stillMesh(geometry, material, shadow = true, { matrixAutoUpdate = true, receiveShadow = true } = {}) {
28
+ const mesh = new THREE.Mesh(geometry, material);
29
+ mesh.castShadow = shadow;
30
+ mesh.receiveShadow = receiveShadow;
31
+ mesh.matrixAutoUpdate = matrixAutoUpdate;
32
+ if (!matrixAutoUpdate) mesh.updateMatrix();
33
+ if (shadow) markStill(mesh);
34
+ return mesh;
35
+ }
package/index.js CHANGED
@@ -8,6 +8,8 @@
8
8
 
9
9
  // ── Context, math & core geometry ────────────────────────────────────────
10
10
  export { RENDER_LAYERS, createRenderContext } from './rendering/context.js';
11
+ export { createDaylightSky, createSkyPanorama, createSkyTexture } from './rendering/daylight-sky.js';
12
+ export { bindKeyboardOrbit, createOrbitCamera } from './rendering/orbit-camera.js';
11
13
  export { createDayCycle, luminanceOf } from './rendering/day-cycle.js';
12
14
  export { DEFAULT_DAY_CYCLE, DEFAULT_SKY_PALETTE } from './rendering/day-cycle-defaults.js';
13
15
  export { createSurfaceMaterialFactory } from './rendering/surface-material.js';
@@ -17,6 +19,7 @@ export { createStainMaterial } from './rendering/stain-material.js';
17
19
  export { createNoise } from './math/noise.js';
18
20
  export { mulberry32 } from './math/random.js';
19
21
  export { GB as GeometryBuilder, geometryOf } from './geometry/builder.js';
22
+ export { stillMesh } from './geometry/still-mesh.js';
20
23
  export { createUnitShapes } from './geometry/primitives.js';
21
24
 
22
25
  // ── Spaces & player motion ───────────────────────────────────────────────
@@ -33,10 +36,11 @@ export { createMoundFaces } from './geometry/land-mound-faces.js';
33
36
  export { createTownGround } from './geometry/land-town-ground.js';
34
37
  export { createDryBasin } from './geometry/land-dry-basin.js';
35
38
  export { landEdgeGrid } from './geometry/land-edge.js';
39
+ export { createSimpleWater } from './rendering/water-simple.js';
36
40
 
37
41
  // ── Settlements, houses, fortifications & interiors ──────────────────────
38
42
  export { createHouseKit } from './geometry/house-kit.js';
39
- export { createHouseKitMeshes } from './rendering/house-kit-meshes.js';
43
+ export { createHouseKitMaterials, createHouseKitMeshes } from './rendering/house-kit-meshes.js';
40
44
  export { createPooledKit } from './geometry/house-kit-pool.js';
41
45
  export { createQuarterStream } from './rendering/settlement-quarter.js';
42
46
  export { createTowns } from './rendering/settlement-town.js';
@@ -98,6 +102,11 @@ export { createFigureAssembler } from './rendering/figure-skeleton.js';
98
102
  export { createShields } from './rendering/figure-shield.js';
99
103
  export { createBodyOrders } from './runtime/figure-orders.js';
100
104
  export { createFigurePose, figureActor } from './motion/figure-pose.js';
105
+ export { actorNameSeed, createCastActor, extractFigureParts } from './motion/cast-actors.js';
106
+ export { createCastManager } from './motion/cast-manager.js';
107
+ export { createCastStage, createStandIn, uploadCastMeshes, warmFigureShaders } from './rendering/cast-stage.js';
108
+ export { createNameplateGroups } from './rendering/nameplate-groups.js';
109
+ export { createNameplates, renderNameplateCanvas, wrapSubtitle } from './rendering/nameplates.js';
101
110
  export { rigHorse } from './rendering/animal-horse-figure.js';
102
111
  export { buildCattle } from './rendering/animal-cattle-figure.js';
103
112
  export { buildCamel } from './rendering/animal-camel-figure.js';
@@ -131,6 +140,7 @@ export { createCrowdVisibility } from './rendering/crowd-visibility.js';
131
140
  export { createHerdRenderer, createHerdSkins } from './rendering/crowd-herd.js';
132
141
  export { createCrowdBatches } from './rendering/crowd-batches.js';
133
142
  export { createCrowdUpdater, registerCrowd } from './rendering/crowd-update.js';
143
+ export { createCrowdSystem } from './rendering/crowd-system.js';
134
144
 
135
145
  // ── Effects, audio & runtime ─────────────────────────────────────────────
136
146
  export { createFireLightWatch } from './rendering/fire-light-watch.js';
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Pure cast actor records, deterministic name seeding, home placement (ground anchors,
3
+ * interior spaces, moving reference frames and orbits), and scene-state transitions.
4
+ * Free of Three.js so workers and Node tests can evaluate actor placement directly.
5
+ * @module
6
+ */
7
+ import { createHash } from '../math/random.js';
8
+ import { TAU } from '../math/scalar.js';
9
+ import { figureActor } from './figure-pose.js';
10
+
11
+ const DEFAULT_HASH = createHash(0);
12
+ const DEFAULT_ORBIT_RISE = 9; // metres a circling flier rises and falls over one cycle
13
+
14
+ /**
15
+ * Computes a repeatable 32-bit FNV-1a seed from an actor identifier so a character
16
+ * always generates the same procedural appearance regardless of load order.
17
+ *
18
+ * @param {string} id - Stable actor identifier.
19
+ * @returns {number} Unsigned 32-bit integer seed.
20
+ */
21
+ export function actorNameSeed(id) {
22
+ let seed = 2166136261;
23
+ for (let i = 0; i < id.length; i++) seed = Math.imul(seed ^ id.charCodeAt(i), 16777619);
24
+ return seed >>> 0;
25
+ }
26
+
27
+ /**
28
+ * Normalizes a character definition's `home` field into an array of home descriptors.
29
+ * The first entry is the primary actor's home; each further entry spawns an echo figure.
30
+ *
31
+ * @param {object} def - Character definition record.
32
+ * @returns {object[]} Zero or more home descriptors.
33
+ */
34
+ export function homesOf(def) {
35
+ return Array.isArray(def.home) ? def.home : def.home ? [def.home] : [];
36
+ }
37
+
38
+ const NULL_PART_KEYS = [
39
+ 'legL',
40
+ 'legR',
41
+ 'cloak',
42
+ 'cloakLow',
43
+ 'capeL',
44
+ 'capeR',
45
+ 'foreL',
46
+ 'foreR',
47
+ 'shinL',
48
+ 'shinR',
49
+ 'footL',
50
+ 'footR',
51
+ 'toesL',
52
+ 'toesR',
53
+ 'head',
54
+ 'sheaths',
55
+ 'hi',
56
+ 'lo',
57
+ 'root',
58
+ 'pelvis',
59
+ 'chest',
60
+ 'rig',
61
+ 'lid',
62
+ 'jaw',
63
+ 'face',
64
+ 'elbowL',
65
+ 'elbowR',
66
+ 'wristL',
67
+ 'wristR',
68
+ 'fingersL',
69
+ 'fingersR',
70
+ 'neck',
71
+ 'tail',
72
+ 'limbs',
73
+ 'handL',
74
+ 'handR',
75
+ 'openR',
76
+ 'openL',
77
+ 'gripR',
78
+ 'gripL',
79
+ 'hold',
80
+ 'hairBone',
81
+ 'bow',
82
+ 'wear',
83
+ ];
84
+
85
+ /**
86
+ * Extracts the scene-graph and skeleton part handles from a built figure or stand-in
87
+ * so an actor record can be initialized or promoted in place without leaking stale fields.
88
+ *
89
+ * @param {object} figure - Built figure (from an assembler or creature builder) or stand-in.
90
+ * @returns {object} Flat map of figure part references and LOD metadata.
91
+ */
92
+ export function extractFigureParts(figure) {
93
+ const f = figure;
94
+ const parts = {
95
+ group: f.group,
96
+ armL: f.armL,
97
+ armR: f.armR,
98
+ height: f.height,
99
+ kind: f.kind,
100
+ itemR: f.itemR,
101
+ itemL: f.itemL,
102
+ worn: f.worn,
103
+ sheath: f.sheath,
104
+ robe: !!f.robe,
105
+ armClear: f.armClear || 0,
106
+ nearBuilt: f.nearBuilt ?? true,
107
+ nearLater: f.nearBuilt !== undefined,
108
+ lx: f.lx || 0.1,
109
+ lidA: f.lidA || 0,
110
+ itemSize: f.itemSize ?? 1,
111
+ hair: f.hair || '',
112
+ gearSwings: !!f.gearSwings,
113
+ mount: f.mount ? { y: f.mount.seat, H: f.mount } : null,
114
+ };
115
+ for (let i = 0; i < NULL_PART_KEYS.length; i++) {
116
+ const key = NULL_PART_KEYS[i];
117
+ parts[key] = f[key] || null;
118
+ }
119
+ return parts;
120
+ }
121
+
122
+ /**
123
+ * Creates a cast actor record built on {@link figureActor} with additional cast lifecycle,
124
+ * worker order, home, echo, and nameplate state initialized in one monomorphic shape.
125
+ *
126
+ * @param {string} id - Actor identifier (or echo identifier such as `'id@1'`).
127
+ * @param {object} def - Character definition containing at least `{ look }`.
128
+ * @param {object} standIn - Lightweight placeholder figure (`{ group, kind, height }`).
129
+ * @param {number} index - Zero-based enlistment index used to seed repeatable idle variation.
130
+ * @param {object} [options]
131
+ * @param {(x: number, y: number, salt?: number) => number} [options.hash] - Seeded 2D hash in `[0, 1)`.
132
+ * @param {number} [options.defaultRange=8] - Default nameplate reading distance (metres).
133
+ * @param {string} [options.defaultSpace='world'] - Initial space identifier.
134
+ * @returns {object} Monomorphic cast actor record ready for `createCastManager`.
135
+ */
136
+ export function createCastActor(id, def, standIn, index, { hash = DEFAULT_HASH, defaultRange = 8, defaultSpace = 'world' } = {}) {
137
+ const actor = figureActor(standIn, {
138
+ id,
139
+ look: def.look,
140
+ phase: hash(index, 3, 9) * TAU,
141
+ seed: hash(index + 1, 5, 11),
142
+ weightRate: TAU / (9 + 8 * hash(index + 1, 7, 13)),
143
+ blinkIn: 1 + 4 * hash(index + 1, 9, 17),
144
+ breath: hash(index + 1, 11, 19) * TAU,
145
+ });
146
+ Object.assign(actor, extractFigureParts(standIn), {
147
+ def,
148
+ built: false,
149
+ preparing: false,
150
+ order: null,
151
+ nearOrder: null,
152
+ figureSeed: 0,
153
+ active: false,
154
+ space: defaultSpace,
155
+ met: false,
156
+ plate: null,
157
+ plateOnCard: false,
158
+ plateA: 0,
159
+ plateBeside: false,
160
+ dist: 0,
161
+ sx: 0,
162
+ sy: 0,
163
+ ph: 0,
164
+ range: defaultRange,
165
+ hs: null,
166
+ home: null,
167
+ });
168
+ return actor;
169
+ }
170
+
171
+ /**
172
+ * Clears transient scene action state when an actor enters a fresh pose or returns home.
173
+ *
174
+ * @param {object} actor - Cast actor record.
175
+ */
176
+ export function atRest(actor) {
177
+ actor.act = actor.watch = null;
178
+ actor.drawn = actor.forward = actor.awake = actor.carryingProp = false;
179
+ actor.effort = 0;
180
+ }
181
+
182
+ /**
183
+ * Resets locomotion velocity, turn target, and foot-plant state after teleporting an actor.
184
+ *
185
+ * @param {object} actor - Cast actor record.
186
+ */
187
+ export function standStill(actor) {
188
+ actor.px = actor.x;
189
+ actor.pz = actor.z;
190
+ actor.turn = actor.hip = NaN;
191
+ actor.feet = null;
192
+ actor.spin = actor.speed = actor.fwd = actor.side = actor.slope = 0;
193
+ }
194
+
195
+ /**
196
+ * Places an actor immediately at `(x, z)` facing `yaw` (radians), on the ground or at `y`.
197
+ *
198
+ * @param {object} actor - Cast actor record.
199
+ * @param {number} x - World X coordinate (metres).
200
+ * @param {number} z - World Z coordinate (metres).
201
+ * @param {number} [yaw] - Optional facing angle (radians, 0 faces +Z).
202
+ * @param {number} [y] - Optional fixed Y elevation (metres); omit to follow ground.
203
+ */
204
+ export function placeCastActor(actor, x, z, yaw, y) {
205
+ actor.x = x;
206
+ actor.z = z;
207
+ if (yaw !== undefined) actor.yaw = yaw;
208
+ actor.fixY = y === undefined ? null : y;
209
+ actor.move = null;
210
+ actor.active = true;
211
+ standStill(actor);
212
+ }
213
+
214
+ /**
215
+ * Snaps an actor into its current `pose` without easing, updates unconscious eyelid state,
216
+ * and clears transient action flags.
217
+ *
218
+ * @param {object} actor - Cast actor record.
219
+ * @param {(actor: object) => void} takePose - Immediate pose setter from the figure pose pipeline.
220
+ */
221
+ export function settleCastPose(actor, takePose) {
222
+ takePose(actor);
223
+ actor.unconscious = actor.pose === 'dead' || ((actor.pose === 'lie' || actor.pose === 'prone') && !actor.awake) ? 1 : 0;
224
+ atRest(actor);
225
+ }
226
+
227
+ /**
228
+ * Resolves an actor's position and heading on or orbiting a registered moving reference frame.
229
+ * Returns `false` when the frame is unregistered or has no walkable ground under the anchor.
230
+ *
231
+ * @param {object} actor - Cast actor record with `actor.home.on`.
232
+ * @param {Record<string, { origin: { x: number, y: number, z: number }, turn: () => number, ground: (x: number, z: number) => number }>} frames - Registered moving frames by name.
233
+ * @param {number} t - Elapsed world time (seconds).
234
+ * @param {number} [orbitRise=9] - Vertical bobbing amplitude (metres) for orbiting fliers.
235
+ * @returns {boolean} True when the actor was placed on or around the frame.
236
+ */
237
+ export function homeOnFrame(actor, frames, t, orbitRise = DEFAULT_ORBIT_RISE) {
238
+ const h = actor.home,
239
+ frame = frames[h.on];
240
+ if (!frame) return false;
241
+ const o = frame.origin;
242
+ if (h.orbit) {
243
+ const [r, up, per, ph] = h.orbit,
244
+ an = ph + (t * TAU) / per;
245
+ actor.x = o.x + Math.cos(an) * r;
246
+ actor.z = o.z + Math.sin(an) * r;
247
+ actor.fixY = o.y + up + Math.sin(t * 0.21 + ph * 3) * orbitRise;
248
+ actor.yaw = Math.atan2(-Math.sin(an) * Math.sign(per), Math.cos(an) * Math.sign(per));
249
+ return true;
250
+ }
251
+ const cos = Math.cos(frame.turn()),
252
+ sin = Math.sin(frame.turn()),
253
+ at = (u, v, k) => (k ? o.z - sin * u + cos * v : o.x + cos * u + sin * v);
254
+ const x = at(h.d[0], h.d[1], 0),
255
+ z = at(h.d[0], h.d[1], 1),
256
+ y = frame.ground(x, z);
257
+ if (!Number.isFinite(y)) return false;
258
+ actor.x = x;
259
+ actor.z = z;
260
+ actor.fixY = y + (h.y || 0);
261
+ const lx = h.look ? at(h.look[0], h.look[1], 0) : o.x,
262
+ lz = h.look ? at(h.look[0], h.look[1], 1) : o.z;
263
+ actor.yaw = Math.atan2(lx - x, lz - z);
264
+ return true;
265
+ }
266
+
267
+ /**
268
+ * Places an actor inside an interior space when that space is built, or deactivates it until then.
269
+ *
270
+ * @param {object} actor - Cast actor record.
271
+ * @param {object} home - Interior home descriptor `{ in, d, look?, y? }`.
272
+ * @param {object} options
273
+ * @param {(spaceId: string) => boolean} options.isSpaceBuilt - Reports whether a space has been built.
274
+ * @param {(spaceId: string) => { origin: { x: number, z: number }, ground: (x: number, z: number) => number }} options.getSpace - Looks up a built space by id.
275
+ */
276
+ export function placeActorInside(actor, home, { isSpaceBuilt, getSpace }) {
277
+ if (!isSpaceBuilt(home.in)) {
278
+ actor.active = false;
279
+ actor.group.visible = false;
280
+ return;
281
+ }
282
+ const sp = getSpace(home.in),
283
+ x = sp.origin.x + home.d[0],
284
+ z = sp.origin.z + home.d[1],
285
+ to = home.look ?? [0, 0];
286
+ actor.space = home.in;
287
+ actor.active = true;
288
+ actor.pose = 'idle';
289
+ actor.x = x;
290
+ actor.z = z;
291
+ actor.yaw = Math.atan2(sp.origin.x + to[0] - x, sp.origin.z + to[1] - z);
292
+ actor.fixY = home.y === undefined ? null : sp.ground(x, z) + home.y;
293
+ }
294
+
295
+ /**
296
+ * Sends an actor back to its home (interior space, moving frame, or outdoor ground anchor),
297
+ * clearing any active scene or movement state.
298
+ *
299
+ * @param {object} actor - Cast actor record.
300
+ * @param {object} options
301
+ * @param {(spaceId: string) => boolean} options.isSpaceBuilt - Reports whether a space is currently built.
302
+ * @param {(spaceId: string) => object} options.getSpace - Returns a built space by id.
303
+ * @param {(key: string) => (number | { x: number, y?: number, z: number })} options.resolvePlace - Resolves named place anchors.
304
+ * @param {(x: number, z: number) => number} options.worldGround - Samples ground height (metres) in the default world space.
305
+ * @param {number} [options.defaultRange=8] - Restored nameplate reading distance (metres).
306
+ * @param {string} [options.worldSpaceId='world'] - Space identifier for outdoor ground homes.
307
+ * @param {(actor: object, onFoot: boolean) => void} [options.setAfoot] - Resets rider/dismount state.
308
+ * @param {(actor: object) => string} [options.idlePoseOf] - Returns the resting pose for an outdoor actor (`'idle'` by default).
309
+ */
310
+ export function placeActorAtHome(
311
+ actor,
312
+ {
313
+ isSpaceBuilt,
314
+ getSpace,
315
+ resolvePlace,
316
+ worldGround,
317
+ defaultRange = 8,
318
+ worldSpaceId = 'world',
319
+ setAfoot = null,
320
+ idlePoseOf = () => 'idle',
321
+ },
322
+ ) {
323
+ const h = actor.home;
324
+ if (setAfoot) setAfoot(actor, false);
325
+ actor.inScene = false;
326
+ actor.move = null;
327
+ actor.range = defaultRange;
328
+ actor.lookAt = null;
329
+ actor.turn = NaN;
330
+ atRest(actor);
331
+ if (h?.in) return placeActorInside(actor, h, { isSpaceBuilt, getSpace });
332
+ if (!h || !isSpaceBuilt(worldSpaceId)) {
333
+ actor.active = false;
334
+ actor.group.visible = false;
335
+ return;
336
+ }
337
+ actor.space = worldSpaceId;
338
+ actor.active = true;
339
+ actor.pose = idlePoseOf(actor);
340
+ if (h.on) {
341
+ actor.fixY = null;
342
+ return;
343
+ }
344
+ const p = resolvePlace(h.at),
345
+ x = p.x + h.d[0],
346
+ z = p.z + h.d[1];
347
+ let yaw = 0;
348
+ if (h.look) yaw = Math.atan2(p.x + h.look[0] - x, p.z + h.look[1] - z);
349
+ else yaw = Math.atan2(p.x - x, p.z - z);
350
+ actor.x = x;
351
+ actor.z = z;
352
+ actor.yaw = yaw;
353
+ if (h.y === undefined) actor.fixY = null;
354
+ else if (typeof h.y === 'number') actor.fixY = worldGround(x, z) + h.y;
355
+ else {
356
+ const target = resolvePlace(h.y);
357
+ actor.fixY = typeof target === 'number' ? target : target.y;
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Determines whether an actor is active in `spaceId` on this frame, hiding echoes whose
363
+ * primary actor is currently playing in a scene and updating moving-frame anchors.
364
+ *
365
+ * @param {object} actor - Cast actor record.
366
+ * @param {number} t - Elapsed world time (seconds).
367
+ * @param {string} spaceId - Space identifier to test against.
368
+ * @param {Record<string, object>} frames - Registered moving reference frames.
369
+ * @param {number} [orbitRise=9] - Orbit vertical oscillation amplitude (metres).
370
+ * @returns {boolean} True when the actor should be updated and considered for visibility.
371
+ */
372
+ export function isActorInPlay(actor, t, spaceId, frames, orbitRise = DEFAULT_ORBIT_RISE) {
373
+ return !(
374
+ !actor.active ||
375
+ actor.space !== spaceId ||
376
+ (actor.primary && actor.primary.inScene) ||
377
+ (actor.home && actor.home.on && !actor.inScene && !actor.move && !homeOnFrame(actor, frames, t, orbitRise))
378
+ );
379
+ }