@rig-c/parts 2.8.0 → 2.9.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,191 @@
1
+ /** Report-only visible-back residual candidates after edge composition (#999). */
2
+ import { EDGE_OWNER_ALPHA } from './paintingedges.ts';
3
+ import { type Raster, RasterError } from './raster/types.ts';
4
+
5
+ export const EDGE_PAIR_RESIDUAL = 'EDGE_PAIR_RESIDUAL';
6
+ export const EDGE_RESIDUAL_FILE = 'edge_residuals.json';
7
+ export interface ResidualPart {
8
+ name: string;
9
+ x: number;
10
+ y: number;
11
+ image: Raster;
12
+ }
13
+ export interface ResidualPair {
14
+ front: string;
15
+ back: string;
16
+ status: 'measured' | 'skip' | 'unavailable';
17
+ residual_px: number | null;
18
+ /** Rig pixels, [left, top, width, height]. */
19
+ box: [number, number, number, number] | null;
20
+ /** Coordinates reference the existing back part PNG at its parts.json placement.
21
+ * Spans are [y, left, right-exclusive], sorted by y then left. */
22
+ back_pixels: { count: number; spans: Array<[number, number, number]> };
23
+ skipped: string[];
24
+ unavailable: string[];
25
+ unavailable_px: number;
26
+ }
27
+ export interface EdgeResidualReport {
28
+ spec: 'rig-parts-edge-residuals/1';
29
+ observation: 'visible-back RGB-error components touching one overlapping front boundary; candidates, painting ownership unproven';
30
+ stage: 'final assembled parts after paintingEdges and seam correction';
31
+ grid: [number, number];
32
+ rgb_tolerance: number;
33
+ owner_alpha_above: number;
34
+ connectivity: 8;
35
+ pairs: ResidualPair[];
36
+ summary: { pairs: number; measured: number; skipped: number; unavailable: number; residual_px: number; unassigned_error_px: number };
37
+ }
38
+
39
+ function offset(part: ResidualPart, x: number, y: number): number | null {
40
+ const lx = x - part.x, ly = y - part.y;
41
+ if (lx < 0 || ly < 0 || lx >= part.image.width || ly >= part.image.height) return null;
42
+ return (ly * part.image.width + lx) * 4;
43
+ }
44
+ function alpha(part: ResidualPart, x: number, y: number): number {
45
+ const at = offset(part, x, y);
46
+ return at === null ? 0 : part.image.data[at + 3];
47
+ }
48
+ function overlap(a: ResidualPart, b: ResidualPart): boolean {
49
+ const right = Math.min(a.x + a.image.width, b.x + b.image.width);
50
+ const bottom = Math.min(a.y + a.image.height, b.y + b.image.height);
51
+ for (let y = Math.max(a.y, b.y); y < bottom; y++) {
52
+ for (let x = Math.max(a.x, b.x); x < right; x++) {
53
+ if (alpha(a, x, y) > EDGE_OWNER_ALPHA && alpha(b, x, y) > EDGE_OWNER_ALPHA) return true;
54
+ }
55
+ }
56
+ return false;
57
+ }
58
+ function spans(pixels: number[], width: number): Array<[number, number, number]> {
59
+ const out: Array<[number, number, number]> = [];
60
+ for (const p of pixels.sort((a, b) => a - b)) {
61
+ const x = p % width, y = Math.floor(p / width), previous = out.at(-1);
62
+ if (previous !== undefined && previous[0] === y && previous[2] === x) previous[2]++;
63
+ else out.push([y, x, x + 1]);
64
+ }
65
+ return out;
66
+ }
67
+
68
+ /** Read existing limits, never set a new bar or a reach cap. Components are
69
+ * observations of residual colour error. Semantic painting ownership cannot
70
+ * be established from colour and draw order and is explicitly unproven. */
71
+ export function edgePairResiduals(parts: readonly ResidualPart[], painting: Raster, composite: Raster, tolerance: number): EdgeResidualReport {
72
+ const W = painting.width, H = painting.height, size = W * H;
73
+ if (composite.width !== W || composite.height !== H) throw new RasterError('edgePairResiduals: composite and painting require the same native rig grid');
74
+ const n = parts.length;
75
+ const owner = new Int32Array(size).fill(-1);
76
+ const pure = new Uint8Array(size);
77
+ const visible = new Uint32Array(n);
78
+ const errors = new Uint8Array(size);
79
+ for (let y = 0; y < H; y++) {
80
+ for (let x = 0; x < W; x++) {
81
+ const p = y * W + x;
82
+ for (let i = n - 1; i >= 0; i--) {
83
+ if (alpha(parts[i], x, y) > EDGE_OWNER_ALPHA) { owner[p] = i; visible[i]++; break; }
84
+ }
85
+ const back = owner[p];
86
+ if (back >= 0) {
87
+ let opaque = alpha(parts[back], x, y) === 255;
88
+ for (let i = back + 1; i < n && opaque; i++) if (alpha(parts[i], x, y) > 0) opaque = false;
89
+ pure[p] = opaque ? 1 : 0;
90
+ }
91
+ let delta = 0;
92
+ for (let c = 0; c < 3; c++) delta = Math.max(delta, Math.abs(composite.data[p * 4 + c] - painting.data[p * 4 + c]));
93
+ errors[p] = delta > tolerance ? 1 : 0;
94
+ }
95
+ }
96
+ const neighbours = (p: number, visit: (q: number) => void): void => {
97
+ const x = p % W, y = Math.floor(p / W);
98
+ for (let dy = -1; dy <= 1; dy++) {
99
+ for (let dx = -1; dx <= 1; dx++) {
100
+ if ((dx === 0 && dy === 0) || x + dx < 0 || x + dx >= W || y + dy < 0 || y + dy >= H) continue;
101
+ visit((y + dy) * W + x + dx);
102
+ }
103
+ }
104
+ };
105
+ const adjacency = new Uint8Array(n * n);
106
+ for (let p = 0; p < size; p++) {
107
+ if (owner[p] < 0) continue;
108
+ neighbours(p, q => {
109
+ if (owner[q] > owner[p]) adjacency[owner[q] * n + owner[p]] = 1;
110
+ });
111
+ }
112
+ const rows = new Map<number, ResidualPair>();
113
+ const selected = new Map<number, number[]>();
114
+ for (let front = 1; front < n; front++) {
115
+ for (let back = 0; back < front; back++) {
116
+ const row: ResidualPair = { front: parts[front].name, back: parts[back].name, status: 'measured', residual_px: 0, box: null, back_pixels: { count: 0, spans: [] }, skipped: [], unavailable: [], unavailable_px: 0 };
117
+ if (!overlap(parts[front], parts[back])) { row.status = 'skip'; row.skipped.push('no alpha overlap above the existing owner floor'); }
118
+ else if (visible[front] === 0 || visible[back] === 0) {
119
+ row.status = 'unavailable';
120
+ row.unavailable.push(visible[front] === 0 ? 'front has no visible boundary observation' : 'back has no visible pixel observation');
121
+ row.residual_px = null;
122
+ } else if (adjacency[front * n + back] === 0) { row.status = 'skip'; row.skipped.push('no exposed front/back boundary'); }
123
+ rows.set(front * n + back, row);
124
+ }
125
+ }
126
+ const visited = new Uint8Array(size);
127
+ let unassigned = 0;
128
+ for (let start = 0; start < size; start++) {
129
+ if (errors[start] === 0 || visited[start] === 1) continue;
130
+ const back = owner[start];
131
+ if (back < 0) { visited[start] = 1; unassigned++; continue; }
132
+ const queue = [start], fronts = new Set<number>();
133
+ let mixed = false;
134
+ visited[start] = 1;
135
+ for (let cursor = 0; cursor < queue.length; cursor++) {
136
+ const p = queue[cursor];
137
+ if (pure[p] === 0) mixed = true;
138
+ neighbours(p, q => {
139
+ const front = owner[q];
140
+ if (front > back && rows.get(front * n + back)?.status === 'measured') fronts.add(front);
141
+ if (errors[q] === 1 && owner[q] === back && visited[q] === 0) { visited[q] = 1; queue.push(q); }
142
+ });
143
+ }
144
+ if (fronts.size !== 1 || mixed) {
145
+ unassigned += queue.length;
146
+ for (const front of fronts) {
147
+ const row = rows.get(front * n + back)!;
148
+ row.unavailable_px += queue.length;
149
+ const reason = mixed ? 'residual component includes partial-alpha or additional foreground contribution' : 'residual component touches multiple overlapping fronts';
150
+ if (!row.unavailable.includes(reason)) row.unavailable.push(reason);
151
+ }
152
+ continue;
153
+ }
154
+ const front = [...fronts][0], key = front * n + back;
155
+ const pixels = selected.get(key) ?? [];
156
+ for (const pixel of queue) pixels.push(pixel);
157
+ selected.set(key, pixels);
158
+ }
159
+ for (const [key, row] of rows) {
160
+ const pixels = selected.get(key) ?? [];
161
+ row.back_pixels = { count: pixels.length, spans: spans(pixels, W) };
162
+ if (pixels.length > 0) {
163
+ let left = W, top = H, right = 0, bottom = 0;
164
+ for (const p of pixels) { const x = p % W, y = Math.floor(p / W); left = Math.min(left, x); top = Math.min(top, y); right = Math.max(right, x + 1); bottom = Math.max(bottom, y + 1); }
165
+ row.box = [left, top, right - left, bottom - top];
166
+ }
167
+ if (row.unavailable.length > 0) {
168
+ row.status = 'unavailable';
169
+ row.residual_px = null;
170
+ // Retained candidates still count when this pair's attribution is unavailable.
171
+ unassigned += pixels.length;
172
+ }
173
+ else if (row.status === 'measured') row.residual_px = pixels.length;
174
+ }
175
+ const pairs = [...rows.values()];
176
+ return {
177
+ spec: 'rig-parts-edge-residuals/1',
178
+ observation: 'visible-back RGB-error components touching one overlapping front boundary; candidates, painting ownership unproven',
179
+ stage: 'final assembled parts after paintingEdges and seam correction',
180
+ grid: [W, H], rgb_tolerance: tolerance, owner_alpha_above: EDGE_OWNER_ALPHA, connectivity: 8, pairs,
181
+ summary: { pairs: pairs.length, measured: pairs.filter(p => p.status === 'measured').length, skipped: pairs.filter(p => p.status === 'skip').length, unavailable: pairs.filter(p => p.status === 'unavailable').length, residual_px: pairs.reduce((sum, p) => sum + (p.residual_px ?? 0), 0), unassigned_error_px: unassigned },
182
+ };
183
+ }
184
+
185
+ export function edgeResidualLines(report: EdgeResidualReport): string[] {
186
+ const s = report.summary;
187
+ return [
188
+ `${EDGE_PAIR_RESIDUAL}: ${s.measured} of ${s.pairs} pairs measured, ${s.skipped} skipped, ${s.unavailable} unavailable; ${s.residual_px} candidate px, ${s.unassigned_error_px} unassigned error px; painting ownership unproven; report only`,
189
+ ...report.pairs.map(p => `${EDGE_PAIR_RESIDUAL}: front "${p.front}", back "${p.back}" ${p.status}; residual px ${p.residual_px ?? 'unavailable'}, box ${p.box === null ? 'none' : `[${p.box.join(', ')}]`}, back pixels ${p.back_pixels.count}${p.skipped.length === 0 ? '' : `; skipped ${p.skipped.join(', ')}`}${p.unavailable.length === 0 ? '' : `; unavailable ${p.unavailable.join(', ')}`}`),
190
+ ];
191
+ }
package/src/mesh.ts CHANGED
@@ -44,8 +44,9 @@
44
44
  * against.
