@rig-c/parts 2.33.0 → 2.35.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
@@ -15,7 +15,8 @@ import { CUT_MATERIAL_LINE, CUT_MATERIAL_SOURCES, materialLines } from './cutmat
15
15
  import { ART_JOINT_LINE, artJointLines } from './artjoints.ts';
16
16
  import { applyTakenLayers } from './takelayers.ts';
17
17
  import { applyTakenRegions } from './takeregion.ts';
18
- import { bindOccluderPlates, occluderStageWarnings } from './occluderstage.ts';
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,16 +524,21 @@ 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);
532
+ const occluders = cfg.assemble.occluders === undefined ? undefined : readOccluderInputs(cfg.assemble.occluders, input.config, src);
390
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 }),
391
- ...((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 });
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));
392
536
 
393
- // Issue #1230 / #1237: copied occluder colour in a declared occluder's under parts is named, never kept silent;
537
+ // Issue #1230 / #1237 / #1246: copied occluder colour in a declared occluder's under parts and unheld occluder px are named, never kept silent;
394
538
  // when `plate` is declared on an occluder entry, its receipt is verified and bound to occluder, painting and base run.
395
539
  if (cfg.assemble.occluders !== undefined) {
396
540
  for (const line of occluderStageWarnings({ occluders: cfg.assemble.occluders, configPath: input.config, source: src, runs, plan: fields.plan, resolution: fields.resolution, headBox: fields.headBox, rigScale: fields.rigScale })) log(line);
541
+ for (const line of result.occluderUnheldWarnings ?? []) log(line);
397
542
  const boundPlates = bindOccluderPlates({ occluders: cfg.assemble.occluders, configPath: input.config, sourcePath: input.source, fullPath: input.full });
398
543
  if (boundPlates.length > 0) result.parts.occluder_plates = boundPlates;
399
544
  }
@@ -620,7 +765,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
620
765
  const altExtend: Extend[] = altRuns.single ? [] : fields.extend.filter((e) => altPlanNames.has(e.part));
621
766
  const altPatches: Patch[] = fields.patches.filter((p) => coveredSet.has(p.name)).map((p) => ({ ...p, draw: remapDraw(p.draw) }));
622
767
  const altCuts: Cut[] = rawCuts.map((c) => ({ ...c, draw: remapDraw(c.draw) }));
623
- 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);
624
770
  const altHeadBox = alt.head_box ?? (altRuns.single ? singleRunHeadBox(altSrc.width, altSrc.height, fields.resolution) : fields.headBox);
625
771
  let altBones = fields.bones;
626
772
  let altDrawnLength: Record<string, number> | undefined;
@@ -784,6 +930,11 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
784
930
  }
785
931
  throw err;
786
932
  }
933
+ const altMaskProblems = verifyUnderPlateMasks(altRes, altCuts, altUnderPlates, `${alt.at}.cuts`);
934
+ if (altMaskProblems.length > 0) {
935
+ altProblems.push(...altMaskProblems);
936
+ continue;
937
+ }
787
938
  const keptImages = altRes.images
788
939
  .filter(({ record }) => coveredSet.has(record.name))
789
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
@@ -1813,7 +1822,7 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null, p
1813
1822
  checkOccluders(c, a, null, base);
