@rig-c/parts 2.8.1 → 2.9.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/propose.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { dustOf } from './mesh.ts';
1
2
  import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
2
3
  /**
3
4
  * The propose stage: bone origins, mesh candidate lists, regions and a default
@@ -132,10 +133,11 @@ import { explicitWeightRows, regionBone, type RegionSpec } from './config.ts';
132
133
  import { existsSync } from 'node:fs';
133
134
  import { join } from 'node:path';
134
135
  import { drawText, GLYPH_H } from '@rig-c/core/font5x7';
135
- import { type BoneEntry, type CharacterConfig, type ConfigConstraint, type ConfigStop, contourRegionsOf, deriveBustRegions, type Limb, type MeshSpec, type PartBinding, parseConfig, type Point, type Segment, type SkeletonSections, turnRidersByBone } from './config.ts';
136
+ import { type BoneEntry, type CharacterConfig, type ConfigConstraint, type ConfigStop, type ContourBustSpec, type ContourSpec, contourRegionsOf, deriveBustRegions, type Limb, type MeshSpec, type PartBinding, parseConfig, type Point, type Segment, type SkeletonSections, turnRidersByBone } from './config.ts';
136
137
  export { contourRegionsOf, deriveBustRegions };
137
138
  import { computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toWorld } from './coords.ts';
138
139
  import { PartsError, type Problem, refuseIfAny } from './errors.ts';
140
+ import { GRID } from './contour.ts';
139
141
  import { eyeLineDegrees, type FrameFeature, headAxes, type HeadAxes, headFrame, type HeadFrame } from './headframe.ts';
140
142
  import { type LayerSet, OPAQUE_ALPHA_ABOVE } from './layers.ts';
141
143
  import { PAINTING_RUN, type PartRecord, type PartsFile, readParts } from './parts.ts';
@@ -157,7 +159,7 @@ import { configRoles, type RoleOf } from './structure.ts';
157
159
  import { AUTHOR_NO_ROLE, isAuthorTag } from './tags.ts';
158
160
  import { TURN_BONE, TURN_CARRIER_TAG, TURN_PLACES, TURN_RIDER_OFFSET, TURN_RIDER_TAGS, turnFractions, turnNearest, turnPivot, turnRiderDepth, type TurnSpec } from './turn.ts';
159
161
  import { edgeLength } from './length.ts';
160
- import { bonePlaces, jointLine, type JointLine, limbCrossing, limbPolyline, limbRun, limbWidth, nearestLimb, nearestOnLine, offLineFigure, type Pt } from './limbs.ts';
162
+ import { bonePlaces, jointLine, type JointLine, limbCrossing, limbPolyline, limbRun, limbWidth, nearestLimb, nearestOnLine, offLineFigure, segmentOf, type Pt } from './limbs.ts';
161
163
  import { type BranchSqueezeFinding, branchSqueezes, chainSqueezes, type SqueezeFinding } from './squeeze.ts';
162
164
  import { backHairMasses, type BackHairMass, backHairMassTrees, INFLUENCE_RADIUS_CELLS, RECIPE_BACK_HAIR_CHAINS, RECIPE_LENGTH_RATIO, chainConstraints, clothNote, type ClothRecipe, type ClothRecipes, type ClothTarget, CLOTH_TARGETS, draftTrees, spanCrosses, swingName, type Tail, tailOverlap, type TailOverlap, type TailSpan, treeConstraints, type TreeChain, type TreeInput, type TreeMassInput } from './cloth.ts';
163
165
  import { TEXTURE_STRETCH_CEILING } from './check.ts';
@@ -1403,13 +1405,39 @@ const SIDES = [
1403
1405
  ['l', -1],
1404
1406
  ] as const;
1405
1407
 
1408
+ /** Declared bust landmarks in rig pixels, or an explicit omission reason. */
1409
+ export interface BustDraft {
1410
+ landmarks?: { apex_r: Point; apex_l: Point; cleavage?: Point };
1411
+ noBust?: string;
1412
+ }
1413
+
1414
+ /** Read only the declared landmark fields. Geometry is checked by checkProposal's config reader. */
1415
+ export function readBustLandmarks(raw: unknown): NonNullable<BustDraft['landmarks']> {
1416
+ const problems: Problem[] = [];
1417
+ const record = typeof raw === 'object' && raw !== null && !Array.isArray(raw)
1418
+ ? raw as Record<string, unknown>
1419
+ : {};
1420
+ for (const key of Object.keys(record)) {
1421
+ if (!['apex_r', 'apex_l', 'cleavage'].includes(key)) problems.push({ code: 'PROPOSE_BUST_INPUT', object: `landmarks.${key}`, detail: 'is unknown. Give apex_r, apex_l and optional cleavage in rig pixels' });
1422
+ }
1423
+ for (const key of ['apex_r', 'apex_l', 'cleavage']) {
1424
+ if (key === 'cleavage' && record[key] === undefined) continue;
1425
+ const value = record[key];
1426
+ if (!Array.isArray(value) || value.length !== 2 || !value.every(n => typeof n === 'number' && Number.isFinite(n))) {
1427
+ problems.push({ code: 'PROPOSE_BUST_INPUT', object: `landmarks.${key}`, detail: `is ${JSON.stringify(value) ?? 'absent'}. A finite [x, y] point in rig pixels is required` });
1428
+ }
1429
+ }
1430
+ refuseIfAny(problems);
1431
+ return record as NonNullable<BustDraft['landmarks']>;
1432
+ }
1433
+
1406
1434
  /**
1407
1435
  * Propose bones, meshes, regions and an idle from the parts. With `joints`
1408
1436
  * (`propose --keypoints`, issue #75), a joint the file gives a position is
1409
1437
  * used as given in place of the body-ratio rule for the bone it places, and
1410
1438
  * every joint the proposer could use gets one note saying how it was used or
1411
- * which rule stood in; without it every value and note is the one this
1412
- * function wrote before the parameter existed.
1439
+ * which rule stood in. Bust landmarks are supplied separately through `bust`.
1440
+ * Their absence leaves the contour torso with a missing-landmarks note.
1413
1441
  */
