roamwright 0.61.4 → 0.61.5

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.
@@ -15,6 +15,151 @@ import { C } from './primitives.js';
15
15
  // pale (a lighter belly, throat and inner leg), mask (a dark muzzle), socks (dark feet), mottle (blotches of the second
16
16
  // colour), grizzle (a muzzle flecked with grey), mange (bare patches), scars.
17
17
  // ════════════════════════════════════════════════════════════════════════
18
+ /**
19
+ * Cupped ear-shell parameter rows for each canid kind (passed to `earShell` in `geometry/animal-ear.js`).
20
+ * Linear sizes are in head-size units; `at` is `[x/wide, y/size, z/size]` on the skull; `tip` is tip
21
+ * roundness (0 pointed to 1 broad rounded lobe); `fold` is the fraction of height where the blade bends
22
+ * forward (1 = upright) by `bend` radians; `fur` is inner ear furring (0..1).
23
+ */
24
+ export const CANINE_EARS = {
25
+ // Wolf: upright, broad at the base, compact rounded tips, deeply cupped and furred pale inside, seated high and wide.
26
+ wolf: {
27
+ width: 0.12,
28
+ height: 0.132,
29
+ cup: 0.28,
30
+ tip: 0.8,
31
+ fold: 1,
32
+ bend: 0,
33
+ lean: 0.04,
34
+ tilt: 0.05,
35
+ slope: 0.22,
36
+ thick: 0.017,
37
+ fur: 0.9,
38
+ up: [0.24, 0.96, -0.12],
39
+ front: [0.3, 0.12, 0.94],
40
+ at: [0.06, 0.048, 0.04],
41
+ },
42
+ // Jackal: tall, pointed, upright acoustic cups seated high on the narrow skull.
43
+ jackal: {
44
+ width: 0.112,
45
+ height: 0.184,
46
+ cup: 0.3,
47
+ tip: 0.16,
48
+ fold: 1,
49
+ bend: 0,
50
+ lean: 0.03,
51
+ tilt: 0.05,
52
+ slope: 0.22,
53
+ thick: 0.013,
54
+ fur: 0.45,
55
+ up: [0.26, 0.95, -0.08],
56
+ front: [0.28, 0.1, 0.95],
57
+ at: [0.062, 0.048, 0.044],
58
+ },
59
+ // Street / pariah dog: medium semi-erect ears with the upper third tipped forward, seated lower than a wolf's.
60
+ cur: {
61
+ width: 0.108,
62
+ height: 0.144,
63
+ cup: 0.26,
64
+ tip: 0.48,
65
+ fold: 0.62,
66
+ bend: 1.1,
67
+ lean: 0.05,
68
+ tilt: 0.05,
69
+ slope: 0.26,
70
+ thick: 0.013,
71
+ fur: 0.25,
72
+ up: [0.3, 0.93, -0.1],
73
+ front: [0.36, 0.12, 0.92],
74
+ at: [0.074, 0.044, 0.042],
75
+ },
76
+ // Herding / cattle dog: medium-broad ears folded forward, seated low and wide on the broad skull.
77
+ cattle: {
78
+ width: 0.114,
79
+ height: 0.146,
80
+ cup: 0.25,
81
+ tip: 0.58,
82
+ fold: 0.48,
83
+ bend: 1.95,
84
+ lean: 0.05,
85
+ tilt: 0.04,
86
+ slope: 0.24,
87
+ thick: 0.016,
88
+ fur: 0.22,
89
+ up: [0.36, 0.91, -0.08],
90
+ front: [0.4, 0.1, 0.91],
91
+ at: [0.072, 0.04, 0.042],
92
+ },
93
+ // Ratter / small terrier: V-shaped button ears rising cleanly then folded forward at the tip.
94
+ ratter: {
95
+ width: 0.1,
96
+ height: 0.138,
97
+ cup: 0.24,
98
+ tip: 0.48,
99
+ fold: 0.45,
100
+ bend: 2.18,
101
+ lean: 0.04,
102
+ tilt: 0.04,
103
+ slope: 0.24,
104
+ thick: 0.012,
105
+ fur: 0.2,
106
+ up: [0.34, 0.92, -0.06],
107
+ front: [0.38, 0.1, 0.92],
108
+ at: [0.068, 0.046, 0.046],
109
+ },
110
+ // Lapdog: long rounded hanging ears (`point: 0` leaf root) draping smoothly beside the cheeks, cup facing inward.
111
+ lapdog: {
112
+ width: 0.108,
113
+ height: 0.18,
114
+ cup: 0.2,
115
+ point: 0,
116
+ tip: 0.85,
117
+ fold: 1,
118
+ bend: 0,
119
+ lean: -0.1,
120
+ tilt: 0,
121
+ slope: 0,
122
+ thick: 0.015,
123
+ fur: 0.15,
124
+ up: [0.26, -0.95, 0.16],
125
+ front: [-0.88, -0.18, 0.44],
126
+ at: [0.068, 0.042, 0.052],
127
+ },
128
+ // Heavy semi-erect hound ear (used by legacy `['half', size]` breed rows).
129
+ half: {
130
+ width: 0.12,
131
+ height: 0.148,
132
+ cup: 0.28,
133
+ tip: 0.48,
134
+ fold: 0.64,
135
+ bend: 1.05,
136
+ lean: 0.05,
137
+ tilt: 0.05,
138
+ slope: 0.26,
139
+ thick: 0.018,
140
+ fur: 0.35,
141
+ up: [0.28, 0.94, -0.12],
142
+ front: [0.34, 0.12, 0.93],
143
+ at: [0.07, 0.046, 0.04],
144
+ },
145
+ };
146
+
147
+ /**
148
+ * Resolves a breed's `ear` value (an explicit parameter row or a legacy `[kind, size]` tuple) into an
149
+ * `earShell` parameter row, or `null` for non-canid round/cat ear kinds handled elsewhere.
150
+ * @param {object | [string, number]} earSpec
151
+ */
152
+ function resolveEar(earSpec) {
153
+ if (!earSpec) return CANINE_EARS.wolf;
154
+ if (!Array.isArray(earSpec)) return { ...CANINE_EARS.wolf, ...earSpec };
155
+ const [kind, size = 1] = earSpec;
156
+ if (kind === 'round' || kind === 'cat') return null;
157
+ const base =
158
+ CANINE_EARS[kind] ??
159
+ (kind === 'prick' ? CANINE_EARS.wolf : kind === 'fold' ? CANINE_EARS.ratter : kind === 'drop' ? CANINE_EARS.lapdog : CANINE_EARS.cur);
160
+ return size === 1 ? base : { ...base, width: base.width * size, height: base.height * size };
161
+ }
162
+
18
163
  /** The numbers every canine starts from, which a breed and then a look set again (see above). */