1814
1823
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
1815
1824
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, Array.isArray(a.plan) ? new Set(a.plan.filter((r): r is Json[] => Array.isArray(r) && typeof r[0] === 'string').map(r => r[0] as string)) : null);
1816
- if ('take' in a) checkTakeLayers(c, a.take);
1825
+ if ('take' in a) checkTakeLayers(c, a.take, null, a);
1817
1826
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
1818
1827
  if ('yield_refused' in a && typeof a.yield_refused !== 'boolean') {
1819
1828
  c.fail('CONFIG_FIELD_TYPE', 'config.assemble.yield_refused', `is ${show(a.yield_refused)}; true or false is required`);
@@ -2572,18 +2581,19 @@ function checkRequiredHiddenExtent(c: Check, a: Record<string, Json>, names: rea
2572
2581
  }
2573
2582
 
2574
2583
  /**
2575
- * Issue #1230 / #1241: `config.assemble.occluders`, `[{image, sha256, under, over?, rgb_within}]`. Shape at every door; `under`
2576
- * and `over` resolved against the plan where the door reads it; the file and its sha256 where the door knows the config's
2577
- * directory (`checkOccluderFiles`).
2584
+ * Issue #1230 / #1241 / #1246 / #1251: `config.assemble.occluders`, `[{image, sha256, under, over?, rgb_within, plate?, part?, grow?}]`.
2585
+ * Shape at every door; `under`, `over` and `part` resolved against the plan where the door reads it; the file and its
2586
+ * sha256 where the door knows the config's directory (`checkOccluderFiles`). Returns the declared `part` names, in order.
2578
2587
  */
2579
- function checkOccluders(c: Check, a: Record<string, Json>, names: readonly string[] | null, base: string | null): void {
2580
- if (!('occluders' in a)) return;
2588
+ function checkOccluders(c: Check, a: Record<string, Json>, names: readonly string[] | null, base: string | null): string[] {
2589
+ if (!('occluders' in a)) return [];
2581
2590
  const at = 'config.assemble.occluders';
2582
- if (!c.array(at, a.occluders, false)) return;
2591
+ if (!c.array(at, a.occluders, false)) return [];
2583
2592
  const declarations: OccluderDeclaration[] = [];
2593
+ const partNames: string[] = [];
2584
2594
  (a.occluders as Json[]).forEach((value, i) => {
2585
2595
  const p = `${at}[${i}]`;
2586
- const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], ['over', 'plate']);
2596
+ const row = c.object(p, value, ['image', 'sha256', 'under', 'rgb_within'], ['over', 'plate', 'part', 'grow']);
2587
2597
  if (row === null) return;
2588
2598
  const imageOk = c.string(`${p}.image`, row.image);
2589
2599
  const shaOk = typeof row.sha256 === 'string' && SHA256_PATTERN.test(row.sha256);
@@ -2598,12 +2608,34 @@ function checkOccluders(c: Check, a: Record<string, Json>, names: readonly strin
2598
2608
  const rgbOk = typeof row.rgb_within === 'number' && Number.isInteger(row.rgb_within) && row.rgb_within >= 0 && row.rgb_within <= 255;
2599
2609
  if (!rgbOk) c.fail('CONFIG_FIELD_TYPE', `${p}.rgb_within`, `is ${show(row.rgb_within)}; an integer from 0 to 255 is required`);
2600
2610
  const plateOk = !('plate' in row) || c.string(`${p}.plate`, row.plate);
2601
- if (imageOk && shaOk && underOk && overOk && rgbOk && plateOk) {
2602
- 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 } : {}) });
2611
+ let partOk = true;
2612
+ let partName: string | undefined;
2613
+ if ('part' in row) {
2614
+ partOk = c.string(`${p}.part`, row.part);
2615
+ if (partOk) {
2616
+ partName = row.part as string;
2617
+ if (!partNameOk(partName)) {
2618
+ c.fail('CONFIG_PART_NAME', `${p}.part`, `names the part ${show(partName)}; a part name is a file name, so it may not be empty, start with "." or hold a slash`);
2619
+ partOk = false;
2620
+ } else {
2621
+ partNames.push(partName);
2622
+ }
2623
+ }
2624
+ }
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
+ if (imageOk && shaOk && underOk && overOk && rgbOk && plateOk && partOk && growOk) {
2633
+ 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 } : {}) });
2603
2634
  }
2604
2635
  });
2605
2636
  c.problems.push(...occluderNameProblems(declarations, names));
2606
2637
  if (base !== null) c.problems.push(...occluderFileProblems(declarations, base));
2638
+ return partNames;
2607
2639
  }
2608
2640
 
2609
2641
  /** The occluder files, at the doors that know the config's directory but read the plan elsewhere. */
@@ -2630,16 +2662,19 @@ function checkKeepUnderOccluders(c: Check, a: Record<string, Json>, plan: readon
2630
2662
  });
2631
2663
  }
2632
2664
 
