rig-parts 1.82.1 → 1.83.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,4 +1,5 @@
1
1
  #!/usr/bin/env bun
2
+ import { applyTakenLayers } from './src/takelayers.ts';
2
3
  /**
3
4
  * rig-parts — one painting and its See-through layers in, Spine-ready parts
4
5
  * and rig specs out, verified through rig-c.
@@ -1722,10 +1723,12 @@ function cmdAssemble(args: string[]): number {
1722
1723
  if (propose) {
1723
1724
  const target = writePath === undefined ? null : readConfigWriteTarget(writePath);
1724
1725
  const src = readSource(source);
1725
- const runs = readRuns(full, head);
1726
- const g = proposeFields(loadEarlyConfig(config, 'layers'), runs.single ? { w: src.width, h: src.height } : null);
1726
+ const cfg = loadEarlyConfig(config, 'layers');
1727
+ const runs = applyTakenLayers(readRuns(full, head), src, { ...cfg, assemble: { ...cfg.assemble, plan: undefined } }, config);
1728
+ const g = proposeFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
1727
1729
  const geometry = { sourceW: src.width, sourceH: src.height, ...g };
1728
1730
  const proposal = runs.single ? proposeSinglePlan(runs.full, geometry) : proposePlan(runs.full, runs.head, geometry);
1731
+ proposal.notes.unshift(...runs.notes);
1729
1732
  if (target !== null) {
1730
1733
  staged = stageConfigWrite(target, { kind: 'assemble-plan', plan: proposal.plan, extend_below_crop: proposal.extend_below_crop });
1731
1734
  staged.commit();
package/docs/AUTHORING.md CHANGED
@@ -131,7 +131,7 @@ read by no CPU stage).
131
131
  | `assemble.patches` | assemble; `meshes`/`regions` keys may name them too | **authored**, optional: `[{name, box, alpha, draw}]` — an extra part cut from the **painting** itself, for figure no See-through layer holds (a hem both runs dropped). `box` is `[x0, y0, x1, y1]` in **rig** pixels, `x1`/`y1` exclusive — the space of `parts.json` and `recomposite_rig.png`, where the hole is found; `alpha` is `"silhouette"` (the painting's figure silhouette inside the box, the one `--seam silhouette` uses) or `"box"` (the whole box); `draw` is `"back"`, `"front"` or `{"before": "<plan part>"}`. A patch is always a region: its bone is `regions.<name>`, in the one place every region's bone lives, and a `meshes` entry for it is refused. `draw` sets assembled part order; an exclusively bound limb rider's final rig slot joins that limb's block (see the limbs subsection). Use [Source before scissors](#source-before-scissors) before a patch; §5 describes structural placement |
132
132
  | `assemble.cuts` | assemble; `meshes`/`regions` keys may name the new parts too, and must (each is a part like any other) | **authored**, optional (issue #170): `[{from, into, polygon, draw, overlap, under, under_fill}]`, `under` and `under_fill` optional — a structural separation under [Source before scissors](#source-before-scissors), cut from a plan part's layer by the author's polygon: the pixels of plan part `from` whose **centre** lies inside `polygon` (even-odd; a centre exactly on an edge is outside) leave `from` and make the new part `into`, colour and alpha, so every pixel of the layer ends in exactly one of the two. `polygon` is `[[x, y], …]`, at least three points, non-negative integer **rig** pixels — the space of `parts.json` and of the patches' boxes. The file that shows the layer in those coordinates is `assemble`'s own `rig/parts/<from>.png`, placed at its `parts.json` `x`, `y` (the PNG's pixel `(i, j)` is rig pixel `(x + i, y + j)`), or `render/recomposite_rig.png`, the whole rig 1:1; the contact sheets (`sheet`) are scaled and carry no coordinates. `draw` is `"back"`, `"front"` or `{"before": "<plan part>"}`, as for a patch (to keep the setup pose, draw the piece immediately in front of `from` — `{"before": "<the plan part after from>"}`, or `"front"` when `from` is the last plan part; `{"before": "<from>"}` draws it behind `from`, which `under` refuses as `ASSEMBLE_UNDER_DRAW` because the fill would hide it). `from` must be a plan part (`CONFIG_NAME_RESOLVES`; a patch or another cut's piece is refused; a part a limb takes may be cut where no segment of the limb holds it, issue #564, §5 *Limbs*), `into` a new name (`CONFIG_PART_UNIQUE`), the polygon three or more integer points (`CONFIG_FIELD_TYPE`). The piece's `parts.json` record carries `from`'s `<run>:<tag>` and its own counts, each split from the layer's by where the pixel lies; it is a mesh or a region under its own name, and the coverage rule holds it like a plan part. What the config cannot know the stage refuses: a polygon point past the rig (`ASSEMBLE_CUT_INSIDE`), two cuts of one part sharing a pixel (`ASSEMBLE_CUT_OVERLAP`), a cut that takes none of the layer's opaque pixels or leaves `from` none (`ASSEMBLE_CUT_PIXELS`), a cut of a part a limb takes that takes a pixel a segment of the limb holds (`ASSEMBLE_CUT_CROSSES_LIMB`). `overlap` is required, a non-negative integer of rig pixels with no default (`CONFIG_FIELD_TYPE`): the **band** — the polygon's pixels within `overlap` px of its edge by Chebyshev distance (the polygon's mask less its erosion by a `2 * overlap + 1` square) — stays in `from` as well as going to the piece, so the piece's resampled edge has art under it; the counts stay a strict partition and the band is the base's extra copy, printed on the `cut:` line. At `0` the two abut and `check`'s seam bar judges the edge between them (`CHECK_SEAM_WITHIN_BAR`, §5). A band only covers the edge at rest: a piece that swings well clear of where it was painted shows the hole it leaves, and a thin piece's band shows a ghost of the piece. `under` (issue #193), optional, is the author's image of what lies under the piece: a PNG path relative to the config's directory (`CONFIG_FIELD_TYPE` unless a non-empty string), in rig pixels over the polygon's **bounding box** — the least and greatest polygon x and y, so the image is `max x − min x` by `max y − min y` and its pixel `(i, j)` is rig pixel `(min x + i, min y + j)`. Where the cut removed pixels from `from` — the piece's pixels (alpha above 0) less the band — `from` takes the image's pixel, colour and alpha wherever the image's alpha is at least the alpha the cut removed there (**filled**); elsewhere `from` stays empty there (**left empty**): a transparent pixel is the author's statement that nothing lies under it (the background, or a part drawn behind), and a less opaque one is not half-filled. The image is read nowhere else, so its pixels over the band, over the box outside the polygon or where the layer had no art never change `from`. The `cut:` line then ends `; under <n> px filled, <m> px left empty` (`n + m` is every removed pixel), so an unintended hole is a number in the log, not a guess; the filled pixels count in `from`'s `opaque_px` and `occluded_px` (the piece is drawn over them), never as visible or projected. The stage refuses: a file that is not there (`ASSEMBLE_UNDER_PRESENT`) or not a PNG (`ASSEMBLE_UNDER_DECODES`), an image not exactly the box's size (`ASSEMBLE_UNDER_SIZE`, both sizes given), an image that fills none of the removed pixels — all transparent there, or another file (`ASSEMBLE_UNDER_EMPTY`; to leave the whole hole, drop `under`), and a piece drawn behind `from` (`ASSEMBLE_UNDER_DRAW`: the fill would hide it; draw it `"front"` or `{"before": "<the plan part after from>"}`). Producing the image is the author's, by whatever means; absent, `from` keeps only its band. `under_fill` (issue #360), optional, is the one value `"colour"` (`CONFIG_FIELD_TYPE` on any other): the same pixels are filled and left empty, and a filled pixel takes the image's **colour** at the alpha the cut removed there instead of the image's alpha, so `from`'s alpha is the uncut layer's wherever the image fills and its silhouette does not grow — an opaque image over a soft edge leaves the edge soft. It applies to the part's hidden-art layer as well as to a file; a cut with neither is refused (`ASSEMBLE_UNDER_FILL_SOURCE`). The `cut:` line's filled count then says how many took the colour only: `; under 190 px filled (190 colour only, at the alpha the cut removed), 0 px left empty`. Absent, a filled pixel takes the image's colour and alpha, as above |
133
133
  | `assemble.alternates` | assemble, rig, check (`--set`, `--all-sets`) | **authored**, optional (issues #454, #465, #472, #473, #476): `[{name, source?, full?, head?, head_box?, parts?, hides?, cuts?, skeleton?, anchor?, base_anchor?, drawn?, tips?, front?}]` — alternate painting sets assembled into `<out>/rig/parts/<set>_<part>.png` (`parts.json` `alternates`), attached on each covered slot in `rig.json` as `<set>_<part>` beside the base attachment, and indexed in `<out>/rig/sets.json` (`rig-parts-sets/1`: `sets.<set>.slots`, `.hides`, `.drawn` when present, and `.threshold: {yaw: 15, pitch: 12}` when the set replaces `face` on a rig with `turn` or `turn`/`tilt` slider animations). `source`, `full` and `head` may instead be given on the CLI with `--alt <name>=<source>:<full>[:<head>]`. Windows absolute drive paths such as `C:\paint\painting.png` are accepted as written; each segment's leading drive colon belongs to that path, while other colons still separate `source`, `full` and `head`. `parts` lists the subset of parts the set replaces (default: every part not in `hides`); a **subset set** (issue #473, e.g. mouth visemes `a`, `i`, `u` with `"parts": ["mouth"]`) cuts only its covered parts from the alternate runs (refusing with `ASSEMBLE_ALT_INPUT_PRESENT` if a covered part's layer is missing or empty), writes only `{slot: "<set>_<slot>"}` in `sets.json` so `@rig-c/play`'s `setSet(name)` switches those slots while leaving every other slot on its base attachment (and `setSet(null)` restores the base pose), may be keyed on a slot attachment track in `motion.animations_from` as `{"t": …, "set": "<name>" \| null}` (`CONFIG_SET_COVERS_SLOT` if `"set"` is undeclared or does not cover the track's slot), and under `check --set <name>` counts `ANIMATIONS_DO_NOT_FOLD` only on its own covered slots; `hides` lists slots the set hides (`null` in `sets.json`). A **gesture subset set** (issue #476) covers a limb chain declared in `config.limbs.<limb>` (all of its segment `part`s; with `drawn` alone, cut at the base's joints posed to the set's own `drawn` angles by `poseBoneEntriesForDrawn`, each segment keeping the base's length; with `skeleton` (issue #539), cut at the skeleton's own joint positions by `placeBoneEntriesForSkeleton` — each covered bone the body-18 table names (`sleeve_*`, `arm_*0`/`arm_*1`, `leg_*0`/`leg_*1`) at its skeleton origin with the skeleton segment's own length and direction (`drawn` overriding the direction of a bone it names), and a covered bone the table does not name (a hand link `arm_r2`, a single `foot_r`) placed from its parent's new place — its base offset from the parent, stretched along the parent by the parent's length change and turned by its turn, so a link or a foot at the parent's end lands on the skeleton's end — with its base length and the drawn or base direction, so a foreshortened shin or forearm is cut where it is painted; naming the unsplit `from` layer, covering only some segments of the limb, or declaring polygon `cuts` on a limb set is refused with `CONFIG_LIMB_SET_JOINTS`) and carries `drawn` (or `skeleton`) for the covered bones only (giving `drawn` for an uncovered bone is refused with `CONFIG_SET_COVERS_BONE` / `RIG_SET_COVERS_BONE`; uncovered bones keep the base's `drawn`). A subset set's limb part takes no pixel that a base part drawn after it, which the set neither covers nor hides, covers at setup (issue #587): the set's attachment is drawn in the base slot's place, so that base part is drawn over it and what the set's painting shows there is that base part (shorts over a leg set's thigh top, which See-through synthesised in the set's leg layer); `assemble` clears those pixels — the base part's PNG at alpha above 8, at its `parts.json` x, y, on the shared canvas — from the set's part once its limbs are cut, before any count — its `merged_px` and its cap's record too (issue #603): a cap pixel it clears leaves the count it was in (`layer_px`, `image_px`, `upper_px`, `lower_px`, `lower_kept_px`) for the cap's `excluded_px`, written only when above 0, so every count is the written PNG's — and prints `LINT set "<set>" <part>: <n> px under <base part> excluded` per part and base part that took a pixel (n counts alpha above 8); a set that carries that base part itself (`"parts": ["thigh_l", "shin_l", "bottomwear"]`) excludes nothing and writes what it wrote before. A subset set that names one limb side of a layer more limbs take (issue #588: `"parts": ["thigh_r", "shin_r"]` where `leg_r` and `leg_l` both take the one `legs` layer) would put every pixel of that layer on its one limb, so each of its parts would hold a piece of both legs; when the set's layer holds more than one island (8-connected pixels with alpha above 8) of at least 1 % of its largest (issue #608: the ghost clean-up's own share; a smaller island is a speck, which goes with the island nearest it — the one holding the pixel centre nearest one of the speck's, none when two are equally near — and is never an island of its own), each segment part keeps the island its joints fall on — its bone's origin and the next segment's bone's origin, at the set's own bones, a joint on the island of a pixel whose square holds the point, and a joint on no island on the one island whose nearest pixel centre lies within the radius of the cap cut at that joint (`cap.radius`: an ankle just past the legwear's edge, on the shoe) — and drops the rest, once its limbs are cut and before the exclusion above, and `assemble` prints `LINT set "<set>" <part>: <layer part> holds <n> islands (8-connected, alpha above 8)[, and <s> speck(s) under 1 % of the largest (<f> px), each with the island nearest it], kept the one under <bone> [x, y] and <bone> [x, y][ (<e> px off it, within its cap's radius <r>)] (<k> px), dropped <m> (<d> px)` per part (k and d count the part's pixels above alpha 8, m the islands it lost one from, and `dropped none` when it lost none); a joint on no island with none or two within that radius, or with no cap cut at it (a limb's first joint), and a segment whose joints fall on two, are refused with `ASSEMBLE_ALT_LIMB_ISLAND` rather than guessed. A layer of one island — specks aside — may hold both legs over each other (a folded shin across the standing leg; issue #609): each of the set's segment parts then keeps the pixels nearer its own limb's segment line — the polyline of only its segments taking that source, their bone origins and the last segment's supplied tip or following segment's joint (issue #638) — than the other limb's, both in the set's pose, and gives the rest away, once its limbs are cut and before the exclusion above; a pixel whose two distances differ by 0.5 px or less (the overlap band: half a pixel, the reach by which a pixel centre is read as on a line) goes to the limb whose part there is drawn later in the base's draw order, and the `LINT set` line above counts what each part kept, gave and held in the band. The other limb stands where the set's `skeleton` places it — its keypoints place every limb bone of the body-18 table, the other leg's as well as the set's own (its `drawn` and `drawnLength` stay the covered bones') — and never at the base's place: a set that does not place it (a `drawn` set, which may not name a bone it does not cover, or a set with neither) is refused with `ASSEMBLE_ALT_LIMB_POSE` when its layer has art where the base draws that limb, and when it has none nothing says the layer holds it and the layer is cut as before; two limbs whose segment lines run closer than the limb's half-width over most of where their art can meet are refused with `ASSEMBLE_ALT_LIMB_OVERLAP`. A set that carries every limb of the layer is cut as before. For a subset set, where a limb's own source layer holds art (`alpha > 8`) under another layer of that run drawn in front (`alpha > 8`, by the projection's plan/depth order), the limb keeps its own layer pixels through projection, limb cutting, island/nearest-line assignment, base-footprint exclusion, fringe clearing and seam correction (issue #637). Those pixels are occluded, never counted as painting projection; no base footprint or painting colour replaces them. After source-art island/nearest-line assignment, a source-transparent cap pixel is assigned before protection, in both doors: its centre is compared against only the segments taking the recipient's source, at the set's supplied bones (ankle-to-toe for a separate foot source), with the existing 0.5 px overlap band and base draw order. A missing last endpoint is refused with `ASSEMBLE_ALT_LIMB_POSE`; an actual following joint may supply that endpoint, never a guessed point. An unposed other limb with base art beneath these cap pixels is likewise refused; without such overlap the existing compatible path retains the cap without inventing the other limb's pose. A pixel cleared by this assignment is never restored. `CAP_FROM_UPPER` records a copy made before assignment and alone proves no ownership: only a retained copy is protected beneath the upper segment, which is drawn over it. The source-art island selection itself is unchanged. Other retained cap pixels (from the layer or a supplied cap image) are protected under an actual front layer even where the lower source is transparent. Protection follows each assigned piece through exclusion, fringe clearing and seam correction; it never restores a pixel ownership removed. Cap pixels removed during ownership leave their original counts for `excluded_px`, just as excluded pixels do, so the cap ledger describes the written PNG. Target assignment reconciles this ledger even when there are no source-transparent cap candidates and when a direct caller does not request cover protection. Unprotected source pixels still obey the base-footprint exclusion. Missing limb/cap art is never extended or guessed. Base builds and uncovered, unexcluded sets keep their existing bytes. `skeleton` (a pose file path relative to the config's directory, `{"width": W, "height": H, "points": {…}}` with all 18 body-18 keypoints on the canvas, validated by the same rules as `generation.control.skeleton`: `CONFIG_FILE_PRESENT`, `CONFIG_IS_JSON`, `CONFIG_FIELD_TYPE`, `CONFIG_KEY_KNOWN`, `CONFIG_KEY_UNIQUE`, `CONFIG_POSE_CANVAS`, `CONFIG_POSE_KEYPOINTS`, `CONFIG_POSE_IN_CANVAS`) or `drawn` (`{<bone>: <worldDegrees>}`, each bone resolved against `bones`, `CONFIG_NAME_RESOLVES`) declares the posed angles the alternate was painted at (issue #465); when `skeleton` is given, `assemble` derives `drawn` from its 18 keypoints (filtered to covered bones on a subset set, with `drawn` overriding any bone named in both), records both `skeleton` (scaled by `assemble.rig_scale` to rig px) and `drawn` in `parts.json` `alternates` — and, when the skeleton placed the set's limb bones (issue #539), `drawnLength` (`{<bone>: <ratio>}`, each covered table bone's skeleton segment length over its base length, 6 places) and `registration` (`{offset: [dx, dy], scale}`: the similarity without rotation, about the canvas origin, that maps the skeleton's torso — the mean of its shoulders `r_shoulder`/`l_shoulder` to the mean of its hips `r_hip`/`l_hip`, read where the base declares the bone rooted there, `sleeve_*0`/`arm_*0` and `leg_*0` — onto those base bones' origins, 6 places), both also written to `sets.json`; the set's painting must be registered, its torso within 1 rig px and 1 % in scale of the base's, or the set is refused by name before any joint is cut (`ASSEMBLE_ALT_SKELETON_REGISTERED`, with the offset and scale the painting would need) — and the `rig` stage writes `<set>_*` region and mesh attachments in the bone-local frame of `poseRigBonesForDrawn(bones, drawn)` (weighting limb segments directly from `skeleton`'s joint endpoints when `skeleton` is present) and emits `drawn` in `sets.json` so `rig-pose` and `check --set <name>` / `--all-sets` pose the bones at `drawn` without rotating the already-posed art a second time. `front` (issue #664) lists covered limb segment parts the set draws on their **front slot** instead of the base slot: each must be in the set's `parts` and not its `hides`, and listed in some `config.limbs.<limb>.front.parts` (`CONFIG_SET_FRONT`); the set then maps `<part>_front` (never `<part>`) to `<set>_<part>` in `parts.json` and `sets.json` and hides `<part>` (and `<part>_still`), its #587 exclusion counts only base parts drawn after the front slot's target, and keying that part's set on a slot track is refused (`CONFIG_SET_FRONT_KEYED`) — *Front slots (issue #664)* below `layers` optionally maps covered, nonhidden output part names to layer names in their existing source run (issue #666); for example `"layers": {"upperarm_r": "author:raised", "forearm_r": "author:raised"}`. Limb cuts, caps, islands and base exclusions read the selected layer; the base plan stays unchanged. |
134
- | `assemble.head_face_underfill` | assemble, `assemble --propose-plan` | **authored**, optional (issue #492): `boolean` (`CONFIG_FIELD_TYPE` on any other). When both runs exist and `full:face` has at least `200` opaque run px (`PROPOSE_MIN_PX`), the stage maps `full:face` into the head canvas via `fullLayerToHead` and measures how much of its hole-filled silhouette (`alpha > 8`) is covered by `head:face` (`alpha > 8`). A head-run `face` covering less than `75 %` (`HEAD_FACE_COVERAGE_FLOOR`, measured `0.0 %..48.6 %` on hollow/omitted head runs vs `84.8 %..99.6 %` on clean head runs across the 4 public examples and 9-standee corpus) is refused with `SEETHROUGH_HEAD_RUN_HOLLOW` unless `head_face_underfill: true` is declared. When `head_face_underfill: true` is declared and `head:face` exists (`opaqueRunPx >= 200`), `fullLayerToHead(full:face)` is composited under `head:face` on the head canvas (`alpha = max(headAlpha, fullAlpha)`, RGB blended by `headAlpha / 255`) before `head:face` is placed in rig space (`underfill=<N>px(full:face)` on the `face` part log line and a `face: head_face_underfill composited …` note in `assemble --propose-plan`). The fill restores transparent pixels only and leaves the cut's own edge where it is — a hollow whose edge is not under hair stays visible; follow [Source before scissors](#source-before-scissors) for its source remedy. When `head:face` has fewer than `200` opaque pixels, `SEETHROUGH_HEAD_RUN_HOLLOW` still fires even under `head_face_underfill: true` because the head run omitted the face layer and cannot supply a jawline |
134
+ | `assemble.head_face_underfill` | assemble, `assemble --propose-plan` | **authored**, optional (issue #492): `boolean` (`CONFIG_FIELD_TYPE` on any other). During head-face preparation, when both runs exist and `full:face` has at least `150` opaque run px (`PROPOSE_MIN_PX`), the stage maps `full:face` into the head canvas via `fullLayerToHead` and measures how much of its hole-filled silhouette (`alpha > 8`) is covered by `head:face` (`alpha > 8`). An explicit plan selecting `head:face` is refused when that layer covers less than `75 %` (`HEAD_FACE_COVERAGE_FLOOR`, measured `0.0 %..48.6 %` on hollow/omitted head runs vs `84.8 %..99.6 %` on clean head runs across the 4 public examples and 9-standee corpus), with `SEETHROUGH_HEAD_RUN_HOLLOW`, unless `head_face_underfill: true` is declared. When `head_face_underfill: true` is declared and `head:face` exists (`opaqueRunPx >= 150`), `fullLayerToHead(full:face)` is composited under `head:face` on the head canvas (`alpha = max(headAlpha, fullAlpha)`, RGB blended by `headAlpha / 255`) before `head:face` is placed in rig space (`underfill=<N>px(full:face)` on the `face` part log line and a `face: head_face_underfill composited …` note in `assemble --propose-plan`). The fill restores transparent pixels only and leaves the cut's own edge where it is — a hollow whose edge is not under hair stays visible; follow [Source before scissors](#source-before-scissors) for its source remedy. When `head:face` has fewer than `150` opaque pixels, `SEETHROUGH_HEAD_RUN_HOLLOW` still fires even under `head_face_underfill: true` because the head run omitted the face layer and cannot supply a jawline. The proposer instead selects `full:face` after this refusal when that full-run candidate passes the pixel floor and plausibility guards (issue #863); if it does not, the refusal remains. An assemble plan selecting `full:face` without `head:face` does not prepare the unused head face |
135
135
  | `assemble.yield_refused` | assemble | **authored**, optional boolean, default `false` (issue #819; other types: `CONFIG_FIELD_TYPE`). With `true`, an original front projection-core pixel refused at max-channel drift > `DRIFT_LIMIT` (90) can yield when its original source pixel is still opaque. Non-core rim pixels (0 < alpha < `CORE_ALPHA`, 250) on the same 8-connected part body can then yield too (issue #832). Connectivity reads the part support before clearing: the opaque border outside the eroded projection core connects the body to its rim but is not itself newly cleared. A separate rim island without a yielded core seed is unchanged. At every cleared pixel, the actual top-most opaque holder below it (alpha >= 250), after earlier yields, must have colour within 90 of the painting. A deeper matching part cannot bypass an intervening opaque mismatch. This setting also applies to alternate sets. A yielded pixel's alpha becomes 0 and its RGB is not repainted. Accepted own-core pixels in the same connected support within the original yielded core's Gaussian footprint (radius 4 rig pixels), with a matching opaque behind holder, finish to painting RGB while retaining alpha and ownership (issue #841); original refusals, protected samples and replacements are excluded. Away from that footprint projection is unchanged. Merge/ring replacements, samples explicitly kept by `keep_under_occluders`, and pixels outside a derived piece cannot connect a rim or be newly yielded. Front is relative to the matching part behind, so original refusals in another run are eligible even when a different part is the global top holder. The reading proceeds back to front against the current behind pixels; alpha changes do not repaint or create a new matching colour. `yieldReadings` optionally records `finishedProjection` (accepted samples whose RGB changed), and records `yieldedRim` as the rim subset of total `yielded`, skipped core merge/ring/nonopaque/no-match counts and original/final global holders; a yielded pixel also taken by projection closing is omitted from the written `source_px_taken` count. Existing cuts/patches and thresholds are unchanged. The `drift:` line reports `yielded N px` per affected part, even below the drift-body size bar; with the setting off it names `assemble.yield_refused: true` as the conditional remedy. Rebuild and inspect the newly exposed layer in motion before considering any cut; a mismatching or absent behind holder cannot be repaired by this setting. |
136
136
  | `assemble.keep_under_occluders` | assemble | **authored**, optional array of unique source part names from `assemble.plan`, default `[]` (issue #825). For each named part, keep its own See-through RGBA where the front-most covering part in the final draw stack has alpha greater than 0 and below `CORE_ALPHA` (250), including a cover in the other run. For an explicitly named part, original alpha 1–8 fringe removed by ghost cleanup also counts as source cover, within its final piece region: those pixels still contributed to the painting. Only original opaque own-layer samples are restored after source projection/closing and protected from later seam re-take; merged/rim, cap, under-fill and authored replacement pixels are excluded. This keeps their existing provenance and makes no holes; fully opaque cover and absent cover keep the old path. Cuts and limb pieces inherit the source part's protection. Unknown names: `CONFIG_NAME_RESOLVES`; duplicates: `CONFIG_PART_UNIQUE`; invalid shape: `CONFIG_FIELD_TYPE`. Inspect the part's own amodal layer first: this handle preserves its existing content and cannot complete a missing pixel. Example: `"keep_under_occluders": ["shin_r"]`. |
137
137
  | `limbs` | assemble (the cut and the caps), rig (through `regions`), check (`LIMB_ONE_BONE`) | **proposed** by `propose --keypoints` (issue #349), then checked: `{<limb>: {segments: [{part, from, bone}, {part, from, bone, joint, range?, cap?, edge?, cap_shape?, cut_band?, hybrid?}, …], split?, layout?, front?}}`, the upper segment first. The rule is *Limbs: cut at their joints* below the table. `part` is a new part (`CONFIG_PART_NAME`, `CONFIG_PART_UNIQUE` against the plan, patches, cuts and every other limb part); `from` a plan part or a cut's piece (`CONFIG_NAME_RESOLVES`) — the layer the segment's pixels come from, which is cut into the limb parts and is not itself made: a `meshes` or `regions` entry for it is `CONFIG_NAME_RESOLVES`, and the segments of one limb that take one part are consecutive (`CONFIG_LIMB_FROM_RUN`); `bone` a declared bone, each segment's the child of the one before (`CONFIG_LIMB_BONES_CHAIN`); the upper segment names no `joint`, `range`, `cap`, `edge`, `cap_shape` or `cut_band` (`CONFIG_KEY_KNOWN`), every other names its `joint` (`CONFIG_FIELD_PRESENT`) — the joint is its bone's origin; `range` is `[min, max]` degrees from rest with `min <= 0 <= max` (`CONFIG_LIMB_RANGE`), which `assemble` writes into the lower part's `parts.json` record and `check` poses the joint at — its two ends and its middle — reading the seam there (`SEAM_OVER_RANGE`, issue #360; rig-c needs no rotation limit); `cap` a PNG path relative to the config's directory (`CONFIG_FIELD_TYPE`); `edge` `"feather"` (issue #360), the one value it takes, and `cap_shape` `"disc"` (issue #360) or `"ball"` (issue #579) (`CONFIG_FIELD_TYPE` on any other) — the cut's geometry at that joint, *Limbs: cut at their joints* below; absent, the cut is hard and the cap the layer's half-disc of half the limb's width; `cut_band` a whole number of px, 1 or more (`CONFIG_FIELD_TYPE`), on a segment that takes the segment above's part — between two layers nothing is cut, so a band there is `CONFIG_KEY_KNOWN` — places the cut within that many px of the joint line (issue #360, *Limbs: cut at their joints*); absent, the cut is the joint line. Each limb part is attached like any part — `regions.<part>`, which must be the segment's `bone` (`CONFIG_LIMB_BONE`), or a mesh, which `check` holds to that bone alone (`LIMB_ONE_BONE`). With `limbs`, `assemble` reads `bones` too (`CONFIG_FIELD_PRESENT` without it). Absent, nothing is cut at a joint and no byte of any output moves. Optional `front` (issue #664), `{parts: [<own segment part>, …], after: "<produced part>"}`, gives each named segment a second slot `<part>_front`, empty at setup, placed after `after`'s slot family, for a gesture set to draw on (`CONFIG_FRONT_SCOPE`, `CONFIG_FRONT_NAME`, `CONFIG_FRONT_LAYOUT`; *Front slots (issue #664)* below) |
@@ -615,6 +615,88 @@ remain separate authoring decisions; a shifted shoe can still require work on
615
615
  its neighbouring shin. A walk built from eight generated keyframes motivated
616
616
  the opt-in placement; it does not change the default for existing inputs.
617
617
 
618
+ ### Taking named layers from another run (`assemble.take`, issue #866)
619
+
620
+ A run of the same painting, or a different painting with the same pixels under
621
+ some layers, can supply those tags without editing either run directory:
622
+
623
+ ```json
624
+ "take": [{
625
+ "run": "full",
626
+ "run_dir": "runs/other",
627
+ "st_input": "inputs/other_full.png",
628
+ "tags": ["front hair", "mouth"]
629
+ }]
630
+ ```
631
+
632
+ This array belongs in `assemble`. Every entry requires all four fields. `run`
633
+ is the **target** `full` or `head` run; `head` requires `--head`. `run_dir` and
634
+ `st_input` resolve relative to the config, for assemble, build and
635
+ `assemble --propose-plan` alike. Each target run/tag may be selected once. Empty
636
+ `take` and absent `take` leave the existing output unchanged. This selects base
637
+ run layers; alternate painting sets keep their own existing declarations.
638
+
639
+ `st_input` is the author's explicit declaration of the original PNG fed to the
640
+ donor. The tool reads `run_dir/layers.json`
641
+ and `run_dir/meta.json`, requiring a nonempty `prompt_id` and a nonnegative safe
642
+ integer `seed`; it never infers either from the target config. Existing metadata
643
+ does **not** bind that PNG's bytes to the prompt or layers. This checks the
644
+ supplied evidence's pixel identity, not cryptographic provenance of a remote
645
+ execution. Keep the original run, its metadata and original input together;
646
+ renaming a supplied image does not establish that it was the donor's input.
647
+
648
+ The target input is derived from the painting by the existing input model:
649
+ `full` uses the exact centred white `squarePad`, and `head` the configured
650
+ `head_box`. A nonsquare single-run file uses the painting at its original file
651
+ size before the assembler's existing padding. Donor and target run canvases must
652
+ have equal dimensions; donor and target input PNGs must also have equal
653
+ dimensions. Incompatible canvases or input sizes are refused, never resized to
654
+ make the comparison pass.
655
+
656
+ For each selected layer, support means its **original** alpha > 8, including
657
+ specks before ghost cleanup. Grow that support by the existing projection-core
658
+ `CORE_KERNEL` (5 x 5, radius 2 run pixels), clipped to the run canvas. Map each
659
+ covered run cell to **every intersecting** original input pixel cell. Compare
660
+ all four RGBA bytes exactly, with no filtering or tolerance. Checking each
661
+ layer's grown support checks their union too; the note reports both per-layer
662
+ and union counts. A mismatch names the donor run, tag, number of differing
663
+ pixels and `[left, top, right, bottom]` bbox in input pixels, right/bottom
664
+ exclusive. A tag absent from the donor, or with no alpha > 8 support, is refused.
665
+ An input difference outside that union is permitted.
666
+
667
+ Taken layers replace the target's tag, keeping the donor's tag and
668
+ `depth_median`, so existing hair/blink classification continues to read `from`.
669
+ Larger depth draws behind smaller depth. Numeric ties keep manifest order only
670
+ inside one original run. Equal or null depths **across** runs are ambiguous
671
+ and refused, even if the plan gives an order. A supplied plan reversing the
672
+ mixed-run depth order is also refused; `--propose-plan` drafts the depth order.
673
+ Replacing a layer with hidden companion art is refused because independent
674
+ hidden-art identity has not been declared. Active scalar depth sheets (`depth`
675
+ opt-in or already bound sheets) are also refused: selecting donor art does not
676
+ rebind a target atlas or invent donor scalar units. Inactive `depth_filename`
677
+ hints remain inactive; numeric `depth_median` ordering is preserved.
678
+
679
+ The proposal's `notes` and assemble/build log name every taken layer's run
680
+ directory, prompt ID, seed and input path, plus support/checked/differing counts.
681
+ `parts.json` adds `taken_layers` only to affected parts: each entry records
682
+ `run`, `tag`, `run_dir`, `st_input`, `prompt_id`, `seed`, `support_px` (run cells),
683
+ `checked_px` (original input cells), and `differing_px` (zero). Cuts, generated
684
+ arm layers, limb segments and copied extension sources retain these receipts.
685
+ The strict parts reader refuses partial, unknown, duplicate or nonzero-difference
686
+ receipts. These source identities are separate from pixel-writer counts.
687
+
688
+ Motivation, from the recorded 2026-10-30 decomposition measurements: a side-view
689
+ control held 62,627 front-hair, 36,643 headwear and 595 mouth pixels at
690
+ **alpha >= 250**. Three body repaints reported zero pixels at that threshold
691
+ for front hair and mouth at seed 42; their alpha > 8 counts were nonzero.
692
+ Six further runs at seeds 43, 101 and 2027 reported no run retaining both front
693
+ hair and headwear. These are recorded measurements, not a new pixel audit:
694
+ the retained run receipts contain no original layer PNGs. The records report
695
+ identical head input pixels and body-dependent limb results; this feature makes
696
+ identity an executable check on supplied original inputs instead of trusting
697
+ that claim or hand-editing `layers.json`. Seed and painting selection remain
698
+ the author's decisions.
699
+
618
700
  ### Alternate part layers (`assemble.alternates[i].layers`, issue #666)
619
701
 
620
702
  A gesture run may hold a raised arm only in a layer the author added, while
@@ -3086,6 +3168,22 @@ full loader before its assemble stage writes anything.
3086
3168
  6. `rig-parts assemble --propose-plan --source … --full … --head … --config config.json --write-config config.json`
3087
3169
  saves `assemble.plan` and `assemble.extend_below_crop`. Config: the
3088
3170
  `layers` row, with `head_box`.
3171
+ The proposer prefers the head run for `front hair`, `back hair` and `face`.
3172
+ If that head layer is missing, below `PROPOSE_MIN_PX`, or refused by a plan
3173
+ guard, it takes the full-run layer only when that candidate passes the same
3174
+ pixel floor and plausibility guards (issue #863). A suitable head layer stays
3175
+ selected; these three tags do not use headwear/earwear's 0.8 area preference.
3176
+ Back hair stays behind the body and face; a fallback face precedes head details
3177
+ and front hair; fallback front hair is drawn in front of the face. The note
3178
+ names both rig-pixel areas and the head candidate's failure. Full-run hair is
3179
+ already on the full canvas, so it gets no `extend_below_crop` entry.
3180
+ A hollow-head refusal also permits this validated full-face fallback. Explicit
3181
+ plans selecting `head:face` keep the hollow check and underfill opt-in; a plan
3182
+ selecting `full:face` does not prepare or validate the unused head face.
3183
+ The oversized-layer guard still measures a layer against the other layers'
3184
+ union **in its own run**, after face preparation. Losing supporting head layers
3185
+ can shrink that denominator, and underfill can enlarge the numerator; neither
3186
+ event relaxes the guard or makes a rejected full candidate eligible.
3089
3187
  Read `notes`: every layer not planned — each tag a layer of either run holds that no
3090
3188
  row takes — is named there once, `<tag>: in no plan row — …`, with why, run by run: the
3091
3189
  run holds no such layer; the proposer takes that tag from the other run only
@@ -4349,6 +4447,19 @@ those settings. Changing a config seed alone cannot change a no-config run.
4349
4447
 
4350
4448
  | rule | means | change |
4351
4449
  | --- | --- | --- |
4450
+ | <a id="ASSEMBLE_TAKE_INPUT_IDENTITY"></a>`ASSEMBLE_TAKE_INPUT_IDENTITY` | original input RGBA differs under a taken tag's grown support; detail gives run/tag, count and exclusive input bbox | select a compatible donor and its actual original `st_input`; no tolerance or repaint is applied |
4451
+ | <a id="ASSEMBLE_TAKE_TAG_IN_RUN"></a>`ASSEMBLE_TAKE_TAG_IN_RUN` | selected donor does not hold the tag | choose a tag present in that donor |
4452
+ | <a id="ASSEMBLE_TAKE_SUPPORT"></a>`ASSEMBLE_TAKE_SUPPORT` | selected layer has zero alpha > 8 pixels | choose a nonempty donor layer |
4453
+ | <a id="ASSEMBLE_TAKE_DEPTH_AMBIGUOUS"></a>`ASSEMBLE_TAKE_DEPTH_AMBIGUOUS` | different original runs have equal or null depths | use a run with distinct numeric depths; do not invent an inter-run tie order |
4454
+ | <a id="ASSEMBLE_TAKE_PLAN_ORDER"></a>`ASSEMBLE_TAKE_PLAN_ORDER` | supplied plan reverses mixed-run depth order | use the depth order drafted by `assemble --propose-plan` |
4455
+ | <a id="ASSEMBLE_TAKE_GEOMETRY"></a>`ASSEMBLE_TAKE_GEOMETRY` | missing target head, unequal run canvases or unequal original input dimensions | supply matching geometry; the check does not resize inputs |
4456
+ | <a id="ASSEMBLE_TAKE_META"></a>`ASSEMBLE_TAKE_META` | donor `meta.json` lacks a readable prompt ID or seed | retain the original run metadata |
4457
+ | <a id="ASSEMBLE_TAKE_INPUT"></a>`ASSEMBLE_TAKE_INPUT` | declared donor input PNG cannot be read | name its original PNG relative to the config |
4458
+ | <a id="ASSEMBLE_TAKE_DEPTH_SHEET"></a>`ASSEMBLE_TAKE_DEPTH_SHEET` | taking layers with an active depth opt-in or bound scalar sheets has no declared mixed-run binding | keep scalar depth inactive; numeric ordering depth is retained, and a target sheet is never attached silently |
4459
+ | <a id="ASSEMBLE_TAKE_HIDDEN"></a>`ASSEMBLE_TAKE_HIDDEN` | a replaced tag has hidden companion art | independent hidden-art identity is undeclared; choose a run without that companion |
4460
+ | <a id="ASSEMBLE_TAKE_UNIQUE"></a>`ASSEMBLE_TAKE_UNIQUE` | repeated donor for one target tag at runtime | declare each target run/tag once |
4461
+ | <a id="CONFIG_TAKE_UNIQUE"></a>`CONFIG_TAKE_UNIQUE` | config selects the same target run/tag more than once | retain one donor per target tag |
4462
+ | <a id="PARTS_TAKEN_LAYERS"></a>`PARTS_TAKEN_LAYERS` | a taken-layer receipt is partial, unknown, duplicated, malformed or claims differing pixels | regenerate parts with assemble; never patch source receipts by hand |
4352
4463
  | <a id="ASSEMBLE_FIELD_PRESENT"></a>`ASSEMBLE_FIELD_PRESENT` | `seethrough.head_box` is missing | `propose --head-box` proposes it (§3) |
4353
4464
  | <a id="ASSEMBLE_RIG_SIZE"></a>`ASSEMBLE_RIG_SIZE` | `rig_scale` makes an empty rig | `assemble.rig_scale` |
4354
4465
  | <a id="ASSEMBLE_HEAD_BOX_INSIDE"></a>`ASSEMBLE_HEAD_BOX_INSIDE` | the head box is outside the painting | `head_box` — `propose --head-box` holds it inside |
@@ -4359,7 +4470,7 @@ those settings. Changing a config seed alone cannot change a no-config run.
4359
4470
  | <a id="ASSEMBLE_SINGLE_RUN_HEAD_BOX"></a>`ASSEMBLE_SINGLE_RUN_HEAD_BOX` | with no `--head`, the config sets `seethrough.head_box`, which places a head run there is not | remove `head_box`, or give the head run with `--head` |
4360
4471
  | <a id="ASSEMBLE_ARM_SPLIT_CUTS_ARM"></a>`ASSEMBLE_ARM_SPLIT_CUTS_ARM` | `seethrough.arm_split` cuts a horizontal opaque run of the arm layer into more than two segments (issue #439; the detail gives the row, the run and the split x) | `seethrough.arm_split`: move `x` or `line` so each horizontal opaque run of the arm layer is split at most once |
4361
4472
  | <a id="SEETHROUGH_ARM_RUN_MERGED"></a>`SEETHROUGH_ARM_RUN_MERGED` | a full-run `handwear-r` or `handwear-l` layer merges sleeve, bare hand (`>= 40` skin run px around `<s>_wrist`, `GHOST_MIN_AREA`) and overgarment into one arm layer with non-skin pixels reaching more than `1.0x` the forearm length (`<s>_elbow -> <s>_wrist`) below `<s>_wrist` (measured `-0.15x..0.45x` on the 6 clean standees vs `1.25x..2.02x` on the 3 merged standees), and the sleeve above `<s>_wrist` and the drape below `<s>_wrist` have Euclidean RGB distance `< 80` (`ARM_DRAPE_COLOR_DISTANCE`, measured `20.8..28.2` when same-coloured vs `103.6..236.0` when distinct) so the stage cannot split them by colour (issue #490; the detail gives the hand px, the non-skin span, the forearm length and both RGB medians) | follow [Source before scissors](#source-before-scissors): select another layer/run, then a tighter run (`comfy seethrough --config <config.json>` to read changed `seethrough` settings, or explicit `--seed <n>`), then correct depth/role; if no separate source exists and sleeve and overgarment must move independently, a structural `author:` layer or `assemble.cuts` entry separates them |
4362
- | <a id="SEETHROUGH_HEAD_RUN_HOLLOW"></a>`SEETHROUGH_HEAD_RUN_HOLLOW` | `full:face` has at least `200` opaque run px (`PROPOSE_MIN_PX`) and `head:face` covers less than `75 %` (`HEAD_FACE_COVERAGE_FLOOR`, measured `0.0 %..48.6 %` on hollow/omitted head runs vs `84.8 %..99.6 %` on clean head runs across the 4 public examples and 9-standee corpus) of `fullLayerToHead(full:face)`'s hole-filled silhouette (`alpha > 8`) in the head canvas while `config.assemble.head_face_underfill: true` is not declared, or `head:face` has fewer than `200` opaque pixels so there is no head-run `face` layer to under-fill (issue #492; the detail gives the full-run mapped count, the head-run overlap and upper/lower half shares) | change `config.seethrough.seed` and re-run `comfy seethrough --config <config.json>` (or pass `--seed <n>`), or set `config.assemble.head_face_underfill: true` when `head:face` exists so the stage composites `fullLayerToHead(full:face)` under `head:face` on the head canvas (the fill restores transparent pixels only and leaves the cut's own edge where it is — a hollow whose edge is not under hair stays visible; follow [Source before scissors](#source-before-scissors) for its source remedy) |
4473
+ | <a id="SEETHROUGH_HEAD_RUN_HOLLOW"></a>`SEETHROUGH_HEAD_RUN_HOLLOW` | `full:face` has at least `150` opaque run px (`PROPOSE_MIN_PX`) and `head:face` covers less than `75 %` (`HEAD_FACE_COVERAGE_FLOOR`, measured `0.0 %..48.6 %` on hollow/omitted head runs vs `84.8 %..99.6 %` on clean head runs across the 4 public examples and 9-standee corpus) of `fullLayerToHead(full:face)`'s hole-filled silhouette (`alpha > 8`) in the head canvas while `config.assemble.head_face_underfill: true` is not declared, or `head:face` has fewer than `150` opaque pixels so there is no head-run `face` layer to under-fill (issue #492; the detail gives the full-run mapped count, the head-run overlap and upper/lower half shares) | `assemble --propose-plan` falls back to `full:face` when it passes the pixel floor and plausibility guards (issue #863); explicit `head:face` plans still refuse. Re-propose and rebuild, change `config.seethrough.seed` and re-run `comfy seethrough --config <config.json>` (or pass `--seed <n>`), or set `config.assemble.head_face_underfill: true` when `head:face` exists so the stage composites `fullLayerToHead(full:face)` under `head:face` on the head canvas (the fill restores transparent pixels only and leaves the cut's own edge where it is — a hollow whose edge is not under hair stays visible; follow [Source before scissors](#source-before-scissors) for its source remedy) |
4363
4474
  | <a id="ASSEMBLE_PLAN_TAG_IN_RUN"></a><a id="ASSEMBLE_EXTEND_TAG_IN_RUN"></a>`ASSEMBLE_PLAN_TAG_IN_RUN`, `ASSEMBLE_EXTEND_TAG_IN_RUN` | an entry takes a tag its run does not hold (the detail lists what it does hold) | that entry's run or tag |
4364
4475
  | <a id="ASSEMBLE_PAINTING_BAND_INSIDE"></a>`ASSEMBLE_PAINTING_BAND_INSIDE` | an extension band reaches past the rig canvas | supply an in-canvas half-open band in rig pixels; no bound is clipped |
4365
4476
  | <a id="CONFIG_ORDER_UNIQUE"></a>`CONFIG_ORDER_UNIQUE` | two `assemble.extend_painting` entries declare the same precedence order | give every entry a unique nonnegative safe integer `order`; lower orders claim first, no implicit tie break |
package/docs/STABILITY.md CHANGED
@@ -129,10 +129,11 @@ part name, `[i]` an entry of a list):
129
129
  - **generation.control.skeleton**, the pose file it names when it is no built-in — required: `width`, `height`, `points`
130
130
  - **seethrough** — required: `resolution`, `steps`, `seed`, `offload`; optional: `head_box`, `arm_split`
131
131
  - **seethrough.arm_split** — required: `order`, and one of `x` or `line` (issue #439)
132
- - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `keep_under_occluders`, `extend_painting`
132
+ - **assemble** — required: `rig_scale`, `plan` (from plain `assemble` on); optional: `extend_below_crop`, `patches`, `cuts`, `alternates`, `head_face_underfill`, `yield_refused`, `keep_under_occluders`, `extend_painting`, `take`
133
133
  - **assemble.alternates[i]** — required: `name`; optional: `source`, `full`, `head`, `parts`, `hides`, `head_box`, `cuts`, `skeleton`, `anchor`, `base_anchor`, `drawn`, `tips`, `front`, `layers`, `focus` (issues #454, #465, #543, #652, #664, #666, #719, #780). `focus` is an authored finite `[x, y]` in painting pixels, within its canvas (edges included), refused as CONFIG_SET_FOCUS before assemble output when invalid; only when present, `parts.json` records it with focus_source_size and `sets.json` emits it in setup-world coordinates through the actual rig resize and `src/coords.ts`. Absent focus emits no field or inferred value; changing/removing it requires reassembly
134
134
  - **assemble.extend_below_crop[i]** — required: `part`, `run`, `tag`
135
135
  - **assemble.extend_painting[i]** — required: `part`, `band`, `max_distance`; optional: `min_held_alpha`, `order` (issues #848, #854, #855; explicit final layer-derived part, half-open rig band and positive four-neighbour path bound; base painting only). The optional integer floor 1–255 admits exact original alpha-over coverage strictly below it; absent or 1 blocks every nonzero holder. Only selected target samples below the floor may take painting RGBA; target samples at/above the floor and every non-target holder remain exact. By default overlapping reachable claims refuse. With `order` on every entry (unique nonnegative safe integers), lower values claim first and their gains block later candidates and paths; array order never breaks ties or supplies missing precedence
136
+ - **assemble.take[i]** — required: `run`, `run_dir`, `st_input`, `tags` (issue #866)
136
137
  - **assemble.patches[i]** — required: `name`, `box`, `alpha`, `draw`
137
138
  - **assemble.patches[i].draw**, when an object — required: `before`
138
139
  - **assemble.cuts[i]** — required: `from`, `into`, `polygon`, `draw`, `overlap`; optional: `under`, `under_fill`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rig-parts",
3
- "version": "1.82.1",
3
+ "version": "1.83.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,3 +1,4 @@
1
+ import { unionTakenSources } from './takesource.ts';
1
2
  import { paintingExtensionMasks, paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
2
3
  import { AUTOMATIC_WRITERS as AW, compactValueBaseline, pixelProvenance, rgbaEqual, type ValueBaseline } from './provenance.ts';
3
4
  import { bindDepthRun, copyDepthMaterial, registerDepthRun, transportPartDepth, type DepthConfig, type RegisteredDepth } from './depthsheets.ts';
@@ -1494,6 +1495,7 @@ export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSp
1494
1495
  name,
1495
1496
  tag: readLayerTag(name) as LayerTagReading,
1496
1497
  file: refLayer.file,
1498
+ takenLayers: unionTakenSources(handLayers.map(l => l.takenLayers)),
1497
1499
  pixels: crop(canvas, m.x0, m.y0, m.x1 - m.x0 + 1, m.y1 - m.y0 + 1),
1498
1500
  left: m.x0,
1499
1501
  top: m.y0,
@@ -1803,6 +1805,7 @@ export function splitMergedArmRunsWithNotes(
1803
1805
  name,
1804
1806
  tag: readLayerTag(name) as LayerTagReading,
1805
1807
  file: hwLayer.file,
1808
+ ...(hwLayer.takenLayers === undefined ? {} : { takenLayers: hwLayer.takenLayers }),
1806
1809
  pixels: crop(canvas, x0, y0, x1 - x0 + 1, y1 - y0 + 1),
1807
1810
  left: x0,
1808
1811
  top: y0,
@@ -2098,6 +2101,7 @@ function prepareHeadFace(
2098
2101
  const postStats = measureCoverage(comp);
2099
2102
  const replacedLayer: Layer = {
2100
2103
  ...headFaceLayer,
2104
+ takenLayers: unionTakenSources([headFaceLayer.takenLayers, fullFaceLayer.takenLayers]),
2101
2105
  pixels: crop(comp, x0, y0, x1 - x0 + 1, y1 - y0 + 1),
2102
2106
  left: x0,
2103
2107
  top: y0,
@@ -4663,10 +4667,11 @@ export function assemble(input: AssembleInput): AssembleResult {
4663
4667
  });
4664
4668
  const sourcePlan = plan.flatMap(row => [row, ...cutLayerPlan.filter(([name]) => input.cuts.some(c => c.into === name && c.from === row[0]))]);
4665
4669
  // Issue #492: in two-run mode, check that head:face covers >= 75% of full:face's silhouette on the head canvas
4666
- // (after applying head_face_underfill when declared). Skip only on a single-run subset (a mouth-only or clothes-only alternate).
4670
+ // (after applying head_face_underfill when declared). A plan selecting full:face does not consume head:face (#863).
4667
4671
  const checkHeadFace =
4668
4672
  !single &&
4669
- (plan.some(([, r, t]) => r === 'head' && t === 'face') || (plan.some(([, r]) => r === 'full') && plan.some(([, r]) => r === 'head')));
4673
+ (plan.some(([, r, t]) => r === 'head' && t === 'face') ||
4674
+ (!plan.some(([, r, t]) => r === 'full' && t === 'face') && plan.some(([, r]) => r === 'full') && plan.some(([, r]) => r === 'head')));
4670
4675
  const headFacePrep = checkHeadFace
4671
4676
  ? prepareHeadFace(full, depthHeadInput, frame, input.resolution, input.headFaceUnderfill === true)
4672
4677
  : { head: single ? full : depthHeadInput, underfillPx: 0, underfillNote: null };
@@ -5521,6 +5526,13 @@ export function assemble(input: AssembleInput): AssembleResult {
5521
5526
  merged_px: merged,
5522
5527
  seam_override_px: 0,
5523
5528
  };
5529
+ const sourceKeys = new Set([key, ...extendKeys.filter((_, i) => trace.from.some(v => v === i))]);
5530
+ const takenLayers = unionTakenSources([...sourceKeys].map(k => {
5531
+ const colon = k.indexOf(':');
5532
+ const run = k.slice(0, colon) as Run;
5533
+ return (run === 'full' ? full : head).layers.find(l => l.name === k.slice(colon + 1))?.takenLayers;
5534
+ }));
5535
+ if (takenLayers.length > 0) record.taken_layers = takenLayers;
5524
5536
  const paintingGain = paintingGains.get(name);
5525
5537
  if (paintingGain !== undefined) record.painting_extension_px = paintingGain.data.reduce((sum, value) => sum + value, 0);
5526
5538
  if (pushedHere.length > 0) record.fringe_pushed_back = pushedHere;
@@ -5541,6 +5553,15 @@ export function assemble(input: AssembleInput): AssembleResult {
5541
5553
  },
5542
5554
  ...((limb?.cap?.image_px ?? 0) > 0 || (limb?.cap?.lower_px ?? 0) > 0 ? { unsupported: `cap copies ${(limb?.cap?.image_px ?? 0) + (limb?.cap?.lower_px ?? 0)} pixels from a separate cap image whose scalar grid is undeclared` } : {}),
5543
5555
  });
5556
+ if (capSource !== null && upperIndex >= 0 && capSource.codes.some(code => code === CAP_FROM_UPPER)) {
5557
+ const upper = limbPieces[upperIndex];
5558
+ const keys = [upper.key, ...upper.extendKeys.filter((_, i) => upper.trace.from.some(v => v === i))];
5559
+ const sources = unionTakenSources([record.taken_layers, ...keys.map(k => {
5560
+ const colon = k.indexOf(':');
5561
+ return (k.slice(0, colon) === 'full' ? full : head).layers.find(l => l.name === k.slice(colon + 1))?.takenLayers;
5562
+ })]);
5563
+ if (sources.length > 0) record.taken_layers = sources;
5564
+ }
5544
5565
  if (scalar !== undefined) record.depth = scalar.reference;
5545
5566
  if (scalar !== undefined && scalar.clampedSamples > 0) depthClamps.push({ part: name, samples: scalar.clampedSamples });
5546
5567
  set({ record, image, ...(scalar === undefined ? {} : { depthImage: scalar.image }) });
@@ -6027,6 +6048,9 @@ export const PROPOSE_HEAD_TAGS: readonly string[] = [
6027
6048
  'eyebrow-l',
6028
6049
  ];
6029
6050
 
6051
+ /** #863: prefer suitable head layers; only unusable head candidates may fall back for these tags. */
6052
+ const HEAD_FALLBACK_TAGS: readonly string[] = ['back hair', 'face', 'front hair'];
6053
+
6030
6054
  /** The part name the reference proposes for a tag; any other tag becomes its own name with spaces and hyphens as underscores. */
