@rig-c/parts 2.34.0 → 2.36.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/src/build.ts CHANGED
@@ -16,6 +16,7 @@ import { ART_JOINT_LINE, artJointLines } from './artjoints.ts';
16
16
  import { applyTakenLayers } from './takelayers.ts';
17
17
  import { applyTakenRegions } from './takeregion.ts';
18
18
  import { bindOccluderPlates, occluderStageWarnings, readOccluderInputs } from './occluderstage.ts';
19
+ import { PLATE_RECEIPT_FILE, type PlateReceipt, verifyPlateReceipt } from './plate.ts';
19
20
  import { ownershipLines, provenanceLines } from './provenance.ts';
20
21
  import { readSourceDepth } from './depthsheets.ts';
21
22
  import { orderedBaseAnchor } from './baseanchor.ts';
@@ -67,7 +68,7 @@ import { createHash } from 'node:crypto';
67
68
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
68
69
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
69
70
  import { type AnimFrame, EncodeError, encodeApng, encodeIndexedApng, INDEXED_DEFAULTS } from './apng.ts';
70
- import { assemble, type AssembleResult, cutLines, edgeSplitLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine } from './assemble.ts';
71
+ import { assemble, type AssembleResult, boxOf, cutLines, edgeSplitLines, type ExcludedCount, excludedLines, setExclusions, islandLines, setIslandSources, type IslandCount, hiddenLines, SINGLE_RUN_FACE_TAGS, singleRunHeadBox, softOcclusionLine, driftLine, limbLines, FIGURE_MASK_FILE, figuresLine, groundWarning, holeKindsLine, holeLines, measurePinholes, measureRecomposite, pinholeProblems, pinholesLine, type ProjectRule, recomposite, recompositeRecord, scenePhrase, type SeamRule, sourceInRig, stageFields, uncoveredLine, underBox } from './assemble.ts';
71
72
  import { allocationClause, type Reducer, stageBClause, unboundedClause } from './automesh.ts';
72
73
  import { residualClause } from './autoenvelope.ts';
73
74
  import { type AutoMotionCase, failingRows, idleSchedule, localRow, motionClause, motionDeformation, motionDocument, motionInput, motionRowText, motionStimulus, motionVerdict, noStimulusProblem, prepareComparison, type ReplayCandidate, runComparison, runPreparedComparison, sourceSelfFailure, stimulusMotion, withStimulus } from './automotion.ts';
@@ -105,7 +106,7 @@ import { CONTROL_SUFFIX, withAnimations } from './motion.ts';
105
106
  import type { PaletteError } from './palette.ts';
106
107
  import { type LayerSet, readLayers } from './layers.ts';
107
108
  import { placeBoneEntriesForSkeleton, poseBoneEntriesForDrawn, REGISTER_OFFSET_BAR, REGISTER_SCALE_BAR, registeredWithinBar, registerSkeleton, SKELETON_LIMB_BONES, skeletonDrawnLength, skeletonLimbJoints } from './limbs.ts';
108
- import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type PartRecord, partImageReference, depthImageReference, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
109
+ import { type AlternatePartsRecord, PAINTING_IN_RIG_FILE, FRONT_SUFFIX, type OccluderPlateRecord, type PartRecord, partImageReference, depthImageReference, readParts, type RecompositeRecord, type SingleRunPad, tagOf, writeParts } from './parts.ts';
109
110
  import { encodePngBytes, readPng, writePng } from './raster/png.ts';
110
111
  import type { Raster } from './raster/types.ts';
111
112
  import { type Mask, newMask } from './raster/types.ts';
