@rig-c/parts 1.55.2 → 1.57.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/config.ts CHANGED
@@ -260,6 +260,8 @@ export interface AlternateSetConfig {
260
260
  cuts?: Cut[];
261
261
  skeleton?: string;
262
262
  drawn?: Record<string, number>;
263
+ /** Explicit bone endpoints on this alternate painting, full source-crop pixels, x right/y down. */
264
+ tips?: Record<string, Point>;
263
265
  }
264
266
 
265
267
  export interface Assemble {
@@ -931,8 +933,15 @@ export interface LimbSplit {
931
933
  export interface Limb {
932
934
  segments: LimbSegment[];
933
935
  split?: LimbSplit;
936
+ /** Explicit rig-stage adjacency; absent, the existing limb closure is unchanged. */
937
+ layout?: LimbLayout;
934
938
  }
935
939
 
940
+ export type LimbLayoutTarget = { limb: string; part?: never } | { part: string; limb?: never };
941
+ export type LimbLayout = { parts?: string[] } & (
942
+ { before: LimbLayoutTarget; after?: never } | { after: LimbLayoutTarget; before?: never }
943
+ );
944
+
936
945
  export interface CharacterConfig {
937
946
  key: string;
938
947
  note?: string;
@@ -1349,6 +1358,9 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1349
1358
  // Issue #349: the limbs' joints are their bones' origins, so the bones are read with them, and only then.
1350
1359
  let limbs: LimbNames | null = null;
1351
1360
  let names: { bones: Set<string>; chains: Map<string, number>; parents: Map<string, string> } | null = null;
1361
+ const hasTips = isPlainObject(t.assemble) && Array.isArray(t.assemble.alternates) && t.assemble.alternates.some((a) => isPlainObject(a) && 'tips' in a);
1362
+ if (hasTips && !('bones' in t)) c.fail('CONFIG_FIELD_PRESENT', 'config.bones', 'is absent; alternate tips name declared bones, so assemble reads bones when tips are supplied');
1363
+ if (hasTips && 'bones' in t && !('limbs' in t)) names = checkBones(c, t.bones);
1352
1364
  if ('limbs' in t) {
1353
1365
  if (!('bones' in t)) c.fail('CONFIG_FIELD_PRESENT', 'config.bones', 'is absent; config.limbs names bones, and each joint is its bone\'s origin, so assemble reads the bones with the limbs');
1354
1366
  names = 'bones' in t ? checkBones(c, t.bones) : null;
@@ -1791,7 +1803,7 @@ export function parseProposalSections(raw: Json): SkeletonSections & { limbs?: R
1791
1803
  const taken = isPlainObject(top.limbs)
1792
1804
  ? Object.values(top.limbs).flatMap((l) => (isPlainObject(l) && Array.isArray(l.segments) ? l.segments.flatMap((sg) => (isPlainObject(sg) && typeof sg.from === 'string' ? [sg.from] : [])) : []))
1793
1805
  : [];
1794
- checkLimbs(c, top.limbs, { parts: [...new Set(taken)], patches: [], cuts: [] }, names);
1806
+ checkLimbs(c, top.limbs, { parts: [...new Set(taken)], patches: [], cuts: [] }, names, false);
1795
1807
  }
1796
1808
  if ('meshes' in top) checkMeshes(c, top.meshes, names.bones, names.chains);
1797
1809
  if ('regions' in top) checkRegions(c, top.regions, names.bones);
@@ -2125,7 +2137,7 @@ function checkAlternates(
2125
2137
  const seenNames = new Map<string, number>();
2126
2138
  (v as Json[]).forEach((entry, i) => {
2127
2139
  const at = `${p}[${i}]`;
2128
- const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn']);
2140
+ const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn', 'tips']);
2129
2141
  if (e === null) return;
2130
2142
  if ('name' in e && c.string(`${at}.name`, e.name)) {
2131
2143
  if (!partNameOk(e.name)) c.fail('CONFIG_PART_NAME', `${at}.name`, `names the set ${show(e.name)}; a set name is a file prefix, so it may not be empty, start with "." or hold a slash`);
@@ -2148,6 +2160,17 @@ function checkAlternates(
2148
2160
  }
2149
2161
  }
2150
2162
  }
2163
+ if ('tips' in e) {
2164
+ if (!isPlainObject(e.tips) || Object.keys(e.tips).length === 0) {
2165
+ c.fail('CONFIG_FIELD_TYPE', `${at}.tips`, `is ${show(e.tips)}; a non-empty object of declared bone name -> [x, y] in full source-crop pixels is required`);
2166
+ } else for (const [bone, point] of Object.entries(e.tips)) {
2167
+ const path = `${at}.tips.${bone}`;
2168
+ if (bones !== null && (bone === ROOT_BONE || !bones.has(bone))) c.fail('CONFIG_NAME_RESOLVES', path, `names "${bone}", which config.bones does not declare as a single bone or expanded chain link`);
2169
+ if (!Array.isArray(point) || point.length !== 2 || !point.every((n) => typeof n === 'number' && Number.isFinite(n))) {
2170
+ c.fail('CONFIG_FIELD_TYPE', path, `is ${show(point)}; a finite point [x, y] in full source-crop pixels is required`);
2171
+ }
2172
+ }
2173
+ }
2151
2174
  if ('head_box' in e) checkHeadBox(c, `${at}.head_box`, e.head_box);
2152
2175
  const altCuts = 'cuts' in e ? checkCuts(c, e.cuts, made.parts, [], `${at}.cuts`) : [];
2153
2176
  let cutsConsumedLimb = false;
@@ -2969,7 +2992,7 @@ interface LimbNames {
2969
2992
  * has two segments or more. With `names` null (no `bones`), bones are not
2970
2993
  * resolved. Returns the limb parts and the parts the limbs take.
2971
2994
  */
2972
- function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[]; cuts: string[] }, names: { bones: Set<string>; parents: Map<string, string> } | null): LimbNames {
2995
+ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[]; cuts: string[] }, names: { bones: Set<string>; parents: Map<string, string> } | null, resolveLayoutParts = true): LimbNames {
2973
2996
  const out: LimbNames = { parts: new Map(), consumed: new Map(), chains: new Map() };
2974
2997
  if (!isPlainObject(v)) {
2975
2998
  c.fail('CONFIG_FIELD_TYPE', 'config.limbs', `is ${show(v)}; an object of limb name -> {"segments": [...]} is required`);
@@ -2981,7 +3004,7 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
2981
3004
  const splitLimbs: string[] = [];
2982
3005
  for (const [limb, spec] of Object.entries(v)) {
2983
3006
  const at = `config.limbs.${limb}`;
2984
- const o = c.object(at, spec, ['segments'], ['split']);
3007
+ const o = c.object(at, spec, ['segments'], ['split', 'layout']);
2985
3008
  if (o === null) continue;
2986
3009
  if ('split' in o) {
2987
3010
  const sp = c.object(`${at}.split`, o.split, [], ['line', 'edge']);
@@ -3119,9 +3142,46 @@ function checkLimbs(c: Check, v: Json, made: { parts: string[]; patches: string[
3119
3142
  }
3120
3143
  }
3121
3144
  }
3145
+ checkLimbLayouts(c, v, made, out, resolveLayoutParts);
3122
3146
  return out;
3123
3147
  }
3124
3148
 
3149
+ /** Validate after every limb is known; a declaration may refer forward by name. */
3150
+ function checkLimbLayouts(c: Check, limbs: Record<string, Json>, made: { parts: string[]; patches: string[]; cuts: string[] }, names: LimbNames, resolveParts: boolean): void {
3151
+ const produced = new Set([...made.parts, ...made.patches, ...made.cuts].filter((n) => !names.consumed.has(n)));
3152
+ for (const n of names.parts.keys()) produced.add(n);
3153
+ for (const [limb, raw] of Object.entries(limbs)) {
3154
+ if (!isPlainObject(raw) || !('layout' in raw)) continue;
3155
+ const at = `config.limbs.${limb}.layout`;
3156
+ const l = c.object(at, raw.layout, [], ['before', 'after', 'parts']);
3157
+ if (l === null) continue;
3158
+ const sides = ['before', 'after'].filter((s) => s in l);
3159
+ if (sides.length !== 1) c.fail('CONFIG_LAYOUT_TARGET', at, 'exactly one of before or after is required; it means immediate setup-slot adjacency');
3160
+ for (const side of sides) {
3161
+ const t = c.object(`${at}.${side}`, l[side], [], ['limb', 'part']);
3162
+ if (t === null) continue;
3163
+ const keys = ['limb', 'part'].filter((k) => k in t);
3164
+ if (keys.length !== 1) { c.fail('CONFIG_LAYOUT_TARGET', `${at}.${side}`, 'exactly one typed target, {limb: name} or {part: name}, is required'); continue; }
3165
+ const k = keys[0], n = t[k];
3166
+ if (!c.string(`${at}.${side}.${k}`, n)) continue;
3167
+ if (k === 'limb' ? !Object.hasOwn(limbs, n) : resolveParts && !produced.has(n)) {
3168
+ const consumed = names.consumed.get(n);
3169
+ c.fail('CONFIG_LAYOUT_NAME', `${at}.${side}.${k}`, `names "${n}"; ${k === 'limb' ? `a declared limb (${Object.keys(limbs).join(', ')})` : `a produced part (${[...produced].join(', ')})`} is required${consumed === undefined ? '' : `; "${n}" is consumed by limb "${consumed}" into ${names.chains.get(consumed)?.parts.join(', ')}`}`);
3170
+ }
3171
+ }
3172
+ if (!('parts' in l)) continue;
3173
+ const own = names.chains.get(limb)?.parts ?? [];
3174
+ if (!Array.isArray(l.parts) || l.parts.length === 0 || !l.parts.every((p) => typeof p === 'string' && own.includes(p))) {
3175
+ c.fail('CONFIG_LAYOUT_SCOPE', `${at}.parts`, `is ${show(l.parts)}; a nonempty list of this limb's source-bound segment parts (${own.join(', ')}) is required; rider names are not selectors`);
3176
+ continue;
3177
+ }
3178
+ const positions = l.parts.map((p) => own.indexOf(p as string)).sort((a, b) => a - b);
3179
+ if (new Set(positions).size !== positions.length || positions.some((p, i) => i > 0 && p !== positions[i - 1] + 1)) {
3180
+ c.fail('CONFIG_LAYOUT_SCOPE', `${at}.parts`, `is ${show(l.parts)}; distinct consecutive segment-part references in ${own.join(', ')} are required`);
3181
+ }
3182
+ }
3183
+ }
3184
+
3125
3185
  /**
3126
3186
  * Every plan part — and every cut's piece, which the caller lists with them —
3127
3187
  * is exactly one of a mesh or a region, every patch is a region, and every
@@ -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
+ }
package/src/limbs.ts CHANGED
@@ -115,6 +115,7 @@
115
115
  * crossing.
116
116
  */
117
117
  import type { BoneEntry, Limb, LimbSplit } from './config.ts';
118
+ import { refuseIfAny, type Problem } from './errors.ts';
118
119
  import { edgeLength } from './length.ts';
119
120
  import { pyRound } from './round.ts';
120
121
  import type { KeypointName, PosePoints } from './skeleton.ts';
@@ -128,13 +129,24 @@ export interface BonePlace {
128
129
  }
129
130
 
130
131
  /** Where every bone `bones` declares sits and ends (module comment). */
131
- export function bonePlaces(bones: readonly BoneEntry[]): Map<string, BonePlace> {
132
+ export function bonePlaces(bones: readonly BoneEntry[], tips?: Readonly<Record<string, readonly [number, number]>>): Map<string, BonePlace> {
132
133
  const out = new Map<string, BonePlace>();
133
134
  for (const b of bones) {
134
135
  if ('chain' in b) {
135
136
  b.points.forEach((p, k) => out.set(`${b.chain}${k}`, { at: [p[0], p[1]], end: k + 1 < b.points.length ? [b.points[k + 1][0], b.points[k + 1][1]] : [b.tip[0], b.tip[1]] }));
136
137
  } else out.set(b.name, { at: [b.at[0], b.at[1]], end: b.tip === undefined ? null : [b.tip[0], b.tip[1]] });
137
138
  }
139
+ // Explicit alternate endpoints overlay the already placed bones. Origins and
140
+ // following chain-link joints stay where the existing pose put them.
141
+ const problems: Problem[] = [];
142
+ for (const [bone, tip] of Object.entries(tips ?? {})) {
143
+ const place = out.get(bone);
144
+ const validPoint = Array.isArray(tip) && tip.length === 2 && tip.every((n) => typeof n === 'number' && Number.isFinite(n));
145
+ if (place === undefined) problems.push({ code: 'ASSEMBLE_ALT_TIP_NAME', object: `alternate tips.${bone}`, detail: `names "${bone}", which the supplied bones do not declare` });
146
+ if (!validPoint) problems.push({ code: 'ASSEMBLE_ALT_TIP_POINT', object: `alternate tips.${bone}`, detail: 'requires a finite [x, y] endpoint in rig-crop pixels' });
147
+ if (place !== undefined && validPoint) out.set(bone, { at: place.at, end: [tip[0], tip[1]] });
148
+ }
149
+ refuseIfAny(problems);
138
150
  return out;
139
151
  }
140
152
 
@@ -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
@@ -304,6 +304,10 @@ export interface AlternatePartsRecord {
304
304
  scene?: SceneRecord;
305
305
  single_run_pad?: SingleRunPad;
306
306
  skeleton?: PosePoints;
307
+ /** Explicit endpoints normalized once into this parts file's rig-crop frame. */
308
+ tips?: Record<string, [number, number]>;
309
+ /** Source dimensions used to normalize tips onto rig_size; required with tips. */
310
+ tips_source_size?: [number, number];
307
311
  drawn?: Record<string, number>;
308
312
  /** Issue #539: as `sets.json`'s; written only when `skeleton` placed the set's limb bones. */
309
313
  drawnLength?: Record<string, number>;
@@ -455,6 +459,8 @@ export function serializeParts(file: PartsFile): string {
455
459
  ...(a.single_run_pad === undefined ? {} : { single_run_pad: Object.fromEntries(SINGLE_RUN_PAD_KEYS.map((k) => [k, (a.single_run_pad as SingleRunPad)[k]])) }),
456
460
  ...(a.skeleton === undefined ? {} : { skeleton: Object.fromEntries(KEYPOINT_NAMES.map((k) => [k, (a.skeleton as PosePoints)[k]])) }),
457
461
  ...(a.drawn === undefined ? {} : { drawn: a.drawn }),
462
+ ...(a.tips_source_size === undefined ? {} : { tips_source_size: a.tips_source_size }),
463
+ ...(a.tips === undefined ? {} : { tips: Object.fromEntries(Object.keys(a.tips).sort().map((bone) => [bone, (a.tips as Record<string, [number, number]>)[bone]])) }),
458
464
  ...(a.drawnLength === undefined ? {} : { drawnLength: a.drawnLength }),
459
465
  ...(a.registration === undefined ? {} : { registration: { offset: a.registration.offset, scale: a.registration.scale } }),
460
466
  })),
@@ -672,8 +678,26 @@ function checkParts(raw: unknown, path: string): PartsFile {
672
678
  o.alternates.forEach((a, i) => {
673
679
  if (typeof a !== 'object' || a === null || Array.isArray(a)) return;
674
680
  const set = a as Record<string, unknown>;
675
- if (!Array.isArray(set.records)) return;
676
681
  const at = `${path} alternates[${i}]${typeof set.name === 'string' ? ` (set "${set.name}")` : ''}`;
682
+ if ('tips' in set || 'tips_source_size' in set) {
683
+ const sourceSize = set.tips_source_size;
684
+ if (!('tips' in set) || !Array.isArray(sourceSize) || sourceSize.length !== 2 || !sourceSize.every((n) => typeof n === 'number' && Number.isInteger(n) && n > 0)) {
685
+ fail('PARTS_ALT_TIPS_SOURCE', `${at} tips_source_size`, 'requires the positive integer [source_width, source_height] used to normalize the tips; re-run assemble');
686
+ } else if (sizeOk && typeof scale === 'number' && (Math.trunc(sourceSize[0] * scale) !== (size as number[])[0] || Math.trunc(sourceSize[1] * scale) !== (size as number[])[1])) {
687
+ fail('PARTS_ALT_TIPS_SOURCE', `${at} tips_source_size`, 'does not produce rig_size at scale_rig_per_source; re-run assemble rather than guessing the normalization ratio');
688
+ }
689
+ }
690
+ if ('tips' in set) {
691
+ const t = set.tips;
692
+ if (typeof t !== 'object' || t === null || Array.isArray(t) || Object.keys(t).length === 0) {
693
+ fail('PARTS_ALT_TIPS', `${at} tips`, 'requires a non-empty bone-name map of finite [x, y] endpoints in rig-crop pixels');
694
+ } else for (const [bone, point] of Object.entries(t)) {
695
+ if (!Array.isArray(point) || point.length !== 2 || !point.every((n) => typeof n === 'number' && Number.isFinite(n))) {
696
+ fail('PARTS_ALT_TIPS', `${at} tips.${bone}`, 'requires a finite [x, y] endpoint in rig-crop pixels');
697
+ }
698
+ }
699
+ }
700
+ if (!Array.isArray(set.records)) return;
677
701
  set.records.forEach((p, j) => {
678
702
  if (typeof p !== 'object' || p === null || Array.isArray(p)) return;
679
703
  const r = p as Record<string, unknown>;