6031
6055
  export const PROPOSE_ALIAS: Readonly<Record<string, string>> = {
6032
6056
  'back hair': 'hair_back',
@@ -6075,7 +6099,12 @@ function fmt0(v: number): string {
6075
6099
  * head run, the rest from the full run. Order, back to front: `back hair`;
6076
6100
  * the body layers in the full run's draw order, with `neck` placed just before
6077
6101
  * the first of topwear, bottomwear or neckwear; then the remaining head layers
6078
- * in the head run's draw order. A `headwear`/`earwear` the head run drops or
6102
+ * in the head run's draw order. Missing, below-floor or guard-refused head
6103
+ * `back hair`, `face` and `front hair` use a full-run candidate only if it
6104
+ * passes the same floor and plausibility guards (#863); back hair stays
6105
+ * behind the body, face before head details, front hair in front of the face.
6106
+ * A suitable head candidate is retained. Every fallback names the two rig
6107
+ * areas and the reason. A `headwear`/`earwear` the head run drops or
6079
6108
  * shrinks (its rig-pixel area below 0.8 of the full run's) is taken from the
6080
6109
  * full run instead, drawn right after `back hair` — noted. `front hair` and
6081
6110
  * `back hair` taken from the head run are extended below the crop from the
@@ -6163,15 +6192,27 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6163
6192
  // Issue #490: when generation.control.skeleton is present, split merged arm layers (or refuse when sleeve and drape share one colour).
6164
6193
  const mergedSplit = g.keySkeleton === undefined ? { set: fullArmSplit, notes: [] as string[] } : splitMergedArmRunsWithNotes(fullArmSplit, g.resolution, frame, g.sourceW, g.sourceH, g.keySkeleton);
6165
6194
  const full = mergedSplit.set;
6166
- // Issue #492: check (and when head_face_underfill: true, repair) a hollow head-run face against full:face mapped into the head canvas.
6167
- const headFacePrep =
6168
- g.single === true
6169
- ? { head: full, underfillPx: 0, underfillNote: null as string | null }
6170
- : prepareHeadFace(full, head0, frame, g.resolution, g.headFaceUnderfill === true, minPx);
6195
+ const fullLayers = runLayers(full, g.resolution);
6196
+ const fullFigures = layerFigures(full);
6197
+ // A hollow head face must not block a usable full-run candidate before selection (#863).
6198
+ // Preserve every other preparation refusal, and preserve this one when the full candidate fails.
6199
+ let headFaceRefusal: Problem | null = null;
6200
+ let headFacePrep = { head: g.single === true ? full : head0, underfillPx: 0, underfillNote: null as string | null };
6201
+ if (g.single !== true) {
6202
+ try {
6203
+ headFacePrep = prepareHeadFace(full, head0, frame, g.resolution, g.headFaceUnderfill === true, minPx);
6204
+ } catch (err) {
6205
+ const face = fullLayers.find(l => l.tag === 'face');
6206
+ const f = fullFigures.find(l => l.name === 'face');
6207
+ if (!(err instanceof PartsError) || err.problems.length !== 1 || err.problems[0].code !== 'SEETHROUGH_HEAD_RUN_HOLLOW' ||
6208
+ face === undefined || face.opaqueRunPx < minPx || f === undefined || implausibleRules(f).length > 0) throw err;
6209
+ headFaceRefusal = err.problems[0];
6210
+ }
6211
+ }
6171
6212
  const head = headFacePrep.head;
6172
- const runs = { full: runLayers(full, g.resolution), head: runLayers(head, g.resolution) };
6213
+ const runs = { full: fullLayers, head: runLayers(head, g.resolution) };
6173
6214
  const find = (run: Run, tag: string): RunLayer | undefined => runs[run].find((l) => l.tag === tag);
6174
- const figures: Record<Run, LayerFigures[]> = { full: layerFigures(full), head: layerFigures(head) };
6215
+ const figures: Record<Run, LayerFigures[]> = { full: fullFigures, head: layerFigures(head) };
6175
6216
  const dropNotes: string[] = [];
6176
6217
  const noted = new Set<string>();
6177
6218
  /** The plausibility rules `run:tag` crosses; the first time a consulted layer crosses any, a note says so. */
@@ -6188,13 +6229,20 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6188
6229
  const ok = (run: Run, tag: string): boolean => {
6189
6230
  const l = find(run, tag);
6190
6231
  const floor = ARM_MERGED_SPLIT_TAGS.some((p) => tag === `${p}-r` || tag === `${p}-l`) ? 1 : minPx;
6191
- return tag !== 'nose' && l !== undefined && l.opaqueRunPx >= floor && !implausible(run, tag, 'not proposed');
6232
+ return tag !== 'nose' && !(run === 'head' && tag === 'face' && headFaceRefusal !== null) &&
6233
+ l !== undefined && l.opaqueRunPx >= floor && !implausible(run, tag, 'not proposed');
6192
6234
  };
6193
6235
  const body = runs.full.filter((l) => !PROPOSE_HEAD_TAGS.includes(l.tag) && ok('full', l.tag)).map((l) => l.tag);
6194
6236
  // Issue #256: an author-made layer is proposed from the run that holds it, at its place in that run's draw order,
6195
6237
  // like any layer; one both runs hold is proposed once, from the full run when the full run's is proposed, and the note says so.
6196
6238
  const authorBoth = runs.head.filter((l) => readAuthorTag(l.tag) !== null && body.includes(l.tag)).map((l) => l.tag);
6197
6239
  const heads = runs.head.filter((l) => (PROPOSE_HEAD_TAGS.includes(l.tag) || (readAuthorTag(l.tag) !== null && !authorBoth.includes(l.tag))) && ok('head', l.tag)).map((l) => l.tag);
6240
+ const fallback = new Set(HEAD_FALLBACK_TAGS.filter(t => !ok('head', t) && ok('full', t)));
6241
+ // Full-run back hair stays behind the body; face precedes head details, front hair follows the face.
6242
+ if (fallback.has('back hair')) heads.unshift('back hair');
6243
+ if (fallback.has('face')) heads.unshift('face');
6244
+ if (fallback.has('front hair')) heads.push('front hair');
6245
+ const headRun = (t: string): Run => fallback.has(t) ? 'full' : 'head';
6198
6246
  const hw = body.filter((t) => t.startsWith('handwear'));
6199
6247
  const plan: PlanEntry[] = [];
6200
6248
  const drop = (t: string): void => {
@@ -6202,7 +6250,7 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6202
6250
  if (i >= 0) heads.splice(i, 1);
6203
6251
  };
6204
6252
  if (heads.includes('back hair')) {
6205
- plan.push([PROPOSE_ALIAS['back hair'], 'head', 'back hair']);
6253
+ plan.push([PROPOSE_ALIAS['back hair'], headRun('back hair'), 'back hair']);
6206
6254
  drop('back hair');
6207
6255
  }
6208
6256
  let neckDone = !heads.includes('neck');
@@ -6217,6 +6265,20 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6217
6265
  const notes: string[] = [...mergedSplit.notes, ...(headFacePrep.underfillNote === null ? [] : [headFacePrep.underfillNote])];
6218
6266
  const headArea = (frame.headK * frame.S) ** 2;
6219
6267
  const fullArea = (frame.fullK * frame.S) ** 2;
6268
+ for (const t of HEAD_FALLBACK_TAGS) {
6269
+ if (!fallback.has(t)) continue;
6270
+ const hl = find('head', t);
6271
+ const hp = (hl?.opaqueRunPx ?? 0) * headArea;
6272
+ const fp = (find('full', t)?.opaqueRunPx ?? 0) * fullArea;
6273
+ const f = figures.head.find(l => l.name === t);
6274
+ const reason = t === 'face' && headFaceRefusal !== null
6275
+ ? `${headFaceRefusal.code}: ${headFaceRefusal.detail}`
6276
+ : hl === undefined ? 'missing layer'
6277
+ : hl.opaqueRunPx < minPx ? `${hl.opaqueRunPx} run px below ${minPx} (PROPOSE_MIN_PX)`
6278
+ : (f === undefined ? [] : implausibleRules(f)).join(', ');
6279
+ const draw = t === 'back hair' ? 'behind the body and face' : t === 'face' ? 'before head details and front hair' : 'in front of the face';
6280
+ notes.push(`${t}: head run ${fmt0(hp)} rig px (${reason}); full run ${fmt0(fp)} rig px -> full-run layer, drawn ${draw}`);
6281
+ }
6220
6282
  for (const t of ['headwear', 'earwear']) {
6221
6283
  const hl = find('head', t);
6222
6284
  const fl = find('full', t);
@@ -6229,7 +6291,7 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6229
6291
  notes.push(`${t}: head run ${fmt0(hp)} rig px < 0.8 x full run ${fmt0(fp)} -> full-run layer, drawn behind the face`);
6230
6292
  }
6231
6293
  }
6232
- for (const t of heads) plan.push([aliasOf(t), 'head', t]);
6294
+ for (const t of heads) plan.push([aliasOf(t), headRun(t), t]);
6233
6295
  for (const [part, run, tag] of plan) {
6234
6296
  if (readAuthorTag(tag) !== null) notes.push(`${tag}: ${AUTHOR_NO_ROLE}; proposed as "${part}" from the ${run} run, at its place in that run's draw order`);
6235
6297
  }
@@ -6373,7 +6435,7 @@ function unplannedNotes(
6373
6435
  if (l === undefined) return `${run} run: no layer`;
6374
6436
  const px = `${run} run: ${l.opaqueRunPx} px`;
6375
6437
  const headTag = PROPOSE_HEAD_TAGS.includes(tag);
6376
- const fallback = tag === 'headwear' || tag === 'earwear';
6438
+ const fallback = tag === 'headwear' || tag === 'earwear' || HEAD_FALLBACK_TAGS.includes(tag);
6377
6439
  if (run === 'full' && headTag && !fallback) return `${px}, but the proposer takes ${tag} from the head run only (PROPOSE_HEAD_TAGS, src/assemble.ts)`;
6378
6440
  if (run === 'head' && !headTag && readAuthorTag(tag) === null) return `${px}, but the proposer takes ${tag} from the full run only (it is not one of PROPOSE_HEAD_TAGS, src/assemble.ts)`;
6379
6441
  if (l.opaqueRunPx < minPx) return `${px}, empty: below ${floor}`;
@@ -6381,6 +6443,7 @@ function unplannedNotes(
6381
6443
  const f = figures[run].find((x) => x.name === tag) as LayerFigures;
6382
6444
  return `${px}, crosses ${implausibleRules(f).join(', ')} (named with its figures in the note below)`;
6383
6445
  }
6446
+ if (run === 'full' && HEAD_FALLBACK_TAGS.includes(tag)) return `${px}, but the proposer retains a suitable head-run layer; full-run fallback requires a missing, below-floor or guard-refused head layer`;
6384
6447
  if (run === 'full' && fallback) {
6385
6448
  return `${px}, but the proposer takes ${tag} from the full run only when the head run's is below 0.8 of it in rig px (head run ${fmt0(rigPx('head', tag))}, full run ${fmt0(rigPx('full', tag))})`;
6386
6449
  }
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { applyTakenLayers } from './takelayers.ts';
1
2
  import { ownershipLines, provenanceLines } from './provenance.ts';
2
3
  import { readSourceDepth } from './depthsheets.ts';
3
4
  import { orderedBaseAnchor } from './baseanchor.ts';
@@ -320,7 +321,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
320
321
  // regions and motion, so it requires only what it reads (issue #20).
321
322
  const cfg = loadEarlyConfig(input.config, 'assemble');
322
323
  const src = readSource(input.source);
323
- const runs = readRuns(input.full, input.head);
324
+ const runs = applyTakenLayers(readRuns(input.full, input.head), src, cfg, input.config);
325
+ for (const note of runs.notes) log(`note: ${note}`);
324
326
  const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
325
327
  const under = readUnders(input.config, fields.cuts);
326
328
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
package/src/config.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { TakeLayers } from './takelayers.ts';
1
2
  import { paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
2
3
  import { baseAnchorProblems, type BaseAnchor } from './baseanchor.ts';
3
4
  import type { DepthConfig } from './depthsheets.ts';
@@ -299,6 +300,8 @@ export interface AlternateSetConfig {
299
300
  }
300
301
 
301
302
  export interface Assemble {
303
+ /** Verified named replacements from another See-through run (#866). */
304
+ take?: TakeLayers[];
302
305
  /** Rig pixels per source pixel. */
303
306
  rig_scale: number;
304
307
  plan: PlanEntry[];
@@ -1619,7 +1622,7 @@ export interface EarlyConfig {
1619
1622
  depth?: DepthConfig;
1620
1623
  key: string;
1621
1624
  seethrough: SeeThrough;
1622
- assemble: { rig_scale: number; head_face_underfill?: boolean; yield_refused?: boolean; keep_under_occluders?: string[]; extend_painting?: PaintingExtension[] };
1625
+ assemble: { rig_scale: number; take?: TakeLayers[]; head_face_underfill?: boolean; yield_refused?: boolean; keep_under_occluders?: string[]; extend_painting?: PaintingExtension[] };
1623
1626
  }
1624
1627
 
1625
1628
  /** What plain `assemble` reads: the early config plus the plan `--propose-plan` printed. */
@@ -1688,7 +1691,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1688
1691
  if (door === 'layers') {
1689
1692
  if ('seethrough' in t) checkSeeThrough(c, t.seethrough);
1690
1693
  if ('assemble' in t) {
1691
- const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting']);
1694
+ const a = c.object('config.assemble', t.assemble, sectionRequired(door, 'assemble'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take']);
1692
1695
  if (a !== null) {
1693
1696
  if ('rig_scale' in a) c.number('config.assemble.rig_scale', a.rig_scale, 'positive');
1694
1697
  if ('head_face_underfill' in a && typeof a.head_face_underfill !== 'boolean') {
@@ -1696,6 +1699,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1696
1699
  }
1697
1700
  checkKeepUnderOccluders(c, a, null);
1698
1701
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
1702
+ if ('take' in a) checkTakeLayers(c, a.take);
1699
1703
  if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
1700
1704
  c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
1701
1705
  }
@@ -2433,9 +2437,29 @@ function checkKeepUnderOccluders(c: Check, a: Record<string, Json>, plan: readon
2433
2437
  });
2434
2438
  }
2435
2439
 
2440
+ function checkTakeLayers(c: Check, value: Json): void {
2441
+ const at = 'config.assemble.take';
2442
+ if (!c.array(at, value, false)) return;
2443
+ const seen = new Set<string>();
2444
+ (value as Json[]).forEach((v, i) => {
2445
+ const p = `${at}[${i}]`, o = c.object(p, v, ['run', 'run_dir', 'st_input', 'tags'], []);
2446
+ if (o === null) return;
2447
+ if (o.run !== 'full' && o.run !== 'head') c.fail('CONFIG_FIELD_TYPE', p + '.run', '"full" or "head" is required');
2448
+ for (const k of ['run_dir', 'st_input']) c.string(`${p}.${k}`, o[k]);
2449
+ if (!c.array(p + '.tags', o.tags, true)) return;
2450
+ (o.tags as Json[]).forEach((tag, j) => {
2451
+ const reading = typeof tag === 'string' ? readLayerTag(tag) : null;
2452
+ if (reading === null || reading.group === 'author') c.fail('CONFIG_TAG_KNOWN', `${p}.tags[${j}]`, 'a See-through tag is required; author layers do not carry a See-through role');
2453
+ const key = `${String(o.run)}:${String(tag)}`;
2454
+ if (seen.has(key)) c.fail('CONFIG_TAKE_UNIQUE', `${p}.tags[${j}]`, `names ${key} again; one donor per target tag is required`);
2455
+ seen.add(key);
2456
+ });
2457
+ });
2458
+ }
2459
+
2436
2460
  function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: string[]; patches: string[]; cuts: string[] } {
2437
2461
  const required = sectionRequired(door, 'assemble');
2438
- const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting']);
2462
+ const a = c.object('config.assemble', v, required.filter((k) => k !== 'plan'), ['plan', 'extend_below_crop', 'patches', 'cuts', 'alternates', 'head_face_underfill', 'yield_refused', 'keep_under_occluders', 'extend_painting', 'take']);
2439
2463
  if (a === null) return { parts: [], patches: [], cuts: [] };
2440
2464
  if (required.includes('plan') && !('plan' in a)) {
2441
2465
  c.fail('CONFIG_FIELD_PRESENT', 'config.assemble.plan', 'is absent and required; `assemble --propose-plan` prints one from the two runs — paste its plan and extend_below_crop into config.assemble');
@@ -2471,6 +2495,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2471
2495
  }
2472
2496
  checkKeepUnderOccluders(c, a, parts);
2473
2497
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
2498
+ if ('take' in a) checkTakeLayers(c, a.take);
2474
2499
  if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
2475
2500
  (a.extend_below_crop as Json[]).forEach((entry, i) => {
2476
2501
  const at = `${p}.extend_below_crop[${i}]`;
package/src/layers.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { TakenLayerSource } from './takesource.ts';
1
2
  /**
2
3
  * The input contract: one See-through decomposition as a `LayerSet`.
3
4
  *
@@ -53,6 +54,8 @@ export const CORE_ALPHA = 250;
53
54
  export const NEAR_WHITE_MIN = 235;
54
55
 
55
56
  export interface Layer {
57
+ /** Verified donor identities retained through generated splits. */
58
+ takenLayers?: TakenLayerSource[];
56
59
  /** As the input names it: a v3 tag, possibly with a `-r`/`-l` side, or an author-made layer's `author:<label>`. */
57
60
  name: string;
58
61
  tag: LayerTagReading;
package/src/parts.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { takenSourceProblems, type TakenLayerSource } from './takesource.ts';
1
2
  import { AUTOMATIC_WRITERS, provenanceAddsUp, type PixelProvenance, type CutOwnership } from './provenance.ts';
2
3
  import { baseAnchorProblems, orderedBaseAnchor, type BaseAnchor } from './baseanchor.ts';
3
4
  import { partDepthProblems, type PartDepthReference } from './depthsheets.ts';
@@ -97,6 +98,8 @@ import { edgeLength } from './length.ts';
97
98
  import { recordedFocusProblems } from './setfocus.ts';
98
99
 
99
100
  export interface PartRecord {
101
+ /** Verified donor sources, including sources of cuts, limbs and extensions. */
102
+ taken_layers?: TakenLayerSource[];
100
103
  /** Report-only final last-writer census (#817); absent on older records. */
101
104
  provenance?: PixelProvenance;
102
105
  /** Painting ownership gained by #848, independent of final raw-value equality. */
@@ -426,6 +429,7 @@ export const PART_KEYS = [
426
429
  'name',
427
430
  'from',
428
431
  'cut_from',
432
+ 'taken_layers',
429
433
  'x',
430
434
  'y',
431
435
  'w',
@@ -451,10 +455,10 @@ const FRINGE_KEY = 'fringe_pushed_back';
451
455
  const CUT_FROM_KEY = 'cut_from';
452
456
  /** The one part field that is a record of its own: a limb segment's provenance (issue #349), written only on one. */
453
457
  const LIMB_KEY = 'limb';
454
- const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance') as ReadonlyArray<(typeof PART_KEYS)[number]>;
458
+ const COUNT_KEYS = PART_KEYS.slice(2).filter((k) => k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers') as ReadonlyArray<(typeof PART_KEYS)[number]>;
455
459
  /** The port's own counts: all three or none (none = a record the reference wrote). */
456
460
  export const VISIBILITY_KEYS = ['visible_px', 'occluded_px', 'visible_not_projected_px'] as const;
457
- const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance');
461
+ const REQUIRED_KEYS = PART_KEYS.filter((k) => k !== 'painting_extension_px' && !(VISIBILITY_KEYS as readonly string[]).includes(k) && k !== FRINGE_KEY && k !== CUT_FROM_KEY && k !== LIMB_KEY && k !== 'depth' && k !== 'provenance' && k !== 'taken_layers');
458
462
 
459
463
  /** Where a part came from: a See-through run and a v3 tag or an author-made layer's `author:<label>` (issue #256), or the painting itself for a patch. */
460
464
  export type From = { run: 'full' | 'head'; tag: string } | { run: 'painting'; patch: string };
@@ -504,7 +508,7 @@ function orderedProvenance(p: PixelProvenance): PixelProvenance {
504
508
 
505
509
  function serializePartList(parts: readonly PartRecord[]): Array<Record<string, unknown>> {
506
510
  return parts.map((p) =>
507
- Object.fromEntries(PART_KEYS.filter((k) => p[k] !== undefined).map((k) => [k, k === FRINGE_KEY ? (p.fringe_pushed_back ?? []).map((q) => ({ part: q.part, px: q.px })) : k === LIMB_KEY ? orderedLimb(p.limb as LimbRecord) : k === 'provenance' ? orderedProvenance(p.provenance as PixelProvenance) : p[k]])),
511
+ Object.fromEntries(PART_KEYS.filter((k) => p[k] !== undefined).map((k) => [k, k === FRINGE_KEY ? (p.fringe_pushed_back ?? []).map((q) => ({ part: q.part, px: q.px })) : k === LIMB_KEY ? orderedLimb(p.limb as LimbRecord) : k === 'taken_layers' ? p.taken_layers?.map(t => ({ run: t.run, tag: t.tag, run_dir: t.run_dir, st_input: t.st_input, prompt_id: t.prompt_id, seed: t.seed, support_px: t.support_px, checked_px: t.checked_px, differing_px: t.differing_px })) : k === 'provenance' ? orderedProvenance(p.provenance as PixelProvenance) : p[k]])),
508
512
  );
509
513
  }
510
514
 
@@ -649,6 +653,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
649
653
  return;
650
654
  }
651
655
  const r = p as Record<string, unknown>;
656
+ if ('taken_layers' in r) problems.push(...takenSourceProblems(r.taken_layers, `${at}.taken_layers`));
652
657
  if ('depth' in r) problems.push(...partDepthProblems(r.depth, `${path} part depth`));
653
658
  const label = typeof r.name === 'string' ? `part "${r.name}"` : at;
654
659
  for (const k of Object.keys(r)) if (!(PART_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${label} key "${k}"`, `is not a part field; known: ${PART_KEYS.join(', ')}`);
@@ -0,0 +1,110 @@
1
+ /** Verified replacement in an existing full/head run; never writes or forges a run manifest. */
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, resolve } from 'node:path';
4
+ import type { EarlyConfig, PlanEntry, Run } from './config.ts';
5
+ import { CORE_KERNEL } from './assemble.ts';
6
+ import { makeInputs } from './inputs.ts';
7
+ import { OPAQUE_ALPHA_ABOVE, readLayers, type Layer, type LayerSet } from './layers.ts';
8
+ import { PartsError, refuseIfAny, type Problem } from './errors.ts';
9
+ import { dilate } from './raster/morph.ts';
10
+ import { newMask, type Raster } from './raster/types.ts';
11
+ import { readPng } from './raster/png.ts';
12
+ import type { TakenLayerSource } from './takesource.ts';
13
+
14
+ export interface TakeLayers {
15
+ run: Run;
16
+ run_dir: string;
17
+ /** The exact PNG supplied to See-through, resolved from the config directory. */
18
+ st_input: string;
19
+ tags: string[];
20
+ }
21
+ function refuse(code: string, object: string, detail: string): never { throw new PartsError([{ code, object, detail }]); }
22
+ function metadata(path: string): { prompt_id: string; seed: number } {
23
+ let value: unknown;
24
+ try { value = JSON.parse(readFileSync(path, 'utf8')); } catch { return refuse('ASSEMBLE_TAKE_META', path, 'a readable meta.json with prompt_id and seed from the donor run is required'); }
25
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return refuse('ASSEMBLE_TAKE_META', path, 'a metadata object with prompt_id and seed is required');
26
+ const o = value as Record<string, unknown>;
27
+ if (typeof o.prompt_id !== 'string' || !o.prompt_id.trim() || !Number.isSafeInteger(o.seed) || (o.seed as number) < 0) return refuse('ASSEMBLE_TAKE_META', path, 'a nonempty prompt_id and nonnegative safe integer seed are required; neither is invented');
28
+ return { prompt_id: o.prompt_id, seed: o.seed as number };
29
+ }
30
+ function identity(layer: Layer, canvas: LayerSet['canvas'], donor: Raster, target: Raster, object: string): { support: number; checked: Uint8Array } {
31
+ const mask = newMask(canvas.w, canvas.h); let support = 0;
32
+ for (let y = 0; y < layer.pixels.height; y++) for (let x = 0; x < layer.pixels.width; x++) if (layer.pixels.data[(y * layer.pixels.width + x) * 4 + 3] > OPAQUE_ALPHA_ABOVE) {
33
+ mask.data[(layer.top + y) * canvas.w + layer.left + x] = 1; support++;
34
+ }
35
+ if (support === 0) return refuse('ASSEMBLE_TAKE_SUPPORT', object, `has 0 pixels of alpha above ${OPAQUE_ALPHA_ABOVE}; a nonempty taken layer is required`);
36
+ const grown = dilate(mask, CORE_KERNEL, CORE_KERNEL);
37
+ const checked = new Uint8Array(target.width * target.height);
38
+ // A run pixel is a cell on st_input, not a sample that can be rounded to a
39
+ // neighbouring centre. Compare EVERY intersecting input cell before any resize.
40
+ for (let y = 0; y < canvas.h; y++) for (let x = 0; x < canvas.w; x++) if (grown.data[y * canvas.w + x] === 1) {
41
+ for (let iy = Math.floor(y * target.height / canvas.h); iy < Math.ceil((y + 1) * target.height / canvas.h); iy++)
42
+ for (let ix = Math.floor(x * target.width / canvas.w); ix < Math.ceil((x + 1) * target.width / canvas.w); ix++) checked[iy * target.width + ix] = 1;
43
+ }
44
+ let differing = 0, x0 = target.width, y0 = target.height, x1 = 0, y1 = 0;
45
+ for (let p = 0; p < checked.length; p++) if (checked[p] === 1 && [0, 1, 2, 3].some(c => donor.data[p * 4 + c] !== target.data[p * 4 + c])) {
46
+ differing++; const x = p % target.width, y = Math.floor(p / target.width); x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x + 1); y1 = Math.max(y1, y + 1);
47
+ }
48
+ if (differing > 0) return refuse('ASSEMBLE_TAKE_INPUT_IDENTITY', object, `${differing} differing pixel(s), bbox [${x0}, ${y0}, ${x1}, ${y1}] in st_input pixels (right/bottom exclusive); exact RGBA identity under alpha > ${OPAQUE_ALPHA_ABOVE}, grown by ${CORE_KERNEL}x${CORE_KERNEL}, is required`);
49
+ return { support, checked };
50
+ }
51
+ export function takeLayerNote(source: TakenLayerSource): string {
52
+ return `take ${source.run}:${source.tag} from ${source.run_dir}; prompt_id ${source.prompt_id}; seed ${source.seed}; st_input ${source.st_input}; support ${source.support_px} run px; checked ${source.checked_px} input px; differing ${source.differing_px}; alpha > ${OPAQUE_ALPHA_ABOVE}, ${CORE_KERNEL}x${CORE_KERNEL} margin`;
53
+ }
54
+ /** Apply every declaration together, so replacing all tied layers from one run can retain its known order. */
55
+ export function applyTakenLayers(runs: { full: LayerSet; head: LayerSet; single: boolean }, painting: Raster, cfg: Pick<EarlyConfig, 'seethrough' | 'depth'> & { assemble: { take?: TakeLayers[]; plan?: PlanEntry[] } }, configPath: string): { full: LayerSet; head: LayerSet; single: boolean; notes: string[] } {
56
+ const declarations = cfg.assemble.take ?? [];
57
+ if (declarations.length === 0) return { ...runs, notes: [] };
58
+ if (cfg.depth !== undefined || [...runs.full.layers, ...runs.head.layers].some(l => l.depthSheet !== undefined)) return refuse('ASSEMBLE_TAKE_DEPTH_SHEET', 'config.assemble.take', 'active scalar depth sheets have no mixed-run binding; disable the depth opt-in or assemble a separately bound run before taking layers (numeric depth_median ordering is retained)');
59
+ const inputs = makeInputs(painting, cfg, 'take target painting');
60
+ const base = dirname(resolve(configPath));
61
+ const lists = { full: [...runs.full.layers], head: [...runs.head.layers] };
62
+ const origins = new Map<Layer, string>();
63
+ const notes: string[] = [], seen = new Set<string>();
64
+ for (const d of declarations) {
65
+ const at = `config.assemble.take run "${d.run_dir}" (${d.run})`;
66
+ if (d.run === 'head' && runs.single) return refuse('ASSEMBLE_TAKE_GEOMETRY', at, 'there is no --head run; choose full or supply a head run');
67
+ const target = d.run === 'head' ? inputs.head : runs.single && (runs.full.canvas.w !== runs.full.canvas.h) ? painting : inputs.full;
68
+ const set = runs[d.run];
69
+ const donor = readLayers(resolve(base, d.run_dir));
70
+ const meta = metadata(resolve(base, d.run_dir, 'meta.json'));
71
+ let image: Raster;
72
+ try { image = readPng(resolve(base, d.st_input)); } catch { return refuse('ASSEMBLE_TAKE_INPUT', at, `st_input "${d.st_input}" must name the original readable PNG supplied to the donor run`); }
73
+ if (target === null || donor.canvas.w !== set.canvas.w || donor.canvas.h !== set.canvas.h || image.width !== target.width || image.height !== target.height) return refuse('ASSEMBLE_TAKE_GEOMETRY', at, `donor canvas ${donor.canvas.w}x${donor.canvas.h}, target canvas ${set.canvas.w}x${set.canvas.h}, donor st_input ${image.width}x${image.height}, target st_input ${target?.width ?? 0}x${target?.height ?? 0}; equal canvases and equal input dimensions are required (full uses squarePad; head uses head_box)`);
74
+ const union = new Uint8Array(image.width * image.height);
75
+ for (const tag of d.tags) {
76
+ const key = `${d.run}:${tag}`;
77
+ if (seen.has(key)) return refuse('ASSEMBLE_TAKE_UNIQUE', at, `tag "${tag}" replaces ${key} twice; declare one donor per target tag`);
78
+ seen.add(key);
79
+ const layer = donor.layers.find(l => l.name === tag);
80
+ if (layer === undefined) return refuse('ASSEMBLE_TAKE_TAG_IN_RUN', at, `tag "${tag}" is absent; a named See-through tag held by that donor is required`);
81
+ const checked = identity(layer, donor.canvas, image, target, `${at} tag "${tag}"`);
82
+ for (let p = 0; p < union.length; p++) union[p] |= checked.checked[p];
83
+ const source: TakenLayerSource = { run: d.run, tag, run_dir: d.run_dir, st_input: d.st_input, prompt_id: meta.prompt_id, seed: meta.seed, support_px: checked.support, checked_px: checked.checked.reduce((a, b) => a + b, 0), differing_px: 0 };
84
+ const replacement: Layer = { ...layer, takenLayers: [source] };
85
+ lists[d.run] = [...lists[d.run].filter(l => l.name !== tag), replacement];
86
+ origins.set(replacement, resolve(base, d.run_dir));
87
+ notes.push(takeLayerNote(source));
88
+ }
89
+ notes.push(`take union ${d.run} from ${d.run_dir}: checked ${union.reduce((a, b) => a + b, 0)} input px; differing 0`);
90
+ }
91
+ for (const run of ['full', 'head'] as const) {
92
+ const list = lists[run], targetOrigin = resolve(dirname(runs[run].source));
93
+ const origin = (l: Layer): string => origins.get(l) ?? targetOrigin;
94
+ const problems: Problem[] = [];
95
+ for (let i = 0; i < list.length; i++) for (let j = i + 1; j < list.length; j++) if (origin(list[i]) !== origin(list[j]) && (list[i].depth === null || list[j].depth === null || list[i].depth === list[j].depth)) problems.push({ code: 'ASSEMBLE_TAKE_DEPTH_AMBIGUOUS', object: `${run}: "${list[i].name}" (${origin(list[i])}) / "${list[j].name}" (${origin(list[j])})`, detail: `depths ${list[i].depth} / ${list[j].depth}; distinct numeric depths across runs are required; manifest order resolves ties only inside the same run` });
96
+ refuseIfAny(problems);
97
+ list.sort((a, b) => a.depth === null || b.depth === null || a.depth === b.depth ? a.drawOrder - b.drawOrder : b.depth - a.depth);
98
+ lists[run] = list.map((l, drawOrder) => ({ ...l, drawOrder }));
99
+ const selected = (cfg.assemble.plan ?? []).filter(p => p[1] === run).map(p => ({ part: p[0], layer: list.find(l => l.name === p[2]) }));
100
+ for (let i = 0; i < selected.length; i++) for (let j = i + 1; j < selected.length; j++) {
101
+ const a = selected[i], b = selected[j];
102
+ if (a.layer !== undefined && b.layer !== undefined && origin(a.layer) !== origin(b.layer) && list.indexOf(a.layer) > list.indexOf(b.layer)) problems.push({ code: 'ASSEMBLE_TAKE_PLAN_ORDER', object: `${run} plan parts "${a.part}" / "${b.part}"`, detail: `plan order reverses mixed-run depths ${a.layer.depth} / ${b.layer.depth}; put the larger depth behind, as in assemble --propose-plan` });
103
+ }
104
+ refuseIfAny(problems);
105
+ const replaced = new Set(declarations.filter(d => d.run === run).flatMap(d => d.tags));
106
+ if (runs[run].hidden.some(l => replaced.has(l.of)) || declarations.some(d => d.run === run && readLayers(resolve(base, d.run_dir)).hidden.some(l => d.tags.includes(l.of)))) return refuse('ASSEMBLE_TAKE_HIDDEN', run, 'a replaced layer has hidden companion art; separate hidden provenance is not declared, so the combination is refused');
107
+ }
108
+ const full = { ...runs.full, layers: lists.full }, head = runs.single ? full : { ...runs.head, layers: lists.head };
109
+ return { full, head, single: runs.single, notes };
110
+ }
@@ -0,0 +1,43 @@
1
+ /** Layer identity receipts, retained independently of part names and derived geometry. */
2
+ import type { Problem } from './errors.ts';
3
+ import { readLayerTag } from './tags.ts';
4
+ export interface TakenLayerSource {
5
+ run: 'full' | 'head';
6
+ tag: string;
7
+ run_dir: string;
8
+ st_input: string;
9
+ prompt_id: string;
10
+ seed: number;
11
+ support_px: number;
12
+ checked_px: number;
13
+ differing_px: 0;
14
+ }
15
+ export function unionTakenSources(lists: readonly (readonly TakenLayerSource[] | undefined)[]): TakenLayerSource[] {
16
+ const out: TakenLayerSource[] = [];
17
+ for (const list of lists) for (const item of list ?? []) if (!out.some(p => p.run === item.run && p.tag === item.tag && p.run_dir === item.run_dir)) out.push(item);
18
+ return out;
19
+ }
20
+ /** Strict parts reader: unknown fields and partial or invented identity receipts are refused. */
21
+ export function takenSourceProblems(value: unknown, at: string): Problem[] {
22
+ const problems: Problem[] = [];
23
+ const fail = (detail: string): void => { problems.push({ code: 'PARTS_TAKEN_LAYERS', object: at, detail }); };
24
+ const keys = ['run', 'tag', 'run_dir', 'st_input', 'prompt_id', 'seed', 'support_px', 'checked_px', 'differing_px'];
25
+ if (!Array.isArray(value) || value.length === 0) { fail('a non-empty list of verified layer sources is required'); return problems; }
26
+ const seen = new Set<string>();
27
+ for (const item of value) {
28
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) { fail('each source must be a complete identity receipt'); continue; }
29
+ const o = item as Record<string, unknown>;
30
+ const tag = typeof o.tag === 'string' ? readLayerTag(o.tag) : null;
31
+ if (Object.keys(o).some(k => !keys.includes(k)) || keys.some(k => !(k in o)) ||
32
+ (o.run !== 'full' && o.run !== 'head') || tag === null || tag.group === 'author' ||
33
+ ['run_dir', 'st_input', 'prompt_id'].some(k => typeof o[k] !== 'string' || !(o[k] as string).trim()) ||
34
+ !Number.isSafeInteger(o.seed) || (o.seed as number) < 0 ||
35
+ ['support_px', 'checked_px'].some(k => !Number.isSafeInteger(o[k]) || (o[k] as number) <= 0) || o.differing_px !== 0) {
36
+ fail('each source requires exactly run, See-through tag, run_dir, st_input, prompt_id, nonnegative safe integer seed, positive support_px/checked_px and differing_px 0'); continue;
37
+ }
38
+ const key = JSON.stringify([o.run, o.tag, o.run_dir]);
39
+ if (seen.has(key)) fail(`duplicate source ${key}; each source must appear once`);
40
+ seen.add(key);
41
+ }
42
+ return problems;
43
+ }