@rig-c/parts 2.34.0 → 2.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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, type OccluderGuardRecord, 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
  /**
@@ -289,10 +294,20 @@ export function padSingleRun(set: LayerSet, frame: Pick<Frame, 'fullPad' | 'full
289
294
  const dx = frame.fullPad;
290
295
  const dy = frame.fullPadTop;
291
296
  if (dx === 0 && dy === 0 && set.canvas.w === resolution && set.canvas.h === resolution) return set;
297
+ const shiftLayer = (l: Layer): Layer => ({
298
+ ...l,
299
+ left: l.left + dx,
300
+ top: l.top + dy,
301
+ right: l.right + dx,
302
+ bottom: l.bottom + dy,
303
+ ...(l.occluderSplit === undefined
304
+ ? {}
305
+ : { occluderSplit: { occluder: l.occluderSplit.occluder, base: shiftLayer(l.occluderSplit.base), donor: shiftLayer(l.occluderSplit.donor), merged: l.occluderSplit.merged } }),
306
+ });
292
307
  return {
293
308
  ...set,
294
309
  canvas: { w: resolution, h: resolution },
295
- layers: set.layers.map((l) => ({ ...l, left: l.left + dx, top: l.top + dy, right: l.right + dx, bottom: l.bottom + dy })),
310
+ layers: set.layers.map(shiftLayer),
296
311
  hidden: set.hidden.map((l) => ({ ...l, left: l.left + dx, top: l.top + dy, right: l.right + dx, bottom: l.bottom + dy })),
297
312
  };
298
313
  }
@@ -1949,6 +1964,68 @@ export function layerToRig(canvas: Raster, frame: Frame, run: Run): Raster {
1949
1964
  return out;
1950
1965
  }
1951
1966
 
1967
+ /**
1968
+ * Resample an occluder image (on the painting's grid) onto the `W x H` rig grid
1969
+ * by nearest centre (`alpha > COPIED_ALPHA_ABOVE`), before any `grow`.
1970
+ */
1971
+ export function occluderCoreMask(image: Raster, W: number, H: number): { coreBefore: Mask; coveredBefore: number } {
1972
+ const occSx = (x: number): number => Math.min(image.width - 1, Math.floor((x + 0.5) * image.width / W));
1973
+ const occSy = (y: number): number => Math.min(image.height - 1, Math.floor((y + 0.5) * image.height / H));
1974
+ const coreBefore = newMask(W, H);
1975
+ let coveredBefore = 0;
1976
+ for (let y = 0; y < H; y++) {
1977
+ const srcY = occSy(y);
1978
+ for (let x = 0; x < W; x++) {
1979
+ const a = image.data[(srcY * image.width + occSx(x)) * 4 + 3];
1980
+ const p = y * W + x;
1981
+ if (a > COPIED_ALPHA_ABOVE) {
1982
+ coreBefore.data[p] = 1;
1983
+ coveredBefore++;
1984
+ }
1985
+ }
1986
+ }
1987
+ return { coreBefore, coveredBefore };
1988
+ }
1989
+
1990
+ /**
1991
+ * Issue #1251: place a layer on the rig grid, warping an occluder-split layer's
1992
+ * base and donor runs through {@link layerToRig} separately and picking between
1993
+ * them on the rig grid using the occluder's boolean core (`alpha > 128`, before
1994
+ * any `grow`) so resampling never blends base and donor across the occluder edge.
1995
+ */
1996
+ export function layerToRigSplit(
1997
+ layer: Layer,
1998
+ resolution: number,
1999
+ frame: Frame,
2000
+ run: Run,
2001
+ occluderCoreMasks: readonly Mask[],
2002
+ cleaned = false,
2003
+ ): Raster {
2004
+ const toRig = (l: Layer): Raster => {
2005
+ const placed = placeLayer(l, resolution);
2006
+ return layerToRig(cleaned ? cleanGhosts(placed).canvas : placed, frame, run);
2007
+ };
2008
+ const split = layer.occluderSplit;
2009
+ const mask = split === undefined ? undefined : occluderCoreMasks[split.occluder];
2010
+ if (split === undefined || layer.pixels !== split.merged || mask === undefined) return toRig(layer);
2011
+ // Ghost clean-up reads the merged layer, as before the split moved to the rig grid: a donor fragment joined to the
2012
+ // base across the occluder edge is one component there. What the merged clean-up drops is dropped from both sides.
2013
+ const kept = cleaned ? cleanGhosts(placeLayer(layer, resolution)).canvas : null;
2014
+ const sideToRig = (l: Layer): Raster => {
2015
+ const placed = placeLayer(l, resolution);
2016
+ if (kept !== null) for (let p = 0; p < resolution * resolution; p++) if (kept.data[p * 4 + 3] === 0) placed.data[p * 4 + 3] = 0;
2017
+ return layerToRig(placed, frame, run);
2018
+ };
2019
+ const baseRig = sideToRig(split.base);
2020
+ const donorRig = sideToRig(split.donor);
2021
+ const out = newRaster(frame.W, frame.H);
2022
+ for (let p = 0; p < frame.W * frame.H; p++) {
2023
+ const src = mask.data[p] === 1 ? baseRig.data : donorRig.data;
2024
+ out.data.set(src.subarray(p * 4, p * 4 + 4), p * 4);
2025
+ }
2026
+ return out;
2027
+ }
2028
+
1952
2029
  /**
1953
2030
  * Issue #492: warp a full-run layer (`resolution x resolution`) onto the head
1954
2031
  * run's `resolution x resolution` canvas using the same premultiplied float32
@@ -3770,6 +3847,35 @@ export function underBox(polygon: ReadonlyArray<readonly [number, number]>): { x
3770
3847
  return { x0, y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 };
3771
3848
  }
3772
3849
 
3850
+ /**
3851
+ * Issue #1230: the fill mask on the painting's grid (`sourceW x sourceH`) for a
3852
+ * cut piece `piece` (in rig space, `polygon ∩ from alpha > 0`, including the
3853
+ * overlap band): opaque white `[255, 255, 255, 255]` where a painting pixel
3854
+ * whose sampled rig pixel has `alpha > 0` (identity at `rig_scale: 1`), and
3855
+ * transparent `[0, 0, 0, 0]` everywhere else.
3856
+ */
3857
+ export function cutFillMask(piece: Raster, sourceW: number, sourceH: number): Raster {
3858
+ const { width: W, height: H } = piece;
3859
+ // Issue #1230: each painting pixel reads the rig pixel it samples, so the mask covers the
3860
+ // piece's whole footprint on the painting grid at any rig_scale (a forward rig -> painting
3861
+ // mapping leaves gaps whenever the rig is smaller than the painting).
3862
+ const rigX = (sx: number): number => Math.min(W - 1, Math.floor((sx + 0.5) * W / sourceW));
3863
+ const rigY = (sy: number): number => Math.min(H - 1, Math.floor((sy + 0.5) * H / sourceH));
3864
+ const mask = newRaster(sourceW, sourceH);
3865
+ for (let sy = 0; sy < sourceH; sy++) {
3866
+ const ry = rigY(sy);
3867
+ for (let sx = 0; sx < sourceW; sx++) {
3868
+ if (piece.data[(ry * W + rigX(sx)) * 4 + 3] === 0) continue;
3869
+ const q = (sy * sourceW + sx) * 4;
3870
+ mask.data[q] = 255;
3871
+ mask.data[q + 1] = 255;
3872
+ mask.data[q + 2] = 255;
3873
+ mask.data[q + 3] = 255;
3874
+ }
3875
+ }
3876
+ return mask;
3877
+ }
3878
+
3773
3879
  /**
3774
3880
  * Fill the base where a cut removed its pixels (issue #193). The removed
3775
3881
  * pixels are those the piece holds (alpha above 0) and the band does not —
@@ -4800,6 +4906,8 @@ export interface AssembleResult {
4800
4906
  edgeSplits: EdgeSplitReading[];
4801
4907
  /** Issue #1246: `ASSEMBLE_OCCLUDER_UNHELD` WARN lines when `part` is omitted and occluder px are unheld at rest. */
