@rig-c/parts 1.84.0 → 1.86.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/check.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import { SETUP_PAINTING_LINE, setupPaintingBounds, setupPaintingLine, type SetupPainting, type SetupPaintingLine } from './setuppainting.ts';
2
+ import { readMaterialSources } from './cutmaterialio.ts';
3
+ import { CUT_MATERIAL_LINE, checkJointMaterial, type MaterialLine } from './cutmaterial.ts';
1
4
  import { ART_JOINT_LINE, artJointLine, type ArtJointLine } from './artjoints.ts';
2
5
  import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
3
6
  /**
@@ -80,12 +83,13 @@ import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
80
83
  * the last idle frame is refused unless it sits at t = duration (within
81
84
  * `TIME_SLACK`, issue #244).
82
85
  */
86
+ import { jointContactReading, type JointContactReading } from './jointcontact.ts';
83
87
  import { createHash } from 'node:crypto';
84
88
  import { createRequire } from 'node:module';
85
89
  import type { Viewport as RootCoverageViewport } from '@rig-c/core/render-shared';
86
90
  import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
87
91
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
88
- import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
92
+ import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig, figureSilhouette } from './assemble.ts';
89
93
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toBoneLocal } from './coords.ts';
90
94
  import { capBox, inDisc } from './limbs.ts';
91
95
  import { motionSeamProblems } from './motionseams.ts';
@@ -1931,6 +1935,35 @@ function officialRenderer(): OfficialRenderer {
1931
1935
  return require('@rig-c/core/render-shared') as OfficialRenderer;
1932
1936
  }
1933
1937
 
1938
+ /** Observe the actual setup on the declared stage grid. No frame-zero motion,
1939
+ * fitted alignment, flat recomposite or duplicate core validation. */
1940
+ export function measureSetupPainting(build: string, stage: StageBox, source: Raster, declared: SetupPainting, problems: Problem[]): SetupPaintingLine {
1941
+ const api = officialRenderer();
1942
+ const skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
1943
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: 'setup versus painting' }, { skeleton, atlas }, undefined);
1944
+ const pose = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, { geometry: true, texture: true })).value[0];
1945
+ if (pose === undefined || pose.pieces.some(p => 'source' in p)) {
1946
+ refuseIfAny([{ code: 'CHECK_SETUP_PAINTING_MEASURED', object: SETUP_PAINTING_LINE, detail: 'actual textured setup pieces are unavailable or include clipping; no guessed ownership is substituted' }]);
1947
+ }
1948
+ const W = stage.width, H = stage.height;
1949
+ if (!Number.isSafeInteger(W) || !Number.isSafeInteger(H) || W <= 0 || H <= 0) refuseIfAny([{ code: 'CHECK_SETUP_PAINTING_MEASURED', object: SETUP_PAINTING_LINE, detail: 'requires positive integer stage width/height for a native source-grid observation' }]);
1950
+ const vp = { minX: stage.x, minY: stage.y, maxX: stage.x + W, maxY: stage.y + H, scale: 1, width: W, height: H };
1951
+ const project = api.projector(vp), owners = new Int32Array(W * H).fill(-1);
1952
+ pose.pieces.forEach((piece, i) => api.rasterisePiece(api.pageFor(candidate.pages, piece), piece, project, vp, (x, y, _r, _g, _b, a) => { if (a > 0) owners[y * W + x] = i; }));
1953
+ // sourceInRig intentionally reads opaque RGB, discarding source alpha before
1954
+ // resizing. This optional comparison declares source-over white instead:
1955
+ // flatten at ORIGINAL source resolution first, so hidden RGB cannot reach
1956
+ // Lanczos taps or the figure silhouette. Do not change the legacy helper.
1957
+ const whiteSource = newRaster(source.width, source.height);
1958
+ for (let p = 0; p < source.width * source.height; p++) {
1959
+ for (let c = 0; c < 3; c++) whiteSource.data[p * 4 + c] = Math.round(source.data[p * 4 + c] * source.data[p * 4 + 3] / 255 + 255 * (1 - source.data[p * 4 + 3] / 255));
1960
+ whiteSource.data[p * 4 + 3] = 255;
1961
+ }
1962
+ const painting = sourceInRig(whiteSource, W, H);
1963
+ const setup = api.renderFrame(pose, candidate.pages, vp, [0, 0, 0, 0]);
1964
+ return setupPaintingLine(declared, painting, { width: W, height: H, data: new Uint8ClampedArray(setup.data) }, figureSilhouette(painting).data, owners, pose.pieces.map(p => p.slot), problems);
1965
+ }
1966
+
1934
1967
  /** One decoder/poser lifetime per state; retain only finite bounds and identities, never atlas pages or rasters. */
