@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/assemble.ts CHANGED
@@ -15,6 +15,7 @@ import { paintingExtensionMasks, paintingExtensionProblems, type PaintingExtensi
15
15
  import { applyEdgeSplits, edgeSplitLines, edgeSplitProblems, type EdgeSplit, type EdgeSplitReading } from './edgesplit.ts';
16
16
  import { AUTOMATIC_WRITERS as AW, compactValueBaseline, pixelProvenance, rgbaEqual, type ValueBaseline, type StageMap } from './provenance.ts';
17
17
  import { bindDepthRun, copyDepthMaterial, registerDepthRun, transportPartDepth, type DepthConfig, type RegisteredDepth } from './depthsheets.ts';
18
+ import { COPIED_ALPHA_ABOVE, OCCLUDER_EMPTY, occluderDrawCycleProblems, type OccluderDeclaration, occluderUnheldWarning, orderPlanForOccluders } from './occluders.ts';
18
19
  /**
19
20
  * The assemble stage: two See-through runs over one painting — a FULL-body run
20
21
  * and a HEAD-crop run — merged into one set of rig-space parts, each part one
@@ -122,7 +123,8 @@ import { foldName, PartsError, type Problem, refuseIfAny } from './errors.ts';
122
123
  import { CORE_ALPHA, figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
123
124
  import { padToSquare, squarePad } from './inputs.ts';
124
125
  import type { MotionSeamDeclaration } from './motionseams.ts';
125
- 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';
126
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';
127
129
  import {
128
130
  alphaComposite,
@@ -237,6 +239,12 @@ export interface Geometry {
237
239
  yieldRefused?: boolean;
238
240
  /** Plan parts whose own samples survive source re-take beneath soft front cover. */
239
241
  keepUnderOccluders?: readonly string[];
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. */
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 }>;
240
248
  }
241
249
 
242
250
  /**
@@ -422,6 +430,8 @@ export interface AssembleInput {
422
430
  capOwnership?: 'target' | 'source';
423
431
  /** Issue #791: pairs of parts a turn moves relative to each other, whose fringe and seam colour stay untouched. */
424
432
  turnMovingPair?: ((a: string, b: string) => boolean) | null;
433
+ /** Issue #1246: declared occluders with their decoded source-grid RGBA images. */
434
+ occluders?: ReadonlyArray<{ declaration: OccluderDeclaration; image: Raster }>;
425
435
  }
426
436
 
427
437
  /**
@@ -3765,6 +3775,35 @@ export function underBox(polygon: ReadonlyArray<readonly [number, number]>): { x
3765
3775
  return { x0, y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 };
3766
3776
  }
3767
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
+
3768
3807
  /**
3769
3808
  * Fill the base where a cut removed its pixels (issue #193). The removed
3770
3809
  * pixels are those the piece holds (alpha above 0) and the band does not —
@@ -4793,6 +4832,10 @@ export interface AssembleResult {
4793
4832
  capSplits: SplitCount[];
4794
4833
  /** Issue #1231: what each `edge_splits` entry moved before projection; empty without one. */
4795
4834
  edgeSplits: EdgeSplitReading[];
4835
+ /** Issue #1246: `ASSEMBLE_OCCLUDER_UNHELD` WARN lines when `part` is omitted and occluder px are unheld at rest. */
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 }>;
4796
4839
  }
4797
4840
 
4798
4841
  /** Issue #953: the edge pixels `paintingEdges` resolved, the part pixels it changed, and the edge pixels it left, by reason. */
@@ -4847,7 +4890,7 @@ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[]
4847
4890
  }
4848
4891
 
4849
4892
  /** `r`'s pixels over the box `[x0, y0, w, h]`, transparent where the box reaches past `r`. */
