spine-parts 2.38.1 → 2.40.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/cli.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  import { diffComponentsCommand } from './src/diffcomponents.ts';
3
3
  import { applyTakenLayers } from './src/takelayers.ts';
4
- import { applyDepth, prepareDepth } from './src/depthworkflow.ts';
4
+ import { applyDepth, bindDepthMap, prepareDepth } from './src/depthworkflow.ts';
5
5
  /**
6
6
  * rig-parts — one painting and its See-through layers in, Spine-ready parts
7
7
  * and rig specs out, verified through rig-c.
@@ -74,7 +74,7 @@ const HELP = `rig-parts ${version()} — Spine-ready parts from one painting and
74
74
 
75
75
  usage:
76
76
  rig-parts diff-components --stack <png> --painting <png> --parts <parts.json> --floor <px>
77
- [--threshold <channel>] [--figure <binary-png>] (--out <json> | --verify <json>)
77
+ [--threshold <channel>] [--figure <binary-png>] [--owners] (--out <json> | --verify <json>)
78
78
  Exhaustive native difference inventory; default max RGB channel > 40.
79
79
 
80
80
 
@@ -82,6 +82,10 @@ usage:
82
82
  Write per-part inference PNGs on neutral gray, upscaled and padded as
83
83
  declared, plus a source-hashed manifest. No model is bundled or called.
84
84
 
85
+ rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>
86
+ Write <map>.binding.json with both file hashes; never overwrite a receipt.
87
+ Attests the current files, not that inference used this input.
88
+
85
89
  rig-parts depth-apply --parts <assembled-dir> --manifest <manifest.json> --config <depth-recipe.json> --rig-config <config.json> --out <empty-dir>
86
90
  Register floating-point JSON depth or signed normals, normalize inside
87
91
  alpha >=128, apply declared median/relief and group near/zScale/pivot,
@@ -1075,7 +1079,15 @@ function usage(message: string): number {
1075
1079
  }
1076
1080
 
1077
1081
  function cmdDiffComponents(args: string[]): number {
1082
+ const switches: readonly string[] = TAKES['diff-components'].switches;
1083
+ const seen = new Set<string>();
1078
1084
  for (let i = 0; i < args.length; i += 2) {
1085
+ if (switches.includes(args[i])) {
1086
+ if (seen.has(args[i])) return usage(`${args[i]} is given twice`);
1087
+ seen.add(args[i]);
1088
+ i--;
1089
+ continue;
1090
+ }
1079
1091
  if (!takesValued('diff-components', args[i])) return usage(notTaken('diff-components', args[i]));
1080
1092
  if (args[i + 1] === undefined || args[i + 1].startsWith('--')) return usage(`diff-components ${args[i]} requires a value`);
1081
1093
  }
@@ -1171,7 +1183,8 @@ function printLayerTable(set: LayerSet): void {
1171
1183
  */
