@rig-c/parts 1.55.1 → 1.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ /** Explicit setup adjacency (#647). Ownership proves eligibility, never intent. */
2
+ import type { Limb, LimbLayoutTarget } from './config.ts';
3
+ import { createHash } from 'node:crypto';
4
+ import { type Problem, refuseIfAny } from './errors.ts';
5
+ import type { LimbSlotLayout } from './limbslots.ts';
6
+ import type { RigSpec } from './rig.ts';
7
+
8
+ export const LAYOUT_FILE = 'layout.json';
9
+ export const LAYOUT_SPEC = 'rig-parts-layout/1';
10
+ interface SegmentSource { limb: string; part: string }
11
+ export interface LayoutPlacement {
12
+ limb: string;
13
+ parts: string[];
14
+ before?: LimbLayoutTarget;
15
+ after?: LimbLayoutTarget;
16
+ slots: string[];
17
+ target_slots: string[];
18
+ }
19
+ /** Internal proof is not a RigSpec field and is never serialized as one. */
20
+ export interface LayoutPlan {
21
+ placements: LayoutPlacement[];
22
+ sources: Map<string, SegmentSource[]>;
23
+ limbs: Readonly<Record<string, Limb>>;
24
+ families: ReadonlyMap<string, readonly string[]>;
25
+ originalOrder: string[];
26
+ }
27
+ export interface LayoutCompanion {
28
+ spec: typeof LAYOUT_SPEC;
29
+ rig: { file: 'rig.json'; sha256: string };
30
+ sets?: { file: 'sets.json'; sha256: string };
31
+ setup_slots: string[];
32
+ placements: LayoutPlacement[];
33
+ }
34
+
35
+ /** Keep the concrete declared boundary that 646's parent walk encounters. */
36
+ function segmentSources(limbs: Readonly<Record<string, Limb>>, bones: RigSpec['bones']): Map<string, SegmentSource[]> {
37
+ const seeds = new Map<string, SegmentSource[]>();
38
+ for (const [limb, l] of Object.entries(limbs)) for (const s of l.segments) seeds.set(s.bone, [...(seeds.get(s.bone) ?? []), { limb, part: s.part }]);
39
+ const parents = new Map(bones.map((b) => [b.name, b.parent]));
40
+ const result = new Map<string, SegmentSource[]>();
41
+ for (const b of bones) {
42
+ let at: string | undefined = b.name;
43
+ const seen = new Set<string>();
44
+ while (at !== undefined && !seen.has(at) && !seeds.has(at)) { seen.add(at); at = parents.get(at); }
45
+ result.set(b.name, at === undefined ? [] : seeds.get(at) ?? []);
46
+ }
47
+ return result;
48
+ }
49
+
50
+ function bindings(slot: RigSpec['slots'][number], skin: RigSpec['skins']['default']): string[][] {
51
+ return Object.values(skin[slot.name] ?? {}).map((a) => 'type' in a ? a.weights.flatMap((v) => v.map((w) => w.bone)) : [slot.bone]);
52
+ }
53
+ function bindingDetail(slots: RigSpec['slots'], skin: RigSpec['skins']['default'], sources: LayoutPlan['sources']): string {
54
+ return JSON.stringify(slots.map((s) => ({ slot: s.name, attachments: Object.entries(skin[s.name] ?? {}).map(([attachment, a]) => ({ attachment, bones: ('type' in a ? a.weights.flatMap((v) => v.map((w) => w.bone)) : [s.bone]).map((bone) => ({ bone, sources: sources.get(bone) ?? [] })) })) })));
55
+ }
56
+ function owned(slot: RigSpec['slots'][number], skin: RigSpec['skins']['default'], sources: LayoutPlan['sources'], limb: string, parts: readonly string[]): boolean {
57
+ const bs = bindings(slot, skin);
58
+ return bs.length > 0 && bs.every((b) => b.length > 0 && b.every((n) => {
59
+ const s = sources.get(n) ?? [];
60
+ return s.length === 1 && s[0].limb === limb && parts.includes(s[0].part);
61
+ }));
62
+ }
63
+ /** A crossing target may be outside every limb, but may not mix owners. */
64
+ function targetSafe(slots: RigSpec['slots'], skin: RigSpec['skins']['default'], sources: LayoutPlan['sources']): boolean {
65
+ const owners = new Set<string>();
66
+ let good = slots.length > 0;
67
+ for (const slot of slots) {
68
+ const bs = bindings(slot, skin);
69
+ if (bs.length === 0) good = false;
70
+ for (const b of bs) {
71
+ if (b.length === 0) good = false;
72
+ for (const n of b) {
73
+ const s = sources.get(n) ?? [];
74
+ if (s.length > 1) good = false;
75
+ owners.add(s.length === 0 ? 'outside' : `limb:${s[0].limb}`);
76
+ }
77
+ }
78
+ }
79
+ return good && owners.size === 1;
80
+ }
81
+
82
+ /** Called only for opt-in declarations, over 646's unchanged permutation. */
83
+ export function placeLimbLayouts(limbs: Readonly<Record<string, Limb>> | undefined, bones: RigSpec['bones'], base: LimbSlotLayout, skin: RigSpec['skins']['default'], families: ReadonlyMap<string, readonly string[]>, inheritedSources?: LayoutPlan['sources']): { slots: RigSpec['slots']; plan?: LayoutPlan } {
84
+ if (limbs === undefined || !Object.values(limbs).some((l) => l.layout !== undefined)) return { slots: base.slots };
85
+ const sources = inheritedSources ?? segmentSources(limbs, bones), problems: Problem[] = [], placements: LayoutPlacement[] = [];
86
+ const names = base.slots.map((s) => s.name);
87
+ for (const [limb, l] of Object.entries(limbs)) {
88
+ const d = l.layout;
89
+ if (d === undefined) continue;
90
+ const at = `config.limbs.${limb}.layout`, parts = l.segments.map((s) => s.part).filter((p) => d.parts === undefined || d.parts.includes(p));
91
+ const subject = base.slots.filter((s) => owned(s, skin, sources, limb, parts));
92
+ const authored = d.before ?? d.after as LimbLayoutTarget;
93
+ const target: LimbLayoutTarget = authored.limb === undefined ? { part: authored.part } : { limb: authored.limb };
94
+ let targets: RigSpec['slots'];
95
+ if (target.limb !== undefined) {
96
+ const other = limbs[target.limb];
97
+ const all = other?.segments.map((s) => s.part) ?? [];
98
+ targets = base.slots.filter((s) => owned(s, skin, sources, target.limb as string, all));
99
+ for (const p of all) {
100
+ if ((families.get(p) ?? []).length === 0) problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `target limb "${target.limb}" segment part "${p}" has no emitted family` });
101
+ for (const n of families.get(p) ?? []) if (!targets.some((s) => s.name === n)) problems.push({ code: 'RIG_LAYOUT_NONEXCLUSIVE', object: `${at} target limb "${target.limb}" slot "${n}"`, detail: `requires exclusive target ownership across every attachment; found ${bindingDetail(base.slots.filter((s) => s.name === n), skin, sources)}` });
102
+ }
103
+ } else targets = base.slots.filter((s) => (families.get(target.part) ?? []).includes(s.name));
104
+ for (const p of parts) {
105
+ const family = families.get(p) ?? [];
106
+ if (family.length === 0) problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `selected segment part "${p}" has no emitted slot family` });
107
+ for (const n of family) if (!subject.some((s) => s.name === n)) problems.push({ code: 'RIG_LAYOUT_NONEXCLUSIVE', object: `${at} part "${p}" slot "${n}"`, detail: `requires exclusive selected-scope bindings across every attachment; found ${bindingDetail(base.slots.filter((s) => s.name === n), skin, sources)}` });
108
+ }
109
+ if (targets.length === 0) problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `target ${JSON.stringify(target)} has no emitted exclusive slot group` });
110
+ else if (!targetSafe(targets, skin, sources)) problems.push({ code: 'RIG_LAYOUT_NONEXCLUSIVE', object: `${at} target ${JSON.stringify(target)}`, detail: `requires one binding owner across base/alternate attachments; found ${bindingDetail(targets, skin, sources)}` });
111
+ const idx = targets.map((s) => names.indexOf(s.name));
112
+ if (idx.some((v, i) => i > 0 && v !== idx[i - 1] + 1)) problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `target slots ${targets.map((s) => s.name).join(', ')} do not form one contiguous block; no unrelated slot is absorbed` });
113
+ placements.push({ limb, parts, ...(d.before === undefined ? { after: target } : { before: target }), slots: subject.map((s) => s.name), target_slots: targets.map((s) => s.name) });
114
+ }
115
+ const participating = new Map<string, string>();
116
+ for (const p of placements) for (const n of [...p.slots, ...p.target_slots]) {
117
+ const at = `config.limbs.${p.limb}.layout`, other = participating.get(n);
118
+ if (other !== undefined) problems.push({ code: 'RIG_LAYOUT_CONFLICT', object: at, detail: `slot "${n}" also participates in ${other}; self, reciprocal, chained and shared-slot declarations are refused, so declare one disjoint pair` });
119
+ else participating.set(n, at);
120
+ }
121
+ refuseIfAny(problems);
122
+ placements.sort((a, b) => names.indexOf(a.target_slots[0]) - names.indexOf(b.target_slots[0]));
123
+ const moving = new Set(placements.flatMap((p) => p.slots));
124
+ const result: RigSpec['slots'] = [];
125
+ for (const s of base.slots) {
126
+ if (moving.has(s.name)) continue;
127
+ for (const p of placements) if (p.before !== undefined && p.target_slots[0] === s.name) result.push(...base.slots.filter((x) => p.slots.includes(x.name)));
128
+ result.push(s);
129
+ for (const p of placements) if (p.after !== undefined && p.target_slots[p.target_slots.length - 1] === s.name) result.push(...base.slots.filter((x) => p.slots.includes(x.name)));
130
+ }
131
+ const plan = { placements, sources, limbs, families, originalOrder: names };
132
+ validateLimbLayout(plan, { slots: result, skins: { default: skin } });
133
+ return { slots: result, plan };
134
+ }
135
+
136
+ /** A replay may change weights. Resolve closure again before that candidate is gated. */
137
+ export function refreshLimbLayout(plan: LayoutPlan, rig: RigSpec): LayoutPlan {
138
+ const byName = new Map(rig.slots.map((s) => [s.name, s]));
139
+ const slots = plan.originalOrder.flatMap((n) => { const s = byName.get(n); return s === undefined ? [] : [s]; });
140
+ if (slots.length !== rig.slots.length || new Set(rig.slots.map((s) => s.name)).size !== slots.length) refuseIfAny([{ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: 'rig.slots', detail: 'accepted candidate changed the source slot population; an exact permutation is required' }]);
141
+ const next = placeLimbLayouts(plan.limbs, rig.bones, { slots, owners: [], anchors: [] }, rig.skins.default, plan.families, plan.sources);
142
+ rig.slots = next.slots;
143
+ return next.plan as LayoutPlan;
144
+ }
145
+
146
+ /** Explicit generated alias, supplied where stops/turn actually create it. */
147
+ export function layoutAlias(plan: LayoutPlan | undefined, original: string, emitted: string): void {
148
+ if (plan !== undefined) plan.sources.set(emitted, plan.sources.get(original) ?? []);
149
+ }
150
+
151
+ /** Recheck accepted attachments after rebinds or mesh replay, before any emit. */
152
+ export function validateLimbLayout(plan: LayoutPlan, rig: Pick<RigSpec, 'slots' | 'skins'>): void {
153
+ const names = rig.slots.map((s) => s.name), problems: Problem[] = [];
154
+ for (const p of plan.placements) {
155
+ const at = `config.limbs.${p.limb}.layout`, target = p.before ?? p.after as LimbLayoutTarget;
156
+ const read = (ns: readonly string[]) => rig.slots.filter((s) => ns.includes(s.name));
157
+ const ss = read(p.slots), ts = read(p.target_slots);
158
+ const contiguous = (ns: string[]) => ns.length > 0 && ns.every((n, i) => i === 0 || names.indexOf(n) === names.indexOf(ns[i - 1]) + 1);
159
+ if (ss.length !== p.slots.length || ts.length !== p.target_slots.length || !contiguous(p.slots) || !contiguous(p.target_slots) || (p.before !== undefined ? names.indexOf(p.slots[p.slots.length - 1]) + 1 !== names.indexOf(p.target_slots[0]) : names.indexOf(p.target_slots[p.target_slots.length - 1]) + 1 !== names.indexOf(p.slots[0]))) {
160
+ problems.push({ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: at, detail: `accepted setup slots do not preserve the exact declared adjacency: ${JSON.stringify(p)}` });
161
+ }
162
+ if (ss.some((s) => !owned(s, rig.skins.default, plan.sources, p.limb, p.parts)) || !targetSafe(ts, rig.skins.default, plan.sources) || (target.limb !== undefined && ts.some((s) => !owned(s, rig.skins.default, plan.sources, target.limb as string, plan.limbs[target.limb as string].segments.map((s) => s.part))))) {
163
+ problems.push({ code: 'RIG_LAYOUT_NONEXCLUSIVE', object: at, detail: `accepted/replayed bindings must remain exclusive to their declared group; found ${bindingDetail([...ss, ...ts], rig.skins.default, plan.sources)}; no stale ownership proof is emitted` });
164
+ }
165
+ }
166
+ refuseIfAny(problems);
167
+ }
168
+
169
+ /** Hash exact accepted texts, never the pre-replay candidate or a core extension. */
170
+ export function layoutCompanion(plan: LayoutPlan, rig: RigSpec, rigText: string, setsText?: string): LayoutCompanion {
171
+ validateLimbLayout(plan, rig);
172
+ if (JSON.stringify(JSON.parse(rigText)) !== JSON.stringify(rig)) refuseIfAny([{ code: 'RIG_LAYOUT_UNREPRESENTABLE', object: 'layout.json rig source', detail: 'final rig text and accepted layout object differ; nothing may be emitted from a stale candidate' }]);
173
+ const hash = (s: string): string => createHash('sha256').update(s).digest('hex');
174
+ return {
175
+ spec: LAYOUT_SPEC,
176
+ rig: { file: 'rig.json', sha256: hash(rigText) },
177
+ ...(setsText === undefined ? {} : { sets: { file: 'sets.json' as const, sha256: hash(setsText) } }),
178
+ setup_slots: rig.slots.map((s) => s.name),
179
+ placements: plan.placements.map((p) => ({ limb: p.limb, parts: [...p.parts], ...(p.before === undefined ? { after: p.after } : { before: p.before }), slots: [...p.slots], target_slots: [...p.target_slots] })),
180
+ };
181
+ }
@@ -0,0 +1,37 @@
1
+ /** Shared source-segment geometry for subset ownership; no inferred endpoints. */
2
+ import type { Limb } from './config.ts';
3
+ import { type BonePlace, limbPolyline, polylineDist2 } from './limbs.ts';
4
+
5
+ export interface SourceLimbTarget {
6
+ segments: Limb['segments'];
7
+ line: Array<[number, number]>;
8
+ /** The last source segment has neither a supplied tip nor a following joint. */
9
+ missingEndBone: string | null;
10
+ }
11
+
12
+ /** Issue #638's source selection: only consecutive segments taking this source. */
13
+ export function sourceLimbTarget(limb: Limb, source: string, places: ReadonlyMap<string, BonePlace>): SourceLimbTarget {
14
+ const segments = limb.segments.filter((sg) => sg.from === source);
15
+ if (segments.length === 0) return { segments, line: [], missingEndBone: null };
16
+ const last = segments[segments.length - 1];
17
+ const line = limbPolyline({ ...limb, segments }, places);
18
+ if ((places.get(last.bone) as BonePlace).end === null) {
19
+ const next = limb.segments[limb.segments.indexOf(last) + 1];
20
+ if (next !== undefined) line.push((places.get(next.bone) as BonePlace).at);
21
+ }
22
+ return { segments, line, missingEndBone: line.length <= segments.length ? last.bone : null };
23
+ }
24
+
25
+ /** The nearest source segment and its part, with the same stable first-segment tie as #609. */
26
+ export function nearestTargetPart(target: SourceLimbTarget, x: number, y: number): { distance: number; part: string } {
27
+ let distance = Infinity;
28
+ let segment = 0;
29
+ for (let k = 0; k + 1 < target.line.length; k++) {
30
+ const d = polylineDist2([target.line[k], target.line[k + 1]], x, y);
31
+ if (d < distance) {
32
+ distance = d;
33
+ segment = k;
34
+ }
35
+ }
36
+ return { distance: Math.sqrt(distance), part: target.segments[segment].part };
37
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Issue #646: close each declared limb's existing slot block over its riders.
3
+ * No anatomical role or crossed target is inferred. A declared segment is an
4
+ * ownership boundary: descendants belong to the first segment encountered up
5
+ * their parent graph, so a nested limb does not become its ancestor's rider.
6
+ */
7
+ import type { Limb } from './config.ts';
8
+ import type { RigSpec } from './rig.ts';
9
+
10
+ export interface LimbSlotOwner {
11
+ slot: string;
12
+ kind: 'exclusive' | 'nonexclusive' | 'outside' | 'unbound';
13
+ limb: string | null;
14
+ /** Every attachment's actual binding, not a mesh slot's carrier bone. */
15
+ bindings: Array<{ attachment: string; bones: string[] }>;
16
+ limbs: string[];
17
+ outside: string[];
18
+ }
19
+
20
+ export interface LimbSlotLayout {
21
+ slots: RigSpec['slots'];
22
+ owners: LimbSlotOwner[];
23
+ /** First segment SLOT encountered in setup order, not anatomical segment 0. */
24
+ anchors: Array<{ limb: string; slot: string | null }>;
25
+ }
26
+
27
+ /**
28
+ * Read after all alternate attachments exist and before stops/turn rewrite
29
+ * bindings. Keep the returned slot references until those rewrites finish;
30
+ * only then publish the permutation, so their own enumeration order is intact.
31
+ *
32
+ * All weights of all attachments must resolve exclusively to the same limb.
33
+ * Even a listed zero-weight reference is read, as in meshBoundBones: there is
34
+ * no epsilon or first-weight rule. Mixed/outside/empty bindings stay outside
35
+ * the gathered blocks, with their classification returned for inspection.
36
+ * Their mutual order is preserved; complete closure is not promised across a
37
+ * nonexclusive segment or rider. No new refusal is introduced.
38
+ */
39
+ export function coalesceLimbSlots(
40
+ limbs: Readonly<Record<string, Limb>> | undefined,
41
+ bones: RigSpec['bones'],
42
+ slots: RigSpec['slots'],
43
+ skin: RigSpec['skins']['default'],
44
+ ): LimbSlotLayout {
45
+ if (limbs === undefined || Object.keys(limbs).length === 0) return { slots, owners: [], anchors: [] };
46
+ const seeds = new Map<string, string[]>();
47
+ for (const [name, limb] of Object.entries(limbs)) {
48
+ for (const s of limb.segments) {
49
+ const names = seeds.get(s.bone) ?? [];
50
+ if (!names.includes(name)) names.push(name);
51
+ seeds.set(s.bone, names);
52
+ }
53
+ }
54
+ const parents = new Map(bones.map((b) => [b.name, b.parent]));
55
+ const ownerOf = (bone: string): readonly string[] => {
56
+ let at: string | undefined = bone;
57
+ const seen = new Set<string>();
58
+ while (at !== undefined && !seen.has(at)) {
59
+ seen.add(at);
60
+ const declared = seeds.get(at);
61
+ if (declared !== undefined) return declared;
62
+ at = parents.get(at);
63
+ }
64
+ return [];
65
+ };
66
+ const owners: LimbSlotOwner[] = slots.map((slot) => {
67
+ const bindings = Object.entries(skin[slot.name] ?? {}).map(([attachment, att]) => ({
68
+ attachment,
69
+ bones: 'type' in att ? [...new Set(att.weights.flatMap((v) => v.map((w) => w.bone)))] : [slot.bone],
70
+ }));
71
+ const mine = new Set<string>();
72
+ const outside = new Set<string>();
73
+ let exclusive = bindings.length > 0;
74
+ for (const b of bindings) {
75
+ if (b.bones.length === 0) exclusive = false;
76
+ for (const bone of b.bones) {
77
+ const names = ownerOf(bone);
78
+ if (names.length !== 1) exclusive = false;
79
+ if (names.length === 0) outside.add(bone);
80
+ for (const name of names) mine.add(name);
81
+ }
82
+ }
83
+ const kind = exclusive && mine.size === 1 && outside.size === 0 ? 'exclusive' : mine.size > 0 ? 'nonexclusive' : bindings.some((b) => b.bones.length > 0) ? 'outside' : 'unbound';
84
+ return { slot: slot.name, kind, limb: kind === 'exclusive' ? [...mine][0] : null, bindings, limbs: [...mine], outside: [...outside] };
85
+ });
86
+ const anchors = Object.entries(limbs).map(([name, limb]) => ({ limb: name, slot: slots.find((s) => limb.segments.some((sg) => sg.part === s.name))?.name ?? null }));
87
+ const at = new Map<string, string[]>();
88
+ const anchored = new Set<string>();
89
+ for (const anchor of anchors) {
90
+ if (anchor.slot === null) continue;
91
+ at.set(anchor.slot, [...(at.get(anchor.slot) ?? []), anchor.limb]);
92
+ anchored.add(anchor.limb);
93
+ }
94
+ const owned = new Map(owners.map((o) => [o.slot, o.limb !== null && anchored.has(o.limb) ? o.limb : null]));
95
+ const gathered = new Map<string, RigSpec['slots']>();
96
+ for (const slot of slots) {
97
+ const name = owned.get(slot.name);
98
+ if (name !== null && name !== undefined) gathered.set(name, [...(gathered.get(name) ?? []), slot]);
99
+ }
100
+ const reordered: RigSpec['slots'] = [];
101
+ for (const slot of slots) {
102
+ for (const name of at.get(slot.name) ?? []) reordered.push(...(gathered.get(name) ?? []));
103
+ if (owned.get(slot.name) === null) reordered.push(slot);
104
+ }
105
+ return { slots: reordered.every((s, i) => s === slots[i]) ? slots : reordered, owners, anchors };
106
+ }
package/src/parts.ts CHANGED
@@ -167,12 +167,12 @@ export interface CapRecord {
167
167
  short_px?: { left: number; right: number };
168
168
  /**
169
169
  * Issue #603, written only when above 0: the cap's pixels a subset set's
170
- * exclusion (issue #587) cleared — pixels a base part the set does not
171
- * replace covers at setup — each taken out of the count it was in
170
+ * exclusion (issue #587) or preceding ownership assignment (issue #637)
171
+ * cleared, each taken out of the count it was in
172
172
  * (`layer_px`, `image_px`, `upper_px`, `lower_px`, `lower_kept_px`), so
173
173
  * those counts are the written PNG's. The disc's pixels are then the
174
174
  * counts above, `upper_px`, the lower half's and `excluded_px` together.
175
- * A cap no exclusion touched writes no key.
175
+ * A cap neither step touched writes no key.
176
176
  */
177
177
  excluded_px?: number;
178
178
  /**
package/src/rig.ts CHANGED
@@ -83,8 +83,9 @@
83
83
  * transparent edge and the render changes at rest — measured on the demo
84
84
  * example, 36 px of the setup pose (max 7 levels) — while a clear-row cut
85
85
  * changes no pixel outside the blink (issue #26, `RG16`). A `painting:`
86
- * patch (`assemble.patches`) is always a region; its slot sits where
87
- * parts.json puts it, which is where its `draw` put it.
86
+ * patch (`assemble.patches`) is always a region. With declared limbs, an
87
+ * exclusively bound rider joins its limb's slot block (issue #646), keeping
88
+ * that limb's internal draw order; other patches keep the parts order.
88
89
  * - **The idle** and, under `idleKeys: 'ctl'` (the default), its control
89
90
  * bones (`src/motion.ts`). Under `idleKeys: 'direct'` the keys stay on the
90
91
  * bones the meshes are weighted to, no `<bone>_ctl` is added, and the rig
@@ -167,6 +168,8 @@ import { type ContourChainRibs, type ContourReport, contourMesh, type ContourReg
167
168
  import { type LocalInfluence, localInfluences } from './localweights.ts';
168
169
  import { edgeLength } from './length.ts';
169
170
  import { skeletonLimbJoints } from './limbs.ts';
171
+ import { coalesceLimbSlots } from './limbslots.ts';
172
+ import { layoutAlias, placeLimbLayouts, type LayoutPlan } from './limblayout.ts';
170
173
  import { artCoverage, ART_ALPHA, latticeCells, latticeMesh, latticeStray, ONE_LOOP_PASSES } from './mesh.ts';
171
174
  import { bindFaceSurfaceDeform, BLINK, blinkHoldMisses, blinkSpan, CONTROL_SUFFIX, controlledBones, IDLE_FPS, idleMotion, type MotionSpec, moveKeysToControls } from './motion.ts';
172
175
  import { type AlternateSetMap, PAINTING_RUN, type PartsFile, readFrom, tagOf } from './parts.ts';
@@ -1077,6 +1080,8 @@ export interface AttachmentSetsFile {
1077
1080
 
1078
1081
  export interface RigOutput {
1079
1082
  rig: RigSpec;
1083
+ /** Internal explicit-layout provenance; serialized only as an external companion. */
1084
+ layout?: LayoutPlan;
1080
1085
  motion: MotionSpec;
1081
1086
  meshReport: MeshReport[];
1082
1087
  /** The padded images, by file name (`<part>.png`), in parts.json order. */
@@ -1693,6 +1698,11 @@ export function buildRig(
1693
1698
 
1694
1699
  // ---- attachments -------------------------------------------------------
1695
1700
  const slots: RigSpec['slots'] = [];
1701
+ const slotFamilies = new Map<string, string[]>();
1702
+ const addSlots = (part: string, ...rows: RigSpec['slots']): void => {
1703
+ slots.push(...rows);
1704
+ slotFamilies.set(part, [...(slotFamilies.get(part) ?? []), ...rows.map((s) => s.name)]);
1705
+ };
1696
1706
  const skin: RigSpec['skins']['default'] = {};
1697
1707
  const meshReport: MeshReport[] = [];
1698
1708
  const outImages: Array<[string, Raster]> = [];
@@ -2219,12 +2229,12 @@ export function buildRig(
2219
2229
  const cyUp = p.y + r / 2;
2220
2230
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cyLow) };
2221
2231
  skin[still] = { [still]: region(stillFile, sb.name, cx, cyUp) };
2222
- slots.push({ name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2232
+ addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name }, { name: still, bone: sb.name, attachment: still });
2223
2233
  continue;
2224
2234
  }
2225
2235
  const cy = p.y + p.h / 2;
2226
2236
  skin[p.name] = { [p.name]: region(file, bone.name, cx, cy) };
2227
- slots.push({ name: p.name, bone: bone.name, attachment: p.name });
2237
+ addSlots(p.name, { name: p.name, bone: bone.name, attachment: p.name });
2228
2238
  continue;
2229
2239
  }