45
45
  */
46
46
  import { type Problem } from './errors.ts';
47
- import { connectedComponents, fillHoles, fillPoly, type Mask, newMask } from './raster/index.ts';
48
- import { rint } from './round.ts';
47
+ import { alphaAbove, connectedComponents, fillHoles, fillPoly, type Mask, newMask } from './raster/index.ts';
48
+ import type { Raster } from './raster/types.ts';
49
+ import { pyRound, rint } from './round.ts';
49
50
 
50
51
  /** A pixel counts as art when its alpha is above this — the reference's `im[..., 3] > 8`. */
51
52
  export const ART_ALPHA = 8;
@@ -440,3 +441,29 @@ export function latticeStray(art: Mask, stray: number): LatticeStray {
440
441
  for (let i = 0; i < data.length; i++) if (out[comp.labels[i]] === 1) data[i] = 0;
441
442
  return { art: { width: art.width, height: art.height, data }, islands, pixels, artPixels, largest };
442
443
  }
444
+
445
+ /** A part's art islands, largest first, and what the dust rule makes of them. */
446
+ export type DustReading = { stray: number | undefined; islands: number[]; dust: number[] } | { keep: string; islands: number[] };
447
+
448
+ /**
449
+ * The dust rule on a part image (its alpha, unpadded or padded alike: the pad adds no art): the 4-connected islands
450
+ * of alpha above `ART_ALPHA` — the contour mode's own island rule — and whether every island past the largest is
451
+ * dust ({@link DUST_MAX_PX}, {@link DUST_MAX_SHARE}). A tie for the largest is no single largest island, which the
452
+ * contour mode refuses, so it keeps the lattice too.
453
+ */
454
+ export function dustOf(image: Raster): DustReading {
455
+ const comp = connectedComponents(alphaAbove(image, ART_ALPHA), 4);
456
+ const islands = comp.stats.slice(1).map((s) => s.area).sort((a, b) => b - a);
457
+ const art = islands.reduce((a, b) => a + b, 0);
458
+ if (islands.length === 0) return { keep: `its image has no pixel with alpha above ${ART_ALPHA}`, islands };
459
+ if (islands.length > 1 && islands[0] === islands[1]) return { keep: `its art is ${islands.length} islands (${islands.join(', ')} px) of which two share the largest count, so no one island is the largest`, islands };
460
+ const extra = islands.slice(1);
461
+ const pieces = extra.filter((n) => !isDust(n, art));
462
+ if (pieces.length > 0) {
463
+ return {
464
+ keep: `its art is ${islands.length} islands (${islands.join(', ')} px); ${pieces.length} beside the largest ${pieces.length === 1 ? 'is a real piece' : 'are real pieces'}, not dust (at most ${DUST_MAX_PX} px and at most ${pyRound(DUST_MAX_SHARE * 100, 6)} % of the part's ${art} art px), and the contour mode meshes one island`,
465
+ islands,
466
+ };
467
+ }
468
+ return { stray: extra.length === 0 ? undefined : extra[0], islands, dust: extra };
469
+ }
package/src/meshdraft.ts CHANGED
@@ -67,13 +67,12 @@ import { MeshReductionError } from '@rig-c/core/mesh';
67
67
  import { explicitFrameId, idleSchedule } from './automotion.ts';