@@ -266,12 +267,72 @@ export function authorPartLines(parts: readonly PartRecord[]): string[] {
266
267
  * file that does not decode as a PNG (`ASSEMBLE_UNDER_DECODES`). The stage
267
268
  * itself holds the image to the polygon's box and the removed pixels.
268
269
  */
269
- export function readUnders(configPath: string, cuts: readonly Cut[]): Array<Raster | null> {
270
+ export function readUnders(
271
+ configPath: string,
272
+ cuts: readonly Cut[],
273
+ options?: { sourcePath?: string; rigSize?: readonly [number, number]; cutsAt?: string; platesOut?: Array<OccluderPlateRecord | null> },
274
+ ): Array<Raster | null> {
270
275
  const problems: Problem[] = [];
276
+ const base = dirname(resolve(configPath));
277
+ const cutsAt = options?.cutsAt ?? 'config.assemble.cuts';
278
+ const sourceSha = options?.sourcePath !== undefined && existsSync(options.sourcePath) && statSync(options.sourcePath).isFile()
279
+ ? createHash('sha256').update(readFileSync(options.sourcePath)).digest('hex')
280
+ : null;
271
281
  const out = cuts.map((q, i): Raster | null => {
282
+ options?.platesOut?.push(null);
272
283
  if (q.under === undefined) return null;
273
- const file = resolve(dirname(resolve(configPath)), q.under);
274
- const object = `config.assemble.cuts[${i}].under (part "${q.into}")`;
284
+ const object = `${cutsAt}[${i}].under (part "${q.into}")`;
285
+ if (typeof q.under === 'object') {
286
+ const plateRel = q.under.plate;
287
+ const plateDir = resolve(base, plateRel);
288
+ const receiptFile = join(plateDir, PLATE_RECEIPT_FILE);
289
+ if (!existsSync(receiptFile) || !statSync(receiptFile).isFile()) {
290
+ problems.push({
291
+ code: 'CONFIG_FILE_PRESENT',
292
+ object,
293
+ detail: `names ${plateRel} (${plateDir}), which holds no ${PLATE_RECEIPT_FILE}; a comfy plate --mode occluder output directory relative to the config's directory is required`,
294
+ });
295
+ return null;
296
+ }
297
+ const receiptProblems = verifyPlateReceipt(receiptFile);
298
+ if (receiptProblems.length > 0) {
299
+ problems.push(...receiptProblems);
300
+ return null;
301
+ }
302
+ const receiptBytes = readFileSync(receiptFile);
303
+ const receipt = JSON.parse(receiptBytes.toString('utf8')) as PlateReceipt;
304
+ if (receipt.mode !== 'occluder' || receipt.occluder === undefined) {
305
+ problems.push({
306
+ code: 'PLATE_RECEIPT_KEYS',
307
+ object: `${cutsAt}[${i}].under.plate`,
308
+ detail: `names ${receiptFile} with mode ${JSON.stringify(receipt.mode)}; an occluder plate receipt (mode "occluder") is required for ${object}`,
309
+ });
310
+ return null;
311
+ }
312
+ if (sourceSha !== null && receipt.painting.sha256 !== sourceSha) {
313
+ problems.push({
314
+ code: 'ASSEMBLE_UNDER_PLATE_PAINTING',
315
+ object,
316
+ detail: `cut ${i} ("${q.into}") receipt ${receiptFile} records painting.sha256 ${receipt.painting.sha256}, while --source (${options?.sourcePath}) is ${sourceSha}; re-run rig-parts assemble --emit-fill-masks then rig-parts comfy plate --mode occluder`,
317
+ });
318
+ return null;
319
+ }
320
+ const platePng = readPng(resolve(plateDir, receipt.output.path));
321
+ const [W, H] = options?.rigSize ?? [platePng.width, platePng.height];
322
+ const rigPlate = sourceInRig(platePng, W, H);
323
+ const box = underBox(q.polygon);
324
+ const record: OccluderPlateRecord = {
325
+ receipt: `${plateRel.replace(/\\/g, '/').replace(/\/+$/, '')}/${PLATE_RECEIPT_FILE}`,
326
+ receipt_sha256: createHash('sha256').update(receiptBytes).digest('hex'),
327
+ occluder_sha256: receipt.occluder.sha256,
328
+ painting_sha256: receipt.painting.sha256,
329
+ output_sha256: receipt.output.sha256,
330
+ mask_sha256: receipt.mask.sha256,
331
+ };
332
+ if (options?.platesOut !== undefined) options.platesOut[i] = record;
333
+ return boxOf(rigPlate, box.x0, box.y0, box.w, box.h);
334
+ }
335
+ const file = resolve(base, q.under);
275
336
  if (!existsSync(file) || !statSync(file).isFile()) {
276
337
  problems.push({ code: 'ASSEMBLE_UNDER_PRESENT', object, detail: `names ${file}, which is no such file; a PNG of what lies under the piece, its path relative to the config's directory, is required` });
277
338
  return null;
@@ -287,6 +348,85 @@ export function readUnders(configPath: string, cuts: readonly Cut[]): Array<Rast
287
348
  return out;
288
349
  }
289
350
 
351
+ function verifyUnderPlateMasks(
352
+ result: AssembleResult,
353
+ cuts: readonly Cut[],
354
+ plates: ReadonlyArray<OccluderPlateRecord | null>,
355
+ cutsAt = 'config.assemble.cuts',
356
+ ): Problem[] {
357
+ const problems: Problem[] = [];
358
+ const masks = result.cutFillMasks ?? [];
359
+ cuts.forEach((q, i) => {
360
+ const plate = plates[i] ?? null;
361
+ if (plate === null) return;
362
+ const entry = masks[i];
363
+ const maskBytes = encodePngBytes(entry.mask);
364
+ const maskSha = createHash('sha256').update(maskBytes).digest('hex');
365
+ if (plate.occluder_sha256 !== maskSha) {
366
+ problems.push({
367
+ code: 'ASSEMBLE_UNDER_PLATE_MASK',
368
+ object: `${cutsAt}[${i}].under (part "${q.into}")`,
369
+ detail: `cut ${i} ("${q.into}") receipt ${plate.receipt} records occluder.sha256 ${plate.occluder_sha256}, while the fill mask derived from the current cut is ${maskSha}; re-run rig-parts assemble --emit-fill-masks then rig-parts comfy plate --mode occluder`,
370
+ });
371
+ return;
372
+ }
373
+ const row = result.parts.cut_ownership?.find((r) => r.into === q.into);
374
+ if (row !== undefined) row.under_plate = plate;
375
+ });
376
+ return problems;
377
+ }
378
+
379
+ export interface EmitFillMasksInput {
380
+ source: string;
381
+ full: string;
382
+ head: string | null;
383
+ config: string;
384
+ outDir: string;
385
+ seam?: SeamRule;
386
+ project?: ProjectRule;
387
+ }
388
+
389
+ export function emitFillMasksStage(input: EmitFillMasksInput, log: Log): Array<{ into: string; path: string; sha256: string; opaquePx: number }> {
390
+ const cfg = loadEarlyConfig(input.config, 'assemble', input.project);
391
+ const seam = input.seam ?? cfg.assemble.seam ?? DEFAULT_SEAM_RULE;
392
+ const project = input.project ?? cfg.assemble.project ?? DEFAULT_PROJECT_RULE;
393
+ const src = readSource(input.source);
394
+ const read = readRuns(input.full, input.head);
395
+ const takenRuns = applyTakenLayers(read, src, cfg, input.config);
396
+ const receipts = readEditorReceipts(cfg.assemble.editor_receipts, input.config);
397
+ const runs = applyTakenRegions(takenRuns, src, cfg, input.config, undefined, receipts, input.source);
398
+ const fields = stageFields(cfg, runs.single ? { w: src.width, h: src.height } : null);
399
+ const strippedCuts = fields.cuts.map((q) => ({ from: q.from, into: q.into, polygon: q.polygon, draw: q.draw, overlap: q.overlap }));
400
+ const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
401
+ const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
402
+ const result = assemble({
403
+ source: src,
404
+ full: runs.full,
405
+ head: runs.head,
406
+ depth: cfg.depth,
407
+ depthBase: dirname(resolve(input.config)),
408
+ ...fields,
409
+ cuts: strippedCuts,
410
+ ...(caps === undefined ? {} : { caps }),
411
+ ...(occluders === undefined ? {} : { occluders }),
412
+ seamRule: seam,
413
+ projectRule: project,
414
+ });
415
+ mkdirSync(input.outDir, { recursive: true });
416
+ const out: Array<{ into: string; path: string; sha256: string; opaquePx: number }> = [];
417
+ for (const entry of result.cutFillMasks ?? []) {
418
+ const bytes = encodePngBytes(entry.mask);
419
+ const sha = createHash('sha256').update(bytes).digest('hex');
420
+ const file = join(input.outDir, `${entry.into}.png`);
421
+ writeFileSync(file, bytes);
422
+ let opaquePx = 0;
423
+ for (let i = 3; i < entry.mask.data.length; i += 4) if (entry.mask.data[i] > 0) opaquePx++;
424
+ log(` fill mask: "${entry.from}" -> "${entry.into}" ${entry.mask.width}x${entry.mask.height}, ${opaquePx} opaque px -> ${file} (sha256 ${sha})`);
425
+ out.push({ into: entry.into, path: file, sha256: sha, opaquePx });
426
+ }
427
+ return out;
428
+ }
429
+
290
430
  /**
291
431
  * Each limb segment's `cap` image (issue #349), read from its path relative to
292
432
  * the config's directory and keyed `<limb>/<segment index>`. Every one is read
@@ -384,12 +524,15 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
384
524
  : readRequirements(requirements.read).setup_painting;
385
525
  const figureSupport = setupPainting === undefined ? undefined
386
526
  : readSetupFigureMask(setupPainting, requirements!.read, src, Math.trunc(src.width * fields.rigScale), Math.trunc(src.height * fields.rigScale));
387
- const declaredFigure = figureSupport === undefined ? undefined : { width: Math.trunc(src.width * fields.rigScale), height: Math.trunc(src.height * fields.rigScale), data: figureSupport };
388
- const under = readUnders(input.config, fields.cuts);
527
+ const rigSize: [number, number] = [Math.trunc(src.width * fields.rigScale), Math.trunc(src.height * fields.rigScale)];
528
+ const declaredFigure = figureSupport === undefined ? undefined : { width: rigSize[0], height: rigSize[1], data: figureSupport };
529
+ const underPlates: Array<OccluderPlateRecord | null> = [];
530
+ const under = readUnders(input.config, fields.cuts, { sourcePath: input.source, rigSize, platesOut: underPlates });
389
531
  const caps = fields.limbs === undefined ? undefined : readCaps(input.config, fields.limbs);
390
532
  const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
391
533
  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 }),
392
534
  ...((cfg.assemble.take ?? []).some(t => 'seed' in t) ? { regionTake: { full: takenRuns.full, head: takenRuns.head, targets: (cfg.assemble.take ?? []).flatMap(t => 'seed' in t ? [t.part] : []) } } : {}), ...(caps === undefined ? {} : { caps }), ...(occluders === undefined ? {} : { occluders }), seamRule: seam, projectRule: project });
535
+ refuseIfAny(verifyUnderPlateMasks(result, fields.cuts, underPlates));
393
536
 
394
537
  // Issue #1230 / #1237 / #1246: copied occluder colour in a declared occluder's under parts and unheld occluder px are named, never kept silent;
395
538
  // when `plate` is declared on an occluder entry, its receipt is verified and bound to occluder, painting and base run.
@@ -622,7 +765,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
622
765
  const altExtend: Extend[] = altRuns.single ? [] : fields.extend.filter((e) => altPlanNames.has(e.part));
623
766
  const altPatches: Patch[] = fields.patches.filter((p) => coveredSet.has(p.name)).map((p) => ({ ...p, draw: remapDraw(p.draw) }));
624
767
  const altCuts: Cut[] = rawCuts.map((c) => ({ ...c, draw: remapDraw(c.draw) }));
625
- const altUnder = alt.cuts !== undefined ? readUnders(input.config, altCuts) : altCuts.map(() => null);
768
+ const altUnderPlates: Array<OccluderPlateRecord | null> = [];
769
+ const altUnder = alt.cuts !== undefined ? readUnders(input.config, altCuts, { sourcePath: alt.source, rigSize: result.parts.rig_size, cutsAt: `${alt.at}.cuts`, platesOut: altUnderPlates }) : altCuts.map(() => null);
626
770
  const altHeadBox = alt.head_box ?? (altRuns.single ? singleRunHeadBox(altSrc.width, altSrc.height, fields.resolution) : fields.headBox);
627
771
  let altBones = fields.bones;
628
772
  let altDrawnLength: Record<string, number> | undefined;
@@ -786,6 +930,11 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
786
930
  }
787
931
  throw err;
788
932
  }
933
+ const altMaskProblems = verifyUnderPlateMasks(altRes, altCuts, altUnderPlates, `${alt.at}.cuts`);
934
+ if (altMaskProblems.length > 0) {
935
+ altProblems.push(...altMaskProblems);
936
+ continue;
937
+ }
789
938
  const keptImages = altRes.images
790
939
  .filter(({ record }) => coveredSet.has(record.name))
791
940
  .flatMap(({ record, image, depthImage }) => [{ name: `${alt.name}_${record.name}`, image }, ...(depthImage === undefined || record.depth === undefined ? [] : [{ name: `${alt.name}_${record.depth.image.slice(0, -4)}`, image: depthImage }])]);
package/src/config.ts CHANGED
@@ -249,6 +249,12 @@ export interface Patch {
249
249
  * for a `from` a limb takes (issue #564), whether the polygon takes a pixel a
250
250
  * segment of the limb holds (`ASSEMBLE_CUT_CROSSES_LIMB`).
251
251
  */
252
+ export interface CutUnderPlate {
253
+ plate: string;
254
+ }
255
+
256
+ export type CutUnder = string | CutUnderPlate;
257
+
252
258
  export interface Cut {
253
259
  from: string;
254
260
  into: string;
@@ -262,13 +268,16 @@ export interface Cut {
262
268
  */
263
269
  overlap: number;
264
270
  /**
265
- * Issue #193, optional: a PNG, its path relative to the config's directory,
266
- * of what lies under the piece — in rig pixels over the polygon's bounding
267
- * box (`underBox` in `src/assemble.ts`). Where the cut removed pixels from
268
- * the base (the piece's pixels less the band), the base takes this image's
269
- * pixels; it is read nowhere else. Absent: the base keeps only its band.
271
+ * Issue #193 / #1230, optional: a PNG, its path relative to the config's
272
+ * directory, of what lies under the piece — in rig pixels over the polygon's
273
+ * bounding box (`underBox` in `src/assemble.ts`) — or `{"plate": "<dir>"}`
274
+ * naming a `comfy plate --mode occluder` output directory whose `plate.png`
275
+ * is resampled to rig pixels and cropped to `underBox`. Where the cut
276
+ * removed pixels from the base (the piece's pixels less the band), the base
277
+ * takes this image's pixels; it is read nowhere else. Absent: the base keeps
278
+ * only its band.
270
279
  */
271
- under?: string;
280
+ under?: CutUnder;
272
281
  /**
273
282
  * Issue #360 (item 11), optional, one value: `"colour"` — where the under
274
283
  * fills a removed pixel, the base takes the under's colour and keeps the
@@ -2572,7 +2581,7 @@ function checkRequiredHiddenExtent(c: Check, a: Record<string, Json>, names: rea
2572
2581
  }
2573
2582
 
2574
2583
  /**
2575
- * Issue #1230 / #1241 / #1246: `config.assemble.occluders`, `[{image, sha256, under, over?, rgb_within, plate?, part?}]`.
2584
+ * Issue #1230 / #1241 / #1246 / #1251 / #1259: `config.assemble.occluders`, `[{image, sha256, under, over?, rgb_within, plate?, part?, grow?, guard?}]`.
2576
2585
  * Shape at every door; `under`, `over` and `part` resolved against the plan where the door reads it; the file and its
2577
2586
  * sha256 where the door knows the config's directory (`checkOccluderFiles`). Returns the declared `part` names, in order.
2578
2587
  */
@@ -2584,7 +2593,7 @@ function checkOccluders(c: Check, a: Record<string, Json>, names: readonly strin
2584
2593
  const partNames: string[] = [];
2585
2594
  (a.occluders as Json[]).forEach((value, i) => {
2586
2595
  const p = `${at}[${i}]`;
2587
- const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], ['over', 'plate', 'part']);
2596
+ const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], ['over', 'plate', 'part', 'grow', 'guard']);
2588
2597
  if (row === null) return;
2589
2598
  const imageOk = c.string(`${p}.image`, row.image);
2590
2599
  const shaOk = typeof row.sha256 === 'string' && SHA256_PATTERN.test(row.sha256);
@@ -2613,8 +2622,22 @@ function checkOccluders(c: Check, a: Record<string, Json>, names: readonly strin
2613
2622
  }
2614
2623
  }
2615
2624
  }
2616
- if (imageOk && shaOk && underOk && overOk && rgbOk && plateOk && partOk) {
2617
- declarations.push({ image: row.image as string, sha256: row.sha256 as string, under: row.under as string[], ...('over' in row ? { over: row.over as string[] } : {}), rgb_within: row.rgb_within as number, ...('plate' in row ? { plate: row.plate as string } : {}), ...(partName !== undefined ? { part: partName } : {}) });
2625
+ let growOk = true;
2626
+ let growVal: number | undefined;
2627
+ if ('grow' in row) {
2628
+ growOk = typeof row.grow === 'number' && Number.isInteger(row.grow) && row.grow >= 0;
2629
+ if (!growOk) c.fail('CONFIG_FIELD_TYPE', `${p}.grow`, `is ${show(row.grow)}; a non-negative integer is required`);
2630
+ else growVal = row.grow as number;
2631
+ }
2632
+ let guardOk = true;
2633
+ let guardVal: number | undefined;
2634
+ if ('guard' in row) {
2635
+ guardOk = typeof row.guard === 'number' && Number.isInteger(row.guard) && row.guard >= 0;
2636
+ if (!guardOk) c.fail('CONFIG_FIELD_TYPE', `${p}.guard`, `is ${show(row.guard)}; a non-negative integer is required`);
2637
+ else guardVal = row.guard as number;
2638
+ }
2639
+ if (imageOk && shaOk && underOk && overOk && rgbOk && plateOk && partOk && growOk && guardOk) {
2640
+ declarations.push({ image: row.image as string, sha256: row.sha256 as string, under: row.under as string[], ...('over' in row ? { over: row.over as string[] } : {}), rgb_within: row.rgb_within as number, ...('plate' in row ? { plate: row.plate as string } : {}), ...(partName !== undefined ? { part: partName } : {}), ...(growVal !== undefined ? { grow: growVal } : {}), ...(guardVal !== undefined ? { guard: guardVal } : {}) });
2618
2641
  }
2619
2642
  });
2620
2643
  c.problems.push(...occluderNameProblems(declarations, names));
@@ -2881,8 +2904,13 @@ function checkCuts(c: Check, v: Json, plan: string[], patches: string[], p = 'co
2881
2904
  const at = `${p}[${i}]`;
2882
2905
  const e = c.object(at, entry, ['from', 'into', 'polygon', 'draw', 'overlap'], ['under', 'under_fill']);
2883
2906
  if (e === null) return;
2884
- if ('under' in e && !(typeof e.under === 'string' && e.under !== '')) {
2885
- c.fail('CONFIG_FIELD_TYPE', `${at}.under`, `is ${show(e.under)}; a non-empty path to a PNG is required, relative to the config's directory — the image of what lies under the piece, in rig pixels over the polygon's bounding box`);
2907
+ if ('under' in e) {
2908
+ if (typeof e.under === 'object' && e.under !== null && !Array.isArray(e.under)) {
2909
+ const u = c.object(`${at}.under`, e.under, ['plate'], []);
2910
+ if (u !== null && 'plate' in u) c.string(`${at}.under.plate`, u.plate);
2911
+ } else if (!(typeof e.under === 'string' && e.under !== '')) {
2912
+ c.fail('CONFIG_FIELD_TYPE', `${at}.under`, `is ${show(e.under)}; a non-empty path to a PNG or {"plate": "<dir>"} is required, relative to the config's directory — the image of what lies under the piece, in rig pixels over the polygon's bounding box, or a comfy plate --mode occluder output directory`);
2913
+ }
2886
2914
  }
2887
2915
  if ('under_fill' in e && e.under_fill !== 'colour') {
2888
2916
  c.fail('CONFIG_FIELD_TYPE', `${at}.under_fill`, `is ${show(e.under_fill)}; "colour" is required — the base takes the under's colour and keeps the alpha the cut removed, so its silhouette does not grow; leave under_fill out for the under's colour and alpha`);
@@ -151,12 +151,12 @@ export function editedRunImages(runs: { full: LayerSet; head: LayerSet; single:
151
151
  return out;
152
152
  }
153
153
 
154
- /** The images a config names by path that the author painted: every cut's `under` and every limb segment's `cap`. */
155
- export function editedConfigImages(configPath: string, cuts: ReadonlyArray<{ into: string; under?: string }>, limbs: Readonly<Record<string, { segments: ReadonlyArray<{ part: string; cap?: string }> }>> | undefined, cutsAt = 'config.assemble.cuts'): EditedImage[] {
154
+ /** The images a config names by path that the author painted: every string-form cut's `under` and every limb segment's `cap` (a `{plate}` under carries its own machine receipt). */
155
+ export function editedConfigImages(configPath: string, cuts: ReadonlyArray<{ into: string; under?: string | { plate: string } }>, limbs: Readonly<Record<string, { segments: ReadonlyArray<{ part: string; cap?: string }> }>> | undefined, cutsAt = 'config.assemble.cuts'): EditedImage[] {
156
156
  const base = dirname(resolve(configPath));
157
157
  const out: EditedImage[] = [];
158
158
  cuts.forEach((q, i) => {
159
- if (q.under !== undefined) out.push({ object: `${cutsAt}[${i}].under (part "${q.into}")`, path: resolve(base, q.under) });
159
+ if (typeof q.under === 'string') out.push({ object: `${cutsAt}[${i}].under (part "${q.into}")`, path: resolve(base, q.under) });
160
160
  });
161
161
  for (const [l, limb] of Object.entries(limbs ?? {})) {
162
162
  limb.segments.forEach((sg, k) => {
package/src/layers.ts CHANGED
@@ -56,6 +56,8 @@ export const NEAR_WHITE_MIN = 235;
56
56
  export interface Layer {
57
57
  /** Exact seeded component in the original run canvas; internal, never serialized. */
58
58
  regionSelection?: Mask;
59
+ /** Unmerged base and donor layers for an occluder-split take, placed separately on the rig grid; internal, never serialized. */
60
+ occluderSplit?: { occluder: number; base: Layer; donor: Layer; merged: Raster };
59
61
  /** Verified donor identities retained through generated splits. */
60
62
  takenLayers?: TakenLayerSource[];
61
63
  /** As the input names it: a v3 tag, possibly with a `-r`/`-l` side, or an author-made layer's `author:<label>`. */
package/src/occluders.ts CHANGED
@@ -36,6 +36,10 @@ export interface OccluderDeclaration {
36
36
  plate?: string;
37
37
  /** An optional part name (`painting:<part>`) emitted from the painting for occluder pixels not held at rest by front parts (issue #1246). */
38
38
  part?: string;
39
+ /** An optional non-negative integer rig-px radius by which the occluder's > 128 core is dilated on the rig grid before the under guard, the occluder part and UNHELD read it (issue #1251). */
40
+ grow?: number;
41
+ /** An optional non-negative integer rig-px radius by which the occluder's > 128 core is dilated on the rig grid for the under guard only, without painting a part or changing UNHELD (issue #1259). */
42
+ guard?: number;
39
43
  }
40
44
 
41
45
  export const OCCLUDER_COLOUR_COPIED = 'ASSEMBLE_OCCLUDER_COLOUR_COPIED';
@@ -249,13 +253,45 @@ export function occluderFileProblems(declarations: readonly OccluderDeclaration[
249
253
  /**
250
254
  * Reorder a draft `assemble.plan` in place so each declared `occluders[i].over`
251
255
  * part sits after every `under` part of the same entry across `full` and `head`
252
- * rows, keeping every other row's relative order unchanged (issue #1247).
256
+ * rows, keeping every other row's relative order unchanged (issues #1247, #1251).
257
+ *
258
+ * A declared `over` or `under` name matches a proposed row whose name (`row[0]`)
259
+ * equals it, or whose See-through tag (`row[2]`) equals `takenTags[name]` (the
260
+ * tag of the config's taken layer for that name). Any `over` or `under` name on
261
+ * an entry with `over` that matches no proposed row is returned as a note for
262
+ * `proposal.notes`.
253
263
  */
254
264
  export function orderPlanForOccluders<T extends readonly [string, ...unknown[]]>(
255
265
  plan: T[],
256
266
  declarations: readonly OccluderDeclaration[] | undefined,
257
- ): void {
258
- if (declarations === undefined || declarations.length === 0) return;
267
+ takenTags?: Readonly<Record<string, string>>,
268
+ ): string[] {
269
+ if (declarations === undefined || declarations.length === 0) return [];
270
+ const matchesRow = (row: T, name: string): boolean => {
271
+ if (row[0] === name) return true;
272
+ const tag = takenTags?.[name];
273
+ return tag !== undefined && typeof row[2] === 'string' && row[2] === tag;
274
+ };
275
+ const matchesSet = (row: T, names: ReadonlySet<string>): boolean => {
276
+ for (const name of names) {
277
+ if (matchesRow(row, name)) return true;
278
+ }
279
+ return false;
280
+ };
281
+ const notes: string[] = [];
282
+ declarations.forEach((d, i) => {
283
+ if (d.over === undefined || d.over.length === 0) return;
284
+ for (const name of d.under) {
285
+ if (!plan.some((row) => matchesRow(row, name))) {
286
+ notes.push(`occluders[${i}].under "${name}" matched no proposed row`);
287
+ }
288
+ }
289
+ for (const name of d.over) {
290
+ if (!plan.some((row) => matchesRow(row, name))) {
291
+ notes.push(`occluders[${i}].over "${name}" matched no proposed row`);
292
+ }
293
+ }
294
+ });
259
295
  for (let pass = 0; pass <= plan.length; pass++) {
260
296
  let moved = false;
261
297
  for (const d of declarations) {
@@ -263,14 +299,14 @@ export function orderPlanForOccluders<T extends readonly [string, ...unknown[]]>
263
299
  const underSet = new Set(d.under);
264
300
  let lastUnder = -1;
265
301
  for (let i = 0; i < plan.length; i++) {
266
- if (underSet.has(plan[i][0])) lastUnder = i;
302
+ if (matchesSet(plan[i], underSet)) lastUnder = i;
267
303
  }
268
304
  if (lastUnder < 0) continue;
269
305
  const overSet = new Set(d.over);
270
306
  const beforeOver: T[] = [];
271
307
  const keptBefore: T[] = [];
272
308
  for (let i = 0; i < lastUnder; i++) {
273
- if (overSet.has(plan[i][0])) beforeOver.push(plan[i]);
309
+ if (matchesSet(plan[i], overSet)) beforeOver.push(plan[i]);
274
310
  else keptBefore.push(plan[i]);
275
311
  }
276
312
  if (beforeOver.length === 0) continue;
@@ -280,6 +316,7 @@ export function orderPlanForOccluders<T extends readonly [string, ...unknown[]]>
280
316
  }
281
317
  if (!moved) break;
282
318
  }
319
+ return notes;
283
320
  }
284
321
 
285
322
  export interface OccluderCopy {
@@ -318,6 +355,6 @@ export function occluderColourWarning(index: number, copy: OccluderCopy, rgbWith
318
355
  return `WARN ${OCCLUDER_COLOUR_COPIED}: ${AT}[${index}] part "${copy.part}" — ${copy.px} rig px of its selected layer at alpha > ${COPIED_ALPHA_ABOVE} under the occluder (alpha > 0) lie within ${rgbWithin} of the painting (max channel); first at ${copy.first[0]},${copy.first[1]}; the layer holds the occluder's own colour — take this part from a See-through run on the painting with the occluder removed (comfy plate --mode occluder)`;
319
356
  }
320
357
 
321
- export function occluderUnheldWarning(index: number, image: string, under: readonly string[], px: number, first: readonly [number, number]): string {
322
- return `WARN ${OCCLUDER_UNHELD}: ${AT}[${index}] — ${px} rig px of occluder "${image}" (alpha > 8, first at ${first[0]},${first[1]}) are not held at alpha >= 250 by any part drawn in front of under [${under.map((u) => `"${u}"`).join(', ')}]; declare ${AT}[${index}].part to fill the unheld occluder pixels`;
358
+ export function occluderUnheldWarning(index: number, image: string, under: readonly string[], px: number, first: readonly [number, number], coreAlpha: number): string {
359
+ return `WARN ${OCCLUDER_UNHELD}: ${AT}[${index}] — ${px} rig px of occluder "${image}" (alpha > ${COPIED_ALPHA_ABOVE}, first at ${first[0]},${first[1]}) are not held at alpha >= ${coreAlpha} by any part drawn in front of under [${under.map((u) => `"${u}"`).join(', ')}]; declare ${AT}[${index}].part to fill the unheld occluder pixels`;
323
360
  }
@@ -10,7 +10,7 @@
10
10
  import { createHash } from 'node:crypto';
11
11
  import { existsSync, readFileSync, statSync } from 'node:fs';
12
12
  import { dirname, join, resolve } from 'node:path';
13
- import { checkGeometry, layerToRig, padSingleRun, placeLayer, sourceInRig } from './assemble.ts';
13
+ import { checkGeometry, layerToRigSplit, occluderCoreMask, padSingleRun, sourceInRig } from './assemble.ts';
14
14
  import type { PlanEntry } from './config.ts';
15
15
  import { SHA256_PATTERN } from './editreceipt.ts';
16
16
  import { PartsError } from './errors.ts';
@@ -76,7 +76,9 @@ export function occluderStageWarnings(input: OccluderStageInput): string[] {
76
76
  const full = runs.single ? padSingleRun(runs.full, frame, input.resolution) : runs.full;
77
77
  const painting = sourceInRig(source, frame.W, frame.H);
78
78
  const lines: string[] = [];
79
- readOccluderInputs(input.occluders, input.configPath, source).forEach(({ declaration: d, image }, i) => {
79
+ const occluderInputs = readOccluderInputs(input.occluders, input.configPath, source);
80
+ const occluderCoreMasks = occluderInputs.map(({ image }) => occluderCoreMask(image, frame.W, frame.H).coreBefore);
81
+ occluderInputs.forEach(({ declaration: d, image }, i) => {
80
82
  // A rig pixel reads the occluder at the source pixel its centre falls in.
81
83
  const sx = (x: number): number => Math.min(source.width - 1, Math.floor((x + 0.5) * source.width / frame.W));
82
84
  const sy = (y: number): number => Math.min(source.height - 1, Math.floor((y + 0.5) * source.height / frame.H));
@@ -85,7 +87,7 @@ export function occluderStageWarnings(input: OccluderStageInput): string[] {
85
87
  const row = input.plan.find(([part]) => part === name);
86
88
  if (row === undefined) return [];
87
89
  const layer = (row[1] === 'full' ? full : runs.head).layers.find((l) => l.name === row[2]);
88
- return layer === undefined ? [] : [{ name, image: layerToRig(placeLayer(layer, input.resolution), frame, row[1]) }];
90
+ return layer === undefined ? [] : [{ name, image: layerToRigSplit(layer, input.resolution, frame, row[1], occluderCoreMasks) }];
89
91
  });
90
92
  for (const copy of occluderColourCopies(parts, painting, alpha, d.rgb_within)) lines.push(occluderColourWarning(i, copy, d.rgb_within));
91
93
  });