4850
- 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 {
4851
4894
  const out = newRaster(w, h);
4852
4895
  for (let y = 0; y < h; y++) {
4853
4896
  const sy = y0 + y;
@@ -5064,17 +5107,66 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5064
5107
  const srcr = sourceInRig(source, W, H);
5065
5108
  const supportPainted = paintedFigure(srcr);
5066
5109
  const groundShare = groundRingShare(srcr, supportPainted);
5110
+ const occSx = (x: number): number => Math.min(source.width - 1, Math.floor((x + 0.5) * source.width / W));
5111
+ const occSy = (y: number): number => Math.min(source.height - 1, Math.floor((y + 0.5) * source.height / H));
5112
+ const occluderGrowRecords: OccluderGrowRecord[] = [];
5113
+ const occluderEntries = (input.occluders ?? []).map(({ declaration, image }, index) => {
5114
+ const coreBefore = newMask(W, H);
5115
+ let coveredBefore = 0;
5116
+ for (let y = 0; y < H; y++) {
5117
+ const srcY = occSy(y);
5118
+ for (let x = 0; x < W; x++) {
5119
+ const a = image.data[(srcY * source.width + occSx(x)) * 4 + 3];
5120
+ const p = y * W + x;
5121
+ if (a > COPIED_ALPHA_ABOVE) {
5122
+ coreBefore.data[p] = 1;
5123
+ coveredBefore++;
5124
+ }
5125
+ }
5126
+ }
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 };
5144
+ });
5145
+ const occluderUnderKeepByPlanPart = new Map<string, Mask>();
5146
+ if (projectRule === 'visible') {
5147
+ for (const { declaration, copiedMask } of occluderEntries) {
5148
+ for (const u of declaration.under) {
5149
+ let m = occluderUnderKeepByPlanPart.get(u);
5150
+ if (m === undefined) {
5151
+ m = newMask(W, H);
5152
+ occluderUnderKeepByPlanPart.set(u, m);
5153
+ }
5154
+ for (let p = 0; p < W * H; p++) if (copiedMask.data[p] === 1) m.data[p] = 1;
5155
+ }
5156
+ }
5157
+ }
5067
5158
  // Issue #359: a part's hidden-art layer is the under of a cut that names none — and, with one named, a refusal, since
5068
5159
  // reading either would be a guess. Its uses are counted for `hiddenLines`.
5069
5160
  const hiddenArt = hiddenArtByPart(plan, input.cuts, { full, head }, frame, input.resolution);
5070
5161
  const hiddenUses = new Map<string, string[]>();
5071
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}`, []);
5072
5163
  const hiddenProblems: Problem[] = [];
5164
+ const showCutUnder = (u: Cut['under']): string => typeof u === 'object' && u !== null ? `{"plate": ${JSON.stringify(u.plate)}}` : String(u);
5073
5165
  const unders = input.cuts.map((q, i) => {
5074
5166
  const art = hiddenArt.get(q.from);
5075
5167
  if (art === undefined) return input.under?.[i] ?? null;
5076
5168
  if (q.under !== undefined) {
5077
- 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` });
5078
5170
  return null;
5079
5171
  }
5080
5172
  const box = underBox(q.polygon);
@@ -5138,16 +5230,31 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5138
5230
  const rigLayers = layers.map((l) => layerToRig(l.canvas, frame, run));
5139
5231
  const rank = planRanks(layers.map((l) => l.tag), run, sourcePlan);
