roamwright 0.61.2 → 0.61.4

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.
package/index.js CHANGED
@@ -63,6 +63,7 @@ export { createIrrigatedFieldSurface, IRRIGATED_FIELD_KIND, IRRIGATED_FIELD_SURF
63
63
  export { DRYSTONE_WALL, FIELD_STONE, drystoneStone, planDrystoneWall } from './geometry/drystone-wall.js';
64
64
  export { FARM_BOUNDARIES, planFieldBoundaries } from './geometry/farm-boundaries.js';
65
65
  export { meshFarmCells, scatterFarmLots } from './rendering/farm-cells.js';
66
+ export { DEFAULT_LIVESTOCK_CASTS, createLivestockCache } from './rendering/farm-livestock.js';
66
67
  export { DEFAULT_FARM_HERDS, FARM_LIFE, herdPlaces, parcelPlaces, planFarmLife, ploughSite } from './geometry/farm-life.js';
67
68
  export { STOOK, createStook } from './geometry/prop-stook.js';
68
69
  export { PLOUGH, ploughGear } from './geometry/prop-plough.js';
@@ -169,7 +170,18 @@ export { planCrewAtStations, planTownsfolk } from './motion/crowd-town.js';
169
170
  export { driveToWater, trekToWater, waterNear } from './motion/crowd-water.js';
170
171
  export { createCrowdVisibility } from './rendering/crowd-visibility.js';
171
172
  export { createHerdRenderer, createHerdSkins } from './rendering/crowd-herd.js';
172
- export { createCrowdBatches } from './rendering/crowd-batches.js';
173
+ export {
174
+ DEFAULT_BEARERS,
175
+ DEFAULT_BY_ROLE,
176
+ DEFAULT_CROWD_HAIR,
177
+ DEFAULT_CROWD_LOOKS,
178
+ DEFAULT_CROWD_SKINS,
179
+ DEFAULT_SOLDIER_BEARER,
180
+ DEFAULT_UNIFORMS,
181
+ bakeCrowdWalks,
182
+ createCrowdBatches,
183
+ createLookPicker,
184
+ } from './rendering/crowd-batches.js';
173
185
  export { createCrowdUpdater, registerCrowd } from './rendering/crowd-update.js';
174
186
  export { createCrowdSystem } from './rendering/crowd-system.js';
175
187
 
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A limb of two bones in one plane: a leg from hip to ankle, an arm from shoulder to hand. For an end point (forward, up) from
3
+ * the root joint, it finds how far the first bone swings from hanging straight down and how far the middle joint bends.
4
+ * @module
5
+ */
6
+ import { clamp } from './scalar.js';
7
+
8
+ /**
9
+ * Solves a two-bone limb in its plane, writing [swing, bend] into `out`.
10
+ *
11
+ * The swing is the first bone's angle from straight down, positive toward `forward`; the bend is the middle joint's, 0 when
12
+ * the limb is straight. A middle joint that bends backward (an elbow: `bendsForward` false) leaves the first bone pointing
13
+ * ahead of the target; one that bends forward (a knee) leaves it behind. The reach is clamped to `[nearest, farthest]`, so a
14
+ * target out of reach gets the straightest limb pointing at it, and one too near gets the tightest bend allowed.
15
+ * @param {number[]} out - Written: [swing, bend], radians.
16
+ * @param {number} first - The first bone's length (thigh, upper arm).
17
+ * @param {number} second - The second bone's length, to the end point (shin to the ankle, forearm to the hand).
18
+ * @param {number} forward - The end point ahead of the root joint, in the bones' units.
19
+ * @param {number} up - The end point above the root joint (negative below).
20
+ * @param {number} nearest - The shortest reach allowed.
21
+ * @param {number} farthest - The longest reach allowed (at most `first + second`).
22
+ * @param {boolean} [bendsForward=false] - True for a joint that bends forward, like a knee.
23
+ * @returns {number[]} `out`.
24
+ */
25
+ export function solveTwoBone(out, first, second, forward, up, nearest, farthest, bendsForward = false) {
26
+ const reach = clamp(Math.sqrt(forward * forward + up * up), nearest, farthest),
27
+ bend = Math.acos(clamp((reach * reach - first * first - second * second) / (2 * first * second), -1, 1)),
28
+ lag = Math.atan2(second * Math.sin(bend), first + second * Math.cos(bend));
29
+ out[0] = bendsForward ? Math.atan2(forward, -up) + lag : Math.atan2(forward, -up) - lag;
30
+ out[1] = bend;
31
+ return out;
32
+ }
@@ -1,12 +1,11 @@
1
- import { clamp, lerp, sstep } from '../math/scalar.js';
1
+ import { lerp, sstep } from '../math/scalar.js';
2
+ import { solveTwoBone } from '../math/two-bone.js';
2
3
 
3
4
  // Two-bone leg from hip to ankle in the fore-and-aft plane: for an ankle at (forward, up) from the hip, the thigh's and the
4
5
  // knee's rotation, written into out.
5
6
  export function solveBipedLeg(out, rig, forward, up, minReach = Math.abs(rig.thigh - rig.shin)) {
6
- const reach = clamp(Math.sqrt(forward * forward + up * up), minReach, rig.thigh + rig.shin - 1e-4),
7
- bend = Math.acos(clamp((reach * reach - rig.thigh * rig.thigh - rig.shin * rig.shin) / (2 * rig.thigh * rig.shin), -1, 1));
8
- out[0] = -(Math.atan2(forward, -up) + Math.atan2(rig.shin * Math.sin(bend), rig.thigh + rig.shin * Math.cos(bend)));
9
- out[1] = bend;
7
+ solveTwoBone(out, rig.thigh, rig.shin, forward, up, minReach, rig.thigh + rig.shin - 1e-4, true);
8
+ out[0] = -out[0]; // the thigh's rotation turns it back for a positive angle
10
9
  }
11
10
  // The pitch of a foot's sole (toes down is more) at share u of its stride: it lands on its heel with the toes up by `strike`,
12
11
  // lies flat while the body passes over it, rolls up onto its toes until the heel has risen by `push`, and in the air comes
@@ -74,23 +74,21 @@ export function crowdMotion() {
74
74
 
75
75
  /**
76
76
  * Creates a crowd poser bound to a world's seeded hash, kind-to-bearing mapper, busy-focus predicate,
77
- * and optional default pose-texture buffer provider.
77
+ * and well crank dimensions. Callers pass the target pose-texture buffer directly on each call.
78
78
  *
79
79
  * @param {object} [options]
80
80
  * @param {(x: number, y: number, salt?: number) => number} [options.hash] Seeded 2D hash for combat rhythm variation.
81
81
  * @param {(kind: string, focus: string|undefined) => import('./crowd-attention.js').CrowdBearing} [options.bearing] Maps crowd kind + focus to engine bearing.
82
82
  * @param {(focus: string|undefined) => boolean} [options.busy] Returns true for focuses that ignore stage/alarm attention.
83
- * @param {() => Float32Array|null} [options.getPoseData] Optional default target buffer when `data` is omitted.
84
83
  * @param {number} [options.wellStand=WELL_STAND] Distance from well crank axle (metres).
85
84
  * @param {number} [options.wellArm=WELL_ARM] Well crank arm radius (metres).
86
85
  * @param {number} [options.wellCrank=WELL_CRANK] Well crank axle height (metres).
87
- * @returns {(g: object, variant: object, row: number, motion: ReturnType<typeof crowdMotion>, data?: Float32Array) => void}
86
+ * @returns {(g: object, variant: object, row: number, motion: ReturnType<typeof crowdMotion>, data: Float32Array) => void}
88
87
  */
89
88
  export function createCrowdPoser({
90
89
  hash = defaultHash,
91
90
  bearing = defaultBearing,
92
91
  busy = defaultBusy,
93
- getPoseData = null,
94
92
  wellStand = WELL_STAND,
95
93
  wellArm = WELL_ARM,
96
94
  wellCrank = WELL_CRANK,
@@ -167,7 +165,7 @@ export function createCrowdPoser({
167
165
  }
168
166
  }
169
167
 
170
- return function crowdPose(g, variant, row, motion, data = getPoseData?.()) {
168
+ return function crowdPose(g, variant, row, motion, data) {
171
169
  const { t, phase, speed, ground, focus } = motion,
172
170
  { head, lidA, cloak, rig } = variant,
173
171
  b = rig.bones;
@@ -232,7 +230,7 @@ export function createCrowdPoser({
232
230
  }
233
231
  }
234
232
  if (cloak) cloak.rotation.set(-0.07 * walking - 0.05 * eased, 0.035 * rest, 0.04 * over);
235
- if (focus === 'crank' && crankPose(b, head, t, g.ph, wellStand, wellArm, wellCrank) && cloak) cloak.rotation.set(0.15, 0, 0);
233
+ if (focus === 'crank' && crankPose(b, head, t, g.ph, wellStand, wellArm, wellCrank, g.s) && cloak) cloak.rotation.set(0.15, 0, 0);
236
234
  if (focus === 'sit') {
237
235
  const lean = 0.16 + 0.03 * rest;
238
236
  b[0].position.set(0, -0.47, 0.03);
@@ -5,9 +5,10 @@
5
5
  * @module
6
6
  */
7
7
 
8
- import { clamp, lerp, sstep, TAU } from '../math/scalar.js';
8
+ import { lerp, sstep, TAU } from '../math/scalar.js';
9
9
  import { createHash } from '../math/random.js';
10
- import { ANKLE, BOOT_HEEL, BOOT_TOE, HIPS, SHANK, THIGH } from './figure-bones.js';
10
+ import { solveTwoBone } from '../math/two-bone.js';
11
+ import { ANKLE, BOOT_HEEL, BOOT_TOE, FOREARM, HIPS, PALM, SHANK, SHOULDERS, THIGH, UPPER_ARM } from './figure-bones.js';
11
12
  import { solveBipedLeg } from './biped-leg.js';
12
13
  import { CROWD_BONES } from '../geometry/crowd-weld.js';
13
14
 
@@ -49,9 +50,9 @@ export function windlass(t, phase) {
49
50
  return wellState;
50
51
  }
51
52
 
52
- const SHOULDER_Y = 1.36;
53
- const UPPER_ARM = 0.3;
54
- const FOREARM = 0.3;
53
+ // The arm as the crank solves it, in figure units: the upper arm, and the forearm to the middle of the palm on the handle.
54
+ const HAND_ON_HANDLE = FOREARM + PALM,
55
+ crankReach = [0, 0];
55
56
 
56
57
  /**
57
58
  * Solves a two-bone reach placing both hands on a rotating well crank handle in front of the figure.
@@ -63,22 +64,23 @@ const FOREARM = 0.3;
63
64
  * @param {number} [wellStand=WELL_STAND] Distance from crank axle (metres).
64
65
  * @param {number} [wellArm=WELL_ARM] Crank radius (metres).
65
66
  * @param {number} [wellCrank=WELL_CRANK] Crank axle height (metres).
67
+ * @param {number} [scale=1] The figure's size (its bones' figure units are metres at 1), so a smaller figure reaches up more.
66
68
  * @returns {boolean} True while actively turning the crank.
67
69
  */
68
- export function crankPose(b, head, t, phase, wellStand = WELL_STAND, wellArm = WELL_ARM, wellCrank = WELL_CRANK) {
70
+ export function crankPose(b, head, t, phase, wellStand = WELL_STAND, wellArm = WELL_ARM, wellCrank = WELL_CRANK, scale = 1) {
69
71
  const w = windlass(t, phase);
70
72
  if (!w.turning) return false;
71
- const forward = wellStand - wellArm * Math.cos(w.angle),
72
- rise = wellCrank + wellArm * Math.sin(w.angle) - SHOULDER_Y,
73
- reach = clamp(Math.hypot(forward, rise), 0.15, UPPER_ARM + FOREARM - 0.01),
74
- bend = Math.PI - Math.acos(clamp((UPPER_ARM ** 2 + FOREARM ** 2 - reach ** 2) / (2 * UPPER_ARM * FOREARM), -1, 1)),
75
- toward = Math.atan2(forward, -rise),
76
- lag = Math.atan2(FOREARM * Math.sin(bend), UPPER_ARM + FOREARM * Math.cos(bend));
73
+ // the handle from the shoulder, in figure units of this figure's size
74
+ const forward = (wellStand - wellArm * Math.cos(w.angle)) / scale,
75
+ rise = (wellCrank + wellArm * Math.sin(w.angle)) / scale - SHOULDERS;
76
+ solveTwoBone(crankReach, UPPER_ARM, HAND_ON_HANDLE, forward, rise, 0.15, UPPER_ARM + HAND_ON_HANDLE - 0.01);
77
+ const swing = crankReach[0],
78
+ bend = crankReach[1];
77
79
  b[0].rotation.x = 0.12 + 0.06 * Math.cos(w.angle);
78
80
  head.rotation.x = 0.2;
79
81
  for (let i = 0; i < 2; i++) {
80
82
  const s = i ? 1 : -1;
81
- b[2 + i * 2].rotation.set(-(toward - lag), -s * 0.05, -s * 0.12);
83
+ b[2 + i * 2].rotation.set(-swing, -s * 0.05, -s * 0.12);
82
84
  b[3 + i * 2].rotation.x = -bend;
83
85
  b[13 + i].rotation.set(-0.1, 0, 0);
84
86
  }
@@ -59,6 +59,7 @@ const SHOULDERS = 1.43,
59
59
  BOOT_TOE = 0.206,
60
60
  UPPER_ARM = 0.33, // the elbow below the shoulder, the wrist below the elbow,
61
61
  FOREARM = 0.315,
62
+ PALM = 0.055, // the middle of the palm below the wrist (where a hand rests on what it holds)
62
63
  GRIP = 0.09; // and the bone of what a hand holds below the wrist
63
64
 
64
65
  export {
@@ -102,6 +103,7 @@ export {
102
103
  MOUTH_R,
103
104
  OPEN_L,
104
105
  OPEN_R,
106
+ PALM,
105
107
  PELVIS,
106
108
  ROOT,
107
109
  SHANK,
@@ -8,7 +8,15 @@
8
8
  */
9
9
  import { clamp, lerp } from '../math/scalar.js';
10
10
  import { restingPostureDrift, solveCrawlSlope, solveRecumbentSlope } from './biped-posture.js';
11
- import { HIPS as HIP_HEIGHT, SHOULDERS as SHOULDERS_ABOVE_HIPS, THIGH, UPPER_ARM } from './figure-bones.js';
11
+ import { solveTwoBone } from '../math/two-bone.js';
12
+ import {
13
+ FOREARM as WRIST_BELOW_ELBOW,
14
+ HIPS as HIP_HEIGHT,
15
+ PALM,
16
+ SHOULDERS as SHOULDERS_ABOVE_HIPS,
17
+ THIGH,
18
+ UPPER_ARM,
19
+ } from './figure-bones.js';
12
20
  import { HIPS, LIE, THIGH_L, THIGH_R, TRUNK, editable } from './figure-pose-table.js';
13
21
 
14
22
  const KNEE_L = 0,
@@ -21,9 +29,9 @@ const KNEE_L = 0,
21
29
  TABLE_R = 7;
22
30
  // The figure's proportions, in figure units, as the seat solves them: the thigh, how high the hips stand, how far above them
23
31
  // the shoulders are and the upper arm are the bones' (figure-bones.js); the shin here is the knee to the sole (the bones'
24
- // shank and the ankle's height), and the forearm the elbow to the middle of the hand (the bones' forearm ends at the wrist).
32
+ // shank and the ankle's height), and the forearm the elbow to the middle of the hand (the bones' forearm and the palm).
25
33
  const SHIN = 0.474,
26
- FOREARM = 0.37;
34
+ FOREARM = WRIST_BELOW_ELBOW + PALM;
27
35
  const FLOOR_SEAT = 0.44, // the height of a seat where none is given, and of the hip joint above what it sits on
28
36
  HIP_ABOVE_SEAT = 0.092,
29
37
  KNEES_APART = 0.24, // how differently one person's knees splay from another's
@@ -176,22 +184,7 @@ function createFigureSeat({ ground = FLAT, seatHere = ANY_SEAT } = {}) {
176
184
  const reach = [0, 0],
177
185
  FULL_REACH = 0.995, // a target further than this share of the arm's length is brought in to it
178
186
  CLOSEST = 0.14; // and one nearer the shoulder than this is taken as this far
179
- function armIK(forward, up) {
180
- const upper = UPPER_ARM,
181
- fore = FOREARM;
182
- let distance = Math.hypot(forward, up);
183
- const most = (upper + fore) * FULL_REACH;
184
- if (distance > most) {
185
- forward *= most / distance;
186
- up *= most / distance;
187
- distance = most;
188
- }
189
- if (distance < CLOSEST) distance = CLOSEST;
190
- const bend = Math.acos(clamp((distance * distance - upper * upper - fore * fore) / (2 * upper * fore), -1, 1));
191
- reach[0] = Math.atan2(forward, -up) - Math.atan2(fore * Math.sin(bend), upper + fore * Math.cos(bend));
192
- reach[1] = bend;
193
- return reach;
194
- }
187
+ const armIK = (forward, up) => solveTwoBone(reach, UPPER_ARM, FOREARM, forward, up, CLOSEST, (UPPER_ARM + FOREARM) * FULL_REACH);
195
188
  // A seated figure's arms reach for where its hands rest (seatTarget), as far as it is seated.
196
189
  function seatedArms(a, w, lean) {
197
190
  const joints = a.joints,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roamwright",
3
- "version": "0.61.2",
3
+ "version": "0.61.4",
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",
@@ -122,21 +122,38 @@ export function bakeCrowdWalks(geos, variant, crowdPose) {
122
122
  });
123
123
  }
124
124
 
125
- function defaultPickLook(group, member, index, pick) {
126
- const choices =
127
- DEFAULT_UNIFORMS[group.kind] ||
128
- (group.kind === 'camp' || group.kind === 'guard'
129
- ? [6]
130
- : group.kind === 'sappers'
131
- ? [14]
132
- : group.kind === 'plain'
133
- ? [7]
134
- : group.festival
135
- ? [8, 8, 0, 5]
136
- : group.kind === 'mob'
137
- ? [0, 1, 2, 3, 4, 5]
138
- : DEFAULT_BY_ROLE[member.role] || [0, 2, 3, 5]);
139
- return member.held ? (DEFAULT_BEARERS[group.kind] ?? DEFAULT_SOLDIER_BEARER) : pick(index, 38, choices);
125
+ /**
126
+ * Creates a crowd look picker from generic or world-extended uniform, bearer, and role tables.
127
+ *
128
+ * @param {object} [options]
129
+ * @param {Record<string, number[]>} [options.uniforms=DEFAULT_UNIFORMS] Uniformed look index lists keyed by crowd kind.
130
+ * @param {Record<string, number>} [options.bearers=DEFAULT_BEARERS] Bearer look indices keyed by crowd kind.
131
+ * @param {number} [options.soldierBearer=DEFAULT_SOLDIER_BEARER] Fallback bearer look index for kinds absent from `bearers`.
132
+ * @param {Record<string, number[]>} [options.byRole=DEFAULT_BY_ROLE] Civilian look index pools keyed by member role.
133
+ * @returns {(group: object, member: object, index: number, pick: Function) => number}
134
+ */
135
+ export function createLookPicker({
136
+ uniforms = DEFAULT_UNIFORMS,
137
+ bearers = DEFAULT_BEARERS,
138
+ soldierBearer = DEFAULT_SOLDIER_BEARER,
139
+ byRole = DEFAULT_BY_ROLE,
140
+ } = {}) {
141
+ return function pickLook(group, member, index, pick) {
142
+ const choices =
143
+ uniforms[group.kind] ||
144
+ (group.kind === 'camp' || group.kind === 'guard'
145
+ ? [6]
146
+ : group.kind === 'sappers'
147
+ ? [14]
148
+ : group.kind === 'plain'
149
+ ? [7]
150
+ : group.festival
151
+ ? [8, 8, 0, 5]
152
+ : group.kind === 'mob'
153
+ ? [0, 1, 2, 3, 4, 5]
154
+ : byRole[member.role] || [0, 2, 3, 5]);
155
+ return member.held ? (bearers[group.kind] ?? soldierBearer) : pick(index, 38, choices);
156
+ };
140
157
  }
141
158
 
142
159
  /**
@@ -153,9 +170,14 @@ function defaultPickLook(group, member, index, pick) {
153
170
  * @param {Array<[string, object]>} [config.looks=DEFAULT_CROWD_LOOKS] Look table `[kindName, figureLookSpec]`.
154
171
  * @param {number[]} [config.skins=DEFAULT_CROWD_SKINS] Default skin hex palette.
155
172
  * @param {number[]} [config.hair=DEFAULT_CROWD_HAIR] Default hair hex palette.
173
+ * @param {Record<string, { skins?: number[], hair?: number[] }>|null} [config.palettesByKind=null] Optional per-crowd-kind skin/hair palette overrides.
156
174
  * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash for look and palette picking.
157
- * @param {(group: object, member: object, index: number, pick: Function) => number} [config.pickLook] Maps a crowd member to an index in `looks`.
158
- * @param {(group: object, member: object, index: number, pick: Function) => [number, number]} [config.pickSkinHair] Returns `[skinHex, hairHex]` for a member.
175
+ * @param {Record<string, number[]>} [config.uniforms=DEFAULT_UNIFORMS] Uniformed look index lists keyed by crowd kind (used when `pickLook` is omitted).
176
+ * @param {Record<string, number>} [config.bearers=DEFAULT_BEARERS] Bearer look indices keyed by crowd kind (used when `pickLook` is omitted).
177
+ * @param {number} [config.soldierBearer=DEFAULT_SOLDIER_BEARER] Fallback bearer look index (used when `pickLook` is omitted).
178
+ * @param {Record<string, number[]>} [config.byRole=DEFAULT_BY_ROLE] Civilian look index pools keyed by member role (used when `pickLook` is omitted).
179
+ * @param {((group: object, member: object, index: number, pick: Function) => number)|null} [config.pickLook=null] Optional custom look picker overriding table-based lookup.
180
+ * @param {((group: object, member: object, index: number, pick: Function) => [number, number])|null} [config.pickSkinHair=null] Optional custom `[skinHex, hairHex]` picker overriding `palettesByKind`/`skins`/`hair`.
159
181
  * @param {(kind: string) => boolean} [config.hasFirewood=carriesFirewood] Predicate for whether a look carries firewood.
160
182
  * @param {(kind: string) => number} [config.carryBendOf] Forearm bend (radians) for left-hand carried items (`0` if none).
161
183
  */
@@ -169,12 +191,18 @@ export function createCrowdBatches({
169
191
  looks = DEFAULT_CROWD_LOOKS,
170
192
  skins = DEFAULT_CROWD_SKINS,
171
193
  hair = DEFAULT_CROWD_HAIR,
194
+ palettesByKind = null,
172
195
  hash = defaultHash,
173
- pickLook = defaultPickLook,
196
+ uniforms = DEFAULT_UNIFORMS,
197
+ bearers = DEFAULT_BEARERS,
198
+ soldierBearer = DEFAULT_SOLDIER_BEARER,
199
+ byRole = DEFAULT_BY_ROLE,
200
+ pickLook = null,
174
201
  pickSkinHair = null,
175
202
  hasFirewood = carriesFirewood,
176
203
  carryBendOf = kind => (kind === 'basket' ? -0.68 : kind === 'sack' ? -0.16 : 0),
177
204
  }) {
205
+ const resolveLook = pickLook ?? createLookPicker({ uniforms, bearers, soldierBearer, byRole });
178
206
  let poseTexture = null,
179
207
  activeBatches = null,
180
208
  warmFigure = null,
@@ -338,7 +366,7 @@ export function createCrowdBatches({
338
366
  for (const c of groups)
339
367
  for (let i = 0; i < c.list.length; i++) {
340
368
  const g = c.list[i];
341
- const look = pickLook(c, g, i, pick);
369
+ const look = resolveLook(c, g, i, pick);
342
370
  g.look = look;
343
371
  g.row = row++;
344
372
  g.lod = 0;
@@ -349,7 +377,10 @@ export function createCrowdBatches({
349
377
  sizes[look]++;
350
378
  const offset = (g.row * CROWD_POSE_WIDTH + CROWD_BONES * 3) * 4;
351
379
  g.c1.toArray(data, offset);
352
- const [skinHex, hairHex] = pickSkinHair ? pickSkinHair(c, g, i, pick) : [pick(i, 39, skins), pick(i, 40, hair)];
380
+ const kindPalette = palettesByKind?.[c.kind];
381
+ const [skinHex, hairHex] = pickSkinHair
382
+ ? pickSkinHair(c, g, i, pick)
383
+ : [pick(i, 39, kindPalette?.skins ?? skins), pick(i, 40, kindPalette?.hair ?? hair)];
353
384
  _cc.setHex(skinHex).toArray(data, offset + 4);
354
385
  _cc.setHex(hairHex).toArray(data, offset + 8);
355
386
  }
@@ -51,7 +51,12 @@ import { createFigureAssembler } from './figure-skeleton.js';
51
51
  * @param {Array<[string, object]>} [config.looks] Crowd look table forwarded to `createCrowdBatches`.
52
52
  * @param {number[]} [config.skins] Skin tone hex palette forwarded to `createCrowdBatches`.
53
53
  * @param {number[]} [config.hair] Hair tone hex palette forwarded to `createCrowdBatches`.
54
+ * @param {Record<string, { skins?: number[], hair?: number[] }>|null} [config.palettesByKind] Per-crowd-kind skin/hair overrides forwarded to `createCrowdBatches`.
54
55
  * @param {(x: number, y: number, salt?: number) => number} [config.hash] Seeded 2D hash forwarded to `createCrowdBatches` and `registerCrowd`.
56
+ * @param {Record<string, number[]>} [config.uniforms] Uniform look lists forwarded to `createCrowdBatches`.
57
+ * @param {Record<string, number>} [config.bearers] Bearer look indices forwarded to `createCrowdBatches`.
58
+ * @param {number} [config.soldierBearer] Fallback bearer look index forwarded to `createCrowdBatches`.
59
+ * @param {Record<string, number[]>} [config.byRole] Role look pools forwarded to `createCrowdBatches`.
55
60
  * @param {Function} [config.pickLook] Custom look picker forwarded to `createCrowdBatches`.
56
61
  * @param {Function|null} [config.pickSkinHair] Custom skin/hair picker forwarded to `createCrowdBatches`.
57
62
  * @param {Function} [config.hasFirewood] Firewood predicate forwarded to `createCrowdBatches`.
@@ -90,7 +95,12 @@ export function createCrowdSystem({
90
95
  looks,
91
96
  skins,
92
97
  hair,
98
+ palettesByKind,
93
99
  hash,
100
+ uniforms,
101
+ bearers,
102
+ soldierBearer,
103
+ byRole,
94
104
  pickLook,
95
105
  pickSkinHair,
96
106
  hasFirewood,
@@ -132,7 +142,12 @@ export function createCrowdSystem({
132
142
  if (looks) batchConfig.looks = looks;
133
143
  if (skins) batchConfig.skins = skins;
134
144
  if (hair) batchConfig.hair = hair;
145
+ if (palettesByKind) batchConfig.palettesByKind = palettesByKind;
135
146
  if (hash) batchConfig.hash = hash;
147
+ if (uniforms) batchConfig.uniforms = uniforms;
148
+ if (bearers) batchConfig.bearers = bearers;
149
+ if (soldierBearer !== undefined) batchConfig.soldierBearer = soldierBearer;
150
+ if (byRole) batchConfig.byRole = byRole;
136
151
  if (pickLook) batchConfig.pickLook = pickLook;
137
152
  if (pickSkinHair) batchConfig.pickSkinHair = pickSkinHair;
138
153
  if (hasFirewood) batchConfig.hasFirewood = hasFirewood;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Worker-backed geometry cache for static posed farm livestock (cattle, oxen, sheep): pre-casts
3
+ * standing and grazing near/far geometries on background workers while a land loads, hands each
4
+ * pre-built geometry out once when consumed, and falls back synchronously to `castCattle`.
5
+ * @module
6
+ */
7
+
8
+ import { geometryOf as defaultGeometryOf } from '../geometry/builder.js';
9
+ import { NO_ANIMAL_OPTIONS } from '../geometry/animal-options.js';
10
+ import { castCattle } from '../motion/animal-cattle-cast.js';
11
+
12
+ const BOTH = Object.freeze([
13
+ Object.freeze([true, false]),
14
+ Object.freeze([true, true]),
15
+ Object.freeze([false, false]),
16
+ Object.freeze([false, true]),
17
+ ]);
18
+
19
+ /**
20
+ * Default farm livestock cast plan per animal build: `[grazing, far]` pairs for cows and sheep
21
+ * (both head poses and both LOD skins) plus a standing near ox for plough teams and carts.
22
+ */
23
+ export const DEFAULT_LIVESTOCK_CASTS = Object.freeze({
24
+ cow: BOTH,
25
+ sheep: BOTH,
26
+ ox: Object.freeze([Object.freeze([false, false])]),
27
+ });
28
+
29
+ const castKey = (build, grazing, far) => `${build}:${grazing}:${far}`;
30
+
31
+ /**
32
+ * Creates a page-scoped cache for pre-cast farm livestock geometries backed by an optional worker
33
+ * pool, with synchronous fallback via `castCattle`.
34
+ *
35
+ * @param {object} [options]
36
+ * @param {import('../geometry/animal-options.js').AnimalKitOptions} [options.animals=NO_ANIMAL_OPTIONS] World animal kit tuning forwarded to `castCattle`.
37
+ * @param {Record<string, ReadonlyArray<readonly [boolean, boolean]>>} [options.casts=DEFAULT_LIVESTOCK_CASTS] Map of build name to `[grazing, far]` pairs pre-cast by `castFarmBeasts`.
38
+ * @param {() => boolean} [options.pooled] Returns true when a worker pool is ready to accept jobs.
39
+ * @param {((job: string, spec: { build: string, casts: ReadonlyArray<readonly [boolean, boolean]> }) => Promise<object[]>)|null} [options.run=null] Worker job runner returning packed attribute arrays per cast.
40
+ * @param {string} [options.job='farm beasts'] Worker job name passed to `run`.
41
+ * @param {(arrays: object) => import('three').BufferGeometry} [options.geometryOf] Converts worker attribute arrays into a `THREE.BufferGeometry`.
42
+ * @returns {{
43
+ * castFarmBeasts: () => Promise<void> | null,
44
+ * cattleGeometry: (grazing: boolean, far: boolean, build?: string, fallen?: boolean) => import('three').BufferGeometry,
45
+ * clear: () => void,
46
+ * sheepGeometry: (grazing: boolean, far: boolean) => import('three').BufferGeometry,
47
+ * takeFarmBeasts: () => Promise<void> | null,
48
+ * }}
49
+ */
50
+ export function createLivestockCache({
51
+ animals = NO_ANIMAL_OPTIONS,
52
+ casts = DEFAULT_LIVESTOCK_CASTS,
53
+ pooled = () => false,
54
+ run = null,
55
+ job = 'farm beasts',
56
+ geometryOf = defaultGeometryOf,
57
+ } = {}) {
58
+ const cast = new Map();
59
+ let casting = null;
60
+
61
+ /**
62
+ * Returns a plain geometry for a cow, ox, or sheep facing +z on y = 0, consuming a pre-cast
63
+ * worker geometry when available or casting synchronously otherwise.
64
+ *
65
+ * @param {boolean} grazing True for head down grazing, false for head up standing.
66
+ * @param {boolean} far True for the lighter distant skin.
67
+ * @param {string} [build='cow'] Animal build (`'cow'`, `'ox'`, `'sheep'`, etc.).
68
+ * @param {boolean} [fallen=false] True for a dead animal pose (always cast synchronously).
69
+ * @returns {import('three').BufferGeometry}
70
+ */
71
+ function cattleGeometry(grazing, far, build = 'cow', fallen = false) {
72
+ const key = castKey(build, grazing, far),
73
+ done = !fallen && cast.get(key);
74
+ if (!done) return castCattle(grazing, far, build, fallen, animals);
75
+ cast.delete(key);
76
+ return done;
77
+ }
78
+
79
+ /**
80
+ * Dispatches worker jobs to cast every `[grazing, far]` variant declared in `casts` while the
81
+ * caller builds the rest of the land. Clears the cache on failure so synchronous fallback runs.
82
+ *
83
+ * @returns {Promise<void> | null} The in-flight casting promise, or `null` if no worker pool is active.
84
+ */
85
+ function castFarmBeasts() {
86
+ if (!pooled() || !run) return null;
87
+ const builds = Object.keys(casts);
88
+ casting = Promise.all(builds.map(build => run(job, { build, casts: casts[build] })))
89
+ .then(lists => {
90
+ lists.forEach((list, i) => list.forEach((arrays, k) => cast.set(castKey(builds[i], ...casts[builds[i]][k]), geometryOf(arrays))));
91
+ })
92
+ .catch(() => cast.clear());
93
+ return casting;
94
+ }
95
+
96
+ /** Returns the promise from the latest `castFarmBeasts()` call, or `null` if none was started. */
97
+ const takeFarmBeasts = () => casting;
98
+
99
+ /** Convenience wrapper returning a posed sheep geometry facing +z on y = 0. */
100
+ const sheepGeometry = (grazing, far) => cattleGeometry(grazing, far, 'sheep');
101
+
102
+ /** Drops any cached geometries and clears the pending worker promise. */
103
+ function clear() {
104
+ cast.clear();
105
+ casting = null;
106
+ }
107
+
108
+ return { castFarmBeasts, cattleGeometry, clear, sheepGeometry, takeFarmBeasts };
109
+ }