@rig-c/parts 1.67.0 → 1.68.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.
package/src/propose.ts CHANGED
@@ -291,7 +291,7 @@ export interface Proposal {
291
291
  /** Only with `propose --cloth` (issue #364, `src/cloth.ts`): the physics (and a skirt swing's transforms) of the trees it drafted; absent otherwise, so a proposal without it is the one written before it. */
292
292
  constraints?: ConfigConstraint[];
293
293
  /** Only with `propose --full`/`--head` (issue #251, {@link draftTurn}); absent otherwise, so a proposal without them is the one written before it. */
294
- turn?: TurnSpec;
294
+ turn?: TurnSpec & { pivot: number; depths: Record<string, number> };
295
295
  /** The `assemble.rig_scale` (`parts.json`'s `scale_rig_per_source`) its coordinates were drafted at (issue #354). */
296
296
  proposed_rig_scale: number;
297
297
  notes: string[];
@@ -524,7 +524,7 @@ export type TurnRuns = Partial<Record<'full' | 'head', LayerSet>>;
524
524
  * each carrier the other run places more than {@link TURN_RUN_APART} of the
525
525
  * span away.
526
526
  */
527
- export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { turn: TurnSpec | null; notes: string[] } {
527
+ export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { turn: (TurnSpec & { pivot: number; depths: Record<string, number> }) | null; notes: string[] } {
528
528
  P = P.beforeLimbs();
529
529
  const problems: Problem[] = [];
530
530
  const read: Array<{ part: string; run: 'full' | 'head'; tag: string; base: string | null; own: number; area: number; order: number; piece: boolean }> = [];
@@ -615,7 +615,7 @@ export function draftTurn(P: PartSet, runs: TurnRuns, binds?: PartBinding): { tu
615
615
  notes.push(`turn: every carried part lies at depth ${nearest.depth}, so none is nearer than the pivot and no turn control is drafted`);
616
616
  return { turn: null, notes };
617
617
  }
618
- const turn: TurnSpec = { pivot, depths };
618
+ const turn = { pivot, depths };
619
619
  const fr = turnFractions(turn, rows.map((r) => r.part));
620
620
  notes.push(
621
621
  `turn: control "${TURN_BONE}" under root, keyed by nothing — its x is the dial. Pivot depth ${pivot}: the mean of the ${rows.length} carried parts' depths weighted by opaque_px, the one depth at which the painted pixels' centroid does not slide (correct it in turn.pivot). ` +
@@ -651,7 +651,7 @@ export const TURN_DEPTH_CAVEAT: readonly string[] = [
651
651
  ];
652
652
 
653
653
  /** The proposal with `turn` written after `motion` and `notes` extended; the proposal itself when `turn` is null. */
654
- export function withTurn(p: Proposal, draft: { turn: TurnSpec | null; notes: string[] }): Proposal {
654
+ export function withTurn(p: Proposal, draft: { turn: (TurnSpec & { pivot: number; depths: Record<string, number> }) | null; notes: string[] }): Proposal {
655
655
  // Issue #349: a part a limb takes is not made; each of its limb parts carries its depth instead.
656
656
  let turn = draft.turn;
657
657
  if (turn !== null && p.limbs !== undefined) {
@@ -663,7 +663,7 @@ export function withTurn(p: Proposal, draft: { turn: TurnSpec | null; notes: str
663
663
  if (parts === undefined) depths[part] = d;
664
664
  else for (const q of parts) depths[q] = d;
665
665
  }
666
- turn = { pivot: turn.pivot, depths };
666
+ turn = { ...turn, pivot: turn.pivot, depths };
667
667
  }
668
668
  return { bones: p.bones, meshes: p.meshes, regions: p.regions, ...(p.limbs === undefined ? {} : { limbs: p.limbs }), ...(p.motion_seams === undefined ? {} : { motion_seams: p.motion_seams }), motion: p.motion, ...(p.constraints === undefined ? {} : { constraints: p.constraints }), ...(turn === null ? {} : { turn }), proposed_rig_scale: p.proposed_rig_scale, notes: [...p.notes, ...draft.notes] };
669
669
  }
package/src/rig.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { padDepthSheet, padTurnDepthSheet, depthSheetProblems, type PartDepthReference } from './depthsheets.ts';
1
2
  import { explicitBoneNames, explicitSlotBones, explicitWeightRows, regionBone } from './config.ts';
2
3
  import { explicitAttachment, type ExplicitMeshReport } from './explicitmesh.ts';
3
4
  /**
@@ -182,7 +183,7 @@ import { alphaAbove, crop, pad, type Raster } from './raster/index.ts';
182
183
  import { pyRound } from './round.ts';
183
184
  import { boneHeat, type HeatDust, heatInfluences, HEAT_LIMITS, heatRow, type HeatRow, latticeSilhouette, tracedSilhouette } from './heat.ts';
184
185
  import type { PosePoints } from './skeleton.ts';
185
- import { applyFaceSurfaceDeform, FACE_RATED_BAND, TURN_BONE, TURN_CARRIER_TAG, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnTwin } from './turn.ts';
186
+ import { applyFaceSurfaceDeform, buildDepth25DTurn, FACE_RATED_BAND, FACESHIFT_BONE, PITCH_DIAL_BONE, REAR_SHIFT_BONE, resolveTurnGrid, TURN_BONE, TURN_CARRIER_TAG, TURN_GRID_MAX_TRIANGLES_PER_SLOT, TURN_GRID_MAX_TRIANGLES_TOTAL, TURN_PLACES, TURN_RIDER_APART, TURN_RIDER_TAGS, turnRiderDepth, type TurnSpec, turnConstraintName, turnFractions, turnNearest, turnSurfaceBone, turnTwin, YAW_DIAL_BONE } from './turn.ts';
186
187
  import { DISTANCE_EXPONENT, type FloorForm, type Influence, influences, type InfluenceLimits, type MeshInfluences, meshLimits, type Segment } from './weights.ts';
187
188
 
188
189
  /** Transparent pixels added round every part image — the reference's `PAD`. */
@@ -500,6 +501,12 @@ export interface MeshAttachment {
500
501
  triangles: number[];
501
502
  hull: number;
502
503
  weights: WeightEntry[][];
504
+ generator?: {
505
+ kind: 'grid';
506
+ cols: number;
507
+ rows: number;
508
+ depth?: Omit<PartDepthReference, 'sources'>;
509
+ };
503
510
  }
504
511
 
505
512
  export interface RegionAttachment {
@@ -536,7 +543,14 @@ export interface RigSpec {
536
543
  * the idle keys a mesh-driving bone. `detached`: written only when a
537
544
  * constraint follows a bone ({@link detachedRules}).
538
545
  */
539
- invariants?: { idleDrivesMeshes?: { why: string }; detached?: DetachedRule[]; deformMayFold?: Array<{ slot: string; why: string }>; axes?: RigAxis[] };
546
+ invariants?: {
547
+ idleDrivesMeshes?: { why: string };
548
+ detached?: DetachedRule[];
549
+ deformMayFold?: Array<{ slot: string; why: string }>;
550
+ axes?: RigAxis[];
551
+ meshSlots?: number;
552
+ meshTriangles?: number;
553
+ };
540
554
  }
541
555
 
542
556
  /** One `invariants.detached` entry: rig-c's `RigDetachedRule`, checked by its gate rule `A25`. */
@@ -597,6 +611,9 @@ function signed4(v: number): string {
597
611
  * layer) is read by its tag, never by its bones, as `propose` reads it.
598
612
  */
599
613
  function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile['parts']): Problem[] {
614
+ if (turn.depths === undefined || turn.pivot === undefined) return [];
615
+ const depths = turn.depths;
616
+ const pivot = turn.pivot;
600
617
  const baseOf = (from: string): string | null => {
601
618
  const t = tagOf(from);
602
619
  return t === null ? null : (readTag(t)?.base ?? null);
@@ -606,12 +623,12 @@ function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile
606
623
  const b = baseOf(from);
607
624
  return faces.length === 1 && b !== null && TURN_RIDER_TAGS.includes(b);
608
625
  };
609
- const carried = recs.filter((r) => Object.hasOwn(turn.depths, r.name) && !tagRider(r.from));
626
+ const carried = recs.filter((r) => Object.hasOwn(depths, r.name) && !tagRider(r.from));
610
627
  const { riders } = turnRidersByBone(cfg, carried.map((r) => ({ part: r.name, area: r.opaque_px })));
611
628
  if (riders.size === 0) return [];
612
- const nearest = turnNearest(turn.depths);
629
+ const nearest = turnNearest(depths);
613
630
  if (nearest === null) return [];
614
- const span = turn.pivot - nearest.depth;
631
+ const span = pivot - nearest.depth;
615
632
  const order = recs.map((r) => r.name);
616
633
  const frac = new Map(turnFractions(turn, order).map((f) => [f.part, f.fraction]));
617
634
  const problems: Problem[] = [];
@@ -621,13 +638,13 @@ function turnRiderProblems(turn: TurnSpec, cfg: CharacterConfig, recs: PartsFile
621
638
  const diff = Math.abs(fp - fh);
622
639
  if (!(diff > TURN_RIDER_APART)) continue;
623
640
  const above = order.indexOf(part) > order.indexOf(ride.host);
624
- const want = pyRound(turnRiderDepth(turn.depths[ride.host], above), TURN_PLACES + 3);
641
+ const want = pyRound(turnRiderDepth(depths[ride.host], above), TURN_PLACES + 3);
625
642
  problems.push({
626
643
  code: 'CONFIG_TURN_RIDER_DEPTH',
627
644
  object: `config.turn.depths.${part}`,
628
645
  detail:
629
- `is ${turn.depths[part]}, fraction ${signed4(fp)} of the dial; "${part}" rides "${ride.host}" by bone — every ownable bone it binds (${ride.bones.join(', ')}) is hosted by "${ride.host}", the carried part binding it with the most opaque px — ` +
630
- `whose depth ${turn.depths[ride.host]} travels ${signed4(fh)}: the difference ${pyRound(diff, 4)} is more than ${TURN_RIDER_APART} of pivot − nearest (${turn.pivot} − ${nearest.depth} = ${pyRound(span, TURN_PLACES)}), so at the dial's x the part leaves what it rides by ${pyRound(diff, 4)} of it; ` +
646
+ `is ${depths[part]}, fraction ${signed4(fp)} of the dial; "${part}" rides "${ride.host}" by bone — every ownable bone it binds (${ride.bones.join(', ')}) is hosted by "${ride.host}", the carried part binding it with the most opaque px — ` +
647
+ `whose depth ${depths[ride.host]} travels ${signed4(fh)}: the difference ${pyRound(diff, 4)} is more than ${TURN_RIDER_APART} of pivot − nearest (${pivot} − ${nearest.depth} = ${pyRound(span, TURN_PLACES)}), so at the dial's x the part leaves what it rides by ${pyRound(diff, 4)} of it; ` +
631
648
  `the host's depth ${above ? '−' : '+'} 0.001 (${want}, drawn ${above ? 'above' : 'under'} it) is required, or redraft the turn with propose --full/--head`,
632
649
  });
633
650
  }
@@ -714,7 +731,7 @@ export function applyTurn(
714
731
  };
715
732
  for (const sl of mine) {
716
733
  bind(sl.bone);
717
- for (const att of Object.values(skin[sl.name] ?? {})) if ('type' in att) for (const v of att.weights) for (const w of v) bind(w.bone);
734
+ for (const att of Object.values(skin[sl.name] ?? {})) if ('type' in att && att.weights !== undefined) for (const v of att.weights) for (const w of v) bind(w.bone);
718
735
  }
719
736
  for (const b of bound) orderOf(b);
720
737
  if (orderByDeclaration) bound.sort((a, b) => orderOf(a) - orderOf(b));
@@ -741,7 +758,7 @@ export function applyTurn(
741
758
  sl.bone = twinOf.get(sl.bone) as string;
742
759
  const atts = skin[sl.name] ?? {};
743
760
  for (const [k, att] of Object.entries(atts)) {
744
- if ('type' in att) atts[k] = { ...att, weights: att.weights.map((v) => v.map((w) => ({ ...w, bone: twinOf.get(w.bone) as string }))) };
761
+ if ('type' in att && att.weights !== undefined) atts[k] = { ...att, weights: att.weights.map((v) => v.map((w) => ({ ...w, bone: twinOf.get(w.bone) as string }))) };
745
762
  }
746
763
  }
747
764
  const cname = turnConstraintName(row.part);
@@ -813,7 +830,7 @@ export const IDLE_DRIVES_MESHES_WHY = 'painting rig: the idle is meant to deform
813
830
  * every mode; `remesh --delta`'s row (`deltaRow`, `src/remesh.ts`) takes the same function.
814
831
  */
815
832
  export function meshBoundBones(att: Pick<MeshAttachment, 'weights'>): string[] {
816
- return [...new Set(att.weights.flatMap((w) => w.map((e) => e.bone)))].sort();
833
+ return [...new Set((att.weights ?? []).flatMap((w) => w.map((e) => e.bone)))].sort();
817
834
  }
818
835
 
819
836
  /** One row of `mesh_report.json`: a lattice mesh's row is as it always was; a contour mesh's says so. */
@@ -1110,6 +1127,7 @@ export interface AttachmentSetsFile {
1110
1127
  }
1111
1128
 
1112
1129
  export interface RigOutput {
1130
+ depthReferences?: Array<{ part: string; size: [number, number]; depth: PartDepthReference }>;
1113
1131
  rig: RigSpec;
1114
1132
  /** Internal explicit-layout provenance; serialized only as an external companion. */
1115
1133
  layout?: LayoutPlan;
@@ -1833,6 +1851,21 @@ export function buildRig(
1833
1851
  const skin: RigSpec['skins']['default'] = {};
1834
1852
  const meshReport: MeshReport[] = [];
1835
1853
  const outImages: Array<[string, Raster]> = [];
1854
+ const depthReferences: NonNullable<RigOutput['depthReferences']> = [];
1855
+ const emitDepth = (part: string, reference: PartDepthReference, scalar: Raster): void => {
1856
+ if (outImages.some(([file]) => file === reference.image)) {
1857
+ fail('DEPTH_SHEET_UNAMBIGUOUS', reference.image, 'collides with an emitted asset; choose noncolliding part/sheet names');
1858
+ return;
1859
+ }
1860
+ const art = images.get(part);
1861
+ const image =
1862
+ cfg.turn?.roles?.[part] !== undefined && art !== undefined && art.width === scalar.width && art.height === scalar.height
1863
+ ? padTurnDepthSheet(scalar, art, PAD)
1864
+ : padDepthSheet(scalar, PAD);
1865
+ outImages.push([reference.image, image]);
1866
+ depthReferences.push({ part, size: [image.width, image.height], depth: reference });
1867
+ };
1868
+
1836
1869
  const loopPasses: Record<string, number> = {};
1837
1870
  const autoMotion: AutoMotionCase[] = [];
1838
1871
  // A region's centre in its bone's setup frame; on a turned bone the image
@@ -2333,9 +2366,59 @@ export function buildRig(
2333
2366
  for (const p of parts.parts) {
2334
2367
  const img = pad(images.get(p.name) as Raster, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2335
2368
  const file = `${p.name}.png`;
2369
+ const artIndex = outImages.length;
2336
2370
  outImages.push([file, img]);
2371
+ const scalar = p.depth === undefined ? undefined : images.get(p.depth.image);
2372
+ if (p.depth !== undefined) {
2373
+ if (scalar === undefined) fail('DEPTH_SHEET_PRESENT', p.depth.image, `part "${p.name}" declares a sheet; the unpadded source sheet must be handed to buildRig`);
2374
+ else {
2375
+ problems.push(...depthSheetProblems(scalar, [p.w, p.h], p.depth.image));
2376
+ if (parts.parts.some(q => `${q.name}.png` === p.depth?.image)) fail('DEPTH_SHEET_UNAMBIGUOUS', p.depth.image, 'collides with artwork; use noncolliding part names');
2377
+ else if (cfg.meshes[p.name] !== undefined || stills[p.name] === undefined) emitDepth(p.name, p.depth, scalar);
2378
+ }
2379
+ }
2380
+
2337
2381
  const mesh = cfg.meshes[p.name];
2338
2382
  if (mesh === undefined) {
2383
+ if (cfg.turn?.roles?.[p.name] === 'surface') {
2384
+ if (p.depth === undefined || scalar === undefined) {
2385
+ fail(
2386
+ 'RIG_TURN_SURFACE_DEPTH_REQUIRED',
2387
+ `config.turn.roles.${p.name}`,
2388
+ `declares role "surface" for "${p.name}", which requires a depth sheet in parts.json; run assemble with config.depth or provide "${p.name}_depth.png"`,
2389
+ );
2390
+ continue;
2391
+ }
2392
+ const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
2393
+ const triCount = 2 * (cols - 1) * (rows - 1);
2394
+ if (triCount > TURN_GRID_MAX_TRIANGLES_PER_SLOT) {
2395
+ fail(
2396
+ 'RIG_TURN_GRID_BUDGET',
2397
+ `config.turn.grid (${p.name})`,
2398
+ `specifies a ${cols}x${rows} grid (${triCount} triangles), which exceeds the per-slot budget of ${TURN_GRID_MAX_TRIANGLES_PER_SLOT} triangles`,
2399
+ );
2400
+ continue;
2401
+ }
2402
+ const surfBone = turnSurfaceBone(p.name);
2403
+ const { sources: _sources, ...coreDepth } = p.depth;
2404
+ const gridAtt: Omit<MeshAttachment, 'uvs' | 'triangles' | 'hull' | 'weights'> = {
2405
+ type: 'mesh',
2406
+ image: file,
2407
+ width: img.width,
2408
+ height: img.height,
2409
+ generator: {
2410
+ kind: 'grid',
2411
+ cols,
2412
+ rows,
2413
+ depth: coreDepth,
2414
+ },
2415
+ };
2416
+ skin[p.name] = {
2417
+ [p.name]: gridAtt as MeshAttachment,
2418
+ };
2419
+ addSlots(p.name, { name: p.name, bone: surfBone, attachment: p.name });
2420
+ continue;
2421
+ }
2339
2422
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
2340
2423
  const cx = p.x + p.w / 2;
2341
2424
  const st = stills[p.name];
@@ -2350,8 +2433,15 @@ export function buildRig(
2350
2433
  const lower = pad(crop(src, 0, r, p.w, p.h - r), PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2351
2434
  const upper = pad(crop(src, 0, 0, p.w, r), PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2352
2435
  const sb = B.get(st.bone) as Bone;
2353
- outImages[outImages.length - 1] = [file, lower];
2436
+ outImages[artIndex] = [file, lower];
2354
2437
  outImages.push([stillFile, upper]);
2438
+ if (p.depth !== undefined && scalar !== undefined) {
2439
+ // The SAME source row r as the art; each drawing owns a distinct
2440
+ // padded scalar grid, while original-source provenance stays intact.
2441
+ emitDepth(p.name, p.depth, crop(scalar, 0, r, p.w, p.h - r));
2442
+ emitDepth(still, { ...p.depth, image: `${still}_depth.png` }, crop(scalar, 0, 0, p.w, r));
2443
+ }
2444
+
2355
2445
  const cyLow = st.row + (p.h - r) / 2;
2356
2446
  const cyUp = p.y + r / 2;
2357
2447
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cyLow) };
@@ -2646,6 +2736,12 @@ export function buildRig(
2646
2736
  const img = pad(rawImg, PAD, PAD, PAD, PAD, [0, 0, 0, 0]);
2647
2737
  const file = `${attName}.png`;
2648
2738
  outImages.push([file, img]);
2739
+ if (p.depth !== undefined) {
2740
+ const scalar = images.get(p.depth.image);
2741
+ if (scalar === undefined) fail('DEPTH_SHEET_PRESENT', p.depth.image, `alternate "${attName}" requires its declared source sheet`);
2742
+ else { problems.push(...depthSheetProblems(scalar, [p.w, p.h], p.depth.image)); emitDepth(attName, p.depth, scalar); }
2743
+ }
2744
+
2649
2745
  const mesh = cfg.meshes[p.name];
2650
2746
  if (mesh === undefined) {
2651
2747
  const bone = B.get(regionBone(cfg.regions[p.name])) as Bone;
@@ -2659,7 +2755,7 @@ export function buildRig(
2659
2755
  const fullSegs = meshSegments.get(p.name) as Segment[];
2660
2756
  const explicitSegments = new Map(fullSegs.map((s, k) => [s, typeof mesh.segments[(meshSegmentEntries.get(p.name) as number[])[k]] !== 'string']));
2661
2757
  const baseAtt = skin[p.name]?.[p.name];
2662
- const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set(baseAtt.weights.flatMap((v) => v.map((e) => e.bone))) : null;
2758
+ const baseBones = baseAtt !== undefined && 'type' in baseAtt ? new Set((baseAtt.weights ?? []).flatMap((v) => v.map((e) => e.bone))) : null;
2663
2759
  const filteredSegs = baseBones !== null && baseBones.size > 0 ? fullSegs.filter((s) => baseBones.has(s.bone)) : fullSegs;
2664
2760
  let segs = filteredSegs.length > 0 ? filteredSegs : fullSegs;
2665
2761
  if (drawn !== undefined) {
@@ -2852,8 +2948,136 @@ export function buildRig(
2852
2948
  // ---- the turn control (issue #251) -------------------------------------
2853
2949
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2854
2950
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2855
- const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
2951
+ const turned = cfg.turn === undefined || cfg.turn.roles !== undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, rebound, skin, cfg.constraints ?? [], declaredFront, slotFamilies, stops, turnOrderByDeclaration);
2856
2952
  for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
2953
+ const finalSlots = frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies);
2954
+ let generatedMeshBudget: { meshSlots: number; meshTriangles: number } | null = null;
2955
+ if (cfg.turn?.roles !== undefined) {
2956
+ const roles = cfg.turn.roles;
2957
+ let totalGridTriangles = 0;
2958
+ const headIdx = bones.findIndex((b) => b.name === 'head');
2959
+ if (headIdx === -1) {
2960
+ fail('RIG_TURN_HEAD_BONE', 'config.turn.roles', 'requires a declared "head" bone in config.bones to parent the 2.5D turn carriers');
2961
+ } else {
2962
+ const headTransform = world.get('head') as BoneTransform;
2963
+ const headTurnDeg = turn.get('head') ?? 0;
2964
+ const surfBones: RigBone[] = [];
2965
+ for (const p of parts.parts) {
2966
+ if (roles[p.name] !== 'surface' || cfg.meshes[p.name] !== undefined) continue;
2967
+ const [cols, rows] = resolveTurnGrid(cfg.turn, p.name);
2968
+ totalGridTriangles += 2 * (cols - 1) * (rows - 1);
2969
+ const cx = p.x + p.w / 2;
2970
+ const cy = p.y + p.h / 2;
2971
+ const [lx, ly] = toBoneLocal(headTransform, spineX(cx), spineY(cy));
2972
+ const rot = places(normaliseDegrees(-headTurnDeg));
2973
+ surfBones.push({
2974
+ name: turnSurfaceBone(p.name),
2975
+ parent: FACESHIFT_BONE,
2976
+ x: places(lx),
2977
+ y: places(ly),
2978
+ ...(rot === 0 ? {} : { rotation: rot }),
2979
+ });
2980
+ }
2981
+ if (totalGridTriangles > TURN_GRID_MAX_TRIANGLES_TOTAL) {
2982
+ fail(
2983
+ 'RIG_TURN_GRID_BUDGET',
2984
+ 'config.turn.grid',
2985
+ `allocates ${totalGridTriangles} total grid triangles across surface slots, which exceeds the total budget of ${TURN_GRID_MAX_TRIANGLES_TOTAL} triangles`,
2986
+ );
2987
+ }
2988
+ const hasRear = Object.values(roles).includes('rear');
2989
+ const carriers: RigBone[] = [
2990
+ { name: FACESHIFT_BONE, parent: 'head', x: 0, y: 0 },
2991
+ ...(hasRear ? [{ name: REAR_SHIFT_BONE, parent: 'head', x: 0, y: 0 }] : []),
2992
+ ...surfBones,
2993
+ ];
2994
+ bones.splice(headIdx + 1, 0, ...carriers);
2995
+ const existingNames = new Set(bones.map((b) => b.name));
2996
+ if (!existingNames.has(YAW_DIAL_BONE)) bones.push({ name: YAW_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
2997
+ if (!existingNames.has(PITCH_DIAL_BONE)) bones.push({ name: PITCH_DIAL_BONE, parent: ROOT_BONE, x: 0, y: 0 });
2998
+
2999
+ const boneByName = new Map(bones.map((b) => [b.name, b]));
3000
+ const slotByName = new Map(finalSlots.map((s) => [s.name, s]));
3001
+ const reparentFromHead = (boneName: string, targetParent: string): void => {
3002
+ const b = boneByName.get(boneName);
3003
+ if (b !== undefined && b.parent === 'head') b.parent = targetParent;
3004
+ };
3005
+ const rebindPartToCarrier = (part: string, carrierBone: string): void => {
3006
+ const sl = slotByName.get(part);
3007
+ if (sl !== undefined && sl.bone === 'head') sl.bone = carrierBone;
3008
+ const stillSl = slotByName.get(`${part}${STILL_SUFFIX}`);
3009
+ if (stillSl !== undefined) {
3010
+ if (stillSl.bone === 'head') stillSl.bone = carrierBone;
3011
+ else reparentFromHead(stillSl.bone, carrierBone);
3012
+ }
3013
+ const atts = skin[part] ?? {};
3014
+ for (const att of Object.values(atts)) {
3015
+ if (!('type' in att) || att.weights === undefined) continue;
3016
+ for (const row of att.weights) {
3017
+ for (const w of row) {
3018
+ if (w.bone === 'head') {
3019
+ w.bone = carrierBone;
3020
+ } else {
3021
+ // Find the ancestor of w.bone that hangs directly under head and reparent it to carrierBone.
3022
+ let cur = boneByName.get(w.bone);
3023
+ while (cur !== undefined && cur.parent !== undefined && cur.parent !== 'head' && cur.parent !== carrierBone) {
3024
+ cur = boneByName.get(cur.parent);
3025
+ }
3026
+ if (cur !== undefined && cur.parent === 'head') cur.parent = carrierBone;
3027
+ }
3028
+ }
3029
+ }
3030
+ }
3031
+ };
3032
+
3033
+ for (const [part, role] of Object.entries(roles)) {
3034
+ if (role === 'unit') {
3035
+ if (cfg.regions[part] !== undefined) {
3036
+ const bName = regionBone(cfg.regions[part]);
3037
+ if (bName === 'head') {
3038
+ const sl = slotByName.get(part);
3039
+ if (sl !== undefined) sl.bone = FACESHIFT_BONE;
3040
+ } else {
3041
+ reparentFromHead(bName, FACESHIFT_BONE);
3042
+ }
3043
+ const st = stills[part];
3044
+ if (st !== undefined) reparentFromHead(st.bone, FACESHIFT_BONE);
3045
+ } else if (cfg.meshes[part] !== undefined) {
3046
+ rebindPartToCarrier(part, FACESHIFT_BONE);
3047
+ }
3048
+ } else if (role === 'rear' && hasRear) {
3049
+ if (cfg.regions[part] !== undefined) {
3050
+ const bName = regionBone(cfg.regions[part]);
3051
+ if (bName === 'head') {
3052
+ const sl = slotByName.get(part);
3053
+ if (sl !== undefined) sl.bone = REAR_SHIFT_BONE;
3054
+ } else {
3055
+ reparentFromHead(bName, REAR_SHIFT_BONE);
3056
+ }
3057
+ } else if (cfg.meshes[part] !== undefined) {
3058
+ rebindPartToCarrier(part, REAR_SHIFT_BONE);
3059
+ }
3060
+ }
3061
+ }
3062
+
3063
+ let meshSlots = 0;
3064
+ let meshTriangles = 0;
3065
+ for (const atts of Object.values(skin)) {
3066
+ let slotHasMesh = false;
3067
+ for (const att of Object.values(atts)) {
3068
+ if (!('type' in att)) continue;
3069
+ slotHasMesh = true;
3070
+ const tris =
3071
+ att.generator?.kind === 'grid'
3072
+ ? 2 * (att.generator.cols - 1) * (att.generator.rows - 1)
3073
+ : (att.triangles?.length ?? 0) / 3;
3074
+ if (tris > meshTriangles) meshTriangles = tris;
3075
+ }
3076
+ if (slotHasMesh) meshSlots++;
3077
+ }
3078
+ generatedMeshBudget = { meshSlots, meshTriangles };
3079
+ }
3080
+ }
2857
3081
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2858
3082
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
2859
3083
  for (const row of meshReport) {
@@ -2870,6 +3094,15 @@ export function buildRig(
2870
3094
  const att = skin[row.part]?.[row.part];
2871
3095
  if (att !== undefined && 'type' in att) row.bones = meshBoundBones(att);
2872
3096
  }
3097
+ // Check the complete namespace: an alternate's art can arrive after a base
3098
+ // sheet (or a still asset) with the same filename. Never let write order
3099
+ // decide which drawing or measurement survives on disk.
3100
+ const assetIndices = new Map<string, number>();
3101
+ outImages.forEach(([file], index) => {
3102
+ const previous = assetIndices.get(file);
3103
+ if (previous !== undefined) fail('DEPTH_SHEET_UNAMBIGUOUS', file, `output assets[${previous}] and [${index}] require the same filename; choose distinct base, still, alternate and sheet names`);
3104
+ else assetIndices.set(file, index);
3105
+ });
2873
3106
  refuseIfAny(problems);
2874
3107
  const name = `${cfg.key}_painting`;
2875
3108
  const rig: RigSpec = {
@@ -2878,7 +3111,7 @@ export function buildRig(
2878
3111
  images: 'images',
2879
3112
  skeleton: { x: -CX, y: 0, width: W, height: H },
2880
3113
  bones,
2881
- slots: frontSlots.length === 0 ? explicitLayout.slots : spliceFrontSlots(explicitLayout.slots, frontSlots, frontTargets, slotFamilies),
3114
+ slots: finalSlots,
2882
3115
  skins: { default: skin },
2883
3116
  };
2884
3117
  if (cfg.constraints !== undefined) rig.constraints = cfg.constraints.map(constraintForRig);
@@ -2893,23 +3126,53 @@ export function buildRig(
2893
3126
  // issue #239: the face's line, written only when the face bones were turned to one, so no other rig moves.
2894
3127
  const axes = [faceAxis.axis, faceAxis.tipAxis].flatMap((x) => (x === null ? [] : [x]));
2895
3128
  if (axes.length > 0) rig.invariants = { ...rig.invariants, axes };
3129
+ if (generatedMeshBudget !== null) {
3130
+ rig.invariants = { ...rig.invariants, ...generatedMeshBudget };
3131
+ }
2896
3132
  const faceImg = outImages.find(([k]) => k === 'face.png')?.[1];
2897
3133
  const facePart = parts.parts.find((p) => p.name === 'face');
2898
3134
  const partAreas: Record<string, number> = {};
2899
3135
  for (const p of parts.parts) partAreas[p.name] = p.opaque_px;
2900
- bindFaceSurfaceDeform(motion, (merged) => {
2901
- expandSetAttachmentKeys(rig, sets, merged);
2902
- applyFaceSurfaceDeform(rig, merged, {
2903
- imageWidth: faceImg?.width,
2904
- imageHeight: faceImg?.height,
2905
- opaqueWidth: facePart?.w,
2906
- opaqueHeight: facePart?.h,
2907
- overrides: cfg.turn?.deform,
2908
- hasAlternateFaceSet,
3136
+ const boneLandmarks = new Map<string, readonly [number, number]>();
3137
+ for (const [bName, bEntry] of B) {
3138
+ boneLandmarks.set(bName, [bEntry.x, bEntry.y]);
3139
+ }
3140
+ if (cfg.turn?.roles !== undefined) {
3141
+ buildDepth25DTurn(rig, motion, {
2909
3142
  turn: cfg.turn,
2910
- partAreas,
2911
- requireTurn: true,
3143
+ parts: parts.parts,
3144
+ images,
3145
+ regions: cfg.regions,
3146
+ stills,
3147
+ boneLandmarks,
3148
+ hasAlternateFaceSet,
2912
3149
  });
3150
+ }
3151
+ bindFaceSurfaceDeform(motion, (merged) => {
3152
+ expandSetAttachmentKeys(rig, sets, merged);
3153
+ if (cfg.turn?.roles !== undefined) {
3154
+ buildDepth25DTurn(rig, merged, {
3155
+ turn: cfg.turn,
3156
+ parts: parts.parts,
3157
+ images,
3158
+ regions: cfg.regions,
3159
+ stills,
3160
+ boneLandmarks,
3161
+ hasAlternateFaceSet,
3162
+ });
3163
+ } else {
3164
+ applyFaceSurfaceDeform(rig, merged, {
3165
+ imageWidth: faceImg?.width,
3166
+ imageHeight: faceImg?.height,
3167
+ opaqueWidth: facePart?.w,
3168
+ opaqueHeight: facePart?.h,
3169
+ overrides: cfg.turn?.deform,
3170
+ hasAlternateFaceSet,
3171
+ turn: cfg.turn,
3172
+ partAreas,
3173
+ requireTurn: true,
3174
+ });
3175
+ }
2913
3176
  if (sets !== undefined && (merged.animations.turn !== undefined || merged.animations.tilt !== undefined)) {
2914
3177
  for (const entry of Object.values(sets.sets)) {
2915
3178
  if (Object.hasOwn(entry.slots, 'face')) {
@@ -2923,6 +3186,7 @@ export function buildRig(
2923
3186
  motion,
2924
3187
  meshReport,
2925
3188
  images: outImages,
3189
+ ...(depthReferences.length === 0 ? {} : { depthReferences }),
2926
3190
  controls,
2927
3191
  meshKeyed,
2928
3192
  idleKeys,