1172
1184
  const TAKES = {
1173
1185
  'check-parts': { valued: ['--parts', '--out'], switches: ['--json'] },
1174
- 'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: [] },
1186
+ 'diff-components': { valued: ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'], switches: ['--owners'] },
1187
+ 'depth-bind': { valued: ['--map', '--input', '--part'], switches: [] },
1175
1188
  'depth-prepare': { valued: ['--parts', '--config', '--out'], switches: [] },
1176
1189
  'depth-apply': { valued: ['--parts', '--manifest', '--config', '--rig-config', '--out'], switches: [] },
1177
1190
  layers: { valued: ['--export', '--template', '--canvas', '--full', '--source', '--config'], switches: [] },
@@ -1787,7 +1800,7 @@ function cmdPropose(args: string[]): number {
1787
1800
  if (target !== null) for (const line of configWriteLines(target, staged.changes)) console.error(line);
1788
1801
  }
1789
1802
  console.log(`wrote proposal.json (${prop.bones.length} bone entries, ${Object.keys(prop.meshes).length} meshes) and render/landmarks.png (+_head) under ${out}`);
1790
- for (const n of prop.notes) console.log(`note: ${n}`);
1803
+ for (const n of prop.notes) console.log(n.startsWith('WARN PROPOSE_TORSO_ISLAND_LEFT_OUT:') ? n : `note: ${n}`);
1791
1804
  if (leftBehind.unread !== null) console.log(`note: the keyed chains were not read after the recipe (issue #572): ${leftBehind.unread}`);
1792
1805
  printLint(P, prop, joints, [...draftLint, ...leftBehind.findings]);
1793
1806
  console.log(basisLine(bfile, out));
@@ -2479,6 +2492,17 @@ function cmdDepthPrepare(args: string[]): number {
2479
2492
  } catch (error) { return printRefusal(error); }
2480
2493
  }
2481
2494
 
2495
+ function cmdDepthBind(args: string[]): number {
2496
+ const f = flags(args, 'depth-bind', ['--map', '--input', '--part']);
2497
+ if (typeof f === 'string') return usage(f);
2498
+ try {
2499
+ const result = bindDepthMap({ map: f.get('--map')!, input: f.get('--input')!, part: f.get('--part')! });
2500
+ console.log(`depth-bind: part "${result.part}" mapSha256=${result.mapSha256} inputSha256=${result.inputSha256}; wrote map binding receipt`);
2501
+ console.log('depth-bind: binds these files at invocation; does not prove the map was inferred from this input');
2502
+ return EXIT_OK;
2503
+ } catch (error) { return printRefusal(error); }
2504
+ }
2505
+
2482
2506
  function cmdDepthApply(args: string[]): number {
2483
2507
  const f = flags(args, 'depth-apply', ['--parts', '--manifest', '--config', '--rig-config', '--out']);
2484
2508
  if (typeof f === 'string') return usage(f);
@@ -2503,6 +2527,7 @@ function main(argv: string[]): number | Promise<number> {
2503
2527
  if (command === 'diff-components') return cmdDiffComponents(rest);
2504
2528
  if (command === 'layers') return cmdLayers(rest);
2505
2529
  if (command === 'depth-prepare') return cmdDepthPrepare(rest);
2530
+ if (command === 'depth-bind') return cmdDepthBind(rest);
2506
2531
  if (command === 'depth-apply') return cmdDepthApply(rest);
2507
2532
  if (command === 'sheet') return cmdSheet(rest);
2508
2533
  if (command === 'rig') return cmdRig(rest);
package/docs/AUTHORING.md CHANGED
@@ -181,7 +181,7 @@ read by no CPU stage).
181
181
  | `constraints` | rig (handed to rig-c as `rig.json`'s `constraints`); `compare` and the coverage lines (roles) | **authored**, optional; `propose` writes none, but with `--cloth` (issue #364), where it writes the recipe's physics and swing transforms (*Recipe: cloth and hair that answer the world*, below). A list of constraints in **rig-c's own rig-spec shape** (`RigConstraint`: `ik`, `transform`, `path`, `physics`, `slider` — rig-c's `src/rig.ts` documents every field), in the order rigc applies them. The loader checks only what this package owns: each entry is an object with a `type` rigc names (`CONFIG_CONSTRAINT_TYPE_KNOWN`) and a non-empty `name`, unique within its kind as rigc finds constraints (`CONFIG_CONSTRAINT_NAME_UNIQUE`; an ik and a transform may share one); every bone it names — `bones`, an ik's `target`, a transform's `source`, a physics or slider constraint's `bone` — is a bone `bones` declares, a chain link as `<chain><i>` (`CONFIG_NAME_RESOLVES`); the bone a constraint follows does not sit under a bone it drives (`CONFIG_CONSTRAINT_TARGET_DETACHED`). Every other field (`mix`, `softness`, `properties`, a path's `slot`, a slider's `animation`) and every value is rigc's to accept or refuse at the rig stage's gate, in rigc's words (`RIG_RIGC_GREEN`) — an ik's `bones` as a shape too: from rig-c 2.15.0 rigc refuses an ik over more than two bones, or over a pair whose second bone is not the first's child (issue #103; this loader refused both itself until then). A note and an `x-` record may ride on an entry; the rig stage leaves them out of what it hands rigc. Under the default `--idle-keys ctl` a two-bone ik whose child link the idle keys is split by that link's control, and rigc refuses the pair: run `rig --idle-keys direct` or `build --idle-keys direct` (the rig stage adds that sentence, naming the flag on the command that ran, to rigc's line; `build` forwards it to its rig stage, issue #95). Each bone a constraint follows is declared to rigc as `invariants.detached` from every bone it drives, which rigc's gate rule `A25` checks |
182
182
  | `stops` | rig (handed to rig-c as `rig.json`'s `stops`, and moves slots, mesh weights and child bones on stopped links onto `<link>_d`); `propose --from-config` (`LINT stop on <chain> …`) | **authored**, optional (issues #404, #447): `[{chain, links?, against, at, inward, outward, lower?: {inward, outward}}]` — rig-c's leg stops (`RigStop`, rig-c 2.56.0, `@rig-c/core/stop`). `chain` is a chain `bones` declares (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `links`, optional, is a non-empty list of links of that chain (`CONFIG_NAME_RESOLVES`, `CONFIG_FIELD_TYPE`), or absent for every link of `chain` in chain order; `against` is a bone `bones` declares, a chain link as `<chain><i>` (`CONFIG_NAME_RESOLVES`, `RIG_NAME_RESOLVES`); `at` is `[x, y]` in `against`'s local space, as rig-c's stop takes it (`CONFIG_FIELD_TYPE`): since each chain link (`leg_r0`, `leg_r1`) is turned to point along its segment (`+x` from origin to next link or tip, `+y` 90° counter-clockwise in Spine world), `at: [d, n]` sits `d` px from `against`'s origin toward its end and `n` px perpendicular to it; `inward`, `outward` and `lower.inward`, `lower.outward` are finite numbers (`CONFIG_FIELD_TYPE`). Every other stop rule — non-negative bounds, each stopped link written by a constraint, `against` not under the stopped chain, the aim not degenerate, `\|rest\| + outward <= 180°` (`RIG_STOP_BOUNDS`) — is rigc's to accept or refuse at the rig stage's gate, in rigc's words (`RIG_RIGC_GREEN`). **Rising-limb / prone geometry (issue #447):** rig-c's `expandStops` aims `<chain>_rest` from `links[0]`'s setup origin at `<chain>_touch` (`at` in `against`'s local frame) and clamps `<link>_d` inside `[rest − inward, rest + outward]`; Spine wraps rotation at `±180°`, so `\|rest\| + outward <= 180°` is required (`RIG_STOP_BOUNDS`). Whenever `<chain>_touch` lies **above** `links[0]`'s root in rig pixels (`ty < y0`, i.e. higher Spine `y` — e.g. stopping a hanging cloth chain against a rising shin `leg_<s1>` in a prone or kneeling pose where the knee sits below `links[0]` and the ankle above it, so positive `at[0]` walks upward along the shin past `links[0]`'s root), `rest` lands in the upper half-plane (`\|rest\| > 90°`) and `\|rest\| + outward` exceeds `180°`. Stop against the descending thigh (`leg_<s0>`), set `links` to start at a link whose root sits above `<chain>_touch`, or omit the stop when the rising shin sits outside the hanging chain's sweep; `propose --from-config` prints `LINT stop on <chain> …` with the exact coordinates and angles when `<chain>_touch` lies above `links[0]`'s root or `\|rest\| + outward > 180°`. For every stopped link `<link>`, the rig stage moves any slot on `<link>`, any mesh weight on `<link>`, and any bone whose parent is `<link>` (a branched cloth tree's branches hanging from `<trunk_last>`, before `--idle-keys ctl` adds `<bone>_ctl` and before `turn` adds `turn_<part>_<bone>`) onto `<link>_d`, the drawn link bone rig-c's `expandStops` creates at `<link>`'s setup frame to carry the clamped rotation. Absent, `rig.json` carries no `stops` and no byte of any output moves |
183
183
  | `turn` | rig (adds the turn control or 2.5D head-turn producer) | **proposed** only with `propose --full`/`--head` (issue #251), then corrected, or **authored** for 2.5D depth-sampled head turns (issue #763): `{pivot?, depths?, deform?, band?, radius?, surface?: {radius?}, head?: {pivot?, radius?}, roles?, counter?, grid?, unitDepths?, body?}`. When `roles` is declared (`{<part>: "surface" \| "unit" \| "rear"}`, issue #763; `CONFIG_TURN_ROLE_UNKNOWN`, `CONFIG_TURN_SURFACE_REQUIRED`, `RIG_TURN_SURFACE_MESH_BINDINGS`, `CONFIG_TURN_UNIT_MESH_BONES`), the rig stage runs the 2.5D depth-sampled head-turn producer: it edge-extends each turn-bound part's depth sheet across its transparent border and semi-transparent fringe from the nearest fully opaque (`alpha === 255`) texel before `PAD = 4` clamping (`padTurnDepthSheet`, `DEPTH_SILHOUETTE_SIZE_MISMATCH`), keeps authored `"surface"` meshes and their skinning (#795), sampling each vertex at its weighted setup position on its own extended sheet and emitting one inverse-setup-bone offset per influence (`D = -(pivot + z - zRef) * sin(angle)`, on x for yaw and y for pitch, with no narrowing or 2D spin); shared frames moved by another turn role are refused (`RIG_TURN_SURFACE_MESH_BINDINGS`), as are alternate drawings without their own depth sampling frame (`RIG_TURN_SURFACE_MESH_ATTACHMENT`). It promotes `"surface"` regions to `generator: {kind: "grid", cols, rows, depth}` (`grid`: `[cols, rows]` or `{<part>: [cols, rows]}`, default `[13, 16]`, bounded at `<= 2,400` triangles per slot and `<= 4,000` total, `RIG_TURN_GRID_BUDGET`, `RIG_TURN_SURFACE_DEPTH_REQUIRED`, `RIG_TURN_SHARED_DEPTH_SCALE`), emits `faceshift` and `rear_shift` under `head` (`CONFIG_TURN_HEAD_BONE`, `RIG_TURN_HEAD_BONE`), `<part>_surface` and `<part>_unit` under `faceshift`, and `yaw_dial` and `pitch_dial` under `root` (`CONFIG_TURN_BONE_FREE`, `RIG_TURN_NAME_FREE`), re-parents `"unit"` region bones and `"rear"` bones and mesh weights to `faceshift` and `rear_shift` (while `"unit"` mesh parts receive their own `<part>_unit` carrier under `faceshift`, rebind direct `"head"` weights to `<part>_unit`, reparent bound chain roots to `<part>_unit` while keeping chain skinning weights intact, and key `<part>_unit` in `turn_units`, #790), samples each `"unit"` bone's depth from the `"surface"` depth sheet at its rest position (or reads `unitDepths.<part>`, `RIG_TURN_UNIT_DEPTH_REQUIRED`), enforces ear occlusion (`ear_r`/`ear_l` drawn before the `face` surface in `assemble.plan`, `CONFIG_TURN_EAR_DRAW_ORDER`, and behind the cheek surface, `RIG_TURN_EAR_DEPTH_BEHIND_CHEEK`), and writes `turn` and `tilt` `derive` tracks (`pivot` default `55` rig px, `counter` default `0.1` in `[0, 1]`, `CONFIG_TURN_COUNTER_RANGE`). `depths` holds, per part, the See-through layer's `depth_median` the part came from (larger = further back), read from the run the part was assembled from; a `painting:` patch has none and is not carried. A rider (issue #271) — a part from an `eyewhite`, `irides`, `eyelash`, `eyebrow`, `nose` or `mouth` layer — is drafted at the `face` part's depth, 0.001 nearer when parts.json draws it after the face and 0.001 further when before: See-through makes no depth of its own for the eye group (it cuts them from one depth map of the combined eyes) and clamps nose and mouth to the face's median − 0.001, and the two runs' own medians for these layers disagreed by up to 0.47 and swapped their order against the face. Every other layer — ears, headwear and earwear included — keeps its own median, unless it rides another part's bone. With no `face` part, or more than one, the riders keep their own and a note says so. A rider by bone (issue #535) — a part every *ownable* bone of which (a chain link, or a bone no other bone hangs from; `head`, `chest` and any bone with a child are shared and never count on their own) is *hosted* by another carried part, the host of a bone being the carried part that binds it (its region's bone; a mesh's `segments`, `contour` and `auto` regions' bones) with the most `opaque_px`, the earlier in parts.json on a tie, and which hosts no bone itself — is drafted at its host's depth, 0.001 nearer when drawn after the host and 0.001 further when before, and a note names the host, the bones and its own median: a pin, clip or ornament on the back hair's links travels with the back hair, not with its own layer's depth. `propose` reads the proposal's own `bones`, `meshes` and `regions`; the face riders are read by their tag first and never by their bones. A part bound to two hosts' bones rides neither and a note says so. In the rig stage, an authored depth on a rider by bone whose fraction differs from its host's by more than 0.1 of the dial (`TURN_RIDER_APART`, a share of `pivot − nearest`) is refused (`CONFIG_TURN_RIDER_DEPTH`); the host is read off `parts.json`'s `opaque_px`, so the config loader cannot see it. One note lists each part's depth and where it came from; a carrier the other run places more than 10 % of `pivot − nearest` away gets a note naming both values and the run read — the two runs are not reconciled. `pivot` is the depth that stays put; `propose` drafts the mean of the parts' depths weighted by `opaque_px`, the one depth at which the painted pixels' centroid does not slide under the dial. The rig stage adds a bone `turn` under `root` at its origin that nothing keys — its local x is the dial, in rig px — and carries each part by `(pivot − depth) / (pivot − nearest depth)` of it: the nearest part all of it, a part behind the pivot the other way, a part at the pivot not at all. Each part rides leaf twins (`turn_<part>_<bone>`, an identity child of every bone its slot and weights bind) moved by one `transform` constraint (`turn_<part>`, after the config's own); the idle's keys, the `<bone>_ctl` controls and a physics constraint stay on the bones, and the dial moves none of them. Optional `deform` (`Partial<FaceDeformFractions>`, issue #436) overrides the Set B ×2.5 face surface deformation table (`FACE_DEFORM_FRACTIONS`, checked against `FACE_DEFORM_RANGES` by `CONFIG_TURN_DEFORM_RANGE`); when `applyFaceSurfaceDeform` runs on a rig whose `motion` carries `tilt` or `turn` slider `derive` keys, it requires `config.turn` (`CONFIG_TURN_REQUIRED`, issue #478; `propose --full`/`--head` drafts it), promotes `face` on `head` (or `turn_face_head` when `turn` is declared) to the uneven 5×5 grid mesh, keys `face`, `hair_front` and `hair_back` deform timelines and ear/topknot tracks from `evalPitchFaceSurface` and `evalYawFaceSurface`, and samples the same deform field across each `features` member's rest span (`featRx = (24 / 106) · W`, `featRy = (12 / 128) · H`) with its depth fraction `z / zRef` as the field's angle input and chord foreshortening (`scalex` narrowing on the leading side and widening on the trailing side, `scaley` on pitch) so every feature's bounding box stays inside the deformed face plate across the rated band (issue #468). On yaw (`issue #479`), `evalYawFaceSurface` evaluates a **cylinder projection** (`cylinderYawDx`: `Δx(x, θ, R) = R · (sin(clamp(arcsin(clamp(x / R, −1, 1)) − θ, −π/2, π/2)) − clamp(x / R, −1, 1))`) of radius `R` (`turnSurfaceRadius`: `turn.surface.radius ?? turn.radius ?? turn.head.radius`, positive rig px checked by `CONFIG_FIELD_TYPE`, defaulting to half the face plate's opaque width `W / 2`) tapered by a cubic Hermite outline weight (`wOutline = 1` for `\|ux\| <= 0.7`, reaching `0` at `\|ux\| = 1.0`) so features slide across a fixed outline (`iris` shift within `±2%` of `cylinderYawDx`), the trailing cheek strip widens (`>= 1.54×` at `±15°`), and the leading jaw edge holds fixed (`0 px` shift) unless explicit horizontal `turn.deform` overrides (`turn_mid_x`, `turn_lead_compress_x`, `turn_trail_shift_x`) request the flat yaw table. On yaw (`issue #478`), `applyFaceSurfaceDeform` also derives a **head-only pivot** (`headTurnPivot`: `turn.head.pivot` when authored, otherwise the `opaque_px`-weighted mean of `depths[part]` across the head parts `DEFAULT_HEAD_TURN_PARTS` — `face`, `hair_front`, `hair_back`, `ear_r`, `ear_l`, `hairpin` — from `parts.json`, falling back to `turn.pivot`) so a forward torso or arm in `turn.depths` does not pull the head's rotation axis in front of `face`: `hair_back` (`depth_median > headPivot`, negative `headTurnFraction`) and `hairpin` behind `headPivot` translate opposite to the face's turn (`dx = s · turn_face_center_x · W · (headPivot − depth) / (headPivot − nearestHeadDepth)`), emerging on the trailing side to compensate for the leading-cheek foreshortening and keeping the combined head silhouette width near-constant across `±15°` without any same-sign `turn_hair_back_cheek_x` term. Optional `band` (`number` or `{yaw?, pitch?}`, positive degrees, issue #472) declares the rig's rated face turn band (default `FACE_RATED_BAND`: `yaw <= 15°`, `pitch <= 12°`); declaring a `turn.band` or a `motion.animations_from` `turn`/`tilt` `derive.degrees` above `±15°` yaw or `±12°` pitch without an `assemble.alternates` entry that replaces `face` is refused (`CONFIG_FACE_BAND_EXCEEDED`), and on a single-plate rig `applyFaceSurfaceDeform` adds self-targeting transform constraints `yaw_clamp` (`[-15, 15]`) and `pitch_clamp` (`[-12, 12]`) ahead of the slider constraints so driving `yaw` or `pitch` beyond the rated band clamps at the boundary. At rest: with `turn` declared, no pixel differs by more than 1 level at dial 0 (not byte-identical; the cause is float noise in the identity child bones, and the constraints add nothing); without `turn`, byte-identical. Neither `pivot` nor `depths` has a default (`CONFIG_FIELD_PRESENT`); `pivot` and `head.pivot` must lie behind the nearest part (`CONFIG_TURN_PIVOT_BEHIND_NEAREST`). Absent, no control is added and no byte of any output moves |
184
- | `scene` | assemble (the recomposite, its holes and the figure's mask); check, through `parts.json`'s `scene` block (`RECOMPOSITE_HOLES`, the seam) | **authored**, optional; `propose` writes none (issue #242). `{}` declares the painting a scene: the figure and its surroundings in one image, See-through's full run holding only the figure. With it, `assemble` reads the recomposite figures, the hole list and the `uncovered:` lines inside the figure — the rig pixels where any full-run layer's alpha is above 8 (`OPAQUE_ALPHA_ABOVE`, the cut every layer's painted pixels are read by) — each line starting `inside the figure (config.scene: …, <n> of <m> rig px)`; writes that figure as `figure_rig.png` (white on black) beside the recomposite (and the same bytes beside `parts.json` when standalone `assemble` writes it to another directory, issue #1177), and a `scene` block in `parts.json`; flags error pixels on the error map inside it only (outside, the painting grey); and `check` leaves out of the seam every frame pixel whose composite sample reaches the painting's outermost row or column, saying how many (`seam_border` in `check.json`, and on the seam line). It takes no field: the figure and its threshold are derived. A key in it other than a record or an annotation is `CONFIG_KEY_KNOWN`. Absent, no byte of any output moves |
184
+ | `scene` | assemble (the recomposite, its holes and the figure's mask); check, through `parts.json`'s `scene` block (`RECOMPOSITE_HOLES`, the seam) | **authored**, optional; `propose` writes none (issue #242). `{}` declares the painting a scene: the figure and its surroundings in one image, See-through's full run holding only the figure. With it, `assemble` reads the recomposite figures, the hole list and the `uncovered:` lines inside the figure — the rig pixels where any full-run layer's alpha is above 8 (`OPAQUE_ALPHA_ABOVE`, the cut every layer's painted pixels are read by) — each line starting `inside the figure (config.scene: …, <n> of <m> rig px)`; writes that figure as `figure_rig.png` (white on black) beside the recomposite (and the same bytes beside `parts.json` when standalone `assemble` writes it to another directory, issue #1177), and a `scene` block in `parts.json`; flags error pixels on the error map inside it only (outside, the painting grey); and `check` leaves out of the seam every frame pixel whose composite sample reaches the painting's outermost row or column, saying how many (`seam_border` in `check.json`, and on the seam line). When `assemble` writes `figure_rig.png`, it also prints `figure mask (figure_rig.png):` and one `figure rim full:<tag>` row per full-run layer with a nonzero count, naming the union `alpha >= 250` core, the outer `alpha 9..127` soft rim in the 4-connected exterior of that core and its pixels more than 40 (`ERROR_LIMIT`) off the painting in the rig, and the mask pixels outside every emitted part at `alpha > 8`: when a soft rim over a contrasting ground or an outside-all-parts island is present, declare `setup_painting.figure_mask` for an independent figure domain, or retouch against the painting only inside the `alpha >= 250` core (issue #1297). It takes no field: the figure and its threshold are derived. A key in it other than a record or an annotation is `CONFIG_KEY_KNOWN`. Absent, no byte of any output moves |
185
185
  | `cloth` | `propose --cloth` only; no other stage reads it, so it moves no byte of any build | **authored**, optional (issue #364): one recipe per tag, `{"bottomwear": {…}, "back hair": {…}, "front hair": {…}}`, each `{chains, links, wind, gravity, split?, length_ratio?, strength?, damping?, alternate_damping?, translate?, swing?, part?, influence?}`. `influence` (issue #518) — `{across, max, shape, radius?}`: the parts this recipe meshes are drafted in the influence mode (`meshes.<part>.influence` above) at their lattice's cell, with `across`, `max` and `shape` as declared (each required — the reading behind the radius did not vary them) and `radius` as declared or, absent, drafted as the farthest vertex's distance plus 3 cells (the `influence.radius` row); without it the parts keep their lattice. `chains` — trees across the piece (for `back hair`, per side of the eye axis), a whole number, 1 or more; `links` — links from root to tip on every path, 1 or more; `split` — `{at, into}`: the first `at` links are the trunk, which forks into `into` (2 or more) branches; `at` below `links` (`CONFIG_CLOTH_SPLIT_BEFORE_TIP`); `length_ratio` — a path's last link over its first, above 0, default 0.5; `strength` — `{trunk, branch, edge}`, each above 0 and below the spring's stability bound (`CONFIG_CLOTH_SPRING_STABLE`), default 100 / 100 / 50; `damping` — in [0, 1], absent: rig-c's default; `alternate_damping` — the odd trees' damping, in [0, 1], beside `damping` and different from it (`CONFIG_CLOTH_ALTERNATE_DIFFERS`); `wind`, `gravity` — `[root, tip]`, each 0 or more, tip at or above root (`CONFIG_CLOTH_RESPONSE_GROWS_TO_TIP`); `translate` — the x and y mix of a dangling end's flutter, above 0 and at most 1; `swing` — `bottomwear` only, `{scales}`, one positive scale per tree (`CONFIG_CLOTH_SWING_SCALE_PER_TREE`); `part` — `bottomwear` only (`CONFIG_CLOTH_PART_ON_BOTTOMWEAR`), a non-empty part or cut-piece name: the `topwear` part that holds a skirt See-through returned inside it (a dress), or its skirt piece cut by `assemble.cuts`, which takes the skirt's trees (issue #402, *A skirt inside topwear* below; the part is checked by `propose`, `PROPOSE_CLOTH_PART`). The two defaults are the recipe's own, measured on its synthetic fixture (the recipe below). The recipe below says what each field drafts. The config written: `propose --cloth <config.json> --write-config <out.json>` (issue #537) writes this config's own text back with the sections the recipe drafts spliced in — `meshes.<part>` and `regions.<part>`, and `bones`, `constraints` and `motion.tracks` entry by entry by name (issue #552) — and every other byte as read; `--from <previous config>` (issue #571) takes an entry equal to the previous recipe's draft as the recipe's (*The config written*, under the recipe below) |
186
186
  | `proposed_rig_scale` | assemble, rig, build, `propose --from-config`/`--compare` | **proposed** by `propose` (issue #354): `parts.json`'s `scale_rig_per_source`, the `assemble.rig_scale` the rig sections (`bones`, `meshes`, `limbs`, `motion`) were drafted at. Held equal to `assemble.rig_scale` when present (`CONFIG_PROPOSED_RIG_SCALE`; 0, negative or not a number: `CONFIG_FIELD_TYPE`). Absent on a hand-authored config, where no byte of any output moves |
187
187
  | `motion_seams` | propose, assemble, check | Optional `[{part, neighbour}]`, using output part names. Each unordered pair is declared once; self-pairs, unknown names, wrong shapes and unknown fields refuse (`CONFIG_MOTION_SEAM`, `PARTS_MOTION_SEAM`, `CHECK_MOTION_SEAM_DECLARATION`). Empty adds no pair. Assemble copies the declaration into `parts.json`; check merges it with existing pairs and never regenerates a removed declaration. It uses the existing non-root WARN floor and changes no bar or exit status. See *Explicit motion seam observations* below. |
@@ -189,10 +189,24 @@ read by no CPU stage).
189
189
 
190
190
  ### Drafting the chest carrier
191
191
 
192
+ `propose` drafts the chest carrier's largest art island as a contour.
193
+
192
194
  The drafted contour torso also uses mesh-draft's existing dust rule. Extra islands
193
195
  of at most 4 pixels and at most 0.1% of the part's art set `contour.stray` to the
194
196
  largest dust island. The proposal note names the islands and pixels left out.
195
- A real extra piece is refused by `PROPOSE_TORSO_ISLANDS` and must be separated.
197
+
198
+ A non-dust extra island is accepted for omission only when its art-pixel count
199
+ is strictly below the drafted `contour.spacing` squared (`spacing²`). Each such
200
+ island produces a `PROPOSE_TORSO_ISLAND_LEFT_OUT` warning with its art-pixel count
201
+ and bounding box in rig pixels. When islands are omitted, `contour.stray` is set
202
+ to the largest omitted island's art-pixel count, including dust. The `spacing²`
203
+ threshold is a derived sampling-cell area policy; an area below it does not prove
204
+ that no vertex can lie inside the small island.
205
+
206
+ Equal-largest island ties and any non-dust extra island with an art-pixel count
207
+ greater than or equal to `spacing²` are refused by `PROPOSE_TORSO_ISLANDS`.
208
+ The refusal detail includes the threshold; separate the extra pieces before
209
+ drafting. A chest carrier with no art is also refused by that code.
196
210
 
197
211
  `propose --bust-landmarks <landmarks.json>` reads an object with `apex_r` and `apex_l`,
198
212
  and optional `cleavage`, each a finite `[x, y]` in rig pixels (crop origin at top left,
@@ -1122,6 +1136,23 @@ final-alpha partition and resolve replacement writer IDs through the sidecar's
1122
1136
  receipt-associated; this does not exempt other config shapes or baseline
1123
1137
  inputs from their existing source/receipt checks.
1124
1138
 
1139
+ At admission, `assemble` also prints an `edited part front colour:` measurement
1140
+ line for each receipted part (issue #1290): surviving pixels (`alpha > 8`) that
1141
+ the edit changed or added against the base part (`from_sha256`), where the
1142
+ painting pixel's raw-plan owner (`rawPaintingOwner`, the last `assemble.plan`
1143
+ layer with `alpha >= 128`) is a different part drawn in front and the edited
1144
+ RGB lies within `ERROR_LIMIT` (`40`, max channel) of the painting. A positive
1145
+ count means the edited back part carries the front part's painting colour under
1146
+ that front part (hidden at rest while the front part covers it, exposed as a
1147
+ stain when the front part moves); the line reports the edited part, each front
1148
+ owner, the pixel count and the rig-pixel bounding box `[x, y, w, h]`, or `0 px,
1149
+ front owner none, box none` when none. With no declared limit it is a
1150
+ measurement only, never a pass or a refusal. To clear a positive count, remove
1151
+ the front part's colour from the hidden overlap of the edited PNG in the image
1152
+ editor — keep the base part's pixels there or fill the hidden area with the
1153
+ back part's own surface colour rather than sampling the composite painting —
1154
+ and update the receipt's `sha256`.
1155
+
1125
1156
  All replacement refusals happen before output emission, including when an
1126
1157
  output directory already contains a successful build. The folder and every
1127
1158
  existing file remain unchanged. Each code and its remedy is listed in
@@ -3543,7 +3574,8 @@ world units. Other proposal modes (`--keypoints`, `--compare`, `--grid-rule`,
3543
3574
 
3544
3575
  | rule | means | change |
3545
3576
  | --- | --- | --- |
3546
- | <a id="PROPOSE_TORSO_ISLANDS"></a>`PROPOSE_TORSO_ISLANDS` | the chest carrier has no art, tied largest islands, or an extra island exceeding the existing mesh-draft dust limits | separate real pieces so the torso has one largest art island and only dust beside it |
3577
+ | <a id="PROPOSE_TORSO_ISLAND_LEFT_OUT"></a>`PROPOSE_TORSO_ISLAND_LEFT_OUT` | WARN: a non-dust island smaller than one drafted sampling cell is omitted; names its art px and rig-pixel box | inspect the omitted art; separate it if it needs its own mesh; `contour.stray` records the largest omitted island |
3578
+ | <a id="PROPOSE_TORSO_ISLANDS"></a>`PROPOSE_TORSO_ISLANDS` | the chest carrier has no art, equal-largest island ties, or a non-dust extra island with an art-pixel count greater than or equal to the drafted `contour.spacing` squared; the detail includes the threshold | supply art with one uniquely largest island; separate non-dust extra pieces at or above the threshold; dust keeps its existing rule, and smaller non-dust islands are omitted with `PROPOSE_TORSO_ISLAND_LEFT_OUT` |
3547
3579
  | <a id="PROPOSE_BUST_INPUT"></a>`PROPOSE_BUST_INPUT` | a chest torso has neither a bust declaration nor an omission reason, a bust landmark is missing, malformed or unknown, the omission reason is blank or conflicts with landmarks, the midline has no unique crossing inside the apex segment, or the chest carrier is absent or ambiguous, or its recipe declares an incompatible influence mode | give finite rig-pixel apex_r/apex_l and optional cleavage, or a non-blank omission reason; separate overlapping chest-holding topwear |
3548
3580
  | <a id="PROPOSE_NECK_BODY_TURN"></a>`PROPOSE_NECK_BODY_TURN` | no authored sampled body turn | follow this recipe and supply the named input; the refusal writes no config |
3549
3581
  | <a id="PROPOSE_NECK_PLAN"></a>`PROPOSE_NECK_PLAN` | no unique neck plan row | follow this recipe and supply the named input; the refusal writes no config |
@@ -5710,7 +5742,7 @@ recorded transform. The record fields and sampling formula are specified in
5710
5742
  | <a id="PARTS_PAINTING_REFERENCE_WRITE"></a>`PARTS_PAINTING_REFERENCE_WRITE` | Reference publication failed | Preserve existing files and retry with the same sealed inputs |
5711
5743
  | <a id="DIFF_COMPONENTS_INPUT"></a>`DIFF_COMPONENTS_INPUT` | `diff-components` needs readable PNG stack/painting/part images, a writable `--out` target when writing, explicit parts, positive integer floor, a finite threshold in [0,255], matching native dimensions and valid coverage/domain inputs; flags must be unique and known, with nonempty values | Supply the named missing or invalid input; no resampling or inferred figure is performed |
5712
5744
  | <a id="DIFF_COMPONENTS_BINDING"></a>`DIFF_COMPONENTS_BINDING` | The shipped report reader found a stack or painting SHA-256 different from the supplied bytes; found and required digests are printed | Regenerate against the bytes being reviewed |
5713
- | <a id="DIFF_COMPONENTS_REPORT"></a>`DIFF_COMPONENTS_REPORT` | Invalid report JSON/spec, or its exhaustive inventory, definition, paths, domain or coverage differs from remeasurement; capped inventories are refused | Regenerate the complete versioned report against the same input paths, bytes, parts and figure domain |
5745
+ | <a id="DIFF_COMPONENTS_REPORT"></a>`DIFF_COMPONENTS_REPORT` | Invalid report JSON/spec (`rig-parts-diff-components/1` or `rig-parts-diff-components/2` is required, or the spec requested by a narrow reader), or its exhaustive inventory, definition, paths, domain, coverage or topmost `owners` (on `/2`) differs from remeasurement; capped inventories are refused | Regenerate the complete versioned report against the same input paths, bytes, parts and figure domain |
5714
5746
  | <a id="ASSEMBLE_PINHOLES"></a>`ASSEMBLE_PINHOLES` | the requirements file declares `pinholes.required: true` and the flat parts stack holds a pinhole: an 8-connected opening (alpha 0 on every part, enclosed by the parts' alpha above 0) whose every pixel the painting shows as figure. One refusal per pinhole, largest first, naming its box, its px and the parts bordering it; nothing is written (issue #944, [Pinholes at rest](#pinholes-at-rest-issue-944)) | `assemble.plan` / `assemble.take` / the head pass: take the pinhole's pixels from a layer that holds them ([Source before scissors](#source-before-scissors)); where no layer holds them, the defect is the input's. Without the declaration the bar reports SKIP |
5715
5747
  | <a id="ASSEMBLE_PATCH_BOX_INSIDE"></a>`ASSEMBLE_PATCH_BOX_INSIDE` | a patch's box reaches past the rig (the painting times `rig_scale`; the detail gives the size) | that patch's `box` — it is in rig pixels, not painting pixels |
5716
5748
  | <a id="ASSEMBLE_PATCH_OPAQUE"></a>`ASSEMBLE_PATCH_OPAQUE` | a patch takes no pixel: a `"silhouette"` patch whose box holds none of the figure | move the box onto the figure, or `"alpha": "box"` |
@@ -8130,6 +8162,7 @@ is declared, never inferred from a filename or guessed from art.
8130
8162
  ```sh
8131
8163
  rig-parts depth-prepare --parts assembled --config depth.json --out inference
8132
8164
  # A provider reads inference/*.png and writes the declared floating-point maps.
8165
+ rig-parts depth-bind --map face.json --input inference/face.png --part face
8133
8166
  rig-parts depth-apply --parts assembled --manifest inference/manifest.json --config depth.json --rig-config config.json --out mapped
8134
8167
  rig-parts rig --parts mapped --config mapped/config.json --out compiled
8135
8168
  ```
@@ -8156,11 +8189,14 @@ declares `near`, positive `zScale` and `pivot`; optional `unitDepths` explicitly
8156
8189
  replaces that group's rigid depths. `clear` explicitly lists part references to
8157
8190
  remove, including any small units intended to sample the surface. Unselected
8158
8191
  parts retain their artwork and depth references. The output config copies the
8159
- original, sets the declared group pivots/unit depths, and relocates animation,
8160
- requirements and control-skeleton file paths. Built-in skeleton names remain
8161
- names. A selected part whose provenance records `depth.kind: "authored-unit"`
8162
- is refused before output (`DEPTH_AUTHORED_UNIT_CONFLICT`); apply does not invent
8163
- a transition to a transported scalar reference. Unselected authored units keep
8192
+ original, sets the declared group pivots/unit depths, and relocates every file
8193
+ reference `configFileReferences` declares, including `assemble.edited_parts`
8194
+ receipt files, through that reference's `set`
8195
+ ([STABILITY](STABILITY.md#programmatic-config-file-references)). Built-in
8196
+ skeleton names remain names. A selected part whose provenance records
8197
+ `depth.kind: "authored-unit"` is refused before output
8198
+ (`DEPTH_AUTHORED_UNIT_CONFLICT`); apply does not invent a transition
8199
+ to a transported scalar reference. Unselected authored units keep
8164
8200
  their original representation. Roles and draw order stay the author's.
8165
8201
 
8166
8202
  Maps are UTF-8 JSON `{"spec":"rig-parts-map/1","width":2,"height":2,
@@ -8174,6 +8210,33 @@ whole prepared image and crops its declared padding before reduction. Scalar
8174
8210
  maps use float32 BOX reduction. Normal sources require signed image-axis XYZ
8175
8211
  (x right, y down), not an RGB normal preview.
8176
8212
 
8213
+ Each map may carry a parts-owned receipt at `<map filename>.binding.json`
8214
+ (for `face.json`, `face.json.binding.json`). Call `depth-bind --map face.json --input inference/face.png --part face` when
8215
+ the provider produces that map. The writer validates the numeric map and PNG,
8216
+ computes both SHA-256 values itself, and exclusively creates the receipt beside
8217
+ the map; it refuses to overwrite existing evidence. Never bind an old map to
8218
+ a freshly prepared input. The resulting receipt has this shape:
8219
+
8220
+ ```json
8221
+ {"spec":"rig-parts-depth-map-binding/1","part":"face","mapSha256":"<64 lowercase hex digits>","inputSha256":"<64 lowercase hex digits>"}
8222
+ ```
8223
+
8224
+ These are the only receipt fields. `part` must match the selected part;
8225
+ `mapSha256` hashes the numeric JSON file's bytes; `inputSha256` hashes the exact
8226
+ prepared inference PNG, matching the manifest row. Apply validates present
8227
+ receipts before writing anything. A changed map or inference input refuses with
8228
+ `DEPTH_MAP_BINDING`, naming the part, found and required hashes, and the remedy:
8229
+ re-run depth for these inputs, then call
8230
+ `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>`. Malformed
8231
+ present receipts also refuse. Symlinked receipts, including dangling links, are
8232
+ refused; a regular file is required. Preparing again never rebinds a map.
8233
+ Under the compatibility policy dated **2026-11-16**, a missing receipt preserves
8234
+ legacy output bytes and exits, with one `DEPTH_MAP_BINDING_ABSENT` WARN per
8235
+ selected map on stderr. This is unverified inference-input identity, not a
8236
+ binding pass. The provider flow calls the writer when producing a map. The writer binds these
8237
+ files at invocation; it cannot prove the map was inferred from that input.
8238
+ Parts does not run inference or invent provenance.
8239
+
8177
8240
  Apply computes `u=(raw-median(raw))/(p95-p5)` inside original alpha >=128,
8178
8241
  using linear percentiles, then `Z=median+relief*u`. A flat map requires explicit
8179
8242
  relief 0. Encode `Z/zScale` for near white, `1-Z/zScale` for near black, clip to
@@ -8251,6 +8314,8 @@ by `rig`, so their output requires no alternate compiler or dependency pin.
8251
8314
  | <a id="DEPTH_INPUT_JSON"></a>`DEPTH_INPUT_JSON` | malformed numeric or configuration JSON | write valid finite JSON |
8252
8315
  | <a id="DEPTH_PART_RESOLVES"></a>`DEPTH_PART_RESOLVES` | selected or cleared name absent from parts.json | use the assembled part name |
8253
8316
  | <a id="DEPTH_OUTPUT_EMPTY"></a>`DEPTH_OUTPUT_EMPTY` | nonempty output or output containing an input | choose a separate absent or empty directory |
8317
+ | <a id="DEPTH_MAP_BINDING"></a>`DEPTH_MAP_BINDING` | malformed present map receipt, wrong part, map hash or inference-input hash | re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
8318
+ | <a id="DEPTH_MAP_BINDING_ABSENT"></a>`DEPTH_MAP_BINDING_ABSENT` | WARN only: no receipt, compatibility policy dated 2026-11-16 | legacy behavior is retained; re-run depth for these inputs, then `rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>` |
8254
8319
  | <a id="DEPTH_INPUT_BINDING"></a>`DEPTH_INPUT_BINDING` | changed recipe, art, part record, crop, padding or inference PNG | prepare again for these exact inputs |
8255
8320
  | <a id="DEPTH_MAP_FORMAT"></a>`DEPTH_MAP_FORMAT` | wrong numeric schema, channels, shape, count, unknown field or nonfinite element | provide the declared float JSON map, not a preview |
8256
8321
  | <a id="DEPTH_MAP_SIZE"></a>`DEPTH_MAP_SIZE` | map dimensions differ from its explicit frame | use the registered part, enlarged art or padded input grid |
@@ -8469,7 +8534,7 @@ references remain active declarations. See [the input contract and refusals](AUT
8469
8534
  ### Whole-figure difference inventory
8470
8535
 
8471
8536
  `rig-parts diff-components --stack stack.png --painting painting.png --parts parts.json --floor 2 --out diff-components.json`
8472
- writes `rig-parts-diff-components/1`. Supply the assembled stack and the painting
8537
+ writes `rig-parts-diff-components/1` by default. Pass `--owners` during retouch rounds that need the topmost owning part for each differing component (replacing hand-written scripts that recomputed per-pixel draw-order ownership): with `--owners`, the command writes `rig-parts-diff-components/2` and adds `owners` to every component. Without `--owners`, output bytes stay `rig-parts-diff-components/1` with no `owners` field. Supply the assembled stack and the painting
8473
8538
  **already in the same native canvas** (for a scaled assembly, use its rig-sized
8474
8539
  painting). Parts are read in manifest order from the `parts/` sibling directory.
8475
8540
  No registration or resampling occurs. For scene assemblies pass
@@ -8489,8 +8554,12 @@ SHA-256 of the binary figure domain (`null` for the whole canvas).
8489
8554
  PNG buffer decoded for measurement. `components` is uncapped and ordered by
8490
8555
  first pixel in row-major scan order. Each entry records `id` (`p<first pixel
8491
8556
  index>-n<pixel count>`), `px`, `box: {x,y,w,h}`, `coverage`, `uncovered_px` and
8492
- `borders`. Coverage is `covered`, `uncovered` or `mixed`: a whole-error component
8493
- can cross a part's edge, so a boolean would lose pixels. Borders use the existing
8557
+ `borders` (plus `owners` before `borders` in `rig-parts-diff-components/2` under `--owners`). Coverage is `covered`, `uncovered` or `mixed`: a whole-error component
8558
+ can cross a part's edge, so a boolean would lose pixels. Under `--owners`, `owners` lists each topmost part
8559
+ (in `parts.json` draw order, back to front) with alpha above the coverage cut (`COVERED_ALPHA`, >128)
8560
+ drawing the component's covered pixels, as `{part, px}`; an uncovered pixel names no owner, so an
8561
+ uncovered component has `owners: []` and the sum of `owners[].px` plus `uncovered_px` equals `px`.
8562
+ Borders use the existing
8494
8563
  hole convention: part pixels above the coverage cut touching a component in
8495
8564
  their 3x3 neighbourhood, counted once per part pixel, sorted by count then
8496
8565
  manifest order. A covered component may therefore name its own covering part.
@@ -8501,7 +8570,7 @@ Listed `px` plus `below_floor.px` equals `error_px`; listed `uncovered_px` plus
8501
8570
  `parts.json.recomposite` block, including `holes_listed: 5`, is unchanged.
8502
8571
 
8503
8572
  Replace `--out` with `--verify diff-components.json` to use the shipped reader.
8504
- Use the same paths and floor/threshold flags. It collects both source-binding mismatches before refusing. With matching bindings,
8573
+ Use the same paths and floor/threshold flags. `--verify` accepts both `rig-parts-diff-components/1` and `rig-parts-diff-components/2` reports (pass `--owners` with `--verify` or `readDiffComponents(text, input, [DIFF_COMPONENTS_SPEC])` when a caller requires a single spec version; a `/1`-only reader refuses a `/2` report by name with `DIFF_COMPONENTS_REPORT`). It collects both source-binding mismatches before refusing. With matching bindings,
8505
8574
  it recomputes every field against the supplied parts and domain, refusing
8506
8575
  missing, capped or altered components, stale coverage and definition drift. Every
8507
8576
  changed, missing or extra inventory field names its path, the value found and the
package/docs/STABILITY.md CHANGED
@@ -29,6 +29,28 @@ below). A build's bytes are not promised across versions. A later version may mo
29
29
  them, and when it does, the change that moves them declares which bytes and why (the
30
30
  winding change of #133 is the example: [MIGRATION.md](MIGRATION.md)).
31
31
 
32
+ ## Provider-map input identity
33
+
34
+ Issue #1284 adds optional parts-owned `<map>.binding.json` receipts, spec
35
+ `rig-parts-depth-map-binding/1`, with exactly `spec`, `part`, `mapSha256` and
36
+ `inputSha256`. The SHA-256 values are lowercase 64-digit hexadecimal hashes of
37
+ the numeric map file and its consumed prepared inference PNG. A present receipt
38
+ must match the selected part, current map bytes and manifest `inputSha256`;
39
+ otherwise `DEPTH_MAP_BINDING` refuses before any output write. A malformed present
40
+ receipt also refuses; symlinked receipts (including dangling links) are refused.
41
+ The depth recipe and prepare manifest are unchanged.
42
+
43
+ Compatibility policy dated **2026-11-16**: an absent receipt retains the shipped
44
+ map behavior, output bytes and success exit, adding one stderr WARN named
45
+ `DEPTH_MAP_BINDING_ABSENT` per selected map. Absence does not establish provenance.
46
+ This follows the stable-item meaning promise above: existing maps remain accepted
47
+ inside the major version. A matching receipt changes no output bytes or report
48
+ keys. Preparing fresh inputs does not create or update a map receipt. Call `depth-bind` when inference produces the map: it computes both hashes and
49
+ exclusively writes the receipt beside the map, refusing to overwrite evidence.
50
+ It binds the files at invocation and cannot prove that inference used that input.
51
+ See
52
+ [Per-part provider maps](AUTHORING.md#per-part-provider-maps-897).
53
+
32
54
  ## Parts-stage integrity report
33
55
 
34
56
  `rig-parts check-parts --parts <assembled-dir> --out <disjoint-report-dir>
@@ -223,8 +245,9 @@ defaults are the help's too, and none is guessed from the art.
223
245
  <!-- stable:commands -->
224
246
  | command | flags |
225
247
  | --- | --- |
226
- | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`; exactly one of `--out`, `--verify` (issue #1005; exhaustive native error inventory, with byte-bound reader) |
248
+ | `diff-components` | `--stack`, `--painting`, `--parts`, `--floor`; optional `--threshold`, `--figure`, `--owners`; exactly one of `--out`, `--verify` (issues #1005, #1291; exhaustive native error inventory, `rig-parts-diff-components/1` by default and `rig-parts-diff-components/2` with `--owners`, and byte-bound reader for both) |
227
249
  | `depth-prepare` | `--parts`, `--config`, `--out` (issue #897; separate numeric-depth recipe) |
250
+ | `depth-bind` | `--map`, `--input`, `--part` (issue #1284; exclusive receipt creation from current file bytes) |
228
251
  | `depth-apply` | `--parts`, `--manifest`, `--config`, `--rig-config`, `--out` (issue #897; original character config is read-only) |
229
252
  | `layers` | one positional path: a wrapper directory, a `layers.json` or a `.psd`; with it, optional `--export` (a directory to write the wrapper form into, issue #359); or `--template` with `--canvas` and no path; or a positional head run with `--full`, `--source`, `--config` together for `PLAN_HEAD_GARMENT_OVERLAP` (issue #826) |
230
253
  | `sheet` | `--source`, `--layers` (repeatable), `--out`; optional `--cell`, `--cols` |
@@ -442,6 +465,12 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
442
465
 
443
466
  ## Files this package writes
444
467
 
468
+ `depth-bind` writes `<map>.binding.json` beside the numeric map, spec
469
+ `rig-parts-depth-map-binding/1`, with `spec`, `part`, `mapSha256`, `inputSha256`
470
+ in that order. Hashes are computed from current map and input PNG bytes.
471
+ Exclusive creation refuses an existing receipt and preserves it unchanged.
472
+
473
+
445
474
  ### Source cover report
446
475
 
447
476
  `assemble` and the assemble stage of `build` always write `source_cover.json`
@@ -672,6 +701,7 @@ execution in historical evidence is inferred from a current export.
672
701
  | the scene report | `compose` | spec `spine-parts-scene-report/1`; the plate block carries `sha256` of the plate PNG's bytes after `size` (issue #1183, additive under *What "stable" means here*: a new report key in a minor version, so the spec stays `/1`) |
673
702
  | `idle.png`, `idle-indexed.png`, `idle.gif` | `loop`, `build --loop` | APNG and GIF encodings of the rendered idle |
674
703
  | `run.json` | `rig`, `assemble` | spec `rig-run/1` (issue #1165, additive): `spec`, `package` (`name`, `version`), `command` (`"rig"` or `"assemble"`), `started_at` and `finished_at` (UTC ISO-8601 millisecond timestamps ending in `Z`, read in the CLI layer), `config` (`path` relative to `--out`, `sha256` of the config file on disk), and `outputs` (`path` relative to `--out`, `sha256` of each written output file on disk, sorted by `path` in code-unit order and excluding `run.json` itself); written only after the command's gate is green |
704
+ | the difference inventory (`--out`) | `diff-components` | spec `rig-parts-diff-components/1` by default (issue #1005: `stack`, `painting`, `definition`, `error_px`, `uncovered_error_px`, `components` — each `id`, `px`, `box`, `coverage`, `uncovered_px`, `borders` — and `below_floor`, byte-identical to 2.38.1), and spec `rig-parts-diff-components/2` under `--owners` (issue #1291: adds `owners` — each `{part, px}`, the topmost `parts.json` part above `COVERED_ALPHA` per covered pixel, back to front — before `borders` on every component); `--verify` verifies both `/1` and `/2` reports (with `--owners`, `/2` is required), while a `/1`-only reader (`readDiffComponents(text, input, [DIFF_COMPONENTS_SPEC])`) refuses `/2` by name |
675
705
 
676
706
  Issue #705 pins setup-seam acceptance to one source-relative scale1 union U of the authored stage and all actual drawn base/checked-set still vertices. U is snapped relative to the source origin, including odd-width half phase.
677
707
  The existing seam fields and pair pictures use that grid; source/blink and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spine-parts",
3
- "version": "2.38.1",
3
+ "version": "2.40.0",
4
4
  "description": "AI-authored 2D character parts from one anime painting and its See-through layer decomposition: measured parts, weighted-mesh rig specs, verified through rig-c before anything is written. A CLI for agents that cannot see the image.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/assemble.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { sourceCoverRun, type SourceCoverReading } from './sourcecover.ts';
2
- import { replaceEditedParts, type EditedPartContext, type VerifiedEditedPart } from './editedparts.ts';
3
- import { paintingReceivers, rawPaintingOwner } from './paintingowner.ts';
2
+ import { replaceEditedParts, type EditedPartContext, type EditedPartFrontColourReading, type VerifiedEditedPart } from './editedparts.ts';
3
+ import { paintingReceivers, rawPaintingOwner, type PaintingOwner } from './paintingowner.ts';
4
4
  import { hiddenExtentProblems, type HiddenExtentDeclaration, type HiddenExtentSource } from './hiddenextent.ts';
5
5
  import { headBoxInside } from './headbox.ts';
6
6
  import { edgePairResiduals, type EdgeResidualReport } from './edgeresidual.ts';
@@ -3640,6 +3640,163 @@ export function holeKindsLine(k: HoleKinds, scene: string | null = null): string
3640
3640
  );
3641
3641
  }
3642
3642
 
3643
+ /** One full-run layer's outer soft rim in `figure_rig.png` (issue #1297). */
3644
+ export interface FigureRimLayer {
3645
+ /** The full-run layer tag. */
3646
+ tag: string;
3647
+ /** The plan part that takes `full:<tag>` directly, or null when no plan row does. */
3648
+ part: string | null;
3649
+ /** Layer pixels at alpha `OPAQUE_ALPHA_ABOVE + 1 .. COVERED_ALPHA - 1` (9..127) in the 4-connected exterior of the union `alpha >= CORE_ALPHA` core. */
3650
+ rimPx: number;
3651
+ /** Those rim pixels whose max absolute RGB channel difference from the painting in the rig is above `ERROR_LIMIT`. */
3652
+ farPx: number;
3653
+ /** Total pixels of this full-run layer on the rig grid with alpha above `OPAQUE_ALPHA_ABOVE`. */
3654
+ maskPx: number;
3655
+ }
3656
+
3657
+ /**
3658
+ * What `figure_rig.png` holds beyond the union `alpha >= CORE_ALPHA` core and
3659
+ * beyond the emitted parts' support (issue #1297).
3660
+ */
3661
+ export interface FigureMaskReading {
3662
+ /** Total pixels in `figure_rig.png` (`inside[p] === 1`, union of full-run layers at alpha above `OPAQUE_ALPHA_ABOVE`). */
3663
+ figurePx: number;
3664
+ /** Total pixels in the union of full-run layers at alpha >= `CORE_ALPHA` (250). */
3665
+ corePx: number;
3666
+ /** Union of full-run layer rim pixels (alpha 9..127 in the 4-connected exterior of the union alpha >= 250 core). */
3667
+ rimPx: number;
3668
+ /** Union of full-run layer far-rim pixels (rim pixels with max-channel RGB difference from the painting in the rig > `ERROR_LIMIT`). */
3669
+ farPx: number;
3670
+ /** Full-run layers with `rimPx > 0`, largest `rimPx` first (then `farPx`, then `tag`). */
3671
+ layers: FigureRimLayer[];
3672
+ /** Figure-mask pixels that no emitted part carries at alpha above `OPAQUE_ALPHA_ABOVE` (8), 8-connected. */
3673
+ outsideParts: HoleKindSummary;
3674
+ /** Pixels in both the union rim and `outsideParts`. */
3675
+ alsoInRimPx: number;
3676
+ /** Pixels in the union rim or `outsideParts` (overlap counted once). */
3677
+ rimOrOutsidePx: number;
3678
+ }
3679
+
3680
+ /**
3681
+ * Measure the figure mask's outer soft rim (`alpha 9..127` in the 4-connected
3682
+ * exterior of the union `alpha >= CORE_ALPHA` core), its far-rim subset (`max`
3683
+ * RGB channel difference from `srcr` > `ERROR_LIMIT`), and the mask pixels
3684
+ * outside every emitted part at `alpha > OPAQUE_ALPHA_ABOVE` (issue #1297).
3685
+ */
3686
+ export function measureFigureMask(
3687
+ inside: Uint8Array,
3688
+ fullRig: ReadonlyArray<{ tag: string; rig: Raster }>,
3689
+ srcr: Raster,
3690
+ parts: readonly PlacedPart[],
3691
+ plan: readonly PlanEntry[],
3692
+ ): FigureMaskReading {
3693
+ const { width: W, height: H } = srcr;
3694
+ const n = W * H;
3695
+ let figurePx = 0;
3696
+ for (let p = 0; p < n; p++) figurePx += inside[p];
3697
+ const core = newMask(W, H);
3698
+ for (const { rig } of fullRig) {
3699
+ for (let p = 0; p < n; p++) {
3700
+ if (rig.data[p * 4 + 3] >= CORE_ALPHA) core.data[p] = 1;
3701
+ }
3702
+ }
3703
+ let corePx = 0;
3704
+ for (let p = 0; p < n; p++) corePx += core.data[p];
3705
+ const filledCore = fillHoles(core);
3706
+ const unionRim = new Uint8Array(n);
3707
+ const unionFar = new Uint8Array(n);
3708
+ const layers: FigureRimLayer[] = [];
3709
+ for (const { tag, rig } of fullRig) {
3710
+ let rimPx = 0;
3711
+ let farPx = 0;
3712
+ let maskPx = 0;
3713
+ for (let p = 0; p < n; p++) {
3714
+ const a = rig.data[p * 4 + 3];
3715
+ if (a > OPAQUE_ALPHA_ABOVE) maskPx++;
3716
+ if (filledCore.data[p] === 0 && a > OPAQUE_ALPHA_ABOVE && a < COVERED_ALPHA) {
3717
+ rimPx++;
3718
+ unionRim[p] = 1;
3719
+ if (maxDiff(rig.data, p * 4, srcr.data, p * 4) > ERROR_LIMIT) {
3720
+ farPx++;
3721
+ unionFar[p] = 1;
3722
+ }
3723
+ }
3724
+ }
3725
+ if (rimPx > 0) {
3726
+ const part = plan.find(([, run, t]) => run === 'full' && t === tag)?.[0] ?? null;
3727
+ layers.push({ tag, part, rimPx, farPx, maskPx });
3728
+ }
3729
+ }
3730
+ layers.sort((a, b) => b.rimPx - a.rimPx || b.farPx - a.farPx || (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0));
3731
+ let rimPx = 0;
3732
+ let farPx = 0;
3733
+ for (let p = 0; p < n; p++) {
3734
+ rimPx += unionRim[p];
3735
+ farPx += unionFar[p];
3736
+ }
3737
+ const partSupport = new Uint8Array(n);
3738
+ for (const { image, record } of parts) {
3739
+ for (let y = 0; y < record.h; y++) {
3740
+ const ry = record.y + y;
3741
+ if (ry < 0 || ry >= H) continue;
3742
+ for (let x = 0; x < record.w; x++) {
3743
+ const rx = record.x + x;
3744
+ if (rx < 0 || rx >= W) continue;
3745
+ if (image.data[(y * record.w + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE) partSupport[ry * W + rx] = 1;
3746
+ }
3747
+ }
3748
+ }
3749
+ const outsideMask = newMask(W, H);
3750
+ let alsoInRimPx = 0;
3751
+ let rimOrOutsidePx = 0;
3752
+ for (let p = 0; p < n; p++) {
3753
+ const out = inside[p] === 1 && partSupport[p] === 0;
3754
+ if (out) {
3755
+ outsideMask.data[p] = 1;
3756
+ if (unionRim[p] === 1) alsoInRimPx++;
3757
+ }
3758
+ if (unionRim[p] === 1 || out) rimOrOutsidePx++;
3759
+ }
3760
+ return {
3761
+ figurePx,
3762
+ corePx,
3763
+ rimPx,
3764
+ farPx,
3765
+ layers,
3766
+ outsideParts: summarizeKindMask(outsideMask),
3767
+ alsoInRimPx,
3768
+ rimOrOutsidePx,
3769
+ };
3770
+ }
3771
+
3772
+ /**
3773
+ * The measurement line and per-layer rows when `assemble` writes
3774
+ * `figure_rig.png` (issue #1297): the union `alpha >= CORE_ALPHA` core, the
3775
+ * outer `alpha 9..127` soft rim and its pixels more than `ERROR_LIMIT` off the
3776
+ * painting in the rig, the mask pixels outside every emitted part at
3777
+ * `alpha > OPAQUE_ALPHA_ABOVE`, and one row per full-run layer with a nonzero
3778
+ * rim count.
3779
+ */
3780
+ export function figureMaskLines(m: FigureMaskReading, scene: string | null = null): string[] {
3781
+ const outside =
3782
+ m.outsideParts.px === 0 || m.outsideParts.largest === null
3783
+ ? '0 px'
3784
+ : `${m.outsideParts.px} px in ${m.outsideParts.count} component(s) (8-connected, largest ${m.outsideParts.largest.px} px at ${m.outsideParts.largest.x},${m.outsideParts.largest.y} ${m.outsideParts.largest.w}x${m.outsideParts.largest.h})`;
3785
+ const head =
3786
+ `${scene === null ? '' : `${scene}: `}figure mask (${FIGURE_MASK_FILE}): ` +
3787
+ `core (alpha >= ${CORE_ALPHA}) ${m.corePx} px; ` +
3788
+ `soft rim (alpha ${OPAQUE_ALPHA_ABOVE + 1}..${COVERED_ALPHA - 1} in the 4-connected exterior of the union alpha >= ${CORE_ALPHA} core): union ${m.rimPx} px, far (max channel > ${ERROR_LIMIT} from the painting in the rig) ${m.farPx} px; ` +
3789
+ `outside all parts (no part at alpha > ${OPAQUE_ALPHA_ABOVE}): ${outside} (${m.alsoInRimPx} px also in rim, rim or outside ${m.rimOrOutsidePx} px); ` +
3790
+ `measurement, no declared limit`;
3791
+ return [
3792
+ head,
3793
+ ...m.layers.map(
3794
+ (l) =>
3795
+ ` figure rim full:${l.tag} (${l.part === null ? 'no full-run plan part' : `part "${l.part}"`}): rim ${l.rimPx} px, far ${l.farPx} px (of ${l.maskPx} layer mask px)`,
3796
+ ),
3797
+ ];
3798
+ }
3799
+
3643
3800
  /** The `parts.json` `recomposite` block: the four figures, the limits they were measured at, and the listed holes. */
3644
3801
  export function recompositeRecord(f: RecompositeFigures): RecompositeRecord {
3645
3802
  return {
@@ -4858,6 +5015,8 @@ export interface AssembleResult {
4858
5015
  softOcclusion?: SoftOcclusionReading[];
4859
5016
  /** Informational only; never serialized into parts.json. */
4860
5017
  cropClipped?: string[];
5018
+ /** Report-only front-part painting colour carried by an edited part (#1290). */
5019
+ editedPartFrontColours?: EditedPartFrontColourReading[];
4861
5020
  parts: PartsFile;
4862
5021
  /** In plan order, each cropped to its record's box. */
4863
5022
  images: PlacedPart[];
@@ -4866,6 +5025,8 @@ export interface AssembleResult {
4866
5025
  errorMap: Raster;
4867
5026
  /** Under `config.scene` (issue #242), the figure the recomposite was read inside ({@link figureImage}); null otherwise. */
4868
5027
  figure: Raster | null;
5028
+ /** Under `config.scene` (issue #1297), the figure mask's soft rim and outside-all-parts counts; absent otherwise. */
5029
+ figureMask?: FigureMaskReading;
4869
5030
  figures: RecompositeFigures;
4870
5031
  /** What each `assemble.cuts` entry took, counted when it was made (`cutLines`); empty without cuts. */
4871
5032
  cuts: CutCount[];
@@ -6158,16 +6319,35 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6158
6319
  }
6159
6320
  return whole;
6160
6321
  };
6322
+ const rawPaintingOwnerForPlan = (): PaintingOwner => {
6323
+ let keepByPlanPart: ReadonlyMap<string, Mask> = occluderUnderKeepByPlanPart;
6324
+ if (projectRule !== 'visible' && occluderEntries.length > 0) {
6325
+ const localKeep = new Map<string, Mask>();
6326
+ for (const { declaration, guardMask } of occluderEntries) {
6327
+ for (const u of declaration.under) {
6328
+ let m = localKeep.get(u);
6329
+ if (m === undefined) {
6330
+ m = newMask(W, H);
6331
+ localKeep.set(u, m);
6332
+ }
6333
+ for (let p = 0; p < W * H; p++) if (guardMask.data[p] === 1) m.data[p] = 1;
6334
+ }
6335
+ }
6336
+ keepByPlanPart = localKeep;
6337
+ }
6338
+ const rawPlan = input.plan.map(([name, run, tag]) => {
6339
+ const layer = (run === 'full' ? fullPadded : depthHeadInput).layers.find(l => l.name === tag)!;
6340
+ return { name, raster: layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks), keep: keepByPlanPart.get(name) ?? null };
6341
+ });
6342
+ if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
6343
+ return rawPaintingOwner(rawPlan, W * H);
6344
+ };
6345
+ let paintingOwner: PaintingOwner | undefined;
6161
6346
  if (projectRule === 'visible') {
6162
6347
  // paintingEdges reads every image as the whole rig canvas. A plan part's image already is one; a patch is its cut,
6163
6348
  // placed at record.x / record.y, so it is placed on a canvas here. The step never writes a patch, so a copy is enough.
6164
6349
  const canvases = stack.map(onRig);
6165
- const rawPlan = input.plan.map(([name, run, tag]) => {
6166
- const layer = input[run].layers.find(l => l.name === tag)!;
6167
- return { name, raster: layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks), keep: occluderUnderKeepByPlanPart.get(name) ?? null };
6168
- });
6169
- if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
6170
- const owner = rawPaintingOwner(rawPlan, W * H);
6350
+ const owner = (paintingOwner = rawPaintingOwnerForPlan());
6171
6351
  const lineage: Array<[string, string]> = [
6172
6352
  ...input.cuts.map(c => [c.from, c.into] as [string, string]),
6173
6353
  ...Object.values(input.limbs ?? {}).flatMap(l => l.segments.flatMap(segment => [
@@ -6529,7 +6709,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6529
6709
  return { ...original, runs: original.runs.map(remap), pre_seam_writer_runs: original.pre_seam_writer_runs.map(remap) };
6530
6710
  });
6531
6711
  }
6532
- if ((input.editedParts?.length ?? 0) > 0) replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!);
6712
+ const editedPartFrontColours = (input.editedParts?.length ?? 0) > 0
6713
+ ? replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!, srcr, paintingOwner ?? rawPaintingOwnerForPlan(), ERROR_LIMIT)
6714
+ : [];
6533
6715
  if (editContexts !== undefined) for (const p of placed) {
6534
6716
  const samples = editContexts.get(p)?.depthClampedSamples;
6535
6717
  if (samples === undefined) continue;
@@ -6546,8 +6728,10 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6546
6728
  for (const group of [built, pieces, cutSources, limbPieces]) for (const b of group) if (b !== null) b.writers = undefined;
6547
6729
  const can = recomposite(placed, W, H);
6548
6730
  // Issue #242: on a scene painting the figure is read off the full run, and every recomposite figure inside it.
6549
- const inside = input.scene === true ? sceneFigure([...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([, r]) => r), W, H) : null;
6731
+ const fullRigAll = [...rig.entries()].filter(([k]) => k.startsWith('full:')).map(([k, r]) => ({ tag: k.slice('full:'.length), rig: r }));
6732
+ const inside = input.scene === true ? sceneFigure(fullRigAll.map((l) => l.rig), W, H) : null;
6550
6733
  const sceneRecord: SceneRecord | null = inside === null ? null : { figure_alpha_above: OPAQUE_ALPHA_ABOVE, figure_px: inside.reduce((a, b) => a + b, 0), figure_mask: FIGURE_MASK_FILE };
6734
+ const figureMask = inside === null ? undefined : measureFigureMask(inside, fullRigAll, srcr, placed, plan);
6551
6735
  const figures = measureRecomposite(can, srcr, placed, inside);
6552
6736
  const covered = coveredMask(placed, W, H);
6553
6737
  const err = errorMask(can, srcr, inside);
@@ -6579,6 +6763,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6579
6763
  sourceCover,
6580
6764
  ...(softOcclusion.length === 0 ? {} : { softOcclusion }),
6581
6765
  ...(!single ? { cropClipped: cropClippedLines(plan, extend, (run, tag) => rig.get(`${run}:${tag}`) ?? null, frame) } : {}),
6766
+ ...(editedPartFrontColours.length === 0 ? {} : { editedPartFrontColours }),
6582
6767
  paintingInRig: srcr,
6583
6768
  ...(stageMap === undefined ? {} : { stageMap }),
6584
6769
  parts: {
@@ -6603,6 +6788,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6603
6788
  recomposite: can,
6604
6789
  errorMap: recompositeErrorMap(can, srcr, placed, inside),
6605
6790
  figure: inside === null ? null : figureImage(inside, W, H),
6791
+ ...(figureMask === undefined ? {} : { figureMask }),
6606
6792
  figures,
6607
6793
  cuts: cutCounts,
6608
6794
  cutMaterial: [...cutMaterial, ...lim.material],
package/src/build.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { readEditedParts } from './editedparts.ts';
1
+ import { editedPartFrontColourLines, readEditedParts } from './editedparts.ts';
2
2
  import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
3
3
  import { STAGE_MAP_FILE } from './provenance.ts';
4
4
  import { withoutCheckRows } from './checkrow.ts';
@@ -69,7 +69,7 @@ import { createHash } from 'node:crypto';
69
69
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
70
70
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
71
71
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
72
- import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
72
+ import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, ERROR_LIMIT, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figureMaskLines, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
73
73
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
74
74
  import { residualClause } from './autoenvelope.ts';
75
75
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -1182,6 +1182,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1182
1182
  );
1183
1183
  }
1184
1184
  for (const line of provenanceLines(result.parts.parts)) log(line);
1185
+ for (const line of editedPartFrontColourLines(result.editedPartFrontColours ?? [], ERROR_LIMIT)) log(line);
1185
1186
  for (const line of ownershipLines(result.parts.cut_ownership ?? [])) log(line);
1186
1187
  for (const alt of altBuilt) for (const line of [...provenanceLines(alt.record.records), ...ownershipLines(alt.record.cut_ownership ?? [])]) log(` set "${alt.record.name}" ${line.trimStart()}`);
1187
1188
  // Issue #256: one line per part from an author-made layer, so it never reads as See-through's. None without one.
@@ -1209,6 +1210,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
1209
1210
  for (const l of holeLines(result.figures, scene)) log(l);
1210
1211
  if (result.figures.uncoveredErrorPx > 0) log(holeKindsLine(result.holeKinds, scene));
1211
1212
  for (const u of result.uncovered) log(uncoveredLine(u, scene));
1213
+ if (result.figureMask !== undefined) for (const l of figureMaskLines(result.figureMask, scene)) log(l);
1212
1214
  log(pinholesLine(pinholes, altBuilt.map((b) => b.record.name)));
1213
1215
  for (const d of result.drift) log(driftLine(d));
1214
1216
  for (const d of result.softOcclusion ?? []) log(softOcclusionLine(d));
@@ -3,7 +3,7 @@
3
3
  * the first output is emitted; output directories must be absent or empty.
4
4
  */
5
5
  import { createHash } from 'node:crypto';
6
- import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
8
8
  import { configFileReferences, loadConfigAndAnimations, parseConfig } from './config.ts';
9
9
  import { depthReading, readSourceDepth } from './depthsheets.ts';
@@ -146,7 +146,72 @@ function extendIntegratedHeight(data: Float64Array, art: Raster): Float64Array {
146
146
  }
147
147
  return filled;
148
148
  }
149
- export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string }): Obj {
149
+ const MAP_BINDING_ABSENT = 'DEPTH_MAP_BINDING_ABSENT';
150
+ const BINDING_REMEDY = 're-run depth for these inputs, then rig-parts depth-bind --map <numeric-map.json> --input <prepared.png> --part <name>';
151
+ /** Bound diagnostic values; never echo a receipt payload. */
152
+ function bindingFound(value: unknown): string {
153
+ if (value === undefined) return 'absent';
154
+ if (value === null) return 'null';
155
+ if (Array.isArray(value)) return 'array';
156
+ if (typeof value === 'object') return 'object';
157
+ return JSON.stringify(value)?.slice(0, 96) ?? String(value);
158
+ }
159
+
160
+ /** Attest the two files available now, not the unobserved inference execution. */
161
+ export function bindDepthMap(input: { map: string; input: string; part: string }): Obj {
162
+ if (!input.part || input.part.startsWith('.') || /[\\/]/.test(input.part) || input.part.includes('\0')) {
163
+ fail('DEPTH_MAP_BINDING', 'depth-bind --part', `found ${bindingFound(input.part)}; required a nonempty plain part filename; ${BINDING_REMEDY}`);
164
+ }
165
+ const read = (file: string): Uint8Array => {
166
+ if (!existsSync(file) || !statSync(file).isFile()) return fail('DEPTH_INPUT_PRESENT', file, 'is missing or not a file; restore the declared input');
167
+ return readFileSync(file);
168
+ };
169
+ const mapBytes = read(input.map), inputBytes = read(input.input);
170
+ readNumericMap(readJson(input.map), input.part);
171
+ decodePngBytes(inputBytes, input.part);
172
+ const receipt = { spec: 'rig-parts-depth-map-binding/1', part: input.part, mapSha256: hash(mapBytes), inputSha256: hash(inputBytes) };
173
+ const target = input.map + '.binding.json';
174
+ // Exclusive creation preserves a previous attestation; all readers run first.
175
+ try { writeFileSync(target, text(receipt), { flag: 'wx' }); }
176
+ catch (error) {
177
+ const code = error !== null && typeof error === 'object' && 'code' in error ? String(error.code) : 'UNKNOWN';
178
+ const reason = code === 'EEXIST' ? 'already exists (EEXIST)' : `write failed (${code})`;
179
+ return fail('DEPTH_MAP_BINDING', `part "${input.part}"`, `receipt ${JSON.stringify(target)} ${reason}; required an absent receipt in a writable directory; keep existing evidence and use a new map filename; ${BINDING_REMEDY}`);
180
+ }
181
+ return receipt;
182
+ }
183
+
184
+ // existsSync follows symlinks; a dangling receipt is present malformed evidence.
185
+ function isReceiptLink(path: string): boolean {
186
+ try { return lstatSync(path).isSymbolicLink(); } catch { return false; }
187
+ }
188
+
189
+ /** Parts-owned provenance beside the numeric map; never inferred from a new prepare. */
190
+ function mapBinding(mapPath: string, bytes: Uint8Array, part: PreparedPart): string | undefined {
191
+ const receiptPath = mapPath + '.binding.json';
192
+ if (!existsSync(receiptPath) && !isReceiptLink(receiptPath)) return `WARN ${MAP_BINDING_ABSENT}: part "${part.part}" — no map binding receipt (compatibility policy dated 2026-11-16); applying legacy map without inference-input identity; ${BINDING_REMEDY}`;
193
+ const remedy = BINDING_REMEDY;
194
+ const refuse = (detail: string): never => fail('DEPTH_MAP_BINDING', `part "${part.part}"`, `${detail}; ${remedy}`);
195
+ if (!lstatSync(receiptPath).isFile()) return refuse('receipt found a symlink or nonregular file; required a regular file');
196
+ let raw: unknown;
197
+ try { raw = JSON.parse(readFileSync(receiptPath, 'utf8')) as unknown; }
198
+ catch { return refuse('receipt found unreadable or invalid JSON; required a readable JSON object'); }
199
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return refuse(`receipt found ${bindingFound(raw)}; required an object`);
200
+ const r = raw as Obj;
201
+ const sha = (v: unknown): v is string => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
202
+ const unknown = Object.keys(r).filter(k => !['spec', 'part', 'mapSha256', 'inputSha256'].includes(k));
203
+ if (unknown.length) return refuse(`receipt found unknown key ${bindingFound(unknown[0])}; required only spec, part, mapSha256, inputSha256`);
204
+ if (r.spec !== 'rig-parts-depth-map-binding/1') return refuse(`receipt spec found ${bindingFound(r.spec)}; required "rig-parts-depth-map-binding/1"`);
205
+ if (r.part !== part.part) return refuse(`receipt part found ${bindingFound(r.part)}; required ${JSON.stringify(part.part)}`);
206
+ for (const key of ['mapSha256', 'inputSha256'] as const) {
207
+ if (!sha(r[key])) return refuse(`receipt ${key} found ${bindingFound(r[key])}; required 64 lowercase hexadecimal digits`);
208
+ }
209
+ const mapSha = hash(bytes);
210
+ if (r.mapSha256 !== mapSha) return refuse(`map sha found ${r.mapSha256}; required ${mapSha}`);
211
+ if (r.inputSha256 !== part.inputSha256) return refuse(`inference input sha found ${r.inputSha256}; required ${part.inputSha256}`);
212
+ return undefined;
213
+ }
214
+ export function applyDepth(input: { parts: string; manifest: string; config: string; rigConfig: string; out: string }, log: (line: string) => void = console.warn): Obj {
150
215
  const recipe = parseDepthRecipe(readJson(input.config)), expected = preparedParts(input.parts, recipe);
151
216
  const supplied = readJson(input.manifest);
152
217
  if (text(supplied) !== text(expected.manifest)) fail('DEPTH_INPUT_BINDING', input.manifest, 'does not match the recipe, parts.json, art hashes, crop or padding; run depth-prepare again for these exact inputs');
@@ -154,7 +219,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
154
219
  const file = join(dirname(input.manifest), p.input);
155
220
  if (!existsSync(file) || hash(readFileSync(file)) !== p.inputSha256) fail('DEPTH_INPUT_BINDING', p.part, 'prepared inference PNG is missing or changed; restore its exact bytes or prepare again');
156
221
  }
157
- emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).map(p => resolve(dirname(input.config), p.map))]);
222
+ emptyOutput(input.out, [input.parts, input.config, input.manifest, input.rigConfig, ...Object.values(recipe.parts).flatMap(p => { const map = resolve(dirname(input.config), p.map); return [map, map + '.binding.json']; })]);
158
223
  const rawParts = object(readJson(join(input.parts, 'parts.json')), 'parts.json'), file = readParts(join(input.parts, 'parts.json'));
159
224
  for (const p of file.parts) if (Object.hasOwn(recipe.parts, p.name) && p.provenance?.depth?.kind === 'authored-unit') fail('DEPTH_AUTHORED_UNIT_CONFLICT', `part "${p.name}"`, 'has provenance.depth.kind "authored-unit"; a transported scalar reference cannot coexist with authored unit depth — retain the unit declaration or supply an explicitly reassembled scalar-compatible input; no automatic transition is made');
160
225
  loadConfigAndAnimations(input.rigConfig);
@@ -168,6 +233,7 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
168
233
  ref.set(relative(resolve(input.out), resolve(dirname(input.rigConfig), ref.value)));
169
234
  }
170
235
  parseConfig(raw);
236
+ const warnings: string[] = [];
171
237
  const writes = new Map<string, Uint8Array>(), rows: Obj[] = [], recs = rawParts.parts as Obj[];
172
238
  // Retain auxiliary art (including alternate sets) and diagnostics byte-for-byte.
173
239
  // Symlink inputs would obscure ownership and can escape this assembled directory.
@@ -194,6 +260,8 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
194
260
  if (!Object.hasOwn(object(target.roles, `config.turn.${declaration.group}.roles`), name)) fail('DEPTH_GROUP_BINDING', name, `declared group ${declaration.group} does not name this part in its roles; register it explicitly`);
195
261
  const prepared = expected.manifest.parts.find(row => row.part === name) as PreparedPart;
196
262
  const mapPath = resolve(dirname(input.config), declaration.map), numeric = readNumericMap(readJson(mapPath), name), mapBytes = readFileSync(mapPath);
263
+ const warning = mapBinding(mapPath, mapBytes, prepared);
264
+ if (warning !== undefined) warnings.push(warning);
197
265
  const map = registeredMap(numeric, prepared, declaration.frame, name);
198
266
  let values: ArrayLike<number>, normal: ReturnType<typeof integrateNormals> | undefined;
199
267
  if (declaration.source === 'normals') {
@@ -232,5 +300,6 @@ export function applyDepth(input: { parts: string; manifest: string; config: str
232
300
  writeFileSync(join(input.out, 'parts.json'), text(rawParts));
233
301
  writeFileSync(join(input.out, 'config.json'), text(raw));
234
302
  writeFileSync(join(input.out, 'depth-report.json'), text(report));
303
+ for (const warning of warnings) log(warning);
235
304
  return report;
236
305
  }
@@ -10,6 +10,8 @@ import { decodePngBytes } from './raster/png.ts';
10
10
  import { newMask, type Raster } from './raster/types.ts';
11
11
 
12
12
  export const DIFF_COMPONENTS_SPEC = 'rig-parts-diff-components/1';
13
+ export const DIFF_COMPONENTS_OWNERS_SPEC = 'rig-parts-diff-components/2';
14
+ export type DiffComponentsSpec = typeof DIFF_COMPONENTS_SPEC | typeof DIFF_COMPONENTS_OWNERS_SPEC;
13
15
  export interface DiffBytes { path: string; bytes: Uint8Array }
14
16
  export interface DiffInputs {
15
17
  stack: DiffBytes;
@@ -24,10 +26,11 @@ export interface DiffComponent {
24
26
  box: { x: number; y: number; w: number; h: number };
25
27
  coverage: 'covered' | 'uncovered' | 'mixed';
26
28
  uncovered_px: number;
29
+ owners?: { part: string; px: number }[];
27
30
  borders: { part: string; px: number }[];
28
31
  }
29
32
  export interface DiffComponentsReport {
30
- spec: typeof DIFF_COMPONENTS_SPEC;
33
+ spec: DiffComponentsSpec;
31
34
  stack: { path: string; sha256: string };
32
35
  painting: { path: string; sha256: string };
33
36
  definition: {
@@ -63,7 +66,7 @@ function diffPng(bytes: Uint8Array, label: string): Raster {
63
66
  }
64
67
 
65
68
  /** Hash and decode each source from the same buffer. No alignment or resampling. */
66
- export function measureDiffComponents(input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
69
+ export function measureDiffComponents(input: DiffInputs, floor: number, threshold = ERROR_LIMIT, withOwners = false): DiffComponentsReport {
67
70
  diffDefinition(floor, threshold);
68
71
  const stack = diffPng(input.stack.bytes, input.stack.path);
69
72
  const painting = diffPng(input.painting.bytes, input.painting.path);
@@ -74,9 +77,12 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
74
77
  if (input.inside.length !== W * H || bad >= 0) inputFailure('inside', `has ${input.inside.length} pixels, first nonbinary value ${bad < 0 ? 'none' : `${input.inside[bad]} at index ${bad}`}; ${W * H} binary 0/1 pixels in the painting's native frame are required`);
75
78
  }
76
79
  const names = new Set<string>();
77
- for (const { record: p, image } of input.parts) {
80
+ const topmost = new Int32Array(W * H).fill(-1);
81
+ for (let i = 0; i < input.parts.length; i++) {
82
+ const { record: p, image } = input.parts[i];
78
83
  if (!p.name || names.has(p.name) || ![p.x, p.y, p.w, p.h].every(Number.isSafeInteger) || p.x < 0 || p.y < 0 || p.w < 1 || p.h < 1 || p.x + p.w > W || p.y + p.h > H || image.width !== p.w || image.height !== p.h || image.data.length < p.w * p.h * 4) inputFailure(`part "${p.name}"`, `box ${p.x},${p.y} ${p.w}x${p.h}, image ${image.width}x${image.height} with ${image.data.length} RGBA bytes, duplicate name ${names.has(p.name)}; a unique nonempty name and an integer in-canvas matching box with four RGBA bytes per pixel are required on ${W}x${H}`);
79
84
  names.add(p.name);
85
+ for (let y = 0; y < p.h; y++) for (let x = 0; x < p.w; x++) if (image.data[(y * p.w + x) * 4 + 3] > COVERED_ALPHA) topmost[(p.y + y) * W + p.x + x] = i;
80
86
  }
81
87
  const covered = coveredMask(input.parts, W, H);
82
88
  const err = errorMask(stack, painting, input.inside, threshold);
@@ -96,12 +102,22 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
96
102
  for (const s of cc.stats.slice(1).filter(s => s.area > 0).sort((a,b) => first[a.label] - first[b.label])) {
97
103
  const u = uncovered[s.label];
98
104
  if (s.area < floor) { below.count++; below.px += s.area; below.uncovered_px += u; continue; }
105
+ let owners: { part: string; px: number }[] | undefined;
106
+ if (withOwners) {
107
+ const counts = new Int32Array(input.parts.length);
108
+ for (let y = s.top; y < s.top + s.height; y++) for (let x = s.left; x < s.left + s.width; x++) {
109
+ const p = y * W + x;
110
+ if (cc.labels[p] === s.label && topmost[p] >= 0) counts[topmost[p]]++;
111
+ }
112
+ owners = [];
113
+ for (let i = 0; i < input.parts.length; i++) if (counts[i] > 0) owners.push({ part: input.parts[i].record.name, px: counts[i] });
114
+ }
99
115
  components.push({ id: `p${first[s.label]}-n${s.area}`, px: s.area,
100
116
  box: { x: s.left, y: s.top, w: s.width, h: s.height },
101
117
  coverage: u === 0 ? 'covered' : u === s.area ? 'uncovered' : 'mixed', uncovered_px: u,
102
- borders: holeBorders(input.parts, cc, s, W, H, COVERED_ALPHA) });
118
+ ...(owners === undefined ? {} : { owners }), borders: holeBorders(input.parts, cc, s, W, H, COVERED_ALPHA) });
103
119
  }
104
- return { spec: DIFF_COMPONENTS_SPEC,
120
+ return { spec: withOwners ? DIFF_COMPONENTS_OWNERS_SPEC : DIFF_COMPONENTS_SPEC,
105
121
  stack: { path: input.stack.path, sha256: sha(input.stack.bytes) },
106
122
  painting: { path: input.painting.path, sha256: sha(input.painting.bytes) },
107
123
  definition: { metric: 'max-absolute-rgb-channel', threshold, comparison: '>', connectivity: 8, floor_px: floor,
@@ -110,8 +126,8 @@ export function measureDiffComponents(input: DiffInputs, floor: number, threshol
110
126
  error_px: errorPx, uncovered_error_px: uncoveredPx, components, below_floor: below };
111
127
  }
112
128
  export function serializeDiffComponents(report: DiffComponentsReport): string { return JSON.stringify(report, null, 2) + '\n'; }
113
- export function writeDiffComponents(path: string, input: DiffInputs, floor: number, threshold = ERROR_LIMIT): DiffComponentsReport {
114
- const report = measureDiffComponents(input, floor, threshold);
129
+ export function writeDiffComponents(path: string, input: DiffInputs, floor: number, threshold = ERROR_LIMIT, withOwners = false): DiffComponentsReport {
130
+ const report = measureDiffComponents(input, floor, threshold, withOwners);
115
131
  try { writeFileSync(path, serializeDiffComponents(report)); }
116
132
  catch (err) { inputFailure(path, `cannot write report: ${JSON.stringify(err instanceof Error ? err.message : err)}; a writable output file path is required`); }
117
133
  return report;
@@ -119,11 +135,11 @@ export function writeDiffComponents(path: string, input: DiffInputs, floor: numb
119
135
  const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
120
136
  const shown = (v: unknown): string => v === undefined ? 'missing' : Array.isArray(v) ? `array with ${v.length} entries` : typeof v === 'number' && !Number.isFinite(v) ? String(v) : JSON.stringify(v);
121
137
  /** Recompute the inventory against the supplied bytes and coverage/domain. A capped or edited report is refused. */
122
- export function readDiffComponents(text: string, input: DiffInputs): DiffComponentsReport {
138
+ export function readDiffComponents(text: string, input: DiffInputs, allowedSpecs: readonly DiffComponentsSpec[] = [DIFF_COMPONENTS_SPEC, DIFF_COMPONENTS_OWNERS_SPEC]): DiffComponentsReport {
123
139
  let raw: unknown;
124
140
  try { raw = JSON.parse(text); } catch (err) { return reportFailure(`cannot parse JSON: ${JSON.stringify(err instanceof Error ? err.message : err)}; valid JSON is required`); }
125
141
  if (!object(raw)) return reportFailure(`found ${shown(raw)}; a ${DIFF_COMPONENTS_SPEC} report object is required`);
126
- if (raw.spec !== DIFF_COMPONENTS_SPEC) return reportFailure(`spec is ${shown(raw.spec)}; ${DIFF_COMPONENTS_SPEC} is required`);
142
+ if (!allowedSpecs.includes(raw.spec as DiffComponentsSpec)) return reportFailure(`spec is ${shown(raw.spec)}; ${allowedSpecs.join(' or ')} is required`);
127
143
  if (!object(raw.stack) || !object(raw.painting) || !object(raw.definition)) return reportFailure(`stack=${shown(raw.stack)}, painting=${shown(raw.painting)}, definition=${shown(raw.definition)}; all three objects are required`);
128
144
  const bindings: Problem[] = [];
129
145
  for (const key of ['stack', 'painting'] as const) {
@@ -135,7 +151,7 @@ export function readDiffComponents(text: string, input: DiffInputs): DiffCompone
135
151
  if (bindings.length > 0) throw new PartsError(bindings);
136
152
  const floor = raw.definition.floor_px, threshold = raw.definition.threshold;
137
153
  if (typeof floor !== 'number' || typeof threshold !== 'number') return reportFailure(`definition floor_px=${shown(floor)}, threshold=${shown(threshold)}; both must be numbers`);
138
- const expected = measureDiffComponents(input, floor, threshold);
154
+ const expected = measureDiffComponents(input, floor, threshold, raw.spec === DIFF_COMPONENTS_OWNERS_SPEC);
139
155
  const differences: Problem[] = [];
140
156
  const fail = (path: string, found: unknown, required: unknown): void => {
141
157
  differences.push({ code: 'DIFF_COMPONENTS_REPORT', object: path,
@@ -164,9 +180,11 @@ export function readDiffComponents(text: string, input: DiffInputs): DiffCompone
164
180
  export function diffComponentsCommand(args: string[]): void {
165
181
  const allowed = ['--stack', '--painting', '--parts', '--figure', '--floor', '--threshold', '--out', '--verify'];
166
182
  const flags = new Map<string,string>();
183
+ let withOwners = false;
167
184
  for (let i = 0; i < args.length; i += 2) {
168
185
  const key = args[i], value = args[i + 1];
169
- if (!allowed.includes(key) || flags.has(key) || value === undefined || value.startsWith('--')) inputFailure('arguments', `requires unique ${allowed.join(', ')} flags with values; found ${key}`);
186
+ if (key === '--owners' && !withOwners) { withOwners = true; i--; continue; }
187
+ if (!allowed.includes(key) || flags.has(key) || value === undefined || value.startsWith('--')) inputFailure('arguments', `requires unique ${allowed.join(', ')} flags with values (and optional --owners); found ${key}`);
170
188
  if (value.length === 0) inputFailure(key, 'is ""; a nonempty value is required');
171
189
  flags.set(key, value);
172
190
  }
@@ -202,7 +220,7 @@ export function diffComponentsCommand(args: string[]): void {
202
220
  const input = { stack, painting, parts: placed, inside };
203
221
  if (flags.has('--verify')) {
204
222
  const path = flags.get('--verify')!;
205
- const report = readDiffComponents(new TextDecoder().decode(bytes(path).bytes), input);
223
+ const report = readDiffComponents(new TextDecoder().decode(bytes(path).bytes), input, withOwners ? [DIFF_COMPONENTS_OWNERS_SPEC] : [DIFF_COMPONENTS_SPEC, DIFF_COMPONENTS_OWNERS_SPEC]);
206
224
  if (report.definition.floor_px !== floor || report.definition.threshold !== threshold) inputFailure('definition', `report floor_px=${report.definition.floor_px}, threshold=${report.definition.threshold}; caller floor_px=${floor}, threshold=${threshold} are required`);
207
- } else writeDiffComponents(flags.get('--out')!, input, floor, threshold);
225
+ } else writeDiffComponents(flags.get('--out')!, input, floor, threshold, withOwners);
208
226
  }
@@ -10,6 +10,7 @@ import { decodePngBytes, encodePngBytes } from './raster/png.ts';
10
10
  import type { Mask, Raster } from './raster/types.ts';
11
11
  import type { PlacedPart } from './assemble.ts';
12
12
  import type { PartDepthReference } from './depthsheets.ts';
13
+ import type { PaintingOwner } from './paintingowner.ts';
13
14
 
14
15
  export interface EditedPartReceipt extends EditorReceipt { part: string }
15
16
  export interface EditedParts { dir: string; receipts: EditedPartReceipt[] }
@@ -29,6 +30,20 @@ export interface EditedPartProvenance {
29
30
  changed_excluded_px: number;
30
31
  removed_opaque_px: number;
31
32
  }
33
+ export interface EditedPartFrontColourOwner {
34
+ owner: string;
35
+ px: number;
36
+ /** Rig-pixel bounding box [x, y, w, h] of changed/added pixels under this front owner within ERROR_LIMIT of the painting. */
37
+ box: [number, number, number, number];
38
+ }
39
+ export interface EditedPartFrontColourReading {
40
+ edit: string;
41
+ part: string;
42
+ px: number;
43
+ /** Rig-pixel bounding box [x, y, w, h] across all front owners, or null when px === 0. */
44
+ box: [number, number, number, number] | null;
45
+ owners: EditedPartFrontColourOwner[];
46
+ }
32
47
  /** Only held for an edited build, including its region-take counterfactual. */
33
48
  export interface EditedPartContext {
34
49
  baseline: ValueBaseline | null;
@@ -83,7 +98,16 @@ function reader(runs: ReadonlyArray<readonly [number, number]>): () => number {
83
98
  }
84
99
 
85
100
  /** Validate every baseline before replacing any image. No output writes here. */
86
- export function replaceEditedParts(placed: PlacedPart[], edits: readonly VerifiedEditedPart[], plan: ReadonlySet<string>, map: StageMap, contexts: ReadonlyMap<PlacedPart, EditedPartContext>): void {
101
+ export function replaceEditedParts(
102
+ placed: PlacedPart[],
103
+ edits: readonly VerifiedEditedPart[],
104
+ plan: ReadonlySet<string>,
105
+ map: StageMap,
106
+ contexts: ReadonlyMap<PlacedPart, EditedPartContext>,
107
+ painting: Raster,
108
+ owner: PaintingOwner,
109
+ errorLimit: number,
110
+ ): EditedPartFrontColourReading[] {
87
111
  const problems: Problem[] = [], seen = new Set<string>();
88
112
  for (const edit of edits) {
89
113
  const { receipt, image } = edit, part = placed.find(p => p.record.name === receipt.part);
@@ -101,6 +125,7 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
101
125
  if (actual !== receipt.sha256) problems.push({ code: 'ASSEMBLE_EDITED_PART_SHA256', object, detail: `edited bytes sha256 is ${actual}; receipt sha256 ${receipt.sha256} is required` });
102
126
  }
103
127
  refuseIfAny(problems);
128
+ const readings: EditedPartFrontColourReading[] = [];
104
129
  for (const edit of edits) {
105
130
  const part = placed.find(p => p.record.name === edit.receipt.part)!;
106
131
  const old = part.image, record = part.record, context = contexts.get(part)!;
@@ -118,6 +143,9 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
118
143
  ...(record.provenance?.depth === undefined ? {} : { depth: record.provenance.depth }), edited_part: metadata };
119
144
  const counts = new Map<number, number>();
120
145
  let opaque = 0, visible = 0, projected = 0, paintingGain = 0;
146
+ const partOwnerIndex = owner.names.indexOf(record.name);
147
+ const byOwner = new Map<number, { px: number; left: number; top: number; right: number; bottom: number }>();
148
+ let frontColourPx = 0, fcLeft = map.rig_size[0], fcTop = map.rig_size[1], fcRight = 0, fcBottom = 0;
121
149
  const baseline = context.baseline;
122
150
  for (let p = 0; p < old.width * old.height; p++) {
123
151
  const offset = p * 4, prior = previous(), priorSeam = preSeam();
@@ -132,6 +160,34 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
132
160
  opaque++;
133
161
  const x = record.x + p % record.w, y = record.y + Math.floor(p / record.w);
134
162
  const q = y * map.rig_size[0] + x;
163
+ if (changed && partOwnerIndex >= 0) {
164
+ const ownerIndex = owner.pixels[q];
165
+ if (ownerIndex > partOwnerIndex) {
166
+ const qOffset = q * 4;
167
+ const dMax = Math.max(
168
+ Math.abs(edit.image.data[offset] - painting.data[qOffset]),
169
+ Math.abs(edit.image.data[offset + 1] - painting.data[qOffset + 1]),
170
+ Math.abs(edit.image.data[offset + 2] - painting.data[qOffset + 2]),
171
+ );
172
+ if (dMax <= errorLimit) {
173
+ frontColourPx++;
174
+ if (x < fcLeft) fcLeft = x;
175
+ if (y < fcTop) fcTop = y;
176
+ if (x + 1 > fcRight) fcRight = x + 1;
177
+ if (y + 1 > fcBottom) fcBottom = y + 1;
178
+ const prev = byOwner.get(ownerIndex);
179
+ if (prev === undefined) {
180
+ byOwner.set(ownerIndex, { px: 1, left: x, top: y, right: x + 1, bottom: y + 1 });
181
+ } else {
182
+ prev.px++;
183
+ if (x < prev.left) prev.left = x;
184
+ if (y < prev.top) prev.top = y;
185
+ if (x + 1 > prev.right) prev.right = x + 1;
186
+ if (y + 1 > prev.bottom) prev.bottom = y + 1;
187
+ }
188
+ }
189
+ }
190
+ }
135
191
  if (context.visible?.data[q] === 1) visible++;
136
192
  if (context.visible?.data[q] === 1 && context.projected?.data[q] === 1) projected++;
137
193
  if (context.paintingGain?.data[q] === 1) paintingGain++;
@@ -164,5 +220,29 @@ export function replaceEditedParts(placed: PlacedPart[], edits: readonly Verifie
164
220
  part.image = edit.image;
165
221
  part.encodedBytes = edit.bytes;
166
222
  map.parts[map.parts.indexOf(stage)] = next;
223
+ const owners: EditedPartFrontColourOwner[] = [...byOwner.entries()]
224
+ .sort(([a], [b]) => a - b)
225
+ .map(([ownerIndex, b]) => ({
226
+ owner: owner.names[ownerIndex],
227
+ px: b.px,
228
+ box: [b.left, b.top, b.right - b.left, b.bottom - b.top],
229
+ }));
230
+ readings.push({
231
+ edit: name,
232
+ part: record.name,
233
+ px: frontColourPx,
234
+ box: frontColourPx === 0 ? null : [fcLeft, fcTop, fcRight - fcLeft, fcBottom - fcTop],
235
+ owners,
236
+ });
167
237
  }
238
+ return readings;
239
+ }
240
+
241
+ /** Measurement-only lines for front-part painting colour carried by an edited part (#1290). */
242
+ export function editedPartFrontColourLines(readings: readonly EditedPartFrontColourReading[], errorLimit: number): string[] {
243
+ return readings.flatMap(r =>
244
+ r.owners.length === 0
245
+ ? [` edited part front colour: part "${r.part}" (${r.edit}) 0 px, front owner none, box none (within ${errorLimit} of painting; measurement, no declared limit)`]
246
+ : r.owners.map(o => ` edited part front colour: part "${r.part}" (${r.edit}) front owner "${o.owner}" ${o.px} px, box [${o.box.join(', ')}] (within ${errorLimit} of painting; measurement, no declared limit)`),
247
+ );
168
248
  }
package/src/propose.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { dustOf } from './mesh.ts';
1
+ import { ART_ALPHA, dustOf, isDust } from './mesh.ts';
2
2
  import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
3
3
  /**
4
4
  * The propose stage: bone origins, mesh candidate lists, regions and a default
@@ -145,7 +145,7 @@ import { connectedComponents } from './raster/components.ts';
145
145
  import { dilate, morphGradient } from './raster/morph.ts';
146
146
  import { readPng } from './raster/png.ts';
147
147
  import { resize } from './raster/resize.ts';
148
- import { type Mask, newMask, newRaster, type Raster } from './raster/types.ts';
148
+ import { alphaAbove, type Mask, newMask, newRaster, type Raster } from './raster/types.ts';
149
149
  import { npMean, npMedian, npPercentile, pyFixed, pyInt, pyIntList, pyRepr, pyRound, pyStrList } from './pyfmt.ts';
150
150
  import type { JointState, RigJoint, RigJoints } from './keypoints.ts';
151
151
  import { IDLE_FPS } from './motion.ts';
@@ -3489,10 +3489,31 @@ export function proposeWithBasis(
3489
3489
  torsoImage = { ...torsoImage, data };
3490
3490
  }
3491
3491
  const dust = dustOf(torsoImage);
3492
+ let torsoStray: number | undefined;
3492
3493
  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
+ const cellArea = fig.grid * fig.grid;
3495
+ const components = connectedComponents(alphaAbove(torsoImage, ART_ALPHA), 4);
3496
+ const islands = components.stats.slice(1).sort((a, b) => b.area - a.area || a.label - b.label);
3497
+ const art = islands.reduce((sum, island) => sum + island.area, 0);
3498
+ const extra = islands.slice(1);
3499
+ // One drafted sampling cell supplies the area policy, not a geometric claim that a smaller island
3500
+ // cannot contain a sample point. Dust retains its independent, existing limits.
3501
+ if (islands.length === 0 || islands[0].area === islands[1]?.area ||
3502
+ extra.some(island => !isDust(island.area, art) && island.area >= cellArea)) {
3503
+ throw new PartsError([{ code: 'PROPOSE_TORSO_ISLANDS', object: `chest carrier "${torsoName}"`, detail: `${dust.keep}. Non-dust islands must hold fewer than spacing squared = ${fig.grid} * ${fig.grid} = ${cellArea} art px. Separate the real pieces before drafting a contour torso` }]);
3504
+ }
3505
+ torsoStray = extra[0]?.area;
3506
+ for (const island of extra) {
3507
+ if (isDust(island.area, art)) continue;
3508
+ const code = 'PROPOSE_TORSO_ISLAND_LEFT_OUT';
3509
+ notes.push(`WARN ${code}: chest carrier "${torsoName}" — ${island.area} art px at box [${source.x + island.left}, ${source.y + island.top}, ${island.width}, ${island.height}] rig px left out of the contour; below spacing squared ${fig.grid} * ${fig.grid} = ${cellArea} art px; contour.stray=${torsoStray}`);
3510
+ }
3511
+ const small = extra.filter(island => isDust(island.area, art));
3512
+ if (small.length > 0) notes.push(`${torsoName}: contour dust rule leaves out ${small.length} island(s), ${small.reduce((sum, island) => sum + island.area, 0)} px; contour.stray=${torsoStray}`);
3513
+ } else {
3514
+ torsoStray = dust.stray;
3515
+ 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}`);
3494
3516
  }
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
3517
  const [, radius] = gridR(source);
3497
3518
  const segments: Segment[] = lattice !== undefined && 'grid' in lattice ? lattice.segments : [['chest', rnd(neckAt), rnd(hip)]];
3498
3519
  // Same figure formulas as mesh-draft's figureRules (issue #265). Importing meshdraft here would cycle through propose.
@@ -3502,7 +3523,7 @@ export function proposeWithBasis(
3502
3523
  margin: tolerance,
3503
3524
  spacing: fig.grid,
3504
3525
  maxEdge: fig.grid,
3505
- ...(dust.stray === undefined ? {} : { stray: dust.stray }),
3526
+ ...(torsoStray === undefined ? {} : { stray: torsoStray }),
3506
3527
  };
3507
3528
  if (bust.noBust !== undefined) {
3508
3529
  notes.push(`${torsoName}: contour bust omitted for the declared reason: ${bust.noBust}`);