5140
5232
  const keep = layers.map((l, i): Mask | null => {
5141
- if (input.limbUnderCover !== true || ![...plan, ...cutLayerPlan].some(([name, ru, tag]) => (limbPlans.has(name) || limbSources.has(name)) && ru === run && tag === l.tag)) return null;
5142
- const mask = newMask(W, H);
5143
- const cover = newMask(W, H);
5144
- for (let p = 0; p < W * H; p++) {
5145
- if (!rigLayers.some((r, j) => frontOf(j, i, rank) && r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE)) continue;
5146
- cover.data[p] = 1;
5147
- if (rigLayers[i].data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) mask.data[p] = 1;
5233
+ let mask: Mask | null = null;
5234
+ if (input.limbUnderCover === true && [...plan, ...cutLayerPlan].some(([name, ru, tag]) => (limbPlans.has(name) || limbSources.has(name)) && ru === run && tag === l.tag)) {
5235
+ mask = newMask(W, H);
5236
+ const cover = newMask(W, H);
5237
+ for (let p = 0; p < W * H; p++) {
5238
+ if (!rigLayers.some((r, j) => frontOf(j, i, rank) && r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE)) continue;
5239
+ cover.data[p] = 1;
5240
+ if (rigLayers[i].data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) mask.data[p] = 1;
5241
+ }
5242
+ underCover.set(`${run}:${l.tag}`, mask);
5243
+ coverFootprints.set(`${run}:${l.tag}`, cover);
5244
+ }
5245
+ const occParts = [
5246
+ ...sourcePlan.filter(([, ru, tag]) => ru === run && tag === l.tag).map(([name]) => name),
5247
+ ...extend.filter((e) => e.run === run && e.tag === l.tag).map((e) => e.part),
5248
+ ].filter((name) => occluderUnderKeepByPlanPart.has(name));
5249
+ if (occParts.length > 0) {
5250
+ if (mask === null) mask = newMask(W, H);
5251
+ for (const name of occParts) {
5252
+ const occKeep = occluderUnderKeepByPlanPart.get(name)!;
5253
+ for (let p = 0; p < W * H; p++) {
5254
+ if (occKeep.data[p] === 1 && rigLayers[i].data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) mask.data[p] = 1;
5255
+ }
5256
+ }
5148
5257
  }
5149
- underCover.set(`${run}:${l.tag}`, mask);
5150
- coverFootprints.set(`${run}:${l.tag}`, cover);
5151
5258
  return mask;
5152
5259
  });
5153
5260
  // Normalize the unedited input to the same rig grid. Cleanup effects on
@@ -5323,7 +5430,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5323
5430
  const object = `config.assemble.cuts[${i}].under (part "${q.into}")`;
5324
5431
  const u = unders[i];
5325
5432
  if (u === null) {
5326
- 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)` });
5327
5434
  return;
5328
5435
  }
5329
5436
  const box = underBox(q.polygon);
@@ -5331,7 +5438,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5331
5438
  patchProblems.push({
5332
5439
  code: 'ASSEMBLE_UNDER_SIZE',
5333
5440
  object,
5334
- 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)`,
5335
5442
  });
5336
5443
  }
5337
5444
  const at = order0.findIndex((d) => 'cut' in d && d.cut === i);
@@ -5385,6 +5492,10 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5385
5492
  const f = rig.get(`${run2}:${tag2}`) as Raster;
5386
5493
  for (let p = 0; p < W * H; p++) if (f.data[p * 4 + 3] >= FRONT_ALPHA) front.data[p] = 1;
5387
5494
  }
5495
+ const occKeep = occluderUnderKeepByPlanPart.get(name);
5496
+ if (occKeep !== undefined) {
5497
+ for (let p = 0; p < W * H; p++) if (occKeep.data[p] === 1) front.data[p] = 1;
5498
+ }
5388
5499
  merged = mergeCropEntries(r, extras, front, srcr, frame, extend.filter(e => e.part === name), trace, (p, stage) => { writers[p] = AW[stage]; });
5389
5500
  }
5390
5501
  const { x1, opaque } = measureBox(r);
