@rig-c/parts 1.83.2 → 1.85.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/build.ts CHANGED
@@ -1,3 +1,7 @@
1
+ import { SETUP_PAINTING_LINE, setupPaintingLines } from './setuppainting.ts';
2
+ import { writeMaterialSources } from './cutmaterialio.ts';
3
+ import { CUT_MATERIAL_LINE, CUT_MATERIAL_SOURCES, materialLines } from './cutmaterial.ts';
4
+ import { ART_JOINT_LINE, artJointLines } from './artjoints.ts';
1
5
  import { applyTakenLayers } from './takelayers.ts';
2
6
  import { ownershipLines, provenanceLines } from './provenance.ts';
3
7
  import { readSourceDepth } from './depthsheets.ts';
@@ -153,6 +157,8 @@ export interface AlternateCliInput {
153
157
  }
154
158
 
155
159
  export interface AssembleStageInput {
160
+ /** Write source-edge evidence only when cut_material is explicitly declared. */
161
+ requirements?: string;
156
162
  source: string;
157
163
  full: string;
158
164
  /** The head run, or null for one run that holds the face (issue #359). */
@@ -317,6 +323,7 @@ export function frontOrdered<T extends { record: { name: string } }>(items: read
317
323
 
318
324
  /** Read, assemble, and write only after every refusal has had its chance. Throws a PartsError on a refusal, having written nothing. */
319
325
  export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs, log: Log): AssembleResult {
326
+ const materialAsked = input.requirements === undefined ? false : readRequirements(input.requirements).cut_material !== undefined;
320
327
  // The early door: assemble runs before propose has drafted bones, meshes,
321
328
  // regions and motion, so it requires only what it reads (issue #20).
322
329
  const cfg = loadEarlyConfig(input.config, 'assemble');
@@ -771,6 +778,8 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
771
778
  for (const b of altBuilt) {
772
779
  for (const { name, image } of b.images) writePng(join(outs.partsDir, `${name}.png`), image);
773
780
  }
781
+ if (materialAsked) writeMaterialSources(outs.partsJson, outs.partsDir, result.parts, result.materialSources);
782
+ else rmSync(join(dirname(outs.partsJson), CUT_MATERIAL_SOURCES), { force: true });
774
783
  writePng(outs.recomposite, result.recomposite);
775
784
  writePng(outs.errorMap, result.errorMap);
776
785
  // Issue #242: under config.scene, the figure the recomposite was read inside, beside the recomposite.
@@ -798,6 +807,7 @@ export function assembleStage(input: AssembleStageInput, outs: AssembleOutputs,
798
807
  for (const l of authorPartLines(result.parts.parts)) log(l);
799
808
  // One line per plan part an assemble.cuts entry cut, before the fringe lines: the cut is made first. None without cuts.
800
809
  for (const l of cutLines(result.cuts)) log(l);
810
+ if (materialAsked) for (const line of materialLines({ status: 'SKIP', rows: result.cutMaterial, reason: 'assemble source readings only; check --requirements judges declared joint material' })) log(` ${line}`);
801
811
  // Issue #349: one line per part a limb took, and one per joint with its cap's pixels. None without limbs.
802
812
  for (const l of limbLines(result.limbs)) log(l);
803
813
  for (const l of fringeLines(result.parts.parts)) log(l);
@@ -1941,6 +1951,12 @@ export function checkStage(input: CheckStageInput, rigc: RigcRunner, bin: string
1941
1951
  if (vsSource !== undefined) log(` ${judgementLine(SOURCE_LINE, vsSource)}`);
1942
1952
  const windBand = fig[WIND_BAND_LINE];
1943
1953
  if (windBand !== undefined) for (const l of windBandLines(windBand)) log(` ${l}`);
1954
+ const cutMaterial = fig[CUT_MATERIAL_LINE];
1955
+ if (cutMaterial !== undefined) for (const line of materialLines(cutMaterial)) log(` ${line}`);
1956
+ const artJoints = fig[ART_JOINT_LINE];
1957
+ if (artJoints !== undefined) for (const line of artJointLines(artJoints)) log(` ${line}`);
1958
+ const setupPainting = fig[SETUP_PAINTING_LINE];
1959
+ if (setupPainting !== undefined) for (const line of setupPaintingLines(setupPainting)) log(` ${line}`);
1944
1960
  if (r.requirements !== null) {
1945
1961
  for (const [name, line] of Object.entries(r.requirements.lines)) log(` ${requirementText(name, line)}`);
1946
1962
  log(` ${summaryText(r.requirements.summary)}`);
@@ -2385,6 +2401,8 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2385
2401
  const out = input.out;
2386
2402
  mkdirSync(out, { recursive: true });
2387
2403
  for (const p of BUILD_OWNS) rmSync(join(out, p), { recursive: true, force: true });
2404
+ // Optional source evidence is cleared separately; BUILD_OWNS is the legacy complete output tree.
2405
+ rmSync(join(out, CUT_MATERIAL_SOURCES), { force: true });
2388
2406
  // Issue #242: the figure mask is written only under config.scene; one left by an earlier scene build is not this build's.
2389
2407
  rmSync(join(out, FIGURE_MASK_FILE), { force: true });
2390
2408
  // The idle-keys value is named only when it is not the default, so a build without the flag, or with the default, prints the line it printed before issue #95.
@@ -2410,7 +2428,7 @@ export function build(input: BuildInput, run: BuildRunners, log: Log): BuildResu
2410
2428
  // And the steady-wind band spec (issue #590), as check reads it.
2411
2429
  if (input.windBand !== undefined) readWindBand(input.windBand);
2412
2430
  stages.assemble(
2413
- { source: input.source, full: input.full, head: input.head, config: input.config, seam: input.seam, project: input.project, ...(input.alts === undefined ? {} : { alts: input.alts }) },
2431
+ { source: input.source, full: input.full, head: input.head, config: input.config, seam: input.seam, project: input.project, ...(req === null ? {} : { requirements: req.read }), ...(input.alts === undefined ? {} : { alts: input.alts }) },
2414
2432
  { partsJson: join(out, 'parts.json'), partsDir: join(out, 'parts'), recomposite: join(out, 'recomposite_rig.png'), errorMap: join(out, ERROR_MAP_FILE) },
2415
2433
  prefixed('assemble'),
2416
2434
  );
package/src/check.ts CHANGED
@@ -1,3 +1,7 @@
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';
4
+ import { ART_JOINT_LINE, artJointLine, type ArtJointLine } from './artjoints.ts';
1
5
  import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
2
6
  /**
3
7
  * The check stage: build a rig through rig-c, gate it under both
@@ -84,7 +88,7 @@ import { createRequire } from 'node:module';
84
88
  import type { Viewport as RootCoverageViewport } from '@rig-c/core/render-shared';
85
89
  import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
86
90
  import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
87
- import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
91
+ import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig, figureSilhouette } from './assemble.ts';
88
92
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toBoneLocal } from './coords.ts';
89
93
  import { capBox, inDisc } from './limbs.ts';
90
94
  import { motionSeamProblems } from './motionseams.ts';
@@ -1930,6 +1934,35 @@ function officialRenderer(): OfficialRenderer {
1930
1934
  return require('@rig-c/core/render-shared') as OfficialRenderer;
1931
1935
  }
1932
1936
 
1937
+ /** Observe the actual setup on the declared stage grid. No frame-zero motion,
1938
+ * fitted alignment, flat recomposite or duplicate core validation. */
1939
+ export function measureSetupPainting(build: string, stage: StageBox, source: Raster, declared: SetupPainting, problems: Problem[]): SetupPaintingLine {
1940
+ const api = officialRenderer();
1941
+ const skeleton = join(build, 'skeleton.json'), atlas = join(build, 'skeleton.atlas');
1942
+ const candidate = api.loadCandidate({ skeletonText: readFileSync(skeleton, 'utf8'), atlasText: readFileSync(atlas, 'utf8'), atlasDir: build, label: 'setup versus painting' }, { skeleton, atlas }, undefined);
1943
+ const pose = api.throughPoser(candidate.choice, p => api.sampleSetupPose(p, { geometry: true, texture: true })).value[0];
1944
+ if (pose === undefined || pose.pieces.some(p => 'source' in p)) {
1945
+ 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' }]);
1946
+ }
1947
+ const W = stage.width, H = stage.height;
1948
+ 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' }]);
1949
+ const vp = { minX: stage.x, minY: stage.y, maxX: stage.x + W, maxY: stage.y + H, scale: 1, width: W, height: H };
1950
+ const project = api.projector(vp), owners = new Int32Array(W * H).fill(-1);
1951
+ 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; }));
1952
+ // sourceInRig intentionally reads opaque RGB, discarding source alpha before
1953
+ // resizing. This optional comparison declares source-over white instead:
1954
+ // flatten at ORIGINAL source resolution first, so hidden RGB cannot reach
1955
+ // Lanczos taps or the figure silhouette. Do not change the legacy helper.
1956
+ const whiteSource = newRaster(source.width, source.height);
1957
+ for (let p = 0; p < source.width * source.height; p++) {
1958
+ 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));
1959
+ whiteSource.data[p * 4 + 3] = 255;
1960
+ }
1961
+ const painting = sourceInRig(whiteSource, W, H);
1962
+ const setup = api.renderFrame(pose, candidate.pages, vp, [0, 0, 0, 0]);
1963
+ return setupPaintingLine(declared, painting, { width: W, height: H, data: new Uint8ClampedArray(setup.data) }, figureSilhouette(painting).data, owners, pose.pieces.map(p => p.slot), problems);
1964
+ }
1965
+
1933
1966
  /** One decoder/poser lifetime per state; retain only finite bounds and identities, never atlas pages or rasters. */
