@rig-c/parts 1.65.0 → 1.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/assemble.ts CHANGED
@@ -102,8 +102,9 @@
102
102
  import { sourceLimbTarget, nearestTargetPart } from './limbownership.ts';
103
103
  import { type ArmSplit, type BoneEntry, type CharacterConfig, type ControlSkeleton, controlSkeletonOf, type Cut, type EarlyConfig, type Extend, type Limb, type Patch, type PlanEntry, type Run, type SeeThrough } from './config.ts';
104
104
  import { type Problem, refuseIfAny } from './errors.ts';
105
- import { figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
105
+ import { CORE_ALPHA, figuresPhrase, implausibleRules, type Layer, type LayerFigures, layerFigures, type LayerSet, NEAR_WHITE_MIN, OPAQUE_ALPHA_ABOVE, ruleSummary } from './layers.ts';
106
106
  import { padToSquare, squarePad } from './inputs.ts';
107
+ import type { MotionSeamDeclaration } from './motionseams.ts';
107
108
  import { type CapRecord, type LimbRecord, PAINTING_RUN, type PartRecord, type PartsFile, type RecompositeRecord, type SceneRecord, type SingleRunPad } from './parts.ts';
108
109
  import { assignCrossedLimbs, assignOverlappingHands, type BonePlace, bonePlaces, capBox, coveredRadius, type CutPlacement, featherWeight, halfWidthAbout, inDisc, jointLine, type JointLine, jointOffsets, limbPolyline, limbRun, luma601, nearestLimb, nearestOnLine, offLineFigure, pastJoint, placeCut, polylineDist2, segmentOf } from './limbs.ts';
109
110
  import {
@@ -133,8 +134,6 @@ const f32 = Math.fround;
133
134
  // the reference's constants, each named once
134
135
  // ---------------------------------------------------------------------------
135
136
 
136
- /** Alpha at or above this is "opaque" for ownership, projection cores and the seam override. `>= 250`, not `== 255`: See-through leaves alpha-254 speckle. */
137
- export const CORE_ALPHA = 250;
138
137
  /** A ghost component is kept when its area is at least this many pixels … */
139
138
  export const GHOST_MIN_AREA = 40;
140
139
  /** … and at least this fraction of the layer's largest component. */
@@ -160,7 +159,7 @@ export const CROP_PROBE_ALPHA = 128;
160
159
  /** Alpha at or above this in a later plan part keeps `growRim`'s ring off the pixel. */
161
160
  export const FRONT_ALPHA = 128;
162
161
  /** A painting pixel whose min channel is above this is "near-white" (the faithful rim and seam guard). Defined beside the layer reader, which applies the same test to a layer's colour (`layerFigures`). */
163
- export { NEAR_WHITE_MIN };
162
+ export { CORE_ALPHA, NEAR_WHITE_MIN };
164
163
  /** The seam override acts where the flat composite differs from the painting by more than this, max channel. */
165
164
  export const SEAM_LIMIT = 60;
166
165
  /** `--propose-plan` drops a tag with fewer run-space opaque pixels than this after ghost clean-up. */
@@ -322,6 +321,7 @@ export interface AssembleInput {
322
321
  patches: Patch[];
323
322
  /** `assemble.cuts`: plan parts' pixels taken into new parts by polygon (`cutPart`), placed per their `draw`. */
324
323
  cuts: Cut[];
324
+ motion_seams?: MotionSeamDeclaration[];
325
325
  /** Internal alternate selection: piece layer by cut output; polygon subtraction and under stay on from. */
326
326
  cutLayers?: ReadonlyMap<string, string>;
327
327
  /**
@@ -5107,6 +5107,7 @@ export function assemble(input: AssembleInput): AssembleResult {
5107
5107
  parts: {
5108
5108
  rig_size: [W, H],
5109
5109
  scale_rig_per_source: frame.S,
5110
+ ...(input.motion_seams === undefined ? {} : { motion_seams: input.motion_seams.map(({ part, neighbour }) => ({ part, neighbour })) }),
5110
5111
  parts: placed.map((p) => p.record),
5111
5112
  ghost_px: ghost,
5112
5113
  recomposite: recompositeRecord(figures),
@@ -5214,7 +5215,13 @@ export function driftBodies(part: string, from: string, refused: Mask, minPx: nu
5214
5215
  * `drift: "topwear" refuses 196 px of full:topwear (its colour more than 90
5215
5216
  * off the painting, max channel), in a body of 196 px at 16,12 14x14 (at
5216
5217
  * least 150 px past a 5x5 opening); by the plan's draw order "face" holds 196
5217
- * px of it (the top-most part at alpha >= 250), drawn in front of "topwear"`.
5218
+ * px of it (the top-most part at alpha >= 250), "face" drawn in front of
5219
+ * "topwear"; informational: no gate reads this. Swapping the plan order of the
5220
+ * parts named here can clear it (when only the front one differs from the
5221
+ * painting) or move it to the other part (when both do): swap, rebuild and read
5222
+ * this line again; if it moves, removing it needs different input layers. At
5223
+ * rest, the seam pass repaints the holder's pixels that pass its rule from the
5224
+ * painting`.
5218
5225
  * When `behind` is non-empty (issue #351), names the part(s) drawn behind
5219
5226
  * `part` whose colour is within `DRIFT_LIMIT` of the painting.
5220
5227
  */
@@ -5230,7 +5237,8 @@ export function driftLine(d: DriftBodies): string {
5230
5237
  : '';
5231
5238
  return (
5232
5239
  `drift: "${d.part}" refuses ${d.refusedPx} px of ${d.from} (its colour more than ${DRIFT_LIMIT} off the painting, max channel), in ${held} (at least ${fmtPx(d.minPx)} px past a ${BODY_KERNEL}x${BODY_KERNEL} opening); ` +
5233
- `by the plan's draw order ${d.holders.map((h) => `"${h.part}" holds ${h.px} px`).join(', ')} of it (the top-most part at alpha >= ${CORE_ALPHA})${frontClause}${behindClause}`
5240
+ `by the plan's draw order ${d.holders.map((h) => `"${h.part}" holds ${h.px} px`).join(', ')} of it (the top-most part at alpha >= ${CORE_ALPHA})${frontClause}${behindClause}; ` +
5241
+ "informational: no gate reads this. Swapping the plan order of the parts named here can clear it (when only the front one differs from the painting) or move it to the other part (when both do): swap, rebuild and read this line again; if it moves, removing it needs different input layers. At rest, the seam pass repaints the holder's pixels that pass its rule from the painting"
5234
5242
  );
5235
5243
  }
5236
5244
 
@@ -5870,7 +5878,7 @@ function unplannedNotes(
5870
5878
  * full-loader config, where it is optional.
5871
5879
  */
5872
5880
  export function stageFields(
5873
- cfg: Pick<CharacterConfig, 'seethrough' | 'assemble' | 'scene'> & { limbs?: Record<string, Limb>; bones?: BoneEntry[] },
5881
+ cfg: Pick<CharacterConfig, 'seethrough' | 'assemble' | 'scene' | 'motion_seams'> & { limbs?: Record<string, Limb>; bones?: BoneEntry[] },
5874
5882
  single: { w: number; h: number } | null = null,
5875
5883
  ): {
5876
5884
  resolution: number;
@@ -5880,6 +5888,7 @@ export function stageFields(
5880
5888
  extend: Extend[];
5881
5889
  patches: Patch[];
5882
5890
  cuts: Cut[];
5891
+ motion_seams?: MotionSeamDeclaration[];
5883
5892
  scene?: boolean;
5884
5893
  limbs?: Record<string, Limb>;
5885
5894
  bones?: BoneEntry[];
@@ -5910,6 +5919,7 @@ export function stageFields(
5910
5919
  extend: cfg.assemble.extend_below_crop ?? [],
5911
5920
  patches: cfg.assemble.patches ?? [],
5912
5921
  cuts: cfg.assemble.cuts ?? [],
5922
+ ...(cfg.motion_seams === undefined ? {} : { motion_seams: cfg.motion_seams }),
5913
5923
  ...(cfg.scene === undefined ? {} : { scene: true }),
5914
5924
  ...(cfg.limbs === undefined ? {} : { limbs: cfg.limbs, bones: cfg.bones ?? [] }),
5915
5925
  };
package/src/check.ts CHANGED
@@ -85,6 +85,8 @@ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep
85
85
  import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
86
86
  import { type BoneTransform, computeExactFrameTransforms, cropToSpineY, normaliseDegrees, toBoneLocal } from './coords.ts';
87
87
  import { capBox, inDisc } from './limbs.ts';
88
+ import { motionSeamProblems } from './motionseams.ts';
89
+ import { seamPoseFrame, seamStaticRange, type SeamPoseAtWorst } from './motionseampose.ts';
88
90
  import { coreCompileGuideLine, PartsError, type Problem, refuseIfAny } from './errors.ts';
89
91
  import { framesInside, IDLE_FPS, TIME_SLACK } from './motion.ts';
90
92
  import {
@@ -4305,6 +4307,8 @@ export interface MotionSeamRow {
4305
4307
  worst?: MotionSeamHit & { kind: 'gap' | 'ghost' | 'gapOpen' | 'underGhost' | 'gapOpen+underGhost' };
4306
4308
  /** Exact stock partitions and the resolved UNDER owner, retained even below the floor. */
4307
4309
  cells?: MotionRootCells[];
4310
+ /** Same-render posed evidence on every played non-root WARN. */
4311
+ pose_at_worst?: SeamPoseAtWorst;
4308
4312
  }
4309
4313
 
4310
4314
  /** Existing pairs warn; new body roots alone can FAIL. Unavailable readings are named SKIP, never measured zero. */
@@ -4353,6 +4357,10 @@ export function motionSeamSelection(parts: PartsFile, seams: ReadonlyArray<{ nam
4353
4357
  }
4354
4358
  }
4355
4359
  for (const r of seams) add(r.part, r.neighbour, `requirement "${r.name}" (seam)`);
4360
+ if (parts.motion_seams !== undefined) {
4361
+ refuseIfAny(motionSeamProblems(parts.motion_seams, new Set(parts.parts.map(p => p.name)), 'parts.json motion_seams', 'CHECK_MOTION_SEAM_DECLARATION'));
4362
+ parts.motion_seams.forEach((r, i) => add(r.part, r.neighbour, `motion_seams[${i}]`));
4363
+ }
4356
4364
  const candidates = rig === undefined ? [] : motionRootCandidates(parts, rig);
4357
4365
  const selected: MotionSeamPair[] = [];
4358
4366
  if (candidates.length > 0) {
@@ -4750,6 +4758,7 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4750
4758
  }
4751
4759
  const over = new Map<number, number>();
4752
4760
  let rootWorst: MotionSeamRow['worst'];
4761
+ let warnWorst: MotionSeamRow['worst'];
4753
4762
  const rootFrames = new Set<number>();
4754
4763
  const cells: MotionRootCells[] = [];
4755
4764
  const kinds: Record<'gap' | 'ghost', MotionSeamWorldKind> = { gap: { max_px: 0, worst: null }, ghost: { max_px: 0, worst: null } };
@@ -4767,6 +4776,7 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4767
4776
  // Existing internal pairs retain their original maximum-kind warning and floor.
4768
4777
  for (const h of hits) if (want.root === undefined && (plant.noFloor === true || openingOverFloor(h))) {
4769
4778
  over.set(h.index, Math.max(over.get(h.index) ?? 0, h.px));
4779
+ if (warnWorst === undefined || h.px > warnWorst.px || (h.px === warnWorst.px && h.index < warnWorst.index)) warnWorst = { ...h, kind };
4770
4780
  }
4771
4781
  }
4772
4782
  if (want.root !== undefined && !setup) {
@@ -4842,6 +4852,7 @@ function readSeamRows(dir: string, animations: readonly string[], fps: number, p
4842
4852
  max_px: opens.reduce((m, f) => Math.max(m, over.get(f) ?? 0), 0),
4843
4853
  under_floor: (want.root === undefined ? p.opens : [...rootFrames].filter(f => cells.some(c => c.index === f && c.counted > 0))).filter((f) => !over.has(f)),
4844
4854
  ...(rootWorst === undefined ? {} : { worst: rootWorst }),
4855
+ ...(warnWorst === undefined || setup ? {} : { worst: warnWorst }),
4845
4856
  ...(want.root === undefined ? {} : { cells }),
4846
4857
  });
4847
4858
  });
@@ -4898,9 +4909,99 @@ export function motionSeamLine(pairs: MotionSeamPair[], animations: string[], fp
4898
4909
  };
4899
4910
  }
4900
4911
 
4912
+ /** Enrich active non-root WARNs only, using the SAME seam render and raw hit time. */
4913
+ export function enrichMotionSeamPoses(dir: string, rig: Record<string, unknown>, parts: PartsFile | null, pairs: readonly MotionSeamPair[], rows: MotionSeamRow[]): void {
4914
+ const wanted = rows.filter(row => row.opens.length > 0 && pairs.some(pair => pair.pair === row.pair && pair.root === undefined));
4915
+ if (wanted.length === 0) return;
4916
+ const problems: Problem[] = [];
4917
+ const sidecar = readJson(join(dir, 'frames.json'), problems);
4918
+ refuseIfAny(problems);
4919
+ const sets = Array.isArray(sidecar?.sets) ? sidecar.sets.filter(isRecord) : [];
4920
+ // Slots/weights already bind drawn stop links; resolve their ancestry in the same graph rig-c compiles.
4921
+ const expanded = Array.isArray(rig.stops) ? (expandStops(rig as unknown as RigcRigSpec, 'rig.json') as unknown as Record<string, unknown>) : rig;
4922
+ const bones = (Array.isArray(expanded.bones) ? expanded.bones : []).filter(isRecord);
4923
+ const skin = isRecord(rig.skins) && isRecord(rig.skins.default) ? rig.skins.default : {};
4924
+ const cache = new Map<string, { geometry: Record<string, unknown>; seam: Record<string, unknown>; cohort: FrameSet; parsed: IdleGeometry }>();
4925
+ for (const row of wanted) {
4926
+ const h = row.worst;
4927
+ if (h === undefined) geometryProblem(row.pair, 'above-floor WARN has no worst raw hit');
4928
+ const matches = sets.filter(set => set.animation === row.animation);
4929
+ const set = matches[0];
4930
+ if (matches.length !== 1 || typeof set.dir !== 'string' || isAbsolute(set.dir) || set.dir.split(/[\\/]/).includes('..')) geometryProblem(row.animation, 'one local same-animation frame set required for WARN pose');
4931
+ let data = cache.get(row.animation);
4932
+ if (data === undefined) {
4933
+ const geometry = readJson(join(dir, String(set.dir), GEOMETRY_FILE), problems);
4934
+ const seam = readJson(join(dir, String(set.dir), SEAM_READING_FILE), problems);
4935
+ refuseIfAny(problems);
4936
+ if (geometry === null || seam === null || !Array.isArray(geometry.frames) || geometry.frames.length !== set.written) geometryProblem(row.animation, 'stock seam geometry frame count differs from frames.json');
4937
+ const cohort = readFrameSet(join(dir, String(set.dir)));
4938
+ const parsed = readGeometry(join(dir, String(set.dir), GEOMETRY_FILE), cohort.written);
4939
+ if (parsed === null) geometryProblem(row.animation, 'same-render geometry is missing');
4940
+ data = { geometry, seam, cohort, parsed };
4941
+ cache.set(row.animation, data);
4942
+ }
4943
+ const rawPairs = Array.isArray(data.seam.pairs) ? data.seam.pairs.filter(isRecord) : [];
4944
+ const pair = pairs.find(p => p.pair === row.pair);
4945
+ const raw = rawPairs.find(p => p.a === pair?.a && p.b === pair?.b);
4946
+ const kind = raw?.[h.kind];
4947
+ const hits = isRecord(kind) && Array.isArray(kind.frames) ? kind.frames.filter(isRecord) : [];
4948
+ const hitsAt = hits.filter(hit => hit.index === h.index && hit.px === h.px && hit.cell === h.cell && JSON.stringify(hit.box) === JSON.stringify(h.box));
4949
+ const time = hitsAt[0]?.time;
4950
+ if (hitsAt.length !== 1 || typeof time !== 'number' || !Number.isFinite(time)) geometryProblem(row.pair, 'one matching worst raw hit with actual finite time required');
4951
+ const rawFrames = (data.geometry.frames as unknown[]).filter(isRecord);
4952
+ const frame = rawFrames.find(f => f.index === h.index);
4953
+ const shown = Array.isArray(frame?.attachments) ? frame.attachments.filter(isRecord) : [];
4954
+ const carriers = new Set<string>();
4955
+ for (const name of [pair?.a, pair?.b]) {
4956
+ const active = shown.filter(a => a.slot === name);
4957
+ const onValue = typeof name === 'string' ? skin[name] : undefined;
4958
+ const on = isRecord(onValue) ? onValue : {};
4959
+ const attachment = active.length === 1 && typeof active[0].attachment === 'string' ? on[active[0].attachment] : undefined;
4960
+ if (!isRecord(attachment)) geometryProblem(row.pair, `slot "${String(name)}": active default-skin drawing unavailable at worst frame`);
4961
+ if (Array.isArray(attachment.weights)) {
4962
+ const weights = attachment.weights.flatMap(v => Array.isArray(v) ? v.filter(isRecord) : []);
4963
+ for (const w of weights) if (typeof w.bone === 'string' && typeof w.weight === 'number' && w.weight > 0) carriers.add(w.bone);
4964
+ } else {
4965
+ const slot = (Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord).find(sl => sl.name === name);
4966
+ if (typeof slot?.bone !== 'string') geometryProblem(row.pair, `slot "${String(name)}": no declared bone`);
4967
+ carriers.add(slot.bone);
4968
+ }
4969
+ }
4970
+ if (carriers.size === 0) geometryProblem(row.pair, 'no positive-weight or rigid carrier at worst frame');
4971
+ const ancestry = new Set<string>();
4972
+ for (const carrier of carriers) {
4973
+ const seen = new Set<string>();
4974
+ let next: string | undefined = carrier;
4975
+ while (next !== undefined) {
4976
+ if (seen.has(next)) geometryProblem(row.pair, `cycle in carrier path at "${next}"`);
4977
+ seen.add(next);
4978
+ ancestry.add(next);
4979
+ const named = bones.filter(b => b.name === next);
4980
+ if (named.length !== 1) geometryProblem(row.pair, `carrier "${next}": one declared bone required`);
4981
+ next = typeof named[0].parent === 'string' ? named[0].parent : undefined;
4982
+ }
4983
+ }
4984
+ const joints = bones.filter(b => typeof b.name === 'string' && ancestry.has(b.name)).map(b => {
4985
+ const ranges = parts?.parts.flatMap(p => {
4986
+ const limb = p.limb;
4987
+ return limb !== undefined && limb.bone === b.name && limb.range !== undefined ? [limb.range] : [];
4988
+ }) ?? [];
4989
+ return { bone: String(b.name), parent: typeof b.parent === 'string' ? b.parent : null,
4990
+ inherit: typeof b.inherit === 'string' ? b.inherit : 'normal', ...seamStaticRange(ranges) };
4991
+ });
4992
+ for (const joint of joints) {
4993
+ const track = boneTrackOf(data.parsed, join(dir, String(set.dir), GEOMETRY_FILE), data.cohort, joint.bone);
4994
+ if (typeof track === 'string') geometryProblem(row.pair, track);
4995
+ }
4996
+ row.pose_at_worst = seamPoseFrame(data.geometry, row.animation, h.index, time, data.cohort, joints);
4997
+ }
4998
+ }
4999
+
4901
5000
  /** One warning as the console prints it (issue #493's form, the floor's clause after it). */
4902
5001
  export function motionSeamWarnText(r: MotionSeamRow): string {
4903
- return `WARN seam "${r.pair}" opens on ${r.opens.length} frame(s) ${frameRuns(r.opens)} max ${r.max_px} px in "${r.animation}" — over the one-cell floor${r.under_floor.length === 0 ? '' : `, ${r.under_floor.length} more frame(s) one cell thick not reported`}`;
5002
+ const pose = r.pose_at_worst;
5003
+ const evidence = pose === undefined ? '' : `; worst frame ${pose.index} (t = ${pose.time}s), ${pose.joints.map(j => `bone "${j.bone}" parent ${JSON.stringify(j.parent)} world ${j.world_x_axis_degrees === null ? 'unavailable' : round3(j.world_x_axis_degrees) + 'deg'}; relative setup axis ${j.parent_relative_setup_axis_delta_degrees_mod360 === null ? 'unavailable' : round3(j.parent_relative_setup_axis_delta_degrees_mod360) + 'deg modulo360'}, static range ${JSON.stringify(j.static_range)} (${j.comparison}${j.reason === undefined ? '' : ': ' + j.reason})`).join(' | ')}`;
5004
+ return `WARN seam "${r.pair}" opens on ${r.opens.length} frame(s) ${frameRuns(r.opens)} max ${r.max_px} px in "${r.animation}" — over the one-cell floor${r.under_floor.length === 0 ? '' : `, ${r.under_floor.length} more frame(s) one cell thick not reported`}${evidence}`;
4904
5005
  }
4905
5006
 
4906
5007
  // ---------------------------------------------------------------------------
@@ -6136,10 +6237,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
6136
6237
  const activeDest = stripped === null ? seamMotionDir : join(seamMotionDir, env === null ? 'default' : 'active');
6137
6238
  const renderedWorlds = new Set<'default' | 'still'>();
6138
6239
  const hasRoots = read.some(p => p.root !== undefined);
6139
- const r = measured(['render', '--candidate', buildDir, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), ...(hasRoots ? ['--geometry'] : []), '--out', activeDest]);
6240
+ const r = measured(['render', '--candidate', buildDir, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--geometry', '--out', activeDest]);
6140
6241
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --seam ${list} --fps ${fps}`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
6141
6242
  const activeWorldRows: MotionSeamWorldRow[] = [];
6142
6243
  motionSeam = motionSeamLine(pairs, animationNames, fps, readMotionSeams(activeDest, animationNames, fps, read, {}, stripped !== null && env === null ? activeWorldRows : undefined, hasRoots ? motionRootDrawOrderReader(activeDest) : undefined), undefined, motionRootProblems, unmeasuredRoots);
6244
+ enrichMotionSeamPoses(activeDest, inp.rig, inp.parts, pairs, motionSeam.rows);
6143
6245
  if (stripped !== null) {
6144
6246
  const response = environmentResponse(readFileSync(join(buildDir, 'skeleton.json'), 'utf8'));
6145
6247
  motionSeam.worlds = motionSeamWorlds(true, response.wind.length > 0, world => {
@@ -7168,6 +7270,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
7168
7270
  const carry = breathCarrier(inp.rig, inp.motion, p.name, geometryPath, frames, { art, box: p, stage: inp.stage, shown, toward: rises ? 'up' : 'down', root: t.root, tip: t.tip });
7169
7271
  if (carry !== null) rows[rows.length - 1] = { ...rows[rows.length - 1], carried_by: carry.bone, breath_rig_px: round3(carry.breath), root_without_breath_rig_px: round3(carry.root), tip_without_breath_rig_px: round3(carry.tip) };
7170
7272
  const offChain = carry === null && round3(t.tip) > 0 ? offChainClause(inp.rig, inp.motion, p.name) : null;
7273
+ const misplaced = rises || carry !== null || offChain !== null ? null : chainRootsBelowArtClause(inp.rig, inp.motion, p, inp.stage, readGeometry(geometryPath, frames)?.setupBones);
7171
7274
  const why =
7172
7275
  carry === null
7173
7276
  ? `the chain's amplitudes do not grow toward the tip, or the mesh is not weighted to the chain${offChain === null ? '' : `; ${offChain}`}`
@@ -7177,7 +7280,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
7177
7280
  problems.push({
7178
7281
  code: 'CHECK_TIP_OVER_ROOT',
7179
7282
  object: `part "${p.name}", box ${p.x},${p.y} ${p.w}x${p.h} rig px, posed by the idle's geometry${rises ? ', declared rises' : ''}`,
7180
- detail: `the art in its ${tipHalf} half travels ${round3(t.tip)} rig px and in its ${rootHalf} half ${round3(t.root)} rig px (ratio ${ratio ?? 'undefined: nothing moves'}); a ratio >= ${TIP_RATIO_FLOOR} is required — ${why}`,
7283
+ detail: `the art in its ${tipHalf} half travels ${round3(t.tip)} rig px and in its ${rootHalf} half ${round3(t.root)} rig px (ratio ${ratio ?? 'undefined: nothing moves'}); a ratio >= ${TIP_RATIO_FLOOR} is required — ${misplaced ?? why}`,
7181
7284
  });
7182
7285
  }
7183
7286
  }
@@ -7236,6 +7339,24 @@ function offChainClause(rig: Record<string, unknown>, motion: Record<string, unk
7236
7339
  return `it is weighted off the chain to ${list} — drop the segment on ${drop} in \`meshes.${part}.segments\`, or grow the chain's amplitudes toward the tip`;
7237
7340
  }
7238
7341
 
7342
+ /** #752: a failing hanging part whose carrying pivots all sit below its art needs their placement named, not larger angles. */
7343
+ export function chainRootsBelowArtClause(
7344
+ rig: Record<string, unknown>, motion: Record<string, unknown>, part: Pick<PartRecord, 'name' | 'y' | 'h'>,
7345
+ stage: StageBox, setupBones: unknown,
7346
+ ): string | null {
7347
+ const { found } = chainsCarrying(rig, motion, part.name);
7348
+ if (found.length === 0 || !Array.isArray(setupBones)) return null;
7349
+ const origins = new Map(setupBones.filter(isRecord).filter((b) => typeof b.name === 'string' && typeof b.worldX === 'number' && typeof b.worldY === 'number').map((b) => [String(b.name), { x: b.worldX as number, y: b.worldY as number }]));
7350
+ const roots = found.map((chain) => {
7351
+ const at = origins.get(chain[0]);
7352
+ return at === undefined ? null : { chain, x: at.x - stage.x, y: cropToSpineY(at.y - stage.y, stage.height) };
7353
+ });
7354
+ if (roots.some((r) => r === null || !Number.isFinite(r.x) || !Number.isFinite(r.y) || r.y <= part.y + part.h)) return null;
7355
+ const placed = roots.filter((r): r is NonNullable<typeof r> => r !== null);
7356
+ const list = placed.map((r) => `${r.chain.join(' > ')} at crop [${round3(r.x)}, ${round3(r.y)}]`).join('; ');
7357
+ return `the carrying chains' roots are below the art: ${list}; the part's crop y range is ${part.y}..${part.y + part.h} — re-place these chains' \`bones\` \`points\` / \`tip\` across this art, rooting them in its upper half (y ${part.y}..${part.y + part.h / 2}) and ending in its lower half (y ${part.y + part.h / 2}..${part.y + part.h}); \`propose\` on these assembled parts drafts those positions; increasing amplitudes leaves the root positions unchanged`;
7358
+ }
7359
+
7239
7360
  /**
7240
7361
  * The bones a part's attachments are bound to in the default skin (issue #231): a mesh's weights, or its slot's
7241
7362
  * bone for an attachment that carries no weights.
@@ -157,10 +157,11 @@ function entryEdits(
157
157
  V === null
158
158
  ? `it holds ${held} where ${draftSays}`
159
159
  : `it equals neither the draft, the draft without the recipe, nor the previous recipe's draft: it holds ${held} where ${prev === undefined ? 'the previous recipe\'s draft has no such entry' : `the previous recipe's draft writes ${field === null ? shown(prev) : fieldOf(prev, field)}`} and ${draftSays}`;
160
+ const kind = section === 'motion.tracks' ? 'track' : section === 'bones' ? 'bone' : 'constraint';
160
161
  conflicts.push({
161
162
  code: 'PROPOSE_WRITE_CONFIG_CONFLICT',
162
163
  object: `config.${section}[${i}] "${k}"`,
163
- detail: `${section} entry "${k}" is the recipe's, and it was changed by hand: ${says}, so the write would drop the hand edit; take the draft by removing the hand edit (or the entry), or leave the recipe out for that part (its config.cloth block)`,
164
+ detail: `${section} entry "${k}" is the recipe's, and it was changed by hand: ${says}, so the write would drop the hand edit; to take the recipe's draft, remove the hand-edited ${kind} "${k}" from config.${section} (or revert the hand edit) and run propose --cloth again, or leave the recipe out for that part (its config.cloth block)`,
164
165
  });
165
166
  };
166
167
  for (const k of [...owned, ...removed]) {
@@ -288,7 +289,7 @@ export function clothConfigEdits(drafted: Proposal, plain: Proposal, input: unkn
288
289
  conflicts.push({
289
290
  code: 'PROPOSE_WRITE_CONFIG_CONFLICT',
290
291
  object: where,
291
- detail: `${path.join('.')} is the previous recipe's, the recipe now leaves it to the draft without the recipe, and it was changed by hand: it equals neither the draft nor the previous recipe's draft: it holds ${field === null ? shown(mine) : at(mine, field)} where the previous recipe's draft writes ${c === undefined ? 'no such entry' : field === null ? shown(c) : at(c, field)} and the draft writes ${b === undefined ? 'no such entry' : field === null ? shown(b) : at(b, field)}, so the write would drop the hand edit; take the draft by removing the hand edit (or the entry), or keep the recipe for that part (its config.cloth block)`,
292
+ detail: `${path.join('.')} is the previous recipe's, the recipe now leaves it to the draft without the recipe, and it was changed by hand: it equals neither the draft nor the previous recipe's draft: it holds ${field === null ? shown(mine) : at(mine, field)} where the previous recipe's draft writes ${c === undefined ? 'no such entry' : field === null ? shown(c) : at(c, field)} and the draft writes ${b === undefined ? 'no such entry' : field === null ? shown(b) : at(b, field)}, so the write would drop the hand edit; to take the draft, remove the hand-edited ${path.join('.')} (or revert the hand edit) and run propose --cloth again, or keep the recipe for that part (its config.cloth block)`,
292
293
  });
293
294
  };
294
295
  const prevKeys = (section: string, have: readonly string[]): string[] => {
package/src/config.ts CHANGED
@@ -88,6 +88,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs';
88
88
  import { dirname, resolve } from 'node:path';
89
89
  import { RIG_BONE_INHERIT, RIG_SKIN_CONSTRAINT_KEYS, type RigBoneInherit, type RigConstraint, type RigSkinConstraintKey, type RigStop } from 'rig-c/src/rig.ts';
90
90
  import { pyRound } from './round.ts';
91
+ import { motionSeamProblems, type MotionSeamDeclaration } from './motionseams.ts';
91
92
  import { REQUIREMENTS_SPEC } from './requirements.ts';
92
93
  import { CLOTH_TARGETS, type ClothRecipes, RECIPE_STRENGTH, RIGC_DEFAULT_DAMPING, springStable } from './cloth.ts';
93
94
  import { GRID, MAX_SIDE } from './contour.ts';
@@ -1069,6 +1070,8 @@ export interface CharacterConfig {
1069
1070
  * is read and no byte of any output moves.
1070
1071
  */
1071
1072
  requirements?: string;
1073
+ /** Explicit motion observations, propagated to parts.json; absent means no added pair. */
1074
+ motion_seams?: MotionSeamDeclaration[];
1072
1075
  }
1073
1076
 
1074
1077
  /** `config.scene` (issue #242): the declaration that the painting is a scene. It holds no field today. */
@@ -1389,11 +1392,12 @@ export interface AssembleConfig {
1389
1392
  /** Issue #349: read with `bones` (the joints are the bones' origins) when present. */
1390
1393
  limbs?: Record<string, Limb>;
1391
1394
  bones?: BoneEntry[];
1395
+ motion_seams?: MotionSeamDeclaration[];
1392
1396
  /** Issue #354: the `rig_scale` `propose` drafted the rig sections at, held equal to `assemble.rig_scale` when present. */
1393
1397
  proposed_rig_scale?: number;
1394
1398
  }
1395
1399
 
1396
- const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements'] as const;
1400
+ const TOP_KEYS = ['key', 'generation', 'seethrough', 'assemble', 'limbs', 'bones', 'meshes', 'regions', 'motion', 'constraints', 'stops', 'turn', 'scene', 'cloth', 'proposed_rig_scale', 'requirements', 'motion_seams'] as const;
1397
1401
 
1398
1402
  /**
1399
1403
  * The one partial entry point. It validates exactly what its door requires —
@@ -1464,6 +1468,10 @@ function parseEarlyConfigFrom(raw: Json, door: EarlyDoor, base: string | null):
1464
1468
  if (isPlainObject(t.assemble) && 'alternates' in t.assemble) {
1465
1469
  checkAlternates(c, t.assemble.alternates, made, limbs, names?.bones ?? null, names?.chains ?? null, t.regions, t.meshes);
1466
1470
  }
1471
+ if ('motion_seams' in t) {
1472
+ const output = new Set([...made.parts.filter(n => !limbs?.consumed.has(n)), ...made.patches, ...made.cuts, ...(limbs?.parts.keys() ?? [])]);
1473
+ c.problems.push(...motionSeamProblems(t.motion_seams, output, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1474
+ }
1467
1475
  }
1468
1476
  if ('cloth' in t) checkCloth(c, t.cloth);
1469
1477
  const pose = base === null ? null : poseBeside(c, t.generation, base);
@@ -1660,6 +1668,7 @@ function parseConfigFrom(raw: Json, base: string | null): { config: CharacterCon
1660
1668
  if ('constraints' in t) checkConstraints(c, t.constraints, names.bones, names.parents);
1661
1669
  if ('stops' in t) checkStops(c, t.stops, names.bones, names.chains);
1662
1670
  const attached = attachedParts(t.meshes, t.regions);
1671
+ if ('motion_seams' in t) c.problems.push(...motionSeamProblems(t.motion_seams, attached, 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1663
1672
  const hasAltFace = hasAlternateFaceSet(t.assemble, [...parts, ...cuts]);
1664
1673
  if ('turn' in t) checkTurn(c, t.turn, attached, names.bones, hasAltFace);
1665
1674
  if ('scene' in t) checkScene(c, t.scene);
@@ -1890,9 +1899,9 @@ export interface SkeletonSections {
1890
1899
  * both before writing (`checkProposal`). A key the loader would not take is
1891
1900
  * refused by name, as in a config. Refusals name the fields `proposal.…`.
1892
1901
  */
1893
- export function parseProposalSections(raw: Json): SkeletonSections & { limbs?: Record<string, Limb>; constraints?: ConfigConstraint[]; stops?: ConfigStop[]; proposed_rig_scale?: number } {
1902
+ export function parseProposalSections(raw: Json): SkeletonSections & { limbs?: Record<string, Limb>; constraints?: ConfigConstraint[]; stops?: ConfigStop[]; proposed_rig_scale?: number; motion_seams?: MotionSeamDeclaration[] } {
1894
1903
  const c = new Check();
1895
- const top = c.object('config', raw, ['bones', 'meshes', 'regions', 'motion'], ['notes', 'limbs', 'constraints', 'stops', 'proposed_rig_scale']);
1904
+ const top = c.object('config', raw, ['bones', 'meshes', 'regions', 'motion'], ['notes', 'limbs', 'constraints', 'stops', 'proposed_rig_scale', 'motion_seams']);
1896
1905
  if (top !== null) {
1897
1906
  const names = 'bones' in top ? checkBones(c, top.bones) : { bones: new Set<string>([ROOT_BONE]), chains: new Map<string, number>(), parents: new Map<string, string>() };
1898
1907
  if ('limbs' in top) {
@@ -1903,6 +1912,7 @@ export function parseProposalSections(raw: Json): SkeletonSections & { limbs?: R
1903
1912
  }
1904
1913
  if ('meshes' in top) checkMeshes(c, top.meshes, names.bones, names.chains, top.stops);
1905
1914
  if ('regions' in top) checkRegions(c, top.regions, names.bones);
1915
+ if ('motion_seams' in top) c.problems.push(...motionSeamProblems(top.motion_seams, attachedParts(top.meshes, top.regions), 'config.motion_seams', 'CONFIG_MOTION_SEAM'));
1906
1916
  if ('motion' in top) checkMotion(c, top.motion, names.bones, names.chains, 'regions' in top ? top.regions : undefined);
1907
1917
  if ('constraints' in top) checkConstraints(c, top.constraints, names.bones, names.parents);
1908
1918
  if ('stops' in top) checkStops(c, top.stops, names.bones, names.chains);
@@ -1910,7 +1920,7 @@ export function parseProposalSections(raw: Json): SkeletonSections & { limbs?: R
1910
1920
  if ('notes' in top && c.array('config.notes', top.notes, false)) (top.notes as Json[]).forEach((n, i) => c.string(`config.notes[${i}]`, n, false));
1911
1921
  }
1912
1922
  refuseIfAny(c.problems.map((p) => ({ ...p, object: p.object.replace(/^config\b/, 'proposal') })));
1913
- return raw as SkeletonSections & { limbs?: Record<string, Limb>; constraints?: ConfigConstraint[]; stops?: ConfigStop[]; proposed_rig_scale?: number };
1923
+ return raw as SkeletonSections & { limbs?: Record<string, Limb>; constraints?: ConfigConstraint[]; stops?: ConfigStop[]; proposed_rig_scale?: number; motion_seams?: MotionSeamDeclaration[] };
1914
1924
  }
1915
1925
 
1916
1926
  /**
package/src/layers.ts CHANGED
@@ -41,6 +41,8 @@ import { BODY_TAGS, HEAD_TAGS, HIDDEN_NAME_RULE, type LayerTagReading, layerTagR
41
41
 
42
42
  /** Alpha strictly above this counts as painted. The reference uses the same cut for its ghost clean-up and its sheets. */
43
43
  export const OPAQUE_ALPHA_ABOVE = 8;
44
+ /** Alpha at or above this is "opaque" for ownership, projection cores and the seam override. `>= 250`, not `== 255`: See-through leaves alpha-254 speckle. */
45
+ export const CORE_ALPHA = 250;
44
46
  /**
45
47
  * A pixel whose min channel is above this is "near-white". The assemble stage's
46
48
  * rim and seam guard apply it to the painting (`src/assemble.ts` re-exports it
@@ -100,6 +102,66 @@ export interface LayerSet {
100
102
  hidden: HiddenLayer[];
101
103
  }
102
104
 
105
+ /** Bounds in input-canvas pixels, with exclusive right/bottom boundaries. */
106
+ export interface OpaqueBox {
107
+ left: number;
108
+ top: number;
109
+ right: number;
110
+ bottom: number;
111
+ }
112
+
113
+ function alphaBox(layer: Pick<Layer, 'pixels' | 'left' | 'top'>, includes: (alpha: number) => boolean): OpaqueBox | null {
114
+ const p = layer.pixels;
115
+ let left = p.width;
116
+ let top = p.height;
117
+ let right = 0;
118
+ let bottom = 0;
119
+ for (let y = 0; y < p.height; y++) {
120
+ for (let x = 0; x < p.width; x++) {
121
+ if (!includes(p.data[(y * p.width + x) * 4 + 3])) continue;
122
+ left = Math.min(left, x);
123
+ top = Math.min(top, y);
124
+ right = Math.max(right, x + 1);
125
+ bottom = Math.max(bottom, y + 1);
126
+ }
127
+ }
128
+ return right === 0 ? null : { left: layer.left + left, top: layer.top + top, right: layer.left + right, bottom: layer.top + bottom };
129
+ }
130
+
131
+ /** Original alpha above the legacy painted-pixel cut (>8), before cleanup or resampling. */
132
+ export function layerOpaqueBox(layer: Pick<Layer, 'pixels' | 'left' | 'top'>): OpaqueBox | null {
133
+ return alphaBox(layer, alpha => alpha > OPAQUE_ALPHA_ABOVE);
134
+ }
135
+
136
+ /** Original alpha at or above CORE_ALPHA; not an owned, eroded or resampled projection core. */
137
+ export function layerCoreBox(layer: Pick<Layer, 'pixels' | 'left' | 'top'>): OpaqueBox | null {
138
+ return alphaBox(layer, alpha => alpha >= CORE_ALPHA);
139
+ }
140
+
141
+ function bodyBox(set: LayerSet, readBox: (layer: Layer) => OpaqueBox | null): OpaqueBox | null {
142
+ let union: OpaqueBox | null = null;
143
+ for (const layer of set.layers) {
144
+ if (layer.tag.group !== 'body') continue;
145
+ const box = readBox(layer);
146
+ if (box === null) continue;
147
+ union = union === null ? box : {
148
+ left: Math.min(union.left, box.left), top: Math.min(union.top, box.top),
149
+ right: Math.max(union.right, box.right), bottom: Math.max(union.bottom, box.bottom),
150
+ };
151
+ }
152
+ return union;
153
+ }
154
+
155
+ /** Source >8 union of the reader's existing drawn body group, not an anatomical silhouette. */
156
+ export function bodyOpaqueBox(set: LayerSet): OpaqueBox | null {
157
+ return bodyBox(set, layerOpaqueBox);
158
+ }
159
+
160
+ /** Source >=CORE_ALPHA union of the same body group; no ownership, erosion or cleanup. */
161
+ export function bodyCoreBox(set: LayerSet): OpaqueBox | null {
162
+ return bodyBox(set, layerCoreBox);
163
+ }
164
+
103
165
  function opaque(r: Raster): number {
104
166
  let n = 0;
105
167
  for (let i = 3; i < r.data.length; i += 4) if (r.data[i] > OPAQUE_ALPHA_ABOVE) n++;
@@ -0,0 +1,117 @@
1
+ /** Posed-axis evidence from one stock seam render, never sampled source keys. */
2
+ import type { GeometryFile, GeometryFrame } from 'rig-c/render';
3
+ import type { FrameSet } from './check.ts';
4
+ import { PartsError } from './errors.ts';
5
+
6
+ // Stock rig-c 2.69 geometry header, also exported by rig-c/render. render-shared
7
+ // does not expose its constants; avoid loading the optional Spine side for a header read.
8
+ export const SEAM_GEOMETRY_COORDINATES = 'spine world, y up, world units';
9
+ const SEAM_GEOMETRY_SPEC: GeometryFile['spec'] = 'rigc-geometry/1';
10
+
11
+ export interface SeamMatrix {
12
+ a: number; b: number; c: number; d: number;
13
+ worldX: number; worldY: number;
14
+ }
15
+ export interface SeamJointPose {
16
+ bone: string;
17
+ parent: string | null;
18
+ world_x_axis_degrees: number | null;
19
+ parent_relative_setup_axis_delta_degrees_mod360: number | null;
20
+ static_range: [number, number] | null;
21
+ comparison: 'axis-modulo-360' | 'unavailable';
22
+ reason?: string;
23
+ }
24
+ export interface SeamPoseAtWorst {
25
+ index: number;
26
+ time: number;
27
+ joints: SeamJointPose[];
28
+ }
29
+ const record = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
30
+ const fail = (detail: string): never => { throw new PartsError([{ code: 'CHECK_GEOMETRY_FILE', object: 'motion seam pose', detail }]); };
31
+ const wrap = (degrees: number): number => ((degrees + 180) % 360 + 360) % 360 - 180;
32
+ const angle = (a: number, c: number): number => Math.atan2(c, a) * 180 / Math.PI;
33
+ const inverseProduct = (p: SeamMatrix, c: SeamMatrix): SeamMatrix | null => {
34
+ const det = p.a * p.d - p.b * p.c;
35
+ if (det === 0 || !Number.isFinite(det)) return null;
36
+ const a = (p.d * c.a - p.b * c.c) / det, b = (p.d * c.b - p.b * c.d) / det;
37
+ const x = (-p.c * c.a + p.a * c.c) / det, d = (-p.c * c.b + p.a * c.d) / det;
38
+ return { a, b, c: x, d, worldX: 0, worldY: 0 };
39
+ };
40
+ const regular = (m: SeamMatrix): boolean => {
41
+ const x2 = m.a * m.a + m.c * m.c, y2 = m.b * m.b + m.d * m.d;
42
+ // Floating-point arithmetic slack only, relative to the two axis lengths.
43
+ return x2 > 0 && y2 > 0 && m.a * m.d - m.b * m.c > 0 &&
44
+ Math.abs(m.a * m.b + m.c * m.d) <= 64 * Number.EPSILON * Math.sqrt(x2 * y2);
45
+ };
46
+
47
+ /** World axes remain evidence even when local-range equivalence is unavailable. */
48
+ export function seamJointPose(bone: string, parent: string | null, inherit: string, setup: SeamMatrix, posed: SeamMatrix,
49
+ parentSetup: SeamMatrix | null, parentPosed: SeamMatrix | null, range: [number, number] | null, rangeReason?: string): SeamJointPose {
50
+ const out: SeamJointPose = { bone, parent, world_x_axis_degrees: posed.a === 0 && posed.c === 0 ? null : angle(posed.a, posed.c),
51
+ parent_relative_setup_axis_delta_degrees_mod360: null, static_range: range, comparison: 'unavailable' };
52
+ if (inherit !== 'normal') return { ...out, reason: `inherit ${inherit}: parent-relative local-range comparison unavailable` };
53
+ if (parent === null || parentSetup === null || parentPosed === null) return { ...out, reason: 'no parent frame for a local-range comparison' };
54
+ const rest = inverseProduct(parentSetup, setup), frame = inverseProduct(parentPosed, posed);
55
+ if (rest === null || frame === null || !regular(rest) || !regular(frame) || !regular(parentSetup) || !regular(parentPosed)) return { ...out, reason: 'singular, reflected, sheared or degenerate axes: local-range comparison unavailable' };
56
+ const delta = wrap(angle(frame.a, frame.c) - angle(rest.a, rest.c));
57
+ out.parent_relative_setup_axis_delta_degrees_mod360 = delta;
58
+ if (range === null) return { ...out, reason: rangeReason ?? 'no declared static range; relative axis delta is modulo 360' };
59
+ if (range[0] <= -180 || range[1] >= 180 || Math.abs(delta) === 180) return { ...out, reason: 'ambiguous winding against static range; relative axis delta is modulo 360' };
60
+ // This is explicitly an axis comparison modulo 360, never an unwrapped local key or a new gate.
61
+ return { ...out, comparison: 'axis-modulo-360', reason: 'normal unsheared axes; modulo 360 only, winding not certified' };
62
+ }
63
+
64
+ /** Identical declarations share one range; conflicting declarations remain explicitly ambiguous. */
65
+ export function seamStaticRange(ranges: readonly [number, number][]): { range: [number, number] | null; rangeReason?: string } {
66
+ const unique = [...new Map(ranges.map(range => [JSON.stringify(range), range])).values()];
67
+ return unique.length <= 1 ? { range: unique[0] ?? null }
68
+ : { range: null, rangeReason: `ambiguous declared static ranges ${unique.map(range => JSON.stringify(range)).join(', ')}; no local-range comparison` };
69
+ }
70
+
71
+ export type SeamFrameCohort = Pick<FrameSet, 'animation' | 'fps' | 'viewport'> & { frames: readonly Pick<GeometryFrame, 'index'>[] };
72
+ export interface SeamPoseJoint {
73
+ bone: string;
74
+ parent: string | null;
75
+ inherit: string;
76
+ range: [number, number] | null;
77
+ rangeReason?: string;
78
+ }
79
+
80
+ /** Bind stock coordinates, source parent identities and the complete real PNG frame cohort. */
81
+ export function seamPoseFrame(geometry: unknown, animation: string, index: number, time: number, cohort: SeamFrameCohort,
82
+ joints: readonly SeamPoseJoint[]): SeamPoseAtWorst {
83
+ if (!record(geometry) || geometry.spec !== SEAM_GEOMETRY_SPEC || geometry.animation !== animation || cohort.animation !== animation ||
84
+ geometry.fps !== cohort.fps || !record(geometry.viewport) || !Array.isArray(geometry.frames) || !record(geometry.setup)) return fail('same-animation stock geometry with matching fps, viewport, setup and frames required');
85
+ if (geometry.coordinates !== SEAM_GEOMETRY_COORDINATES) return fail(`coordinates must be ${JSON.stringify(SEAM_GEOMETRY_COORDINATES)}; found ${JSON.stringify(geometry.coordinates)}`);
86
+ const viewport = cohort.viewport;
87
+ for (const key of ['x', 'y', 'width', 'height', 'scale', 'pixelWidth', 'pixelHeight'] as const) {
88
+ if (typeof viewport[key] !== 'number' || !Number.isFinite(viewport[key]) || geometry.viewport[key] !== viewport[key]) return fail(`viewport ${key} differs from frames.json or is not finite`);
89
+ }
90
+ const roster = Array.isArray(geometry.bones) ? geometry.bones.filter(record) : [];
91
+ if (!Array.isArray(geometry.bones) || roster.length !== geometry.bones.length || roster.some(b => typeof b.name !== 'string' || (b.parent !== null && typeof b.parent !== 'string')) ||
92
+ new Set(roster.map(b => b.name)).size !== roster.length) return fail('bone/parent roster requires unique names and explicit string/null parents');
93
+ const declared = new Map<string, GeometryFile['bones'][number]>(roster.map(b => [String(b.name), { name: String(b.name), parent: b.parent as string | null }]));
94
+ for (const b of declared.values()) if (b.parent !== null && !declared.has(b.parent)) return fail(`bone/parent roster: parent "${b.parent}" of "${b.name}" is missing`);
95
+ for (const j of joints) {
96
+ if (!declared.has(j.bone) || declared.get(j.bone)?.parent !== j.parent || (j.parent !== null && !declared.has(j.parent))) return fail(`bone/parent roster for "${j.bone}" disagrees with source parent ${JSON.stringify(j.parent)}`);
97
+ }
98
+ const frames = geometry.frames.filter(record);
99
+ if (frames.length !== geometry.frames.length || frames.some(f => !Number.isSafeInteger(f.index) || Number(f.index) < 0 || typeof f.time !== 'number' || !Number.isFinite(f.time) || f.time < 0) || new Set(frames.map(f => f.index)).size !== frames.length) return fail('frame cohort requires unique integer indices and finite actual times');
100
+ if (frames.length !== cohort.frames.length || frames.some((f, i) => f.index !== cohort.frames[i].index)) return fail('frame cohort differs from the actual PNG frame set (including unselected frames)');
101
+ const frame = frames.find(f => f.index === index);
102
+ if (!Number.isSafeInteger(index) || !Number.isFinite(time) || frame === undefined || frame.time !== time) return fail(`frame ${index}: raw seam and geometry frame/time differ`);
103
+ const matrix = (rows: unknown, name: string): SeamMatrix => {
104
+ const matches = Array.isArray(rows) ? rows.filter(r => record(r) && r.name === name) : [];
105
+ const row = matches[0];
106
+ if (matches.length !== 1 || !record(row) || ['a','b','c','d','worldX','worldY'].some(k => typeof row[k] !== 'number' || !Number.isFinite(row[k]))) return fail(`bone "${name}": one matrix with six finite numbers required`);
107
+ return { a: Number(row.a), b: Number(row.b), c: Number(row.c), d: Number(row.d), worldX: Number(row.worldX), worldY: Number(row.worldY) };
108
+ };
109
+ const required = new Set(joints.flatMap(j => j.parent === null ? [j.bone] : [j.bone, j.parent]));
110
+ for (const name of required) {
111
+ matrix(geometry.setup.bones, name);
112
+ for (const f of frames) matrix(f.bones, name);
113
+ }
114
+ const setupBones = geometry.setup.bones;
115
+ return { index, time, joints: joints.map(j => seamJointPose(j.bone, j.parent, j.inherit, matrix(setupBones, j.bone), matrix(frame.bones, j.bone),
116
+ j.parent === null ? null : matrix(setupBones, j.parent), j.parent === null ? null : matrix(frame.bones, j.parent), j.range, j.rangeReason)) };
117
+ }