1935
1968
  export function seamStateBounds(build: string, state: string): SeamStateBounds {
1936
1969
  try {
@@ -2697,6 +2730,9 @@ export interface CheckFigures {
2697
2730
  requirements?: RequirementsBlock;
2698
2731
  /** Issue #880: only when requirements declares fixed_skeleton. */
2699
2732
  [ART_JOINT_LINE]?: ArtJointLine;
2733
+ /** Only when setup_painting is explicitly declared. */
2734
+ [SETUP_PAINTING_LINE]?: SetupPaintingLine;
2735
+ [CUT_MATERIAL_LINE]?: MaterialLine;
2700
2736
  PASS: boolean;
2701
2737
  }
2702
2738
 
@@ -2943,7 +2979,7 @@ export function barsNotMet(fig: Readonly<Record<string, unknown>>): string[] {
2943
2979
  isRecord(fig.sets) &&
2944
2980
  Object.values(fig.sets).some((s) => isRecord(s) && typeof s.seam_mean === 'number' && typeof s.seam_px_over_40 === 'number' && seamFails(s.seam_mean, s.seam_px_over_40, typeof s.seam_frame_scale === 'number' ? s.seam_frame_scale : 1));
2945
2981
  if ((typeof fig.seam_mean === 'number' && typeof fig.seam_px_over_40 === 'number' && seamFails(fig.seam_mean, fig.seam_px_over_40, scale)) || setFailed) out.push('seam');
2946
- for (const n of [...JUDGEMENT_LINES, FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, ART_JOINT_LINE]) {
2982
+ for (const n of [...JUDGEMENT_LINES, FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE]) {
2947
2983
  const l = fig[n];
2948
2984
  if (typeof l === 'object' && l !== null && (l as { status?: unknown }).status === 'FAIL') out.push(n);
2949
2985
  }
@@ -3052,7 +3088,7 @@ export function checkStatuses(fig: CheckFigures): Record<string, CheckStatus> {
3052
3088
  const bar = (name: string, measured: boolean): CheckStatus => (!measured ? 'SKIP' : notMet.includes(name) ? 'FAIL' : 'PASS');
3053
3089
  const out: Record<string, CheckStatus> = { gate: bar('gate', true), loop: bar('loop', fig.loop_max_diff !== null), seam: bar('seam', fig.seam_mean !== null) };
3054
3090
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3055
- for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, ...REPORTED_LINES, SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE] as const) {
3091
+ for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, ...REPORTED_LINES, SOURCE_LINE, WIND_BAND_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE, SETUP_PAINTING_LINE] as const) {
3056
3092
  const l = fig[n];
3057
3093
  if (l !== undefined) out[n] = l.status;
3058
3094
  }
@@ -4306,6 +4342,8 @@ export interface MotionSeamPair {
4306
4342
  a: string;
4307
4343
  b: string;
4308
4344
  declared: string[];
4345
+ /** Explicit limb joint labels or a proven body root's bone; never inferred for arbitrary seams. */
4346
+ joints?: string[];
4309
4347
  /** Why the pair is not read: a slot `rig.json` does not have. */
4310
4348
  unread?: string;
4311
4349
  /** Issue #686: segment-zero provenance and its immediate named body carrier. */
@@ -4339,6 +4377,8 @@ export interface MotionSeamSelection {
4339
4377
  export interface MotionSeamRow {
4340
4378
  pair: string;
4341
4379
  animation: string;
4380
+ /** Report-only core connectivity, independent of raw counts and verdicts. */
4381
+ joint_contact?: JointContactReading;
4342
4382
  /** rigc's: `skip` when no frame has a band to read — nothing measured, not a seam that held. */
4343
4383
  status: 'read' | 'skip';
4344
4384
  /** Frames both slots draw, and of those the frames read (rigc's `drawn`, `banded`). */
@@ -4391,10 +4431,12 @@ export function motionSeamPairs(parts: PartsFile, seams: ReadonlyArray<{ name: s
4391
4431
  export function motionSeamSelection(parts: PartsFile, seams: ReadonlyArray<{ name: string; part: string; neighbour: string }>, rig?: Record<string, unknown>, readSetup?: (candidates: readonly MotionSeamPair[]) => readonly MotionRootSetupRow[]): MotionSeamSelection {
4392
4432
  const out: MotionSeamPair[] = [];
4393
4433
  const unmeasuredRoots: MotionUnmeasuredRoot[] = [];
4394
- const add = (a: string, b: string, declared: string): void => {
4434
+ const add = (a: string, b: string, declared: string, joint?: string): void => {
4395
4435
  const hit = out.find((p) => (p.a === a && p.b === b) || (p.a === b && p.b === a));
4396
- if (hit !== undefined) hit.declared.push(declared);
4397
- else out.push({ pair: `${a}|${b}`, a, b, declared: [declared] });
4436
+ if (hit !== undefined) {
4437
+ hit.declared.push(declared);
4438
+ if (joint !== undefined && !hit.joints?.includes(joint)) (hit.joints ??= []).push(joint);
4439
+ } else out.push({ pair: `${a}|${b}`, a, b, declared: [declared], ...(joint === undefined ? {} : { joints: [joint] }) });
4398
4440
  };
4399
4441
  const limbs: string[] = [];
4400
4442
  for (const p of parts.parts) if (p.limb !== undefined && !limbs.includes(p.limb.name)) limbs.push(p.limb.name);
@@ -4402,7 +4444,7 @@ export function motionSeamSelection(parts: PartsFile, seams: ReadonlyArray<{ nam
4402
4444
  const segs = parts.parts.filter((p) => p.limb?.name === limb).sort((x, y) => (x.limb as LimbRecord).segment - (y.limb as LimbRecord).segment);
4403
4445
  for (let i = 1; i < segs.length; i++) {
4404
4446
  const lower = segs[i].limb as LimbRecord;
4405
- add(segs[i - 1].name, segs[i].name, `config.limbs.${limb} segment ${lower.segment}${lower.joint === undefined ? '' : `, joint "${lower.joint}"`}`);
4447
+ add(segs[i - 1].name, segs[i].name, `config.limbs.${limb} segment ${lower.segment}${lower.joint === undefined ? '' : `, joint "${lower.joint}"`}`, lower.joint);
4406
4448
  }
4407
4449
  }
4408
4450
  for (const r of seams) add(r.part, r.neighbour, `requirement "${r.name}" (seam)`);
@@ -4438,7 +4480,7 @@ export function motionSeamSelection(parts: PartsFile, seams: ReadonlyArray<{ nam
4438
4480
  }
4439
4481
  }
4440
4482
  for (const root of selected) {
4441
- add(root.a, root.b, root.declared[0]);
4483
+ add(root.a, root.b, root.declared[0], root.root?.bone);
4442
4484
  const pair = out.find(p => (p.a === root.a && p.b === root.b) || (p.a === root.b && p.b === root.a));
4443
4485
  if (pair !== undefined) pair.root = root.root;
4444
4486
  }
@@ -4543,7 +4585,7 @@ function motionRootCandidates(parts: PartsFile, rig: Record<string, unknown>): M
4543
4585
  }
4544
4586
  for (const { part: body } of eligible) out.push({ pair: body.name + '|' + root.name, a: body.name, b: root.name,
4545
4587
  declared: ['config.limbs.' + limb + ' segment 0, body carrier "' + parent + '" from ' + body.from],
4546
- root: { limb, bone: l.bone, parent } });
4588
+ joints: [l.bone], root: { limb, bone: l.bone, parent } });
4547
4589
  }
4548
4590
  refuseIfAny(problems);
4549
4591
  return out;
@@ -4888,11 +4930,14 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4888
4930
  }
4889
4931
  }
4890
4932
  }
4933
+ const contact = setup ? undefined : jointContactReading(p.jointContact, want.joints ?? [], set.written ?? set.sampled, at, problems);
4934
+ if (contact === null) return;
4891
4935
  worldRows?.push({ pair: want.pair, animation, status: p.status, drawn: p.drawn, banded: p.banded, gap: kinds.gap, ghost: kinds.ghost });
4892
4936
  const opens = [...over.keys()].sort((x, y) => x - y);
4893
4937
  rows.push({
4894
4938
  pair: want.pair,
4895
4939
  animation,
4940
+ ...(setup ? {} : { joint_contact: contact }),
4896
4941
  status: p.status,
4897
4942
  drawn: p.drawn,
4898
4943
  banded: p.banded,
@@ -5046,6 +5091,21 @@ export function enrichMotionSeamPoses(dir: string, rig: Record<string, unknown>,
5046
5091
  }
5047
5092
  }
5048
5093
 
5094
+ /** One informational line per observed pair/animation; missing readings are named SKIP. */
5095
+ export function motionJointContactLines(line: MotionSeamLine): string[] {
5096
+ if (line.rows.length === 0) return ['JOINT_CONTACT: SKIP — ' + (line.reason ?? 'no sampled pair/animation reading')];
5097
+ const lines = line.rows.map(row => {
5098
+ const c = row.joint_contact;
5099
+ const head = 'JOINT_CONTACT: "' + row.pair + '" in "' + row.animation + '"';
5100
+ if (c === undefined || c.status === 'SKIP') return head + ': SKIP — ' + (c?.reason ?? 'no contact observation');
5101
+ return head + ', joint ' + (c.joints.length === 0 ? 'unavailable' : c.joints.map(n => JSON.stringify(n)).join(', ')) +
5102
+ ': joined ' + c.joined + ', separated ' + c.separated + ', unavailable ' + c.unavailable + ' frame(s)' +
5103
+ (c.reasons.length === 0 ? '' : '; ' + c.reasons.map(r => r.reason + (r.frames === undefined ? '' : ' on frames ' + frameRuns(r.frames))).join('; ')) + '; report only';
5104
+ });
5105
+ for (const pair of line.pairs) if (!line.rows.some(row => row.pair === pair.pair)) lines.push('JOINT_CONTACT: "' + pair.pair + '": SKIP — ' + (pair.unread ?? line.reason ?? 'no sampled animation'));
5106
+ return lines;
5107
+ }
5108
+
5049
5109
  /** One warning as the console prints it (issue #493's form, the floor's clause after it). */
5050
5110
  export function motionSeamWarnText(r: MotionSeamRow): string {
5051
5111
  const pose = r.pose_at_worst;
@@ -5862,6 +5922,10 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5862
5922
  const file = reqFile as RequirementsFile;
5863
5923
  const ready = inp;
5864
5924
  take(() => resolveRequirements(file, ready.rig, ready.motion, ready.rootBone));
5925
+ if (file.setup_painting !== undefined) take(() => {
5926
+ refuseIfAny(setupPaintingBounds(file.setup_painting as SetupPainting, ready.stage.width, ready.stage.height));
5927
+ if (ready.source === null) refuseIfAny([{ code: 'CHECK_SETUP_PAINTING_SOURCE', object: 'requirements.setup_painting', detail: 'requires --source naming the painting; the assembled composite is not an independent source painting' }]);
5928
+ });
5865
5929
  take(() => refuseIfAny(exceptionProblems(file, ready.parts, ready.noParts)));
5866
5930
  // A seam's pairs are read off parts.json's art (issue #111); both resolvers' problems are named in one refusal.
5867
5931
  if (file.requirements.some((r) => r.kind === 'seam')) {
@@ -5879,6 +5943,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5879
5943
  if (env !== null && !(isRecord(inp.motion.animations) && Object.keys(inp.motion.animations).length > 0)) {
5880
5944
  throw environmentRefused(env.path, `${inp.motionPath} holds no animation, so check renders no frame a schedule could pose — the setup-pose stills take none; rigc render reads a schedule only over an animation's frames`);
5881
5945
  }
5946
+ // Read source support before rendering; no output/sidecar for undeclared builds.
5947
+ if (reqFile?.cut_material !== undefined && (set !== undefined || allSets)) refuseIfAny([{code: 'CHECK_CUT_MATERIAL_MEASURED', object: 'cut_material', detail: 'source evidence binds base assembly only; run check on its base parts without --set/--all-sets; alternate-set coverage requires its own original source instrument'}]);
5948
+ const cutMaterialProblems: Problem[] = [];
5949
+ const cutMaterial = reqFile?.cut_material === undefined ? null : checkJointMaterial(reqFile.cut_material, inp.parts, name => readPng(join(inp.partsDir, `${name}.png`)), cutMaterialProblems, inp.parts === null ? undefined : readMaterialSources(dirname(inp.partsDir), inp.parts));
5950
+ // A measured material failure is a check bar; unavailable data is a refusal.
5882
5951
  const rigcEntry = readRigcEntry(requireRigcVersion(rigc));
5883
5952
  /**
5884
5953
  * Issue #538: a render whose frames a bar or a warning reads, with the physics on — posed under the schedule when
@@ -6407,6 +6476,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6407
6476
  const setHints = new Map<string, string>();
6408
6477
  const fixedSkeleton = reqFile?.fixed_skeleton;
6409
6478
  let artJoints: ArtJointLine | null = null;
6479
+ let setupPainting: SetupPaintingLine | null = null;
6410
6480
  if (inp.parts !== null || inp.source !== null || fixedSkeleton !== undefined) {
6411
6481
  try {
6412
6482
  mkdirSync(stillDir, { recursive: true });
@@ -6434,6 +6504,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6434
6504
  const sr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), ...(fixedSkeleton === undefined ? [] : ['--geometry']), '--out', join(stillDir, 'render')]);
6435
6505
  if (sr.status !== 0) refuseIfAny(rigcFailed('render (the setup-pose still)', sr, sr.out.split('\n').filter((l) => l.includes('FAIL'))));
6436
6506
  const stillSet = readFrameSet(join(stillDir, 'render'));
6507
+ if (reqFile?.setup_painting !== undefined && inp.source !== null) setupPainting = measureSetupPainting(join(stillDir, 'build'), inp.stage, inp.source.painting, reqFile.setup_painting, problems);
6437
6508
  if (fixedSkeleton !== undefined) {
6438
6509
  const geometryPath = join(stillSet.dir, GEOMETRY_FILE);
6439
6510
  const geometry = readGeometry(geometryPath, stillSet.written);
@@ -6636,6 +6707,8 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6636
6707
  ...(Object.keys(setsFigures).length === 0 ? {} : { sets: setsFigures }),
6637
6708
  ...(config === undefined ? {} : { config }),
6638
6709
  ...(artJoints === null ? {} : { [ART_JOINT_LINE]: artJoints }),
6710
+ ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
6711
+ ...(cutMaterial === null ? {} : { [CUT_MATERIAL_LINE]: cutMaterial }),
6639
6712
  ...(reqBlock === null ? {} : { requirements: reqBlock }),
6640
6713
  PASS: false,
6641
6714
  };
@@ -6679,7 +6752,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6679
6752
  const rank = (q: Problem): number => JUDGEMENT_LINES.findIndex((n) => q.code === `CHECK_${n}`);
6680
6753
  problems.sort((a, b) => rank(a) - rank(b));
6681
6754
  problems.unshift(...barProblems);
6682
- problems.push(...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
6755
+ problems.push(...cutMaterialProblems, ...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
6683
6756
  figures.PASS = problems.length === 0;
6684
6757
  const publishCheck = (): void => write('check.json', `${JSON.stringify(figures, null, 1)}\n`);
6685
6758
  if (motionSeam.worlds === undefined) publishCheck();
@@ -6699,7 +6772,9 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6699
6772
  }
6700
6773
  // Issues #320, #333: the fold bar is counted where it is written — on every rig whose motion holds an animation.
6701
6774
  if (folds !== null) tally(FOLD_LINE, null);
6775
+ if (cutMaterial !== null) tally(CUT_MATERIAL_LINE, null);
6702
6776
  if (artJoints !== null) tally(ART_JOINT_LINE, artJoints.status === 'SKIP' ? (artJoints.reason ?? 'no declared limit') : null);
6777
+ if (setupPainting !== null) tally(SETUP_PAINTING_LINE, setupPainting.status === 'SKIP' ? (setupPainting.reason ?? 'no declared limit') : null);
6703
6778
  // Issue #348: the level bar where it is written; a line whose every foot no frame posed says SKIP and is not measured.
6704
6779
  if (level !== null) tally(LEVEL_LINE, level.status === 'SKIP' ? (level.reason ?? '') : null);
6705
6780
  // Issue #347: the stress bar is counted where it is written — on every rig with a handwear part and an idle.
@@ -0,0 +1,285 @@
1
+ import { edgeLength } from './length.ts';
2
+ import { createHash } from 'node:crypto';
3
+ /** Source support at declared joints (#888). Geometry is in stage pixels, y down.
4
+ * No scene, motion, material or threshold is inferred. This measures pixel-cell
5
+ * support on normal rays, not rendered seam visibility or a continuous surface.
6
+ */
7
+ import { type Raster } from './raster/types.ts';
8
+ import { OPAQUE_ALPHA_ABOVE } from './layers.ts';
9
+ import { refuseIfAny, type Problem } from './errors.ts';
10
+ import type { PartsFile } from './parts.ts';
11
+ export type Point = [number, number];
12
+ export interface JointMaterial {
13
+ part: string;
14
+ joint: string;
15
+ at: Point;
16
+ /** Points into the piece; need not be unit length. */
17
+ axis: Point;
18
+ reach_px: number;
19
+ /** Continuous interval in stage coordinates (positive clockwise). */
20
+ bend_degrees: Point;
21
+ }
22
+ export interface MaterialEdge { a: Point; b: Point; inward: Point; opaque_t?: Array<[number, number]>; opaque_length_px?: number; opaque_intervals?: number }
23
+ export interface MaterialSource { part: string; from: string[]; source_sha256: string[]; edges: MaterialEdge[] }
24
+ export const CUT_MATERIAL_SOURCES = 'cut_material_sources.json';
25
+ export const CUT_MATERIAL_SPEC = 'rig-parts-cut-material-sources/1';
26
+ export interface PlacedArt { x: number; y: number; image: Raster }
27
+ export interface MaterialRow {
28
+ part: string; joint: string; edge: [Point, Point]; edge_length_px: number; within_reach_px: number;
29
+ found_px: number; required_px: number; rays: number;
30
+ status: 'PASS' | 'FAIL' | 'SKIP'; reason?: string;
31
+ }
32
+ export const CUT_MATERIAL_LINE = 'CUT_JOINT_MATERIAL';
33
+ export interface MaterialLine { status: 'PASS' | 'FAIL' | 'SKIP'; rows: MaterialRow[]; reason?: string }
34
+ const obj = (x: unknown): x is Record<string, unknown> => typeof x === 'object' && x !== null && !Array.isArray(x);
35
+ const num = (x: unknown): x is number => typeof x === 'number' && Number.isFinite(x);
36
+ const pair = (x: unknown): x is Point => Array.isArray(x) && x.length === 2 && x.every(num);
37
+ export function jointMaterialProblems(raw: unknown, at: string): Problem[] {
38
+ const out: Problem[] = [];
39
+ const fail = (object: string, detail: string): void => { out.push({code:'REQUIREMENTS_FIELD', object, detail}); };
40
+ if (!Array.isArray(raw) || raw.length === 0) return [{code:'REQUIREMENTS_FIELD',object:at,detail:'requires a nonempty list of {part, joint, at, axis, reach_px, bend_degrees}; omit cut_material when undeclared'}];
41
+ const seen = new Set<string>();
42
+ raw.forEach((r, i) => {
43
+ const where = `${at}[${i}]`;
44
+ if (!obj(r)) { fail(where,'requires an object'); return; }
45
+ for (const k of Object.keys(r)) if (!['part','joint','at','axis','reach_px','bend_degrees'].includes(k)) fail(`${where}.${k}`,'is unknown; no guessed fields are read');
46
+ for (const k of ['part','joint']) if (typeof r[k] !== 'string' || r[k].trim() === '') fail(`${where}.${k}`,'requires a nonempty name');
47
+ for (const k of ['at','axis','bend_degrees']) if (!pair(r[k])) fail(`${where}.${k}`,'requires two finite numbers');
48
+ if (pair(r.axis) && (edgeLength(...r.axis) === 0 || !Number.isFinite(edgeLength(...r.axis)))) fail(`${where}.axis`,'requires a nonzero inward direction');
49
+ if (!num(r.reach_px) || r.reach_px <= 0) fail(`${where}.reach_px`,'requires a finite positive stage-pixel reach');
50
+ if (pair(r.bend_degrees) && (r.bend_degrees[0] > r.bend_degrees[1] || r.bend_degrees[0] < -180 || r.bend_degrees[1] > 180)) fail(`${where}.bend_degrees`,'requires an ordered interval inside [-180,180], in stage coordinates');
51
+ const key = JSON.stringify([r.part,r.joint]);
52
+ if (seen.has(key)) fail(where,'declares this part and joint twice');
53
+ seen.add(key);
54
+ });
55
+ return out;
56
+ }
57
+ const point = (a: Point, b: Point, t: number): Point => [a[0]+(b[0]-a[0])*t,a[1]+(b[1]-a[1])*t];
58
+ const unit = (p: Point): Point => { const d = edgeLength(...p); return [p[0]/d,p[1]/d]; };
59
+ const dot = (a: Point, b: Point): number => a[0]*b[0]+a[1]*b[1];
60
+ export function opaqueAt(arts: readonly PlacedArt[], x: number, y: number): boolean {
61
+ return arts.some(a => { const ix = Math.floor(x-a.x), iy = Math.floor(y-a.y); return ix >= 0 && iy >= 0 && ix < a.image.width && iy < a.image.height && a.image.data[(iy*a.image.width+ix)*4+3] > OPAQUE_ALPHA_ABOVE; });
62
+ }
63
+ /** Exact parameter breaks at pixel-cell boundaries, no spatial step or epsilon. */
64
+ function breaks(a: Point, b: Point, arts: readonly PlacedArt[]): number[] {
65
+ const ts = new Set([0,1]);
66
+ for (const r of arts) for (const k of [0,1] as const) {
67
+ const lo = k === 0 ? r.x : r.y, size = k === 0 ? r.image.width : r.image.height;
68
+ if (a[k] === b[k]) continue;
69
+ const start = Math.max(lo,Math.ceil(Math.min(a[k],b[k]))), end = Math.min(lo+size,Math.floor(Math.max(a[k],b[k])));
70
+ for (let v = start; v <= end; v++) { const t = (v-a[k])/(b[k]-a[k]); if (t > 0 && t < 1) ts.add(t); }
71
+ }
72
+ return [...ts].sort((x,y)=>x-y);
73
+ }
74
+ /** On a source pixel boundary the art must exist on both sides of the cut. */
75
+ function across(arts: readonly PlacedArt[], p: Point, n: Point): boolean {
76
+ const cell = (direction: number, k: 0|1): number => Number.isInteger(p[k]) && direction < 0 ? p[k]-0.5 : p[k];
77
+ return opaqueAt(arts,cell(n[0],0),cell(n[1],1)) && opaqueAt(arts,cell(-n[0],0),cell(-n[1],1));
78
+ }
79
+ export function polygonMaterialEdges(poly: readonly Point[]): MaterialEdge[] {
80
+ const area = poly.reduce((s,a,i)=>{ const b=poly[(i+1)%poly.length]; return s+a[0]*b[1]-a[1]*b[0]; },0);
81
+ return poly.flatMap((a,i)=>{const b=poly[(i+1)%poly.length],d=edgeLength(b[0]-a[0],b[1]-a[1]);return d===0?[]:[{a,b,inward:area>0?[-(b[1]-a[1])/d,(b[0]-a[0])/d] as Point:[(b[1]-a[1])/d,-(b[0]-a[0])/d] as Point}];});
82
+ }
83
+ /** Contiguous opaque cells from the joint plane outward. A hole ends support. */
84
+ function support(arts: readonly PlacedArt[], start: Point, n: Point): number {
85
+ const limit = arts.reduce((m,a)=>Math.max(m,edgeLength(a.x-start[0],a.y-start[1])+a.image.width+a.image.height),0);
86
+ if (limit === 0) return 0;
87
+ const end: Point = [start[0]-n[0]*limit,start[1]-n[1]*limit], ts=breaks(start,end,arts);
88
+ for(let i=0;i+1<ts.length;i++){ const p=point(start,end,(ts[i]+ts[i+1])/2);if(!opaqueAt(arts,...p))return ts[i]*limit; }
89
+ return limit;
90
+ }
91
+ /** max outward displacement of t*(-ny,nx), retained as a scalar instrument. */
92
+ export function bendDepth(t: number, degrees: Point): number {
93
+ const angles = [...degrees];
94
+ for (const a of [-90,90]) if (a >= degrees[0] && a <= degrees[1]) angles.push(a);
95
+ return Math.max(0,...angles.map(a=>t*Math.sin(a*Math.PI/180)));
96
+ }
97
+ /** Exact quadrant values avoid inventing support for sin(pi)'s roundoff. */
98
+ function trig(angle: number): [number, number] {
99
+ const q = angle / (Math.PI / 2);
100
+ if (Number.isInteger(q)) {
101
+ const k = ((q % 4) + 4) % 4;
102
+ return [[1,0],[0,1],[-1,0],[0,-1]][k] as [number, number];
103
+ }
104
+ return [Math.cos(angle), Math.sin(angle)];
105
+ }
106
+ /** Clip a convex polygon by a closed half-plane. No geometric tolerance. */
107
+ function clip(poly:Point[],inside:(p:Point)=>number):Point[]{
108
+ const out:Point[]=[];
109
+ for(let i=0;i<poly.length;i++){
110
+ const a=poly[i],b=poly[(i+1)%poly.length],fa=inside(a),fb=inside(b);
111
+ if(fa>=0)out.push(a);
112
+ if((fa<0&&fb>0)||(fa>0&&fb<0))out.push(point(a,b,fa/(fa-fb)));
113
+ }
114
+ return out;
115
+ }
116
+ function polygonArea(poly:Point[]):number{return Math.abs(poly.reduce((s,a,i)=>{const b=poly[(i+1)%poly.length];return s+a[0]*b[1]-a[1]*b[0];},0))/2;}
117
+ function convexHull(points:Point[]):Point[]{
118
+ const sorted=[...points].sort((a,b)=>a[0]-b[0]||a[1]-b[1]);
119
+ const turn=(a:Point,b:Point,c:Point):number=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
120
+ const half=(ps:Point[]):Point[]=>{const out:Point[]=[];for(const p of ps){while(out.length>=2&&turn(out[out.length-2],out[out.length-1],p)<=0)out.pop();out.push(p);}return out;};
121
+ return [...half(sorted).slice(0,-1),...half(sorted.reverse()).slice(0,-1)];
122
+ }
123
+ /** Empty exterior is four rectangles, so a distant declared joint never
124
+ * turns empty space into an unbounded pixel walk. Interior cells remain exact. */
125
+ function emptyRectangles(at:Point,radius:number,arts:readonly PlacedArt[]):Array<[number,number,number,number]>{
126
+ const x0=Math.floor(at[0]-radius),x1=Math.ceil(at[0]+radius),y0=Math.floor(at[1]-radius),y1=Math.ceil(at[1]+radius);
127
+ if(arts.length===0)return [[x0,y0,x1,y1]];
128
+ const left=Math.max(x0,Math.min(...arts.map(a=>a.x))),right=Math.min(x1,Math.max(...arts.map(a=>a.x+a.image.width))),top=Math.max(y0,Math.min(...arts.map(a=>a.y))),bottom=Math.min(y1,Math.max(...arts.map(a=>a.y+a.image.height)));
129
+ if(left>=right||top>=bottom)return [[x0,y0,x1,y1]];
130
+ const out:Array<[number,number,number,number]>=[];
131
+ for(const rect of [[x0,y0,x1,top],[x0,bottom,x1,y1],[x0,top,left,bottom],[right,top,x1,bottom]] as Array<[number,number,number,number]>)if(rect[0]<rect[2]&&rect[1]<rect[3])out.push(rect);
132
+ for(let y=top;y<bottom;y++)for(let x=left;x<right;x++)if(!opaqueAt(arts,x+0.5,y+0.5))out.push([x,y,x+1,y+1]);
133
+ return out;
134
+ }
135
+ /** The inverse rotation of a full point, with no joint-plane projection. */
136
+ function rotated(p:Point,angle:number):Point{const [c,s]=trig(angle);return [p[0]*c+p[1]*s,p[1]*c-p[0]*s];}
137
+ const cross=(a:Point,b:Point):number=>a[0]*b[1]-a[1]*b[0];
138
+ /**
139
+ * Segment-vs-convex-polygon intersection throughout an angle interval. Changes
140
+ * of incidence occur only when an endpoint crosses a polygon edge, the source
141
+ * line crosses a vertex, or an edge becomes parallel. All are sinusoid roots.
142
+ * One angle inside each resulting interval has the same intersection topology.
143
+ */
144
+ function sweptSegmentWitness(a:Point,b:Point,poly:Point[],degrees:Point):Point|null{
145
+ if(poly.length<3||polygonArea(poly)===0)return null;
146
+ const lo=degrees[0]*Math.PI/180,hi=degrees[1]*Math.PI/180,angles=new Set<number>([lo,hi]);
147
+ const add=(angle:number):void=>{if(angle>=lo&&angle<=hi)angles.add(angle);};
148
+ const roots=(A:number,B:number,C:number):void=>{
149
+ const radius=edgeLength(A,B);if(radius===0||Math.abs(C)>radius)return;
150
+ const phase=Math.atan2(B,A),offset=Math.acos(C/radius);
151
+ for(const k of [-1,0,1]){add(phase+offset+k*2*Math.PI);add(phase-offset+k*2*Math.PI);}
152
+ };
153
+ const delta:Point=[b[0]-a[0],b[1]-a[1]];
154
+ for(let i=0;i<poly.length;i++){
155
+ const p=poly[i],q=poly[(i+1)%poly.length],edge:Point=[q[0]-p[0],q[1]-p[1]],normal:Point=[-edge[1],edge[0]],C=dot(normal,p);
156
+ for(const endpoint of [a,b])roots(dot(normal,endpoint),normal[0]*endpoint[1]-normal[1]*endpoint[0],C);
157
+ roots(cross(delta,p),dot(delta,p),cross(delta,a));
158
+ roots(cross(delta,edge),dot(delta,edge),0);
159
+ }
160
+ const sorted=[...angles].sort((a,b)=>a-b),tests=[...sorted,...sorted.slice(1).map((v,i)=>(v+sorted[i])/2)];
161
+ for(const angle of tests){
162
+ const x=rotated(a,angle),y=rotated(b,angle);let low=0,high=1;
163
+ for(let i=0;i<poly.length;i++){
164
+ const p=poly[i],q=poly[(i+1)%poly.length],edge:Point=[q[0]-p[0],q[1]-p[1]],fa=cross(edge,[x[0]-p[0],x[1]-p[1]]),fb=cross(edge,[y[0]-p[0],y[1]-p[1]]);
165
+ if(fa<0&&fb<0){low=1;high=0;break;}
166
+ if(fa<0)low=Math.max(low,fa/(fa-fb));
167
+ if(fb<0)high=Math.min(high,fa/(fa-fb));
168
+ }
169
+ if(high<=low)continue;
170
+ const witness=point(x,y,(low+high)/2);
171
+ if(poly.every((p,i)=>{const q=poly[(i+1)%poly.length];return cross([q[0]-p[0],q[1]-p[1]],[witness[0]-p[0],witness[1]-p[1]])>0;}))return witness;
172
+ }
173
+ return null;
174
+ }
175
+ /** Entire actual edge segment, including normal offset from the joint. */
176
+ function sweptHole(a:Point,b:Point,n:Point,joint:JointMaterial,piece:readonly PlacedArt[]):{found:number;required:number;at:Point}|null{
177
+ const A:Point=[a[0]-joint.at[0],a[1]-joint.at[1]],B:Point=[b[0]-joint.at[0],b[1]-joint.at[1]],offset=dot(n,A),radius=Math.max(edgeLength(...A),edgeLength(...B));
178
+ // A normal ray starts on the actual edge plane, not the joint plane.
179
+ const bound=radius+Math.abs(offset);
180
+ for(const [x,y,right,bottom] of emptyRectangles(joint.at,bound,piece)){
181
+ const cell:Point[]=[[x-joint.at[0],y-joint.at[1]],[right-joint.at[0],y-joint.at[1]],[right-joint.at[0],bottom-joint.at[1]],[x-joint.at[0],bottom-joint.at[1]]];
182
+ const outward=clip(cell,p=>offset-dot(n,p));if(polygonArea(outward)===0)continue;
183
+ const distance=radius+Math.max(...outward.map(p=>edgeLength(...p)));
184
+ const shadow=convexHull([...outward,...outward.map<Point>(p=>[p[0]-n[0]*distance,p[1]-n[1]*distance])]);
185
+ const q=sweptSegmentWitness(A,B,shadow,joint.bend_degrees);if(q===null)continue;
186
+ const required=offset-dot(n,q);if(required<=0)continue;
187
+ const at:Point=[q[0]+joint.at[0],q[1]+joint.at[1]],start:Point=[at[0]+n[0]*required,at[1]+n[1]*required],found=support(piece,start,n);
188
+ if(found<required)return {found,required,at};
189
+ refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object:'swept source interval',detail:'a strict transparent-cell witness disagrees with its normal support reading; no PASS is inferred'}]);
190
+ }
191
+ return null;
192
+ }
193
+ export function materialRows(part: string, joint: JointMaterial | undefined, edges: readonly MaterialEdge[], source: readonly PlacedArt[], piece: readonly PlacedArt[]): MaterialRow[] {
194
+ return edges.map(edge=>{
195
+ const n=unit(edge.inward), d:Point=[edge.b[0]-edge.a[0],edge.b[1]-edge.a[1]], length=edgeLength(...d);
196
+ let lo=0,hi=1;
197
+ if(joint!==undefined){
198
+ const q:Point=[edge.a[0]-joint.at[0],edge.a[1]-joint.at[1]], A=dot(d,d), B=2*dot(q,d), C=dot(q,q)-joint.reach_px**2, disc=B*B-4*A*C;
199
+ if(A===0||disc<0){lo=1;hi=0;}else{lo=Math.max(0,(-B-Math.sqrt(disc))/(2*A));hi=Math.min(1,(-B+Math.sqrt(disc))/(2*A));}
200
+ }
201
+ if(!Number.isFinite(lo)||!Number.isFinite(hi)||!Number.isFinite(length))refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object:`part "${part}"`,detail:'joint/edge/reach arithmetic is not finite; supply representable measured stage coordinates and reach'}]);
202
+ let crossed=0,found=Infinity,required=0,rays=0,fail=false,margin=Infinity;
203
+ const spans=edge.opaque_t ?? opaqueParameters(edge,source);
204
+ const intervals=spans.map(([a,b]):[Point,Point]=>[point(edge.a,edge.b,a),point(edge.a,edge.b,b)]);
205
+ for(const interval of intervals){
206
+ // Preserve the source pixel-cell partition; clipping changes its endpoints only.
207
+ const param=(p:Point):number=>Math.abs(d[0])>=Math.abs(d[1])?(p[0]-edge.a[0])/d[0]:(p[1]-edge.a[1])/d[1];
208
+ const from=Math.max(lo,param(interval[0])),to=Math.min(hi,param(interval[1]));
209
+ if(to<=from)continue;
210
+ if(joint!==undefined){
211
+ const hole=sweptHole(point(edge.a,edge.b,from),point(edge.a,edge.b,to),n,joint,piece);
212
+ if(hole!==null){fail=true;if(hole.found-hole.required<margin){margin=hole.found-hole.required;found=hole.found;required=hole.required;}}
213
+ }
214
+ const p=point(edge.a,edge.b,(from+to)/2);
215
+ crossed+=(to-from)*length;rays++;
216
+ const at=joint?.at??p,tangent:Point=[-n[1],n[0]],t=dot([p[0]-at[0],p[1]-at[1]],tangent);
217
+ const offset=dot([p[0]-at[0],p[1]-at[1]],n);
218
+ const angles=joint===undefined?[0]:[...joint.bend_degrees].map(a=>a*Math.PI/180);
219
+ for(const angle of angles){
220
+ const [cos,sin]=trig(angle),s=t*cos-offset*sin,start:Point=[at[0]+s*tangent[0]+offset*n[0],at[1]+s*tangent[1]+offset*n[1]];
221
+ const r=joint===undefined?0:Math.max(0,offset*(1-cos)-t*sin),f=support(piece,start,n);
222
+ if(!Number.isFinite(f)||!Number.isFinite(r))refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object:`part "${part}"`,detail:'material support arithmetic is not finite; no PASS is inferred'}]);
223
+ if(f-r<margin || f-r===margin && r>required){margin=f-r;found=f;required=r;}
224
+ if(f<r)fail=true;
225
+ }
226
+ }
227
+ return {part,joint:joint?.joint??'(undeclared)',edge:[edge.a,edge.b],edge_length_px:intervals.reduce((s,[a,b])=>s+edgeLength(b[0]-a[0],b[1]-a[1]),0),within_reach_px:crossed,found_px:found===Infinity?0:found,required_px:required,rays,
228
+ status:joint===undefined||rays===0?'SKIP':fail?'FAIL':'PASS',...(joint===undefined?{reason:'no declared cut_material requirement; measured source support is not a pass'}:rays===0?{reason:'no opaque source crossing within declared joint reach'}:{})};
229
+ });
230
+ }
231
+ /** Original source intersections, represented as ordered bounded parameters. */
232
+ function opaqueParameters(edge:MaterialEdge,source:readonly PlacedArt[]):Array<[number,number]>{
233
+ const ts=breaks(edge.a,edge.b,source),out:Array<[number,number]>=[];
234
+ for(let i=0;i+1<ts.length;i++)if(across(source,point(edge.a,edge.b,(ts[i]+ts[i+1])/2),edge.inward))out.push([ts[i],ts[i+1]]);
235
+ return out;
236
+ }
237
+ /** Canonical unit perpendicular; the sign is the explicitly captured inward side. */
238
+ export function canonicalInward(a:Point,b:Point,inward:Point):Point{
239
+ const d:Point=[b[0]-a[0],b[1]-a[1]],length=edgeLength(...d),normal:Point=[-d[1]/length,d[0]/length];
240
+ return dot(normal,inward)>0?normal:[-normal[0],-normal[1]];
241
+ }
242
+ export function materialSource(part:string,from:string[],edges:readonly MaterialEdge[],source:readonly PlacedArt[]):MaterialSource{
243
+ return {part,from,source_sha256:source.map(s=>createHash('sha256').update(JSON.stringify([s.x,s.y,s.image.width,s.image.height])).update(s.image.data).digest('hex')),edges:edges.map(e=>{
244
+ const inward=canonicalInward(e.a,e.b,e.inward),opaque_t=opaqueParameters({...e,inward},source),length=edgeLength(e.b[0]-e.a[0],e.b[1]-e.a[1]);
245
+ return {a:e.a,b:e.b,inward,opaque_t,opaque_intervals:opaque_t.length,opaque_length_px:opaque_t.reduce((s,[a,b])=>s+(b-a)*length,0)};
246
+ }).filter(e=>e.opaque_t.length>0)};
247
+ }
248
+ export function checkJointMaterial(declarations: readonly JointMaterial[] | undefined, parts: PartsFile | null, image: (name:string)=>Raster, problems:Problem[],sources?:readonly MaterialSource[]): MaterialLine {
249
+ if(declarations===undefined)return {status:'SKIP',rows:[],reason:'no declared cut_material requirement'};
250
+ refuseIfAny(jointMaterialProblems(declarations,'cut_material'));
251
+ if(parts===null)refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object:'cut_material',detail:'requires parts.json and its emitted PNGs; missing art is not zero support'}]);
252
+ const rows:MaterialRow[]=[];
253
+ const records=(parts as PartsFile).parts;
254
+ const art=(name:string):PlacedArt=>{const p=records.find(p=>p.name===name);if(p===undefined)throw new Error(`missing resolved part ${name}`);return {x:p.x,y:p.y,image:image(name)};};
255
+ for(const req of declarations){
256
+ const p=records.find(p=>p.name===req.part),object=`part "${req.part}", joint "${req.joint}"`;
257
+ if(p===undefined||p.cut_from===undefined&&p.limb===undefined)refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'requires a named cut_from or limb segment provenance; nearest parts and inferred joints are not read'}]);
258
+ const rec=p!,limb=rec.limb;
259
+ const original=sources?.find(s=>s.part===req.part);
260
+ if(original===undefined)refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'original source edge readings are unavailable; emitted siblings cannot reconstruct discarded/overlapping source art — rerun assemble --requirements <file> (or build --requirements <file>) to write the source-bound sidecar'}]);
261
+ let piece=[art(rec.name)];
262
+ if(limb!==undefined){
263
+ if(limb.segment===0||limb.band!==undefined)refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'requires a lower limb segment, not segment0 or the generated band'}]);
264
+ const geometry=limb.cap??limb.hybrid;
265
+ if(limb.joint!==req.joint||geometry===undefined||geometry.at[0]!==req.at[0]||geometry.at[1]!==req.at[1])refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'declared joint name/at must equal the recorded lower joint centre; correct the explicit correspondence'}]);
266
+ if(limb.hybrid!==undefined)piece=[...piece,art(limb.hybrid.part)];
267
+ }
268
+ const candidates=(original as MaterialSource).edges.filter(e=>(e.opaque_t??[]).some(([lo,hi])=>{
269
+ const a=point(e.a,e.b,lo),b=point(e.a,e.b,hi),d:Point=[b[0]-a[0],b[1]-a[1]],q:Point=[req.at[0]-a[0],req.at[1]-a[1]],t=Math.max(0,Math.min(1,dot(q,d)/dot(d,d))),closest=point(a,b,t);return edgeLength(closest[0]-req.at[0],closest[1]-req.at[1])<=req.reach_px;
270
+ }));
271
+ if(candidates.length>0&&!candidates.some(e=>{
272
+ const d:Point=[e.b[0]-e.a[0],e.b[1]-e.a[1]],perpendicular=dot(d,req.axis),side=cross(d,req.axis),captured=cross(d,e.inward),sameCanonical=cross(e.inward,req.axis);
273
+ if(!Number.isFinite(perpendicular)||!Number.isFinite(side)||!Number.isFinite(captured)||!Number.isFinite(sameCanonical))refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'edge/axis orientation arithmetic is not finite; supply a representable scalar multiple of the measured inward direction'}]);
274
+ return (perpendicular===0||sameCanonical===0)&&side!==0&&Math.sign(side)===Math.sign(captured);
275
+ }))refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'declared axis matches no original opaque edge inward within reach; correct the explicit edge/joint correspondence'}]);
276
+ const read=materialRows(req.part,req,(original as MaterialSource).edges,[],piece);
277
+ if(read.every(r=>r.rays===0))refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object,detail:'no opaque cut interface within declared reach; correct the explicit joint correspondence/reach or supply source material; no PASS is invented'}]);
278
+ for(const r of read.filter(r=>r.rays>0)){
279
+ rows.push(r);
280
+ if(r.status==='FAIL')problems.push({code:'CHECK_CUT_JOINT_MATERIAL',object,detail:`edge [${r.edge.map(p=>p.join(',')).join(' -> ')}], opaque edge length ${r.edge_length_px} px (${r.within_reach_px} px within reach): material found ${r.found_px} px, required ${r.required_px} px by bend [${req.bend_degrees.join(', ')}] degrees within reach ${req.reach_px} px; source art past the joint is required — follow AUTHORING Source before scissors; no crop or under-piece repair`});
281
+ }
282
+ }
283
+ return {status:rows.some(r=>r.status==='FAIL')?'FAIL':'PASS',rows};
284
+ }
285
+ export function materialLines(line:MaterialLine):string[]{return [`${CUT_MATERIAL_LINE}: ${line.status}${line.reason===undefined?'':` — ${line.reason}`}`,...line.rows.map(r=>`${CUT_MATERIAL_LINE}: part "${r.part}", joint "${r.joint}", edge [${r.edge.map(p=>p.join(',')).join(' -> ')}]: ${r.status}; opaque edge length ${r.edge_length_px} px; material found ${r.found_px} px, required ${r.required_px} px (${r.rays} source rays; continuous inverse-rotation arc)`)];}
@@ -0,0 +1,63 @@
1
+ /** Optional source-bound assembly evidence, absent on undeclared builds. */
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { edgeLength } from './length.ts';
6
+ import { canonicalInward, CUT_MATERIAL_SOURCES, CUT_MATERIAL_SPEC, type MaterialSource, type Point } from './cutmaterial.ts';
7
+ import type { PartsFile } from './parts.ts';
8
+ import { refuseIfAny } from './errors.ts';
9
+ const sha=(data:Uint8Array|string):string=>createHash('sha256').update(data).digest('hex');
10
+ const hash=(path:string):string=>sha(readFileSync(path));
11
+ const record=(v:unknown):v is Record<string,unknown>=>typeof v==='object'&&v!==null&&!Array.isArray(v);
12
+ const digest=(v:unknown):v is string=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
13
+ const point=(v:unknown):v is Point=>Array.isArray(v)&&v.length===2&&v.every(x=>typeof x==='number'&&Number.isFinite(x));
14
+ export function writeMaterialSources(partsPath:string,partsDir:string,parts:PartsFile,sources:readonly MaterialSource[]):void{
15
+ const emitted=sources.filter(s=>parts.parts.some(p=>p.name===s.part));
16
+ writeFileSync(join(dirname(partsPath),CUT_MATERIAL_SOURCES),JSON.stringify({
17
+ spec:CUT_MATERIAL_SPEC,parts_sha256:hash(partsPath),
18
+ images:parts.parts.map(p=>({part:p.name,sha256:hash(join(partsDir,`${p.name}.png`))})),
19
+ sources_sha256:sha(JSON.stringify(emitted)),sources:emitted,
20
+ },null,2)+'\n');
21
+ }
22
+ export function readMaterialSources(home:string,parts:PartsFile):MaterialSource[]{
23
+ const path=join(home,CUT_MATERIAL_SOURCES);
24
+ const fail=(detail:string):never=>{refuseIfAny([{code:'CHECK_CUT_MATERIAL_MEASURED',object:path,detail:`${detail}; rerun assemble --requirements <file> or build --requirements <file>; emitted siblings are not original source evidence`}]);throw new Error('unreachable');};
25
+ if(!existsSync(path))return fail('original source-edge sidecar is unavailable');
26
+ let raw:unknown;
27
+ try{raw=JSON.parse(readFileSync(path,'utf8'));}catch{return fail('source-edge sidecar is not JSON');}
28
+ if(!record(raw)||raw.spec!==CUT_MATERIAL_SPEC||!Array.isArray(raw.images)||!Array.isArray(raw.sources))return fail(`requires ${CUT_MATERIAL_SPEC}, images and sources`);
29
+ if(Object.keys(raw).some(k=>!['spec','parts_sha256','images','sources_sha256','sources'].includes(k)))return fail('source sidecar has an unknown field');
30
+ if(raw.parts_sha256!==hash(join(home,'parts.json')))return fail('source-edge sidecar does not bind these parts.json bytes');
31
+ if(!digest(raw.sources_sha256)||raw.sources_sha256!==sha(JSON.stringify(raw.sources)))return fail('original source-edge payload digest differs; intervals/edges must not be removed or rewritten');
32
+ if(raw.images.length!==parts.parts.length)return fail('image bindings do not cover every emitted base part');
33
+ const seen=new Set<string>();
34
+ for(const binding of raw.images){
35
+ if(!record(binding)||typeof binding.part!=='string'||!digest(binding.sha256)||seen.has(binding.part)||!parts.parts.some(p=>p.name===binding.part))return fail('image bindings require each named base part exactly once and its SHA-256');
36
+ if(Object.keys(binding).some(k=>!['part','sha256'].includes(k)))return fail('image binding has an unknown field');
37
+ seen.add(binding.part);
38
+ const file=join(home,'parts',`${binding.part}.png`);
39
+ if(!existsSync(file)||hash(file)!==binding.sha256)return fail(`source-edge binding for part "${binding.part}" differs from its emitted PNG`);
40
+ }
41
+ const sources=new Set<string>();
42
+ for(const s of raw.sources){
43
+ if(!record(s)||typeof s.part!=='string'||sources.has(s.part)||!parts.parts.some(p=>p.name===s.part)||!Array.isArray(s.from)||s.from.length===0||!s.from.every(f=>typeof f==='string'&&f.length>0)||!Array.isArray(s.source_sha256)||s.source_sha256.length!==s.from.length||!s.source_sha256.every(digest)||!Array.isArray(s.edges))return fail('source readings require unique emitted parts, source labels/digests and edges');
44
+ if(Object.keys(s).some(k=>!['part','from','source_sha256','edges'].includes(k)))return fail('source reading has an unknown field');
45
+ sources.add(s.part);
46
+ for(const edge of s.edges){
47
+ if(!record(edge)||!point(edge.a)||!point(edge.b)||!point(edge.inward)||!Array.isArray(edge.opaque_t))return fail('edge readings require finite a, b, inward and bounded original opaque_t parameters');
48
+ if(Object.keys(edge).some(k=>!['a','b','inward','opaque_t','opaque_intervals','opaque_length_px'].includes(k)))return fail('edge reading has an unknown field; absolute opaque endpoints are not this format');
49
+ const a=edge.a,b=edge.b,n=edge.inward,length=edgeLength(b[0]-a[0],b[1]-a[1]);
50
+ if(!Number.isFinite(length)||length===0||edgeLength(...n)===0)return fail('source edge or its inward direction has zero/unrepresentable length');
51
+ const canonical=canonicalInward(a,b,n);
52
+ if(n[0]!==canonical[0]||n[1]!==canonical[1])return fail('inward must be the canonical unit perpendicular to the actual edge; no oblique inward is supported');
53
+ if(edge.opaque_t.length===0)return fail('listed source edges must have opaque intervals; an empty list may not hide an originally crossed edge');
54
+ let previous=0,total=0;
55
+ for(const span of edge.opaque_t){
56
+ if(!point(span)||span[0]<0||span[1]>1||span[0]>=span[1]||span[0]<previous)return fail('opaque_t intervals must be ordered, nonoverlapping, positive, and inside [0,1] on this actual edge');
57
+ previous=span[1];total+=(span[1]-span[0])*length;
58
+ }
59
+ if(edge.opaque_intervals!==edge.opaque_t.length||edge.opaque_length_px!==total)return fail('opaque interval count/length disagree with the original source-edge census');
60
+ }
61
+ }
62
+ return raw.sources as unknown as MaterialSource[];
63
+ }