68
68
  import { checkStage, gateThroughRigc, type Log, RIGC_MODEL_DOCUMENT, rigStage } from './build.ts';
69
69
  import { BARS, type CheckReport, type PackShape, type PageEdges, type RigcRunner } from './check.ts';
70
- import { type CharacterConfig, type ContourMeshSpec, type LatticeMeshSpec, loadConfigAndAnimations, type Segment } from './config.ts';
70
+ import { type CharacterConfig, configFileReferences, type ConfigFileReference, type ContourMeshSpec, type LatticeMeshSpec, loadConfigAndAnimations, type Segment } from './config.ts';
71
71
  import { PartsError, type Problem, problemLine } from './errors.ts';
72
72
  import { IDLE_FPS } from './motion.ts';
73
73
  import { type ContourBridges, FAINT_ALPHA } from './contour.ts';
74
- import { ART_ALPHA, DUST_MAX_PX, DUST_MAX_SHARE, isDust } from './mesh.ts';
74
+ import { ART_ALPHA, DUST_MAX_PX, DUST_MAX_SHARE, isDust, dustOf, type DustReading } from './mesh.ts';
75
75
  import { type PartsFile, readParts } from './parts.ts';
76
- import { alphaAbove, connectedComponents } from './raster/index.ts';
77
76
  import { readPng } from './raster/png.ts';