@@ -5533,7 +5644,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5533
5644
  empty.push({
5534
5645
  code: 'ASSEMBLE_UNDER_EMPTY',
5535
5646
  object: `config.assemble.cuts[${i}].under (part "${cuts[i].into}")`,
5536
- 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`,
5537
5648
  });
5538
5649
  }
5539
5650
  return { ...f, opaqueFilled };
@@ -5552,6 +5663,11 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5552
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 }])); }
5553
5664
  });
5554
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
+ }));
5555
5671
  // Parent partition counts and under use the removed parent art above. Only
5556
5672
  // the emitted piece (and any limb cut from it) reads this independent source.
5557
5673
  cutSources.forEach((source, i) => {
@@ -5593,6 +5709,16 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5593
5709
  const order = limbOrder(order0, plan, cuts, lim.parts);
5594
5710
  const pieceAt = (d: { plan: number } | { cut: number } | { limb: number }): { name: string; b: Built } =>
5595
5711
  'plan' in d ? { name: plan[d.plan][0], b: built[d.plan] as Built } : 'cut' in d ? { name: cuts[d.cut].into, b: pieces[d.cut] as Built } : { name: lim.parts[d.limb].part, b: limbPieces[d.limb] as Built };
5712
+ const rootPlanPartOfSlot = (d: DrawSlot): string | null => {
5713
+ if ('plan' in d) return plan[d.plan][0];
5714
+ if ('cut' in d) return cuts[d.cut].from;
5715
+ if ('limb' in d) {
5716
+ const ofName = lim.parts[d.limb].of;
5717
+ const cutParent = cuts.find((c) => c.into === ofName);
5718
+ return cutParent !== undefined ? cutParent.from : ofName;
5719
+ }
5720
+ return null;
5721
+ };
5596
5722
 
5597
5723
  // Issue #588: a set that names one limb side keeps, in each part cut from a layer of more than one island, the island its joints fall on.
5598
5724
  // Issue #609: on a layer of one island that also holds a limb the set does not carry, by the nearest segment line.
@@ -5695,10 +5821,19 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5695
5821
  const keptRetake: Array<Mask | null> = order.map(() => null);
5696
5822
  const softOcclusion: SoftOcclusionReading[] = [];
5697
5823
  const keepInOrder = order.map((d, i): Mask | null => {
5824
+ const rootPart = rootPlanPartOfSlot(d);
5825
+ const occKeep = rootPart === null ? undefined : occluderUnderKeepByPlanPart.get(rootPart);
5826
+ const withOccKeep = (base: Mask | null): Mask | null => {
5827
+ if (occKeep === undefined) return base;
5828
+ const out = newMask(W, H);
5829
+ if (base !== null) out.data.set(base.data);
5830
+ for (let p = 0; p < W * H; p++) if (occKeep.data[p] === 1) out.data[p] = 1;
5831
+ return out;
5832
+ };
5698
5833
  const limb = 'limb' in d ? limbKeep[d.limb] : null;
5699
- if ('patch' in d) return limb;
5834
+ if ('patch' in d) return withOccKeep(limb);
5700
5835
  const b = pieceAt(d).b, baseline = valueBaselines.get(b.key);
5701
- if (baseline === undefined || baseline === null) return limb;
5836
+ if (baseline === undefined || baseline === null) return withOccKeep(limb);
5702
5837
  const enabled = sourceKeys.has(b.key);
5703
5838
  const mask = enabled ? newMask(W, H) : limb;
5704
5839
  if (enabled && limb !== null) mask!.data.set(limb.data);
@@ -5738,7 +5873,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5738
5873
  reading.front = [...holders].map(([part, px]) => ({ part, px }));
5739
5874
  softOcclusion.push(reading);
5740
5875
  }
5741
- return mask;
5876
+ return withOccKeep(mask);
5742
5877
  });
5743
5878
  const retakeByName = new Map(order.flatMap((d, i) => 'patch' in d ? [] : [[pieceAt(d).name, keptRetake[i]] as const]));
5744
5879
  const patchWriters = patches.map((_, i) => new Int32Array(W * H).fill(patchIds[i]));
@@ -5898,29 +6033,29 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5898
6033
  const visibleFigure = projectRule === 'visible' ? sourceSupportFigure(source, W, H, srcr) : undefined;
5899
6034
  const edged = new Map<string, Mask>();
5900
6035
  let edgeReading: PaintingEdgeReading | null = null;
6036
+ const onRig = (q: PlacedPart): Raster => {
6037
+ const { image, record } = q;
6038
+ if (image.width === W && image.height === H && record.x === 0 && record.y === 0) return image;
6039
+ const whole = newRaster(W, H);
6040
+ for (let y = 0; y < image.height; y++) {
6041
+ const ry = record.y + y;
6042
+ if (ry < 0 || ry >= H) continue;
6043
+ for (let x = 0; x < image.width; x++) {
6044
+ const rx = record.x + x;
6045
+ if (rx < 0 || rx >= W) continue;
6046
+ const s = (y * image.width + x) * 4;
6047
+ whole.data.set(image.data.subarray(s, s + 4), (ry * W + rx) * 4);
6048
+ }
6049
+ }
6050
+ return whole;
6051
+ };
5901
6052
  if (projectRule === 'visible') {
5902
6053
  // paintingEdges reads every image as the whole rig canvas. A plan part's image already is one; a patch is its cut,
5903
6054
  // placed at record.x / record.y, so it is placed on a canvas here. The step never writes a patch, so a copy is enough.
5904
- const onRig = (q: PlacedPart): Raster => {
5905
- const { image, record } = q;
5906
- if (image.width === W && image.height === H && record.x === 0 && record.y === 0) return image;
5907
- const whole = newRaster(W, H);
5908
- for (let y = 0; y < image.height; y++) {
5909
- const ry = record.y + y;
5910
- if (ry < 0 || ry >= H) continue;
5911
- for (let x = 0; x < image.width; x++) {
5912
- const rx = record.x + x;
5913
- if (rx < 0 || rx >= W) continue;
5914
- const s = (y * image.width + x) * 4;
5915
- whole.data.set(image.data.subarray(s, s + 4), (ry * W + rx) * 4);
5916
- }
5917
- }
5918
- return whole;
5919
- };
5920
6055
  const canvases = stack.map(onRig);
5921
6056
  const rawPlan = input.plan.map(([name, run, tag]) => {
5922
6057
  const layer = input[run].layers.find(l => l.name === tag)!;
5923
- return { name, raster: layerToRig(placeLayer(layer, input.resolution), frame, run) };
6058
+ return { name, raster: layerToRig(placeLayer(layer, input.resolution), frame, run), keep: occluderUnderKeepByPlanPart.get(name) ?? null };
5924
6059
  });
5925
6060
  if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
5926
6061
  const owner = rawPaintingOwner(rawPlan, W * H);
@@ -5993,6 +6128,100 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5993
6128
  }
5994
6129
  return k;
5995
6130
  };
6131
+ const stackCanvases = occluderEntries.length === 0 ? [] : stack.map(onRig);
6132
+ const occluderWithSlot = occluderEntries.map((entry) => {
6133
+ let lastUnderIdx = -1;
6134
+ let firstOverIdx = -1;
6135
+ order.forEach((d, idx) => {
6136
+ const root = rootPlanPartOfSlot(d);
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;
6140
+ });
6141
+ const insertBeforeIdx = firstOverIdx >= 0 ? firstOverIdx : lastUnderIdx + 1;
6142
+ return { ...entry, lastUnderIdx, firstOverIdx, insertBeforeIdx };
6143
+ });
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)) {
6146
+ const partName = entry.declaration.part!;
6147
+ const occCanvas = newRaster(W, H);
6148
+ const occVisible = newMask(W, H);
6149
+ const occProjected = newMask(W, H);
6150
+ for (let p = 0; p < W * H; p++) {
6151
+ if (entry.copiedMask.data[p] !== 1) continue;
6152
+ let heldInFront = false;
6153
+ for (let j = entry.insertBeforeIdx; j < stackCanvases.length; j++) {
6154
+ if (stackCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
6155
+ heldInFront = true;
6156
+ break;
6157
+ }
6158
+ }
6159
+ if (!heldInFront) {
6160
+ for (const frontOcc of builtOccluderParts) {
6161
+ if ((frontOcc.insertBeforeIdx > entry.insertBeforeIdx || (frontOcc.insertBeforeIdx === entry.insertBeforeIdx && frontOcc.index > entry.index)) && frontOcc.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6162
+ heldInFront = true;
6163
+ break;
6164
+ }
6165
+ }
6166
+ }
6167
+ if (heldInFront) continue;
6168
+ occCanvas.data.set(srcr.data.subarray(p * 4, p * 4 + 3), p * 4);
6169
+ occCanvas.data[p * 4 + 3] = 255;
6170
+ occVisible.data[p] = 1;
6171
+ occProjected.data[p] = 1;
6172
+ }
6173
+ const { x0, y0, x1, y1, opaque } = measureBox(occCanvas);
6174
+ if (opaque === 0 && emptyTargets?.has(partName)) {
6175
+ builtOccluderParts.push({
6176
+ index: entry.index,
6177
+ insertBeforeIdx: entry.insertBeforeIdx,
6178
+ canvas: occCanvas,
6179
+ placed: {
6180
+ record: {
6181
+ name: partName, from: `${PAINTING_RUN}:${partName}`, x: 0, y: 0, w: 1, h: 1,
6182
+ opaque_px: 0, visible_px: 0, occluded_px: 0, projected_core_px: 0,
6183
+ source_px_taken: 0, visible_not_projected_px: 0, refused_drift_px: 0,
6184
+ merged_px: 0, seam_override_px: 0,
6185
+ },
6186
+ image: newRaster(1, 1),
6187
+ },
6188
+ });
6189
+ continue;
6190
+ }
6191
+ if (opaque === 0) {
6192
+ empty.push({
6193
+ code: OCCLUDER_EMPTY,
6194
+ object: `config.assemble.occluders[${entry.index}].part (part "${partName}")`,
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`,
6196
+ });
6197
+ continue;
6198
+ }
6199
+ const vc = visibilityCounts(`part "${partName}" (${PAINTING_RUN}:${partName})`, occCanvas, occVisible, occProjected);
6200
+ const record: PartRecord = {
6201
+ name: partName,
6202
+ from: `${PAINTING_RUN}:${partName}`,
6203
+ x: x0,
6204
+ y: y0,
6205
+ w: x1 - x0 + 1,
6206
+ h: y1 - y0 + 1,
6207
+ opaque_px: opaque,
6208
+ visible_px: vc.visible_px,
6209
+ occluded_px: vc.occluded_px,
6210
+ projected_core_px: opaque,
6211
+ source_px_taken: opaque,
6212
+ visible_not_projected_px: vc.visible_not_projected_px,
6213
+ refused_drift_px: 0,
6214
+ merged_px: 0,
6215
+ seam_override_px: 0,
6216
+ };
6217
+ builtOccluderParts.push({
6218
+ index: entry.index,
6219
+ insertBeforeIdx: entry.insertBeforeIdx,
6220
+ canvas: occCanvas,
6221
+ placed: { record, image: crop(occCanvas, x0, y0, record.w, record.h) },
6222
+ });
6223
+ }
6224
+ builtOccluderParts.sort((a, b) => a.insertBeforeIdx - b.insertBeforeIdx || a.index - b.index);
5996
6225
  pieceList.forEach(({ name, b, pushed: pushedHere, at, cutFrom, limb, set }) => {
5997
6226
  const { key, r, st, extendKeys, trace, merged, region } = b;
5998
6227
  // A pixel the merge wrote is judged in the extend layer's run, every other
@@ -6002,6 +6231,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6002
6231
  // is growRim's, counted in merged_px, and is not projection.
6003
6232
  const visible = newMask(W, H);
6004
6233
  const projected = newMask(W, H);
6234
+ const slotIdx = builtOccluderParts.length === 0 ? -1 : order.findIndex((d) => !('patch' in d) && pieceAt(d).name === name);
6005
6235
  for (let p = 0; p < W * H; p++) {
6006
6236
  const e = trace.from[p];
6007
6237
  const own = e < 0 ? st : (stats.get(extendKeys[e]) as ProjectionStats);
@@ -6009,6 +6239,15 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6009
6239
  if (r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE && own.clear.data[p] === 1 && (region === null || region.data[p] === 1)) visible.data[p] = 1;
6010
6240
  if (paintingGains.get(name)?.data[p] === 1) visible.data[p] = 1;
6011
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;
6242
+ if (slotIdx >= 0) {
6243
+ for (const occPart of builtOccluderParts) {
6244
+ if (occPart.insertBeforeIdx > slotIdx && occPart.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6245
+ visible.data[p] = 0;
6246
+ projected.data[p] = 0;
6247
+ break;
6248
+ }
6249
+ }
6250
+ }
6012
6251
  }
6013
6252
  const { x0, y0, x1, y1, opaque } = measureBox(r);
6014
6253
  if (opaque === 0 && emptyTargets?.has(name)) {
@@ -6094,6 +6333,41 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6094
6333
  });
6095
6334
  refuseIfAny(empty);
6096
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);
6336
+ let spliceOffset = 0;
6337
+ for (const occPart of builtOccluderParts) {
6338
+ const insertAt = occPart.insertBeforeIdx + spliceOffset;
6339
+ placed.splice(insertAt, 0, occPart.placed);
6340
+ keepInOrder.splice(insertAt, 0, null);
6341
+ writersInOrder.splice(insertAt, 0, new Int32Array(W * H).fill(AW.sourceProjection));
6342
+ spliceOffset++;
6343
+ }
6344
+ const occluderUnheldWarnings: string[] = [];
6345
+ if (beforeTake === null && occluderWithSlot.some((e) => e.declaration.part === undefined)) {
6346
+ const placedCanvases = placed.map(onRig);
6347
+ for (const entry of occluderWithSlot) {
6348
+ if (entry.declaration.part !== undefined) continue;
6349
+ const frontStart = entry.insertBeforeIdx + builtOccluderParts.filter((o) => o.insertBeforeIdx < entry.insertBeforeIdx || (o.insertBeforeIdx === entry.insertBeforeIdx && o.index < entry.index)).length;
6350
+ let unheldPx = 0;
6351
+ let firstP = -1;
6352
+ for (let p = 0; p < W * H; p++) {
6353
+ if (entry.copiedMask.data[p] !== 1) continue;
6354
+ let held = false;
6355
+ for (let j = frontStart; j < placedCanvases.length; j++) {
6356
+ if (placedCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
6357
+ held = true;
6358
+ break;
6359
+ }
6360
+ }
6361
+ if (!held) {
6362
+ if (firstP < 0) firstP = p;
6363
+ unheldPx++;
6364
+ }
6365
+ }
6366
+ if (unheldPx > 0) {
6367
+ occluderUnheldWarnings.push(occluderUnheldWarning(entry.index, entry.declaration.image, entry.declaration.under, unheldPx, [firstP % W, Math.floor(firstP / W)], CORE_ALPHA));
6368
+ }
6369
+ }
6370
+ }
6097
6371
  const artFiles = new Map<string, string>(); for (const p of placed) { const k = foldName(`${p.record.name}.png`), prev = artFiles.get(k); if (prev !== undefined) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: `${p.record.name}.png`, detail: `part "${prev}" ("${prev}.png") and part "${p.record.name}" ("${p.record.name}.png") collides with a part artwork filename; choose noncolliding part names before sheet emission` }]); artFiles.set(k, p.record.name); }