2633
- function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null): void {
2665
+ function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null, assemble?: Record<string, Json>): void {
2634
2666
  const at = 'config.assemble.take';
2635
2667
  if (!c.array(at, value, false)) return;
2636
2668
  const seen = new Set<string>();
2637
2669
  (value as Json[]).forEach((v, i) => {
2638
2670
  const p = `${at}[${i}]`;
2639
- const region = isPlainObject(v) && ('part' in v || 'seed' in v);
2640
- const o = region
2641
- ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'seed'], ['reference', 'crop'])
2642
- : c.object(p, v, ['run', 'run_dir', 'st_input', 'tags'], ['crop']);
2671
+ const split = isPlainObject(v) && ('occluder' in v || ('tag' in v && !('tags' in v)));
2672
+ const region = !split && isPlainObject(v) && ('part' in v || 'seed' in v);
2673
+ const o = split
2674
+ ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'tag', 'occluder'], ['crop'])
2675
+ : region
2676
+ ? c.object(p, v, ['run', 'run_dir', 'st_input', 'part', 'seed'], ['reference', 'crop'])
2677
+ : c.object(p, v, ['run', 'run_dir', 'st_input', 'tags'], ['crop']);
2643
2678
  if (o === null) return;
2644
2679
  if (o.run !== 'full' && o.run !== 'head') c.fail('CONFIG_FIELD_TYPE', p + '.run', '"full" or "head" is required');
2645
2680
  for (const k of ['run_dir', 'st_input']) c.string(`${p}.${k}`, o[k]);
@@ -2651,6 +2686,44 @@ function checkTakeLayers(c: Check, value: Json, plan: string[] | null = null): v
2651
2686
  if (crop.resample !== 'bilinear') c.fail('CONFIG_FIELD_TYPE', `${p}.crop.resample`, '"bilinear" is required explicitly');
2652
2687
  }
2653
2688
  }
2689
+ if (split) {
2690
+ const partName = c.string(`${p}.part`, o.part) ? o.part : null;
2691
+ if (partName !== null && plan !== null && !plan.includes(partName)) {
2692
+ c.fail('CONFIG_NAME_RESOLVES', `${p}.part`, `names "${partName}"; a part named in assemble.plan is required`);
2693
+ }
2694
+ const reading = typeof o.tag === 'string' ? readLayerTag(o.tag) : null;
2695
+ if (reading === null || reading.group === 'author') {
2696
+ c.fail('CONFIG_TAG_KNOWN', `${p}.tag`, 'a See-through tag is required; author layers do not carry a See-through role');
2697
+ } else if (partName !== null && plan !== null && plan.includes(partName) && Array.isArray(assemble?.plan)) {
2698
+ const row = assemble.plan.find((r): r is Json[] => Array.isArray(r) && r[0] === partName);
2699
+ if (row !== undefined && (row[1] !== o.run || row[2] !== o.tag)) {
2700
+ c.fail('CONFIG_NAME_RESOLVES', `${p}.tag`, `is "${String(o.run)}:${String(o.tag)}" for part "${partName}"; assemble.plan declares ["${partName}", "${String(row[1])}", "${String(row[2])}"]`);
2701
+ }
2702
+ }
2703
+ const tagKey = `${String(o.run)}:${String(o.tag)}`;
2704
+ const partKey = `${String(o.run)}:part:${String(o.part)}`;
2705
+ if (seen.has(tagKey) || seen.has(partKey)) {
2706
+ c.fail('CONFIG_TAKE_UNIQUE', `${p}.tag`, `names ${tagKey} again; one donor per target tag is required`);
2707
+ }
2708
+ seen.add(tagKey);
2709
+ seen.add(partKey);
2710
+ const occOk = c.int(`${p}.occluder`, o.occluder, 0);
2711
+ if (occOk && partName !== null && assemble !== undefined) {
2712
+ const occluders = Array.isArray(assemble.occluders) ? assemble.occluders : [];
2713
+ const idx = o.occluder as number;
2714
+ const entry = occluders[idx];
2715
+ const under = isPlainObject(entry) && Array.isArray(entry.under) ? entry.under : null;
2716
+ const over = isPlainObject(entry) && Array.isArray(entry.over) ? entry.over : [];
2717
+ if (!isPlainObject(entry) || under === null) {
2718
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.occluder`, `index ${idx} does not exist in config.assemble.occluders (${occluders.length} declared); a valid occluder index is required`);
2719
+ } else if (over.includes(partName)) {
2720
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.part`, `names "${partName}", which is in config.assemble.occluders[${idx}].over; a split take is for a part under the occluder, not in its over`);
2721
+ } else if (!under.includes(partName)) {
2722
+ c.fail('ASSEMBLE_TAKE_SPLIT_OCCLUDER', `${p}.part`, `names "${partName}", which is not in config.assemble.occluders[${idx}].under; a part declared under that occluder is required`);
2723
+ }
2724
+ }
2725
+ return;
2726
+ }
2654
2727
  if (region) {
2655
2728
  if (o.reference !== undefined) {
2656
2729
  const r = c.object(`${p}.reference`, o.reference, ['sha256'], ['source', 'painting']);
@@ -2776,10 +2849,10 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2776
2849
  }
2777
2850
  checkKeepUnderOccluders(c, a, parts);
2778
2851
  checkRequiredHiddenExtent(c, a, parts);
2779
- checkOccluders(c, a, parts, null);
2852
+ const occluderParts = checkOccluders(c, a, parts, null);
2780
2853
  if ('extend_painting' in a) checkPaintingExtensions(c, a.extend_painting);
2781
2854
  if ('edge_splits' in a) checkEdgeSplits(c, a.edge_splits, new Set(parts));
2782
- if ('take' in a) checkTakeLayers(c, a.take, parts);
2855
+ if ('take' in a) checkTakeLayers(c, a.take, parts, a);
2783
2856
  if ('editor_receipts' in a) checkEditorReceipts(c, a.editor_receipts);
2784
2857
  if ('extend_below_crop' in a && c.array(`${p}.extend_below_crop`, a.extend_below_crop, false)) {
2785
2858
  (a.extend_below_crop as Json[]).forEach((entry, i) => {
@@ -2801,7 +2874,7 @@ function checkAssemble(c: Check, v: Json, door: 'assemble' | 'full'): { parts: s
2801
2874
  }
2802
2875
  });
2803
2876
  }
2804
- const patches = 'patches' in a ? checkPatches(c, a.patches, parts) : [];
2877
+ const patches = [...('patches' in a ? checkPatches(c, a.patches, parts, occluderParts) : []), ...occluderParts];
2805
2878
  const cuts = 'cuts' in a ? checkCuts(c, a.cuts, parts, patches) : [];
2806
2879
  return { parts, patches, cuts };
2807
2880
  }
