@rig-c/parts 2.34.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/assemble.ts CHANGED
@@ -123,7 +123,8 @@ import { foldName, PartsError, type Problem, refuseIfAny } from './errors.ts';
123
123
  import { CORE_ALPHA, figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
124
124
  import { padToSquare, squarePad } from './inputs.ts';
125
125
  import type { MotionSeamDeclaration } from './motionseams.ts';
126
- import { type CapRecord, type LimbRecord, FIGURE_MASK_FILE, PAINTING_RUN, type PartRecord, type PartsFile, type RecompositeRecord, type SceneRecord, type SingleRunPad } from './parts.ts';
126
+ import { type CapRecord, type LimbRecord, FIGURE_MASK_FILE, type OccluderGrowRecord, PAINTING_RUN, type PartRecord, type PartsFile, type RecompositeRecord, type SceneRecord, type SingleRunPad } from './parts.ts';
127
+ import { growMask } from './plate.ts';
127
128
  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';
128
129
  import {
129
130
  alphaComposite,
@@ -240,6 +241,10 @@ export interface Geometry {
240
241
  keepUnderOccluders?: readonly string[];
241
242
  /** `assemble.occluders` as declared (issue #1247; `AssembleInput.occluders` carries the decoded images): declared occluder entries whose `over` parts sit after their `under` parts in a proposed plan. */
242
243
  occluderDeclarations?: readonly OccluderDeclaration[];
244
+ /** Declared part/tag name -> taken layer See-through tag for `orderPlanForOccluders` (issue #1251). */
245
+ occluderTakenTags?: Readonly<Record<string, string>>;
246
+ /** Occluder-split takes (issue #1251, Codex review): the proposed row for `tag` on `run` keeps the take's declared `part` name, so the proposal assembles. */
247
+ occluderSplitParts?: ReadonlyArray<{ run: Run; part: string; tag: string }>;
243
248
  }
244
249
 
245
250
  /**
@@ -3770,6 +3775,35 @@ export function underBox(polygon: ReadonlyArray<readonly [number, number]>): { x
3770
3775
  return { x0, y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 };
3771
3776
  }
3772
3777
 
3778
+ /**
3779
+ * Issue #1230: the fill mask on the painting's grid (`sourceW x sourceH`) for a
3780
+ * cut piece `piece` (in rig space, `polygon ∩ from alpha > 0`, including the
3781
+ * overlap band): opaque white `[255, 255, 255, 255]` where a painting pixel
3782
+ * whose sampled rig pixel has `alpha > 0` (identity at `rig_scale: 1`), and
3783
+ * transparent `[0, 0, 0, 0]` everywhere else.
3784
+ */
3785
+ export function cutFillMask(piece: Raster, sourceW: number, sourceH: number): Raster {
3786
+ const { width: W, height: H } = piece;
3787
+ // Issue #1230: each painting pixel reads the rig pixel it samples, so the mask covers the
3788
+ // piece's whole footprint on the painting grid at any rig_scale (a forward rig -> painting
3789
+ // mapping leaves gaps whenever the rig is smaller than the painting).
3790
+ const rigX = (sx: number): number => Math.min(W - 1, Math.floor((sx + 0.5) * W / sourceW));
3791
+ const rigY = (sy: number): number => Math.min(H - 1, Math.floor((sy + 0.5) * H / sourceH));
3792
+ const mask = newRaster(sourceW, sourceH);
3793
+ for (let sy = 0; sy < sourceH; sy++) {
3794
+ const ry = rigY(sy);
3795
+ for (let sx = 0; sx < sourceW; sx++) {
3796
+ if (piece.data[(ry * W + rigX(sx)) * 4 + 3] === 0) continue;
3797
+ const q = (sy * sourceW + sx) * 4;
3798
+ mask.data[q] = 255;
3799
+ mask.data[q + 1] = 255;
3800
+ mask.data[q + 2] = 255;
3801
+ mask.data[q + 3] = 255;
3802
+ }
3803
+ }
3804
+ return mask;
3805
+ }
3806
+
3773
3807
  /**
3774
3808
  * Fill the base where a cut removed its pixels (issue #193). The removed
3775
3809
  * pixels are those the piece holds (alpha above 0) and the band does not —
@@ -4800,6 +4834,8 @@ export interface AssembleResult {
4800
4834
  edgeSplits: EdgeSplitReading[];
4801
4835
  /** Issue #1246: `ASSEMBLE_OCCLUDER_UNHELD` WARN lines when `part` is omitted and occluder px are unheld at rest. */
4802
4836
  occluderUnheldWarnings?: string[];
4837
+ /** Issue #1230: each cut's derived fill mask on the painting's grid (`source.width x source.height`), in cut order; present when `cuts` is non-empty. */
4838
+ cutFillMasks?: Array<{ into: string; from: string; mask: Raster }>;
4803
4839
  }
4804
4840
 
4805
4841
  /** Issue #953: the edge pixels `paintingEdges` resolved, the part pixels it changed, and the edge pixels it left, by reason. */
@@ -4854,7 +4890,7 @@ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[]
4854
4890
  }