1414
1442
  export function propose(
1415
1443
  P: PartSet,
@@ -1418,8 +1446,9 @@ export function propose(
1418
1446
  gridRule: GridRule = DEFAULT_GRID_RULE,
1419
1447
  cloth: ClothRecipes | null = null,
1420
1448
  chainRule = true,
1449
+ bust: BustDraft = {},
1421
1450
  ): Proposal {
1422
- return proposeWithBasis(P, joints, wristSnap, gridRule, cloth, chainRule).proposal;
1451
+ return proposeWithBasis(P, joints, wristSnap, gridRule, cloth, chainRule, bust).proposal;
1423
1452
  }
1424
1453
 
1425
1454
  /**
@@ -1439,7 +1468,12 @@ export function proposeWithBasis(
1439
1468
  gridRule: GridRule = DEFAULT_GRID_RULE,
1440
1469
  cloth: ClothRecipes | null = null,
1441
1470
  chainRule = true,
1471
+ bust: BustDraft = {},
1442
1472
  ): { proposal: Proposal; basis: ProposalBasis; draftLint: DraftLintFinding[] } {
1473
+ if (bust.noBust !== undefined && (bust.noBust.trim().length === 0 || bust.landmarks !== undefined)) {
1474
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'bust draft', detail: 'give either landmarks or a non-blank noBust reason, not both' }]);
1475
+ }
1476
+ if (bust.landmarks !== undefined) readBustLandmarks(bust.landmarks);
1443
1477
  // Issue #230: a piece is not given its base's rule a second time, which
1444
1478
  // needs to know which part is the piece. A file that cannot say is refused
1445
1479
  // here, and only here: every other reader of parts.json still takes it.
@@ -3415,6 +3449,117 @@ export function proposeWithBasis(
3415
3449
  );
3416
3450
  }
3417
3451
  }
3452
+ // Issue #986: only the chest carrier changes mode. Other garments retain their drafting rules.
3453
+ const chestCarriers = figPart === null
3454
+ ? tw.filter(p => isOn(P.alpha(p), chest[0], chest[1]))
3455
+ : [];
3456
+ if (figPart === null && chestCarriers.length > 1) {
3457
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'chest carrier', detail: `chest at ${fmtAt(chest)} lies on ${chestCarriers.map(p => p.name).join(', ')}. Separate the chest-holding topwear so exactly one part covers it` }]);
3458
+ }
3459
+ const torsoName = figPart === null ? chestCarriers[0]?.name : 'trunk_chest';
3460
+ if (torsoName !== undefined) {
3461
+ const source = figPart ?? chestCarriers[0];
3462
+ const lattice = meshes[torsoName];
3463
+ const recipeTag = clothMeshed.get(torsoName);
3464
+ if (recipeTag !== undefined && recipeOf(recipeTag)?.influence !== undefined) {
3465
+ throw new PartsError([{
3466
+ code: 'PROPOSE_BUST_INPUT', object: `config.cloth.${JSON.stringify(recipeTag)}.influence`,
3467
+ detail: `declares an influence mesh for chest-holding topwear "${torsoName}". This draft requires a contour torso. Remove influence from this recipe or separate the torso from its cloth part`,
3468
+ }]);
3469
+ }
3470
+ let torsoImage = P.images.get(source.name) as Raster;
3471
+ if (figPart !== null) {
3472
+ // Read the future trunk segment, using the same ownership and joint cuts as assemble.
3473
+ const places = bonePlaces(bones);
3474
+ const sharing = Object.entries(limbs).filter(([, limb]) => limb.segments.some(segment => segment.from === source.name));
3475
+ const trunkIndex = sharing.findIndex(([name]) => name === 'trunk');
3476
+ const polylines = sharing.map(([, limb]) => limbPolyline(limb, places));
3477
+ const trunkPoints = polylines[trunkIndex];
3478
+ const lines = [null, jointLine(trunkPoints[0], trunkPoints[1], trunkPoints[2]), jointLine(trunkPoints[1], trunkPoints[2], null)];
3479
+ const data = new Uint8ClampedArray(torsoImage.data);
3480
+ for (let y = 0; y < torsoImage.height; y++) {
3481
+ for (let x = 0; x < torsoImage.width; x++) {
3482
+ const alpha = (y * torsoImage.width + x) * 4 + 3;
3483
+ if (data[alpha] === 0) continue;
3484
+ const wx = source.x + x;
3485
+ const wy = source.y + y;
3486
+ if (nearestLimb(polylines, wx, wy) !== trunkIndex || segmentOf(lines, 0, 2, wx, wy) !== 1) data[alpha] = 0;
3487
+ }
3488
+ }
3489
+ torsoImage = { ...torsoImage, data };
3490
+ }
3491
+ const dust = dustOf(torsoImage);
3492
+ if ('keep' in dust) {
3493
+ throw new PartsError([{ code: 'PROPOSE_TORSO_ISLANDS', object: `chest carrier "${torsoName}"`, detail: `${dust.keep}. Separate the real pieces before drafting a contour torso` }]);
3494
+ }
3495
+ if (dust.stray !== undefined) notes.push(`${torsoName}: contour dust rule leaves out ${dust.dust.length} island(s), ${dust.dust.reduce((sum, pixels) => sum + pixels, 0)} px; contour.stray=${dust.stray}`);
3496
+ const [, radius] = gridR(source);
3497
+ const segments: Segment[] = lattice !== undefined && 'grid' in lattice ? lattice.segments : [['chest', rnd(neckAt), rnd(hip)]];
3498
+ // Same figure formulas as mesh-draft's figureRules (issue #265). Importing meshdraft here would cycle through propose.
3499
+ const tolerance = Math.max(1, Math.round(fig.height / 554));
3500
+ const contour: ContourSpec = {
3501
+ tolerance,
3502
+ margin: tolerance,
3503
+ spacing: fig.grid,
3504
+ maxEdge: fig.grid,
3505
+ ...(dust.stray === undefined ? {} : { stray: dust.stray }),
3506
+ };
3507
+ if (bust.noBust !== undefined) {
3508
+ notes.push(`${torsoName}: contour bust omitted for the declared reason: ${bust.noBust}`);
3509
+ } else if (bust.landmarks === undefined) {
3510
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: `chest-holding torso "${torsoName}"`,
3511
+ detail: 'needs a declared bust: give --bust-landmarks <file> or --no-bust "<reason>"' }]);
3512
+ } else {
3513
+ const { apex_r, apex_l } = bust.landmarks;
3514
+ let cleavage = bust.landmarks.cleavage;
3515
+ if (cleavage === undefined) {
3516
+ // #475's clearance identity requires cleavage on the apex segment, between the two apices.
3517
+ const apexDeltaX = apex_l[0] - apex_r[0];
3518
+ const apexDeltaY = apex_l[1] - apex_r[1];
3519
+ const midlineDeltaX = hip[0] - neckAt[0];
3520
+ const midlineDeltaY = hip[1] - neckAt[1];
3521
+ const cross = apexDeltaX * midlineDeltaY - apexDeltaY * midlineDeltaX;
3522
+ const share = ((neckAt[0] - apex_r[0]) * midlineDeltaY - (neckAt[1] - apex_r[1]) * midlineDeltaX) / cross;
3523
+ if (!Number.isFinite(share) || share <= 0 || share >= 1) {
3524
+ throw new PartsError([{
3525
+ code: 'PROPOSE_BUST_INPUT', object: 'landmarks.cleavage',
3526
+ detail: `the neck-to-hip midline ${fmtAt(neckAt)} -> ${fmtAt(hip)} has no unique crossing inside apex_r ${fmtAt(apex_r)} -> apex_l ${fmtAt(apex_l)}. Declare cleavage explicitly or place the apices on opposite sides of the torso midline`,
3527
+ }]);
3528
+ }
3529
+ // Derived coordinates use the same fixed-point grid the contour config reader requires.
3530
+ cleavage = [
3531
+ pyRound((apex_r[0] + share * apexDeltaX) * GRID) / GRID,
3532
+ pyRound((apex_r[1] + share * apexDeltaY) * GRID) / GRID,
3533
+ ];
3534
+ }
3535
+ const landmarks: ContourBustSpec = { apex_r, apex_l, cleavage };
3536
+ contour.bust = landmarks;
3537
+ for (const side of ['r', 'l'] as const) {
3538
+ const name = `boob_${side}`;
3539
+ const apex = landmarks[`apex_${side}`];
3540
+ // Unlike ratio placements, declared landmarks retain their subpixel coordinates.
3541
+ bones.push({ name, parent: 'chest', at: [apex[0], apex[1]] });
3542
+ records.push({ bone: name, entry: name, origin: placement('derived', `declared bust landmark apex_${side} in rig pixels`, {
3543
+ parts: [source.name], bones: ['chest'],
3544
+ }), tip: null });
3545
+ }
3546
+ notes.push(`${torsoName}: contour.bust from declared apex_r/apex_l. Cleavage ${bust.landmarks.cleavage === undefined ? 'derived at the apex segment crossing of the neck-to-hip midline' : 'declared'}. Bones boob_r/boob_l are parented to chest`);
3547
+ }
3548
+ const chains = new Set(bones.flatMap(b => 'chain' in b
3549
+ ? [b.chain, ...b.points.map((_, index) => `${b.chain}${index}`)]
3550
+ : []));
3551
+ const onChain = segments.some(segment => chains.has(typeof segment === 'string' ? segment : segment[0]));
3552
+ meshes[torsoName] = {
3553
+ contour,
3554
+ r: lattice !== undefined && 'grid' in lattice ? lattice.r : radius,
3555
+ segments,
3556
+ ...(onChain ? { influences: { maxInfluences: null, floor: 'continuous' as const } } : {}),
3557
+ };
3558
+ delete regions[torsoName];
3559
+ if (onChain) notes.push(`${torsoName}: contour segments name a chain. Drafted influences.maxInfluences=null and floor=continuous to avoid the influence cut's weight step across short outline edges (issue #991)`);
3560
+ } else if (bust.landmarks !== undefined) {
3561
+ throw new PartsError([{ code: 'PROPOSE_BUST_INPUT', object: 'chest carrier', detail: `no topwear art covers chest at ${fmtAt(chest)}. A chest-holding topwear part is required for the declared bust input` }]);
3562
+ }
3418
3563
  if (gridRule === 'figure') {
3419
3564
  const latt = Object.keys(meshes).filter((m) => 'grid' in meshes[m] && ownGrid.has(m));
3420
3565
  if (latt.length > 0) notes.push(gridNote(fig, latt.map((m) => [m, ownGrid.get(m) as number])));
@@ -0,0 +1,76 @@
1
+ /** Optional source-bound independent assembly domains (#998). */
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { SUPPORT_GRID_CODE, type SupportDomain, type SupportDomainReading } from './coincide.ts';
6
+ import { refuseIfAny } from './errors.ts';
7
+ import type { PartsFile } from './parts.ts';
8
+
9
+ export const SUPPORT_DOMAINS_FILE = 'part_support_domains.json';
10
+ const SPEC = 'rig-parts-support-domains/1';
11
+ const sha = (data: Uint8Array | string): string => createHash('sha256').update(data).digest('hex');
12
+ const object = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
13
+ const digest = (v: unknown): v is string => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
14
+
15
+ /** Sorted flattened [start,length] runs retain the assembler's exact mask.
16
+ * The reader decodes them; it never re-derives a second polygon rasteriser. */
17
+ function runs(data: Uint8Array): Array<[number, number]> {
18
+ const out: Array<[number, number]> = [];
19
+ for (let p = 0; p < data.length; p++) {
20
+ if (data[p] === 0) continue;
21
+ const start = p;
22
+ while (p + 1 < data.length && data[p + 1] !== 0) p++;
23
+ out.push([start, p - start + 1]);
24
+ }
25
+ return out;
26
+ }
27
+
28
+ /** Only a separate optional file is written. Existing parts and PNGs are read. */
29
+ export function writeSupportDomains(partsPath: string, partsDir: string, parts: PartsFile, domains: readonly SupportDomainReading[], declarations: string): void {
30
+ const entries = parts.parts.map(part => {
31
+ const domain = domains.find(d => d.part === part.name);
32
+ if (domain !== undefined && 'mask' in domain) return { part: part.name, status: 'measured', provenance: domain.provenance, runs: runs(domain.mask.data) };
33
+ const reason = domain !== undefined ? domain.reason : part.limb !== undefined
34
+ ? `limb segment "${part.name}" has joint lines but no authored radial width; the art-derived cap radius is not an independent witness`
35
+ : 'no authored spatial cut domain; config.regions is only a bone binding';
36
+ return { part: part.name, status: 'unavailable', reason };
37
+ });
38
+ writeFileSync(join(dirname(partsPath), SUPPORT_DOMAINS_FILE), JSON.stringify({
39
+ spec: SPEC, grid: parts.rig_size, declarations_sha256: sha(declarations), parts_sha256: sha(readFileSync(partsPath)),
40
+ images: parts.parts.map(p => ({ part: p.name, sha256: sha(readFileSync(join(partsDir, `${p.name}.png`))) })),
41
+ domains_sha256: sha(JSON.stringify(entries)), domains: entries,
42
+ }, null, 2) + '\n');
43
+ }
44
+
45
+ /** Missing/stale evidence is unavailable. A dimension mismatch is a named
46
+ * refusal because source and setup cells cannot be compared on different grids. */
47
+ export function readSupportDomains(partsPath: string, partsDir: string, parts: PartsFile): SupportDomainReading[] {
48
+ const unavailable = (reason: string): SupportDomainReading[] => parts.parts.map(p => ({ part: p.name, reason }));
49
+ const file = join(dirname(partsPath), SUPPORT_DOMAINS_FILE);
50
+ if (!existsSync(file)) return unavailable('independent support sidecar is unavailable (legacy output)');
51
+ let raw: unknown;
52
+ try { raw = JSON.parse(readFileSync(file, 'utf8')); } catch { return unavailable('independent support sidecar is not readable JSON'); }
53
+ if (!object(raw) || raw.spec !== SPEC || !Array.isArray(raw.grid) || raw.grid.length !== 2 || !raw.grid.every(v => Number.isSafeInteger(v) && v > 0)) return unavailable('independent support sidecar has no valid spec or native grid');
54
+ const [width, height] = parts.rig_size;
55
+ if (raw.grid[0] !== width || raw.grid[1] !== height) refuseIfAny([{ code: SUPPORT_GRID_CODE, object: SUPPORT_DOMAINS_FILE, detail: `declares ${raw.grid.join('x')}; parts.json requires ${width}x${height}` }]);
56
+ if (!digest(raw.declarations_sha256) || raw.parts_sha256 !== sha(readFileSync(partsPath)) || !Array.isArray(raw.images) || raw.images.length !== parts.parts.length || !Array.isArray(raw.domains) || raw.domains.length !== parts.parts.length || raw.domains_sha256 !== sha(JSON.stringify(raw.domains))) return unavailable('independent support sidecar does not bind these parts or its domain payload');
57
+ for (let i = 0; i < parts.parts.length; i++) {
58
+ const binding: unknown = raw.images[i], part = parts.parts[i];
59
+ if (!object(binding) || binding.part !== part.name || binding.sha256 !== sha(readFileSync(join(partsDir, `${part.name}.png`)))) return unavailable(`independent support sidecar PNG binding differs for "${part.name}"`);
60
+ }
61
+ const domains: SupportDomainReading[] = [];
62
+ for (let i = 0; i < parts.parts.length; i++) {
63
+ const row: unknown = raw.domains[i];
64
+ if (!object(row) || row.part !== parts.parts[i].name) return unavailable('independent support sidecar does not name every part in assembly order');
65
+ if (row.status === 'unavailable' && typeof row.reason === 'string' && row.reason.length > 0) { domains.push({ part: row.part, reason: row.reason }); continue; }
66
+ if (row.status !== 'measured' || !object(row.provenance) || row.provenance.kind !== 'cut-polygon' || typeof row.provenance.entry !== 'string' || !Array.isArray(row.runs)) return unavailable(`independent support domain for "${row.part}" lacks authored cut provenance or runs`);
67
+ const data = new Uint8Array(width * height);
68
+ let previous = 0;
69
+ for (const run of row.runs) {
70
+ if (!Array.isArray(run) || run.length !== 2 || !run.every(Number.isSafeInteger) || run[0] < previous || run[1] <= 0 || run[0] + run[1] > data.length) return unavailable(`independent support runs for "${row.part}" are invalid or overlap`);
71
+ data.fill(1, run[0], run[0] + run[1]); previous = run[0] + run[1];
72
+ }
73
+ domains.push({ part: row.part, mask: { width, height, data }, provenance: row.provenance as unknown as SupportDomain['provenance'] });
74
+ }
75
+ return domains;
76
+ }
@@ -4,6 +4,7 @@ import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, wr
4
4
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { assembleStage, checkStage, rigStage, type AssembleOutputs, type AssembleStageInput, type CheckStageInput, type RigStageInput } from '../src/build.ts';
6
6
  import { rigcRunnerAt, type CheckReport, type RigcRunner } from '../src/check.ts';
7
+ import type { Mask } from '../src/raster/types.ts';
7
8
  import { PartsError, type Problem } from '../src/errors.ts';
8
9
 
9
10
  /** Preserve native/custom executables; adapt only a proven package-manager script shim. */
@@ -72,6 +73,20 @@ export type BuildProcessJob =
72
73
  function record(value: unknown): value is Record<string, unknown> {
73
74
  return value !== null && typeof value === 'object' && !Array.isArray(value);
74
75
  }
76
+ type AssemblyReading = { supportFigure?: Mask };
77
+ type StageReading = CheckReport | AssemblyReading | void;
78
+
79
+ /** Private inter-process source observation, never written to build outputs. */
80
+ function encodeSupportFigure(figure: Mask): { width: number; height: number; alpha_base64: string } {
81
+ return { width: figure.width, height: figure.height, alpha_base64: Buffer.from(figure.data).toString('base64') };
82
+ }
83
+ function decodeSupportFigure(value: unknown): Mask {
84
+ if (!record(value) || !Number.isSafeInteger(value.width) || !Number.isSafeInteger(value.height) ||
85
+ typeof value.width !== 'number' || typeof value.height !== 'number' || value.width <= 0 || value.height <= 0 || typeof value.alpha_base64 !== 'string') throw new Error('BUILD_STAGE_SUPPORT_FIGURE: positive native dimensions and encoded alpha are required');
86
+ const data = Buffer.from(value.alpha_base64, 'base64');
87
+ if (data.length !== value.width * value.height || data.toString('base64') !== value.alpha_base64 || data.some(p => p !== 0 && p !== 1)) throw new Error('BUILD_STAGE_SUPPORT_FIGURE: canonical binary alpha must fill the native grid');
88
+ return { width: value.width, height: value.height, data };
89
+ }
75
90
  function problems(value: unknown): value is Problem[] {
76
91
  return Array.isArray(value) && value.length > 0 && value.every((p) => record(p) && typeof p.code === 'string' && typeof p.object === 'string' && typeof p.detail === 'string');
77
92
  }
@@ -93,9 +108,10 @@ function checkReport(value: unknown): value is CheckReport {
93
108
 
94
109
  /** Decode only a matching successful stage or its original named input refusal. */
95
110
  export function readBuildReceipt(stage: 'check', status: number | null, signal: string | null, text: string): CheckReport;
96
- export function readBuildReceipt(stage: 'assemble' | 'rig', status: number | null, signal: string | null, text: string): void;
97
- export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void;
98
- export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): CheckReport | void {
111
+ export function readBuildReceipt(stage: 'assemble', status: number | null, signal: string | null, text: string): AssemblyReading | void;
112
+ export function readBuildReceipt(stage: 'rig', status: number | null, signal: string | null, text: string): void;
113
+ export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): StageReading;
114
+ export function readBuildReceipt(stage: Stage, status: number | null, signal: string | null, text: string): StageReading {
99
115
  if (signal !== null || status === null || (status !== 0 && status !== 1) || (status !== 0 && text === '')) {
100
116
  throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ', signal ' + signal + '; no later stage ran');
101
117
  }
@@ -110,6 +126,8 @@ export function readBuildReceipt(stage: Stage, status: number | null, signal: st
110
126
  if (status !== 0) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' child — exit ' + status + ' with a completion receipt; no later stage ran');
111
127
  if (stage !== 'check') {
112
128
  if (Object.hasOwn(row, 'report') || Object.hasOwn(row, 'sweepSteps')) return resultError(stage, 'a void stage returned an invented check report');
129
+ if (stage === 'assemble' && row.supportFigure !== undefined) return { supportFigure: decodeSupportFigure(row.supportFigure) };
130
+ if (row.supportFigure !== undefined) return resultError(stage, 'only assembly returns a source observation');
113
131
  return;
114
132
  }
115
133
  if (!checkReport(row.report)) return resultError(stage, 'check report is incomplete');
@@ -129,7 +147,7 @@ export function encodeCheckReceipt(report: CheckReport): string {
129
147
  }
130
148
 
131
149
  /** Minimum Bun may attach error to an ordinary nonzero exit; only an unstarted child is a launch failure. */
132
- export function readBuildChild(stage: Stage, child: { status: number | null; signal: string | null; error?: Error }, text: string): CheckReport | void {
150
+ export function readBuildChild(stage: Stage, child: { status: number | null; signal: string | null; error?: Error }, text: string): StageReading {
133
151
  if (!childStarted(child) && child.error !== undefined) throw new Error('BUILD_STAGE_CHILD: ' + stage + ' could not start — ' + child.error.message);
134
152
  return readBuildReceipt(stage, child.status ?? null, child.signal ?? null, text);
135
153
  }
@@ -142,13 +160,15 @@ export function launchBuildChild(argv: readonly string[]): { status: number | nu
142
160
  }
143
161
 
144
162
  export function runBuildProcess(job: Extract<BuildProcessJob, { stage: 'check' }>, home: string): CheckReport;
145
- export function runBuildProcess(job: Exclude<BuildProcessJob, { stage: 'check' }>, home: string): void;
146
- export function runBuildProcess(job: BuildProcessJob, home: string): CheckReport | void {
163
+ export function runBuildProcess(job: Extract<BuildProcessJob, { stage: 'assemble' }>, home: string): AssemblyReading | void;
164
+ export function runBuildProcess(job: Extract<BuildProcessJob, { stage: 'rig' }>, home: string): void;
165
+ export function runBuildProcess(job: BuildProcessJob, home: string): StageReading {
147
166
  mkdirSync(home, { recursive: true });
148
167
  const request = join(home, job.stage + '.request.json');
149
168
  const result = join(home, job.stage + '.result.json');
150
169
  rmSync(result, { force: true });
151
- writeFileSync(request, JSON.stringify(job));
170
+ const wire = job.stage === 'check' && job.input.supportFigure !== undefined ? { ...job, input: { ...job.input, supportFigure: encodeSupportFigure(job.input.supportFigure) } } : job;
171
+ writeFileSync(request, JSON.stringify(wire));
152
172
  try {
153
173
  const child = launchBuildChild([process.execPath, import.meta.path, request, result]);
154
174
  return readBuildChild(job.stage, child, existsSync(result) ? readFileSync(result, 'utf8') : '');
@@ -174,6 +194,7 @@ function readJob(path: string): BuildProcessJob {
174
194
  if (!strings(['config', 'parts', 'out']) || typeof job.scratch !== 'string' || Object.hasOwn(input, 'reduce')) return requestError('rig input or scratch is incomplete, or contains a nonserializable reducer');
175
195
  } else if (job.stage === 'check') {
176
196
  if (!strings(['rig', 'out'])) return requestError('check input paths are incomplete');
197
+ if (input.supportFigure !== undefined) input.supportFigure = decodeSupportFigure(input.supportFigure);
177
198
  } else return requestError('unknown stage ' + JSON.stringify(job.stage));
178
199
  return job as unknown as BuildProcessJob;
179
200
  }
@@ -185,10 +206,11 @@ function worker(args: string[]): number {
185
206
  const log = (line: string): void => { console.log('[' + job.stage + '] ' + line); };
186
207
  try {
187
208
  let report: CheckReport | undefined;
188
- if (job.stage === 'assemble') assembleStage(job.input, job.outputs, log);
209
+ let supportFigure: Mask | undefined;
210
+ if (job.stage === 'assemble') supportFigure = assembleStage(job.input, job.outputs, log).supportFigure;
189
211
  else if (job.stage === 'rig') rigStage(job.input, runner, job.scratch, log);
190
212
  else report = checkStage(job.input, runner, job.bin, log);
191
- writeFileSync(args[1], report === undefined ? JSON.stringify({ version: 1, stage: job.stage, kind: 'done' }) : encodeCheckReceipt(report));
213
+ writeFileSync(args[1], report === undefined ? JSON.stringify({ version: 1, stage: job.stage, kind: 'done', ...(supportFigure === undefined ? {} : { supportFigure: encodeSupportFigure(supportFigure) }) }) : encodeCheckReceipt(report));
192
214
  return 0;
193
215
  } catch (err) {
194
216
  if (!(err instanceof PartsError)) throw err;