19
164
  export const CANINE_BASE = {
20
165
  leg: 0.53,
@@ -29,7 +174,7 @@ export const CANINE_BASE = {
29
174
  stop: 0.8,
30
175
  skull: 1,
31
176
  jowl: 0.15,
32
- ear: ['prick', 1],
177
+ ear: CANINE_EARS.wolf,
33
178
  tail: [1, 0.08, 1.15],
34
179
  fur: 1,
35
180
  ruff: 1,
@@ -67,7 +212,7 @@ export const CANINE_BREEDS = {
67
212
  stop: 0.65,
68
213
  skull: 0.9,
69
214
  jowl: 0,
70
- ear: ['prick', 1.5],
215
+ ear: CANINE_EARS.jackal,
71
216
  tail: [0.8, 0.05, 1.25],
72
217
  fur: 0.7,
73
218
  ruff: 0.5,
@@ -87,7 +232,7 @@ export const CANINE_BREEDS = {
87
232
  stop: 1.5,
88
233
  skull: 1.3,
89
234
  jowl: 1,
90
- ear: ['fold', 0.85],
235
+ ear: CANINE_EARS.cattle,
91
236
  tail: [0.9, 0.3, 0.55],
92
237
  fur: 0.55,
93
238
  ruff: 0.5,
@@ -113,7 +258,7 @@ export const CANINE_BREEDS = {
113
258
  stop: 1.9,
114
259
  skull: 1.2,
115
260
  jowl: 0.45,
116
- ear: ['drop', 1.2],
261
+ ear: CANINE_EARS.lapdog,
117
262
  tail: [0.75, 0.85, 0.55],
118
263
  fur: 1.35,
119
264
  ruff: 0.75,
@@ -128,7 +273,7 @@ export const CANINE_BREEDS = {
128
273
  leg: 0.56,
129
274
  girth: 0.9,
130
275
  bone: 0.9,
131
- ear: ['fold', 0.9],
276
+ ear: CANINE_EARS.cur,
132
277
  tail: [0.95, 0.5, 0.35],
133
278
  fur: 0.45,
134
279
  ruff: 0.3,
@@ -173,7 +318,7 @@ export const CANINE_BREEDS = {
173
318
  head: 1.15,
174
319
  muzzle: 0.9,
175
320
  stop: 1.2,
176
- ear: ['fold', 0.8],
321
+ ear: CANINE_EARS.ratter,
177
322
  tail: [0.4, 0.9, 0.3],
178
323
  fur: 0.9,
179
324
  ruff: 0.6,
@@ -316,4 +461,4 @@ function coatOf(L, p, head, fbm) {
316
461
  };
317
462
  }
318
463
 
319
- export { HEAD, LIMB, TAIL, TRUNK, breedOf, coatOf, hair };
464
+ export { HEAD, LIMB, TAIL, TRUNK, breedOf, coatOf, hair, resolveEar };
@@ -2,7 +2,8 @@ import { lerp, sstep } from '../math/scalar.js';
2
2
  import { C, TRS } from './primitives.js';
3
3
  import { SHAPES } from './animal-shapes.js';
4
4
  import { EYE_TAG, leaf, tube } from './animal-skin.js';
5
- import { HEAD } from './animal-canine-breeds.js';
5
+ import { earShell } from './animal-ear.js';
6
+ import { HEAD, resolveEar } from './animal-canine-breeds.js';
6
7
  import { BONE } from '../motion/quadruped.js';
7
8
 
8
9
  // ════════════════════════════════════════════════════════════════════════
@@ -80,7 +81,10 @@ function muzzledFace(H, p) {
80
81
  H.pads = null;
81
82
  H.iris = p.darkEye ? 0x161210 : 0x8a5e1e;
82
83
  H.mouth = [-0.028 * k, -0.036 * k]; // the height of the upper teeth and the lower
83
- H.ear = [0.08 * wide, 0.052 * k, 0.035 * k]; // the right ear's root
84
+ const earRow = resolveEar(p.ear);
85
+ // Canid ears sit where each kind's ears really grow (high and wide on wolves/jackals, lower on dogs);
86
+ // non-canid round ears (rat, bear) keep their original root placement.
87
+ H.ear = earRow ? [earRow.at[0] * wide, earRow.at[1] * k, earRow.at[2] * k] : [0.08 * wide, 0.052 * k, 0.035 * k];
84
88
  H.hinge = [0, -0.032 * k, 0.1 * k]; // the jaw's
85
89
  H.lip = [0, 0, stop + 0.4 * muzzle]; // the lips' bone
86
90
  return H;
@@ -137,8 +141,8 @@ function catFace(H) {
137
141
  }
138
142
 
139
143
  // The head: skull, brow and face as one skin, with sockets for the eyes; the lower jaw on its hinge; nose, eyes, whisker pads,
140
- // ears, teeth and tongue. Built along its own length and set on the poll. twoFaced: the ears drawn on both faces (a herd's).
141
- function head(b, H, p, L, coat, detail, twoFaced) {
144
+ // ears, teeth and tongue. Built along its own length and set on the poll.
145
+ function head(b, H, p, L, coat, detail) {
142
146
  const { size: k, stop, nose, muzzle, snout, eye, socket } = H,
143
147
  skin = coat(HEAD),
144
148
  lips = (col, x, y, z, nx, ny, nz, a, v) => {
@@ -219,7 +223,7 @@ function head(b, H, p, L, coat, detail, twoFaced) {
219
223
  if (L.pupil !== false)
220
224
  b.add(SHAPES.sph, BLACK, TRS(x + s * ball.pupilAt[0], eye[1], eye[2] + ball.pupilAt[1], px, py, pz, s * ball.turn));
221
225
  if (H.pads) pad(b, H, skin, s);
222
- ear(b, H, p, coat, s, twoFaced);
226
+ ear(b, H, p, L, coat, s, detail);
223
227
  });
224
228
  if (detail === NEAR) teeth(b, H, p, L);
225
229
  }
@@ -238,11 +242,64 @@ function pad(b, H, skin, s) {
238
242
  );
239
243
  }
240
244
 
241
- // An ear by its kind: pricked, tipped over, folded, hanging, a bear's round one, or a cat's upright triangle facing forwards.
242
- function ear(b, H, p, coat, s) {
243
- const [kind, size] = p.ear,
244
- k = H.size,
245
+ const unit3 = v => {
246
+ const l = Math.hypot(v[0], v[1], v[2]) || 1;
247
+ return [v[0] / l, v[1] / l, v[2] / l];
248
+ };
249
+ const cross3 = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
250
+
251
+ // An ear by its kind: canids wear the cupped shell of `geometry/animal-ear.js` shaped by their row in `CANINE_EARS`
252
+ // (upright, semi-erect, folded forward, or hanging); non-canid round ears (rat, bear) keep the round leaf unchanged.
253
+ function ear(b, H, p, L, coat, s, detail) {
254
+ const k = H.size,
245
255
  base = [s * H.ear[0], H.ear[1], H.ear[2]],
256
+ row = resolveEar(p.ear);
257
+ if (row) {
258
+ // Build a strictly orthonormal right-handed frame (up, across = front × up, front = up × across) so inner and outer
259
+ // ear faces stay mirror-symmetric across x = 0 and never invert winding on either side.
260
+ const u = unit3([s * row.up[0], row.up[1], row.up[2]]),
261
+ rawFront = [s * row.front[0], row.front[1], row.front[2]],
262
+ ac = unit3(cross3(rawFront, u)),
263
+ fr = cross3(u, ac),
264
+ col = [0, 0, 0, 0];
265
+ coat(HEAD)(col, base[0], base[1] + 0.04 * k, base[2], s * 0.3, 0.9, 0.2);
266
+ const outer = col.slice(0, 3),
267
+ baseCoat = C(L.c1 ?? 0x4a4038),
268
+ dusky = [outer[0] * 0.52 + 0.05, outer[1] * 0.45 + 0.035, outer[2] * 0.43 + 0.035],
269
+ // Derive pale inner guard fur from the primary coat colour (not the dark crown saddle) so furred ears read pale inside.
270
+ pale = L.c3 !== undefined ? C(L.c3) : [baseCoat[0] * 0.45 + 0.42, baseCoat[1] * 0.45 + 0.39, baseCoat[2] * 0.45 + 0.34],
271
+ furred = [pale[0] * 0.92, pale[1] * 0.9, pale[2] * 0.86],
272
+ inner = [lerp(dusky[0], furred[0], row.fur), lerp(dusky[1], furred[1], row.fur), lerp(dusky[2], furred[2], row.fur)],
273
+ // Match the cat's ear LOD budget; folded ears take one extra row so the forward crease curves smoothly.
274
+ rows = (row.fold < 1 ? [4, 5, 7] : [3, 4, 6])[detail],
275
+ cols = [2, 3, 4][detail];
276
+ earShell(b, {
277
+ base,
278
+ up: u,
279
+ across: ac,
280
+ front: fr,
281
+ height: row.height * k,
282
+ width: row.width * k,
283
+ cup: row.cup,
284
+ point: row.point ?? 1,
285
+ tip: row.tip,
286
+ fold: row.fold,
287
+ bend: row.bend,
288
+ lean: row.lean,
289
+ tilt: -s * row.tilt,
290
+ slope: s * row.slope,
291
+ thick: row.thick * k,
292
+ fur: row.fur,
293
+ inner,
294
+ outer,
295
+ tag: col[3],
296
+ bone: s < 0 ? BONE.earL : BONE.earR,
297
+ rows,
298
+ cols,
299
+ });
300
+ return;
301
+ }
302
+ const [kind, size] = p.ear,
246
303
  hang = kind === 'drop',
247
304
  cat = kind === 'cat',
248
305
  round = kind === 'round',
@@ -1,8 +1,9 @@
1
1
  // ════════════════════════════════════════════════════════════════════════
2
2
  // An ear as a thin shell of skin standing on its base: a rounded triangle open towards a direction (a cat's, a fox's, a
3
- // wolf's), or a rounded leaf (a bear's). Its inner face is a shallow cup, deepest near the base; its back is the cup's outside;
4
- // the rim and the tip thin to nothing, so the shell closes on itself and only its base, buried in the head, stays open. The tip
5
- // leans towards the front or back, and the blade leans outwards, each by a share of its height.
3
+ // wolf's, a jackal's), a folded ear whose upper blade bends forward over a smooth crease (a terrier's, a pariah dog's),
4
+ // or a rounded leaf (a bear's, a hanging drop ear). Its inner face is a shallow cup, deepest near the base; its back is
5
+ // the cup's outside; the rim and the tip thin to nothing, so the shell closes on itself and only its base, buried in the
6
+ // head, stays open. The tip leans towards the front or back, and the blade leans outwards, each by a share of its height.
6
7
  // ════════════════════════════════════════════════════════════════════════
7
8
 
8
9
  /**
@@ -19,6 +20,10 @@
19
20
  * @property {number} tilt How far the blade leans towards `across`, as a share of the height.
20
21
  * @property {number} thick The shell's thickness at the middle of its root.
21
22
  * @property {number} [point=1] 1 a triangle broadest at its root, 0 a leaf rounded at its root.
23
+ * @property {number} [tip] Tip roundness in [0, 1] when `point` is set (0 sharp pointed triangle, ~0.38 cat default, 0.72 wolf rounded tip, 0.85 broad rounded lobe).
24
+ * @property {number} [fold=1] Share of height at which the upper blade begins to fold forward (1: no fold).
25
+ * @property {number} [bend=0] Forward fold angle in radians past `fold` (0: straight upright; ~1.1 semi-erect; ~2.1 folded forward).
26
+ * @property {number} [fur=0] Inner ear furring in [0, 1] (0: bare/cat inner blend; higher fills the cup with soft inner fur).
22
27
  * @property {number} [slope=0] How far the root's outer end (across its -1 side) sits lower than its inner end, as a share of the
23
28
  * width, as a root does over the corner of a skull.
24
29
  * @property {number[]} inner The colour at the bottom of the cup, linear [r, g, b].
@@ -38,17 +43,54 @@ function earShell(gb, o) {
38
43
  const { base, up, across, front, height, width, cup, lean, tilt, thick, inner, outer, tag, bone, rows, cols } = o,
39
44
  point = o.point ?? 1,
40
45
  slope = o.slope ?? 0,
46
+ fold = o.fold ?? 1,
47
+ bend = o.bend ?? 0,
48
+ fur = o.fur ?? 0,
49
+ // Keep the original exponent and thickness path verbatim when no canid shaping option is passed so existing cat bytes never shift.
50
+ shaped = o.tip !== undefined || o.fold !== undefined || o.bend !== undefined || o.fur !== undefined,
51
+ tipExp = o.tip === undefined ? 0.78 : 1.02 - 0.64 * o.tip,
52
+ folded = fold < 1 && bend > 0,
53
+ crease = folded ? Math.min(0.24, Math.max(0.08, (1 - fold) * 0.48)) : 0,
41
54
  half = width / 2,
42
- // the blade's half-width at a share t of its height: a triangle's sides softly convex toward a rounded apex, or a leaf's round
43
- wideAt = t => (point ? half * (1 - t) ** 0.78 : half * Math.sin(Math.PI * (0.25 + 0.75 * t)) ** 0.8 * (1 - t ** 3)),
44
- // a point of the inner face, in the ear's frame: along the ear, across it, and back from its opening (the cup, deepest at
45
- // the root, and the tip's lean)
55
+ // the blade's half-width at a share t of its height: a triangle's sides convex toward a pointed or rounded apex, or a leaf's round
56
+ wideAt = t => (point ? half * (1 - t) ** tipExp : half * Math.sin(Math.PI * (0.25 + 0.75 * t)) ** 0.8 * (1 - t ** 3)),
57
+ // a point of the inner face, in the ear's frame: along the ear, across it, and forward along its opening
46
58
  frame = (t, s) => {
47
59
  const w = wideAt(t) / half;
60
+ if (!folded) {
61
+ return [
62
+ height * t + slope * half * s * (1 - t), // the root's outer end (s = -1: across points inward) sits lower
63
+ wideAt(t) * s + tilt * height * t,
64
+ -cup * width * (1 - s * s) * w * (1 - 0.5 * t) + lean * height * t * t,
65
+ ];
66
+ }
67
+ // Smooth arc-length-preserving circular crease from t = fold over `crease`, then a straight upper flap at angle `bend`.
68
+ let along, fwd, angle;
69
+ if (t <= fold) {
70
+ angle = 0;
71
+ along = height * t;
72
+ fwd = lean * height * t * t;
73
+ } else {
74
+ const dt = t - fold,
75
+ baseFwd = lean * height * fold * fold,
76
+ radius = (crease * height) / bend;
77
+ if (dt <= crease) {
78
+ angle = (bend * dt) / crease;
79
+ along = height * fold + radius * Math.sin(angle);
80
+ fwd = baseFwd + radius * (1 - Math.cos(angle));
81
+ } else {
82
+ angle = bend;
83
+ const rem = (dt - crease) * height;
84
+ along = height * fold + radius * Math.sin(bend) + rem * Math.cos(bend);
85
+ fwd = baseFwd + radius * (1 - Math.cos(bend)) + rem * Math.sin(bend);
86
+ }
87
+ }
88
+ // Push the cup perpendicular to the bent spine so the outer face stays convex over the crease with no self-intersection.
89
+ const depth = cup * width * (1 - s * s) * w * (1 - 0.5 * t);
48
90
  return [
49
- height * t + slope * half * s * (1 - t), // the root's outer end (s = -1: across points inward) sits lower
50
- wideAt(t) * s + tilt * height * t,
51
- -cup * width * (1 - s * s) * w * (1 - 0.5 * t) + lean * height * t * t,
91
+ along + slope * half * s * (1 - t) + depth * Math.sin(angle),
92
+ wideAt(t) * s + tilt * height * Math.min(t, fold),
93
+ fwd - depth * Math.cos(angle),
52
94
  ];
53
95
  },
54
96
  world = (f, out) => {
@@ -85,8 +127,19 @@ function earShell(gb, o) {
85
127
  P = [0, 0, 0],
86
128
  N = [0, 0, 0],
87
129
  put = (p, n, c) => gb.raw(p[0], p[1], p[2], n[0], n[1], n[2], c[0], c[1], c[2], bone, bone, 1),
88
- // the colour of the inner face: the cup's colour at the bottom of its middle, the coat's towards the rim and the tip
130
+ // the colour of the inner face: the cup's colour at the bottom of its middle, the coat's towards the rim and the tip;
131
+ // furred ears keep the paler inner fur broad across the cup with a soft dark hollow right at the root canal
89
132
  innerAt = (t, s) => {
133
+ if (fur > 0) {
134
+ // Keep furred inner pinna bright across the cup, blending to the outer coat only along the rim and tip.
135
+ const edge = Math.min(1, 0.06 + 0.94 * Math.abs(s) ** 2.4 + 0.55 * t ** 2.4);
136
+ const hollow = 1 - fur * 0.16 * (1 - Math.min(1, t * 2.8)) * (1 - s * s);
137
+ return [
138
+ (inner[0] + (outer[0] - inner[0]) * edge) * hollow,
139
+ (inner[1] + (outer[1] - inner[1]) * edge) * hollow,
140
+ (inner[2] + (outer[2] - inner[2]) * edge) * hollow,
141
+ ];
142
+ }
90
143
  const k = Math.min(1, 0.25 + 0.75 * Math.abs(s) ** 1.5 + 0.6 * t);
91
144
  return [inner[0] + (outer[0] - inner[0]) * k, inner[1] + (outer[1] - inner[1]) * k, inner[2] + (outer[2] - inner[2]) * k];
92
145
  };
@@ -113,8 +166,17 @@ function earShell(gb, o) {
113
166
  ].map(([t, s]) => {
114
167
  const f = frame(t, s),
115
168
  n = normal(t, s, N),
116
- k = skin(t, s) * back,
169
+ k = skin(t, s) * back;
170
+ let p;
171
+ if (shaped) {
172
+ // Offset along the world-space surface normal so folded and tilted ears keep uniform skin thickness.
173
+ p = world(f, P);
174
+ p[0] -= n[0] * k;
175
+ p[1] -= n[1] * k;
176
+ p[2] -= n[2] * k;
177
+ } else {
117
178
  p = world([f[0] - n[0] * k, f[1] - n[1] * k, f[2] - n[2] * k], P);
179
+ }
118
180
  return [p.slice(), side > 0 ? n.slice() : n.map(v => -v)];
119
181
  });
120
182
  for (const k of order)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.4",
3
+ "version": "0.61.5",
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
  "keywords": [
6
6
  "threejs",
package/tools/README.md CHANGED
@@ -14,6 +14,7 @@ const { renewShaders, renewalFlags, saltFor } = require('roamwright/tools/shader
14
14
  | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15
15
  | `page-driver.cjs` | What every tool that opens a world's built page starts from: finds Playwright and a headless Chrome shell, launches on the graphics card, enters the world (`enter`), builds route URLs (`routeUrl`), clears camera collisions (`clearView`), seeds prefixed `localStorage` (`applyStorage`), prints the page's own log (`window[debug].log()`) and WebGL warnings on close, installs shader switches (`installCuts`), and guards against hung runs (`longRun`). |
16
16
  | `stills.cjs` | Generic headless capture and inspection runners built on `page-driver.cjs`: single stills (`takeShot`), settled expression evaluation (`evalInPage`), hand-placed camera tours (`captureViews`), headless phone layout checks (`emulatePhone`), four-height land sweeps (`sweepLand`), scene motion strips (`captureStrip`), and labelled contact sheets (`writeContactSheet`). |
17
+ | `beasts-near.cjs` | Generic close-up animal inspector built on `page-driver.cjs` and `scene-run.cjs`: raises nearby herds and scene figures at once, freezes daylight, frames sunlit eye-height side/front/three-quarter close-ups (`frameBeastView`, `runBeastsNear`), and supports explicit `--scene <id> --at <seconds>` beats. |
17
18
  | `contact-sheet.cjs` | Renders arrays of captured frames into labelled JPEG contact sheets on disk (`writeContactSheet`, `sheetDimensions`). |
18
19
  | `look-guard.cjs` | Runs a world's fixed-camera and scene-beat look suites, writes `look.yaml` and contact sheets (`runLookGuard`), and compares measured stats against a kept YAML baseline (`compareLookFiles`). |
19
20
  | `look-compare.cjs` | Single-page A/B frame diffing (`runAB`, `diffRgbaFrames`) and multi-frame temporal steadiness / flicker measurement (`runSteady`, `measureFrameSteadiness`). |
@@ -0,0 +1,498 @@
1
+ // Generic close-up animal inspector built on a Roamwright page driver (`page-driver.cjs`),
2
+ // scene playback helpers (`scene-run.cjs`), and contact sheets (`contact-sheet.cjs`).
3
+ //
4
+ // Opens a world at configured places or scenes where each animal kind lives, raises nearby
5
+ // herds and figures at once rather than waiting for streaming, freezes daylight, and takes
6
+ // eye-height side, front, and three-quarter close-ups — plus optional scene beat captures.
7
+ 'use strict';
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { slugify } = require('./stills.cjs');
11
+ const { writeContactSheet } = require('./contact-sheet.cjs');
12
+ const { readyPageForSceneInPage, seekSceneInPage, startSceneInPage, waitSceneReady } = require('./scene-run.cjs');
13
+
14
+ const DEFAULT_VIEWS = ['side', 'front', 'three'];
15
+ const DEFAULT_HOUR = 0.42; // clear late-morning sun for crisp ear and fur shading
16
+ const DEFAULT_WIDTH = 1200;
17
+ const DEFAULT_HEIGHT = 900;
18
+ const DEFAULT_FOV = 34;
19
+
20
+ const VALUE_FLAGS = {
21
+ '--scene': (out, v) => (out.scene = v),
22
+ '--at': (out, v) => (out.at = Number(v)),
23
+ '--actor': (out, v) => (out.actor = v),
24
+ '--hour': (out, v) => {
25
+ out.hour = Number(v);
26
+ out.hourExplicit = true;
27
+ },
28
+ '--prefix': (out, v) => (out.prefix = v),
29
+ '--width': (out, v) => (out.width = Number(v)),
30
+ '--height': (out, v) => (out.height = Number(v)),
31
+ '--views': (out, v) =>
32
+ (out.views = v
33
+ .split(',')
34
+ .map(s => s.trim())
35
+ .filter(Boolean)),
36
+ };
37
+
38
+ /**
39
+ * Parses CLI arguments for a world's `beasts-near` wrapper.
40
+ *
41
+ * @param {string[]} argv Raw CLI arguments (excluding `node` and script path).
42
+ * @returns {object}
43
+ */
44
+ function parseBeastsNearArgs(argv) {
45
+ const out = {
46
+ kinds: [],
47
+ scene: '',
48
+ at: null,
49
+ actor: '',
50
+ hour: DEFAULT_HOUR,
51
+ hourExplicit: false,
52
+ prefix: 'beasts-near',
53
+ width: DEFAULT_WIDTH,
54
+ height: DEFAULT_HEIGHT,
55
+ views: DEFAULT_VIEWS.slice(),
56
+ sheet: false,
57
+ beatOnly: false,
58
+ list: false,
59
+ };
60
+ for (let i = 0; i < argv.length; i++) {
61
+ const arg = argv[i];
62
+ if (arg === '--sheet') out.sheet = true;
63
+ else if (arg === '--beat-only') out.beatOnly = true;
64
+ else if (arg === '--list') out.list = true;
65
+ else if (!arg.startsWith('--')) out.kinds.push(arg);
66
+ else {
67
+ const eq = arg.indexOf('=');
68
+ const flag = eq >= 0 ? arg.slice(0, eq) : arg;
69
+ const apply = VALUE_FLAGS[flag];
70
+ if (!apply) throw new Error(`Unknown option: ${arg}`);
71
+ if (eq < 0 && i + 1 >= argv.length) throw new Error(`Missing value for ${flag}`);
72
+ apply(out, eq >= 0 ? arg.slice(eq + 1) : argv[++i]);
73
+ }
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /**
79
+ * Computes camera position, look-at target, and vertical FOV for a close-up eye-height view
80
+ * (`side`, `front`, or `three`) around a framed animal, picking the sunlit lateral side.
81
+ *
82
+ * @param {object} target Framed beast geometry (`{ origin, minY, height, length, yaw, head, headFocus, zoom }`).
83
+ * @param {'side'|'front'|'three'} view Requested camera angle.
84
+ * @param {number[]|null} [sunDir] Optional unit vector toward the sun `[x, y, z]`.
85
+ * @returns {{ pos: number[], aim: number[], fov: number }}
86
+ */
87
+ function frameBeastView(target, view, sunDir = null) {
88
+ const height = Math.max(0.15, target.height);
89
+ const length = Math.max(height * 0.9, target.length || height * 1.25);
90
+ const yaw = target.yaw || 0;
91
+ const fx = Math.sin(yaw),
92
+ fz = Math.cos(yaw);
93
+ // Three.js Y-rotation maps local +x to (cos yaw, 0, -sin yaw).
94
+ const rx = Math.cos(yaw),
95
+ rz = -Math.sin(yaw);
96
+ const sideSign = sunDir && sunDir.length >= 3 && rx * sunDir[0] + rz * sunDir[2] < 0 ? -1 : 1;
97
+ const head = target.head || [target.origin[0] + fx * length * 0.28, target.minY + height * 0.78, target.origin[2] + fz * length * 0.28];
98
+ const body = [target.origin[0] + fx * length * 0.1, target.minY + height * 0.6, target.origin[2] + fz * length * 0.1];
99
+ const zoom = target.zoom || 1;
100
+
101
+ if (view === 'front' || view === 'three') {
102
+ const isFront = view === 'front';
103
+ const dist = Math.max(isFront ? 0.32 : 0.36, height * (isFront ? 1.32 : 1.48) * zoom);
104
+ const angle = sideSign * (isFront ? 0.1 : 0.68);
105
+ const dx = fx * Math.cos(angle) + rx * Math.sin(angle);
106
+ const dz = fz * Math.cos(angle) + rz * Math.sin(angle);
107
+ const back = isFront ? 0 : length * 0.05;
108
+ const aim = [head[0] - fx * back, head[1] + height * (isFront ? 0.03 : 0.02), head[2] - fz * back];
109
+ return { pos: [aim[0] + dx * dist, aim[1] + height * (isFront ? 0.04 : 0.06), aim[2] + dz * dist], aim, fov: DEFAULT_FOV };
110
+ }
111
+ const dist = Math.max(0.45, Math.max(height * 1.75, length * 1.05) * zoom);
112
+ const aim = target.headFocus
113
+ ? [head[0] - fx * length * 0.08, head[1] - height * 0.04, head[2] - fz * length * 0.08]
114
+ : [body[0], body[1] + height * 0.04, body[2]];
115
+ return { pos: [aim[0] + rx * sideSign * dist, aim[1] + height * 0.03, aim[2] + rz * sideSign * dist], aim, fov: DEFAULT_FOV };
116
+ }
117
+
118
+ /**
119
+ * Finds a herd matching `build` on the active space and teleports the visitor beside one member
120
+ * so streaming orders and raises the herd at once. Passed to `page.evaluate`.
121
+ *
122
+ * @param {{ debug: string, build: string, coat?: string, member?: number }} arg
123
+ */
124
+ function locateHerdBeastInPage({ debug, build, coat = '', member = 0 }) {
125
+ const app = window[debug];
126
+ const spaceId = app.space?.id;
127
+ const crowds = (app.crowds || []).filter(
128
+ c =>
129
+ c.space === spaceId &&
130
+ c.beasts &&
131
+ c.beasts.input?.build === build &&
132
+ (!coat || c.beasts.input?.coat === coat || c.beasts.input?.look?.breed === coat) &&
133
+ c.list?.length > 0,
134
+ );
135
+ if (!crowds.length) return null;
136
+ const cp = app.camera.position;
137
+ crowds.sort((a, b) => Math.hypot(a.cx - cp.x, a.cz - cp.z) - Math.hypot(b.cx - cp.x, b.cz - cp.z));
138
+ const crowd = crowds[0];
139
+ const idx = Math.min(member, crowd.list.length - 1);
140
+ const g = crowd.list[idx];
141
+ const x = Number.isFinite(g.gx) ? g.gx : (g.legs?.[0]?.x0 ?? g.ax ?? crowd.cx);
142
+ const z = Number.isFinite(g.gz) ? g.gz : (g.legs?.[0]?.z0 ?? g.az ?? crowd.cz);
143
+ if (app.state.fly) app.setFly(false);
144
+ app.holdQuality?.(true);
145
+ app.state.mode = 'play';
146
+ app.placePlayer(x + 2.5, z + 2.5, Math.atan2(-2.5, -2.5));
147
+ const y = app.space.ground(x, z);
148
+ app.camera.position.set(x + 2.5, y + 1.2, z + 2.5);
149
+ app.camera.lookAt(x, y + 0.5, z);
150
+ return { crowdIndex: app.crowds.indexOf(crowd), memberIndex: idx, x, z, total: crowd.list.length };
151
+ }
152
+
153
+ /**
154
+ * Freezes a raised herd beast in LOD 0 at the requested hour and returns its world bounds and heading.
155
+ * Passed to `page.evaluate`.
156
+ *
157
+ * @param {{ debug: string, crowdIndex: number, memberIndex: number, hour: number }} arg
158
+ */
159
+ function settleHerdBeastInPage({ debug, crowdIndex, memberIndex, hour }) {
160
+ const app = window[debug];
161
+ const crowd = app.crowds[crowdIndex];
162
+ if (!crowd?.herd) return null;
163
+ app.env.flow = false;
164
+ app.env.override = -1;
165
+ app.env.ovTarget = -1;
166
+ app.env.goal = -1;
167
+ app.env.time = hour;
168
+ app.holdQuality?.(true);
169
+ app.state.mode = 'inspect';
170
+ app.state.debug = false;
171
+ const g = crowd.list[memberIndex];
172
+ const approxX = Number.isFinite(g.gx) ? g.gx : (g.legs?.[0]?.x0 ?? g.ax);
173
+ const approxZ = Number.isFinite(g.gz) ? g.gz : (g.legs?.[0]?.z0 ?? g.az);
174
+ const approxY = Number.isFinite(g.gy) ? g.gy : app.space.ground(approxX, approxZ);
175
+ app.camera.position.set(approxX + 1.8, approxY + 0.9, approxZ + 1.8);
176
+ app.camera.lookAt(approxX, approxY + 0.45, approxZ);
177
+ app.state.measuring = true;
178
+ if (typeof app.step === 'function') app.step(0.02);
179
+
180
+ const level0 = crowd.herd.levels?.[0];
181
+ const sampleMesh = level0?.rests?.[0]?.[0]?.[0] || level0?.moments?.[0]?.[0] || crowd.herd.all?.[0];
182
+ if (!sampleMesh?.geometry) return null;
183
+ const geo = sampleMesh.geometry;
184
+ if (!geo.boundingBox) geo.computeBoundingBox();
185
+ const bb = geo.boundingBox;
186
+ const s = g.s || 1;
187
+ const x = Number.isFinite(g.gx) ? g.gx : approxX;
188
+ const z = Number.isFinite(g.gz) ? g.gz : approxZ;
189
+ const y = Number.isFinite(g.gy) ? g.gy : app.space.ground(x, z);
190
+ const yaw = Number.isFinite(g.dir) ? g.dir : g.pathYaw || 0;
191
+ const height = (bb.max.y - bb.min.y) * s;
192
+ const length = (bb.max.z - bb.min.z) * s;
193
+ const fx = Math.sin(yaw),
194
+ fz = Math.cos(yaw);
195
+ // Herd animals frequently rest sitting or sniffing lower than peak height; aim at 62% of peak height.
196
+ const head = [x + fx * bb.max.z * s * 0.65, y + (bb.min.y + (bb.max.y - bb.min.y) * 0.62) * s, z + fz * bb.max.z * s * 0.65];
197
+ const sun = app.env?.sunDir ? [app.env.sunDir.x, app.env.sunDir.y, app.env.sunDir.z] : null;
198
+ return { origin: [x, y, z], minY: y + bb.min.y * s, height, length, yaw, head, sun };
199
+ }
200
+
201
+ /**
202
+ * Freezes a raised scene or world actor in near LOD at the requested daylight hour and extracts
203
+ * its world bounding box, head bone position (when rigged), and facing yaw. Passed to `page.evaluate`.
204
+ *
205
+ * @param {{ debug: string, actorId: string, hour: number | null }} arg
206
+ */
207
+ function settleActorInPage({ debug, actorId, hour }) {
208
+ const app = window[debug];
209
+ const a = app.actors?.[actorId];
210
+ if (!a?.group) return null;
211
+ const { THREE } = app;
212
+ if (app.director) app.director.paused = true;
213
+ app.env.flow = false;
214
+ if (Number.isFinite(hour)) {
215
+ // Active scenes lock the sky through env.override; clear it so the requested daylight hour takes effect.
216
+ app.env.override = -1;
217
+ app.env.ovTarget = -1;
218
+ app.env.goal = -1;
219
+ app.env.time = hour;
220
+ }
221
+ app.holdQuality?.(true);
222
+ app.state.mode = 'inspect';
223
+ app.state.debug = false;
224
+ app.state.measuring = true;
225
+ if (typeof app.step === 'function') {
226
+ app.step(0.05);
227
+ app.step(0.05);
228
+ }
229
+ if (a.hi) a.hi.visible = true;
230
+ if (a.lo) a.lo.visible = false;
231
+ a.group.visible = true;
232
+ a.group.updateMatrixWorld(true);
233
+
234
+ const box = new THREE.Box3().setFromObject(a.group);
235
+ const height = Math.max(0.12, box.max.y - box.min.y);
236
+ const length = Math.max(box.max.x - box.min.x, box.max.z - box.min.z);
237
+ const yaw = Number.isFinite(a.group.rotation?.y) ? a.group.rotation.y : a.yaw || 0;
238
+ let head = null;
239
+ // Quadruped head bone is index 5 (motion/quadruped.js BONE.head); read its exact world position when present.
240
+ const headBone = a.rig?.bones?.[5];
241
+ if (headBone) {
242
+ const v = new THREE.Vector3();
243
+ headBone.getWorldPosition(v);
244
+ head = [v.x, v.y, v.z];
245
+ }
246
+ const sun = app.env?.sunDir ? [app.env.sunDir.x, app.env.sunDir.y, app.env.sunDir.z] : null;
247
+ return { origin: [a.group.position.x, a.group.position.y, a.group.position.z], minY: box.min.y, height, length, yaw, head, sun };
248
+ }
249
+
250
+ /**
251
+ * Positions the camera for one close-up frame and draws twice so TAA/exposure settle while frozen.
252
+ * Passed to `page.evaluate`.
253
+ *
254
+ * @param {{ debug: string, pos: number[], aim: number[], fov: number }} arg
255
+ */
256
+ function poseCameraAndDrawInPage({ debug, pos, aim, fov }) {
257
+ const app = window[debug];
258
+ app.state.mode = 'inspect';
259
+ app.camera.fov = fov;
260
+ app.camera.updateProjectionMatrix();
261
+ app.camera.position.set(pos[0], pos[1], pos[2]);
262
+ app.camera.lookAt(aim[0], aim[1], aim[2]);
263
+ app.camera.updateMatrixWorld(true);
264
+ if (typeof app.draw === 'function') {
265
+ app.draw();
266
+ app.draw();
267
+ }
268
+ }
269
+
270
+ async function playSceneToBeat(page, driver, id, targetAt) {
271
+ await page.evaluate(readyPageForSceneInPage, { debug: driver.debug, keepHud: false, clearMeasuring: true });
272
+ await page.evaluate(startSceneInPage, { debug: driver.debug, id });
273
+ if (!(await waitSceneReady(page, driver.debug))) throw new Error(`Scene ${id} failed to prepare`);
274
+ await page.evaluate(seekSceneInPage, { debug: driver.debug, targetSeconds: targetAt, settleSeconds: 0.5, flushMs: 80 });
275
+ await page.waitForFunction(
276
+ ([d, t]) => {
277
+ const dir = window[d].director;
278
+ return !dir.ev || dir.ending || dir.t >= t;
279
+ },
280
+ [driver.debug, targetAt],
281
+ { timeout: 60000 },
282
+ );
283
+ }
284
+
285
+ async function captureTargetViews(page, driver, target, { stem, views, headFocus = true, zoom = 1, tiles = null }) {
286
+ const framed = { ...target, headFocus, zoom };
287
+ const files = [];
288
+ for (const view of views) {
289
+ const shot = frameBeastView(framed, view, target.sun);
290
+ await page.evaluate(poseCameraAndDrawInPage, { debug: driver.debug, ...shot });
291
+ await page.waitForTimeout(120);
292
+ const filename = `${stem}-${view}.jpg`;
293
+ const filePath = path.join(driver.OUT, filename);
294
+ const buf = await page.screenshot({ path: filePath, type: 'jpeg', quality: 90 });
295
+ console.log('saved', filename, JSON.stringify({ view, height: +target.height.toFixed(2) }));
296
+ files.push(filePath);
297
+ if (tiles) tiles.push({ image: buf.toString('base64'), label: `${stem} · ${view}` });
298
+ }
299
+ return files;
300
+ }
301
+
302
+ /**
303
+ * Runs close-up animal inspections for configured kind specs and/or an explicit scene beat.
304
+ *
305
+ * @param {object} driver Page driver from `createPageDriver`.
306
+ * @param {object} config
307
+ * @param {Record<string, object>} config.catalog World-specific animal kind presets (`herd` or `scene`).
308
+ * @param {string[]} [config.defaultKinds] Kinds captured when none are passed on the CLI.
309
+ * @param {(scene: object) => string} [config.routeForScene] Maps a scene catalog entry to its route address.
310
+ * @param {string[]} [config.argv=process.argv.slice(2)] CLI arguments.
311
+ */
312
+ async function runBeastsNear(
313
+ driver,
314
+ { catalog, defaultKinds = Object.keys(catalog), routeForScene = () => '', argv = process.argv.slice(2) },
315
+ ) {
316
+ const opts = parseBeastsNearArgs(argv);
317
+ if (opts.list) {
318
+ console.log('Available kinds:', Object.keys(catalog).join(', '));
319
+ return [];
320
+ }
321
+ fs.mkdirSync(driver.OUT, { recursive: true });
322
+ const browser = await driver.chromium.launch({ executablePath: driver.shell, ...driver.GPU });
323
+ const saved = [];
324
+ const tiles = opts.sheet ? [] : null;
325
+ try {
326
+ const ctx = await browser.newContext({ viewport: { width: opts.width, height: opts.height } });
327
+ await driver.applyStorage(ctx, { quality: 'high', muted: '1' });
328
+ const openPage = async address => {
329
+ const page = await ctx.newPage();
330
+ page.on('pageerror', e => console.log('PAGE ERROR', e.message.slice(0, 300)));
331
+ page.on('console', m => m.type() === 'error' && console.log('CONSOLE', m.text().slice(0, 300)));
332
+ await driver.enter(page, driver.routeUrl(address), { titledMs: 180000 });
333
+ await page.waitForTimeout(1200);
334
+ await page.addStyleTag({ content: `body > *:not(${driver.canvasSelector || '#c'}):not(canvas) { display: none !important; }` });
335
+ return page;
336
+ };
337
+
338
+ if (opts.scene) {
339
+ let page = await openPage('');
340
+ const meta = await page.evaluate(
341
+ ([d, id]) => {
342
+ const ev = window[d].CONFIG.events.find(e => e.id === id || e.title === id);
343
+ return ev ? { id: ev.id, book: ev.book || 1, space: ev.space, dur: ev.dur, cast: Object.keys(ev.cast || {}) } : null;
344
+ },
345
+ [driver.debug, opts.scene],
346
+ );
347
+ if (!meta) throw new Error(`Unknown scene id: ${opts.scene}`);
348
+ const address = routeForScene(meta);
349
+ if (address) {
350
+ await page.close();
351
+ page = await openPage(address);
352
+ }
353
+ const targetAt = Number.isFinite(opts.at) ? opts.at : Math.min(10, (meta.dur || 20) * 0.35);
354
+ await playSceneToBeat(page, driver, meta.id, targetAt);
355
+ await page.evaluate(
356
+ ([d, hour, explicit]) => {
357
+ const app = window[d];
358
+ app.director.paused = true;
359
+ app.state.measuring = true;
360
+ app.env.flow = false;
361
+ if (explicit) {
362
+ app.env.override = -1;
363
+ app.env.ovTarget = -1;
364
+ app.env.goal = -1;
365
+ app.env.time = hour;
366
+ if (typeof app.step === 'function') app.step(0.05);
367
+ }
368
+ if (typeof app.draw === 'function') {
369
+ app.draw();
370
+ app.draw();
371
+ }
372
+ },
373
+ [driver.debug, opts.hour, opts.hourExplicit],
374
+ );
375
+ const beatName = `${opts.prefix}-scene-${slugify(meta.id)}-${Math.round(targetAt)}s.jpg`;
376
+ const beatPath = path.join(driver.OUT, beatName);
377
+ const beatBuf = await page.screenshot({ path: beatPath, type: 'jpeg', quality: 90 });
378
+ console.log('saved', beatName);
379
+ saved.push(beatPath);
380
+ if (tiles) tiles.push({ image: beatBuf.toString('base64'), label: `${meta.id} @ ${targetAt}s` });
381
+
382
+ if (!opts.beatOnly) {
383
+ const actorId =
384
+ opts.actor ||
385
+ (await page.evaluate(
386
+ ([d, castIds]) => {
387
+ const actors = window[d].actors || {};
388
+ return castIds.find(id => actors[id]?.active && actors[id]?.def?.look?.kind === 'hound') || '';
389
+ },
390
+ [driver.debug, meta.cast],
391
+ ));
392
+ if (actorId) {
393
+ const target = await page.evaluate(settleActorInPage, {
394
+ debug: driver.debug,
395
+ actorId,
396
+ hour: opts.hourExplicit ? opts.hour : null,
397
+ });
398
+ if (target) {
399
+ saved.push(
400
+ ...(await captureTargetViews(page, driver, target, {
401
+ stem: `${opts.prefix}-${slugify(meta.id)}-${slugify(actorId)}`,
402
+ views: opts.views,
403
+ headFocus: true,
404
+ tiles,
405
+ })),
406
+ );
407
+ }
408
+ }
409
+ }
410
+ await page.close();
411
+ }
412
+
413
+ const selected = opts.kinds.length ? (opts.kinds.includes('all') ? Object.keys(catalog) : opts.kinds) : opts.scene ? [] : defaultKinds;
414
+ for (const kind of selected) {
415
+ const spec = catalog[kind];
416
+ if (!spec) throw new Error(`Unknown kind '${kind}'. Available: ${Object.keys(catalog).join(', ')}`);
417
+ const page = await openPage(spec.address || '');
418
+ try {
419
+ let target = null;
420
+ if (spec.type === 'herd') {
421
+ const found = await page.evaluate(locateHerdBeastInPage, {
422
+ debug: driver.debug,
423
+ build: spec.build,
424
+ coat: spec.coat || '',
425
+ member: spec.member || 0,
426
+ });
427
+ if (!found) throw new Error(`No '${spec.build}' herd found at '${spec.address || '/'}'`);
428
+ await page.waitForFunction(
429
+ ([d, ci]) => Boolean(window[d].crowds?.[ci]?.herd?.all?.some(m => m.parent)),
430
+ [driver.debug, found.crowdIndex],
431
+ { timeout: 60000 },
432
+ );
433
+ await page.waitForTimeout(300);
434
+ target = await page.evaluate(settleHerdBeastInPage, {
435
+ debug: driver.debug,
436
+ crowdIndex: found.crowdIndex,
437
+ memberIndex: found.memberIndex,
438
+ hour: opts.hour,
439
+ });
440
+ } else if (spec.type === 'scene') {
441
+ if (spec.lookOverride) {
442
+ await page.evaluate(
443
+ ([d, actorId, override]) => {
444
+ const a = window[d].actors?.[actorId];
445
+ if (a && !a.built && a.def?.look) a.def = { ...a.def, look: { ...a.def.look, ...override } };
446
+ },
447
+ [driver.debug, spec.actor, spec.lookOverride],
448
+ );
449
+ }
450
+ await playSceneToBeat(page, driver, spec.scene, spec.at);
451
+ target = await page.evaluate(settleActorInPage, { debug: driver.debug, actorId: spec.actor, hour: opts.hour });
452
+ } else {
453
+ throw new Error(`Unsupported kind spec type '${spec.type}' for '${kind}'`);
454
+ }
455
+ if (!target) throw new Error(`Failed to frame '${kind}'`);
456
+ saved.push(
457
+ ...(await captureTargetViews(page, driver, target, {
458
+ stem: `${opts.prefix}-${slugify(kind)}`,
459
+ views: opts.views,
460
+ headFocus: spec.headFocus !== false,
461
+ zoom: spec.zoom || 1,
462
+ tiles,
463
+ })),
464
+ );
465
+ } finally {
466
+ await page.close();
467
+ }
468
+ }
469
+
470
+ if (tiles && tiles.length) {
471
+ const sheetName = `${opts.prefix}-sheet.jpg`;
472
+ const sheetPath = path.join(driver.OUT, sheetName);
473
+ await writeContactSheet(browser, tiles, sheetPath, {
474
+ columns: Math.min(3, Math.max(1, opts.views.length)),
475
+ cellWidth: 640,
476
+ cellHeight: 480,
477
+ });
478
+ console.log('saved', sheetName);
479
+ saved.push(sheetPath);
480
+ }
481
+ } finally {
482
+ await driver.closeBrowser(browser);
483
+ }
484
+ return saved;
485
+ }
486
+
487
+ module.exports = {
488
+ DEFAULT_FOV,
489
+ DEFAULT_HOUR,
490
+ DEFAULT_VIEWS,
491
+ frameBeastView,
492
+ locateHerdBeastInPage,
493
+ parseBeastsNearArgs,
494
+ poseCameraAndDrawInPage,
495
+ runBeastsNear,
496
+ settleActorInPage,
497
+ settleHerdBeastInPage,
498
+ };
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+ const assert = require('node:assert/strict');
3
+ const test = require('node:test');
4
+ const { frameBeastView, locateHerdBeastInPage, parseBeastsNearArgs, poseCameraAndDrawInPage } = require('./beasts-near.cjs');
5
+
6
+ test('parseBeastsNearArgs parses kinds, scene beat options, and flags cleanly', () => {
7
+ const parsed = parseBeastsNearArgs([
8
+ 'wolf',
9
+ 'dog',
10
+ '--scene',
11
+ 'chase',
12
+ '--at',
13
+ '14.5',
14
+ '--actor=lead',
15
+ '--hour=0.38',
16
+ '--prefix=before',
17
+ '--width=1000',
18
+ '--height=750',
19
+ '--views=side,front',
20
+ '--sheet',
21
+ ]);
22
+ assert.deepEqual(parsed.kinds, ['wolf', 'dog']);
23
+ assert.equal(parsed.scene, 'chase');
24
+ assert.equal(parsed.at, 14.5);
25
+ assert.equal(parsed.actor, 'lead');
26
+ assert.equal(parsed.hour, 0.38);
27
+ assert.equal(parsed.hourExplicit, true);
28
+ assert.equal(parsed.prefix, 'before');
29
+ assert.equal(parsed.width, 1000);
30
+ assert.equal(parsed.height, 750);
31
+ assert.deepEqual(parsed.views, ['side', 'front']);
32
+ assert.equal(parsed.sheet, true);
33
+ assert.throws(() => parseBeastsNearArgs(['--bogus']), /Unknown option/);
34
+ assert.throws(() => parseBeastsNearArgs(['--scene']), /Missing value/);
35
+ });
36
+
37
+ test('frameBeastView places eye-height side, front, and three-quarter cameras on the sunlit side', () => {
38
+ const target = { origin: [10, 0, 20], minY: 0, height: 0.9, length: 1.2, yaw: 0, head: [10, 0.72, 20.4], headFocus: true };
39
+ const sunRight = [0.8, 0.5, 0.2];
40
+ const sunLeft = [-0.8, 0.5, 0.2];
41
+
42
+ const sideR = frameBeastView(target, 'side', sunRight);
43
+ const sideL = frameBeastView(target, 'side', sunLeft);
44
+ assert.ok(sideR.pos[0] > target.origin[0] + 0.5, 'side view picks +x when sun is on +x');
45
+ assert.ok(sideL.pos[0] < target.origin[0] - 0.5, 'side view flips to -x when sun is on -x');
46
+ assert.ok(Math.abs(sideR.pos[1] - sideR.aim[1]) < 0.1, 'side view stays at eye height');
47
+
48
+ const front = frameBeastView(target, 'front', sunRight);
49
+ assert.ok(front.pos[2] > target.head[2] + 0.5, 'front view stands ahead of the nose');
50
+
51
+ const three = frameBeastView(target, 'three', sunRight);
52
+ assert.ok(
53
+ three.pos[0] > target.head[0] + 0.3 && three.pos[2] > target.head[2] + 0.3,
54
+ 'three-quarter view stands ahead and to the sunlit side',
55
+ );
56
+ });
57
+
58
+ test('locateHerdBeastInPage and poseCameraAndDrawInPage talk strictly through window[debug]', () => {
59
+ let placed = null;
60
+ let drawn = 0;
61
+ const camera = {
62
+ fov: 50,
63
+ position: {
64
+ x: 0,
65
+ y: 0,
66
+ z: 0,
67
+ set(x, y, z) {
68
+ this.x = x;
69
+ this.y = y;
70
+ this.z = z;
71
+ },
72
+ },
73
+ lookAt() {},
74
+ updateProjectionMatrix() {},
75
+ updateMatrixWorld() {},
76
+ };
77
+ globalThis.window = {
78
+ APP: {
79
+ space: { id: 'valley', ground: () => 2 },
80
+ state: { fly: false, mode: 'play' },
81
+ camera,
82
+ crowds: [
83
+ { space: 'valley', cx: 5, cz: 8, beasts: { input: { build: 'dog', coat: 'cur' } }, list: [{ gx: 6, gz: 9 }] },
84
+ { space: 'other', cx: 0, cz: 0, beasts: { input: { build: 'dog', coat: 'cur' } }, list: [{ gx: 0, gz: 0 }] },
85
+ ],
86
+ placePlayer(x, z, yaw) {
87
+ placed = { x, z, yaw };
88
+ },
89
+ draw() {
90
+ drawn++;
91
+ },
92
+ },
93
+ };
94
+ try {
95
+ const found = locateHerdBeastInPage({ debug: 'APP', build: 'dog', coat: 'cur' });
96
+ assert.deepEqual(found, { crowdIndex: 0, memberIndex: 0, x: 6, z: 9, total: 1 });
97
+ assert.ok(placed && Math.hypot(placed.x - 6, placed.z - 9) > 2);
98
+
99
+ poseCameraAndDrawInPage({ debug: 'APP', pos: [1, 2, 3], aim: [0, 1, 0], fov: 34 });
100
+ assert.equal(camera.fov, 34);
101
+ assert.equal(drawn, 2);
102
+ } finally {
103
+ delete globalThis.window;
104
+ }
105
+ });