2230
2240
  const segs = meshSegments.get(p.name) as Segment[];
@@ -2232,7 +2242,7 @@ export function buildRig(
2232
2242
  const row = autoAttachment(p, img, file, mesh.auto, mesh.r, mesh.exponent, segs, mesh.rule ?? 'distance', mesh, problems);
2233
2243
  if (row === null) continue;
2234
2244
  skin[p.name] = { [p.name]: row.attachment };
2235
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2245
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2236
2246
  meshReport.push(row.report);
2237
2247
  autoMotion.push(row.motion);
2238
2248
  continue;
@@ -2241,7 +2251,7 @@ export function buildRig(
2241
2251
  const row = contourAttachment(p, img, file, mesh.contour, mesh.r, mesh.exponent, segs, mesh.rule ?? 'distance', mesh, mesh.influences, problems);
2242
2252
  if (row === null) continue;
2243
2253
  skin[p.name] = { [p.name]: row.attachment };
2244
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2254
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2245
2255
  meshReport.push(row.report);
2246
2256
  continue;
2247
2257
  }
@@ -2249,7 +2259,7 @@ export function buildRig(
2249
2259
  const row = influenceAttachment(p, img, file, mesh, segs, meshSegmentEntries.get(p.name) as number[], problems);
2250
2260
  if (row === null) continue;
2251
2261
  skin[p.name] = { [p.name]: row.attachment };
2252
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2262
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2253
2263
  meshReport.push(row.report);
2254
2264
  continue;
2255
2265
  }
@@ -2329,7 +2339,7 @@ export function buildRig(
2329
2339
  const uvs: number[] = [];
2330
2340
  for (const [x, y] of lm.vertices) uvs.push(pyRound(x / w, 6), pyRound(y / h, 6));
2331
2341
  skin[p.name] = { [p.name]: { type: 'mesh', image: file, width: w, height: h, uvs, triangles: lm.triangles, hull: lm.hull, weights } };
2332
- slots.push({ name: p.name, bone: segs[0].bone, attachment: p.name });
2342
+ addSlots(p.name, { name: p.name, bone: segs[0].bone, attachment: p.name });
2333
2343
  meshReport.push({
2334
2344
  part: p.name,
2335
2345
  vertices: lm.vertices.length,
@@ -2558,14 +2568,19 @@ export function buildRig(
2558
2568
  };
2559
2569
  }
2560
2570
  const hasAlternateFaceSet = sets !== undefined && Object.values(sets.sets).some((e) => Object.hasOwn(e.slots, 'face'));
2571
+ // Read every base/alternate binding before rebinds; publish only the slot
2572
+ // permutation below, after stops/turn have used the original enumeration.
2573
+ const limbLayout = coalesceLimbSlots(cfg.limbs, bones, slots, skin);
2574
+ const explicitLayout = placeLimbLayouts(cfg.limbs, bones, limbLayout, skin, slotFamilies);
2561
2575
  // ---- leg stops (issue #404) --------------------------------------------
2562
2576
  // Only when the config has `stops`: each link after the first (and any bone hanging from a stopped link) hangs
2563
2577
  // from the drawn link `<link>_d` above it, and slots and weights on a stopped link bind `<link>_d`.
2564
- const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, slots, skin);
2578
+ const stops = cfg.stops === undefined ? null : applyStops(cfg.stops, chains, bones, slots, skin, (original, emitted) => layoutAlias(explicitLayout.plan, original, emitted));
2565
2579
  // ---- the turn control (issue #251) -------------------------------------
2566
2580
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2567
2581
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2568
2582
  const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, slots, skin, cfg.constraints ?? []);
2583
+ for (const row of turned?.rows ?? []) for (const t of row.twins) layoutAlias(explicitLayout.plan, t.bone, t.twin);
2569
2584
  // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2570
2585
  // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
2571
2586
  for (const row of meshReport) {
@@ -2580,7 +2595,7 @@ export function buildRig(
2580
2595
  images: 'images',
2581
2596
  skeleton: { x: -CX, y: 0, width: W, height: H },
2582
2597
  bones,
2583
- slots,
2598
+ slots: explicitLayout.slots,
2584
2599
  skins: { default: skin },
2585
2600
  };
2586
2601
  if (cfg.constraints !== undefined) rig.constraints = cfg.constraints.map(constraintForRig);
@@ -2633,6 +2648,7 @@ export function buildRig(
2633
2648
  faceAxis,
2634
2649
  turn: turned?.rows ?? null,
2635
2650
  ...(sets === undefined ? {} : { sets }),
2651
+ ...(explicitLayout.plan === undefined ? {} : { layout: explicitLayout.plan }),
2636
2652
  };
2637
2653
  }
2638
2654
 
@@ -2829,12 +2845,13 @@ function applyStops(
2829
2845
  bones: RigBone[],
2830
2846
  slots: RigSpec['slots'],
2831
2847
  skin: RigSpec['skins']['default'],
2848
+ alias?: (original: string, emitted: string) => void,
2832
2849
  ): RigStop[] {
2833
2850
  const out: RigStop[] = [];
2834
2851
  const drawn = new Map<string, string>();
2835
2852
  for (const s of stops) {
2836
2853
  const links = s.links ?? chains.get(s.chain) ?? [];
2837
- for (const l of links) drawn.set(l, `${l}_d`);
2854
+ for (const l of links) { drawn.set(l, `${l}_d`); alias?.(l, `${l}_d`); }
2838
2855
  out.push(stopForRig(s, links));
2839
2856
  }
2840
2857
  for (const b of bones) {