78
77
  import type { Raster } from './raster/types.ts';
79
78
  import { buildRig, type IdleKeys, type MeshAttachment, rigJsonText, type RigSpec } from './rig.ts';
@@ -196,31 +195,7 @@ export function figureRules(parts: Pick<PartsFile, 'parts'>): FigureRules | Prob
196
195
  // the candidate
197
196
  // ---------------------------------------------------------------------------
198
197
 
199
- /** A part's art islands, largest first, and what the dust rule makes of them. */
200
- export type DustReading = { stray: number | undefined; islands: number[]; dust: number[] } | { keep: string; islands: number[] };
201
-
202
- /**
203
- * The dust rule on a part image (its alpha, unpadded or padded alike: the pad adds no art): the 4-connected islands
204
- * of alpha above `ART_ALPHA` — the contour mode's own island rule — and whether every island past the largest is
205
- * dust ({@link DUST_MAX_PX}, {@link DUST_MAX_SHARE}). A tie for the largest is no single largest island, which the
206
- * contour mode refuses, so it keeps the lattice too.
207
- */
208
- export function dustOf(image: Raster): DustReading {
209
- const comp = connectedComponents(alphaAbove(image, ART_ALPHA), 4);
210
- const islands = comp.stats.slice(1).map((s) => s.area).sort((a, b) => b - a);
211
- const art = islands.reduce((a, b) => a + b, 0);
212
- if (islands.length === 0) return { keep: `its image has no pixel with alpha above ${ART_ALPHA}`, islands };
213
- if (islands.length > 1 && islands[0] === islands[1]) return { keep: `its art is ${islands.length} islands (${islands.join(', ')} px) of which two share the largest count, so no one island is the largest`, islands };
214
- const extra = islands.slice(1);
215
- const pieces = extra.filter((n) => !isDust(n, art));
216
- if (pieces.length > 0) {
217
- return {
218
- keep: `its art is ${islands.length} islands (${islands.join(', ')} px); ${pieces.length} beside the largest ${pieces.length === 1 ? 'is a real piece' : 'are real pieces'}, not dust (at most ${DUST_MAX_PX} px and at most ${pyRound(DUST_MAX_SHARE * 100, 6)} % of the part's ${art} art px), and the contour mode meshes one island`,
219
- islands,
220
- };
221
- }
222
- return { stray: extra.length === 0 ? undefined : extra[0], islands, dust: extra };
223
- }
198
+ export { dustOf, type DustReading } from './mesh.ts';
224
199
 
225
200
  /**
226
201
  * The candidate for one lattice entry: the outline mesh at the figure's numbers, its weights' fields as the lattice
@@ -743,28 +718,12 @@ export function splicedConfig(text: string, drafted: ReadonlyMap<string, unknown
743
718
  return r.text;
744
719
  }
745
720
 
746
- /** A path in a config the loader resolves against the config's directory, and how to set it. */
747
- export interface RelativeConfigPath {
748
- at: string;
749
- value: string;
750
- set: (v: string) => void;
751
- }
721
+ /** A config-relative file reference supplied by the loader. */
722
+ export type RelativeConfigPath = ConfigFileReference;
752
723
 
