rig-parts 2.52.0 → 2.53.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
@@ -16,6 +16,8 @@ import { authoredUnitDepths, type AuthoredUnitDepth } from './authoredunit.ts';
16
16
  import { paintingExtensionMasks, paintingExtensionProblems, type PaintingExtension } from './paintingextension.ts';
17
17
  import { applyEdgeSplits, edgeSplitLines, edgeSplitProblems, type EdgeSplit, type EdgeSplitReading } from './edgesplit.ts';
18
18
  import { AUTOMATIC_WRITERS as AW, compactValueBaseline, pixelProvenance, rgbaEqual, type ValueBaseline, type StageMap } from './provenance.ts';
19
+ import type { PartVisibility } from './partvisibility.ts';
20
+ import { encodeSourceStateMap, sourceStateMapImage } from './sourcestates.ts';
19
21
  import { bindDepthRun, copyDepthMaterial, registerDepthRun, transportPartDepth, type DepthConfig, type RegisteredDepth } from './depthsheets.ts';
20
22
  import { COPIED_ALPHA_ABOVE, OCCLUDER_EMPTY, occluderDrawCycleProblems, type OccluderDeclaration, occluderUnheldWarning, orderPlanForOccluders } from './occluders.ts';
21
23
  /**
@@ -326,6 +328,7 @@ export function singleRunPadRecord(single: boolean, sourceW: number, sourceH: nu
326
328
  }
327
329
 
328
330
  export interface AssembleInput {
331
+ visibility?: PartVisibility;
329
332
  /** Verified whole-file base-part edits, placed after all normal raster passes. */
330
333
  editedParts?: readonly VerifiedEditedPart[];
331
334
  /** Observe allocation decisions after guarding and restoration. */