1934
1967
  export function seamStateBounds(build: string, state: string): SeamStateBounds {
1935
1968
  try {
@@ -2694,6 +2727,11 @@ export interface CheckFigures {
2694
2727
  config?: InputFileRecord;
2695
2728
  /** Written only under `--requirements` (issue #93): the file's fps, the summary, and one line per declared requirement, by name. */
2696
2729
  requirements?: RequirementsBlock;
2730
+ /** Issue #880: only when requirements declares fixed_skeleton. */
2731
+ [ART_JOINT_LINE]?: ArtJointLine;
2732
+ /** Only when setup_painting is explicitly declared. */
2733
+ [SETUP_PAINTING_LINE]?: SetupPaintingLine;
2734
+ [CUT_MATERIAL_LINE]?: MaterialLine;
2697
2735
  PASS: boolean;
2698
2736
  }
2699
2737
 
@@ -2940,7 +2978,7 @@ export function barsNotMet(fig: Readonly<Record<string, unknown>>): string[] {
2940
2978
  isRecord(fig.sets) &&
2941
2979
  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));
2942
2980
  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');
2943
- for (const n of [...JUDGEMENT_LINES, FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE]) {
2981
+ for (const n of [...JUDGEMENT_LINES, FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, ART_JOINT_LINE, CUT_MATERIAL_LINE]) {
2944
2982
  const l = fig[n];
2945
2983
  if (typeof l === 'object' && l !== null && (l as { status?: unknown }).status === 'FAIL') out.push(n);
2946
2984
  }
@@ -3049,7 +3087,7 @@ export function checkStatuses(fig: CheckFigures): Record<string, CheckStatus> {
3049
3087
  const bar = (name: string, measured: boolean): CheckStatus => (!measured ? 'SKIP' : notMet.includes(name) ? 'FAIL' : 'PASS');
3050
3088
  const out: Record<string, CheckStatus> = { gate: bar('gate', true), loop: bar('loop', fig.loop_max_diff !== null), seam: bar('seam', fig.seam_mean !== null) };
3051
3089
  for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
3052
- 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] as const) {
3090
+ 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) {
3053
3091
  const l = fig[n];
3054
3092
  if (l !== undefined) out[n] = l.status;
3055
3093
  }
@@ -5859,6 +5897,10 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5859
5897
  const file = reqFile as RequirementsFile;
5860
5898
  const ready = inp;
5861
5899
  take(() => resolveRequirements(file, ready.rig, ready.motion, ready.rootBone));
5900
+ if (file.setup_painting !== undefined) take(() => {
5901
+ refuseIfAny(setupPaintingBounds(file.setup_painting as SetupPainting, ready.stage.width, ready.stage.height));
5902
+ 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' }]);
5903
+ });
5862
5904
  take(() => refuseIfAny(exceptionProblems(file, ready.parts, ready.noParts)));
5863
5905
  // A seam's pairs are read off parts.json's art (issue #111); both resolvers' problems are named in one refusal.
5864
5906
  if (file.requirements.some((r) => r.kind === 'seam')) {
@@ -5876,6 +5918,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
5876
5918
  if (env !== null && !(isRecord(inp.motion.animations) && Object.keys(inp.motion.animations).length > 0)) {
5877
5919
  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`);
5878
5920
  }
5921
+ // Read source support before rendering; no output/sidecar for undeclared builds.
5922
+ 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'}]);
5923
+ const cutMaterialProblems: Problem[] = [];
5924
+ 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));
5925
+ // A measured material failure is a check bar; unavailable data is a refusal.
5879
5926
  const rigcEntry = readRigcEntry(requireRigcVersion(rigc));
5880
5927
  /**
5881
5928
  * Issue #538: a render whose frames a bar or a warning reads, with the physics on — posed under the schedule when
@@ -6402,7 +6449,10 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6402
6449
  const setsFigures: Record<string, SetCheckFigures> = {};
6403
6450
  // Issue #671: a failing set's hint, read with its seam; never written to check.json.
6404
6451
  const setHints = new Map<string, string>();
6405
- if (inp.parts !== null || inp.source !== null) {
6452
+ const fixedSkeleton = reqFile?.fixed_skeleton;
6453
+ let artJoints: ArtJointLine | null = null;
6454
+ let setupPainting: SetupPaintingLine | null = null;
6455
+ if (inp.parts !== null || inp.source !== null || fixedSkeleton !== undefined) {
6406
6456
  try {
6407
6457
  mkdirSync(stillDir, { recursive: true });
6408
6458
  const images = typeof inp.rig.images === 'string' ? resolve(inp.rigDir, inp.rig.images) : inp.rig.images;
@@ -6426,9 +6476,19 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6426
6476
  if (sb.status !== 0) refuseIfAny(rigcFailed('build (the setup-pose still)', sb, buildGateLines(sb.out)));
6427
6477
  // The stage is the parts' canvas wherever parts.json is read (CHECK_RIG_STAGE_IS_THE_CANVAS), so this is its longest side.
6428
6478
  const maxSide = Math.ceil(Math.max(inp.stage.width, inp.stage.height));
6429
- const sr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), '--out', join(stillDir, 'render')]);
6479
+ const sr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), ...(fixedSkeleton === undefined ? [] : ['--geometry']), '--out', join(stillDir, 'render')]);
6430
6480
  if (sr.status !== 0) refuseIfAny(rigcFailed('render (the setup-pose still)', sr, sr.out.split('\n').filter((l) => l.includes('FAIL'))));
6431
6481
  const stillSet = readFrameSet(join(stillDir, 'render'));
6482
+ if (reqFile?.setup_painting !== undefined && inp.source !== null) setupPainting = measureSetupPainting(join(stillDir, 'build'), inp.stage, inp.source.painting, reqFile.setup_painting, problems);
6483
+ if (fixedSkeleton !== undefined) {
6484
+ const geometryPath = join(stillSet.dir, GEOMETRY_FILE);
6485
+ const geometry = readGeometry(geometryPath, stillSet.written);
6486
+ artJoints = artJointLine(fixedSkeleton, inp.stage, bone => {
6487
+ const track = boneTrackOf(geometry, geometryPath, stillSet, bone);
6488
+ if (typeof track === 'string') return geometryProblem(geometryPath, track);
6489
+ return track.setup;
6490
+ }, problems);
6491
+ }
6432
6492
  seamViewport = stillSet.viewport;
6433
6493
  if (keepStills) cpSync(join(stillDir, 'render'), inp.parts === null ? keptDir : join(out, 'setup_still_auto'), { recursive: true });
6434
6494
  if (inp.parts !== null) {
@@ -6621,6 +6681,9 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6621
6681
  ...(Object.keys(skipped).length === 0 ? {} : { skipped }),
6622
6682
  ...(Object.keys(setsFigures).length === 0 ? {} : { sets: setsFigures }),
6623
6683
  ...(config === undefined ? {} : { config }),
6684
+ ...(artJoints === null ? {} : { [ART_JOINT_LINE]: artJoints }),
6685
+ ...(setupPainting === null ? {} : { [SETUP_PAINTING_LINE]: setupPainting }),
6686
+ ...(cutMaterial === null ? {} : { [CUT_MATERIAL_LINE]: cutMaterial }),
6624
6687
  ...(reqBlock === null ? {} : { requirements: reqBlock }),
6625
6688
  PASS: false,
6626
6689
  };
@@ -6664,7 +6727,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6664
6727
  const rank = (q: Problem): number => JUDGEMENT_LINES.findIndex((n) => q.code === `CHECK_${n}`);
6665
6728
  problems.sort((a, b) => rank(a) - rank(b));
6666
6729
  problems.unshift(...barProblems);
6667
- problems.push(...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
6730
+ problems.push(...cutMaterialProblems, ...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
6668
6731
  figures.PASS = problems.length === 0;
6669
6732
  const publishCheck = (): void => write('check.json', `${JSON.stringify(figures, null, 1)}\n`);
6670
6733
  if (motionSeam.worlds === undefined) publishCheck();
@@ -6684,6 +6747,9 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6684
6747
  }
6685
6748
  // Issues #320, #333: the fold bar is counted where it is written — on every rig whose motion holds an animation.
6686
6749
  if (folds !== null) tally(FOLD_LINE, null);
6750
+ if (cutMaterial !== null) tally(CUT_MATERIAL_LINE, null);
6751
+ if (artJoints !== null) tally(ART_JOINT_LINE, artJoints.status === 'SKIP' ? (artJoints.reason ?? 'no declared limit') : null);
6752
+ if (setupPainting !== null) tally(SETUP_PAINTING_LINE, setupPainting.status === 'SKIP' ? (setupPainting.reason ?? 'no declared limit') : null);
6687
6753
  // Issue #348: the level bar where it is written; a line whose every foot no frame posed says SKIP and is not measured.
6688
6754
  if (level !== null) tally(LEVEL_LINE, level.status === 'SKIP' ? (level.reason ?? '') : null);
6689
6755
  // 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
+ }