@rig-c/parts 1.60.1 → 1.61.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.
@@ -31,7 +31,7 @@ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
31
31
  import { join } from 'node:path';
32
32
  import type { ControlPose, PaintConfig } from '../config.ts';
33
33
  import { type Problem, refuseIfAny } from '../errors.ts';
34
- import { buildPrompts, checkGraph, paintingGraph, resolvedControl, resolvedLoras, resolvedSampler } from '../graphs.ts';
34
+ import { buildPrompts, checkGraph, paintingGraph, resolvedControl, resolvedLoras, resolvedSampler, UPSCALE_MODEL, UPSCALE_THEN } from '../graphs.ts';
35
35
  import { decodePngBytes, encodePngBytes } from '../raster/png.ts';
36
36
  import { isSkeletonName, renderSkeleton } from '../skeleton.ts';
37
37
  import { ComfyClient, historyImages, refuse } from './client.ts';
@@ -112,6 +112,7 @@ export async function runPainting(client: ComfyClient, run: PaintRun, say: (line
112
112
  checkpoint: g.checkpoint,
113
113
  loras: resolvedLoras(g.loras),
114
114
  sampler: resolvedSampler(g.sampler),
115
+ upscale: { model: UPSCALE_MODEL, then: UPSCALE_THEN },
115
116
  control,
116
117
  pose_from: prompts.poseFrom,
117
118
  dropped: prompts.dropped,
package/src/config.ts CHANGED
@@ -100,6 +100,19 @@ import { FLOOR_FORMS, type FloorForm, type MeshInfluences } from './weights.ts';
100
100
 
101
101
  export type Point = [number, number];
102
102
 
103
+ /** A rigid binding; the object form can keep an exclusive rider in authored order (#680). */
104
+ export type RegionSpec = string | { bone: string; gather?: false };
105
+
106
+ /** Read a declared region binding without changing the authored representation. */
107
+ export function regionBone(region: RegionSpec): string {
108
+ return typeof region === 'string' ? region : region.bone;
109
+ }
110
+
111
+ /** The raw reader keeps invalid values intact for their own named refusal. */
112
+ function rawRegionBone(region: Json): Json {
113
+ return isPlainObject(region) ? region.bone : region;
114
+ }
115
+
103
116
  export interface Lora {
104
117
  name: string;
105
118
  strength: number;
@@ -255,10 +268,14 @@ export interface AlternateSetConfig {
255
268
  full?: string;
256
269
  head?: string;
257
270
  parts?: string[];
271
+ /** Per covered output part, the layer in its existing source run (issue #666). */
272
+ layers?: Record<string, string>;
258
273
  hides?: string[];
259
274
  head_box?: [number, number, number, number];
260
275
  cuts?: Cut[];
261
276
  skeleton?: string;
277
+ /** One or two skeleton keypoints paired with declared base-bone origins (issue #543). */
278
+ anchor?: Partial<Record<KeypointName, string>>;
262
279
  drawn?: Record<string, number>;
263
280
  /** Explicit bone endpoints on this alternate painting, full source-crop pixels, x right/y down. */
264
281
  tips?: Record<string, Point>;
@@ -329,7 +346,7 @@ export type Segment = string | [string, Point, Point];
329
346
  * locally refined by rig-c's `reduceMesh` under the author's declared
330
347
  * bounds (`src/automesh.ts`).
331
348
  */
332
- export type MeshSpec = LatticeMeshSpec | ContourMeshSpec | AutoMeshSpec | InfluenceMeshSpec;
349
+ export type MeshSpec = (LatticeMeshSpec | ContourMeshSpec | AutoMeshSpec | InfluenceMeshSpec) & { gather?: false };
333
350
 
334
351
  /**
335
352
  * One mesh in the influence mode (issue #378): rig-c's `segments` lattice over the part at `cell` px, every vertex
@@ -701,7 +718,7 @@ export function weightsABone(rg: AutoRegionSpec): rg is AutoWeightRegionSpec {
701
718
  export interface PartBinding {
702
719
  bones: readonly BoneEntry[];
703
720
  meshes: Readonly<Record<string, MeshSpec>>;
704
- regions: Readonly<Record<string, string>>;
721
+ regions: Readonly<Record<string, RegionSpec>>;
705
722
  }
706
723
 
707
724
  /**
@@ -732,7 +749,7 @@ export function partBoundBones(b: PartBinding): Map<string, string[]> {
732
749
  if ('contour' in m) for (const rg of contourRegionsOf(m.contour)) bind(part, rg.bone);
733
750
  if ('auto' in m) for (const rg of m.auto.regions ?? []) if (weightsABone(rg)) bind(part, rg.bone);
734
751
  }
735
- for (const [part, bone] of Object.entries(b.regions)) bind(part, bone);
752
+ for (const [part, region] of Object.entries(b.regions)) bind(part, regionBone(region));
736
753
  return out;
737
754
  }
738
755
 
@@ -971,7 +988,7 @@ export interface CharacterConfig {
971
988
  limbs?: Record<string, Limb>;
972
989
  bones: BoneEntry[];
973
990
  meshes: Record<string, MeshSpec>;
974
- regions: Record<string, string>;
991
+ regions: Record<string, RegionSpec>;
975
992
  motion: Motion;
976
993
  constraints?: ConfigConstraint[];
977
994
  /** Leg stops (issue #404, rig-c 2.56.0's `RigStop`): absent, no stop is added and no byte of any output moves. */
@@ -1796,7 +1813,7 @@ export function repeatedKeys(text: string): Array<{ at: string; key: string; cou
1796
1813
  export interface SkeletonSections {
1797
1814
  bones: BoneEntry[];
1798
1815
  meshes: Record<string, MeshSpec>;
1799
- regions: Record<string, string>;
1816
+ regions: Record<string, RegionSpec>;
1800
1817
  motion: Motion;
1801
1818
  }
1802
1819
 
@@ -1860,7 +1877,7 @@ function checkBlinkStill(c: Check, v: Json, eyes: Json, bones: Set<string>, regi
1860
1877
  c.fail('CONFIG_STILL_OFF_THE_BLINK', `${at}.${part}.bone`, `is "${e.bone}", which config.motion.blink.eyes names, so the still piece would blink too; a bone the blink does not key is required (the eye bone's parent, as propose writes it)`);
1861
1878
  }
1862
1879
  }
1863
- const rb = Object.prototype.hasOwnProperty.call(regionOf, part) ? regionOf[part] : undefined;
1880
+ const rb = Object.prototype.hasOwnProperty.call(regionOf, part) ? rawRegionBone(regionOf[part]) : undefined;
1864
1881
  if (typeof rb !== 'string') {
1865
1882
  c.fail('CONFIG_NAME_RESOLVES', `${at}.${part}`, `names "${part}", which config.regions does not attach; a region part is required — a mesh is not cut`);
1866
1883
  } else if (!eyeList.includes(rb)) {
@@ -2156,7 +2173,7 @@ function checkAlternates(
2156
2173
  const seenNames = new Map<string, number>();
2157
2174
  (v as Json[]).forEach((entry, i) => {
2158
2175
  const at = `${p}[${i}]`;
2159
- const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'drawn', 'tips', 'front']);
2176
+ const e = c.object(at, entry, ['name'], ['source', 'full', 'head', 'parts', 'hides', 'head_box', 'cuts', 'skeleton', 'anchor', 'drawn', 'tips', 'front', 'layers']);
2160
2177
  if (e === null) return;
2161
2178
  if ('name' in e && c.string(`${at}.name`, e.name)) {
2162
2179
  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`);
@@ -2166,6 +2183,16 @@ function checkAlternates(
2166
2183
  for (const k of ['source', 'full', 'head', 'skeleton'] as const) {
2167
2184
  if (k in e) c.string(`${at}.${k}`, e[k]);
2168
2185
  }
2186
+ if ('anchor' in e) {
2187
+ if (!('skeleton' in e)) c.fail('CONFIG_FIELD_PRESENT', `${at}.skeleton`, 'is absent; anchor registers a skeleton set and requires its skeleton file');
2188
+ const a = e.anchor;
2189
+ if (!isPlainObject(a) || Object.keys(a).length < 1 || Object.keys(a).length > 2) {
2190
+ c.fail('CONFIG_FIELD_TYPE', `${at}.anchor`, `is ${show(a)}; one or two keypoint name -> declared base bone entries are required`);
2191
+ } else for (const [keypoint, bone] of Object.entries(a)) {
2192
+ if (!(KEYPOINT_NAMES as readonly string[]).includes(keypoint)) c.fail('CONFIG_KEY_KNOWN', `${at}.anchor.${keypoint}`, `is not a body-18 keypoint; one of ${KEYPOINT_NAMES.join(', ')} is required`);
2193
+ if (typeof bone !== 'string' || (bones !== null && !bones.has(bone))) c.fail('CONFIG_NAME_RESOLVES', `${at}.anchor.${keypoint}`, `names ${show(bone)}; a bone config.bones declares is required`);
2194
+ }
2195
+ }
2169
2196
  if ('drawn' in e) {
2170
2197
  const d = e.drawn;
2171
2198
  if (!isPlainObject(d) || Object.keys(d).length === 0) {
@@ -2247,6 +2274,16 @@ function checkAlternates(
2247
2274
  } else seenHides.add(hn);
2248
2275
  });
2249
2276
  }
2277
+ if ('layers' in e) {
2278
+ if (!isPlainObject(e.layers)) c.fail('CONFIG_FIELD_TYPE', `${at}.layers`, `is ${show(e.layers)}; an object of covered part -> layer name is required`);
2279
+ else for (const [part, layer] of Object.entries(e.layers)) {
2280
+ const path = `${at}.layers.${part}`;
2281
+ const covered = ('parts' in e ? seenParts : allSlots).has(part) && !seenHides.has(part);
2282
+ if (!covered) c.fail('CONFIG_SET_LAYERS', path, `names "${part}", which the set does not cover; name a covered, nonhidden part`);
2283
+ if (made.patches.includes(part)) c.fail('CONFIG_SET_LAYERS', path, `names the painting patch "${part}", which has no run layer source; declare a layer-backed plan part instead`);
2284
+ if (typeof layer !== 'string' || readLayerTag(layer) === null) c.fail('CONFIG_TAG_KNOWN', path, `is ${show(layer)}; a See-through v3 tag or "${AUTHOR_PREFIX}<label>" is required; ${AUTHOR_LABEL_RULE}`);
2285
+ }
2286
+ }
2250
2287
  // Issue #664: a part the set draws on its front slot is one the set covers and a limb declares a front slot for.
2251
2288
  if ('front' in e) {
2252
2289
  if (!Array.isArray(e.front) || e.front.length === 0) {
@@ -2295,8 +2332,8 @@ function checkAlternates(
2295
2332
  const limbSeg = limbs?.parts.get(pn);
2296
2333
  if (limbSeg !== undefined) {
2297
2334
  coveredBones.add(limbSeg.bone);
2298
- } else if (isPlainObject(regions) && typeof regions[pn] === 'string') {
2299
- coveredBones.add(regions[pn]);
2335
+ } else if (isPlainObject(regions) && typeof rawRegionBone(regions[pn]) === 'string') {
2336
+ coveredBones.add(rawRegionBone(regions[pn]) as string);
2300
2337
  } else if (isPlainObject(meshes) && isPlainObject(meshes[pn])) {
2301
2338
  const m = meshes[pn] as Record<string, Json>;
2302
2339
  if (Array.isArray(m.segments)) {
@@ -2491,8 +2528,9 @@ function checkMeshes(c: Check, v: Json, bones: Set<string>, chains: Map<string,
2491
2528
  const at = `config.meshes.${part}`;
2492
2529
  // The known keys keep their old order (grid, r, segments) with contour after them, and `r` and `segments` are
2493
2530
  // required in the place and words the object check uses, so a lattice mesh's refusals read as they did.
2494
- const m = c.object(at, spec, [], ['grid', 'r', 'segments', 'contour', 'auto', 'exponent', 'rule', 'ribs', 'influences', 'stray', 'influence']);
2531
+ const m = c.object(at, spec, [], ['grid', 'r', 'segments', 'contour', 'auto', 'exponent', 'rule', 'ribs', 'influences', 'stray', 'influence', 'gather']);
2495
2532
  if (m === null) continue;
2533
+ checkGather(c, at, m);
2496
2534
  // issue #378: the influence mode weights by rig-c's own pull, so `r` (the distance rule's softening) is not one of its
2497
2535
  // fields — it is refused there below, and required in every other mode as it always was.
2498
2536
  for (const key of 'influence' in m ? ['segments'] : ['r', 'segments']) if (!(key in m)) c.fail('CONFIG_FIELD_PRESENT', `${at}.${key}`, 'is absent and required');
@@ -2800,11 +2838,34 @@ function checkContour(c: Check, at: string, v: Json, bones: Set<string>): void {
2800
2838
  const bandR = RR - rR;
2801
2839
  const bandL = RL - rL;
2802
2840
  if (clearance <= 0 || RR + RL >= D || rR <= 0 || rL <= 0 || bandR < 0 || bandL < 0) {
2803
- const minClearance = Math.max(0, (dR + dL - D) / 2);
2841
+ // Invalid coordinates already have named problems, but c.point accepts any finite pair.
2842
+ // Restrict only this diagnostic search to onGrid's existing domain, not the refusal rule.
2843
+ let remedy = `clearance hint unavailable: correct the CONFIG_FIELD_TYPE landmark coordinates to the 1/${GRID} px grid within ±${MAX_SIDE} px first`;
2844
+ if ([rx, ry, lx, ly, kx, ky].every((n) => Number.isInteger(n * GRID) && Math.abs(n) <= MAX_SIDE)) {
2845
+ let low = 1;
2846
+ let high = Math.ceil(Math.max(dR, dL) * 100) + 100;
2847
+ // The coordinate domain bounds high below 2^24; binary search needs at most 24 steps.
2848
+ const maxSteps = Math.ceil(Math.log2(high));
2849
+ for (let step = 0; low < high && step < maxSteps; step++) {
2850
+ const mid = low + Math.floor((high - low) / 2);
2851
+ if (Math.round(dR - mid / 100) + Math.round(dL - mid / 100) < D) high = mid;
2852
+ else low = mid + 1;
2853
+ }
2854
+ if (low === high) {
2855
+ const candidate = low / 100;
2856
+ const nextRR = Math.round(dR - candidate);
2857
+ const nextRL = Math.round(dL - candidate);
2858
+ const nextR = Math.round(alpha * nextRR);
2859
+ const nextL = Math.round(alpha * nextRL);
2860
+ remedy = nextRR + nextRL < D && nextR > 0 && nextL > 0 && nextRR - nextR >= 0 && nextRL - nextL >= 0
2861
+ ? `the first passing clearance in 0.01 px steps is ${candidate} px for these landmarks and alpha; set clearance to that value`
2862
+ : 'no clearance in 0.01 px steps meets all these rounded-radius checks; move cleavage or the apices, or change alpha, and retry';
2863
+ }
2864
+ }
2804
2865
  c.fail(
2805
2866
  'CONFIG_BUST_CLEARANCE',
2806
2867
  `${bat}.clearance`,
2807
- `is ${clearance} (giving R_r = ${RR}, R_l = ${RL}, R_r + R_l = ${RR + RL} px against apex distance D = ${pyRound(D, 2)} px, r_r = ${rR}, band_r = ${bandR}, r_l = ${rL}, band_l = ${bandL}); a clearance > 0 with R_r + R_l < D (clearance > ${pyRound(minClearance, 2)} px) and positive radii is required`,
2868
+ `is ${clearance} (giving R_r = ${RR}, R_l = ${RL}, R_r + R_l = ${RR + RL} px against apex distance D = ${pyRound(D, 2)} px, r_r = ${rR}, band_r = ${bandR}, r_l = ${rL}, band_l = ${bandL}); a clearance > 0 with R_r + R_l < D and positive core radii and non-negative bands is required; ${remedy}`,
2808
2869
  );
2809
2870
  }
2810
2871
  }
@@ -2991,12 +3052,23 @@ function checkAuto(c: Check, at: string, v: Json, bones: Set<string>): void {
2991
3052
  }
2992
3053
  }
2993
3054
 
3055
+ /** Only false opts out; remove the key for the historical gathering rule. */
3056
+ function checkGather(c: Check, at: string, entry: Record<string, Json>): void {
3057
+ if ('gather' in entry && entry.gather !== false) c.fail('CONFIG_FIELD_TYPE', `${at}.gather`, `is ${show(entry.gather)}; false is required to keep a limb rider at its authored draw position — remove gather for normal gathering`);
3058
+ }
3059
+
2994
3060
  function checkRegions(c: Check, v: Json, bones: Set<string>): void {
2995
3061
  if (typeof v !== 'object' || v === null || Array.isArray(v)) {
2996
3062
  c.fail('CONFIG_FIELD_TYPE', 'config.regions', `is ${show(v)}; an object of part name -> bone name is required`);
2997
3063
  return;
2998
3064
  }
2999
- for (const [part, bone] of Object.entries(v as Record<string, Json>)) {
3065
+ for (const [part, entry] of Object.entries(v as Record<string, Json>)) {
3066
+ const at = `config.regions.${part}`;
3067
+ if (isPlainObject(entry)) {
3068
+ const o = c.object(at, entry, ['bone'], ['gather']);
3069
+ if (o !== null) checkGather(c, at, o);
3070
+ }
3071
+ const bone = rawRegionBone(entry);
3000
3072
  if (typeof bone !== 'string') c.fail('CONFIG_NAME_RESOLVES', `config.regions.${part}`, `is ${show(bone)}; a bone name is required`);
3001
3073
  // Issue #671: the part and the bone by name, so an entry `propose --only-missing` drafted on a bone the config
3002
3074
  // does not declare says which.
@@ -3295,7 +3367,7 @@ function checkCoverage(c: Check, made: string[], patches: string[], meshes: Json
3295
3367
  }
3296
3368
  }
3297
3369
  for (const [part, seg] of limbs.parts) {
3298
- const bone = isPlainObject(regions) ? regions[part] : undefined;
3370
+ const bone = isPlainObject(regions) ? rawRegionBone(regions[part]) : undefined;
3299
3371
  if (typeof bone === 'string' && bone !== seg.bone) {
3300
3372
  c.fail('CONFIG_LIMB_BONE', `config.regions.${part}`, `is "${bone}"; "${part}" is ${seg.at}, which rides "${seg.bone}" with weight 1, so config.regions.${part} "${seg.bone}" is required`);
3301
3373
  }
@@ -1,16 +1,18 @@
1
1
  /**
2
- * The three config updates proposed by the CLI (issue #356). Pure JSON merge:
2
+ * The config updates proposed by the CLI (issues #356, #671, #679):
3
3
  * no file reads/writes and no substitute for the stage's existing validator.
4
4
  * A present proposal section replaces that whole field; an absent optional
5
5
  * section is retained. `proposal-missing` (issue #671, `--only-missing`) instead
6
- * adds only the `meshes` / `regions` entries of proposed parts the config attaches
7
- * by neither, one edit per entry, and leaves every existing entry as it is. The caller supplies the proposer's own section tuple,
6
+ * adds only resolvable `meshes` / `regions` entries for parts not already attached
7
+ * by meshes, regions, limbs or patches, and appends skip diagnostics to the
8
+ * proposal notes. The caller supplies the proposer's own section tuple,
8
9
  * avoiding a second policy list or a runtime import of the proposer graph.
9
10
  */
10
11
  import type { PlanProposal } from './assemble.ts';
11
12
  import type { HeadBoxProposal } from './headbox.ts';
12
13
  import type { Proposal, PROPOSAL_CONFIG_SECTIONS } from './propose.ts';
13
14
  import { PartsError } from './errors.ts';
15
+ import { parseProposalSections } from './config.ts';
14
16
  import type { ConfigEdit } from './meshdraft.ts';
15
17
 
16
18
  export type ConfigJson = null | boolean | number | string | ConfigJson[] | ConfigObject;
@@ -19,7 +21,7 @@ export type ConfigWritePatch =
19
21
  | { kind: 'head-box'; head_box: HeadBoxProposal['head_box'] }
20
22
  | { kind: 'assemble-plan'; plan: PlanProposal['plan']; extend_below_crop: PlanProposal['extend_below_crop'] }
21
23
  | { kind: 'proposal'; proposal: Proposal; sections: typeof PROPOSAL_CONFIG_SECTIONS }
22
- /** Issue #671 (`--only-missing`): only `meshes.<part>` / `regions.<part>` for a proposed part the config attaches by neither. */
24
+ /** Issues #671/#679: add unattached, resolvable entries; append skip explanations to the proposal's notes for the caller to print. */
23
25
  | { kind: 'proposal-missing'; proposal: Proposal; parts: ReadonlyArray<{ name: string; from: string }> };
24
26
  export interface ConfigWriteChange {
25
27
  path: string;
@@ -118,13 +120,52 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
118
120
  break;
119
121
  }
120
122
  case 'proposal-missing': {
121
- // Issue #671: a config proposed before a part existed (the #490 arm split's drape_<s> and hand_<s>) gains its
122
- // plan row (split parts only) and an entry for that part alone, entry by entry, in the section the proposal drafts
123
- // it in. A part the config already attaches, by either section, keeps its entry as written; nothing else of the
124
- // proposal is read.
125
- const attached = (part: string): boolean => (object(config.meshes) && own(config.meshes, part)) || (object(config.regions) && own(config.regions, part));
123
+ // Read attachment ownership from the destination, even without --keypoints. A limb's source is consumed;
124
+ // the loader requires regions for its segment parts instead. Patches are always regions.
125
+ const attachments = new Map<string, string>();
126
126
  for (const section of ['meshes', 'regions'] as const) {
127
127
  if (config[section] !== undefined && !object(config[section])) return refuse(`config.${section}`, 'is not an object; an object of part entries is required before an entry is added to it');
128
+ if (object(config[section])) for (const part of Object.keys(config[section])) attachments.set(part, field(`config.${section}`, part));
129
+ }
130
+ if (object(config.limbs)) for (const [limb, spec] of Object.entries(config.limbs)) {
131
+ if (object(spec) && Array.isArray(spec.segments)) for (const segment of spec.segments) {
132
+ if (object(segment) && typeof segment.from === 'string') attachments.set(segment.from, `${field('config.limbs', limb)} (source cut into its segment parts)`);
133
+ }
134
+ }
135
+ if (object(config.assemble) && Array.isArray(config.assemble.patches)) for (const patch of config.assemble.patches) {
136
+ if (object(patch) && typeof patch.name === 'string') attachments.set(patch.name, 'config.assemble.patches (a patch is always a region)');
137
+ }
138
+ // This mode appends diagnostics to the proposal's existing notes output, never to the destination config.
139
+ const note = (part: string, why: string): void => {
140
+ const line = `--only-missing: skipped part "${part}" — ${why}; no entry or plan row added`;
141
+ if (!patch.proposal.notes.includes(line)) patch.proposal.notes.push(line);
142
+ };
143
+ const proposed = new Set([...patch.parts.map((p) => p.name), ...Object.keys(patch.proposal.meshes), ...Object.keys(patch.proposal.regions), ...Object.values(patch.proposal.limbs ?? {}).flatMap((l) => l.segments.map((s) => s.from))]);
144
+ for (const part of proposed) {
145
+ const by = attachments.get(part);
146
+ if (by !== undefined) note(part, `already attached by ${by}`);
147
+ }
148
+ const entries: Array<{ section: 'meshes' | 'regions'; part: string; value: ConfigJson }> = [];
149
+ const accepted = new Set<string>();
150
+ for (const section of ['meshes', 'regions'] as const) for (const [part, entry] of Object.entries(patch.proposal[section])) {
151
+ if (attachments.has(part) || accepted.has(part)) continue;
152
+ const value = clone(entry, field(`proposal.${section}`, part));
153
+ // Reuse the loader's own bone/chain expansion and mesh reference checks (including auto region names),
154
+ // against CONFIG bones, never the draft's bones. Coverage and all retained fields still pass through the
155
+ // caller's full config gate. Other entries are absent here so a forward dependency cannot leak from a draft.
156
+ try {
157
+ parseProposalSections({ bones: config.bones, meshes: section === 'meshes' ? { [part]: value } : {}, regions: section === 'regions' ? { [part]: value } : {}, motion: config.motion });
158
+ } catch (error) {
159
+ if (!(error instanceof PartsError)) throw error;
160
+ const at = `proposal.${section}.${part}`;
161
+ const problems = error.problems.filter((p) => p.object === at || p.object.startsWith(`${at}.`) || p.object.startsWith(`${at}[`));
162
+ if (problems.length > 0) {
163
+ note(part, problems.map((p) => `${p.code}: ${p.object.replace(/^proposal\./, 'config.')} — ${p.detail}`).join('; '));
164
+ continue;
165
+ }
166
+ }
167
+ entries.push({ section, part, value });
168
+ accepted.add(part);
128
169
  }
129
170
  const added: ConfigWriteChange[] = [];
130
171
  // The #490 split's parts the plan does not name, each row where `mergedArmSplitPlan` puts it: the drape just
@@ -135,6 +176,7 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
135
176
  const row = (e: ConfigJson): [string, string, string] | null =>
136
177
  Array.isArray(e) && e.length === 3 && e.every((x) => typeof x === 'string') ? (e as [string, string, string]) : null;
137
178
  for (const part of patch.parts) {
179
+ if (!accepted.has(part.name)) continue;
138
180
  const m = /^full:(drape|hand)-([rl])$/.exec(part.from);
139
181
  if (m === null) continue;
140
182
  if (plan.some((e) => { const r = row(e); return r !== null && (r[0] === part.name || (r[1] === 'full' && r[2] === `${m[1]}-${m[2]}`)); })) continue;
@@ -147,15 +189,11 @@ export function mergeConfigProposal(raw: unknown, patch: ConfigWritePatch): Conf
147
189
  added.push({ path: `assemble.plan[${at}]`, kind: 'added', value: JSON.stringify(value) });
148
190
  }
149
191
  }
150
- for (const section of ['meshes', 'regions'] as const) {
151
- for (const [part, entry] of Object.entries(patch.proposal[section])) {
152
- if (attached(part)) continue;
153
- const value = clone(entry, field(`proposal.${section}`, part));
154
- if (!object(config[section])) config[section] = {};
155
- (config[section] as ConfigObject)[part] = value;
156
- edits.push({ path: [section, part], value });
157
- added.push({ path: field(section, part), kind: 'added' });
158
- }
192
+ for (const { section, part, value } of entries) {
193
+ if (!object(config[section])) config[section] = {};
194
+ (config[section] as ConfigObject)[part] = value;
195
+ edits.push({ path: [section, part], value });
196
+ added.push({ path: field(section, part), kind: 'added' });
159
197
  }
160
198
  return { config, changes: added, edits };
161
199
  }
@@ -1,3 +1,4 @@
1
+ import { regionBone, type RegionSpec } from './config.ts';
1
2
  /**
2
3
  * What `propose` looked at, said (issue #86): the coverage lines lint's
3
4
  * per-bone record prints, and the basis file written beside the proposal.
@@ -186,7 +187,7 @@ export interface LegChainChoice {
186
187
  none: string | null;
187
188
  }
188
189
 
189
- export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[]; meshes: Proposal['meshes']; regions?: Proposal['regions']; limbs?: Readonly<Record<string, Limb>>; notes?: readonly string[] }, joints?: RigJoints): LegChainChoice {
190
+ export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[]; meshes: Proposal['meshes']; regions?: Readonly<Record<string, RegionSpec>>; limbs?: Readonly<Record<string, Limb>>; notes?: readonly string[] }, joints?: RigJoints): LegChainChoice {
190
191
  const chains: LegChainChoice['chains'] = [];
191
192
  for (const entry of spec.bones) {
192
193
  if (!('chain' in entry) || !/^leg_[rl]$/.test(entry.chain)) continue;
@@ -207,7 +208,7 @@ export function legChainChoice(P: PartSet, spec: { bones: readonly BoneEntry[];
207
208
  for (const [part, mesh] of Object.entries(spec.meshes)) {
208
209
  if (mesh.segments.some((s) => typeof s === 'string' ? s === entry.chain || links.has(s) : links.has(s[0]))) bound(part);
209
210
  }
210
- for (const [part, bone] of Object.entries(spec.regions ?? {})) if (links.has(bone)) bound(part);
211
+ for (const [part, bone] of Object.entries(spec.regions ?? {})) if (links.has(regionBone(bone))) bound(part);
211
212
  chains.push({ chain: entry.chain, sources: [...sources], parts: [...parts] });
212
213
  }
213
214
  if (chains.length > 0) return { chains, none: null };
package/src/limblayout.ts CHANGED
@@ -23,6 +23,8 @@ export interface LayoutPlan {
23
23
  limbs: Readonly<Record<string, Limb>>;
24
24
  families: ReadonlyMap<string, readonly string[]>;
25
25
  originalOrder: string[];
26
+ /** Authored rider families excluded from implicit closure, including replay. */
27
+ ungathered?: readonly string[];
26
28
  }
27
29
  export interface LayoutCompanion {
28
30
  spec: typeof LAYOUT_SPEC;
@@ -88,14 +90,14 @@ export function placeLimbLayouts(limbs: Readonly<Record<string, Limb>> | undefin
88
90
  const d = l.layout;
89
91
  if (d === undefined) continue;
90
92
  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));
93
+ const subject = base.slots.filter((s) => !base.ungathered?.includes(s.name) && owned(s, skin, sources, limb, parts));
92
94
  const authored = d.before ?? d.after as LimbLayoutTarget;
93
95
  const target: LimbLayoutTarget = authored.limb === undefined ? { part: authored.part } : { limb: authored.limb };
94
96
  let targets: RigSpec['slots'];
95
97
  if (target.limb !== undefined) {
96
98
  const other = limbs[target.limb];
97
99
  const all = other?.segments.map((s) => s.part) ?? [];
98
- targets = base.slots.filter((s) => owned(s, skin, sources, target.limb as string, all));
100
+ targets = base.slots.filter((s) => !base.ungathered?.includes(s.name) && owned(s, skin, sources, target.limb as string, all));
99
101
  for (const p of all) {
100
102
  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
103
  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)}` });
@@ -128,7 +130,7 @@ export function placeLimbLayouts(limbs: Readonly<Record<string, Limb>> | undefin
128
130
  result.push(s);
129
131
  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
132
  }
131
- const plan = { placements, sources, limbs, families, originalOrder: names };
133
+ const plan = { placements, sources, limbs, families, originalOrder: names, ...(base.ungathered === undefined ? {} : { ungathered: base.ungathered }) };
132
134
  validateLimbLayout(plan, { slots: result, skins: { default: skin } });
133
135
  return { slots: result, plan };
134
136
  }
@@ -138,7 +140,7 @@ export function refreshLimbLayout(plan: LayoutPlan, rig: RigSpec): LayoutPlan {
138
140
  const byName = new Map(rig.slots.map((s) => [s.name, s]));
139
141
  const slots = plan.originalOrder.flatMap((n) => { const s = byName.get(n); return s === undefined ? [] : [s]; });
140
142
  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);
143
+ const next = placeLimbLayouts(plan.limbs, rig.bones, { slots, owners: [], anchors: [], ...(plan.ungathered === undefined ? {} : { ungathered: plan.ungathered }) }, rig.skins.default, plan.families, plan.sources);
142
144
  rig.slots = next.slots;
143
145
  return next.plan as LayoutPlan;
144
146
  }
package/src/limbs.ts CHANGED
@@ -118,7 +118,7 @@ import type { BoneEntry, Limb, LimbSplit } from './config.ts';
118
118
  import { refuseIfAny, type Problem } from './errors.ts';
119
119
  import { edgeLength } from './length.ts';
120
120
  import { pyRound } from './round.ts';
121
- import type { KeypointName, PosePoints } from './skeleton.ts';
121
+ import { KEYPOINT_NAMES, type KeypointName, type PosePoints } from './skeleton.ts';
122
122
 
123
123
  export type Pt = [number, number];
124
124
 
@@ -301,10 +301,25 @@ export type SkeletonRegistration =
301
301
  * base's the mean of those bones' origins; `scale` is the base torso's length
302
302
  * over the skeleton's, and `offset` takes the skeleton torso's midpoint, so
303
303
  * scaled, onto the base's. Both to 6 places. Not ok when the base declares no
304
- * bone at one end, or the skeleton's torso has no length.
304
+ * bone at one end, or the skeleton's torso has no length. An explicit anchor
305
+ * (issue #543) replaces torso discovery: one pair holds scale at 1; two pairs
306
+ * read scale from their distance and offset from their midpoint.
305
307
  */
306
- export function registerSkeleton(bones: readonly BoneEntry[], pts: PosePoints): SkeletonRegistration {
308
+ export function registerSkeleton(bones: readonly BoneEntry[], pts: PosePoints, anchor?: Partial<Record<KeypointName, string>>): SkeletonRegistration {
307
309
  const places = bonePlaces(bones);
310
+ if (anchor !== undefined) {
311
+ const named = KEYPOINT_NAMES.flatMap((keypoint) => typeof anchor[keypoint] === 'string' ? [{ keypoint, bone: anchor[keypoint] as string }] : []);
312
+ if (named.length < 1 || named.length > 2 || named.some((a) => !places.has(a.bone))) return { ok: false, missing: [], anchors: named };
313
+ const source = named.map((a) => pts[a.keypoint]);
314
+ const target = named.map((a) => (places.get(a.bone) as BonePlace).at);
315
+ const length = source.length === 1 ? 1 : edgeLength(source[1][0] - source[0][0], source[1][1] - source[0][1]);
316
+ if (length === 0) return { ok: false, missing: [], anchors: named };
317
+ const scale = source.length === 1 ? 1 : edgeLength(target[1][0] - target[0][0], target[1][1] - target[0][1]) / length;
318
+ const offset: Pt = [0, 0];
319
+ for (let i = 0; i < source.length; i++) for (const axis of [0, 1] as const) offset[axis] += (target[i][axis] - scale * source[i][axis]) / source.length;
320
+ const rounded = (v: number): number => { const n = pyRound(v, 6); return n === 0 ? 0 : n; };
321
+ return { ok: true, offset: [rounded(offset[0]), rounded(offset[1])], scale: rounded(scale), anchors: named };
322
+ }
308
323
  const anchors: Array<{ keypoint: KeypointName; bone: string; end: 'top' | 'bottom' }> = [];
309
324
  for (const t of SKELETON_TORSO) {
310
325
  const bone = t.bones.find((b) => places.has(b));
package/src/limbslots.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * ownership boundary: descendants belong to the first segment encountered up
5
5
  * their parent graph, so a nested limb does not become its ancestor's rider.
6
6
  */
7
+ import { refuseIfAny } from './errors.ts';
7
8
  import type { Limb } from './config.ts';
8
9
  import type { RigSpec } from './rig.ts';
9
10
 
@@ -19,6 +20,8 @@ export interface LimbSlotOwner {
19
20
 
20
21
  export interface LimbSlotLayout {
21
22
  slots: RigSpec['slots'];
23
+ /** Explicitly retained generated families; omitted for historical output. */
24
+ ungathered?: readonly string[];
22
25
  owners: LimbSlotOwner[];
23
26
  /** First segment SLOT encountered in setup order, not anatomical segment 0. */
24
27
  anchors: Array<{ limb: string; slot: string | null }>;
@@ -33,18 +36,20 @@ export interface LimbSlotLayout {
33
36
  * Even a listed zero-weight reference is read, as in meshBoundBones: there is
34
37
  * no epsilon or first-weight rule. Mixed/outside/empty bindings stay outside
35
38
  * the gathered blocks, with their classification returned for inspection.
39
+ * Declared opt-outs retain their authored family without changing ownership.
36
40
  * Their mutual order is preserved; complete closure is not promised across a
37
- * nonexclusive segment or rider. No new refusal is introduced.
41
+ * nonexclusive segment or rider. An opt-out on a non-rider is refused by name.
38
42
  */
39
43
  export function coalesceLimbSlots(
40
44
  limbs: Readonly<Record<string, Limb>> | undefined,
41
45
  bones: RigSpec['bones'],
42
46
  slots: RigSpec['slots'],
43
47
  skin: RigSpec['skins']['default'],
48
+ retain: readonly { part: string; object: string; slots: readonly string[] }[] = [],
44
49
  ): LimbSlotLayout {
45
- if (limbs === undefined || Object.keys(limbs).length === 0) return { slots, owners: [], anchors: [] };
50
+ if (retain.length === 0 && (limbs === undefined || Object.keys(limbs).length === 0)) return { slots, owners: [], anchors: [] };
46
51
  const seeds = new Map<string, string[]>();
47
- for (const [name, limb] of Object.entries(limbs)) {
52
+ for (const [name, limb] of Object.entries(limbs ?? {})) {
48
53
  for (const s of limb.segments) {
49
54
  const names = seeds.get(s.bone) ?? [];
50
55
  if (!names.includes(name)) names.push(name);
@@ -83,7 +88,13 @@ export function coalesceLimbSlots(
83
88
  const kind = exclusive && mine.size === 1 && outside.size === 0 ? 'exclusive' : mine.size > 0 ? 'nonexclusive' : bindings.some((b) => b.bones.length > 0) ? 'outside' : 'unbound';
84
89
  return { slot: slot.name, kind, limb: kind === 'exclusive' ? [...mine][0] : null, bindings, limbs: [...mine], outside: [...outside] };
85
90
  });
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 }));
91
+ const segments = new Set(Object.values(limbs ?? {}).flatMap((limb) => limb.segments.map((s) => s.part)));
92
+ refuseIfAny(retain.flatMap((r) => {
93
+ const owner = owners.find((o) => o.slot === r.part);
94
+ return owner?.kind === 'exclusive' && !segments.has(r.part) ? [] : [{ code: 'RIG_GATHER_RIDER', object: r.object, detail: `part "${r.part}" is ${segments.has(r.part) ? 'a declared limb segment' : owner?.kind ?? 'absent'}; an exclusively bound non-segment limb rider is required to opt out of gathering — remove gather or bind this rider exclusively to one declared limb` }];
95
+ }));
96
+ const ungathered = new Set(retain.flatMap((r) => [...r.slots]));
97
+ 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
98
  const at = new Map<string, string[]>();
88
99
  const anchored = new Set<string>();
89
100
  for (const anchor of anchors) {
@@ -91,7 +102,7 @@ export function coalesceLimbSlots(
91
102
  at.set(anchor.slot, [...(at.get(anchor.slot) ?? []), anchor.limb]);
92
103
  anchored.add(anchor.limb);
93
104
  }
94
- const owned = new Map(owners.map((o) => [o.slot, o.limb !== null && anchored.has(o.limb) ? o.limb : null]));
105
+ const owned = new Map(owners.map((o) => [o.slot, o.limb !== null && anchored.has(o.limb) && !ungathered.has(o.slot) ? o.limb : null]));
95
106
  const gathered = new Map<string, RigSpec['slots']>();
96
107
  for (const slot of slots) {
97
108
  const name = owned.get(slot.name);
@@ -102,5 +113,5 @@ export function coalesceLimbSlots(
102
113
  for (const name of at.get(slot.name) ?? []) reordered.push(...(gathered.get(name) ?? []));
103
114
  if (owned.get(slot.name) === null) reordered.push(slot);
104
115
  }
105
- return { slots: reordered.every((s, i) => s === slots[i]) ? slots : reordered, owners, anchors };
116
+ return { slots: reordered.every((s, i) => s === slots[i]) ? slots : reordered, owners, anchors, ...(ungathered.size === 0 ? {} : { ungathered: [...ungathered] }) };
106
117
  }
package/src/propose.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { regionBone, type RegionSpec } from './config.ts';
1
2
  /**
2
3
  * The propose stage: bone origins, mesh candidate lists, regions and a default
3
4
  * idle, read off the assembled parts — and the overlay a person or an agent
@@ -4885,7 +4886,7 @@ export function coverageOutcome(c: BoneCoverage): CoverageOutcome {
4885
4886
  */
4886
4887
  export function lint(
4887
4888
  P: PartSet,
4888
- spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, string>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[]; limbs?: Readonly<Record<string, Limb>>; stops?: readonly ConfigStop[] },
4889
+ spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, RegionSpec>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[]; limbs?: Readonly<Record<string, Limb>>; stops?: readonly ConfigStop[] },
4889
4890
  joints?: RigJoints,
4890
4891
  drafted: readonly DraftLintFinding[] = [],
4891
4892
  ): LintResult {
@@ -5391,7 +5392,7 @@ function findingBones(f: LintFinding, bones: readonly BoneEntry[]): string[] {
5391
5392
  * art by design: its role is the reason, never a finding.
5392
5393
  */
5393
5394
  function lintCoverage(
5394
- spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, string>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[] },
5395
+ spec: { bones: readonly BoneEntry[]; meshes: Readonly<Record<string, MeshSpec>>; regions?: Readonly<Record<string, RegionSpec>>; motion?: SkeletonSections['motion']; constraints?: readonly ConfigConstraint[] },
5395
5396
  byName: ReadonlyMap<string, ExpandedBone>,
5396
5397
  read: ReadonlyMap<string, string[]>,
5397
5398
  findings: readonly LintFinding[],
@@ -5433,7 +5434,7 @@ function lintCoverage(
5433
5434
  else if (chain !== null && sp === chain && unknownMeshes.includes(mname)) partless.push(`${at} (mesh ${JSON.stringify(mname)})`);
5434
5435
  });
5435
5436
  }
5436
- const regions = Object.entries(spec.regions ?? {}).filter(([, b]) => b === bone).map(([part]) => `regions.${part}`);
5437
+ const regions = Object.entries(spec.regions ?? {}).filter(([, b]) => regionBone(b) === bone).map(([part]) => `regions.${part}`);
5437
5438
  const stills = Object.entries(spec.motion?.blink?.still ?? {}).filter(([, st]) => st.bone === bone).map(([part]) => `motion.blink.still.${part}`);
5438
5439
  const s = (list: readonly string[], one: string, many: string): string => (list.length === 1 ? one : many);
5439
5440
  if (single.length > 0) why.push(`named as a single bone by ${single.join(', ')}: a single bone has no links, and the off-art check reads only the links <segment><digits> of a chain`);