4855
4891
 
4856
4892
  /** `r`'s pixels over the box `[x0, y0, w, h]`, transparent where the box reaches past `r`. */
4857
- function boxOf(r: Raster, x0: number, y0: number, w: number, h: number): Raster {
4893
+ export function boxOf(r: Raster, x0: number, y0: number, w: number, h: number): Raster {
4858
4894
  const out = newRaster(w, h);
4859
4895
  for (let y = 0; y < h; y++) {
4860
4896
  const sy = y0 + y;
@@ -5073,19 +5109,38 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5073
5109
  const groundShare = groundRingShare(srcr, supportPainted);
5074
5110
  const occSx = (x: number): number => Math.min(source.width - 1, Math.floor((x + 0.5) * source.width / W));
5075
5111
  const occSy = (y: number): number => Math.min(source.height - 1, Math.floor((y + 0.5) * source.height / H));
5112
+ const occluderGrowRecords: OccluderGrowRecord[] = [];
5076
5113
  const occluderEntries = (input.occluders ?? []).map(({ declaration, image }, index) => {
5077
- const opaqueMask = newMask(W, H);
5078
- const copiedMask = newMask(W, H);
5114
+ const coreBefore = newMask(W, H);
5115
+ let coveredBefore = 0;
5079
5116
  for (let y = 0; y < H; y++) {
5080
5117
  const srcY = occSy(y);
5081
5118
  for (let x = 0; x < W; x++) {
5082
5119
  const a = image.data[(srcY * source.width + occSx(x)) * 4 + 3];
5083
5120
  const p = y * W + x;
5084
- if (a > OPAQUE_ALPHA_ABOVE) opaqueMask.data[p] = 1;
5085
- if (a > COPIED_ALPHA_ABOVE) copiedMask.data[p] = 1;
5121
+ if (a > COPIED_ALPHA_ABOVE) {
5122
+ coreBefore.data[p] = 1;
5123
+ coveredBefore++;
5124
+ }
5086
5125
  }
5087
5126
  }
5088
- return { index, declaration, opaqueMask, copiedMask };
5127
+ const grow = declaration.grow ?? 0;
5128
+ let copiedMask = coreBefore;
5129
+ if (grow > 0) {
5130
+ const grown = growMask({ width: W, height: H, inside: coreBefore.data }, grow);
5131
+ copiedMask = newMask(W, H);
5132
+ copiedMask.data.set(grown.inside);
5133
+ let coveredAfter = 0;
5134
+ for (let p = 0; p < W * H; p++) if (copiedMask.data[p] === 1) coveredAfter++;
5135
+ occluderGrowRecords.push({
5136
+ occluder: index,
5137
+ image: declaration.image,
5138
+ grow,
5139
+ covered_px_before: coveredBefore,
5140
+ covered_px_after: coveredAfter,
5141
+ });
5142
+ }
5143
+ return { index, declaration, copiedMask };
5089
5144
  });
5090
5145
  const occluderUnderKeepByPlanPart = new Map<string, Mask>();
5091
5146
  if (projectRule === 'visible') {
@@ -5106,11 +5161,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5106
5161
  const hiddenUses = new Map<string, string[]>();
5107
5162
  for (const [run, set] of single ? ([['full', full]] as const) : ([['full', full], ['head', head]] as const)) for (const h of set.hidden) hiddenUses.set(`${run}:${h.name}`, []);
5108
5163
  const hiddenProblems: Problem[] = [];
5164
+ const showCutUnder = (u: Cut['under']): string => typeof u === 'object' && u !== null ? `{"plate": ${JSON.stringify(u.plate)}}` : String(u);
5109
5165
  const unders = input.cuts.map((q, i) => {
5110
5166
  const art = hiddenArt.get(q.from);
5111
5167
  if (art === undefined) return input.under?.[i] ?? null;
5112
5168
  if (q.under !== undefined) {
5113
- hiddenProblems.push({ code: 'ASSEMBLE_HIDDEN_ONE_SOURCE', object: `config.assemble.cuts[${i}].under (part "${q.into}")`, detail: `names ${q.under}, and "${q.from}" also has the hidden-art layer ${art.layer}; one source of what lies under the piece is required — remove under, or the hidden-art layer` });
5169
+ hiddenProblems.push({ code: 'ASSEMBLE_HIDDEN_ONE_SOURCE', object: `config.assemble.cuts[${i}].under (part "${q.into}")`, detail: `names ${showCutUnder(q.under)}, and "${q.from}" also has the hidden-art layer ${art.layer}; one source of what lies under the piece is required — remove under, or the hidden-art layer` });
5114
5170
  return null;
5115
5171
  }
5116
5172
  const box = underBox(q.polygon);
@@ -5374,7 +5430,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5374
5430
  const object = `config.assemble.cuts[${i}].under (part "${q.into}")`;
5375
5431
  const u = unders[i];
5376
5432
  if (u === null) {
5377
- patchProblems.push({ code: 'ASSEMBLE_UNDER_PRESENT', object, detail: `names ${q.under}, and no image was handed to the stage for it; the decoded PNG is required (a caller of assemble() reads the file)` });
5433
+ patchProblems.push({ code: 'ASSEMBLE_UNDER_PRESENT', object, detail: `names ${showCutUnder(q.under)}, and no image was handed to the stage for it; the decoded PNG is required (a caller of assemble() reads the file)` });
5378
5434
  return;
5379
5435
  }
5380
5436
  const box = underBox(q.polygon);
@@ -5382,7 +5438,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5382
5438
  patchProblems.push({
5383
5439
  code: 'ASSEMBLE_UNDER_SIZE',
5384
5440
  object,
5385
- detail: `${q.under} is ${u.width}x${u.height}; the polygon's bounding box is ${box.w}x${box.h} at ${box.x0},${box.y0} (least and greatest polygon x and y, in rig pixels), and an image of exactly that size is required — its pixel (i, j) is rig pixel (${box.x0} + i, ${box.y0} + j)`,
5441
+ detail: `${showCutUnder(q.under)} is ${u.width}x${u.height}; the polygon's bounding box is ${box.w}x${box.h} at ${box.x0},${box.y0} (least and greatest polygon x and y, in rig pixels), and an image of exactly that size is required — its pixel (i, j) is rig pixel (${box.x0} + i, ${box.y0} + j)`,
5386
5442
  });
5387
5443
  }
5388
5444
  const at = order0.findIndex((d) => 'cut' in d && d.cut === i);
@@ -5588,7 +5644,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5588
5644
  empty.push({
5589
5645
  code: 'ASSEMBLE_UNDER_EMPTY',
5590
5646
  object: `config.assemble.cuts[${i}].under (part "${cuts[i].into}")`,
5591
- detail: `${cuts[i].under} fills 0 of the ${f.empty} pixel(s) the cut removed from "${name}": at every one its alpha is below the alpha removed (an all-transparent image, or another file); an image that fills at least one is required — to leave the whole hole, drop under`,
5647
+ detail: `${showCutUnder(cuts[i].under)} fills 0 of the ${f.empty} pixel(s) the cut removed from "${name}": at every one its alpha is below the alpha removed (an all-transparent image, or another file); an image that fills at least one is required — to leave the whole hole, drop under`,
5592
5648
  });
5593
5649
  }
5594
5650
  return { ...f, opaqueFilled };
@@ -5607,6 +5663,11 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5607
5663
  if (piece !== null) { materialSources.push(materialSource(cuts[i].into, [b.key], polygonMaterialEdges(cuts[i].polygon), [sourceBeforeCuts])); cutMaterial.push(...materialRows(cuts[i].into, undefined, polygonMaterialEdges(cuts[i].polygon), [sourceBeforeCuts], [{ x: 0, y: 0, image: piece.r }])); }
5608
5664
  });
5609
5665
  });