6098
6372
  for (const p of placed) if (p.record.depth !== undefined && artFiles.has(foldName(p.record.depth.image))) refuseIfAny([{ code: 'DEPTH_SHEET_UNAMBIGUOUS', object: p.record.depth.image, detail: `part "${p.record.name}" sheet "${p.record.depth.image}" and part "${artFiles.get(foldName(p.record.depth.image))}" ("${artFiles.get(foldName(p.record.depth.image))}.png") collides with a part artwork filename; choose noncolliding part names before sheet emission` }]);
6099
6373
 
@@ -6197,6 +6471,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6197
6471
  ghost_px: ghost,
6198
6472
  recomposite: recompositeRecord(figures),
6199
6473
  ...(sceneRecord === null ? {} : { scene: sceneRecord }),
6474
+ ...(occluderGrowRecords.length === 0 ? {} : { occluder_grow: occluderGrowRecords }),
6200
6475
  ...(padRecord === null ? {} : { single_run_pad: padRecord }),
6201
6476
  },
6202
6477
  images: placed,
@@ -6217,6 +6492,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6217
6492
  holeKinds: kinds,
6218
6493
  drift,
6219
6494
  ...(input.yieldRefused === true ? { yieldReadings: [...yields.values()].map(q => q.reading) } : {}),