4802
4908
  occluderUnheldWarnings?: string[];
4909
+ /** 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. */
4910
+ cutFillMasks?: Array<{ into: string; from: string; mask: Raster }>;
4803
4911
  }
4804
4912
 
4805
4913
  /** Issue #953: the edge pixels `paintingEdges` resolved, the part pixels it changed, and the edge pixels it left, by reason. */
@@ -4854,7 +4962,7 @@ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[]
4854
4962
  }
4855
4963
 
4856
4964
  /** `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 {
4965
+ export function boxOf(r: Raster, x0: number, y0: number, w: number, h: number): Raster {
4858
4966
  const out = newRaster(w, h);
4859
4967
  for (let y = 0; y < h; y++) {
4860
4968
  const sy = y0 + y;
@@ -5020,12 +5128,54 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5020
5128
  refuseIfAny(depthInputProblems);
5021
5129
  // Issue #366: one run's file, padded to the resolution square; read as both runs, as before.
5022
5130
  const fullPadded = single ? padSingleRun(depthFullInput, frame, input.resolution) : depthFullInput;
5131
+ const { W, H } = frame;
5132
+ const occluderGrowRecords: OccluderGrowRecord[] = [];
5133
+ const occluderGuardRecords: OccluderGuardRecord[] = [];
5134
+ const occluderEntries = (input.occluders ?? []).map(({ declaration, image }, index) => {
5135
+ const { coreBefore, coveredBefore } = occluderCoreMask(image, W, H);
5136
+ const grow = declaration.grow ?? 0;
5137
+ const guard = declaration.guard ?? 0;
5138
+ let copiedMask = coreBefore;
5139
+ if (grow > 0) {
5140
+ const grown = growMask({ width: W, height: H, inside: coreBefore.data }, grow);
5141
+ copiedMask = newMask(W, H);
5142
+ copiedMask.data.set(grown.inside);
5143
+ let coveredAfter = 0;
5144
+ for (let p = 0; p < W * H; p++) if (copiedMask.data[p] === 1) coveredAfter++;
5145
+ occluderGrowRecords.push({
5146
+ occluder: index,
5147
+ image: declaration.image,
5148
+ grow,
5149
+ covered_px_before: coveredBefore,
5150
+ covered_px_after: coveredAfter,
5151
+ });
5152
+ }
5153
+ let guardMask = copiedMask;
5154
+ if (guard > 0) {
5155
+ if (guard > grow) {
5156
+ const guarded = growMask({ width: W, height: H, inside: coreBefore.data }, guard);
5157
+ guardMask = newMask(W, H);
5158
+ guardMask.data.set(guarded.inside);
5159
+ }
5160
+ let guardedAfter = 0;
5161
+ for (let p = 0; p < W * H; p++) if (guardMask.data[p] === 1) guardedAfter++;
5162
+ occluderGuardRecords.push({
5163
+ occluder: index,
5164
+ image: declaration.image,
5165
+ guard,
5166
+ guarded_px_before: coveredBefore,
5167
+ guarded_px_after: guardedAfter,
5168
+ });
5169
+ }
5170
+ return { index, declaration, coreBefore, copiedMask, guardMask };
5171
+ });
5172
+ const occluderCoreMasks = occluderEntries.map((e) => e.coreBefore);
5023
5173
  if ((input.requireHiddenExtent?.length ?? 0) > 0) {
5024
5174
  // Read the selected original layers, before split/underfill/cleanup can replace their material.
5025
5175
  const originals = input.plan.map(([name, run, tag]): HiddenExtentSource => {
5026
5176
  const set = run === 'full' ? fullPadded : depthHeadInput;
5027
5177
  const layer = set.layers.find(candidate => candidate.name === tag);
5028
- return { name, from: `${run}:${tag}`, image: layer === undefined ? null : layerToRig(placeLayer(layer, input.resolution), frame, run) };
5178
+ return { name, from: `${run}:${tag}`, image: layer === undefined ? null : layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks) };
5029
5179
  });
5030
5180
  const painting = patches.length === 0 ? null : sourceInRig(source, frame.W, frame.H);
5031
5181
  const silhouette = painting === null ? null : figureSilhouette(painting);
@@ -5067,36 +5217,19 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5067
5217
  const registeredDepth = new Map([...depthFull, ...depthHead]);
5068
5218
  if (single) checkSingleRun(full, plan, extend);
5069
5219
  checkPlanAgainstRuns(sourcePlan, extend, full, head);
5070
- const { W, H } = frame;
5071
5220
  const srcr = sourceInRig(source, W, H);
5072
5221
  const supportPainted = paintedFigure(srcr);
5073
5222
  const groundShare = groundRingShare(srcr, supportPainted);
5074
- const occSx = (x: number): number => Math.min(source.width - 1, Math.floor((x + 0.5) * source.width / W));
5075
- const occSy = (y: number): number => Math.min(source.height - 1, Math.floor((y + 0.5) * source.height / H));
5076
- const occluderEntries = (input.occluders ?? []).map(({ declaration, image }, index) => {
5077
- const opaqueMask = newMask(W, H);
5078
- const copiedMask = newMask(W, H);
5079
- for (let y = 0; y < H; y++) {
5080
- const srcY = occSy(y);
5081
- for (let x = 0; x < W; x++) {
5082
- const a = image.data[(srcY * source.width + occSx(x)) * 4 + 3];
5083
- 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;
5086
- }
5087
- }
5088
- return { index, declaration, opaqueMask, copiedMask };
5089
- });
5090
5223
  const occluderUnderKeepByPlanPart = new Map<string, Mask>();
5091
5224
  if (projectRule === 'visible') {
5092
- for (const { declaration, copiedMask } of occluderEntries) {
5225
+ for (const { declaration, guardMask } of occluderEntries) {
5093
5226
  for (const u of declaration.under) {
5094
5227
  let m = occluderUnderKeepByPlanPart.get(u);
5095
5228
  if (m === undefined) {
5096
5229
  m = newMask(W, H);
5097
5230
  occluderUnderKeepByPlanPart.set(u, m);
5098
5231
  }
5099
- for (let p = 0; p < W * H; p++) if (copiedMask.data[p] === 1) m.data[p] = 1;
5232
+ for (let p = 0; p < W * H; p++) if (guardMask.data[p] === 1) m.data[p] = 1;
5100
5233
  }
5101
5234
  }
5102
5235
  }
@@ -5106,11 +5239,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5106
5239
  const hiddenUses = new Map<string, string[]>();
5107
5240
  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
5241
  const hiddenProblems: Problem[] = [];
5242
+ const showCutUnder = (u: Cut['under']): string => typeof u === 'object' && u !== null ? `{"plate": ${JSON.stringify(u.plate)}}` : String(u);
5109
5243
  const unders = input.cuts.map((q, i) => {
5110
5244
  const art = hiddenArt.get(q.from);
5111
5245
  if (art === undefined) return input.under?.[i] ?? null;
5112
5246
  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` });
5247
+ 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
5248
  return null;
5115
5249
  }
5116
5250
  const box = underBox(q.polygon);
@@ -5171,7 +5305,14 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5171
5305
  }
5172
5306
  }
5173
5307
  if (run === 'full') fullTags.push(...layers.filter((l) => l.opaqueRunPx > 0).map((l) => l.tag));
5174
- const rigLayers = layers.map((l) => layerToRig(l.canvas, frame, run));
5308
+ const rigLayers = layers.map((l) => {
5309
+ const srcLayer = set.layers.find((q) => q.name === l.tag);
5310
+ return srcLayer?.occluderSplit !== undefined &&
5311
+ srcLayer.pixels === srcLayer.occluderSplit.merged &&
5312
+ srcLayer.regionSelection === undefined
5313
+ ? layerToRigSplit(srcLayer, input.resolution, frame, run, occluderCoreMasks, true)
5314
+ : layerToRig(l.canvas, frame, run);
5315
+ });
5175
5316
  const rank = planRanks(layers.map((l) => l.tag), run, sourcePlan);
5176
5317
  const keep = layers.map((l, i): Mask | null => {
5177
5318
  let mask: Mask | null = null;
@@ -5227,19 +5368,28 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5227
5368
  : original === undefined ? [] : [original];
5228
5369
  let raw: Raster | null = null;
5229
5370
  if (author === 0 && sourceLayers.length > 0) {
5230
- // A sole layer needs no composite copy: layerToRig premultiplies,
5231
- // so discarded RGB at alpha 0 has exactly the same float32 input.
5232
- const canvas = sourceLayers.length === 1 ? placeLayer(sourceLayers[0], input.resolution) : newRaster(input.resolution, input.resolution);
5233
- if (sourceLayers.length > 1) for (const originalLayer of sourceLayers) {
5234
- const sourceCanvas = placeLayer(originalLayer, input.resolution);
5235
- for (let p = 0; p < input.resolution * input.resolution; p++) if (sourceCanvas.data[p * 4 + 3] > 0) canvas.data.set(sourceCanvas.data.subarray(p * 4, p * 4 + 4), p * 4);
5371
+ if (
5372
+ sourceLayers.length === 1 &&
5373
+ sourceLayers[0].occluderSplit !== undefined &&
5374
+ sourceLayers[0].pixels === sourceLayers[0].occluderSplit.merged
5375
+ ) {
5376
+ raw = layerToRigSplit(sourceLayers[0], input.resolution, frame, run, occluderCoreMasks);
5377
+ } else {
5378
+ // A sole layer needs no composite copy: layerToRig premultiplies,
5379
+ // so discarded RGB at alpha 0 has exactly the same float32 input.
5380
+ const canvas = sourceLayers.length === 1 ? placeLayer(sourceLayers[0], input.resolution) : newRaster(input.resolution, input.resolution);
5381
+ if (sourceLayers.length > 1) for (const originalLayer of sourceLayers) {
5382
+ const sourceCanvas = placeLayer(originalLayer, input.resolution);
5383
+ for (let p = 0; p < input.resolution * input.resolution; p++) if (sourceCanvas.data[p * 4 + 3] > 0) canvas.data.set(sourceCanvas.data.subarray(p * 4, p * 4 + 4), p * 4);
5384
+ }
5385
+ raw = layerToRig(canvas, frame, run);
5236
5386
  }
5237
- raw = layerToRig(canvas, frame, run);
5238
5387
  }
5239
5388
  // Reuse only a proved identical placed input, never wrapper identity.
5240
5389
  const samePlacedSource = raw !== null && sourceLayers.length === 1 && prepared !== undefined &&
5241
- sourceLayers[0].pixels === prepared.pixels && sourceLayers[0].left === prepared.left && sourceLayers[0].top === prepared.top;
5242
- const preparedRig = samePlacedSource ? raw : prepared === undefined ? null : layerToRig(placeLayer(prepared, input.resolution), frame, run);
5390
+ sourceLayers[0].pixels === prepared.pixels && sourceLayers[0].left === prepared.left && sourceLayers[0].top === prepared.top &&
5391
+ sourceLayers[0].occluderSplit === prepared.occluderSplit;
5392
+ const preparedRig = samePlacedSource ? raw : prepared === undefined ? null : layerToRigSplit(prepared, input.resolution, frame, run, occluderCoreMasks);
5243
5393
  for (let p = 0; p < W * H; p++) {
5244
5394
  if (rigLayers[i].data[p * 4 + 3] === 0) continue;
5245
5395
  ids[p] = author;
@@ -5374,7 +5524,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5374
5524
  const object = `config.assemble.cuts[${i}].under (part "${q.into}")`;
5375
5525
  const u = unders[i];
5376
5526
  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)` });
5527
+ 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
5528
  return;
5379
5529
  }
5380
5530
  const box = underBox(q.polygon);
@@ -5382,7 +5532,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5382
5532
  patchProblems.push({
5383
5533
  code: 'ASSEMBLE_UNDER_SIZE',
5384
5534
  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)`,
5535
+ 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
5536
  });
5387
5537
  }
5388
5538
  const at = order0.findIndex((d) => 'cut' in d && d.cut === i);
@@ -5588,7 +5738,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5588
5738
  empty.push({
5589
5739
  code: 'ASSEMBLE_UNDER_EMPTY',
5590
5740
  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`,
5741
+ 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
5742
  });
5593
5743
  }
5594
5744
  return { ...f, opaqueFilled };
@@ -5607,6 +5757,11 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5607
5757
  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
5758
  });
5609
5759
  });
5760
+ const cutFillMasks = cuts.map((q, i) => ({
5761
+ into: q.into,
5762
+ from: q.from,
5763
+ mask: pieces[i] === null ? newRaster(source.width, source.height) : cutFillMask((pieces[i] as Built).r, source.width, source.height),
5764
+ }));
5610
5765
  // Parent partition counts and under use the removed parent art above. Only
5611
5766
  // the emitted piece (and any limb cut from it) reads this independent source.
5612
5767
  cutSources.forEach((source, i) => {
@@ -5994,7 +6149,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5994
6149
  const canvases = stack.map(onRig);
5995
6150
  const rawPlan = input.plan.map(([name, run, tag]) => {
5996
6151
  const layer = input[run].layers.find(l => l.name === tag)!;
5997
- return { name, raster: layerToRig(placeLayer(layer, input.resolution), frame, run), keep: occluderUnderKeepByPlanPart.get(name) ?? null };
6152
+ return { name, raster: layerToRigSplit(layer, input.resolution, frame, run, occluderCoreMasks), keep: occluderUnderKeepByPlanPart.get(name) ?? null };
5998
6153
  });
5999
6154
  if ((input.edgeSplits?.length ?? 0) > 0) applyEdgeSplits(input.edgeSplits!, new Map(rawPlan.map(p => [p.name, p.raster])), srcr);
6000
6155
  const owner = rawPaintingOwner(rawPlan, W * H);
@@ -6070,30 +6225,34 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6070
6225
  const stackCanvases = occluderEntries.length === 0 ? [] : stack.map(onRig);
6071
6226
  const occluderWithSlot = occluderEntries.map((entry) => {
6072
6227
  let lastUnderIdx = -1;
6228
+ let firstOverIdx = -1;
6073
6229
  order.forEach((d, idx) => {
6074
6230
  const root = rootPlanPartOfSlot(d);
6075
- if (root !== null && entry.declaration.under.includes(root)) lastUnderIdx = idx;
6231
+ if (root === null) return;
6232
+ if (entry.declaration.under.includes(root)) lastUnderIdx = idx;
6233
+ if (firstOverIdx < 0 && (entry.declaration.over?.includes(root) ?? false)) firstOverIdx = idx;
6076
6234
  });
6077
- return { ...entry, lastUnderIdx };
6235
+ const insertBeforeIdx = firstOverIdx >= 0 ? firstOverIdx : lastUnderIdx + 1;
6236
+ return { ...entry, lastUnderIdx, firstOverIdx, insertBeforeIdx };
6078
6237
  });
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)) {
6238
+ const builtOccluderParts: Array<{ index: number; insertBeforeIdx: number; canvas: Raster; placed: PlacedPart }> = [];
6239
+ for (const entry of [...occluderWithSlot].filter((e) => e.declaration.part !== undefined).sort((a, b) => b.insertBeforeIdx - a.insertBeforeIdx || b.index - a.index)) {
6081
6240
  const partName = entry.declaration.part!;
6082
6241
  const occCanvas = newRaster(W, H);
6083
6242
  const occVisible = newMask(W, H);
6084
6243
  const occProjected = newMask(W, H);
6085
6244
  for (let p = 0; p < W * H; p++) {
6086
- if (entry.opaqueMask.data[p] !== 1) continue;
6245
+ if (entry.copiedMask.data[p] !== 1) continue;
6087
6246
  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) {
6247
+ for (let j = entry.insertBeforeIdx; j < stackCanvases.length; j++) {
6248
+ if (stackCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
6090
6249
  heldInFront = true;
6091
6250
  break;
6092
6251
  }
6093
6252
  }
6094
6253
  if (!heldInFront) {
6095
6254
  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) {
6255
+ if ((frontOcc.insertBeforeIdx > entry.insertBeforeIdx || (frontOcc.insertBeforeIdx === entry.insertBeforeIdx && frontOcc.index > entry.index)) && frontOcc.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6097
6256
  heldInFront = true;
6098
6257
  break;
6099
6258
  }
@@ -6109,7 +6268,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6109
6268
  if (opaque === 0 && emptyTargets?.has(partName)) {
6110
6269
  builtOccluderParts.push({
6111
6270
  index: entry.index,
6112
- lastUnderIdx: entry.lastUnderIdx,
6271
+ insertBeforeIdx: entry.insertBeforeIdx,
6113
6272
  canvas: occCanvas,
6114
6273
  placed: {
6115
6274
  record: {
@@ -6127,7 +6286,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6127
6286
  empty.push({
6128
6287
  code: OCCLUDER_EMPTY,
6129
6288
  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`,
6289
+ 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
6290
  });
6132
6291
  continue;
6133
6292
  }
@@ -6151,12 +6310,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6151
6310
  };
6152
6311
  builtOccluderParts.push({
6153
6312
  index: entry.index,
6154
- lastUnderIdx: entry.lastUnderIdx,
6313
+ insertBeforeIdx: entry.insertBeforeIdx,
6155
6314
  canvas: occCanvas,
6156
6315
  placed: { record, image: crop(occCanvas, x0, y0, record.w, record.h) },
6157
6316
  });
6158
6317
  }
6159
- builtOccluderParts.sort((a, b) => a.lastUnderIdx - b.lastUnderIdx || a.index - b.index);
6318
+ builtOccluderParts.sort((a, b) => a.insertBeforeIdx - b.insertBeforeIdx || a.index - b.index);
6160
6319
  pieceList.forEach(({ name, b, pushed: pushedHere, at, cutFrom, limb, set }) => {
6161
6320
  const { key, r, st, extendKeys, trace, merged, region } = b;
6162
6321
  // A pixel the merge wrote is judged in the extend layer's run, every other
@@ -6176,7 +6335,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6176
6335
  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
6336
  if (slotIdx >= 0) {
6178
6337
  for (const occPart of builtOccluderParts) {
6179
- if (occPart.lastUnderIdx >= slotIdx && occPart.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6338
+ if (occPart.insertBeforeIdx > slotIdx && occPart.canvas.data[p * 4 + 3] >= CORE_ALPHA) {
6180
6339
  visible.data[p] = 0;
6181
6340
  projected.data[p] = 0;
6182
6341
  break;
@@ -6270,7 +6429,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6270
6429
  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
6430
  let spliceOffset = 0;
6272
6431
  for (const occPart of builtOccluderParts) {
6273
- const insertAt = occPart.lastUnderIdx + 1 + spliceOffset;
6432
+ const insertAt = occPart.insertBeforeIdx + spliceOffset;
6274
6433
  placed.splice(insertAt, 0, occPart.placed);
6275
6434
  keepInOrder.splice(insertAt, 0, null);
6276
6435
  writersInOrder.splice(insertAt, 0, new Int32Array(W * H).fill(AW.sourceProjection));
@@ -6281,11 +6440,11 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6281
6440
  const placedCanvases = placed.map(onRig);
6282
6441
  for (const entry of occluderWithSlot) {
6283
6442
  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;
6443
+ const frontStart = entry.insertBeforeIdx + builtOccluderParts.filter((o) => o.insertBeforeIdx < entry.insertBeforeIdx || (o.insertBeforeIdx === entry.insertBeforeIdx && o.index < entry.index)).length;
6285
6444
  let unheldPx = 0;
6286
6445
  let firstP = -1;
6287
6446
  for (let p = 0; p < W * H; p++) {
6288
- if (entry.opaqueMask.data[p] !== 1) continue;
6447
+ if (entry.copiedMask.data[p] !== 1) continue;
6289
6448
  let held = false;
6290
6449
  for (let j = frontStart; j < placedCanvases.length; j++) {
6291
6450
  if (placedCanvases[j].data[p * 4 + 3] >= CORE_ALPHA) {
@@ -6299,7 +6458,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6299
6458
  }
6300
6459
  }
6301
6460
  if (unheldPx > 0) {
6302
- occluderUnheldWarnings.push(occluderUnheldWarning(entry.index, entry.declaration.image, entry.declaration.under, unheldPx, [firstP % W, Math.floor(firstP / W)]));
6461
+ occluderUnheldWarnings.push(occluderUnheldWarning(entry.index, entry.declaration.image, entry.declaration.under, unheldPx, [firstP % W, Math.floor(firstP / W)], CORE_ALPHA));
6303
6462
  }
6304
6463
  }
6305
6464
  }
@@ -6406,6 +6565,8 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6406
6565
  ghost_px: ghost,
6407
6566
  recomposite: recompositeRecord(figures),
6408
6567
  ...(sceneRecord === null ? {} : { scene: sceneRecord }),
6568
+ ...(occluderGrowRecords.length === 0 ? {} : { occluder_grow: occluderGrowRecords }),
6569
+ ...(occluderGuardRecords.length === 0 ? {} : { occluder_guard: occluderGuardRecords }),
6409
6570
  ...(padRecord === null ? {} : { single_run_pad: padRecord }),
6410
6571
  },
6411
6572
  images: placed,
@@ -6438,6 +6599,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6438
6599
  splits: islandKept.splits,
6439
6600
  capSplits: capAssigned.counts,
6440
6601
  edgeSplits,
6602
+ ...(cutFillMasks.length === 0 ? {} : { cutFillMasks }),
6441
6603
  };
6442
6604
  }
6443
6605
 
@@ -7114,7 +7276,24 @@ export function proposePlan(full0: LayerSet, head0: LayerSet, g: Geometry, minPx
7114
7276
  }
7115
7277
  }
7116
7278
  for (const t of heads) plan.push([aliasOf(t), headRun(t), t]);
7117
- orderPlanForOccluders(plan, g.occluderDeclarations);
7279
+ for (const split of g.occluderSplitParts ?? []) {
7280
+ const row = plan.find(([, run, tag]) => run === split.run && tag === split.tag);
7281
+ if (row === undefined) {
7282
+ notes.push(`assemble.take occluder split "${split.part}" (${split.run}:${split.tag}) matched no proposed row`);
7283
+ } else if (row[0] !== split.part) {
7284
+ if (plan.some((r) => r !== row && r[0] === split.part)) {
7285
+ 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]}"`);
7286
+ } else {
7287
+ notes.push(`${split.tag}: proposed as "${split.part}", the part its occluder-split take declares`);
7288
+ row[0] = split.part;
7289
+ }
7290
+ }
7291
+ }
7292
+ const occluderTakenTags: Record<string, string> = { ...g.occluderTakenTags };
7293
+ for (const l of [...full0.layers, ...head0.layers]) {
7294
+ if (l.takenLayers !== undefined && l.takenLayers.length > 0) occluderTakenTags[l.name] = l.name;
7295
+ }
7296
+ notes.push(...orderPlanForOccluders(plan, g.occluderDeclarations, Object.keys(occluderTakenTags).length > 0 ? occluderTakenTags : undefined));
7118
7297
  for (const [part, run, tag] of plan) {
7119
7298
  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
7299
  }
@@ -7404,23 +7583,55 @@ export function stageFields(
7404
7583
  * loader's rules; what is left here is that this stage needs the head box,
7405
7584
  * which that loader leaves optional.
7406
7585
  */