5666
+ const cutFillMasks = cuts.map((q, i) => ({
5667
+ into: q.into,
5668
+ from: q.from,
5669
+ mask: pieces[i] === null ? newRaster(source.width, source.height) : cutFillMask((pieces[i] as Built).r, source.width, source.height),
5670
+ }));
5610
5671
  // Parent partition counts and under use the removed parent art above. Only
5611
5672
  // the emitted piece (and any limb cut from it) reads this independent source.
5612
5673
  cutSources.forEach((source, i) => {
@@ -6070,30 +6131,34 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6070
6131
  const stackCanvases = occluderEntries.length === 0 ? [] : stack.map(onRig);
6071
6132
  const occluderWithSlot = occluderEntries.map((entry) => {
6072
6133
  let lastUnderIdx = -1;
6134
+ let firstOverIdx = -1;
6073
6135
  order.forEach((d, idx) => {
6074
6136
  const root = rootPlanPartOfSlot(d);
6075
- if (root !== null && entry.declaration.under.includes(root)) lastUnderIdx = idx;
6137
+ if (root === null) return;
6138
+ if (entry.declaration.under.includes(root)) lastUnderIdx = idx;
6139
+ if (firstOverIdx < 0 && (entry.declaration.over?.includes(root) ?? false)) firstOverIdx = idx;
6076
6140
  });
6077
- return { ...entry, lastUnderIdx };
6141
+ const insertBeforeIdx = firstOverIdx >= 0 ? firstOverIdx : lastUnderIdx + 1;
6142
+ return { ...entry, lastUnderIdx, firstOverIdx, insertBeforeIdx };
6078
6143
  });
6079
- const builtOccluderParts: Array<{ index: number; lastUnderIdx: number; canvas: Raster; placed: PlacedPart }> = [];
6080
- for (const entry of [...occluderWithSlot].filter((e) => e.declaration.part !== undefined).sort((a, b) => b.lastUnderIdx - a.lastUnderIdx || b.index - a.index)) {
6144
+ const builtOccluderParts: Array<{ index: number; insertBeforeIdx: number; canvas: Raster; placed: PlacedPart }> = [];
6145
+ for (const entry of [...occluderWithSlot].filter((e) => e.declaration.part !== undefined).sort((a, b) => b.insertBeforeIdx - a.insertBeforeIdx || b.index - a.index)) {
6081
6146
  const partName = entry.declaration.part!;
6082
6147
  const occCanvas = newRaster(W, H);
6083
6148
  const occVisible = newMask(W, H);
6084
6149
  const occProjected = newMask(W, H);
6085
6150
  for (let p = 0; p < W * H; p++) {
6086
- if (entry.opaqueMask.data[p] !== 1) continue;
6151
+ if (entry.copiedMask.data[p] !== 1) continue;
6087
6152
  let heldInFront = false;
6088
- for (let j = entry.lastUnderIdx + 1; j < stackCanvases.length; j++) {
6089
- if (stackCanvases[j].data[p * 4 + 3] > COPIED_ALPHA_ABOVE) {
6153
+ for (let j = entry.insertBeforeIdx; j < stackCanvases.length; j++) {
6154
+ if (stackCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
6090
6155
  heldInFront = true;
6091
6156
  break;
6092
6157
  }
6093
6158
  }
6094
6159
  if (!heldInFront) {
6095
6160
  for (const frontOcc of builtOccluderParts) {
6096
- if ((frontOcc.lastUnderIdx > entry.lastUnderIdx || (frontOcc.lastUnderIdx === entry.lastUnderIdx && frontOcc.index > entry.index)) && frontOcc.canvas.data[p * 4 + 3] > COPIED_ALPHA_ABOVE) {
6161
+ if ((frontOcc.insertBeforeIdx > entry.insertBeforeIdx || (frontOcc.insertBeforeIdx === entry.insertBeforeIdx && frontOcc.index > entry.index)) && frontOcc.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6097
6162
  heldInFront = true;
6098
6163
  break;
6099
6164
  }
@@ -6109,7 +6174,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6109
6174
  if (opaque === 0 && emptyTargets?.has(partName)) {
6110
6175
  builtOccluderParts.push({
6111
6176
  index: entry.index,
6112
- lastUnderIdx: entry.lastUnderIdx,
6177
+ insertBeforeIdx: entry.insertBeforeIdx,
6113
6178
  canvas: occCanvas,
6114
6179
  placed: {
6115
6180
  record: {
@@ -6127,7 +6192,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6127
6192
  empty.push({
6128
6193
  code: OCCLUDER_EMPTY,
6129
6194
  object: `config.assemble.occluders[${entry.index}].part (part "${partName}")`,
6130
- detail: `has 0 rig pixels of occluder "${entry.declaration.image}" (alpha > ${OPAQUE_ALPHA_ABOVE}) after excluding the rest support (alpha > ${COPIED_ALPHA_ABOVE}) of parts drawn in front of it; omit config.assemble.occluders[${entry.index}].part when front parts already hold the entire occluder at rest`,
6195
+ detail: `has 0 rig pixels of occluder "${entry.declaration.image}" (alpha > ${COPIED_ALPHA_ABOVE}) after excluding the held pixels (alpha >= ${CORE_ALPHA}) of parts drawn in front of it; omit config.assemble.occluders[${entry.index}].part when front parts already hold the entire occluder at rest`,
6131
6196
  });
6132
6197
  continue;
6133
6198
  }
@@ -6151,12 +6216,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6151
6216
  };
6152
6217
  builtOccluderParts.push({
6153
6218
  index: entry.index,
6154
- lastUnderIdx: entry.lastUnderIdx,
6219
+ insertBeforeIdx: entry.insertBeforeIdx,
6155
6220
  canvas: occCanvas,
6156
6221
  placed: { record, image: crop(occCanvas, x0, y0, record.w, record.h) },
6157
6222
  });
6158
6223
  }
6159
- builtOccluderParts.sort((a, b) => a.lastUnderIdx - b.lastUnderIdx || a.index - b.index);
6224
+ builtOccluderParts.sort((a, b) => a.insertBeforeIdx - b.insertBeforeIdx || a.index - b.index);
6160
6225
  pieceList.forEach(({ name, b, pushed: pushedHere, at, cutFrom, limb, set }) => {
6161
6226
  const { key, r, st, extendKeys, trace, merged, region } = b;
6162
6227
  // A pixel the merge wrote is judged in the extend layer's run, every other
@@ -6176,7 +6241,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6176
6241
  if (edged.get(name)?.data[p] !== 1 && paintingGains.get(name)?.data[p] !== 1 && retakeByName.get(name)?.data[p] !== 1 && yields.get(name)?.mask.data[p] !== 1 && trace.ring.data[p] === 0 && own.takenMask.data[p] === 1 && (region === null || region.data[p] === 1)) projected.data[p] = 1;
6177
6242
  if (slotIdx >= 0) {
6178
6243
  for (const occPart of builtOccluderParts) {
6179
- if (occPart.lastUnderIdx >= slotIdx && occPart.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6244
+ if (occPart.insertBeforeIdx > slotIdx && occPart.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6180
6245
  visible.data[p] = 0;
6181
6246
  projected.data[p] = 0;
6182
6247
  break;
@@ -6270,7 +6335,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6270
6335
  const placed: PlacedPart[] = order.map((d) => ('plan' in d ? planned[d.plan] : 'cut' in d ? cutPlaced[d.cut] : 'limb' in d ? limbPlaced[d.limb] : cut[d.patch]) as PlacedPart);
6271
6336
  let spliceOffset = 0;
6272
6337
  for (const occPart of builtOccluderParts) {
6273
- const insertAt = occPart.lastUnderIdx + 1 + spliceOffset;
6338
+ const insertAt = occPart.insertBeforeIdx + spliceOffset;
6274
6339
  placed.splice(insertAt, 0, occPart.placed);
6275
6340
  keepInOrder.splice(insertAt, 0, null);
6276
6341
  writersInOrder.splice(insertAt, 0, new Int32Array(W * H).fill(AW.sourceProjection));
@@ -6281,11 +6346,11 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6281
6346
  const placedCanvases = placed.map(onRig);
6282
6347
  for (const entry of occluderWithSlot) {
6283
6348
  if (entry.declaration.part !== undefined) continue;
6284
- const frontStart = entry.lastUnderIdx + 1 + builtOccluderParts.filter((o) => o.lastUnderIdx < entry.lastUnderIdx || (o.lastUnderIdx === entry.lastUnderIdx && o.index < entry.index)).length;
6349
+ const frontStart = entry.insertBeforeIdx + builtOccluderParts.filter((o) => o.insertBeforeIdx < entry.insertBeforeIdx || (o.insertBeforeIdx === entry.insertBeforeIdx && o.index < entry.index)).length;
6285
6350
  let unheldPx = 0;
6286
6351
  let firstP = -1;
6287
6352
  for (let p = 0; p < W * H; p++) {
6288
- if (entry.opaqueMask.data[p] !== 1) continue;
6353
+ if (entry.copiedMask.data[p] !== 1) continue;
6289
6354
  let held = false;
6290
6355
  for (let j = frontStart; j < placedCanvases.length; j++) {
6291
6356
  if (placedCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
@@ -6299,7 +6364,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6299
6364
  }
6300
6365
  }
6301
6366
  if (unheldPx > 0) {
6302
- occluderUnheldWarnings.push(occluderUnheldWarning(entry.index, entry.declaration.image, entry.declaration.under, unheldPx, [firstP % W, Math.floor(firstP / W)]));
6367
+ occluderUnheldWarnings.push(occluderUnheldWarning(entry.index, entry.declaration.image, entry.declaration.under, unheldPx, [firstP % W, Math.floor(firstP / W)], CORE_ALPHA));
6303
6368
  }
6304
6369
  }
6305
6370
  }
@@ -6406,6 +6471,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6406
6471
  ghost_px: ghost,
6407
6472
  recomposite: recompositeRecord(figures),
6408
6473
  ...(sceneRecord === null ? {} : { scene: sceneRecord }),
6474
+ ...(occluderGrowRecords.length === 0 ? {} : { occluder_grow: occluderGrowRecords }),
6409
6475
  ...(padRecord === null ? {} : { single_run_pad: padRecord }),
6410
6476
  },
6411
6477
  images: placed,
@@ -6438,6 +6504,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6438
6504
  splits: islandKept.splits,
6439
6505
  capSplits: capAssigned.counts,
6440
6506
  edgeSplits,
6507
+ ...(cutFillMasks.length === 0 ? {} : { cutFillMasks }),
6441
6508
  };
6442
6509
  }
6443
6510
 
@@ -7114,7 +7181,24 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
7114
7181
  }
7115
7182
  }
7116
7183
  for (const t of heads) plan.push([aliasOf(t), headRun(t), t]);
7117
- orderPlanForOccluders(plan, g.occluderDeclarations);
7184
+ for (const split of g.occluderSplitParts ?? []) {
7185
+ const row = plan.find(([, run, tag]) => run === split.run && tag === split.tag);
7186
+ if (row === undefined) {
7187
+ notes.push(`assemble.take occluder split "${split.part}" (${split.run}:${split.tag}) matched no proposed row`);
7188
+ } else if (row[0] !== split.part) {
7189
+ if (plan.some((r) => r !== row && r[0] === split.part)) {
7190
+ notes.push(`assemble.take occluder split "${split.part}" (${split.run}:${split.tag}): the name is already a proposed row, so the row stays "${row[0]}"`);
7191
+ } else {
7192
+ notes.push(`${split.tag}: proposed as "${split.part}", the part its occluder-split take declares`);
7193
+ row[0] = split.part;
7194
+ }
7195
+ }
7196
+ }
7197
+ const occluderTakenTags: Record<string, string> = { ...g.occluderTakenTags };
7198
+ for (const l of [...full0.layers, ...head0.layers]) {
7199
+ if (l.takenLayers !== undefined && l.takenLayers.length > 0) occluderTakenTags[l.name] = l.name;
7200
+ }
7201
+ notes.push(...orderPlanForOccluders(plan, g.occluderDeclarations, Object.keys(occluderTakenTags).length > 0 ? occluderTakenTags : undefined));
7118
7202
  for (const [part, run, tag] of plan) {
7119
7203
  if (readAuthorTag(tag) !== null) notes.push(`${tag}: ${AUTHOR_NO_ROLE}; proposed as "${part}" from the ${run} run, at its place in that run's draw order`);
7120
7204
  }
@@ -7404,23 +7488,55 @@ export function stageFields(
7404
7488
  * loader's rules; what is left here is that this stage needs the head box,
7405
7489
  * which that loader leaves optional.
7406
7490
  */
7491
+ function occluderTakenTagsOf(cfg: EarlyConfig): Readonly<Record<string, string>> | undefined {
7492
+ const take = cfg.assemble.take;
7493
+ if (take === undefined || take.length === 0) return undefined;
7494
+ const out: Record<string, string> = {};
7495
+ for (const item of take) {
7496
+ if ('tags' in item) {
7497
+ for (const tag of item.tags) out[tag] = tag;
7498
+ } else if ('occluder' in item) {
7499
+ out[item.part] = item.tag;
7500
+ out[item.tag] = item.tag;
7501
+ }
7502
+ }
7503
+ const rawPlan = (cfg.assemble as { plan?: unknown }).plan;
7504
+ if (Array.isArray(rawPlan)) {
7505
+ for (const row of rawPlan) {
7506
+ if (!Array.isArray(row) || typeof row[0] !== 'string' || typeof row[1] !== 'string' || typeof row[2] !== 'string') continue;
7507
+ const [part, run, tag] = row;
7508
+ const taken = take.some(
7509
+ (item) =>
7510
+ ('tags' in item && item.run === run && item.tags.includes(tag)) ||
7511
+ ('occluder' in item && item.run === run && item.tag === tag),
7512
+ );
7513
+ if (taken) out[part] = tag;
7514
+ }
7515
+ }
7516
+ return Object.keys(out).length === 0 ? undefined : out;
7517
+ }
7518
+
7407
7519
  export function proposeFields(
7408
7520
  cfg: EarlyConfig,
7409
7521
  single: { w: number; h: number } | null = null,
7410
- ): { resolution: number; headBox: [number, number, number, number]; rigScale: number; single?: boolean; armSplit?: ArmSplit; keySkeleton?: ControlSkeleton; headFaceUnderfill?: boolean; occluderDeclarations?: readonly OccluderDeclaration[] } {
7522
+ ): { resolution: number; headBox: [number, number, number, number]; rigScale: number; single?: boolean; armSplit?: ArmSplit; keySkeleton?: ControlSkeleton; headFaceUnderfill?: boolean; occluderDeclarations?: readonly OccluderDeclaration[]; occluderTakenTags?: Readonly<Record<string, string>>; occluderSplitParts?: ReadonlyArray<{ run: Run; part: string; tag: string }> } {
7411
7523
  const armSplit = cfg.seethrough.arm_split === undefined ? {} : { armSplit: cfg.seethrough.arm_split };
7412
7524
  const keySkeleton = controlSkeletonOf(cfg);
7413
7525
  const skelField = keySkeleton === undefined ? {} : { keySkeleton };
7414
7526
  const underfillField = cfg.assemble.head_face_underfill === undefined ? {} : { headFaceUnderfill: cfg.assemble.head_face_underfill };
7415
7527
  const occludersField = cfg.assemble.occluders === undefined ? {} : { occluderDeclarations: cfg.assemble.occluders };
7528
+ const takenTags = occluderTakenTagsOf(cfg);
7529
+ const takenTagsField = takenTags === undefined ? {} : { occluderTakenTags: takenTags };
7530
+ const splitParts = (cfg.assemble.take ?? []).flatMap((item) => ('occluder' in item ? [{ run: item.run, part: item.part, tag: item.tag }] : []));
7531
+ const splitField = splitParts.length === 0 ? {} : { occluderSplitParts: splitParts };
7416
7532
  if (single !== null) {
7417
7533
  refuseIfAny(singleRunHeadBoxProblems(cfg.seethrough));
7418
- return { resolution: cfg.seethrough.resolution, headBox: singleRunHeadBox(single.w, single.h, cfg.seethrough.resolution), rigScale: cfg.assemble.rig_scale, single: true, ...armSplit, ...skelField, ...underfillField, ...occludersField };
7534
+ return { resolution: cfg.seethrough.resolution, headBox: singleRunHeadBox(single.w, single.h, cfg.seethrough.resolution), rigScale: cfg.assemble.rig_scale, single: true, ...armSplit, ...skelField, ...underfillField, ...occludersField, ...takenTagsField, ...splitField };
7419
7535
  }
7420
7536
  if (cfg.seethrough.head_box === undefined) {
7421
7537
  refuseIfAny([{ code: 'ASSEMBLE_FIELD_PRESENT', object: 'config.seethrough.head_box', detail: 'is absent; the plan is proposed from both runs, and the head run cannot be placed on the painting without the box it was cropped from — run `propose --head-box` first' }]);
7422
7538
  }
7423
- return { resolution: cfg.seethrough.resolution, headBox: cfg.seethrough.head_box as [number, number, number, number], rigScale: cfg.assemble.rig_scale, ...armSplit, ...skelField, ...underfillField, ...occludersField };
7539
+ return { resolution: cfg.seethrough.resolution, headBox: cfg.seethrough.head_box as [number, number, number, number], rigScale: cfg.assemble.rig_scale, ...armSplit, ...skelField, ...underfillField, ...occludersField, ...takenTagsField, ...splitField };
7424
7540
  }
7425
7541
 
7426
7542
  /**
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 }])]);