@@ -1275,12 +1278,13 @@ export function checkGeometry(g: Geometry, runs?: { full: LayerSet; head: LayerS
1275
1278
  * Place a layer's pixels on its run's `resolution x resolution` canvas.
1276
1279
  * `readWrapperLayers`/`readPsdLayers` already refused a box outside it.
1277
1280
  */
1278
- export function placeLayer(layer: Pick<Layer, 'pixels' | 'left' | 'top'>, resolution: number): Raster {
1281
+ export function placeLayer(layer: Pick<Layer, 'pixels' | 'left' | 'top'>, resolution: number, visibility?: PartVisibility): Raster {
1279
1282
  const out = newRaster(resolution, resolution);
1280
1283
  const p = layer.pixels;
1281
1284
  for (let y = 0; y < p.height; y++) {
1282
1285
  out.data.set(p.data.subarray(y * p.width * 4, (y + 1) * p.width * 4), ((layer.top + y) * resolution + layer.left) * 4);
1283
1286
  }
1287
+ visibility?.rows(out, p, 0, 0, p.width, p.height, layer.left, layer.top);
1284
1288
  return out;
1285
1289
  }
1286
1290
 
@@ -1296,9 +1300,10 @@ export function placeLayer(layer: Pick<Layer, 'pixels' | 'left' | 'top'>, resolu
1296
1300
  * `alpha > 8` pixel comes back fully transparent with `ghostPx` 0.
1297
1301
  * (`assemble_parts.py` `clean`.)
1298
1302
  */
1299
- export function cleanGhosts(canvas: Raster): { canvas: Raster; ghostPx: number } {
1303
+ export function cleanGhosts(canvas: Raster, visibility?: PartVisibility): { canvas: Raster; ghostPx: number } {
1300
1304
  const { width: w, height: h } = canvas;
1301
1305
  const out: Raster = { width: w, height: h, data: new Uint8ClampedArray(canvas.data) };
1306
+ visibility?.clone(canvas, out);
1302
1307
  const m = newMask(w, h);
1303
1308
  let any = false;
1304
1309
  for (let i = 0; i < w * h; i++) {
@@ -1338,9 +1343,9 @@ export interface RunLayer {
1338
1343
  }
1339
1344
 
1340
1345
  /** Every layer of a run, placed and cleaned, in draw order (back to front). */
1341
- export function runLayers(set: LayerSet, resolution: number): RunLayer[] {
1346
+ export function runLayers(set: LayerSet, resolution: number, visibility?: PartVisibility): RunLayer[] {
1342
1347
  return set.layers.map((layer) => {
1343
- const { canvas, ghostPx } = cleanGhosts(placeLayer(layer, resolution));
1348
+ const { canvas, ghostPx } = cleanGhosts(placeLayer(layer, resolution, visibility), visibility);
1344
1349
  let opaqueRunPx = 0;
1345
1350
  for (let i = 3; i < canvas.data.length; i += 4) if (canvas.data[i] > OPAQUE_ALPHA_ABOVE) opaqueRunPx++;
1346
1351
  return { tag: layer.name, canvas, drawOrder: layer.drawOrder, ghostPx, opaqueRunPx };
@@ -1400,7 +1405,7 @@ function splitColumnsAtRow(y: number, armSplit: ArmSplit): number[] {
1400
1405
  * - either resulting arm layer is left with 0 opaque pixels, or an arm is cut
1401
1406
  * into disconnected components.
1402
1407
  */
1403
- export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSplit): LayerSet {
1408
+ export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSplit, visibility?: PartVisibility): LayerSet {
1404
1409
  const handLayers = set.layers.filter((l) => l.name === 'handwear-r' || l.name === 'handwear-l');
1405
1410
  if (handLayers.length === 0) {
1406
1411
  refuseIfAny([
@@ -1414,12 +1419,15 @@ export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSp
1414
1419
  const combinedRaw = newRaster(resolution, resolution);
1415
1420
  const scalarOwners = handLayers.some(l => l.depthSheet !== undefined) ? new Int32Array(resolution * resolution).fill(-1) : null;
1416
1421
  for (const [layerIndex, l] of handLayers.entries()) {
1417
- const { canvas } = cleanGhosts(placeLayer(l, resolution));
1422
+ const { canvas } = cleanGhosts(placeLayer(l, resolution, visibility), visibility);
1418
1423
  for (let p = 0; p < resolution * resolution; p++) {
1419
- if (canvas.data[p * 4 + 3] > 0) { combinedRaw.data.set(canvas.data.subarray(p * 4, p * 4 + 4), p * 4); if (scalarOwners !== null) scalarOwners[p] = layerIndex; }
1424
+ if (canvas.data[p * 4 + 3] === 0) continue;
1425
+ combinedRaw.data.set(canvas.data.subarray(p * 4, p * 4 + 4), p * 4);
1426
+ if (scalarOwners !== null) scalarOwners[p] = layerIndex;
1427
+ visibility?.copy(combinedRaw, p, canvas);
1420
1428
  }
1421
1429
  }
1422
- const { canvas: combined } = cleanGhosts(combinedRaw);
1430
+ const { canvas: combined } = cleanGhosts(combinedRaw, visibility);
1423
1431
  const rightCanvas = newRaster(resolution, resolution);
1424
1432
  const leftCanvas = newRaster(resolution, resolution);
1425
1433
  let firstCutRun: { y: number; rx0: number; rx1: number; col: number } | null = null;
@@ -1463,8 +1471,9 @@ export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSp
1463
1471
  for (let cx = 0; cx < resolution; cx++) {
1464
1472
  const p = (y * resolution + cx) * 4;
1465
1473
  if (combined.data[p + 3] === 0) continue;
1466
- const dst = cx < col ? rightCanvas.data : leftCanvas.data;
1467
- dst.set(combined.data.subarray(p, p + 4), p);
1474
+ const dst = cx < col ? rightCanvas : leftCanvas;
1475
+ dst.data.set(combined.data.subarray(p, p + 4), p);
1476
+ visibility?.copy(dst, p / 4, combined);
1468
1477
  }
1469
1478
  }
1470
1479
  const maskOf = (r: Raster): { mask: Mask; opaque: number; x0: number; y0: number; x1: number; y1: number } => {
@@ -1528,7 +1537,7 @@ export function applyArmSplit(set: LayerSet, resolution: number, armSplit: ArmSp
1528
1537
  tag: readLayerTag(name) as LayerTagReading,
1529
1538
  file: refLayer.file,
1530
1539
  takenLayers: unionTakenSources(handLayers.map(l => l.takenLayers)),
1531
- pixels: crop(canvas, m.x0, m.y0, m.x1 - m.x0 + 1, m.y1 - m.y0 + 1),
1540
+ pixels: visibilityCrop(canvas, m.x0, m.y0, m.x1 - m.x0 + 1, m.y1 - m.y0 + 1, visibility),
1532
1541
  left: m.x0,
1533
1542
  top: m.y0,
1534
1543
  right: m.x1 + 1,
@@ -1657,6 +1666,7 @@ export function splitMergedArmRunsWithNotes(
1657
1666
  sourceW: number,
1658
1667
  sourceH: number,
1659
1668
  keySkeleton: ControlSkeleton,
1669
+ visibility?: PartVisibility,
1660
1670
  ): { set: LayerSet; notes: string[] } {
1661
1671
  const [latentW, latentH] = keySkeleton.latent;
1662
1672
  const sx = sourceW / latentW;
@@ -1674,7 +1684,7 @@ export function splitMergedArmRunsWithNotes(
1674
1684
  const tag = `handwear-${s}` as const;
1675
1685
  const hwLayer = set.layers.find((l) => l.name === tag);
1676
1686
  if (hwLayer === undefined) continue;
1677
- const { canvas: cleaned } = cleanGhosts(placeLayer(hwLayer, resolution));
1687
+ const { canvas: cleaned } = cleanGhosts(placeLayer(hwLayer, resolution, visibility), visibility);
1678
1688
  const sh = toRun(keySkeleton.points[`${s}_shoulder`]);
1679
1689
  const el = toRun(keySkeleton.points[`${s}_elbow`]);
1680
1690
  const wr = toRun(keySkeleton.points[`${s}_wrist`]);
@@ -1833,12 +1843,14 @@ export function splitMergedArmRunsWithNotes(
1833
1843
  }
1834
1844
  }
1835
1845
  if (opaque === 0 || x1 < x0) return null;
1846
+ visibility?.clone(cleaned, canvas);
1847
+ visibility?.forgetNative(canvas); // The split discarded part of the source before the warp.
1836
1848
  return copyDepthMaterial({
1837
1849
  name,
1838
1850
  tag: readLayerTag(name) as LayerTagReading,
1839
1851
  file: hwLayer.file,
1840
1852
  ...(hwLayer.takenLayers === undefined ? {} : { takenLayers: hwLayer.takenLayers }),
1841
- pixels: crop(canvas, x0, y0, x1 - x0 + 1, y1 - y0 + 1),
1853
+ pixels: visibilityCrop(canvas, x0, y0, x1 - x0 + 1, y1 - y0 + 1, visibility),
1842
1854
  left: x0,
1843
1855
  top: y0,
1844
1856
  right: x1 + 1,
@@ -1881,8 +1893,9 @@ export function splitMergedArmRuns(
1881
1893
  sourceW: number,
1882
1894
  sourceH: number,
1883
1895
  keySkeleton: ControlSkeleton,
1896
+ visibility?: PartVisibility,
1884
1897
  ): LayerSet {
1885
- return splitMergedArmRunsWithNotes(set, resolution, frame, sourceW, sourceH, keySkeleton).set;
1898
+ return splitMergedArmRunsWithNotes(set, resolution, frame, sourceW, sourceH, keySkeleton, visibility).set;
1886
1899
  }
1887
1900
 
1888
1901
  /**
@@ -1939,7 +1952,7 @@ export function runMap(frame: Frame, run: Run): { k: number; sx: number; tx: num
1939
1952
  * without being warped: every tap would read 0.
1940
1953
  * (`assemble_parts.py` `to_rig`.)
1941
1954
  */
1942
- export function layerToRig(canvas: Raster, frame: Frame, run: Run): Raster {
1955
+ export function layerToRig(canvas: Raster, frame: Frame, run: Run, visibility?: PartVisibility): Raster {
1943
1956
  const { W, H } = frame;
1944
1957
  const n = canvas.width * canvas.height;
1945
1958
  let any = false;
@@ -1953,7 +1966,9 @@ export function layerToRig(canvas: Raster, frame: Frame, run: Run): Raster {
1953
1966
  pre.data[i * 4 + 3] = a;
1954
1967
  }
1955
1968
  const m = runMap(frame, run);
1956
- const wr = warpAffine(pre, { sx: m.sx, sy: m.sx, tx: m.tx, ty: m.ty }, W, H, m.k < 1 ? 'bilinear' : 'bicubic');
1969
+ const map = { sx: m.sx, sy: m.sx, tx: m.tx, ty: m.ty };
1970
+ const filter = m.k < 1 ? 'bilinear' : 'bicubic';
1971
+ const wr = warpAffine(pre, map, W, H, filter);
1957
1972
  const out = newRaster(W, H);
1958
1973
  const eps = f32(1e-3);
1959
1974
  const clip = (v: number): number => (v < 0 ? 0 : v > 255 ? 255 : v);
@@ -1965,6 +1980,7 @@ export function layerToRig(canvas: Raster, frame: Frame, run: Run): Raster {
1965
1980
  }
1966
1981
  out.data[i * 4 + 3] = Math.trunc(a);
1967
1982
  }
1983
+ visibility?.warp(canvas, out, map, filter, undefined, run === 'full' ? frame : undefined);
1968
1984
  return out;
1969
1985
  }
1970
1986
 
@@ -2004,10 +2020,12 @@ export function layerToRigSplit(
2004
2020
  run: Run,
2005
2021
  occluderCoreMasks: readonly Mask[],
2006
2022
  cleaned = false,
2023
+ visibility?: PartVisibility,
2007
2024
  ): Raster {
2008
2025
  const toRig = (l: Layer): Raster => {
2009
- const placed = placeLayer(l, resolution);
2010
- return layerToRig(cleaned ? cleanGhosts(placed).canvas : placed, frame, run);
2026
+ const placed = placeLayer(l, resolution, visibility);
2027
+ if (!cleaned) visibility?.forgetNative(placed);
2028
+ return layerToRig(cleaned ? cleanGhosts(placed, visibility).canvas : placed, frame, run, visibility);
2011
2029
  };
2012
2030
  const split = layer.occluderSplit;
2013
2031
  const mask = split === undefined ? undefined : occluderCoreMasks[split.occluder];
@@ -2016,16 +2034,18 @@ export function layerToRigSplit(
2016
2034
  // base across the occluder edge is one component there. What the merged clean-up drops is dropped from both sides.
2017
2035
  const kept = cleaned ? cleanGhosts(placeLayer(layer, resolution)).canvas : null;
2018
2036
  const sideToRig = (l: Layer): Raster => {
2019
- const placed = placeLayer(l, resolution);
2037
+ const placed = placeLayer(l, resolution, visibility);
2038
+ visibility?.forgetNative(placed);
2020
2039
  if (kept !== null) for (let p = 0; p < resolution * resolution; p++) if (kept.data[p * 4 + 3] === 0) placed.data[p * 4 + 3] = 0;
2021
- return layerToRig(placed, frame, run);
2040
+ return layerToRig(placed, frame, run, visibility);
2022
2041
  };
2023
2042
  const baseRig = sideToRig(split.base);
2024
2043
  const donorRig = sideToRig(split.donor);
2025
2044
  const out = newRaster(frame.W, frame.H);
2026
2045
  for (let p = 0; p < frame.W * frame.H; p++) {
2027
- const src = mask.data[p] === 1 ? baseRig.data : donorRig.data;
2028
- out.data.set(src.subarray(p * 4, p * 4 + 4), p * 4);
2046
+ const src = mask.data[p] === 1 ? baseRig : donorRig;
2047
+ out.data.set(src.data.subarray(p * 4, p * 4 + 4), p * 4);
2048
+ visibility?.copy(out, p, src);
2029
2049
  }
2030
2050
  return out;
2031
2051
  }
@@ -2040,6 +2060,7 @@ export function fullLayerToHead(
2040
2060
  canvas: Raster,
2041
2061
  frame: Pick<Frame, 'fullK' | 'fullPad' | 'fullPadTop' | 'headBox' | 'headK'>,
2042
2062
  resolution: number,
2063
+ visibility?: PartVisibility,
2043
2064
  ): Raster {
2044
2065
  const n = canvas.width * canvas.height;
2045
2066
  let any = false;
@@ -2056,7 +2077,9 @@ export function fullLayerToHead(
2056
2077
  const sx = f32(k);
2057
2078
  const tx = f32(-(frame.headBox[0] + frame.fullPad) / frame.headK);
2058
2079
  const ty = frame.fullPadTop === 0 && frame.headBox[1] === 0 ? 0 : f32(-(frame.headBox[1] + frame.fullPadTop) / frame.headK);
2059
- const wr = warpAffine(pre, { sx, sy: sx, tx, ty }, resolution, resolution, k < 1 ? 'bilinear' : 'bicubic');
2080
+ const map = { sx, sy: sx, tx, ty };
2081
+ const filter = k < 1 ? 'bilinear' : 'bicubic';
2082
+ const wr = warpAffine(pre, map, resolution, resolution, filter);
2060
2083
  const out = newRaster(resolution, resolution);
2061
2084
  const eps = f32(1e-3);
2062
2085
  const clip = (v: number): number => (v < 0 ? 0 : v > 255 ? 255 : v);
@@ -2068,6 +2091,8 @@ export function fullLayerToHead(
2068
2091
  }
2069
2092
  out.data[i * 4 + 3] = Math.trunc(a);
2070
2093
  }
2094
+ // Underfill reads this warp's RGB even when positive filtered alpha truncates to zero.
2095
+ visibility?.warp(canvas, out, map, filter, p => wr.data[p * 4 + 3] > 0);
2071
2096
  return out;
2072
2097
  }
2073
2098
 
@@ -2087,18 +2112,19 @@ function prepareHeadFace(
2087
2112
  resolution: number,
2088
2113
  underfill: boolean,
2089
2114
  minPx = PROPOSE_MIN_PX,
2115
+ visibility?: PartVisibility,
2090
2116
  ): { head: LayerSet; underfillPx: number; underfillNote: string | null } {
2091
2117
  if (full.source !== '' && full.source === head.source) return { head, underfillPx: 0, underfillNote: null };
2092
2118
  const fullFaceLayer = full.layers.find((l) => l.name === 'face');
2093
2119
  if (fullFaceLayer === undefined) return { head, underfillPx: 0, underfillNote: null };
2094
- const cleanedFull = cleanGhosts(placeLayer(fullFaceLayer, resolution));
2120
+ const cleanedFull = cleanGhosts(placeLayer(fullFaceLayer, resolution, visibility), visibility);
2095
2121
  let fullOpaqueRunPx = 0;
2096
2122
  for (let i = 3; i < cleanedFull.canvas.data.length; i += 4) {
2097
2123
  if (cleanedFull.canvas.data[i] > OPAQUE_ALPHA_ABOVE) fullOpaqueRunPx++;
2098
2124
  }
2099
2125
  if (fullOpaqueRunPx < minPx) return { head, underfillPx: 0, underfillNote: null };
2100
2126
 
2101
- const warpedFull = fullLayerToHead(cleanedFull.canvas, frame, resolution);
2127
+ const warpedFull = fullLayerToHead(cleanedFull.canvas, frame, resolution, visibility);
2102
2128
  const rawFullMask = newMask(resolution, resolution);
2103
2129
  for (let p = 0; p < resolution * resolution; p++) {
2104
2130
  if (warpedFull.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) rawFullMask.data[p] = 1;
@@ -2122,7 +2148,7 @@ function prepareHeadFace(
2122
2148
  const cleanedHead =
2123
2149
  headFaceLayer === undefined
2124
2150
  ? { canvas: newRaster(resolution, resolution), ghostPx: 0 }
2125
- : cleanGhosts(placeLayer(headFaceLayer, resolution));
2151
+ : cleanGhosts(placeLayer(headFaceLayer, resolution, visibility), visibility);
2126
2152
  let headRawOpaquePx = 0;
2127
2153
  for (let i = 3; i < cleanedHead.canvas.data.length; i += 4) {
2128
2154
  if (cleanedHead.canvas.data[i] > OPAQUE_ALPHA_ABOVE) headRawOpaquePx++;
@@ -2182,6 +2208,7 @@ function prepareHeadFace(
2182
2208
  comp.data[i + c] = Math.trunc(cleanedHead.canvas.data[i + c] * tf + warpedFull.data[i + c] * (1 - tf));
2183
2209
  }
2184
2210
  comp.data[i + 3] = a;
2211
+ visibility?.underfill(comp, p, cleanedHead.canvas, warpedFull, ta, ua);
2185
2212
  if (ta <= OPAQUE_ALPHA_ABOVE && a > OPAQUE_ALPHA_ABOVE) underfillPx++;
2186
2213
  if (a > OPAQUE_ALPHA_ABOVE) compOpaquePx++;
2187
2214
  if (x < x0) x0 = x;
@@ -2196,7 +2223,7 @@ function prepareHeadFace(
2196
2223
  const replacedLayer: Layer = {
2197
2224
  ...headFaceLayer,
2198
2225
  takenLayers: unionTakenSources([headFaceLayer.takenLayers, fullFaceLayer.takenLayers]),
2199
- pixels: crop(comp, x0, y0, x1 - x0 + 1, y1 - y0 + 1),
2226
+ pixels: visibilityCrop(comp, x0, y0, x1 - x0 + 1, y1 - y0 + 1, visibility),
2200
2227
  left: x0,
2201
2228
  top: y0,
2202
2229
  right: x1 + 1,
@@ -2388,7 +2415,7 @@ export function pixelOwners(rigLayers: readonly Raster[], rank: readonly number[
2388
2415
  * masks mark own-layer art under a subset set's actual cover (alpha above 8);
2389
2416
  * those pixels are occluded, outside every projection core, and never recoloured.
2390
2417
  */
2391
- export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null, changed?: (layer: number, rigPixel: number) => void, observeOwners?: (owner: ArrayLike<number>) => void): ProjectionStats[] {
2418
+ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, run: Run, rule: ProjectRule = DEFAULT_PROJECT_RULE, rank: readonly number[] | null = null, keep: ReadonlyArray<Mask | null> | null = null, changed?: (layer: number, rigPixel: number) => void, observeOwners?: (owner: ArrayLike<number>) => void, visibility?: PartVisibility): ProjectionStats[] {
2392
2419
  const { W, H } = frame;
2393
2420
  const owner = pixelOwners(rigLayers, rank);
2394
2421
  observeOwners?.(owner);
@@ -2459,6 +2486,7 @@ export function projectSource(rigLayers: Raster[], srcr: Raster, frame: Frame, r
2459
2486
  different ||= next !== r.data[p * 4 + c];
2460
2487
  r.data[p * 4 + c] = next;
2461
2488
  }
2489
+ if (w !== 0) visibility?.painting(r, p, 'rgb', rest !== 0);
2462
2490
  if (different) changed?.(i, p);
2463
2491
  }
2464
2492
  return { core: coreN, taken, refused, clear, takenMask, coreMask: core, refusedMask };
@@ -2871,6 +2899,8 @@ export interface PlacedPart {
2871
2899
  /** Verified edited PNG bytes; emit verbatim rather than encoding image again. */
2872
2900
  encodedBytes?: Uint8Array;
2873
2901
  depthImage?: Raster;
2902
+ /** Issue #1473: the per-texel source-state map, written as `record.source_state_map.image`; present exactly when that is. */
2903
+ sourceStates?: Raster;
2874
2904
  record: PartRecord;
2875
2905
  image: Raster;
2876
2906
  }
@@ -3185,6 +3215,7 @@ export function seamOverride(
3185
3215
  turnMovingPair: ((a: string, b: string) => boolean) | null = null,
3186
3216
  written?: (part: number, rigPixel: number) => void,
3187
3217
  decisions?: RegionSeamDecisions,
3218
+ visibility?: PartVisibility,
3188
3219
  ): void {
3189
3220
  const { width: W } = srcr;
3190
3221
  const { top, cand } = seamCandidates(parts, srcr, rule, silhouette);
@@ -3228,6 +3259,7 @@ export function seamOverride(
3228
3259
  image.data[s] = srcr.data[d * 4];
3229
3260
  image.data[s + 1] = srcr.data[d * 4 + 1];
3230
3261
  image.data[s + 2] = srcr.data[d * 4 + 2];
3262
+ visibility?.painting(image, s / 4, 'rgb');
3231
3263
  if (different) written?.(i, d);
3232
3264
  n++;
3233
3265
  }
@@ -4057,7 +4089,7 @@ export function cutFillMask(piece: Raster, sourceW: number, sourceH: number): Ra
4057
4089
  * is the uncut layer's wherever the image fills, so its silhouette does not
4058
4090
  * grow over a soft edge an opaque image covers.
4059
4091
  */
4060
- export function fillUnder(base: Raster, piece: Raster, band: Mask, under: Raster, box: { x0: number; y0: number }, fill?: 'colour'): { filled: number; empty: number } {
4092
+ export function fillUnder(base: Raster, piece: Raster, band: Mask, under: Raster, box: { x0: number; y0: number }, fill?: 'colour', visibility?: PartVisibility): { filled: number; empty: number } {
4061
4093
  const W = base.width;
4062
4094
  let filled = 0;
4063
4095
  let empty = 0;
@@ -4072,7 +4104,12 @@ export function fillUnder(base: Raster, piece: Raster, band: Mask, under: Raster
4072
4104
  if (fill === 'colour') {
4073
4105
  base.data.set(under.data.subarray(u, u + 3), p * 4);
4074
4106
  base.data[p * 4 + 3] = a;
4075
- } else base.data.set(under.data.subarray(u, u + 4), p * 4);
4107
+ visibility?.copy(base, p, piece, p, 'alpha');
4108
+ visibility?.copy(base, p, under, u / 4, 'rgb');
4109
+ } else {
4110
+ base.data.set(under.data.subarray(u, u + 4), p * 4);
4111
+ visibility?.copy(base, p, under, u / 4);
4112
+ }
4076
4113
  filled++;
4077
4114
  }
4078
4115
  return { filled, empty };
@@ -4456,6 +4493,7 @@ function cutLimbs(
4456
4493
  tips?: Record<string, [number, number]>,
4457
4494
  sourceGroups: ReadonlyMap<string, string> = new Map(),
4458
4495
  emptyTargets?: ReadonlySet<string>,
4496
+ visibility?: PartVisibility,
4459
4497
  ): { parts: LimbPart[]; pieces: Built[]; counts: LimbCount[]; capFrom: Array<CapFrom | null>; material: MaterialRow[]; sources: MaterialSource[] } {
4460
4498
  const logical = (source: string): string => sourceGroups.get(source) ?? source;
4461
4499
  const names = Object.keys(limbs);
@@ -4601,6 +4639,7 @@ function cutLimbs(
4601
4639
  if (parts[at].of !== src) continue;
4602
4640
  if (b.r.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) selectedBefore++;
4603
4641
  rasters[at].data.set(b.r.data.subarray(p * 4, p * 4 + 4), p * 4);
4642
+ visibility?.copy(rasters[at], p, b.r);
4604
4643
  if (b.region === null || b.region.data[p] === 1) regions[at].data[p] = 1;
4605
4644
  }
4606
4645
  }
@@ -4695,7 +4734,7 @@ function cutLimbs(
4695
4734
  problems.push({ code: 'ASSEMBLE_HIDDEN_ONE_SOURCE', object: `${object}.cap`, detail: `names ${sg.cap}, and "${sg.from}" also has the hidden-art layer ${hidden.layer}; one source of the cap's art is required — remove cap, or the hidden-art layer` });
4696
4735
  return;
4697
4736
  }
4698
- const img = sg.cap === undefined ? (hidden === null ? null : boxOf(hidden.raster, box[0], box[1], box[2], box[3])) : (caps.get(`${l}/${k}`) ?? null);
4737
+ const img = sg.cap === undefined ? (hidden === null ? null : boxOf(hidden.raster, box[0], box[1], box[2], box[3], visibility)) : (caps.get(`${l}/${k}`) ?? null);
4699
4738
  if (sg.cap !== undefined && img === null) {
4700
4739
  problems.push({ code: 'ASSEMBLE_LIMB_CAP_PRESENT', object: `${object}.cap`, detail: `names ${sg.cap}, and no image was handed to the stage for it; the decoded PNG is required (a caller of assemble() reads the file)` });
4701
4740
  return;
@@ -4752,6 +4791,7 @@ function cutLimbs(
4752
4791
  } else if (img !== null && img.data[u + 3] > 0) {
4753
4792
  capWrite(p, img.data, u);
4754
4793
  lower.data.set(img.data.subarray(u, u + 4), p * 4);
4794
+ visibility?.copy(lower, p, img, u / 4);
4755
4795
  lowerPx++;
4756
4796
  mark(x, y, CAP_FROM_LOWER);
4757
4797
  } else {
@@ -4765,11 +4805,13 @@ function cutLimbs(
4765
4805
  if (img !== null && img.data[u + 3] > 0) {
4766
4806
  capWrite(p, img.data, u);
4767
4807
  lower.data.set(img.data.subarray(u, u + 4), p * 4);
4808
+ visibility?.copy(lower, p, img, u / 4);
4768
4809
  imagePx++;
4769
4810
  mark(x, y, CAP_FROM_IMAGE);
4770
4811
  } else if (ownLower[p] === li && lowerSrc.r.data[p * 4 + 3] > 0) {
4771
4812
  capWrite(p, lowerSrc.r.data, p * 4);
4772
4813
  lower.data.set(lowerSrc.r.data.subarray(p * 4, p * 4 + 4), p * 4);
4814
+ visibility?.copy(lower, p, lowerSrc.r);
4773
4815
  layerPx++;
4774
4816
  mark(x, y, CAP_FROM_LAYER);
4775
4817
  } else if (upper.data[p * 4 + 3] > 0) {
@@ -4778,6 +4820,7 @@ function cutLimbs(
4778
4820
  // short only where no layer of the limb gives a pixel.
4779
4821
  capWrite(p, upper.data, p * 4);
4780
4822
  lower.data.set(upper.data.subarray(p * 4, p * 4 + 4), p * 4);
4823
+ visibility?.copy(lower, p, upper);
4781
4824
  upperPx++;
4782
4825
  mark(x, y, CAP_FROM_UPPER);
4783
4826
  } else {
@@ -4818,6 +4861,7 @@ function cutLimbs(
4818
4861
  if (na === ua) continue;
4819
4862
  if (na === 0) upper.data.fill(0, p * 4, p * 4 + 4);
4820
4863
  else upper.data[p * 4 + 3] = na;
4864
+ visibility?.forgetNative(upper, p);
4821
4865
  // Issue #444: a pixel the feather ramp fades to alpha <= OPAQUE_ALPHA_ABOVE is no longer opaque on the
4822
4866
  // upper piece (its opacity is carried by the lower segment's opaque cap beneath), so it leaves the upper
4823
4867
  // piece's region and its remaining ramp is marked feathered so pushBackFringe does not clear the fade.
@@ -4919,6 +4963,7 @@ function cutLimbs(
4919
4963
  // opaque. The overlap is wholly bound to the matching rigid carrier.
4920
4964
  if (Math.abs(along) <= width / 2 + 1) {
4921
4965
  r.data.set(source.r.data.subarray(p * 4, p * 4 + 4), p * 4);
4966
+ visibility?.copy(r, p, source.r);
4922
4967
  region.data[p] = source.region === null ? 1 : source.region.data[p];
4923
4968
  }
4924
4969
  if (along > -width / 2) { rasters[upAt].data.fill(0, p * 4, p * 4 + 4); regions[upAt].data[p] = 0; }
@@ -5112,7 +5157,7 @@ interface HiddenArt {
5112
5157
  * drawn layers are (`placeLayer`, `layerToRig`) — no ghost clean-up, because
5113
5158
  * it is the artist's own art, not See-through's.
5114
5159
  */
5115
- export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[], sets: { full: LayerSet; head: LayerSet }, frame: Frame, resolution: number): Map<string, HiddenArt> {
5160
+ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[], sets: { full: LayerSet; head: LayerSet }, frame: Frame, resolution: number, visibility?: PartVisibility): Map<string, HiddenArt> {
5116
5161
  const out = new Map<string, HiddenArt>();
5117
5162
  const warped = new Map<string, HiddenArt>();
5118
5163
  for (const [name, run, tag] of plan) {
@@ -5121,7 +5166,7 @@ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[]
5121
5166
  const key = `${run}:${h.name}`;
5122
5167
  let art = warped.get(key);
5123
5168
  if (art === undefined) {
5124
- art = { layer: key, raster: layerToRig(placeLayer(h, resolution), frame, run) };
5169
+ art = { layer: key, raster: layerToRig(placeLayer(h, resolution, visibility), frame, run, visibility) };
5125
5170
  warped.set(key, art);
5126
5171
  }
5127
5172
  out.set(name, art);
@@ -5133,8 +5178,14 @@ export function hiddenArtByPart(plan: readonly PlanEntry[], cuts: readonly Cut[]
5133
5178
  return out;
5134
5179
  }
5135
5180
 
5136
- /** `r`'s pixels over the box `[x0, y0, w, h]`, transparent where the box reaches past `r`. */
5137
- export function boxOf(r: Raster, x0: number, y0: number, w: number, h: number): Raster {
5181
+ function visibilityCrop(image: Raster, x: number, y: number, w: number, h: number, visibility?: PartVisibility): Raster {
5182
+ const result = crop(image, x, y, w, h);
5183
+ visibility?.rows(result, image, x, y, w, h);
5184
+ return result;
5185
+ }
5186
+
5187
+ /** Pixels over the box, transparent where the box reaches past the image. */
5188
+ export function boxOf(r: Raster, x0: number, y0: number, w: number, h: number, visibility?: PartVisibility): Raster {
5138
5189
  const out = newRaster(w, h);
5139
5190
  for (let y = 0; y < h; y++) {
5140
5191
  const sy = y0 + y;
@@ -5143,6 +5194,7 @@ export function boxOf(r: Raster, x0: number, y0: number, w: number, h: number):
5143
5194
  const sx = x0 + x;
5144
5195
  if (sx < 0 || sx >= r.width) continue;
5145
5196
  out.data.set(r.data.subarray((sy * r.width + sx) * 4, (sy * r.width + sx) * 4 + 4), (y * w + x) * 4);
5197
+ visibility?.copy(out, y * w + x, r, sy * r.width + sx);
5146
5198
  }
5147
5199
  }
5148
5200
  return out;
@@ -5290,7 +5342,7 @@ export function assemble(input: AssembleInput): AssembleResult {
5290
5342
  * may be recovered by a take, so only that counterfactual permits them. */
5291
5343
  function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, beforeTake: AssembleResult | null = null, counterfactual?: { cleanup: Map<string, RunLayer[]>; seam: Map<string, Uint8Array> }, editContexts?: Map<PlacedPart, EditedPartContext>): AssembleResult {
5292
5344
  const emptyTargets = beforeTake === null ? targets : undefined;
5293
- const { source, extend, patches, seamRule, projectRule } = input;
5345
+ const { source, extend, patches, seamRule, projectRule, visibility } = input;
5294
5346
  const authoredDepths = input.depth === undefined ? new Map<string, AuthoredUnitDepth>() : authoredUnitDepths(input);
5295
5347
  if (input.paintingExtension !== undefined) refuseIfAny(paintingExtensionProblems(input.paintingExtension));
5296
5348
  if (input.edgeSplits !== undefined) refuseIfAny(edgeSplitProblems(input.edgeSplits, new Set(input.plan.map(([name]) => name))));
@@ -5373,9 +5425,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5373
5425
  refuseIfAny(hiddenExtentProblems(input.requireHiddenExtent!, sources, frame.W, frame.H));
5374
5426
  }
5375
5427
  // Issue #439: when seethrough.arm_split is declared, split the full run's overlapping handwear into handwear-r and handwear-l.
5376
- const fullArmSplit = input.armSplit === undefined ? fullPadded : applyArmSplit(fullPadded, input.resolution, input.armSplit);
5428
+ const fullArmSplit = input.armSplit === undefined ? fullPadded : applyArmSplit(fullPadded, input.resolution, input.armSplit, visibility);
5377
5429
  // Issue #490: when generation.control.skeleton is present, split merged arm layers (or refuse when sleeve and drape share one colour).
5378
- const full = input.keySkeleton === undefined ? fullArmSplit : splitMergedArmRuns(fullArmSplit, input.resolution, frame, source.width, source.height, input.keySkeleton);
5430
+ const full = input.keySkeleton === undefined ? fullArmSplit : splitMergedArmRuns(fullArmSplit, input.resolution, frame, source.width, source.height, input.keySkeleton, visibility);
5379
5431
  const plan = mergedArmSplitPlan(armSplitPlan(input.plan, input.armSplit), full);
5380
5432
  const cutLayerPlan: PlanEntry[] = input.cuts.flatMap(c => {
5381
5433
  const tag = input.cutLayers?.get(c.into);
@@ -5390,7 +5442,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5390
5442
  (plan.some(([, r, t]) => r === 'head' && t === 'face') ||
5391
5443
  (!plan.some(([, r, t]) => r === 'full' && t === 'face') && plan.some(([, r]) => r === 'full') && plan.some(([, r]) => r === 'head')));
5392
5444
  const headFacePrep = checkHeadFace
5393
- ? prepareHeadFace(full, depthHeadInput, frame, input.resolution, input.headFaceUnderfill === true)
5445
+ ? prepareHeadFace(full, depthHeadInput, frame, input.resolution, input.headFaceUnderfill === true, PROPOSE_MIN_PX, visibility)
5394
5446
  : { head: single ? full : depthHeadInput, underfillPx: 0, underfillNote: null };
5395
5447
  const head = headFacePrep.head;
5396
5448
  const padRecord = singleRunPadRecord(single, source.width, source.height, input.resolution, frame);
@@ -5417,7 +5469,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5417
5469
  }
5418
5470
  // Issue #359: a part's hidden-art layer is the under of a cut that names none — and, with one named, a refusal, since
5419
5471
  // reading either would be a guess. Its uses are counted for `hiddenLines`.
5420
- const hiddenArt = hiddenArtByPart(plan, input.cuts, { full, head }, frame, input.resolution);
5472
+ const hiddenArt = hiddenArtByPart(plan, input.cuts, { full, head }, frame, input.resolution, visibility);
5421
5473
  const hiddenUses = new Map<string, string[]>();
5422
5474
  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}`, []);
5423
5475
  const hiddenProblems: Problem[] = [];
@@ -5431,7 +5483,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5431
5483
  }
5432
5484
  const box = underBox(q.polygon);
5433
5485
  hiddenUses.get(art.layer)?.push(`cuts[${i}].under (part "${q.into}")`);
5434
- return boxOf(art.raster, box.x0, box.y0, box.w, box.h);
5486
+ return boxOf(art.raster, box.x0, box.y0, box.w, box.h, visibility);
5435
5487
  });
5436
5488
  const cuts = input.cuts.map((q): Cut => {
5437
5489
  const art = hiddenArt.get(q.from);
@@ -5459,6 +5511,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5459
5511
  const valueBaselines = new Map<string, ValueBaseline | null>();
5460
5512
  // Extend-only rasters are still projected/merged, but are never emitted as own sources.
5461
5513
  const readKeys = new Set(sourcePlan.map(([, run, tag]) => `${run}:${tag}`));
5514
+ const trackedKeys = visibility === undefined ? undefined : new Set([...readKeys, ...extend.map(e => `${e.run}:${e.tag}`)]);
5515
+ const restoreParts = new Set(input.keepUnderOccluders ?? []);
5516
+ const restoreKeys = new Set(input.plan.filter(([name]) => restoreParts.has(name)).map(([, run, tag]) => `${run}:${tag}`));
5462
5517
  const sourceCover: SourceCoverReading = { sources: [], parts: [] };
5463
5518
  const rig = new Map<string, Raster>();
5464
5519
  const stats = new Map<string, ProjectionStats>();
@@ -5468,7 +5523,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5468
5523
  const preparedRuns: Array<{ run: Run; set: LayerSet; layers: ReturnType<typeof runLayers>; rigLayers: Raster[]; rank: number[]; keep: Array<Mask | null>; writes: Array<Int32Array | null> }> = [];
5469
5524
  // A single run (issue #359) is read once: there is no head run to place, project or count ghosts for.
5470
5525
  for (const [run, set] of single ? ([['full', full]] as const) : ([['full', full], ['head', head]] as const)) {
5471
- const layers = runLayers(set, input.resolution);
5526
+ const layers = runLayers(set, input.resolution, visibility);
5472
5527
  if (beforeTake === null) counterfactual?.cleanup.set(run, layers);
5473
5528
  else if (counterfactual !== undefined) for (const layer of layers) {
5474
5529
  const sourceLayer = set.layers.find(q => q.name === layer.tag);
@@ -5481,7 +5536,10 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5481
5536
  const dx = single ? frame.fullPad : 0, dy = single ? frame.fullPadTop : 0;
5482
5537
  for (let y = 0; y < input.resolution; y++) for (let x = 0; x < input.resolution; x++) {
5483
5538
  const sx = x - dx, sy = y - dy, p = y * input.resolution + x;
5484
- if (sx < 0 || sy < 0 || sx >= selection.width || sy >= selection.height || selection.data[sy * selection.width + sx] === 0) layer.canvas.data[p * 4 + 3] = baseline.canvas.data[p * 4 + 3];
5539
+ if (sx < 0 || sy < 0 || sx >= selection.width || sy >= selection.height || selection.data[sy * selection.width + sx] === 0) {
5540
+ layer.canvas.data[p * 4 + 3] = baseline.canvas.data[p * 4 + 3];
5541
+ visibility?.copy(layer.canvas, p, baseline.canvas, p, 'alpha');
5542
+ }
5485
5543
  if (layer.canvas.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) layer.opaqueRunPx++;
5486
5544
  else if (raw.data[p * 4 + 3] > OPAQUE_ALPHA_ABOVE) layer.ghostPx++;
5487
5545
  }
@@ -5489,11 +5547,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5489
5547
  if (run === 'full') fullTags.push(...layers.filter((l) => l.opaqueRunPx > 0).map((l) => l.tag));
5490
5548
  const rigLayers = layers.map((l) => {
5491
5549
  const srcLayer = set.layers.find((q) => q.name === l.tag);
5550
+ const tracked = trackedKeys?.has(`${run}:${l.tag}`) ? visibility : undefined;
5492
5551
  return srcLayer?.occluderSplit !== undefined &&
5493
5552
  srcLayer.pixels === srcLayer.occluderSplit.merged &&
5494
5553
  srcLayer.regionSelection === undefined
5495
- ? layerToRigSplit(srcLayer, input.resolution, frame, run, occluderCoreMasks, true)
5496
- : layerToRig(l.canvas, frame, run);
5554
+ ? layerToRigSplit(srcLayer, input.resolution, frame, run, occluderCoreMasks, true, tracked)
5555
+ : layerToRig(l.canvas, frame, run, tracked);
5497
5556
  });
5498
5557
  const rank = planRanks(layers.map((l) => l.tag), run, sourcePlan);
5499
5558
  const keep = layers.map((l, i): Mask | null => {
@@ -5548,6 +5607,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5548
5607
  const sourceLayers = run === 'full' && splitTag && preparedWriter === AW.armSplit
5549
5608
  ? input.armSplit === undefined ? fullPadded.layers.filter(q => q.name === parentTag) : fullPadded.layers.filter(q => q.name === 'handwear-r' || q.name === 'handwear-l')
5550
5609
  : original === undefined ? [] : [original];
5610
+ const trackBaseline = restoreKeys.has(key) ? visibility : undefined;
5551
5611
  let raw: Raster | null = null;
5552
5612
  if (author === 0 && sourceLayers.length > 0) {
5553
5613
  if (
@@ -5555,16 +5615,21 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5555
5615
  sourceLayers[0].occluderSplit !== undefined &&
5556
5616
  sourceLayers[0].pixels === sourceLayers[0].occluderSplit.merged
5557
5617
  ) {
5558
- raw = layerToRigSplit(sourceLayers[0], input.resolution, frame, run, occluderCoreMasks);
5618
+ raw = layerToRigSplit(sourceLayers[0], input.resolution, frame, run, occluderCoreMasks, false, trackBaseline);
5559
5619
  } else {
5560
5620
  // A sole layer needs no composite copy: layerToRig premultiplies,
5561
5621
  // so discarded RGB at alpha 0 has exactly the same float32 input.
5562
- const canvas = sourceLayers.length === 1 ? placeLayer(sourceLayers[0], input.resolution) : newRaster(input.resolution, input.resolution);
5622
+ const canvas = sourceLayers.length === 1 ? placeLayer(sourceLayers[0], input.resolution, trackBaseline) : newRaster(input.resolution, input.resolution);
5563
5623
  if (sourceLayers.length > 1) for (const originalLayer of sourceLayers) {
5564
- const sourceCanvas = placeLayer(originalLayer, input.resolution);
5565
- 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);
5624
+ const sourceCanvas = placeLayer(originalLayer, input.resolution, trackBaseline);
5625
+ for (let p = 0; p < input.resolution * input.resolution; p++) if (sourceCanvas.data[p * 4 + 3] > 0) {
5626
+ canvas.data.set(sourceCanvas.data.subarray(p * 4, p * 4 + 4), p * 4);
5627
+ trackBaseline?.copy(canvas, p, sourceCanvas);
5628
+ }
5566
5629
  }
5567
- raw = layerToRig(canvas, frame, run);
5630
+ // The restoration baseline deliberately uses uncleaned layer alpha.
5631
+ trackBaseline?.forgetNative(canvas);
5632
+ raw = layerToRig(canvas, frame, run, trackBaseline);
5568
5633
  }
5569
5634
  }
5570
5635
  // Reuse only a proved identical placed input, never wrapper identity.
@@ -5580,7 +5645,9 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5580
5645
  }
5581
5646
  // Keep only samples that could equal a final opaque pixel; full raw and
5582
5647
  // prepared normalization temporaries end with this layer's callback.
5583
- valueBaselines.set(key, raw === null ? null : compactValueBaseline(raw));
5648
+ const baseline = raw === null ? null : compactValueBaseline(raw);
5649
+ if (baseline !== null && raw !== null) trackBaseline?.rows(baseline.image, raw, baseline.x, baseline.y, baseline.image.width, baseline.image.height);
5650
+ valueBaselines.set(key, baseline);
5584
5651
  return ids;
5585
5652
  });
5586
5653
  preparedRuns.push({ run, set, layers, rigLayers, rank, keep, writes });
@@ -5602,6 +5669,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5602
5669
  const idx = prep?.layers.findIndex(l => l.tag === row[2]) ?? -1;
5603
5670
  const w = prep !== undefined && idx >= 0 ? prep.writes[idx] : null;
5604
5671
  if (w !== null && w !== undefined) w[pixel] = cleared ? 0 : AW.sourceProjection;
5672
+ if (!cleared && prep !== undefined && idx >= 0) visibility?.painting(prep.rigLayers[idx], pixel, 'both');
5605
5673
  },
5606
5674
  );
5607
5675
  const edgeSplitDepthProblems: Problem[] = [];
@@ -5625,7 +5693,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5625
5693
  rigLayers, rank, sourcePlan, extend, owners, (o, i) => frontOf(o, i, rank), keep);
5626
5694
  sourceCover.sources.push(...reading.sources);
5627
5695
  sourceCover.parts.push(...reading.parts);
5628
- });
5696
+ }, visibility);
5629
5697
  writes.forEach((ids, i) => { if (ids !== null) layerWriters.set(`${run}:${layers[i].tag}`, ids); });
5630
5698
  writes.length = 0;
5631
5699
  layers.forEach((l, i) => {
@@ -5756,6 +5824,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5756
5824
  const key = `${run}:${tag}`;
5757
5825
  const src = rig.get(key) as Raster;
5758
5826
  const r: Raster = { width: W, height: H, data: new Uint8ClampedArray(src.data) };
5827
+ visibility?.clone(src, r);
5759
5828
  const st = stats.get(key) as ProjectionStats;
5760
5829
  const extendKeys = extend.filter((e) => e.part === name).map((e) => `${e.run}:${e.tag}`);
5761
5830
  const extras = extendKeys.map((k) => rig.get(k) as Raster);
@@ -5773,6 +5842,12 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5773
5842
  for (let p = 0; p < W * H; p++) if (occKeep.data[p] === 1) front.data[p] = 1;
5774
5843
  }
5775
5844
  merged = mergeCropEntries(r, extras, front, srcr, frame, extend.filter(e => e.part === name), trace, (p, stage) => { writers[p] = AW[stage]; });
5845
+ if (visibility !== undefined) for (let p = 0; p < trace.from.length; p++) {
5846
+ const e = trace.from[p];
5847
+ if (e < 0) continue;
5848
+ if (trace.ring.data[p] === 1) visibility.painting(r, p, 'both');
5849
+ else visibility.copy(r, p, extras[e]);
5850
+ }
5776
5851
  }
5777
5852
  const { x1, opaque } = measureBox(r);
5778
5853
  if (opaque === 0 && !emptyTargets?.has(name)) {
@@ -5853,6 +5928,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5853
5928
  const a = b.r.data[p * 4 + 3];
5854
5929
  if (m.data[p] === 0 || a === 0) continue;
5855
5930
  r.data.set(b.r.data.subarray(p * 4, p * 4 + 4), p * 4);
5931
+ visibility?.copy(r, p, b.r);
5856
5932
  if (band.data[p] === 0) b.r.data.fill(0, p * 4, p * 4 + 4);
5857
5933
  if (a > OPAQUE_ALPHA_ABOVE) {
5858
5934
  n++;
@@ -5909,7 +5985,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5909
5985
  if (u === null) return undefined;
5910
5986
  // Filled where the image is at least as opaque as the layer was; left empty elsewhere (`fillUnder`).
5911
5987
  // With under_fill "colour" (issue #360) a filled pixel keeps the alpha the cut removed and takes the image's colour only.
5912
- const f = fillUnder(b.r, (pieces[i] as Built).r, cutBand(cutMasks[i], cuts[i].overlap), u, underBox(cuts[i].polygon), cuts[i].under_fill);
5988
+ const f = fillUnder(b.r, (pieces[i] as Built).r, cutBand(cutMasks[i], cuts[i].overlap), u, underBox(cuts[i].polygon), cuts[i].under_fill, visibility);
5913
5989
  const band = cutBand(cutMasks[i], cuts[i].overlap);
5914
5990
  let opaqueFilled = 0;
5915
5991
  // The under operation wrote only removed pixels it actually filled.
@@ -5949,7 +6025,10 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5949
6025
  cutSources.forEach((source, i) => {
5950
6026
  if (source === null) return;
5951
6027
  const m = cutMasks[i], r = newRaster(W, H);
5952
- for (let p = 0; p < W * H; p++) if (m.data[p] === 1) r.data.set(source.r.data.subarray(p * 4, p * 4 + 4), p * 4);
6028
+ for (let p = 0; p < W * H; p++) if (m.data[p] === 1) {
6029
+ r.data.set(source.r.data.subarray(p * 4, p * 4 + 4), p * 4);
6030
+ visibility?.copy(r, p, source.r);
6031
+ }
5953
6032
  if (opaqueOf(r) === 0 && !emptyTargets?.has(cuts[i].into)) empty.push({ code: 'ASSEMBLE_CUT_PIXELS', object: `config.assemble.cuts[${i}] (part "${cuts[i].into}")`, detail: `takes 0 opaque pixels from selected ${source.key}; draw its polygon over that layer's art` });
5954
6033
  const writers = (source.writers as Int32Array).slice();
5955
6034
  pieces[i] = { ...source, r, writers, region: m, merged: mergedIn(source, m) };
@@ -5978,7 +6057,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
5978
6057
  const ci = cuts.findIndex((q) => q.into === name);
5979
6058
  return ci >= 0 ? pieces[ci] : null;
5980
6059
  };
5981
- const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, limbSource, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by), input.boneTips, input.limbSourceGroups, emptyTargets);
6060
+ const lim = cutLimbs(input.limbs ?? {}, input.bones ?? [], input.caps ?? new Map(), W, H, limbSource, opaqueOf, mergedIn, count, (name) => hiddenArt.get(name) ?? null, (layer, by) => hiddenUses.get(layer)?.push(by), input.boneTips, input.limbSourceGroups, emptyTargets, visibility);
5982
6061
  // Issue #564: and the cap a run's own layer fills above its upper joint, read once the limbs are cut.
5983
6062
  if (bands !== null) refuseIfAny(limbBands(cuts, pieces, input.limbs ?? {}, input.bones ?? [], W, H, (l, k) => lim.parts.find((q) => q.limb === l && q.segment === k)?.record.cap, input.boneTips).problems);
5984
6063
  const limbPieces = lim.pieces;
@@ -6091,9 +6170,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6091
6170
  // #825: decide ownership on the final draw stack, after merges, cuts,
6092
6171
  // limb splits and exclusions. Restore only original own-layer samples:
6093
6172
  // no merge/ring, under-fill, cap, patch or authored replacement is borrowed.
6094
- const wanted = new Set(input.keepUnderOccluders ?? []);
6095
- refuseIfAny([...wanted].filter(name => !input.plan.some(([n]) => n === name)).map(name => ({ code: 'CONFIG_NAME_RESOLVES', object: 'config.assemble.keep_under_occluders', detail: `names "${name}"; a source part in assemble.plan is required` })));
6096
- const sourceKeys = new Set(input.plan.filter(([name]) => wanted.has(name)).map(([, run, tag]) => `${run}:${tag}`));
6173
+ refuseIfAny([...restoreParts].filter(name => !input.plan.some(([n]) => n === name)).map(name => ({ code: 'CONFIG_NAME_RESOLVES', object: 'config.assemble.keep_under_occluders', detail: `names "${name}"; a source part in assemble.plan is required` })));
6097
6174
  const keptRetake: Array<Mask | null> = order.map(() => null);
6098
6175
  const softOcclusion: SoftOcclusionReading[] = [];
6099
6176
  const keepInOrder = order.map((d, i): Mask | null => {
@@ -6110,7 +6187,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6110
6187
  if ('patch' in d) return withOccKeep(limb);
6111
6188
  const b = pieceAt(d).b, baseline = valueBaselines.get(b.key);
6112
6189
  if (baseline === undefined || baseline === null) return withOccKeep(limb);
6113
- const enabled = sourceKeys.has(b.key);
6190
+ const enabled = restoreKeys.has(b.key);
6114
6191
  const mask = enabled ? newMask(W, H) : limb;
6115
6192
  if (enabled && limb !== null) mask!.data.set(limb.data);
6116
6193
  const restored = enabled ? newMask(W, H) : null;
@@ -6136,6 +6213,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6136
6213
  if (different || enabled) holders.set(stack[j].record.name, (holders.get(stack[j].record.name) ?? 0) + 1);
6137
6214
  if (enabled) {
6138
6215
  b.r.data.set(raw.subarray(q, q + 4), p * 4);
6216
+ visibility?.copy(b.r, p, baseline.image, q / 4);
6139
6217
  mask!.data[p] = 1;
6140
6218
  restored!.data[p] = 1;
6141
6219
  reading.kept++;
@@ -6259,7 +6337,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6259
6337
  }
6260
6338
  const finished = finishYieldedProjection(b.r, srcr, b.st, finish, queue.subarray(0, end),
6261
6339
  { kept: keptRetake[orderIdx], region: b.region, merged: b.trace.from, ring: b.trace.ring, behind: behindAt },
6262
- p => { writersInOrder[orderIdx][p] = AW.sourceProjection; });
6340
+ p => { writersInOrder[orderIdx][p] = AW.sourceProjection; visibility?.painting(b.r, p, 'rgb'); });
6263
6341
  if (finished > 0) reading.finishedProjection = finished;
6264
6342
  }
6265
6343
  reading.yielded = yielded;
@@ -6301,6 +6379,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6301
6379
  image.data.set(srcr.data.subarray(p * 4, p * 4 + 3), p * 4);
6302
6380
  image.data[p * 4 + 3] = paintingAlpha!.data[p * 4 + 3];
6303
6381
  writersInOrder[i][p] = AW.paintingExtension;
6382
+ visibility?.painting(image, p, 'both');
6304
6383
  if (!('patch' in d)) {
6305
6384
  const region = pieceAt(d).b.region;
6306
6385
  if (region !== null) region.data[p] = 1;
@@ -6369,6 +6448,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6369
6448
  const e = paintingEdges(canvases, srcr, {
6370
6449
  owner: receivers,
6371
6450
  allocationEvent: input.allocationEvent,
6451
+ visibility,
6372
6452
  painted: supportPainted,
6373
6453
  figure: visibleFigure,
6374
6454
  ...(input.declaredFigure === undefined ? {} : { declaredFigure: input.declaredFigure }),
@@ -6598,7 +6678,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6598
6678
  if (paintingGain !== undefined) record.painting_extension_px = paintingGain.data.reduce((sum, value) => sum + value, 0);
6599
6679
  if (pushedHere.length > 0) record.fringe_pushed_back = pushedHere;
6600
6680
  if (limb !== undefined) record.limb = limb;
6601
- const image = crop(r, x0, y0, record.w, record.h);
6681
+ const image = visibilityCrop(r, x0, y0, record.w, record.h, visibility);
6602
6682
  const limbIndex = limb === undefined ? -1 : lim.parts.findIndex(q => q.record.name === limb.name && q.record.segment === limb.segment);
6603
6683
  const upperIndex = limb === undefined ? -1 : lim.parts.findIndex(q => q.record.name === limb.name && q.record.segment === limb.segment - 1);
6604
6684
  const capSource = limbIndex < 0 ? null : lim.capFrom[limbIndex];
@@ -6686,7 +6766,7 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6686
6766
  preSeamWriters.set(i, changed);
6687
6767
  }
6688
6768
  writersInOrder[i][p] = AW.seamOverride;
6689
- }, counterfactual === undefined ? undefined : beforeTake === null ? { record: counterfactual.seam } : { baseline: counterfactual.seam, support: regionSupport });
6769
+ }, counterfactual === undefined ? undefined : beforeTake === null ? { record: counterfactual.seam } : { baseline: counterfactual.seam, support: regionSupport }, visibility);
6690
6770
  const stageMap: StageMap | undefined = input.stageMap !== true ? undefined : {
6691
6771
  schema: 'rig-parts-stage-map/1', rig_size: [W, H], automatic: AW, edits: [...editNames], parts: [],
6692
6772
  };
@@ -6718,8 +6798,20 @@ function assembleParts(input: AssembleInput, targets?: ReadonlySet<string>, befo
6718
6798
  });
6719
6799
  }
6720
6800
  const editedPartFrontColours = (input.editedParts?.length ?? 0) > 0
6721
- ? replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!, srcr, paintingOwner ?? rawPaintingOwnerForPlan(), ERROR_LIMIT)
6801
+ ? replaceEditedParts(placed, input.editedParts!, new Set(input.plan.map(([name]) => name)), stageMap!, editContexts!, srcr, paintingOwner ?? rawPaintingOwnerForPlan(), ERROR_LIMIT, visibility)
6722
6802
  : [];
6803
+ if (visibility !== undefined) {
6804
+ for (const part of placed) {
6805
+ part.record.source_visibility = visibility.summarize(part.image);
6806
+ // Issue #1473: where each counted state lies, bound by the bytes build writes.
6807
+ const map = encodeSourceStateMap(visibility.states(part.image).codes, part.image.width, part.image.height);
6808
+ part.record.source_state_map = { image: sourceStateMapImage(part.record.name), sha256: map.sha256 };
6809
+ part.sourceStates = map.image;
6810
+ }
6811
+ // Issue #1474: each pair of overlapping parts, in draw order.
6812
+ const overlaps = visibility.overlaps(placed.map(({ record, image }) => ({ name: record.name, x: record.x, y: record.y, image })));
6813
+ placed.forEach((part, i) => { part.record.source_overlaps = overlaps[i]; });
6814
+ }
6723
6815
  if (editContexts !== undefined) for (const p of placed) {
6724
6816
  const samples = editContexts.get(p)?.depthClampedSamples;
6725
6817
  if (samples === undefined) continue;