6495
+ ...(occluderUnheldWarnings.length === 0 ? {} : { occluderUnheldWarnings }),
6220
6496
  hidden: [...hiddenUses].map(([layer, readBy]) => ({ layer, readBy })),
6221
6497
  seamRule,
6222
6498
  projectRule,
@@ -6228,6 +6504,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6228
6504
  splits: islandKept.splits,
6229
6505
  capSplits: capAssigned.counts,
6230
6506
  edgeSplits,
6507
+ ...(cutFillMasks.length === 0 ? {} : { cutFillMasks }),
6231
6508
  };
6232
6509
  }
6233
6510
 
@@ -6794,6 +7071,9 @@ export function headGarmentWarning(w: HeadGarmentOverlap): string {
6794
7071
 
6795
7072
  export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx = PROPOSE_MIN_PX): PlanProposal {
6796
7073
  const frame = checkGeometry(g, { full: full0, head: head0 });
7074
+ if (g.occluderDeclarations !== undefined && g.occluderDeclarations.length > 0) {
7075
+ refuseIfAny(occluderDrawCycleProblems(g.occluderDeclarations));
7076
+ }
6797
7077
  // Issue #366: one run's file, padded to the resolution square as the stage pads it.
6798
7078
  const fullPadded = g.single === true ? padSingleRun(full0, frame, g.resolution) : full0;
6799
7079
  // Issue #439: when seethrough.arm_split is declared, split the full run's overlapping handwear into handwear-r and handwear-l.
@@ -6901,6 +7181,24 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
6901
7181
  }