@@ -2824,8 +2897,13 @@ function checkCuts(c: Check, v: Json, plan: string[], patches: string[], p = 'co
2824
2897
  const at = `${p}[${i}]`;
2825
2898
  const e = c.object(at, entry, ['from', 'into', 'polygon', 'draw', 'overlap'], ['under', 'under_fill']);
2826
2899
  if (e === null) return;
2827
- if ('under' in e && !(typeof e.under === 'string' && e.under !== '')) {
2828
- 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`);
2900
+ if ('under' in e) {
2901
+ if (typeof e.under === 'object' && e.under !== null && !Array.isArray(e.under)) {
2902
+ const u = c.object(`${at}.under`, e.under, ['plate'], []);
2903
+ if (u !== null && 'plate' in u) c.string(`${at}.under.plate`, u.plate);
2904
+ } else if (!(typeof e.under === 'string' && e.under !== '')) {
2905
+ 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`);
2906
+ }
2829
2907
  }
2830
2908
  if ('under_fill' in e && e.under_fill !== 'colour') {
2831
2909
  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`);
@@ -3129,7 +3207,7 @@ function checkAlternates(
3129
3207
  * (`ASSEMBLE_PATCH_BOX_INSIDE`, `ASSEMBLE_PATCH_OPAQUE`). Returns the patch
3130
3208
  * names, in order.
3131
3209
  */
3132
- function checkPatches(c: Check, v: Json, plan: string[]): string[] {
3210
+ function checkPatches(c: Check, v: Json, plan: string[], occluderParts: readonly string[] = []): string[] {
3133
3211
  const p = 'config.assemble.patches';
3134
3212
  const names: string[] = [];
3135
3213
  if (!c.array(p, v, false)) return names;
@@ -3150,6 +3228,7 @@ function checkPatches(c: Check, v: Json, plan: string[]): string[] {
3150
3228
  const name = e.name;
3151
3229
  if (!partNameOk(name)) c.fail('CONFIG_PART_NAME', `${at}.name`, `names the part ${show(name)}; a part name is a file name, so it may not be empty, start with "." or hold a slash`);
3152
3230
  if (plan.includes(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}", which assemble.plan[${plan.indexOf(name)}] already makes; a patch is a part of its own`);
