spine-parts 2.23.4 → 2.25.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/docs/AUTHORING.md CHANGED
@@ -798,6 +798,44 @@ existing geometry refusal and its message.
798
798
  Region take entries accept the same optional `crop` and use this transport before
799
799
  selecting the seeded component on the target run canvas.
800
800
 
801
+ ### Source projection cover (`source_cover.json`, issue #1158)
802
+
803
+ Every assemble writes `source_cover.json` beside `parts.json`, under spec
804
+ `rig-parts-source-cover/1`. Its `sets` array contains the primary (`set: null`)
805
+ and every evaluated alternate, including empty readings. Reusing an output
806
+ replaces this single file, including its previous alternate inventory.
807
+
808
+ The stage is `source-projection-input`, after run preparation, ghost cleanup
809
+ and placement on the rig grid, before projection changes RGB. The predicate
810
+ counts a part's own alpha above 8 where another source owns the pixel at alpha
811
+ at least 250 and is in front. When both sources are planned, their plan ranks
812
+ settle front order. Otherwise the run's draw order does. Each `covered_by` row
813
+ names the owning source, whether it is planned, and `pixels.count` with sorted
814
+ native rig `[y, left, right-exclusive]` spans. A part's
815
+ `held_under_cover_px` counts own support protected by the keep mask separately,
816
+ so that support is excluded from scalar-owner rows.
817
+
818
+ Each set binds its painting and input manifests or PSDs by SHA-256, lists source
819
+ layers with depth, draw order, plan rank and planned/extend consumers, and names
820
+ input-layer identity, preparation and verified taken-layer provenance.
821
+ Generated layers without a same-name input entry have `input_layer: null`.
822
+ Unplanned sources remain listed even when they supply zero cover. An
823
+ extend-only source can be consumed while its plan rank remains -1.
824
+ `parts` describes the evaluated source plan, restricted to covered parts for
825
+ alternate sets. Source-only cut and limb dependencies remain in `sources`.
826
+ A covered derived cut or segment without its own layer row uses `source_of` to
827
+ name its parent's complete projection-input reading, before partitioning.
828
+ On the primary, a cut piece without its own layer is reported under its parent's row.
829
+ `output_assets` maps evaluated and inherited parts to exported image filenames,
830
+ with hidden or filtered assets mapped to null. `inherited_parts` references the
831
+ primary with `set: null`; inherited assets have no independently evaluated
832
+ alternate row. `hidden_parts` lists hidden assets.
833
+
834
+ Direct projection-input cover does not predict downstream changes. In
835
+ particular, an owner can suppress projection core eligibility while leaving a
836
+ part clear, and later merges, fringes and painting edges can change other
837
+ parts. This report observes the existing owner without changing assembly.
838
+
801
839
  ### Owner coverage transfers (`painting_allocation.json`, issue #1146)
802
840
 
803
841
  Under `assemble.project: "visible"`, assemble writes `painting_allocation.json`