6902
7182
  }
6903
7183
  for (const t of heads) plan.push([aliasOf(t), headRun(t), t]);
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));
6904
7202
  for (const [part, run, tag] of plan) {
6905
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`);
6906
7204
  }
@@ -7190,22 +7488,55 @@ export function stageFields(
7190
7488
  * loader's rules; what is left here is that this stage needs the head box,
7191
7489
  * which that loader leaves optional.
7192
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
+
7193
7519
  export function proposeFields(
7194
7520
  cfg: EarlyConfig,
7195
7521
  single: { w: number; h: number } | null = null,
7196
- ): { resolution: number; headBox: [number, number, number, number]; rigScale: number; single?: boolean; armSplit?: ArmSplit; keySkeleton?: ControlSkeleton; headFaceUnderfill?: boolean } {
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 }> } {
7197
7523
  const armSplit = cfg.seethrough.arm_split === undefined ? {} : { armSplit: cfg.seethrough.arm_split };
7198
7524
  const keySkeleton = controlSkeletonOf(cfg);
7199
7525
  const skelField = keySkeleton === undefined ? {} : { keySkeleton };
7200
7526
  const underfillField = cfg.assemble.head_face_underfill === undefined ? {} : { headFaceUnderfill: cfg.assemble.head_face_underfill };
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 };
7201
7532
  if (single !== null) {
7202
7533
  refuseIfAny(singleRunHeadBoxProblems(cfg.seethrough));
7203
- return { resolution: cfg.seethrough.resolution, headBox: singleRunHeadBox(single.w, single.h, cfg.seethrough.resolution), rigScale: cfg.assemble.rig_scale, single: true, ...armSplit, ...skelField, ...underfillField };
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 };
7204
7535
  }
7205
7536
  if (cfg.seethrough.head_box === undefined) {
7206
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' }]);
7207
7538
  }
7208
- return { resolution: cfg.seethrough.resolution, headBox: cfg.seethrough.head_box as [number, number, number, number], rigScale: cfg.assemble.rig_scale, ...armSplit, ...skelField, ...underfillField };
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 };
7209
7540
  }
7210
7541
 
7211
7542
  /**