3231
+ else if (occluderParts.includes(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}", which assemble.occluders already makes; a patch is a part of its own`);
3153
3232
  else if (seen.has(name)) c.fail('CONFIG_PART_UNIQUE', `${at}.name`, `names the part "${name}" again (first at patches[${seen.get(name)}])`);
3154
3233
  else seen.set(name, i);
3155
3234
  names.push(name);
@@ -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/occluders.ts CHANGED
@@ -34,6 +34,10 @@ export interface OccluderDeclaration {
34
34
  rgb_within: number;
35
35
  /** An optional comfy plate --mode occluder output directory, relative to the config's directory (issue #1237). */
36
36
  plate?: string;
37
+ /** An optional part name (`painting:<part>`) emitted from the painting for occluder pixels not held at rest by front parts (issue #1246). */
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;
37
41
  }
38
42
 
39
43
  export const OCCLUDER_COLOUR_COPIED = 'ASSEMBLE_OCCLUDER_COLOUR_COPIED';
@@ -43,6 +47,8 @@ export const OCCLUDER_OVER_TAKEN = 'ASSEMBLE_OCCLUDER_OVER_TAKEN';
43
47
  export const OCCLUDER_PLATE_OCCLUDER = 'ASSEMBLE_OCCLUDER_PLATE_OCCLUDER';
44
48
  export const OCCLUDER_PLATE_PAINTING = 'ASSEMBLE_OCCLUDER_PLATE_PAINTING';
45
49
  export const OCCLUDER_PLATE_BASE_RUN = 'ASSEMBLE_OCCLUDER_PLATE_BASE_RUN';
50
+ export const OCCLUDER_EMPTY = 'ASSEMBLE_OCCLUDER_EMPTY';
51
+ export const OCCLUDER_UNHELD = 'ASSEMBLE_OCCLUDER_UNHELD';
46
52
  /** An `under` layer pixel counts at alpha above this: the half-opaque floor `deriveTakenRegion` reads. */
47
53
  export const COPIED_ALPHA_ABOVE = 128;
48
54
 
@@ -183,9 +189,10 @@ export function occluderOverTakenProblems(
183
189
  return problems;
184
190
  }
185
191
 
186
- /** Every `under` and `over` entry names a plan part (`CONFIG_NAME_RESOLVES`, with `over` entries distinct per occluder, `CONFIG_PART_UNIQUE`); `names` null skips the plan-membership check (a door without the plan). */
192
+ /** Every `under` and `over` entry names a plan part (`CONFIG_NAME_RESOLVES`, with `over` entries distinct per occluder, `CONFIG_PART_UNIQUE`), and any declared `part` is distinct from plan parts and other occluder parts (`CONFIG_PART_UNIQUE`); `names` null skips the plan-membership check (a door without the plan). */
187
193
  export function occluderNameProblems(declarations: readonly OccluderDeclaration[], names: readonly string[] | null): Problem[] {
188
194
  const problems: Problem[] = [];
195
+ const seenParts = new Map<string, number>();
189
196
  declarations.forEach((d, i) => {
190
197
  if (d.over !== undefined) {
191
198
  const seen = new Set<string>();
@@ -194,6 +201,17 @@ export function occluderNameProblems(declarations: readonly OccluderDeclaration[
194
201
  seen.add(name);
195
202
  });
196
203
  }
204
+ if (d.part !== undefined && d.part !== '') {
205
+ if (names !== null && names.includes(d.part)) {
206
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}", which assemble.plan[${names.indexOf(d.part)}] already makes; an occluder part is a part of its own` });
207
+ } else if (names === null && (d.under.includes(d.part) || (d.over?.includes(d.part) ?? false))) {
208
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}", which occluders[${i}] also names in under/over; an occluder part is a part of its own` });
209
+ } else if (seenParts.has(d.part)) {
210
+ problems.push({ code: 'CONFIG_PART_UNIQUE', object: `${AT}[${i}].part`, detail: `names the part "${d.part}" again (first at occluders[${seenParts.get(d.part)}].part)` });
211
+ } else {
212
+ seenParts.set(d.part, i);
213
+ }
214
+ }
197
215
  if (names === null) return;
198
216
  d.under.forEach((name, j) => {
199
217
  if (!names.includes(name)) problems.push({ code: 'CONFIG_NAME_RESOLVES', object: `${AT}[${i}].under[${j}]`, detail: `names "${name}"; a part in config.assemble.plan is required` });
@@ -230,6 +248,75 @@ export function occluderFileProblems(declarations: readonly OccluderDeclaration[
230
248
  return problems;
231
249
  }
232
250
 
251
+ /**
252
+ * Reorder a draft `assemble.plan` in place so each declared `occluders[i].over`
253
+ * part sits after every `under` part of the same entry across `full` and `head`
254
+ * rows, keeping every other row's relative order unchanged (issues #1247, #1251).
255
+ *
256
+ * A declared `over` or `under` name matches a proposed row whose name (`row[0]`)
257
+ * equals it, or whose See-through tag (`row[2]`) equals `takenTags[name]` (the
258
+ * tag of the config's taken layer for that name). Any `over` or `under` name on
259
+ * an entry with `over` that matches no proposed row is returned as a note for
260
+ * `proposal.notes`.
261
+ */
262
+ export function orderPlanForOccluders<T extends readonly [string, ...unknown[]]>(
263
+ plan: T[],
264
+ declarations: readonly OccluderDeclaration[] | undefined,
265
+ takenTags?: Readonly<Record<string, string>>,
266
+ ): string[] {
267
+ if (declarations === undefined || declarations.length === 0) return [];
268
+ const matchesRow = (row: T, name: string): boolean => {
269
+ if (row[0] === name) return true;
270
+ const tag = takenTags?.[name];
271
+ return tag !== undefined && typeof row[2] === 'string' && row[2] === tag;
272
+ };
273
+ const matchesSet = (row: T, names: ReadonlySet<string>): boolean => {
274
+ for (const name of names) {
275
+ if (matchesRow(row, name)) return true;
276
+ }
277
+ return false;
278
+ };
279
+ const notes: string[] = [];
280
+ declarations.forEach((d, i) => {
281
+ if (d.over === undefined || d.over.length === 0) return;
282
+ for (const name of d.under) {
283
+ if (!plan.some((row) => matchesRow(row, name))) {
284
+ notes.push(`occluders[${i}].under "${name}" matched no proposed row`);
285
+ }
286
+ }
287
+ for (const name of d.over) {
288
+ if (!plan.some((row) => matchesRow(row, name))) {
289
+ notes.push(`occluders[${i}].over "${name}" matched no proposed row`);
290
+ }
291
+ }
292
+ });
293
+ for (let pass = 0; pass <= plan.length; pass++) {
294
+ let moved = false;
295
+ for (const d of declarations) {
296
+ if (d.over === undefined || d.over.length === 0) continue;
297
+ const underSet = new Set(d.under);
298
+ let lastUnder = -1;
299
+ for (let i = 0; i < plan.length; i++) {
300
+ if (matchesSet(plan[i], underSet)) lastUnder = i;
301
+ }
302
+ if (lastUnder < 0) continue;
303
+ const overSet = new Set(d.over);
304
+ const beforeOver: T[] = [];
305
+ const keptBefore: T[] = [];
306
+ for (let i = 0; i < lastUnder; i++) {
307
+ if (matchesSet(plan[i], overSet)) beforeOver.push(plan[i]);
308
+ else keptBefore.push(plan[i]);
309
+ }
310
+ if (beforeOver.length === 0) continue;
311
+ const after = plan.slice(lastUnder + 1);
312
+ plan.splice(0, plan.length, ...keptBefore, plan[lastUnder], ...beforeOver, ...after);
313
+ moved = true;
314
+ }
315
+ if (!moved) break;
316
+ }
317
+ return notes;
318
+ }
319
+
233
320
  export interface OccluderCopy {
234
321
  part: string;
235
322
  px: number;
@@ -265,3 +352,7 @@ export function occluderColourCopies(parts: ReadonlyArray<{ name: string; image:
265
352
  export function occluderColourWarning(index: number, copy: OccluderCopy, rgbWithin: number): string {
266
353
  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)`;
267
354
  }
355
+
356
+ export function occluderUnheldWarning(index: number, image: string, under: readonly string[], px: number, first: readonly [number, number], coreAlpha: number): string {
357
+ 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`;
358
+ }