753
- /**
754
- * Each path in `o` (a parsed config) the loader resolves against the config's directory — `motion.animations_from`,
755
- * `generation.control.skeleton` — where it is relative and names a file there.
756
- */
757
- export function relativeConfigPaths(configDir: string, o: Json): RelativeConfigPath[] {
758
- const out: RelativeConfigPath[] = [];
759
- const motion = o.motion as Json | undefined;
760
- if (motion !== undefined && typeof motion.animations_from === 'string' && !isAbsolute(motion.animations_from) && existsSync(resolve(configDir, motion.animations_from))) {
761
- out.push({ at: 'motion.animations_from', value: motion.animations_from, set: (v) => (motion.animations_from = v) });
762
- }
763
- const control = (o.generation as Json | undefined)?.control as Json | undefined;
764
- if (control !== undefined && typeof control.skeleton === 'string' && !isAbsolute(control.skeleton) && existsSync(resolve(configDir, control.skeleton))) {
765
- out.push({ at: 'generation.control.skeleton', value: control.skeleton, set: (v) => (control.skeleton = v) });
766
- }
767
- return out;
724
+ /** Each relative file path the loader knows, with built-in skeleton names excluded. */
725
+ export function relativeConfigPaths(_configDir: string, o: Json): RelativeConfigPath[] {
726
+ return configFileReferences(o).filter((field) => !isAbsolute(field.value));
768
727
  }
769
728
 
770
729
  /**
package/src/propose.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { dustOf } from './mesh.ts';
1
2
  import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
2
3
  /**
3
4
  * The propose stage: bone origins, mesh candidate lists, regions and a default
@@ -132,10 +133,11 @@ import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
132
133
  import { existsSync } from 'node:fs';
133
134
  import { join } from 'node:path';
134
135
  import { drawText, GLYPH_H } from '@rig-c/core/font5x7';
135
- import { type BoneEntry, type CharacterConfig, type ConfigConstraint, type ConfigStop, contourRegionsOf, deriveBustRegions, type Limb, type MeshSpec, type PartBinding, parseConfig, type Point, type Segment, type SkeletonSections, turnRidersByBone } from './config.ts';
136
+ import { type BoneEntry, type CharacterConfig, type ConfigConstraint, type ConfigStop, type ContourBustSpec, type ContourSpec, contourRegionsOf, deriveBustRegions, type Limb, type MeshSpec, type PartBinding, parseConfig, type Point, type Segment, type SkeletonSections, turnRidersByBone } from './config.ts';
136
137
  export { contourRegionsOf, deriveBustRegions };
137
138
  import { computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toWorld } from './coords.ts';
138
139
  import { PartsError, type Problem, refuseIfAny } from './errors.ts';
140
+ import { GRID } from './contour.ts';
139
141
  import { eyeLineDegrees, type FrameFeature, headAxes, type HeadAxes, headFrame, type HeadFrame } from './headframe.ts';
140
142
  import { type LayerSet, OPAQUE_ALPHA_ABOVE } from './layers.ts';
141
143
  import { PAINTING_RUN, type PartRecord, type PartsFile, readParts } from './parts.ts';
@@ -157,7 +159,7 @@ import { configRoles, type RoleOf } from './structure.ts';
157
159
  import { AUTHOR_NO_ROLE, isAuthorTag } from './tags.ts';
158
160
  import { TURN_BONE, TURN_CARRIER_TAG, TURN_PLACES, TURN_RIDER_OFFSET, TURN_RIDER_TAGS, turnFractions, turnNearest, turnPivot, turnRiderDepth, type TurnSpec } from './turn.ts';
159
161
  import { edgeLength } from './length.ts';
160
- import { bonePlaces, jointLine, type JointLine, limbCrossing, limbPolyline, limbRun, limbWidth, nearestLimb, nearestOnLine, offLineFigure, type Pt } from './limbs.ts';
162
+ import { bonePlaces, jointLine, type JointLine, limbCrossing, limbPolyline, limbRun, limbWidth, nearestLimb, nearestOnLine, offLineFigure, segmentOf, type Pt } from './limbs.ts';
161
163
  import { type BranchSqueezeFinding, branchSqueezes, chainSqueezes, type SqueezeFinding } from './squeeze.ts';
162
164
  import { backHairMasses, type BackHairMass, backHairMassTrees, INFLUENCE_RADIUS_CELLS, RECIPE_BACK_HAIR_CHAINS, RECIPE_LENGTH_RATIO, chainConstraints, clothNote, type ClothRecipe, type ClothRecipes, type ClothTarget, CLOTH_TARGETS, draftTrees, spanCrosses, swingName, type Tail, tailOverlap, type TailOverlap, type TailSpan, treeConstraints, type TreeChain, type TreeInput, type TreeMassInput } from './cloth.ts';
163
165
  import { TEXTURE_STRETCH_CEILING } from './check.ts';
@@ -1403,13 +1405,39 @@ const SIDES = [
1403
1405
  ['l', -1],
1404
1406
  ] as const;
1405
1407
 
1408
+ /** Declared bust landmarks in rig pixels, or an explicit omission reason. */
1409
+ export interface BustDraft {
1410
+ landmarks?: { apex_r: Point; apex_l: Point; cleavage?: Point };
1411
+ noBust?: string;
1412
+ }
1413
+
1414
+ /** Read only the declared landmark fields. Geometry is checked by checkProposal's config reader. */
1415
+ export function readBustLandmarks(raw: unknown): NonNullable<BustDraft['landmarks']> {
1416
+ const problems: Problem[] = [];
1417
+ const record = typeof raw === 'object' && raw !== null && !Array.isArray(raw)
1418
+ ? raw as Record<string, unknown>
1419
+ : {};
1420
+ for (const key of Object.keys(record)) {
1421
+ if (!['apex_r', 'apex_l', 'cleavage'].includes(key)) problems.push({ code: 'PROPOSE_BUST_INPUT', object: `landmarks.${key}`, detail: 'is unknown. Give apex_r, apex_l and optional cleavage in rig pixels' });
1422
+ }
1423
+ for (const key of ['apex_r', 'apex_l', 'cleavage']) {
1424
+ if (key === 'cleavage' && record[key] === undefined) continue;
1425
+ const value = record[key];
1426
+ if (!Array.isArray(value) || value.length !== 2 || !value.every(n => typeof n === 'number' && Number.isFinite(n))) {
1427
+ problems.push({ code: 'PROPOSE_BUST_INPUT', object: `landmarks.${key}`, detail: `is ${JSON.stringify(value) ?? 'absent'}. A finite [x, y] point in rig pixels is required` });
1428
+ }
1429
+ }
1430
+ refuseIfAny(problems);
1431
+ return record as NonNullable<BustDraft['landmarks']>;
1432
+ }
1433
+
1406
1434
  /**
1407
1435
  * Propose bones, meshes, regions and an idle from the parts. With `joints`
1408
1436
  * (`propose --keypoints`, issue #75), a joint the file gives a position is
1409
1437
  * used as given in place of the body-ratio rule for the bone it places, and
1410
1438
  * every joint the proposer could use gets one note saying how it was used or
1411
- * which rule stood in; without it every value and note is the one this
1412
- * function wrote before the parameter existed.
1439
+ * which rule stood in. Bust landmarks are supplied separately through `bust`.
1440
+ * Their absence leaves the contour torso with a missing-landmarks note.
1413
1441
  */
1414
1442
  export function propose(
1415
1443
  P: PartSet,
@@ -1418,8 +1446,9 @@ export function propose(
1418
1446
  gridRule: GridRule = DEFAULT_GRID_RULE,
1419
1447
  cloth: ClothRecipes | null = null,
1420
1448
  chainRule = true,
1449
+ bust: BustDraft = {},
1421
1450
  ): Proposal {
1422
- return proposeWithBasis(P, joints, wristSnap, gridRule, cloth, chainRule).proposal;
1451
+ return proposeWithBasis(P, joints, wristSnap, gridRule, cloth, chainRule, bust).proposal;
1423
1452
  }
1424
1453
 
1425
1454
  /**
@@ -1439,7 +1468,12 @@ export function proposeWithBasis(
1439
1468
  gridRule: GridRule = DEFAULT_GRID_RULE,
1440
1469
  cloth: ClothRecipes | null = null,
1441
1470
  chainRule = true,
1471
+ bust: BustDraft = {},
1442
1472
  ): { proposal: Proposal; basis: ProposalBasis; draftLint: DraftLintFinding[] } {
1473
+ if (bust.noBust !== undefined && (bust.noBust.trim().length === 0 || bust.landmarks !== undefined)) {
1474
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'bust draft', detail: 'give either landmarks or a non-blank noBust reason, not both' }]);
1475
+ }
1476
+ if (bust.landmarks !== undefined) readBustLandmarks(bust.landmarks);
1443
1477
  // Issue #230: a piece is not given its base's rule a second time, which
1444
1478
  // needs to know which part is the piece. A file that cannot say is refused
1445
1479
  // here, and only here: every other reader of parts.json still takes it.
@@ -3415,6 +3449,117 @@ export function proposeWithBasis(
3415
3449
  );
3416
3450
  }
3417
3451
  }
3452
+ // Issue #986: only the chest carrier changes mode. Other garments retain their drafting rules.
3453
+ const chestCarriers = figPart === null
3454
+ ? tw.filter(p => isOn(P.alpha(p), chest[0], chest[1]))
3455
+ : [];
3456
+ if (figPart === null && chestCarriers.length > 1) {
3457
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'chest carrier', detail: `chest at ${fmtAt(chest)} lies on ${chestCarriers.map(p => p.name).join(', ')}. Separate the chest-holding topwear so exactly one part covers it` }]);
3458
+ }
3459
+ const torsoName = figPart === null ? chestCarriers[0]?.name : 'trunk_chest';
3460
+ if (torsoName !== undefined) {
3461
+ const source = figPart ?? chestCarriers[0];
3462
+ const lattice = meshes[torsoName];
3463
+ const recipeTag = clothMeshed.get(torsoName);
3464
+ if (recipeTag !== undefined && recipeOf(recipeTag)?.influence !== undefined) {
3465
+ throw new PartsError([{
3466
+ code: 'PROPOSE_BUST_INPUT', object: `config.cloth.${JSON.stringify(recipeTag)}.influence`,
3467
+ detail: `declares an influence mesh for chest-holding topwear "${torsoName}". This draft requires a contour torso. Remove influence from this recipe or separate the torso from its cloth part`,
3468
+ }]);
3469
+ }
3470
+ let torsoImage = P.images.get(source.name) as Raster;
3471
+ if (figPart !== null) {
3472
+ // Read the future trunk segment, using the same ownership and joint cuts as assemble.
3473
+ const places = bonePlaces(bones);
3474
+ const sharing = Object.entries(limbs).filter(([, limb]) => limb.segments.some(segment => segment.from === source.name));
3475
+ const trunkIndex = sharing.findIndex(([name]) => name === 'trunk');
3476
+ const polylines = sharing.map(([, limb]) => limbPolyline(limb, places));
3477
+ const trunkPoints = polylines[trunkIndex];
3478
+ const lines = [null, jointLine(trunkPoints[0], trunkPoints[1], trunkPoints[2]), jointLine(trunkPoints[1], trunkPoints[2], null)];
3479
+ const data = new Uint8ClampedArray(torsoImage.data);
3480
+ for (let y = 0; y < torsoImage.height; y++) {
3481
+ for (let x = 0; x < torsoImage.width; x++) {
3482
+ const alpha = (y * torsoImage.width + x) * 4 + 3;
3483
+ if (data[alpha] === 0) continue;
3484
+ const wx = source.x + x;
3485
+ const wy = source.y + y;
3486
+ if (nearestLimb(polylines, wx, wy) !== trunkIndex || segmentOf(lines, 0, 2, wx, wy) !== 1) data[alpha] = 0;
3487
+ }
3488
+ }
3489
+ torsoImage = { ...torsoImage, data };
3490
+ }
3491
+ const dust = dustOf(torsoImage);
3492
+ if ('keep' in dust) {
3493
+ throw new PartsError([{ code: 'PROPOSE_TORSO_ISLANDS', object: `chest carrier "${torsoName}"`, detail: `${dust.keep}. Separate the real pieces before drafting a contour torso` }]);
3494
+ }
3495
+ if (dust.stray !== undefined) notes.push(`${torsoName}: contour dust rule leaves out ${dust.dust.length} island(s), ${dust.dust.reduce((sum, pixels) => sum + pixels, 0)} px; contour.stray=${dust.stray}`);
3496
+ const [, radius] = gridR(source);
3497
+ const segments: Segment[] = lattice !== undefined && 'grid' in lattice ? lattice.segments : [['chest', rnd(neckAt), rnd(hip)]];
3498
+ // Same figure formulas as mesh-draft's figureRules (issue #265). Importing meshdraft here would cycle through propose.
3499
+ const tolerance = Math.max(1, Math.round(fig.height / 554));
3500
+ const contour: ContourSpec = {
3501
+ tolerance,
3502
+ margin: tolerance,
3503
+ spacing: fig.grid,
3504
+ maxEdge: fig.grid,
3505
+ ...(dust.stray === undefined ? {} : { stray: dust.stray }),
3506
+ };
3507
+ if (bust.noBust !== undefined) {
3508
+ notes.push(`${torsoName}: contour bust omitted for the declared reason: ${bust.noBust}`);
3509
+ } else if (bust.landmarks === undefined) {
3510
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: `chest-holding torso "${torsoName}"`,
3511
+ detail: 'needs a declared bust: give --bust-landmarks <file> or --no-bust "<reason>"' }]);
3512
+ } else {
3513
+ const { apex_r, apex_l } = bust.landmarks;
3514
+ let cleavage = bust.landmarks.cleavage;
3515
+ if (cleavage === undefined) {
3516
+ // #475's clearance identity requires cleavage on the apex segment, between the two apices.
3517
+ const apexDeltaX = apex_l[0] - apex_r[0];
3518
+ const apexDeltaY = apex_l[1] - apex_r[1];
3519
+ const midlineDeltaX = hip[0] - neckAt[0];
3520
+ const midlineDeltaY = hip[1] - neckAt[1];
3521
+ const cross = apexDeltaX * midlineDeltaY - apexDeltaY * midlineDeltaX;
3522
+ const share = ((neckAt[0] - apex_r[0]) * midlineDeltaY - (neckAt[1] - apex_r[1]) * midlineDeltaX) / cross;
3523
+ if (!Number.isFinite(share) || share <= 0 || share >= 1) {
3524
+ throw new PartsError([{
3525
+ code: 'PROPOSE_BUST_INPUT', object: 'landmarks.cleavage',
3526
+ detail: `the neck-to-hip midline ${fmtAt(neckAt)} -> ${fmtAt(hip)} has no unique crossing inside apex_r ${fmtAt(apex_r)} -> apex_l ${fmtAt(apex_l)}. Declare cleavage explicitly or place the apices on opposite sides of the torso midline`,
3527
+ }]);
3528
+ }
3529
+ // Derived coordinates use the same fixed-point grid the contour config reader requires.
3530
+ cleavage = [
3531
+ pyRound((apex_r[0] + share * apexDeltaX) * GRID) / GRID,
3532
+ pyRound((apex_r[1] + share * apexDeltaY) * GRID) / GRID,
3533
+ ];
3534
+ }
3535
+ const landmarks: ContourBustSpec = { apex_r, apex_l, cleavage };
3536
+ contour.bust = landmarks;
3537
+ for (const side of ['r', 'l'] as const) {
3538
+ const name = `boob_${side}`;
3539
+ const apex = landmarks[`apex_${side}`];
3540
+ // Unlike ratio placements, declared landmarks retain their subpixel coordinates.
3541
+ bones.push({ name, parent: 'chest', at: [apex[0], apex[1]] });
3542
+ records.push({ bone: name, entry: name, origin: placement('derived', `declared bust landmark apex_${side} in rig pixels`, {
3543
+ parts: [source.name], bones: ['chest'],
3544
+ }), tip: null });
3545
+ }
3546
+ notes.push(`${torsoName}: contour.bust from declared apex_r/apex_l. Cleavage ${bust.landmarks.cleavage === undefined ? 'derived at the apex segment crossing of the neck-to-hip midline' : 'declared'}. Bones boob_r/boob_l are parented to chest`);
3547
+ }
3548
+ const chains = new Set(bones.flatMap(b => 'chain' in b
3549
+ ? [b.chain, ...b.points.map((_, index) => `${b.chain}${index}`)]
3550
+ : []));
3551
+ const onChain = segments.some(segment => chains.has(typeof segment === 'string' ? segment : segment[0]));
3552
+ meshes[torsoName] = {
3553
+ contour,
3554
+ r: lattice !== undefined && 'grid' in lattice ? lattice.r : radius,
3555
+ segments,
3556
+ ...(onChain ? { influences: { maxInfluences: null, floor: 'continuous' as const } } : {}),
3557
+ };
3558
+ delete regions[torsoName];
3559
+ if (onChain) notes.push(`${torsoName}: contour segments name a chain. Drafted influences.maxInfluences=null and floor=continuous to avoid the influence cut's weight step across short outline edges (issue #991)`);
3560
+ } else if (bust.landmarks !== undefined) {
3561
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'chest carrier', detail: `no topwear art covers chest at ${fmtAt(chest)}. A chest-holding topwear part is required for the declared bust input` }]);
3562
+ }
3418
3563
  if (gridRule === 'figure') {
3419
3564
  const latt = Object.keys(meshes).filter((m) => 'grid' in meshes[m] && ownGrid.has(m));
3420
3565
  if (latt.length > 0) notes.push(gridNote(fig, latt.map((m) => [m, ownGrid.get(m) as number])));
@@ -0,0 +1,76 @@
1
+ /** Optional source-bound independent assembly domains (#998). */
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { SUPPORT_GRID_CODE, type SupportDomain, type SupportDomainReading } from './coincide.ts';
6
+ import { refuseIfAny } from './errors.ts';
7
+ import type { PartsFile } from './parts.ts';
8
+
9
+ export const SUPPORT_DOMAINS_FILE = 'part_support_domains.json';
10
+ const SPEC = 'rig-parts-support-domains/1';
11
+ const sha = (data: Uint8Array | string): string => createHash('sha256').update(data).digest('hex');
12
+ const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
13
+ const digest = (v: unknown): v is string => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
14
+
15
+ /** Sorted flattened [start,length] runs retain the assembler's exact mask.
16
+ * The reader decodes them; it never re-derives a second polygon rasteriser. */
17
+ function runs(data: Uint8Array): Array<[number, number]> {
18
+ const out: Array<[number, number]> = [];
19
+ for (let p = 0; p < data.length; p++) {
20
+ if (data[p] === 0) continue;
21
+ const start = p;
22
+ while (p + 1 < data.length && data[p + 1] !== 0) p++;
23
+ out.push([start, p - start + 1]);
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /** Only a separate optional file is written. Existing parts and PNGs are read. */
29
+ export function writeSupportDomains(partsPath: string, partsDir: string, parts: PartsFile, domains: readonly SupportDomainReading[], declarations: string): void {
30
+ const entries = parts.parts.map(part => {
31
+ const domain = domains.find(d => d.part === part.name);
32
+ if (domain !== undefined && 'mask' in domain) return { part: part.name, status: 'measured', provenance: domain.provenance, runs: runs(domain.mask.data) };
33
+ const reason = domain !== undefined ? domain.reason : part.limb !== undefined
34
+ ? `limb segment "${part.name}" has joint lines but no authored radial width; the art-derived cap radius is not an independent witness`
35
+ : 'no authored spatial cut domain; config.regions is only a bone binding';
36
+ return { part: part.name, status: 'unavailable', reason };
37
+ });
38
+ writeFileSync(join(dirname(partsPath), SUPPORT_DOMAINS_FILE), JSON.stringify({
39
+ spec: SPEC, grid: parts.rig_size, declarations_sha256: sha(declarations), parts_sha256: sha(readFileSync(partsPath)),
40
+ images: parts.parts.map(p => ({ part: p.name, sha256: sha(readFileSync(join(partsDir, `${p.name}.png`))) })),
41
+ domains_sha256: sha(JSON.stringify(entries)), domains: entries,
42
+ }, null, 2) + '\n');
43
+ }
44
+
45
+ /** Missing/stale evidence is unavailable. A dimension mismatch is a named
46
+ * refusal because source and setup cells cannot be compared on different grids. */
47
+ export function readSupportDomains(partsPath: string, partsDir: string, parts: PartsFile): SupportDomainReading[] {
48
+ const unavailable = (reason: string): SupportDomainReading[] => parts.parts.map(p => ({ part: p.name, reason }));
49
+ const file = join(dirname(partsPath), SUPPORT_DOMAINS_FILE);
50
+ if (!existsSync(file)) return unavailable('independent support sidecar is unavailable (legacy output)');
51
+ let raw: unknown;
52
+ try { raw = JSON.parse(readFileSync(file, 'utf8')); } catch { return unavailable('independent support sidecar is not readable JSON'); }
53
+ if (!object(raw) || raw.spec !== SPEC || !Array.isArray(raw.grid) || raw.grid.length !== 2 || !raw.grid.every(v => Number.isSafeInteger(v) && v > 0)) return unavailable('independent support sidecar has no valid spec or native grid');
54
+ const [width, height] = parts.rig_size;
55
+ if (raw.grid[0] !== width || raw.grid[1] !== height) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: SUPPORT_DOMAINS_FILE, detail: `declares ${raw.grid.join('x')}; parts.json requires ${width}x${height}` }]);
56
+ if (!digest(raw.declarations_sha256) || raw.parts_sha256 !== sha(readFileSync(partsPath)) || !Array.isArray(raw.images) || raw.images.length !== parts.parts.length || !Array.isArray(raw.domains) || raw.domains.length !== parts.parts.length || raw.domains_sha256 !== sha(JSON.stringify(raw.domains))) return unavailable('independent support sidecar does not bind these parts or its domain payload');
57
+ for (let i = 0; i < parts.parts.length; i++) {
58
+ const binding: unknown = raw.images[i], part = parts.parts[i];
59
+ if (!object(binding) || binding.part !== part.name || binding.sha256 !== sha(readFileSync(join(partsDir, `${part.name}.png`)))) return unavailable(`independent support sidecar PNG binding differs for "${part.name}"`);
60
+ }
61
+ const domains: SupportDomainReading[] = [];
62
+ for (let i = 0; i < parts.parts.length; i++) {
63
+ const row: unknown = raw.domains[i];
64
+ if (!object(row) || row.part !== parts.parts[i].name) return unavailable('independent support sidecar does not name every part in assembly order');
65
+ if (row.status === 'unavailable' && typeof row.reason === 'string' && row.reason.length > 0) { domains.push({ part: row.part, reason: row.reason }); continue; }
66
+ if (row.status !== 'measured' || !object(row.provenance) || row.provenance.kind !== 'cut-polygon' || typeof row.provenance.entry !== 'string' || !Array.isArray(row.runs)) return unavailable(`independent support domain for "${row.part}" lacks authored cut provenance or runs`);
67
+ const data = new Uint8Array(width * height);
68
+ let previous = 0;
69
+ for (const run of row.runs) {
70
+ if (!Array.isArray(run) || run.length !== 2 || !run.every(Number.isSafeInteger) || run[0] < previous || run[1] <= 0 || run[0] + run[1] > data.length) return unavailable(`independent support runs for "${row.part}" are invalid or overlap`);
71
+ data.fill(1, run[0], run[0] + run[1]); previous = run[0] + run[1];
72
+ }
73
+ domains.push({ part: row.part, mask: { width, height, data }, provenance: row.provenance as unknown as SupportDomain['provenance'] });
74
+ }
75
+ return domains;
76
+ }