@@ -8228,8 +8266,8 @@ Internal `SeamSupport.drawings` never enters check JSON. Named requirement
8228
8266
  | `SEAM_OVER_MOTION.worlds.*.rows` | `SEAM_OVER_MOTION.worlds.*.rows` | 'pair' | evidence | [want.a, want.b] | [check.ts:5288](../src/check.ts#L5288) |
8229
8267
  | `SEAM_OVER_RANGE.joints` | `SEAM_OVER_RANGE.joints` | 'part' | evidence; finding when poses.some(p => p.status === 'FAIL'); otherwise evidence | [j.part] | [check.ts:4335](../src/check.ts#L4335), [check.ts:4381](../src/check.ts#L4381) |
8230
8268
  | `SEAM_OVER_RANGE.joints[].poses` | `SEAM_OVER_RANGE.joints[].poses` | 'part' | finding when fail; otherwise evidence | [j.part] | [check.ts:4379](../src/check.ts#L4379) |
8231
- | `SETUP_MATCHES_PAINTING.regions` | `SETUP_MATCHES_PAINTING.regions` | 'rig' | finding when status === 'FAIL'; otherwise evidence | [] | [setuppainting.ts:174](../src/setuppainting.ts#L174) |
8232
- | `SETUP_MATCHES_PAINTING.regions[].slots` | `SETUP_MATCHES_PAINTING.regions[].slots` | part when the supplied mapping resolves a piece; otherwise rig | evidence | resolved piece for slot; otherwise [] | [setuppainting.ts:175](../src/setuppainting.ts#L175) |
8269
+ | `SETUP_MATCHES_PAINTING.regions` | `SETUP_MATCHES_PAINTING.regions` | 'rig' | finding when status === 'FAIL'; otherwise evidence | [] | [setuppainting.ts:175](../src/setuppainting.ts#L175) |
8270
+ | `SETUP_MATCHES_PAINTING.regions[].slots` | `SETUP_MATCHES_PAINTING.regions[].slots` | part when the supplied mapping resolves a piece; otherwise rig | evidence | resolved piece for slot; otherwise [] | [setuppainting.ts:176](../src/setuppainting.ts#L176) |
8233
8271
  | `STILL_REGIONS_DARK.*.crossing` | `STILL_REGIONS_DARK.*.crossing` | part when the supplied mapping resolves a piece; otherwise rig | finding | resolved piece for sl.name; otherwise [] | [check.ts:8910](../src/check.ts#L8910) |
8234
8272
  | `STILL_REGIONS_DARK.*.still_slots` | `STILL_REGIONS_DARK.*.still_slots` | part when the supplied mapping resolves a piece; otherwise rig | evidence; finding when r.max > tolerance; otherwise evidence | resolved piece for slot; otherwise [] | [check.ts:8896](../src/check.ts#L8896), [check.ts:8901](../src/check.ts#L8901) |
8235
8273
  | `STRESS_OFF_CHAIN.not_read` | `STRESS_OFF_CHAIN.not_read` | 'part' | evidence | [r.part] | [check.ts:3939](../src/check.ts#L3939) |
@@ -8292,3 +8330,16 @@ Here `sourceConfig` is the absolute original config filename and `raw` is its
8292
8330
  JSON-parsed object. Serialize that object at the destination after copying any
8293
8331
  referenced files; callers that copy files can instead set their new relative
8294
8332
  paths. The enumerator derives membership from the loader's own declarations.
8333
+
8334
+ `checkFileReferences(raw, configFile, requirements?)` and `CheckFileReference`
8335
+ are exported from the same `@rig-c/parts/src/config.ts` subpath (issue #1138).
8336
+ Pass the original config filename and the result of `readRequirements` from
8337
+ `@rig-c/parts/src/requirements.ts`. Rows contain `at` and `value`, with config
8338
+ references first and then `requirements.setup_painting.figure_mask.path` and
8339
+ `requirements.setup_painting.backdrop.path` when declared. Every value is
8340
+ resolved relative to the config directory, including images declared relative
8341
+ to the requirements file. Enumeration leaves both parsed inputs unchanged.
8342
+ Rig/parts-directory inputs (including seam PNGs) and separately supplied CLI
8343
+ inputs remain the caller's responsibility when relocating a check.
8344
+
8345
+ Programmatic consumers can enumerate declared assemble PNGs with `partsFileReferences` from `@rig-c/parts/src/parts.ts`, as specified in [STABILITY](STABILITY.md#programmatic-parts-file-references).
package/docs/STABILITY.md CHANGED
@@ -42,6 +42,51 @@ The loader's file-field declarations determine membership; no separate list is
42
42
  maintained. Resolve `value` against the source config directory when relocating.
43
43
  Existing deep package paths remain available.
44
44
 
45
+ The same subpath exports `checkFileReferences(raw: unknown, configFile: string,
46
+ requirements?: RequirementsFile): CheckFileReference[]` and the
47
+ `CheckFileReference` type (issue #1138). `requirements` is the value returned by
48
+ `readRequirements` from `@rig-c/parts/src/requirements.ts`. The result lists every
49
+ file `check` reads from a config and its requirements. Each row has `at: string`
50
+ (the dotted field) and `value: string` (the path relative to the config's
51
+ directory). Rows come in this order: the `configFileReferences` rows, then
52
+ `requirements.setup_painting.figure_mask.path` and
53
+ `requirements.setup_painting.backdrop.path` when they are declared. Setup images
54
+ resolve through the same code the check's readers use. Enumeration neither reads
55
+ files nor changes its inputs. Inputs that resolve from the rig or parts directory
56
+ (seam and `cut_material` part images, `cut_material_sources.json`) are not listed,
57
+ because the caller already carries that directory with the check.
58
+
59
+ ## Programmatic parts file references
60
+
61
+ `@rig-c/parts/src/parts.ts` exports `partsFileReferences(dir: string):
62
+ PartsFileReference[]` and the `PartsFileReference` type. `dir` holds the assemble
63
+ output's `parts.json`. Each row has `path: string`, relative to that directory,
64
+ and `role: 'part' | 'alternate' | 'depth' | 'painting' | 'figure_mask'`. The paths use `/`.
65
+ The complete output-reference fields and their roles are below.
66
+
67
+ | Field | Relative path | Role |
68
+ | --- | --- | --- |
69
+ | `parts[].name` | `parts/<name>.png` | `part` |
70
+ | `alternates[].name` with `records[].name` | `parts/<set>_<name>.png` | `alternate` |
71
+ | Base or alternate record `depth.image` | `parts/<depth.image>` | `depth` |
72
+ | `painting_in_rig.path` | Exactly `painting_in_rig.png` | `painting` |
73
+ | Base or alternate `scene.figure_mask` | Exactly `figure_rig.png` | `figure_mask` |
74
+
75
+ Painting and figure masks sit beside the manifest. Shared base/alternate scene
76
+ references collapse to one row. Depth source provenance filenames and
77
+ `taken_layers` donor directories/input names are historical identity receipts
78
+ and are omitted. There is no separate attachment field.
79
+ Rows are sorted by path, then role, in UTF-16 code-unit order, with duplicate path/role pairs
80
+ collapsed. A path with several roles retains each role. Every PNG that
81
+ parts.json references is listed. A listed file missing on disk is the consumer's
82
+ refusal. Unreferenced extras are outside the identity. Historical source
83
+ provenance is retained in the manifest and is outside the output-file identity. The function reads and validates
84
+ only the manifest, using the production readers' path resolvers. A missing manifest
85
+ refuses with `PARTS_FILE_PRESENT`, malformed JSON with `PARTS_IS_JSON`, and
86
+ invalid fields with the same named rules as `readParts`. It never opens,
87
+ hashes or decodes PNGs and preserves the manifest reader's named refusals.
88
+ Legacy manifests may omit alternates, depth and painting declarations.
89
+
45
90
  ## Commands and flags
46
91
 
47
92
  Exit codes are part of the interface: **0** the command did what it says, **1** it
@@ -272,6 +317,20 @@ every number) are AUTHORING §3's tables, and the loader refuses any other by na
272
317
 
273
318
  ## Files this package writes
274
319
 
320
+ ### Source cover report
321
+
322
+ `assemble` and the assemble stage of `build` always write `source_cover.json`
323
+ beside `parts.json`, with spec `rig-parts-source-cover/1`. `stage`, `predicate`
324
+ and `sets` declare projection-input cover. Each set includes its painting hash,
325
+ rig grid, hash-bound inputs, effective source inventory, evaluated part rows,
326
+ inherited primary references, hidden parts and output asset mappings. Cover
327
+ rows carry owning source identity, planned membership and native pixel counts
328
+ and spans. A derived alternate row's optional `source_of` names its parent
329
+ source-plan reading before partitioning. Held-under-cover support is separate.
330
+ Empty readings remain explicit.
331
+ The report measures direct cover before projection and downstream processing.
332
+ The field semantics are documented in AUTHORING's source projection cover entry.
333
+
275
334
  ### Head-crop preflight stdout
276
335
 
277
336
  `head-crop-preflight` writes one JSON object followed by a newline on success,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spine-parts",
3
- "version": "2.23.4",
3
+ "version": "2.25.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 { sourceCoverRun, type SourceCoverReading } from './sourcecover.ts';
1
2
  import { paintingReceivers, rawPaintingOwner } from './paintingowner.ts';
2
3
  import { hiddenExtentProblems, type HiddenExtentDeclaration, type HiddenExtentSource } from './hiddenextent.ts';
3
4
  import { headBoxInside } from './headbox.ts';
@@ -120,7 +121,7 @@ import { PartsError, type Problem, refuseIfAny } from './errors.ts';
120
121
  import { CORE_ALPHA, figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
121
122
  import { padToSquare, squarePad } from './inputs.ts';
122
123
  import type { MotionSeamDeclaration } from './motionseams.ts';
123
- import { type CapRecord, type LimbRecord, PAINTING_RUN, type PartRecord, type PartsFile, type RecompositeRecord, type SceneRecord, type SingleRunPad } from './parts.ts';
124
+ import { type CapRecord, type LimbRecord, FIGURE_MASK_FILE, PAINTING_RUN, type PartRecord, type PartsFile, type RecompositeRecord, type SceneRecord, type SingleRunPad } from './parts.ts';
124
125
  import { assignCrossedLimbs, assignOverlappingHands, type BonePlace, bonePlaces, capBox, coveredRadius, type CutPlacement, featherWeight, halfWidthAbout, inDisc, jointLine, type JointLine, jointOffsets, limbPolyline, limbRun, luma601, nearestLimb, nearestOnLine, offLineFigure, pastJoint, placeCut, polylineDist2, segmentOf } from './limbs.ts';
125
126
  import {
126
127
  alphaComposite,
@@ -2298,9 +2299,10 @@ export function pixelOwners(rigLayers: readonly Raster[], rank: readonly number[
2298
2299
  * masks mark own-layer art under a subset set's actual cover (alpha above 8);
2299
2300
  * those pixels are occluded, outside every projection core, and never recoloured.
2300
2301
  */
2301
- export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null, changed?: (layer: number, rigPixel: number) => void): ProjectionStats[] {
2302
+ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null, changed?: (layer: number, rigPixel: number) => void, observeOwners?: (owner: ArrayLike<number>) => void): ProjectionStats[] {
2302
2303
  const { W, H } = frame;
2303
2304
  const owner = pixelOwners(rigLayers, rank);
2305
+ observeOwners?.(owner);
2304
2306
  const inFront = (o: number, i: number): boolean => frontOf(o, i, rank);
2305
2307
  let win: Mask | null = null;
2306
2308
  if (run === 'head') {
@@ -3355,7 +3357,7 @@ export function measureRecomposite(can: Raster, srcr: Raster, parts: PlacedPart[
3355
3357
  }
3356
3358
 
3357
3359
  /** The figure mask's file name, beside the recomposite (issue #242): `recomposite_rig.png` -> `figure_rig.png`. */
3358
- export const FIGURE_MASK_FILE = 'figure_rig.png';
3360
+ export { FIGURE_MASK_FILE } from './parts.ts';
3359
3361
 
3360
3362
  /**
3361
3363
  * The figure of a scene painting (issue #242): per rig pixel, 1 where any
@@ -4725,6 +4727,8 @@ export function softOcclusionLine(r: SoftOcclusionReading): string {
4725
4727
  }
4726
4728
 
4727
4729
  export interface AssembleResult {
4730
+ /** Direct projection-input cover; separate from final output visibility. */
4731
+ sourceCover: SourceCoverReading;
4728
4732
  /** Compressed per-pixel classification, present only when requested. */
4729
4733
  stageMap?: StageMap;
4730
4734
  /** The already-resampled opaque painting used by this assembly. */
@@ -5097,6 +5101,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5097
5101
  const valueBaselines = new Map<string, ValueBaseline | null>();
5098
5102
  // Extend-only rasters are still projected/merged, but are never emitted as own sources.
5099
5103
  const readKeys = new Set(sourcePlan.map(([, run, tag]) => `${run}:${tag}`));
5104
+ const sourceCover: SourceCoverReading = { sources: [], parts: [] };
5100
5105
  const rig = new Map<string, Raster>();
5101
5106
  const stats = new Map<string, ProjectionStats>();
5102
5107
  const ghost: Record<string, number> = {};
@@ -5188,7 +5193,13 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5188
5193
  valueBaselines.set(key, raw === null ? null : compactValueBaseline(raw));
5189
5194
  return ids;
5190
5195
  });
5191
- const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep, (i, p) => { if (writes[i] !== null) (writes[i] as Int32Array)[p] = AW.sourceProjection; });
5196
+ const st = projectSource(rigLayers, srcr, frame, run, projectRule, rank, keep, (i, p) => { if (writes[i] !== null) (writes[i] as Int32Array)[p] = AW.sourceProjection; }, owners => {
5197
+ if (targets !== undefined && beforeTake === null) return;
5198
+ const reading = sourceCoverRun(run, set, run === 'full' ? fullPadded : depthHeadInput,
5199
+ rigLayers, rank, sourcePlan, extend, owners, (o, i) => frontOf(o, i, rank), keep);
5200
+ sourceCover.sources.push(...reading.sources);
5201
+ sourceCover.parts.push(...reading.parts);
5202
+ });
5192
5203
  writes.forEach((ids, i) => { if (ids !== null) layerWriters.set(`${run}:${layers[i].tag}`, ids); });
5193
5204
  writes.length = 0;
5194
5205
  layers.forEach((l, i) => {
@@ -6123,7 +6134,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6123
6134
  const supportSilhouette = opaqueSource && visibleFigure === undefined ? silhouette ?? figureSilhouette(srcr, supportPainted) : null;
6124
6135
  const supportFigure = visibleFigure ?? (supportSilhouette === null ? undefined : newMask(W, H));
6125
6136
  if (supportFigure !== undefined && supportSilhouette !== null) for (let p = 0; p < supportPainted.length; p++) supportFigure.data[p] = supportSilhouette.data[p] & supportPainted[p];
6137
+ sourceCover.parts.sort((a, b) => sourcePlan.findIndex(([name]) => name === a.part) - sourcePlan.findIndex(([name]) => name === b.part));
6126
6138
  return {
6139
+ sourceCover,
6127
6140
  ...(softOcclusion.length === 0 ? {} : { softOcclusion }),
6128
6141
  ...(!single ? { cropClipped: cropClippedLines(plan, extend, (run, tag) => rig.get(`${run}:${tag}`) ?? null, frame) } : {}),
6129
6142
  paintingInRig: srcr,
package/src/build.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { SOURCE_COVER_FILE, sourceCoverReport, type SourceCoverSet } from './sourcecover.ts';
1
2
  import { STAGE_MAP_FILE } from './provenance.ts';
2
3
  import { withoutCheckRows } from './checkrow.ts';
3
4
  import { readSetupFigureMask } from './setupfiguremask.ts';
@@ -63,7 +64,7 @@ import { setFocusProblems } from './setfocus.ts';
63
64
  */
64
65
  import { createHash } from 'node:crypto';
65
66
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
66
- import { basename, dirname, join, resolve } from 'node:path';
67
+ import { basename, dirname, join, relative, resolve, sep } from 'node:path';
67
68
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
68
69
  import { assemble, type AssembleResult, cutLines, 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 } from './assemble.ts';
69
70
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
@@ -103,7 +104,7 @@ import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
103
104
  import type { PaletteError } from './palette.ts';
104
105
  import { type LayerSet, readLayers } from './layers.ts';
105
106
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
106
- import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type PartRecord, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
107
+ import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type PartRecord, partImageReference, depthImageReference, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
107
108
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
108
109
  import type { Raster } from './raster/types.ts';
109
110
  import { type Mask, newMask } from './raster/types.ts';
@@ -337,6 +338,23 @@ export function frontOrdered<T extends { record: { name: string } }>(items: read
337
338
  return out;
338
339
  }
339
340
 
341
+ /** Bind the pure owner reading to the exact stage inputs. */
342
+ function sourceCoverSet(result: AssembleResult, set: string | null, painting: string,
343
+ runs: ReturnType<typeof readRuns>): SourceCoverSet {
344
+ const inputs: SourceCoverSet['inputs'] = [];
345
+ for (const run of (runs.single ? ['full'] : ['full', 'head']) as Array<'full' | 'head'>) {
346
+ const layers = runs[run];
347
+ inputs.push({ run, file: basename(layers.source),
348
+ sha256: createHash('sha256').update(readFileSync(layers.source)).digest('hex'),
349
+ layers: layers.layers.map(layer => ({ layer: layer.name,
350
+ image: layer.file === null ? null : relative(dirname(layers.source), layer.file).split(sep).join('/') })) });
351
+ }
352
+ return { set, painting_sha256: createHash('sha256').update(readFileSync(painting)).digest('hex'),
353
+ grid: result.parts.rig_size, inputs, ...result.sourceCover,
354
+ inherited_parts: [], hidden_parts: [],
355
+ output_assets: result.parts.parts.map(part => ({ part: part.name, image: `${part.name}.png` })) };
356
+ }
357
+
340
358
  /** Read, assemble, and write only after every refusal has had its chance. Throws a PartsError on a refusal, having written nothing. */
341
359
  export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log): AssembleResult {
342
360
  const requirementsFile = input.requirements === undefined ? null : readRequirements(input.requirements);
@@ -371,6 +389,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
371
389
  const result = assemble({ allocationEvent: input.allocationEvent === undefined ? undefined : event => input.allocationEvent!(event, null), source: src, full: runs.full, head: runs.head, depth: cfg.depth, depthBase: dirname(resolve(input.config)), ...fields, under, ...(declaredFigure === undefined ? {} : { declaredFigure }),
372
390
  ...((cfg.assemble.take ?? []).some(t => 'part' in t) ? { regionTake: { full: takenRuns.full, head: takenRuns.head, targets: (cfg.assemble.take ?? []).flatMap(t => 'part' in t ? [t.part] : []) } } : {}), ...(caps === undefined ? {} : { caps }), seamRule: seam, projectRule: project });
373
391
 
392
+ const sourceCoverSets = [sourceCoverSet(result, null, input.source, read)];
393
+
374
394
  // Issue #454: alternate painting sets, assembled before any file is written.
375
395
  const configDir = dirname(resolve(input.config));
376
396
  const cliAlts = input.alts ?? [];
@@ -776,6 +796,21 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
776
796
  const altCan = recomposite(fullSetPlaced, rW, rH);
777
797
  altRecomposite = recompositeRecord(measureRecomposite(altCan, altSrcRig, fullSetPlaced));
778
798
  }
799
+ const coverSet = sourceCoverSet(altRes, alt.name, alt.source, altRuns);
800
+ const sourceRows = altRes.sourceCover.parts;
801
+ coverSet.parts = keptRecords.flatMap(record => {
802
+ const direct = sourceRows.find(row => row.part === record.name);
803
+ if (direct !== undefined) return [direct];
804
+ const parent = record.cut_from ?? record.limb?.of;
805
+ const reading = sourceRows.find(row => row.part === parent);
806
+ return reading === undefined ? [] : [{ ...reading, part: record.name, source_of: reading.part }];
807
+ });
808
+ coverSet.inherited_parts = baseSlots.filter(name => !coveredSet.has(name) && !hidesSet.has(name)).map(part => ({ part, set: null }));
809
+ coverSet.hidden_parts = [...hidesSet];
810
+ coverSet.output_assets = [...new Set([...altRes.parts.parts.map(part => part.name), ...baseSlots])].map(name => ({ part: name,
811
+ image: hidesSet.has(name) ? null : keptRecords.some(record => record.name === name)
812
+ ? `${alt.name}_${name}.png` : !coveredSet.has(name) && baseSlots.includes(name) ? `${name}.png` : null }));
813
+ sourceCoverSets.push(coverSet);
779
814
  const alternateAllocation = altRes.paintingEdges?.allocation;
780
815
  if (alternateAllocation !== undefined) {
781
816
  allocationReports.push({
@@ -786,9 +821,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
786
821
  source: { painting_sha256: createHash('sha256').update(readFileSync(alt.source)).digest('hex') },
787
822
  stage: 'paintingEdges after piece guarding and restoration',
788
823
  membership: 'pre-filter-alternate-assembly',
789
- output_assets: [...new Set([...altRes.parts.parts.map(part => part.name), ...baseSlots])].map(name => ({ part: name,
790
- image: hidesSet.has(name) ? null : keptRecords.some(record => record.name === name)
791
- ? `${alt.name}_${name}.png` : !coveredSet.has(name) ? `${name}.png` : null })),
824
+ output_assets: coverSet.output_assets,
792
825
  inherited_parts: baseSlots.filter(name => !coveredSet.has(name) && !hidesSet.has(name)),
793
826
  hidden_parts: [...hidesSet],
794
827
  ...alternateAllocation,
@@ -847,6 +880,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
847
880
  const outputFiles = new Set([
848
881
  outs.partsJson, outs.recomposite, outs.errorMap,
849
882
  join(dirname(outs.partsJson), PAINTING_ALLOCATION_FILE),
883
+ join(dirname(outs.partsJson), SOURCE_COVER_FILE),
850
884
  join(dirname(outs.partsJson), PAINTING_IN_RIG_FILE),
851
885
  join(dirname(outs.partsJson), SUPPORT_DOMAINS_FILE),
852
886
  join(dirname(outs.partsJson), CUT_MATERIAL_SOURCES),
@@ -897,6 +931,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
897
931
  sha256: createHash('sha256').update(paintingBytes).digest('hex'), resample: 'lanczos3-rgb-opaque' };
898
932
  writeFileSync(join(dirname(outs.partsJson), PAINTING_IN_RIG_FILE), paintingBytes);
899
933
  writeParts(outs.partsJson, result.parts);
934
+ writeFileSync(join(dirname(outs.partsJson), SOURCE_COVER_FILE), JSON.stringify(sourceCoverReport(sourceCoverSets), null, 2) + '\n');
900
935
  const stageMapPath = join(dirname(outs.partsJson), STAGE_MAP_FILE);
901
936
  if (result.stageMap === undefined) rmSync(stageMapPath, { force: true });
902
937
  else writeFileSync(stageMapPath, JSON.stringify(result.stageMap) + '\n');
@@ -1591,16 +1626,16 @@ export function readRigInputs(config: string, partsDir: string): RigInputs {
1591
1626
  const images = new Map<string, Raster>();
1592
1627
  const depthProblems: Problem[] = [];
1593
1628
  for (const p of parts.parts) {
1594
- const png = join(partsDir, 'parts', `${p.name}.png`);
1629
+ const png = join(partsDir, partImageReference(p).path);
1595
1630
  if (existsSync(png)) images.set(p.name, readPng(png));
1596
- if (p.depth !== undefined && images.has(p.name)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, 'parts', p.depth.image), images.get(p.name) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1631
+ if (p.depth !== undefined && images.has(p.name)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, depthImageReference(p.depth).path), images.get(p.name) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1597
1632
  }
1598
1633
  for (const alt of parts.alternates ?? []) {
1599
1634
  for (const p of alt.records) {
1600
1635
  const attName = `${alt.name}_${p.name}`;
1601
- const png = join(partsDir, 'parts', `${attName}.png`);
1636
+ const png = join(partsDir, partImageReference(p, alt.name).path);
1602
1637
  if (existsSync(png)) images.set(attName, readPng(png));
1603
- if (p.depth !== undefined && images.has(attName)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, 'parts', p.depth.image), images.get(attName) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1638
+ if (p.depth !== undefined && images.has(attName)) { try { images.set(p.depth.image, readSourceDepth(join(partsDir, depthImageReference(p.depth).path), images.get(attName) as Raster, null).pixels); } catch (error) { if (error instanceof PartsError) depthProblems.push(...error.problems); else throw error; } }
1604
1639
  }
1605
1640
  }
1606
1641
  refuseIfAny(depthProblems);
@@ -2533,7 +2568,7 @@ export interface BuildRunners {
2533
2568
  }
2534
2569
 
2535
2570
  /** Every path `build` writes under `--out`, relative — and so every path it clears first. */
2536
- export const BUILD_OWNS: readonly string[] = ['parts', 'parts.json', PAINTING_IN_RIG_FILE, 'recomposite_rig.png', ERROR_MAP_FILE, 'rig', 'check', 'idle.gif', 'idle.png', 'idle-indexed.png'];
2571
+ export const BUILD_OWNS: readonly string[] = ['parts', 'parts.json', SOURCE_COVER_FILE, PAINTING_IN_RIG_FILE, 'recomposite_rig.png', ERROR_MAP_FILE, 'rig', 'check', 'idle.gif', 'idle.png', 'idle-indexed.png'];
2537
2572
 
2538
2573
  export type BuildStage = 'assemble' | 'rig' | 'check' | 'loop' | 'artifact';
2539
2574
 
package/src/config.ts CHANGED
@@ -92,11 +92,12 @@ import type { DepthConfig } from './depthsheets.ts';
92
92
  * the field is a non-empty string.
93
93
  */
94
94
  import { existsSync, readFileSync, statSync } from 'node:fs';
95
- import { dirname, resolve } from 'node:path';
95
+ import { dirname, relative, resolve } from 'node:path';
96
96
  import { RIG_BONE_INHERIT, RIG_SKIN_CONSTRAINT_KEYS, type RigBoneInherit, type RigConstraint, type RigSkinConstraintKey, type RigStop } from '@rig-c/core/rig';
97
97
  import { pyRound } from './round.ts';
98
98
  import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
99
- import { REQUIREMENTS_SPEC } from './requirements.ts';
99
+ import { REQUIREMENTS_SPEC, type RequirementsFile } from './requirements.ts';
100
+ import { setupPaintingFilePath } from './setuppainting.ts';
100
101
  import { CLOTH_TARGETS, type ClothRecipes, RECIPE_STRENGTH, RIGC_DEFAULT_DAMPING, springStable } from './cloth.ts';
101
102
  import { GRID, MAX_SIDE } from './contour.ts';
102
103
  import { type Problem, refuseIfAny } from './errors.ts';
@@ -1478,6 +1479,31 @@ export function configFileReferences(raw: unknown): ConfigFileReference[] {
1478
1479
  return out;
1479
1480
  }
1480
1481
 
1482
+ /** A declared check input, with its field and path relative to the config directory. */
1483
+ export interface CheckFileReference {
1484
+ at: string;
1485
+ value: string;
1486
+ }
1487
+
1488
+ /**
1489
+ * Config references followed by requirements-relative setup images. Pass the
1490
+ * real reader's RequirementsFile so its path identifies the declaration's base.
1491
+ * Rig/parts-directory inputs and separately supplied CLI inputs are not config
1492
+ * references. This function neither reads files nor changes the parsed inputs.
1493
+ */
1494
+ export function checkFileReferences(raw: unknown, configFile: string, requirements?: RequirementsFile): CheckFileReference[] {
1495
+ const base = dirname(resolve(configFile));
1496
+ const out = configFileReferences(raw).map(({ at, value }) => ({ at, value: relative(base, resolve(base, value)) }));
1497
+ const setup = requirements?.setup_painting;
1498
+ for (const key of ['figure_mask', 'backdrop'] as const) {
1499
+ const declared = setup?.[key];
1500
+ if (declared !== undefined && requirements !== undefined) {
1501
+ out.push({ at: `requirements.setup_painting.${key}.path`, value: relative(base, setupPaintingFilePath(requirements.path, declared.path)) });
1502
+ }
1503
+ }
1504
+ return out;
1505
+ }
1506
+
1481
1507
 
1482
1508
  class Check {
1483
1509
  readonly problems: Problem[] = [];
package/src/parts.ts CHANGED
@@ -369,6 +369,7 @@ export interface AlternatePartsRecord {
369
369
  registration?: { offset: [number, number]; scale: number };
370
370
  }
371
371
 
372
+ export const FIGURE_MASK_FILE = 'figure_rig.png';
372
373
  export const PAINTING_IN_RIG_FILE = 'painting_in_rig.png';
373
374
  export interface PaintingInRig {
374
375
  path: typeof PAINTING_IN_RIG_FILE;
@@ -600,7 +601,48 @@ export function writeParts(path: string, file: PartsFile): void {
600
601
  writeFileSync(path, text);
601
602
  }
602
603
 
603
- export function readParts(path: string): PartsFile {
604
+ /** A declared PNG path relative to the directory holding parts.json. */
605
+ export interface PartsFileReference {
606
+ path: string;
607
+ role: 'part' | 'alternate' | 'depth' | 'painting' | 'figure_mask';
608
+ }
609
+
610
+ /** Shared with the PNG readers, including their alternate attachment names. */
611
+ export function partImageReference(part: PartRecord, set?: string): PartsFileReference {
612
+ return { path: `parts/${set === undefined ? part.name : `${set}_${part.name}`}.png`, role: set === undefined ? 'part' : 'alternate' };
613
+ }
614
+
615
+ export function depthImageReference(depth: PartDepthReference): PartsFileReference {
616
+ return { path: `parts/${depth.image}`, role: 'depth' };
617
+ }
618
+
619
+ function paintingImageReference(painting: PaintingInRig): PartsFileReference {
620
+ return { path: painting.path, role: 'painting' };
621
+ }
622
+
623
+ /** Read the manifest without opening, hashing or decoding its PNG references. */
624
+ export function partsFileReferences(dir: string): PartsFileReference[] {
625
+ const file = readPartsManifest(join(dir, 'parts.json'));
626
+ const references: PartsFileReference[] = [];
627
+ const addScene = (scene: SceneRecord | undefined): void => {
628
+ if (scene !== undefined) references.push({ path: scene.figure_mask, role: 'figure_mask' });
629
+ };
630
+ addScene(file.scene);
631
+ if (file.painting_in_rig !== undefined) references.push(paintingImageReference(file.painting_in_rig));
632
+ const add = (part: PartRecord, set?: string): void => {
633
+ references.push(partImageReference(part, set));
634
+ if (part.depth !== undefined) references.push(depthImageReference(part.depth));
635
+ };
636
+ for (const part of file.parts) add(part);
637
+ for (const alternate of file.alternates ?? []) {
638
+ addScene(alternate.scene);
639
+ for (const part of alternate.records) add(part, alternate.name);
640
+ }
641
+ const unique = new Map(references.map(reference => [`${reference.path}\0${reference.role}`, reference]));
642
+ return [...unique.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : a.role < b.role ? -1 : a.role > b.role ? 1 : 0);
643
+ }
644
+
645
+ function readPartsManifest(path: string): PartsFile {
604
646
  if (!existsSync(path)) refuseIfAny([{ code: 'PARTS_FILE_PRESENT', object: path, detail: 'no such file; --parts names the directory holding parts.json and parts/ (work/rig from assemble --out work, or out from build --out out)' }]);
605
647
  let raw: unknown;
606
648
  try {
@@ -608,10 +650,14 @@ export function readParts(path: string): PartsFile {
608
650
  } catch (err) {
609
651
  refuseIfAny([{ code: 'PARTS_IS_JSON', object: path, detail: `does not parse as JSON: ${(err as Error).message}` }]);
610
652
  }
611
- const file = checkParts(raw, path);
653
+ return checkParts(raw, path);
654
+ }
655
+
656
+ export function readParts(path: string): PartsFile {
657
+ const file = readPartsManifest(path);
612
658
  const declared = file.painting_in_rig;
613
659
  if (declared !== undefined) {
614
- const imagePath = join(dirname(path), declared.path);
660
+ const imagePath = join(dirname(path), paintingImageReference(declared).path);
615
661
  const problems: Problem[] = [];
616
662
  const fail = (code: string, detail: string): void => { problems.push({ code, object: imagePath, detail }); };
617
663
  let bytes: Uint8Array | undefined;
@@ -641,6 +687,14 @@ function checkPaintingExtensionCount(r: Record<string, unknown>, label: string,
641
687
  else if (!Number.isSafeInteger(r.opaque_px) || (n as number) > (r.opaque_px as number)) fail('PARTS_COUNTS_ADD_UP', label + ' painting_extension_px', `is ${show(n)}; at most opaque_px ${show(r.opaque_px)} is required`);
642
688
  }
643
689
 
690
+ function checkFigureMask(value: unknown, object: string, fail: (code: string, object: string, detail: string) => void): void {
691
+ if (value !== FIGURE_MASK_FILE) fail('PARTS_FIELD_TYPE', object, `is ${show(value)}; exactly "${FIGURE_MASK_FILE}" is required`);
692
+ }
693
+
694
+ function isPartName(value: unknown): value is string {
695
+ return typeof value === 'string' && value !== '' && !/[\\/]/.test(value) && !value.startsWith('.');
696
+ }
697
+
644
698
  function show(v: unknown): string {
645
699
  return v === undefined ? 'absent' : JSON.stringify(v);
646
700
  }
@@ -740,7 +794,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
740
794
  if (held.length > 0 && held.length < VISIBILITY_KEYS.length) {
741
795
  fail('PARTS_FIELD_PRESENT', `${label} fields ${VISIBILITY_KEYS.map((k) => `"${k}"`).join(', ')}`, `only ${held.join(', ')} present; all three (assemble writes them) or none (the reference's record) is required`);
742
796
  }
743
- if (typeof r.name !== 'string' || r.name === '' || /[\\/]/.test(r.name) || r.name.startsWith('.')) {
797
+ if (!isPartName(r.name)) {
744
798
  fail('PARTS_FIELD_TYPE', `${label} field "name"`, `is ${show(r.name)}; a file-name-safe part name is required`);
745
799
  } else if (seen.has(r.name)) fail('PARTS_NAME_UNIQUE', label, `appears at parts[${seen.get(r.name)}] and parts[${i}]`);
746
800
  else seen.set(r.name, i);
@@ -842,7 +896,7 @@ function checkParts(raw: unknown, path: string): PartsFile {
842
896
  for (const k of Object.keys(r)) if (!(SCENE_KEYS as readonly string[]).includes(k)) fail('PARTS_KEY_KNOWN', `${path} scene key "${k}"`, `is not a scene field; known: ${SCENE_KEYS.join(', ')}`);
843
897
  for (const k of SCENE_KEYS) if (!(k in r)) fail('PARTS_FIELD_PRESENT', `${path} scene field "${k}"`, 'is absent and required');
844
898
  for (const k of ['figure_alpha_above', 'figure_px'] as const) if (k in r && !(Number.isInteger(r[k]) && (r[k] as number) >= 0)) fail('PARTS_FIELD_TYPE', `${path} scene field "${k}"`, `is ${show(r[k])}; a non-negative integer is required`);
845
- if ('figure_mask' in r && !(typeof r.figure_mask === 'string' && r.figure_mask !== '')) fail('PARTS_FIELD_TYPE', `${path} scene field "figure_mask"`, `is ${show(r.figure_mask)}; the mask's file name is required`);
899
+ if ('figure_mask' in r) checkFigureMask(r.figure_mask, `${path} scene field "figure_mask"`, fail);
846
900
  if (!('recomposite' in o)) fail('PARTS_FIELD_PRESENT', `${path} field "recomposite"`, 'is absent; a scene block says how the recomposite block beside it was measured, so it is required with one');
847
901
  }
848
902
  }
@@ -858,9 +912,19 @@ function checkParts(raw: unknown, path: string): PartsFile {
858
912
  if (Array.isArray(o.alternates)) {
859
913
  // Issue #620: a set record's cap is a cap, so it is held to the base records' rule; the object names the set and the part.
860
914
  o.alternates.forEach((a, i) => {
861
- if (typeof a !== 'object' || a === null || Array.isArray(a)) return;
915
+ if (typeof a !== 'object' || a === null || Array.isArray(a)) {
916
+ fail('PARTS_FIELD_TYPE', `${path} alternates[${i}]`, `is ${show(a)}; an alternate set object is required`);
917
+ return;
918
+ }
862
919
  const set = a as Record<string, unknown>;
863
920
  const at = `${path} alternates[${i}]${typeof set.name === 'string' ? ` (set "${set.name}")` : ''}`;
921
+ if (!isPartName(set.name)) fail('PARTS_FIELD_TYPE', `${at} field "name"`, `is ${show(set.name)}; a file-name-safe set name is required`);
922
+ if (!Array.isArray(set.records)) fail('PARTS_FIELD_TYPE', `${at} field "records"`, `is ${show(set.records)}; an array of alternate part records is required`);
923
+ if ('scene' in set) {
924
+ const scene = set.scene;
925
+ if (typeof scene !== 'object' || scene === null || Array.isArray(scene)) fail('PARTS_FIELD_TYPE', `${at} field "scene"`, `is ${show(scene)}; an object is required`);
926
+ else checkFigureMask((scene as Record<string, unknown>).figure_mask, `${at} scene field "figure_mask"`, fail);
927
+ }
864
928
  if ('cut_ownership' in set) checkOwnership(set.cut_ownership, `${at} cut_ownership`, fail);
865
929
  if ('base_anchor' in set) {
866
930
  const names = new Set(Array.isArray(set.records) ? set.records.flatMap(v => typeof v === 'object' && v !== null && typeof v.name === 'string' ? [v.name] : []) : []);
@@ -903,8 +967,14 @@ function checkParts(raw: unknown, path: string): PartsFile {
903
967
  if (!Array.isArray(set.records)) return;
904
968
  if (set.records.some((p) => typeof p === 'object' && p !== null && !Array.isArray(p) && typeof p.limb === 'object' && p.limb !== null && ('hybrid' in p.limb || 'band' in p.limb))) checkLimbRecords(set.records, `${at} `, fail, false);
905
969
  set.records.forEach((p, j) => {
906
- if (typeof p !== 'object' || p === null || Array.isArray(p)) return;
970
+ if (typeof p !== 'object' || p === null || Array.isArray(p)) {
971
+ fail('PARTS_FIELD_TYPE', `${at} records[${j}]`, `is ${show(p)}; a part object is required`);
972
+ return;
973
+ }
907
974
  const r = p as Record<string, unknown>;
975
+ const recordAt = `${at} records[${j}]`;
976
+ if (!isPartName(r.name)) fail('PARTS_FIELD_TYPE', `${recordAt} field "name"`, `is ${show(r.name)}; a file-name-safe part name is required`);
977
+ if ('depth' in r) problems.push(...partDepthProblems(r.depth, `${recordAt} depth`));
908
978
  const part817 = typeof r.name === 'string' ? `part "${r.name}"` : `records[${j}]`;
909
979
  if ('provenance' in r) checkProvenance(r.provenance, r.opaque_px, `${at} ${part817} provenance`, fail, 'depth' in r);
910
980
  checkPaintingExtensionCount(r, `${at} ${part817}`, fail);
package/src/propose.ts CHANGED
@@ -140,7 +140,7 @@ import { PartsError, type Problem, refuseIfAny } from './errors.ts';
140
140
  import { GRID } from './contour.ts';
141
141
  import { eyeLineDegrees, type FrameFeature, headAxes, type HeadAxes, headFrame, type HeadFrame } from './headframe.ts';
142
142
  import { type LayerSet, OPAQUE_ALPHA_ABOVE } from './layers.ts';
143
- import { PAINTING_RUN, type PartRecord, type PartsFile, readParts } from './parts.ts';
143
+ import { PAINTING_RUN, type PartRecord, type PartsFile, partImageReference, readParts } from './parts.ts';
144
144
  import { connectedComponents } from './raster/components.ts';
145
145
  import { dilate, morphGradient } from './raster/morph.ts';
146
146
  import { readPng } from './raster/png.ts';
@@ -922,7 +922,7 @@ export function readPartSet(dir: string): PartSet {
922
922
  const problems: Problem[] = [];
923
923
  const images = new Map<string, Raster>();
924
924
  for (const p of file.parts) {
925
- const png = join(dir, 'parts', `${p.name}.png`);
925
+ const png = join(dir, partImageReference(p).path);
926
926
  if (!existsSync(png)) {
927
927
  problems.push({ code: 'PROPOSE_PNG_PRESENT', object: `part "${p.name}"`, detail: `${png} does not exist; parts.json names it` });
928
928
  continue;
@@ -1,11 +1,10 @@
1
1
  /** Declared setup plate: hash the same bytes that are decoded, before builds. */
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFileSync } from 'node:fs';
4
- import { dirname, resolve } from 'node:path';
5
4
  import { refuseIfAny } from './errors.ts';
6
5
  import { decodePngBytes } from './raster/png.ts';
7
6
  import type { Raster } from './raster/types.ts';
8
- import type { SetupPainting } from './setuppainting.ts';
7
+ import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
9
8
 
10
9
  export function readSetupBackdrop(declared: SetupPainting, requirements: string, source: Raster | null): Raster | undefined {
11
10
  const plate = declared.backdrop;
@@ -15,7 +14,7 @@ export function readSetupBackdrop(declared: SetupPainting, requirements: string,
15
14
  throw new Error('unreachable');
16
15
  };
17
16
  let bytes: Uint8Array;
18
- try { bytes = new Uint8Array(readFileSync(resolve(dirname(requirements), plate.path))); }
17
+ try { bytes = new Uint8Array(readFileSync(setupPaintingFilePath(requirements, plate.path))); }
19
18
  catch { return fail(`cannot read declared PNG "${plate.path}"; requires the authored opaque backdrop, not a guessed colour`); }
20
19
  const hash = createHash('sha256').update(bytes).digest('hex');
21
20
  if (hash !== plate.sha256) return fail(`PNG "${plate.path}" has sha256 ${hash}; requires declared ${plate.sha256}`);
@@ -1,11 +1,10 @@
1
1
  /** Independent declared alpha support, verified before any candidate build. */
2
2
  import { createHash } from 'node:crypto';
3
3
  import { readFileSync } from 'node:fs';
4
- import { dirname, resolve } from 'node:path';
5
4
  import { refuseIfAny } from './errors.ts';
6
5
  import { decodePngBytes } from './raster/png.ts';
7
6
  import type { Raster } from './raster/types.ts';
8
- import type { SetupPainting } from './setuppainting.ts';
7
+ import { setupPaintingFilePath, type SetupPainting } from './setuppainting.ts';
9
8
 
10
9
  export function readSetupFigureMask(declared: SetupPainting, requirements: string, source: Raster | null, width: number, height: number): Uint8Array | undefined {
11
10
  const mask = declared.figure_mask;
@@ -15,7 +14,7 @@ export function readSetupFigureMask(declared: SetupPainting, requirements: strin
15
14
  throw new Error('unreachable');
16
15
  };
17
16
  let bytes: Uint8Array;
18
- try { bytes = new Uint8Array(readFileSync(resolve(dirname(requirements), mask.path))); }
17
+ try { bytes = new Uint8Array(readFileSync(setupPaintingFilePath(requirements, mask.path))); }
19
18
  catch { return fail(`cannot read declared PNG "${mask.path}"; requires independent figure alpha support`); }
20
19
  const hash = createHash('sha256').update(bytes).digest('hex');
21
20
  if (hash !== mask.sha256) return fail(`PNG "${mask.path}" has sha256 ${hash}; requires declared ${mask.sha256}`);
@@ -1,3 +1,4 @@
1
+ import { dirname, resolve } from 'node:path';
1
2
  import { checkRow, checkSlotRow } from './checkrow.ts';
2
3
  /** Authored source-painting limits over actual renderer setup pixels (#887). */
3
4
  import { refuseIfAny, type Problem } from './errors.ts';
@@ -191,3 +192,8 @@ export function setupPaintingLines(line: SetupPaintingObservation): string[] {
191
192
  ...line.regions.flatMap(r => [`${SETUP_PAINTING_LINE}: region "${r.name}" ${r.status} — box [${r.box.join(', ')}], pixelcount ${r.pixel_count}, limit ${r.limit ?? 'undeclared (SKIP)'}, RGB tolerance ${line.rgb_tolerance}`,
192
193
  ...r.slots.map(s => `${SETUP_PAINTING_LINE}: slot "${s.slot}" region "${r.name}" — box [${s.box.join(', ')}], pixelcount ${s.pixel_count}; region total ${r.pixel_count}, limit ${r.limit ?? 'undeclared (SKIP)'}`)])];
193
194
  }
195
+
196
+ /** Resolve an authored setup image against the requirements file that names it. */
197
+ export function setupPaintingFilePath(requirements: string, path: string): string {
198
+ return resolve(dirname(requirements), path);
199
+ }
package/src/sheet.ts CHANGED
@@ -21,7 +21,7 @@ import { basename, dirname, join } from 'node:path';
21
21
  import { drawText, GLYPH_H } from '@rig-c/core/font5x7';
22
22
  import { type Problem, refuseIfAny } from './errors.ts';
23
23
  import { type LayerSet, OPAQUE_ALPHA_ABOVE, readLayers } from './layers.ts';
24
- import { readParts } from './parts.ts';
24
+ import { partImageReference, readParts } from './parts.ts';
25
25
  import { alphaComposite } from './raster/composite.ts';
26
26
  import { readPng } from './raster/png.ts';
27
27
  import { resize } from './raster/resize.ts';
@@ -109,11 +109,11 @@ export function buildSheet(tiles: Tile[], cols: number, cell: number): Raster {
109
109
  export function tilesFrom(path: string): Tile[] {
110
110
  if (basename(path) === 'parts.json') {
111
111
  const parts = readParts(path);
112
- const dir = join(dirname(path), 'parts');
112
+ const dir = dirname(path);
113
113
  const problems: Problem[] = [];
114
114
  const tiles: Tile[] = [];
115
115
  for (const p of parts.parts) {
116
- const png = join(dir, `${p.name}.png`);
116
+ const png = join(dir, partImageReference(p).path);
117
117
  if (!existsSync(png)) {
118
118
  problems.push({ code: 'SHEET_PNG_PRESENT', object: `part "${p.name}"`, detail: `${png} does not exist; parts.json names it` });
119
119
  continue;
@@ -0,0 +1,131 @@
1
+ /** Direct source-projection cover, observed before projection changes RGB.
2
+ * Counts belong to effective run layers, before cuts, merges and edge writes.
3
+ */
4
+ import type { Extend, PlanEntry, Run } from './config.ts';
5
+ import { CORE_ALPHA, OPAQUE_ALPHA_ABOVE, type LayerSet } from './layers.ts';
6
+ import type { Mask, Raster } from './raster/types.ts';
7
+ import type { TakenLayerSource } from './takesource.ts';
8
+
9
+ export const SOURCE_COVER_FILE = 'source_cover.json';
10
+ export const SOURCE_COVER_SPEC = 'rig-parts-source-cover/1';
11
+
12
+ export interface SourceCoverLayer {
13
+ source: string;
14
+ run: Run;
15
+ layer: string;
16
+ depth_median: number | null;
17
+ draw_order: number;
18
+ plan_rank: number;
19
+ planned_parts: string[];
20
+ extend_parts: string[];
21
+ /** Null for a generated layer with no same-name input entry. */
22
+ input_layer: string | null;
23
+ prepared: boolean;
24
+ taken_layers: readonly TakenLayerSource[];
25
+ }
26
+
27
+ export interface SourceCoverPart {
28
+ part: string;
29
+ /** Parent source-plan reading attributed to a derived alternate part. */
30
+ source_of?: string;
31
+ source: string;
32
+ support_px: number;
33
+ /** Original own support held by keep, excluded from scalar-owner rows. */
34
+ held_under_cover_px: number;
35
+ covered_by: Array<{
36
+ source: string;
37
+ planned: boolean;
38
+ pixels: { count: number; spans: Array<[number, number, number]> };
39
+ }>;
40
+ }
41
+
42
+ export interface SourceCoverReading {
43
+ sources: SourceCoverLayer[];
44
+ parts: SourceCoverPart[];
45
+ }
46
+
47
+ export interface SourceCoverSet extends SourceCoverReading {
48
+ set: string | null;
49
+ painting_sha256: string;
50
+ grid: [number, number];
51
+ inputs: Array<{
52
+ run: Run;
53
+ file: string;
54
+ sha256: string;
55
+ layers: Array<{ layer: string; image: string | null }>;
56
+ }>;
57
+ inherited_parts: Array<{ part: string; set: null }>;
58
+ hidden_parts: string[];
59
+ output_assets: Array<{ part: string; image: string | null }>;
60
+ }
61
+
62
+ export function sourceCoverReport(sets: SourceCoverSet[]) {
63
+ return {
64
+ spec: SOURCE_COVER_SPEC,
65
+ stage: 'source-projection-input',
66
+ predicate: {
67
+ own_alpha_above: OPAQUE_ALPHA_ABOVE,
68
+ owner_alpha_at_least: CORE_ALPHA,
69
+ front: 'plan rank when both layers are planned; run draw order otherwise',
70
+ held_under_cover: 'keep support excluded from covered_by',
71
+ coordinates: 'native rig [y, left, right-exclusive]',
72
+ },
73
+ sets,
74
+ };
75
+ }
76
+
77
+ /** Reads the already-computed owner. Never changes a raster, mask or owner. */
78
+ export function sourceCoverRun(
79
+ run: Run, set: LayerSet, original: LayerSet, images: readonly Raster[],
80
+ ranks: readonly number[], plan: readonly PlanEntry[], extend: readonly Extend[],
81
+ owners: ArrayLike<number>, inFront: (owner: number, layer: number) => boolean,
82
+ keep: ReadonlyArray<Mask | null> | null,
83
+ ): SourceCoverReading {
84
+ const sources: SourceCoverLayer[] = set.layers.map((layer, i) => {
85
+ const input = original.layers.find(candidate => candidate.name === layer.name);
86
+ return {
87
+ source: `${run}:${layer.name}`, run, layer: layer.name,
88
+ depth_median: layer.depth, draw_order: layer.drawOrder, plan_rank: ranks[i],
89
+ planned_parts: plan.filter(([, r, tag]) => r === run && tag === layer.name).map(([part]) => part),
90
+ extend_parts: extend.filter(entry => entry.run === run && entry.tag === layer.name).map(entry => entry.part),
91
+ input_layer: input?.name ?? null,
92
+ prepared: input === undefined || input.left !== layer.left || input.top !== layer.top ||
93
+ input.pixels.width !== layer.pixels.width || input.pixels.height !== layer.pixels.height ||
94
+ input.pixels.data.length !== layer.pixels.data.length ||
95
+ (input.pixels.data !== layer.pixels.data && !input.pixels.data.every((value, pixel) => value === layer.pixels.data[pixel])),
96
+ taken_layers: layer.takenLayers ?? [],
97
+ };
98
+ });
99
+ const parts: SourceCoverPart[] = plan.filter(([, r]) => r === run).map(([part, , tag]) => {
100
+ const layer = set.layers.findIndex(candidate => candidate.name === tag);
101
+ const image = images[layer];
102
+ const cover = new Map<number, SourceCoverPart['covered_by'][number]['pixels']>();
103
+ let support = 0;
104
+ let held = 0;
105
+ for (let p = 0; p < owners.length; p++) {
106
+ if (image.data[p * 4 + 3] <= OPAQUE_ALPHA_ABOVE) continue;
107
+ support++;
108
+ if (keep?.[layer]?.data[p] === 1) { held++; continue; }
109
+ const owner = owners[p];
110
+ if (owner < 0 || owner === layer || !inFront(owner, layer)) continue;
111
+ let pixels = cover.get(owner);
112
+ if (pixels === undefined) {
113
+ pixels = { count: 0, spans: [] };
114
+ cover.set(owner, pixels);
115
+ }
116
+ pixels.count++;
117
+ const x = p % image.width;
118
+ const y = Math.floor(p / image.width);
119
+ const last = pixels.spans[pixels.spans.length - 1];
120
+ if (last !== undefined && last[0] === y && last[2] === x) last[2]++;
121
+ else pixels.spans.push([y, x, x + 1]);
122
+ }
123
+ return {
124
+ part, source: `${run}:${tag}`, support_px: support, held_under_cover_px: held,
125
+ covered_by: [...cover].sort(([a], [b]) => a - b).map(([owner, pixels]) => ({
126
+ source: sources[owner].source, planned: ranks[owner] >= 0, pixels,
127
+ })),
128
+ };
129
+ });
130
+ return { sources, parts };
131
+ }