7586
+ function occluderTakenTagsOf(cfg: EarlyConfig): Readonly<Record<string, string>> | undefined {
7587
+ const take = cfg.assemble.take;
7588
+ if (take === undefined || take.length === 0) return undefined;
7589
+ const out: Record<string, string> = {};
7590
+ for (const item of take) {
7591
+ if ('tags' in item) {
7592
+ for (const tag of item.tags) out[tag] = tag;
7593
+ } else if ('occluder' in item) {
7594
+ out[item.part] = item.tag;
7595
+ out[item.tag] = item.tag;
7596
+ }
7597
+ }
7598
+ const rawPlan = (cfg.assemble as { plan?: unknown }).plan;
7599
+ if (Array.isArray(rawPlan)) {
7600
+ for (const row of rawPlan) {
7601
+ if (!Array.isArray(row) || typeof row[0] !== 'string' || typeof row[1] !== 'string' || typeof row[2] !== 'string') continue;
7602
+ const [part, run, tag] = row;
7603
+ const taken = take.some(
7604
+ (item) =>
7605
+ ('tags' in item && item.run === run && item.tags.includes(tag)) ||
7606
+ ('occluder' in item && item.run === run && item.tag === tag),
7607
+ );
7608
+ if (taken) out[part] = tag;
7609
+ }
7610
+ }
7611
+ return Object.keys(out).length === 0 ? undefined : out;
7612
+ }
7613
+
7407
7614
  export function proposeFields(
7408
7615
  cfg: EarlyConfig,
7409
7616
  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[] } {
7617
+ ): { 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
7618
  const armSplit = cfg.seethrough.arm_split === undefined ? {} : { armSplit: cfg.seethrough.arm_split };
7412
7619
  const keySkeleton = controlSkeletonOf(cfg);
7413
7620
  const skelField = keySkeleton === undefined ? {} : { keySkeleton };
7414
7621
  const underfillField = cfg.assemble.head_face_underfill === undefined ? {} : { headFaceUnderfill: cfg.assemble.head_face_underfill };
7415
7622
  const occludersField = cfg.assemble.occluders === undefined ? {} : { occluderDeclarations: cfg.assemble.occluders };
7623
+ const takenTags = occluderTakenTagsOf(cfg);
7624
+ const takenTagsField = takenTags === undefined ? {} : { occluderTakenTags: takenTags };
7625
+ const splitParts = (cfg.assemble.take ?? []).flatMap((item) => ('occluder' in item ? [{ run: item.run, part: item.part, tag: item.tag }] : []));
7626
+ const splitField = splitParts.length === 0 ? {} : { occluderSplitParts: splitParts };
7416
7627
  if (single !== null) {
7417
7628
  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 };
7629
+ 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
7630
  }
7420
7631
  if (cfg.seethrough.head_box === undefined) {
7421
7632
  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
7633
  }
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 };
7634
+ 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
7635
  }
7425
7636
 
7426
7637
  /**