@rig-c/parts 1.47.0 → 1.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/check.ts CHANGED
@@ -77,6 +77,7 @@
77
77
  * the last idle frame is refused unless it sits at t = duration (within
78
78
  * `TIME_SLACK`, issue #244).
79
79
  */
80
+ import { createHash } from 'node:crypto';
80
81
  import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
81
82
  import { basename, delimiter, dirname, join, resolve } from 'node:path';
82
83
  import { measureRecomposite, type RecompositeFigures, recompositeRecord, scenePhrase, sourceInRig } from './assemble.ts';
@@ -158,6 +159,7 @@ import {
158
159
  } from './requirements.ts';
159
160
  import { RIG_BONE_INHERIT, type RigSpec as RigcRigSpec } from 'rig-c/src/rig.ts';
160
161
  import { expandStops } from 'rig-c/src/stop.ts';
162
+ import { ENVIRONMENT_SPEC, EnvironmentError, readEnvironmentSchedule } from 'rig-c/src/environment.ts';
161
163
  import { alphaComposite } from './raster/composite.ts';
162
164
  import { readPng, writePng } from './raster/png.ts';
163
165
  import { newFloatImage, newRaster, type Raster } from './raster/types.ts';
@@ -1814,6 +1816,12 @@ export interface CheckFigures {
1814
1816
  rigc_entry: RigcEntryRecord;
1815
1817
  /** How the artifact's page was packed: the `--page-edges` and `--pack-shape` rigc was handed, which its pack line was read to agree with ({@link packEdgeProblems}). Provenance, not a bar. */
1816
1818
  pack_mode: { page_edges: PageEdges; pack_shape: PackShape };
1819
+ /**
1820
+ * Written only under `--environment` (issue #538): the `rigc-environment/1` schedule every measured render was posed
1821
+ * under — the path as the command line gave it, the sha256 of the bytes read, and how many steps rigc's reader read
1822
+ * off them ({@link readCheckEnvironment}). Provenance, not a bar; without the flag no key is written.
1823
+ */
1824
+ environment?: CheckEnvironment;
1817
1825
  /** Null when the rig has no idle (issue #77); `skipped.loop` then says why. */
1818
1826
  loop_max_diff: number | null;
1819
1827
  /**
@@ -2134,6 +2142,62 @@ export interface CheckReport {
2134
2142
  cloth: ClothLine;
2135
2143
  }
2136
2144
 
2145
+ /**
2146
+ * How many of the bars measured and how many said SKIP, by name — the
2147
+ * summary's second half (issue #77): `PASS` reads only the bars that measured,
2148
+ * so a run that measured one bar says so on the line that says PASS. The
2149
+ * count is every bar `check` tallied: the {@link BARS}, and
2150
+ * {@link FOLD_LINE} where it is written (issue #320).
2151
+ */
2152
+ export function barsSummary(r: Pick<CheckReport, 'bars'>): string {
2153
+ const { measured, skipped } = r.bars;
2154
+ return `${measured.length} of ${measured.length + skipped.length} bar(s) measured, ${skipped.length} skipped${skipped.length === 0 ? '' : ` (${skipped.map((s) => s.bar).join(', ')})`}`;
2155
+ }
2156
+
2157
+ /** The summary's warning clause: each warning line that read something, named, with the warnings they printed together; empty when none read. */
2158
+ export function warningsClause(r: Pick<CheckReport, 'motionSeam' | 'cloth'>): string {
2159
+ const read = [...(r.motionSeam.status === 'SKIP' ? [] : [{ name: MOTION_SEAM_LINE, n: r.motionSeam.warnings }]), ...(r.cloth.status === 'SKIP' ? [] : [{ name: CLOTH_LINE, n: r.cloth.warnings }])];
2160
+ if (read.length === 0) return '';
2161
+ return `; ${read.reduce((a, x) => a + x.n, 0)} warning(s) (${read.map((x) => x.name).join(', ')}, not a bar)`;
2162
+ }
2163
+
2164
+ /**
2165
+ * The last line `check` prints, whole and as printed (`check: PASS; …` or `check: FAIL — …; …`), issue #541: the
2166
+ * one place it is composed. `check` prints it from here, and `remesh.json` / `retune.json` carry it from here
2167
+ * ({@link CheckReport} in, no clock, no path), so a consumer matching the carried line against a `check` run's stdout
2168
+ * compares the same composer's output twice.
2169
+ */
2170
+ export function checkSummaryLine(r: Pick<CheckReport, 'figures' | 'problems' | 'requirements' | 'bars' | 'motionSeam' | 'cloth'>): string {
2171
+ const reqNotPass = r.requirements === null ? 0 : r.requirements.summary.declared - r.requirements.summary.pass;
2172
+ const notMet = r.requirements === null ? `${r.problems.length} bar(s) not met` : `${r.problems.length - reqNotPass} bar(s) not met, ${reqNotPass} declared requirement(s) not PASS`;
2173
+ return `${r.figures.PASS ? 'check: PASS' : `check: FAIL — ${notMet}`}; ${barsSummary(r)}${warningsClause(r)}`;
2174
+ }
2175
+
2176
+ /** A block's status as {@link checkStatuses} reads it off `check.json`. */
2177
+ export type CheckStatus = 'PASS' | 'FAIL' | 'SKIP' | 'WARN' | 'CLEAR' | 'REPORTED';
2178
+
2179
+ /**
2180
+ * Every block's status as `check.json` records it (issue #541), read off the figures object `check.json` is written
2181
+ * from, in the file's order, one entry per block the file holds. The three bars with figures and no `status` key are
2182
+ * read the way {@link barsNotMet} reads the file: `gate` PASS when `gate_spine_html_green` is true, else FAIL (it is
2183
+ * never skipped); `loop` SKIP when `loop_max_diff` is null, `seam` SKIP when `seam_mean` is null, otherwise FAIL when
2184
+ * {@link barsNotMet} names it and PASS when it does not. Every other block carries its own `status` key and is copied:
2185
+ * the judgement lines, then {@link FOLD_LINE}, {@link LEVEL_LINE}, {@link STRESS_LINE}, {@link LIMB_LINE},
2186
+ * {@link SWEEP_LINE}, {@link MOTION_SEAM_LINE}, {@link CLOTH_LINE}, the reported lines and {@link SOURCE_LINE}, each
2187
+ * where the file writes it. The `requirements` block's lines are not bars and are not read here.
2188
+ */
2189
+ export function checkStatuses(fig: CheckFigures): Record<string, CheckStatus> {
2190
+ const notMet = barsNotMet(fig as unknown as Record<string, unknown>);
2191
+ const bar = (name: string, measured: boolean): CheckStatus => (!measured ? 'SKIP' : notMet.includes(name) ? 'FAIL' : 'PASS');
2192
+ const out: Record<string, CheckStatus> = { gate: bar('gate', true), loop: bar('loop', fig.loop_max_diff !== null), seam: bar('seam', fig.seam_mean !== null) };
2193
+ for (const n of JUDGEMENT_LINES) out[n] = fig[n].status;
2194
+ for (const n of [FOLD_LINE, LEVEL_LINE, STRESS_LINE, LIMB_LINE, SWEEP_LINE, MOTION_SEAM_LINE, CLOTH_LINE, ...REPORTED_LINES, SOURCE_LINE] as const) {
2195
+ const l = fig[n];
2196
+ if (l !== undefined) out[n] = l.status;
2197
+ }
2198
+ return out;
2199
+ }
2200
+
2137
2201
  /**
2138
2202
  * The one line `check` prints when `motion.json` holds animations beside the
2139
2203
  * idle (issue #183), or null when it holds none, so a rig of the idle alone
@@ -3577,6 +3641,61 @@ export function rigcFailed(what: string, call: RigcCall, lines: readonly string[
3577
3641
  return quoted.map((l) => ({ code: 'CHECK_RIGC_GREEN', object, detail: `exit ${call.status}: ${l}${ran}` }));
3578
3642
  }
3579
3643
 
3644
+ // ---------------------------------------------------------------------------
3645
+ // the world the readings are taken in (issue #538)
3646
+ // ---------------------------------------------------------------------------
3647
+
3648
+ /** The refusal of a schedule `check --environment` names: rigc's reader's sentence, or rigc render's, verbatim. */
3649
+ export const ENVIRONMENT_RULE = 'CHECK_ENVIRONMENT';
3650
+
3651
+ /** What `check.json` records of the schedule under `--environment`: provenance, not a bar. */
3652
+ export interface CheckEnvironment {
3653
+ /** The path as the command line gave it — never resolved, so the record holds no directory the caller did not type. */
3654
+ path: string;
3655
+ /** The sha256 of the file's bytes as read, the bytes rigc's reader read. */
3656
+ sha256: string;
3657
+ /** How many steps rigc's reader read off it. */
3658
+ steps: number;
3659
+ }
3660
+
3661
+ function environmentRefused(given: string, sentence: string): PartsError {
3662
+ return new PartsError([{ code: ENVIRONMENT_RULE, object: given, detail: sentence }]);
3663
+ }
3664
+
3665
+ /**
3666
+ * `--environment <file>` read once, before anything is built (issue #538): the file's bytes hashed and handed to
3667
+ * rig-c's own reader, `readEnvironmentSchedule` (`rig-c/src/environment.ts`), which refuses every malformed schedule
3668
+ * — a `spec` other than {@link ENVIRONMENT_SPEC}, a key it does not read, no step, a `t` that is not finite, at or
3669
+ * above 0 and after the step before, a `wind` or `gravity` that is not a pair of finite numbers, a step that changes
3670
+ * nothing — by entry, field, the value found and the value required. Nothing here reads the schedule's meaning: its
3671
+ * sentence is carried as {@link ENVIRONMENT_RULE}'s detail, verbatim, and a path with no file at it is worded as
3672
+ * `rigc render --environment` words it. What a well-formed schedule cannot do to this rig — move a rig with no
3673
+ * physics constraint, change a half no constraint answers, fall after the last frame drawn — is rigc render's to
3674
+ * refuse, and {@link runCheck} carries that sentence the same way.
3675
+ */
3676
+ export function readCheckEnvironment(given: string): CheckEnvironment {
3677
+ const path = resolve(given);
3678
+ if (!existsSync(path) || !statSync(path).isFile()) throw environmentRefused(given, `--environment ${given}: nothing at ${path} — it takes a schedule file { "spec": "${ENVIRONMENT_SPEC}", "steps": [...] }`);
3679
+ let bytes: Buffer;
3680
+ try {
3681
+ bytes = readFileSync(path);
3682
+ } catch (err) {
3683
+ throw environmentRefused(given, `--environment ${given}: not readable — ${(err as Error).message}`);
3684
+ }
3685
+ try {
3686
+ const steps = readEnvironmentSchedule(bytes.toString('utf8'), given);
3687
+ return { path: given, sha256: createHash('sha256').update(bytes).digest('hex'), steps: steps.length };
3688
+ } catch (err) {
3689
+ if (err instanceof EnvironmentError) throw environmentRefused(given, err.message);
3690
+ throw err;
3691
+ }
3692
+ }
3693
+
3694
+ /** The line `check` prints under `--environment`, beside rigc's identity: which schedule, by path and digest, and which renders it poses. */
3695
+ export function environmentLine(env: CheckEnvironment): string {
3696
+ return `environment: ${env.path}, ${ENVIRONMENT_SPEC}, ${env.steps} step(s), sha256 ${env.sha256.slice(0, 16)} — every render a bar or a warning reads with the physics on is posed under it; the physics-off, setup-pose and loop renders are not`;
3697
+ }
3698
+
3580
3699
  /**
3581
3700
  * Run the whole check. Refuses (throws a PartsError) when the inputs are
3582
3701
  * unreadable or a rigc step that everything after it depends on is red — the
@@ -3603,23 +3722,28 @@ export function rigcFailed(what: string, call: RigcCall, lines: readonly string[
3603
3722
  * MEASURABLE is a problem. Without it nothing here reads, writes or prints
3604
3723
  * anything it did not before.
3605
3724
  */
3606
- export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false): CheckReport {
3725
+ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, partsHome?: string, mode: PackMode = DEFAULT_PACK_MODE, source?: string, requirements?: string, seamPairsAsked = false, keepStills = false, set?: string, allSets = false, environment?: string): CheckReport {
3607
3726
  let inp: CheckInputs;
3608
3727
  let reqFile: RequirementsFile | null = null;
3609
3728
  let seams: Map<string, SeamPair[]> | null = null;
3610
- if (requirements === undefined) inp = readCheckInputs(rigDir, partsHome, source, set, allSets);
3611
- else {
3612
- // Both readers collect every problem; one refusal names both sets.
3613
- const refused: Problem[] = [];
3614
- const take = <T>(read: () => T): T | null => {
3615
- try {
3616
- return read();
3617
- } catch (err) {
3618
- if (!(err instanceof PartsError)) throw err;
3619
- refused.push(...err.problems);
3620
- return null;
3621
- }
3622
- };
3729
+ // Every reader collects every problem; one refusal names every set.
3730
+ const refused: Problem[] = [];
3731
+ const take = <T>(read: () => T): T | null => {
3732
+ try {
3733
+ return read();
3734
+ } catch (err) {
3735
+ if (!(err instanceof PartsError)) throw err;
3736
+ refused.push(...err.problems);
3737
+ return null;
3738
+ }
3739
+ };
3740
+ // Issue #538: the schedule is read once, first, by rigc's own reader; refused, nothing is built or written.
3741
+ const env = environment === undefined ? null : take(() => readCheckEnvironment(environment));
3742
+ if (requirements === undefined) {
3743
+ const got = take(() => readCheckInputs(rigDir, partsHome, source, set, allSets));
3744
+ refuseIfAny(refused);
3745
+ inp = got as CheckInputs;
3746
+ } else {
3623
3747
  const got = take(() => readCheckInputs(rigDir, partsHome, source, set, allSets));
3624
3748
  reqFile = take(() => readRequirements(requirements));
3625
3749
  refuseIfAny(refused);
@@ -3638,7 +3762,29 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3638
3762
  }
3639
3763
  refuseIfAny(refused);
3640
3764
  }
3765
+ // Issue #538: a motion with no animation gives check no render a schedule could pose — every frame it reads would be
3766
+ // the setup still's — so the flag is refused rather than recorded over readings it did not move.
3767
+ if (env !== null && !(isRecord(inp.motion.animations) && Object.keys(inp.motion.animations).length > 0)) {
3768
+ 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`);
3769
+ }
3641
3770
  const rigcEntry = readRigcEntry(requireRigcVersion(rigc));
3771
+ /**
3772
+ * Issue #538: a render whose frames a bar or a warning reads, with the physics on — posed under the schedule when
3773
+ * `--environment` names one (the path as given; rigc reads the file the same way). A refusal rigc render prints of
3774
+ * the schedule against this rig (its `--environment <path>:` line) is carried as {@link ENVIRONMENT_RULE}, verbatim;
3775
+ * any other failure is the call site's to name. Without the flag it is `rigc`, and no argument moves.
3776
+ */
3777
+ const measured: RigcRunner =
3778
+ env === null
3779
+ ? rigc
3780
+ : (args) => {
3781
+ const call = rigc([...args, '--environment', env.path]);
3782
+ if (call.status !== 0) {
3783
+ const said = call.out.split('\n').map((l) => l.trim()).find((l) => l.startsWith(`rigc: --environment ${env.path}: `));
3784
+ if (said !== undefined) throw environmentRefused(env.path, `${said.slice('rigc: '.length)}${rigcRanClause(call)}`);
3785
+ }
3786
+ return call;
3787
+ };
3642
3788
  const out = resolve(outDir);
3643
3789
  mkdirSync(out, { recursive: true });
3644
3790
  const buildDir = join(out, 'build');
@@ -3709,7 +3855,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3709
3855
  const levelProblems: Problem[] = [];
3710
3856
  try {
3711
3857
  if (inp.idleDuration !== null) {
3712
- const render = rigc(['render', '--candidate', buildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--geometry', '--out', idleDir]);
3858
+ const render = measured(['render', '--candidate', buildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--geometry', '--out', idleDir]);
3713
3859
  if (render.status !== 0) refuseIfAny(rigcFailed('render --animation idle --geometry', render, render.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3714
3860
  idle = readFrameSet(idleDir);
3715
3861
  const last = idle.frames[idle.frames.length - 1];
@@ -3784,7 +3930,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3784
3930
  // Issue #348: with a foot to read, the keyed render writes each animation's geometry as well.
3785
3931
  const geometry = feet.length > 0 ? ['--geometry'] : [];
3786
3932
  if (stripped === null) {
3787
- const fr = rigc(['render', '--candidate', buildDir, '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', foldDir]);
3933
+ const fr = measured(['render', '--candidate', buildDir, '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', foldDir]);
3788
3934
  if (fr.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps}`, fr, fr.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3789
3935
  const readings = filterFolds(readFoldSets(foldDir, animationNames, fps, fr.out));
3790
3936
  folds = foldsLine(animationNames, fps, 0, readings, mayFoldForRun, reqFile === null ? null : reqFile.path, foldProblems, readings, inp.rig, []);
@@ -3800,8 +3946,10 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3800
3946
  } else {
3801
3947
  const onDir = join(foldDir, 'on');
3802
3948
  const offDir = join(foldDir, 'off');
3803
- const frOn = rigc(['render', '--candidate', buildDir, '--folds', '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', onDir]);
3949
+ const frOn = measured(['render', '--candidate', buildDir, '--folds', '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', onDir]);
3804
3950
  if (frOn.status !== 0) refuseIfAny(rigcFailed(`render --folds --fps ${fps}`, frOn, frOn.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3951
+ // The physics-off half takes no schedule (issue #538): its candidate declares no physics constraint, so no
3952
+ // world moves it, and rigc render refuses a schedule on it by name.
3805
3953
  const frOff = rigc(['render', '--candidate', keyedBuild('the animations with their physics constraint(s) left out'), '--folds', ...geometry, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', offDir]);
3806
3954
  if (frOff.status !== 0) refuseIfAny(rigcFailed(`render --folds${geometry.map((g) => ` ${g}`).join('')} --fps ${fps} (physics constraint(s) left out)`, frOff, frOff.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3807
3955
  const readingsOn = filterFolds(readFoldSets(onDir, animationNames, fps, frOn.out));
@@ -3828,7 +3976,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3828
3976
  // 3b. the parts a judgement reads alone: each rendered by its own slots, on the whole rig's grid
3829
3977
  const isolated = (label: string, ps: readonly PartRecord[]): FrameSet => {
3830
3978
  const dir = join(isoDir, label);
3831
- const r = rigc(['render', '--candidate', buildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--slot', ps.map((p) => p.name).join(','), '--out', dir]);
3979
+ const r = measured(['render', '--candidate', buildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--slot', ps.map((p) => p.name).join(','), '--out', dir]);
3832
3980
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --animation idle --slot ${ps.map((p) => p.name).join(',')}`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3833
3981
  return readFrameSet(dir);
3834
3982
  };
@@ -3853,7 +4001,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
3853
4001
  if (b.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (BREATH_VISIBLE's copy, the idle beside it with its breath tracks held at rest)`, b, buildGateLines(b.out)));
3854
4002
  const slots = ps.map((p) => p.name).join(',');
3855
4003
  const render = (animation: string, label: string): FrameSet => {
3856
- const r = rigc(['render', '--candidate', join(dir, 'build'), '--animation', animation, '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--slot', slots, '--out', join(dir, label)]);
4004
+ const r = measured(['render', '--candidate', join(dir, 'build'), '--animation', animation, '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--slot', slots, '--out', join(dir, label)]);
3857
4005
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --animation ${animation} --slot ${slots} (BREATH_VISIBLE's copy)`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
3858
4006
  return readFrameSet(join(dir, label));
3859
4007
  };
@@ -4003,7 +4151,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4003
4151
  rmSync(seamMotionDir, { recursive: true, force: true });
4004
4152
  try {
4005
4153
  const list = read.map((p) => `${p.a}:${p.b}`).join(',');
4006
- const r = rigc(['render', '--candidate', buildDir, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', seamMotionDir]);
4154
+ const r = measured(['render', '--candidate', buildDir, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', seamMotionDir]);
4007
4155
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --seam ${list} --fps ${fps}`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
4008
4156
  motionSeam = motionSeamLine(pairs, animationNames, fps, readMotionSeams(seamMotionDir, animationNames, fps, read));
4009
4157
  } finally {
@@ -4183,7 +4331,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4183
4331
 
4184
4332
  // 5. the scene's declared requirements (issue #93), only under --requirements
4185
4333
  const reqProblems: Problem[] = [];
4186
- const reqBlock = reqFile === null ? null : measureRequirements(inp, reqFile, buildDir, out, rigc, reqProblems, seams ?? new Map());
4334
+ const reqBlock = reqFile === null ? null : measureRequirements(inp, reqFile, buildDir, out, rigc, reqProblems, seams ?? new Map(), measured);
4187
4335
 
4188
4336
  const skipped: { loop?: string; seam?: string } = {};
4189
4337
  if (inp.noIdle !== null) skipped.loop = inp.noIdle;
@@ -4192,6 +4340,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
4192
4340
  gate_spine_html_green: htmlGreen,
4193
4341
  rigc_entry: rigcEntry,
4194
4342
  pack_mode: { page_edges: mode.pageEdges, pack_shape: mode.packShape },
4343
+ ...(env === null ? {} : { environment: env }),
4195
4344
  loop_max_diff: loop === null ? null : loop.max,
4196
4345
  ...(loopPhysics === null ? {} : { loop_physics: loopPhysics }),
4197
4346
  seam_mean: seam === null ? null : round3(seam.mean),
@@ -4329,7 +4478,7 @@ const REQUIREMENTS_SCRATCH = '_requirements';
4329
4478
  * `CHECK_RIGC_GREEN`, quoting rigc. Lines go into the returned block; each
4330
4479
  * FAIL and NOT MEASURABLE into `problems`.
4331
4480
  */
4332
- export function measureRequirements(inp: CheckInputs, file: RequirementsFile, buildDir: string, out: string, rigc: RigcRunner, problems: Problem[], seams: ReadonlyMap<string, readonly SeamPair[]> = new Map()): RequirementsBlock {
4481
+ export function measureRequirements(inp: CheckInputs, file: RequirementsFile, buildDir: string, out: string, rigc: RigcRunner, problems: Problem[], seams: ReadonlyMap<string, readonly SeamPair[]> = new Map(), render: RigcRunner = rigc): RequirementsBlock {
4333
4482
  const reqDir = join(out, REQUIREMENTS_DIR);
4334
4483
  const scratch = join(out, REQUIREMENTS_SCRATCH);
4335
4484
  for (const d of [reqDir, scratch]) rmSync(d, { recursive: true, force: true });
@@ -4350,7 +4499,7 @@ export function measureRequirements(inp: CheckInputs, file: RequirementsFile, bu
4350
4499
  return b.dir;
4351
4500
  };
4352
4501
  const posesOf = (candidate: string, animation: string, dir: string, label: string): { poses: Poses; geo: IdleGeometry; path: string } => {
4353
- const r = rigc(['render', '--candidate', candidate, '--animation', animation, '--fps', String(file.fps), '--max', String(IDLE_MAX_PX), '--geometry', '--out', dir]);
4502
+ const r = render(['render', '--candidate', candidate, '--animation', animation, '--fps', String(file.fps), '--max', String(IDLE_MAX_PX), '--geometry', '--out', dir]);
4354
4503
  if (r.status !== 0) refuseIfAny(rigcFailed(`render --animation ${animation} --geometry (${label})`, r, r.out.split('\n').filter((l) => l.includes('FAIL') || l.includes('rigc:'))));
4355
4504
  const set = readFrameSet(dir);
4356
4505
  if (set.written !== set.sampled || set.stride !== 1) {
@@ -7,12 +7,15 @@
7
7
  * (`cloth: null`), and each config section of the proposal ({@link PROPOSAL_CONFIG_SECTIONS}) whose value differs
8
8
  * between the two is drafted ({@link clothConfigEdits}). An object section (`meshes`, `regions`, `motion`) is
9
9
  * spliced entry by entry — `meshes.<part>` and `regions.<part>` for each part the recipe moved, `motion.tracks` and
10
- * not the author's `animations_from` — and an array section (`bones`, `constraints`) whole: the drafted array
11
- * replaces the input's, so a bone the author added by hand does not survive a write. A section the recipe does not
10
+ * not the author's `animations_from` — and so, from issue #552, is an array section (`bones`, `constraints`,
11
+ * `motion.tracks`): its entries are named ({@link ARRAY_SECTIONS}), the entries the recipe produced or changed are
12
+ * replaced in place or inserted, the entries it replaced are removed, and every other entry of the input — one the
13
+ * author added by hand among them — keeps its bytes and its place. A hand edit to an entry the recipe re-drafts or
14
+ * removes is refused by name, `PROPOSE_WRITE_CONFIG_CONFLICT`, rather than dropped. A section the recipe does not
12
15
  * move keeps the input's bytes.
13
16
  */
14
17
 
15
- import { PartsError } from './errors.ts';
18
+ import { PartsError, type Problem } from './errors.ts';
16
19
  import { type ConfigEdit, splicedEdits } from './meshdraft.ts';
17
20
  import { PROPOSAL_CONFIG_SECTIONS, type Proposal } from './propose.ts';
18
21
 
@@ -20,25 +23,182 @@ function isPlain(v: unknown): v is Record<string, unknown> {
20
23
  return typeof v === 'object' && v !== null && !Array.isArray(v);
21
24
  }
22
25
 
26
+ /** Key-order-blind JSON text: two entries are the same value when this is the same string. */
27
+ function canon(v: unknown): string {
28
+ if (Array.isArray(v)) return `[${v.map(canon).join(',')}]`;
29
+ if (isPlain(v)) {
30
+ return `{${Object.keys(v)
31
+ .filter((k) => v[k] !== undefined)
32
+ .sort()
33
+ .map((k) => `${JSON.stringify(k)}:${canon(v[k])}`)
34
+ .join(',')}}`;
35
+ }
36
+ return JSON.stringify(v);
37
+ }
38
+
39
+ /** One edit `--write-config` makes, with the words the write line prints for it. */
40
+ export interface ClothEdit extends ConfigEdit {
41
+ label: string;
42
+ }
43
+
23
44
  /**
24
- * The edits that turn a config holding the draft without the recipe (`plain`) into one holding the draft with it
25
- * (`drafted`): for each config section whose value differs, an object section entry by entry (an entry the recipe
26
- * removed, such as a part it took from `regions` into `meshes`, is removed) and any other section whole.
45
+ * An array section spliced entry by entry (issue #552), and what names an entry in it: a bone by `name` (a single
46
+ * bone) or `chain` (a chain), one namespace, as a mesh segment resolves either; a constraint by `name`; a track by
47
+ * `chain`, or by `bone` and `prop` (the proposer writes two tracks on one bone, `translatey` and `scalex`). An entry
48
+ * with no such name has no identity: it is never the recipe's, so it is kept.
49
+ */
50
+ export const ARRAY_SECTIONS: ReadonlyArray<{ path: readonly string[]; identity: (e: unknown) => string | null }> = [
51
+ { path: ['bones'], identity: (e) => (isPlain(e) ? (typeof e.name === 'string' ? e.name : typeof e.chain === 'string' ? e.chain : null) : null) },
52
+ { path: ['constraints'], identity: (e) => (isPlain(e) && typeof e.name === 'string' ? e.name : null) },
53
+ {
54
+ path: ['motion', 'tracks'],
55
+ identity: (e) => (isPlain(e) ? (typeof e.chain === 'string' ? e.chain : typeof e.bone === 'string' && typeof e.prop === 'string' ? `${e.bone} ${e.prop}` : null) : null),
56
+ },
57
+ ];
58
+
59
+ function valueAt(o: unknown, path: readonly string[]): unknown {
60
+ let v = o;
61
+ for (const k of path) v = isPlain(v) ? v[k] : undefined;
62
+ return v;
63
+ }
64
+
65
+ /** Each entry of a drafted array by its name; the proposer names every entry once, and anything else is this module's error. */
66
+ function byName(arr: readonly unknown[], identity: (e: unknown) => string | null, which: string, section: string): Map<string, unknown> {
67
+ const m = new Map<string, unknown>();
68
+ for (const e of arr) {
69
+ const k = identity(e);
70
+ if (k === null) throw new Error(`clothConfigEdits: the ${which} ${section} holds an entry with no name: ${JSON.stringify(e)}`);
71
+ if (m.has(k)) throw new Error(`clothConfigEdits: the ${which} ${section} names "${k}" twice`);
72
+ m.set(k, e);
73
+ }
74
+ return m;
75
+ }
76
+
77
+ /** The first field, in the author's order, where the author's entry differs from `ref`; null when the two are not both objects. */
78
+ function firstField(author: unknown, ref: unknown): string | null {
79
+ if (!isPlain(author) || !isPlain(ref)) return null;
80
+ for (const k of [...Object.keys(author), ...Object.keys(ref).filter((k) => !(k in author))]) if (canon(author[k]) !== canon(ref[k])) return k;
81
+ return null;
82
+ }
83
+
84
+ function shown(v: unknown): string {
85
+ const t = JSON.stringify(v);
86
+ return t.length > 60 ? `${t.slice(0, 57)}...` : t;
87
+ }
88
+
89
+ /**
90
+ * The edits on one array section, entry by entry (issue #552). With `I` the input's entry of a name, `P` the plain
91
+ * draft's and `D` the recipe's (equality is of the value, key order aside):
92
+ * - owned (D present, and P absent or different): `I` absent is inserted after the input's entry that precedes it in
93
+ * the drafted array (the nearest earlier drafted entry the array holds, one inserted before it included), else at
94
+ * the end; `I` equal to `P` is replaced in place; `I` equal to `D` is left as it is;
95
+ * - removed (P present, D absent — the recipe replaced a plain chain with its trees): `I` equal to `P` is removed;
96
+ * - every other input entry is kept, bytes and order;
97
+ * - an owned or removed `I` that is none of those — changed by hand — is a conflict, as is a name the input states twice.
98
+ */
99
+ function entryEdits(path: readonly string[], identity: (e: unknown) => string | null, drafted: readonly unknown[], plain: readonly unknown[], input: readonly unknown[], conflicts: Problem[]): ClothEdit[] {
100
+ const section = path.join('.');
101
+ const D = byName(drafted, identity, 'drafted', section);
102
+ const P = byName(plain, identity, 'plain', section);
103
+ const keys = input.map(identity);
104
+ const where = new Map<string, number[]>();
105
+ keys.forEach((k, i) => {
106
+ if (k !== null) where.set(k, [...(where.get(k) ?? []), i]);
107
+ });
108
+ const owned = [...D.keys()].filter((k) => !P.has(k) || canon(P.get(k)) !== canon(D.get(k)));
109
+ const removed = [...P.keys()].filter((k) => !D.has(k));
110
+ const replace: string[] = [];
111
+ const remove: string[] = [];
112
+ const conflict = (k: string, i: number, drafts: boolean): void => {
113
+ const author = input[i];
114
+ const field = firstField(author, P.has(k) ? P.get(k) : D.get(k));
115
+ const fieldOf = (e: unknown, f: string): string => (isPlain(e) && e[f] !== undefined ? `${f} ${shown(e[f])}` : `no ${f}`);
116
+ const held = field === null ? `the entry ${shown(author)}` : fieldOf(author, field);
117
+ const draft = D.get(k);
118
+ const draftSays = !drafts ? 'the draft removes the entry (the recipe drafts that part afresh)' : field === null ? `the draft writes ${shown(draft)}` : `the draft writes ${fieldOf(draft, field)}`;
119
+ conflicts.push({
120
+ code: 'PROPOSE_WRITE_CONFIG_CONFLICT',
121
+ object: `config.${section}[${i}] "${k}"`,
122
+ detail: `${section} entry "${k}" is the recipe's, and it was changed by hand: it holds ${held} where ${draftSays}, 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)`,
123
+ });
124
+ };
125
+ for (const k of [...owned, ...removed]) {
126
+ const at = where.get(k) ?? [];
127
+ if (at.length > 1) {
128
+ conflicts.push({
129
+ code: 'PROPOSE_WRITE_CONFIG_CONFLICT',
130
+ object: `config.${section}[${at[1]}] "${k}"`,
131
+ detail: `${section} names "${k}" ${at.length} times (entries ${at.join(', ')}), and the recipe drafts that name, so the write cannot tell which entry is the recipe's; state it once`,
132
+ });
133
+ continue;
134
+ }
135
+ if (at.length === 0) continue;
136
+ const I = canon(input[at[0]]);
137
+ if (D.has(k)) {
138
+ if (I === canon(D.get(k))) continue;
139
+ if (P.has(k) && I === canon(P.get(k))) replace.push(k);
140
+ else conflict(k, at[0], true);
141
+ } else if (I === canon(P.get(k))) remove.push(k);
142
+ else conflict(k, at[0], false);
143
+ }
144
+ const edits: ClothEdit[] = [];
145
+ const work = [...keys];
146
+ for (const k of replace) edits.push({ path: [...path, work.indexOf(k)], value: D.get(k), label: `${section}["${k}"] replaced` });
147
+ for (const k of remove) {
148
+ const i = work.indexOf(k);
149
+ edits.push({ path: [...path, i], value: undefined, label: `${section}["${k}"] removed` });
150
+ work.splice(i, 1);
151
+ }
152
+ const order = [...D.keys()];
153
+ for (const k of owned) {
154
+ if (work.includes(k)) continue;
155
+ let pos = work.length;
156
+ for (let j = order.indexOf(k) - 1; j >= 0; j--) {
157
+ const before = work.indexOf(order[j]);
158
+ if (before >= 0) {
159
+ pos = before + 1;
160
+ break;
161
+ }
162
+ }
163
+ edits.push({ path: [...path, pos], value: D.get(k), insert: true, label: `${section}["${k}"] inserted` });
164
+ work.splice(pos, 0, k);
165
+ }
166
+ return edits;
167
+ }
168
+
169
+ /**
170
+ * The edits that turn `input` (the `--cloth` config, parsed) into one holding what the recipe drafts, measured as the
171
+ * difference between the draft with the recipe (`drafted`) and without it (`plain`): for each config section whose
172
+ * value differs, an object section entry by entry (an entry the recipe removed, such as a part it took from `regions`
173
+ * into `meshes`, is removed), an array section of {@link ARRAY_SECTIONS} entry by entry ({@link entryEdits}) where
174
+ * the input holds it as an array, and any other section, or one the input lacks, whole. Every conflict is collected and
175
+ * refused in one throw, `PROPOSE_WRITE_CONFIG_CONFLICT`, before anything is written.
176
+ *
177
+ * `whole` is the selftest's mutant only (issue #552): `bones`, `constraints` and `motion.tracks` replaced whole, as
178
+ * the #537 writer did; no flag or environment reaches it.
27
179
  */
28
- export function clothConfigEdits(drafted: Proposal, plain: Proposal): ConfigEdit[] {
29
- const edits: ConfigEdit[] = [];
30
- const d = drafted as unknown as Record<string, unknown>;
31
- const p = plain as unknown as Record<string, unknown>;
180
+ export function clothConfigEdits(drafted: Proposal, plain: Proposal, input: unknown, whole = false): ClothEdit[] {
181
+ const edits: ClothEdit[] = [];
182
+ const conflicts: Problem[] = [];
183
+ const d = JSON.parse(JSON.stringify(drafted)) as Record<string, unknown>;
184
+ const p = JSON.parse(JSON.stringify(plain)) as Record<string, unknown>;
185
+ const one = (path: readonly string[], a: unknown, b: unknown): void => {
186
+ const s = whole ? undefined : ARRAY_SECTIONS.find((x) => x.path.join('.') === path.join('.'));
187
+ const mine = valueAt(input, path);
188
+ if (s !== undefined && Array.isArray(b) && (a === undefined || Array.isArray(a)) && Array.isArray(mine)) edits.push(...entryEdits(path, s.identity, b, Array.isArray(a) ? a : [], mine, conflicts));
189
+ else edits.push({ path, value: b, label: path.join('.') });
190
+ };
32
191
  for (const section of PROPOSAL_CONFIG_SECTIONS) {
33
192
  const a = p[section];
34
193
  const b = d[section];
35
194
  if (JSON.stringify(a) === JSON.stringify(b)) continue;
36
195
  if (isPlain(a) && isPlain(b)) {
37
196
  for (const k of [...Object.keys(b), ...Object.keys(a).filter((k) => !(k in b))]) {
38
- if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) edits.push({ path: [section, k], value: b[k] });
197
+ if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) one([section, k], a[k], b[k]);
39
198
  }
40
- } else edits.push({ path: [section], value: b });
199
+ } else one([section], a, b);
41
200
  }
201
+ if (conflicts.length > 0) throw new PartsError(conflicts);
42
202
  return edits;
43
203
  }
44
204
 
@@ -61,7 +221,7 @@ export function writtenClothConfig(where: string, text: string, edits: readonly
61
221
  return r.text;
62
222
  }
63
223
 
64
- /** The paths the edits name, dotted, in order: what the write line prints. */
65
- export function editPaths(edits: readonly ConfigEdit[]): string[] {
66
- return edits.map((e) => e.path.join('.'));
224
+ /** What each edit names, in order: what the write line prints. */
225
+ export function editPaths(edits: readonly ClothEdit[]): string[] {
226
+ return edits.map((e) => e.label);
67
227
  }