@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/meshdraft.ts CHANGED
@@ -484,10 +484,11 @@ export function partsNamed(p: Problem, among: readonly string[], seams: { draft:
484
484
  // ---------------------------------------------------------------------------
485
485
 
486
486
  /**
487
- * Where a JSON value starts and ends in a text, by a path of object keys, and (for a non-empty path) where the key
488
- * naming it starts (`key`, its opening quote). Throws when the path does not resolve.
487
+ * Where a JSON value starts and ends in a text, by a path of object keys and array indices (a number steps to that
488
+ * element of an array, issue #552), and (for a non-empty path) where the last step starts (`key`: a member's opening
489
+ * quote, or the element itself). Throws when the path does not resolve.
489
490
  */
490
- export function jsonValueSpan(text: string, path: readonly string[]): { start: number; end: number; key?: number } {
491
+ export function jsonValueSpan(text: string, path: readonly (string | number)[]): { start: number; end: number; key?: number } {
491
492
  let i = 0;
492
493
  const ws = (): void => {
493
494
  while (i < text.length && /\s/.test(text[i])) i++;
@@ -541,6 +542,22 @@ export function jsonValueSpan(text: string, path: readonly string[]): { start: n
541
542
  skip();
542
543
  return keyAt === undefined ? { start, end: i } : { start, end: i, key: keyAt };
543
544
  }
545
+ const step = path[depth];
546
+ if (typeof step === 'number') {
547
+ if (text[i] !== '[') throw new Error(`jsonValueSpan: ${path.slice(0, depth).join('.') || 'the document'} is not an array`);
548
+ i++;
549
+ for (let n = 0; ; n++) {
550
+ ws();
551
+ if (text[i] === ']') throw new Error(`jsonValueSpan: no element ${step} at ${path.slice(0, depth).join('.') || 'the top'}`);
552
+ if (n === step) {
553
+ keyAt = i;
554
+ return find(depth + 1);
555
+ }
556
+ skip();
557
+ ws();
558
+ if (text[i] === ',') i++;
559
+ }
560
+ }
544
561
  if (text[i] !== '{') throw new Error(`jsonValueSpan: ${path.slice(0, depth).join('.') || 'the document'} is not an object`);
545
562
  i++;
546
563
  for (;;) {
@@ -562,14 +579,20 @@ export function jsonValueSpan(text: string, path: readonly string[]): { start: n
562
579
  return find(0);
563
580
  }
564
581
 
565
- /** One edit {@link splicedEdits} makes: the value at `path` set (replaced, or inserted when absent), or, `undefined`, removed. */
582
+ /**
583
+ * One edit {@link splicedEdits} makes: the value at `path` set (replaced, or inserted when absent), or, `undefined`,
584
+ * removed. A path whose last step is an index (issue #552) addresses an array element: set replaces it, `undefined`
585
+ * removes it, and `insert` puts `value` before it (at the array's length: after its last element), every later
586
+ * element moving up one.
587
+ */
566
588
  export interface ConfigEdit {
567
- path: readonly string[];
589
+ path: readonly (string | number)[];
568
590
  value: unknown;
591
+ insert?: boolean;
569
592
  }
570
593
 
571
594
  /** The span at `path`, or null where the path does not resolve (a key absent, or a step that is not an object). */
572
- function spanOrNull(text: string, path: readonly string[]): { start: number; end: number; key?: number } | null {
595
+ function spanOrNull(text: string, path: readonly (string | number)[]): { start: number; end: number; key?: number } | null {
573
596
  try {
574
597
  return jsonValueSpan(text, path);
575
598
  } catch {
@@ -583,8 +606,32 @@ function indentAt(text: string, at: number): string {
583
606
  return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? '';
584
607
  }
585
608
 
609
+ /** An element inserted into the array at `arrayPath` before its element `index` (at its length: after the last). */
610
+ function insertElement(text: string, arrayPath: readonly (string | number)[], index: number, value: unknown): string {
611
+ const arr = spanOrNull(text, arrayPath);
612
+ if (arr === null || text[arr.start] !== '[') throw new Error(`splicedEdits: ${arrayPath.join('.') || 'the document'} is not an array`);
613
+ const next = spanOrNull(text, [...arrayPath, index]);
614
+ if (next !== null) {
615
+ // Before the element: the new one takes its line, and the old one follows on a line of its own at the same indent.
616
+ const indent = indentAt(text, next.start);
617
+ const body = JSON.stringify(value, null, 2).split('\n').join(`\n${indent}`);
618
+ return `${text.slice(0, next.start)}${body},\n${indent}${text.slice(next.start)}`;
619
+ }
620
+ const prev = index > 0 ? spanOrNull(text, [...arrayPath, index - 1]) : null;
621
+ if (index > 0 && prev === null) throw new Error(`splicedEdits: ${arrayPath.join('.')} has no element ${index - 1}`);
622
+ const indent = prev !== null ? indentAt(text, prev.start) : `${indentAt(text, arr.start)} `;
623
+ const body = JSON.stringify(value, null, 2).split('\n').join(`\n${indent}`);
624
+ if (prev === null) return `${text.slice(0, arr.start + 1)}\n${indent}${body}\n${indentAt(text, arr.start)}${text.slice(arr.end - 1)}`;
625
+ return `${text.slice(0, prev.end)},\n${indent}${body}${text.slice(prev.end)}`;
626
+ }
627
+
586
628
  /** One edit on `text`; every byte it does not name is the input's. */
587
- function spliceOne(text: string, path: readonly string[], value: unknown): string {
629
+ function spliceOne(text: string, path: readonly (string | number)[], value: unknown, insert = false): string {
630
+ const step = path[path.length - 1];
631
+ if (insert) {
632
+ if (typeof step !== 'number') throw new Error(`splicedEdits: an insert names an array index; ${path.join('.')} does not`);
633
+ return insertElement(text, path.slice(0, -1), step, value);
634
+ }
588
635
  const at = spanOrNull(text, path);
589
636
  if (value === undefined) {
590
637
  if (at === null || at.key === undefined) return text;
@@ -594,6 +641,8 @@ function spliceOne(text: string, path: readonly string[], value: unknown): strin
594
641
  if (text[before] === ',') return `${text.slice(0, before)}${text.slice(at.end)}`;
595
642
  let after = at.end;
596
643
  while (after < text.length && /\s/.test(text[after])) after++;
644
+ // An array's only element: the brackets close on each other.
645
+ if (typeof step === 'number' && text[before] === '[' && text[after] === ']') return `${text.slice(0, before + 1)}${text.slice(after)}`;
597
646
  if (text[after] === ',') {
598
647
  after++;
599
648
  while (after < text.length && /\s/.test(text[after])) after++;
@@ -605,13 +654,14 @@ function spliceOne(text: string, path: readonly string[], value: unknown): strin
605
654
  const body = JSON.stringify(value, null, 2).split('\n').join(`\n${indentAt(text, at.start)}`);
606
655
  return `${text.slice(0, at.start)}${body}${text.slice(at.end)}`;
607
656
  }
657
+ if (typeof step === 'number') throw new Error(`splicedEdits: ${path.join('.')} names no element; an element is added by an insert`);
608
658
  const parentPath = path.slice(0, -1);
609
659
  const parent = spanOrNull(text, parentPath);
610
660
  // A parent the text lacks is inserted whole, holding this one member.
611
- if (parent === null) return spliceOne(text, parentPath, { [path[path.length - 1]]: value });
661
+ if (parent === null) return spliceOne(text, parentPath, { [step]: value });
612
662
  if (text[parent.start] !== '{') throw new Error(`splicedEdits: ${parentPath.join('.') || 'the document'} is not an object`);
613
663
  const indent = `${indentAt(text, parent.start)} `;
614
- const member = `"${path[path.length - 1]}": ${JSON.stringify(value, null, 2).split('\n').join(`\n${indent}`)}`;
664
+ const member = `"${step}": ${JSON.stringify(value, null, 2).split('\n').join(`\n${indent}`)}`;
615
665
  let last = parent.end - 2;
616
666
  while (last > parent.start && /\s/.test(text[last])) last--;
617
667
  if (last === parent.start) return `${text.slice(0, parent.start + 1)}\n${indent}${member}\n${indentAt(text, parent.start)}${text.slice(parent.end - 1)}`;
@@ -634,24 +684,35 @@ function firstMoved(got: unknown, want: unknown, path: readonly string[]): strin
634
684
  /**
635
685
  * The input's own text with each edit made in order: a value present is replaced, as `JSON.stringify(value, null, 2)`
636
686
  * indented to the line it starts on; one absent is inserted as the last member of its object (an absent parent
637
- * inserted with it); `undefined` removes the member. Every other byte is the input's. The result is parsed and held
687
+ * inserted with it); `undefined` removes the member. An index step addresses an array element (issue #552): replaced
688
+ * or removed in place, or, `insert`, put before that element on a line of its own at the neighbours' indent (after
689
+ * the last element at the array's length), and a removed element takes one comma beside it. Every other byte is the
690
+ * input's. The result is parsed and held
638
691
  * to the intended document — the input parsed with the same edits made on it — and `moved` names the first path
639
692
  * where it is not (a key the text states twice is the way it is not: the edit lands on the first, the parse keeps the
640
693
  * last); null when it is.
641
694
  */
642
695
  export function splicedEdits(text: string, edits: readonly ConfigEdit[]): { text: string; moved: string | null } {
643
696
  let out = text;
644
- for (const e of edits) out = spliceOne(out, e.path, e.value);
697
+ for (const e of edits) out = spliceOne(out, e.path, e.value, e.insert === true);
645
698
  const want = JSON.parse(text) as Record<string, unknown>;
646
699
  for (const e of edits) {
647
- let o = want;
700
+ let o: Record<string | number, unknown> | unknown[] = want;
648
701
  for (const k of e.path.slice(0, -1)) {
649
- if (typeof o[k] !== 'object' || o[k] === null) o[k] = {};
650
- o = o[k] as Record<string, unknown>;
702
+ const rec = o as Record<string | number, unknown>;
703
+ if (typeof rec[k] !== 'object' || rec[k] === null) rec[k] = {};
704
+ o = rec[k] as Record<string | number, unknown> | unknown[];
651
705
  }
652
706
  const last = e.path[e.path.length - 1];
653
- if (e.value === undefined) delete o[last];
654
- else o[last] = e.value;
707
+ if (Array.isArray(o) && typeof last === 'number') {
708
+ if (e.insert === true) o.splice(last, 0, e.value);
709
+ else if (e.value === undefined) o.splice(last, 1);
710
+ else o[last] = e.value;
711
+ } else {
712
+ const rec = o as Record<string | number, unknown>;
713
+ if (e.value === undefined) delete rec[last];
714
+ else rec[last] = e.value;
715
+ }
655
716
  }
656
717
  return { text: out, moved: firstMoved(JSON.parse(out), want, []) };
657
718
  }
package/src/remesh.ts CHANGED
@@ -61,14 +61,14 @@ import { createHash } from 'node:crypto';
61
61
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
62
62
  import { dirname, join, relative, resolve, sep } from 'node:path';
63
63
  import { checkStage, gateThroughRigc, type Log, RIGC_MODEL_DOCUMENT, rigStage } from './build.ts';
64
- import { barsNotMet, type CheckReport, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
64
+ import { barsNotMet, type CheckReport, checkStatuses, type CheckStatus, checkSummaryLine, DEFAULT_PACK_SHAPE, DEFAULT_PAGE_EDGES, type PackShape, type PageEdges, rigcRanClause, type RigcRunner } from './check.ts';
65
65
  import { loadConfigAndAnimations } from './config.ts';
66
66
  import { PartsError, type Problem, problemLine, refuseIfAny } from './errors.ts';
67
67
  import { jsonValueSpan, scratchConfig } from './meshdraft.ts';
68
68
  import { computeExactFrameTransforms } from './coords.ts';
69
69
  import { type PartsFile } from './parts.ts';
70
70
  import { applyMeshEdit, type DeltaApplied, type DeltaPlant, deltaSourceProblems, type MeshEditDocument, readMeshEdit } from './remeshdelta.ts';
71
- import { DEFAULT_IDLE_KEYS, type IdleKeys, type MeshAttachment, rigJsonText, type RigSpec } from './rig.ts';
71
+ import { DEFAULT_IDLE_KEYS, type IdleKeys, type MeshAttachment, meshBoundBones, rigJsonText, type RigSpec } from './rig.ts';
72
72
  import { pyRound } from './round.ts';
73
73
 
74
74
  /** The provenance file's spec. */
@@ -144,13 +144,21 @@ export interface MeshCounts {
144
144
  hull: number;
145
145
  }
146
146
 
147
- /** One side of the provenance's check block. */
147
+ /**
148
+ * One side of the provenance's check block. The first five fields are what the hold ({@link checkHeldProblems})
149
+ * reads; `line` and `status` (issue #541) are what `check` itself reports on the same tree — its last line, whole,
150
+ * and every block's status as `check.json` records it — so a consumer need not run `check` a second time.
151
+ */
148
152
  export interface CheckSide {
149
153
  pass: boolean;
150
154
  measured: string[];
151
155
  not_met: string[];
152
156
  skipped: Array<{ bar: string; reason: string }>;
153
157
  physics: string | null;
158
+ /** The last line `check` prints ({@link checkSummaryLine}), byte for byte. */
159
+ line: string;
160
+ /** Every block's status as `check.json` records it, in the file's order ({@link checkStatuses}). */
161
+ status: Record<string, CheckStatus>;
154
162
  }
155
163
 
156
164
  /** `remesh.json` (spec {@link REMESH_SPEC}). */
@@ -461,6 +469,8 @@ export function checkSide(r: CheckReport): CheckSide {
461
469
  not_met: barsNotMet(r.figures as unknown as Record<string, unknown>),
462
470
  skipped: r.bars.skipped.map((s) => ({ bar: s.bar, reason: s.reason })),
463
471
  physics: r.loopPhysics,
472
+ line: checkSummaryLine(r),
473
+ status: checkStatuses(r.figures),
464
474
  };
465
475
  }
466
476
 
@@ -555,7 +565,7 @@ const textsOf = (tree: FileTree): Array<readonly [string, string]> => [...tree].
555
565
 
556
566
  /**
557
567
  * The delta's `mesh_report.json` row (issue #526): the input's row, key for key, with `vertices`, `triangles`, `hull`,
558
- * `bones` (the sorted set the new weights name), `max_influences` and `mean_influences` recomputed from the new
568
+ * `bones` (the sorted set the new weights name, `meshBoundBones` — the reading every rig row takes), `max_influences` and `mean_influences` recomputed from the new
559
569
  * attachment and `mode` "delta" (in place, or last when the row had none). Every other key is the input's and
560
570
  * describes the mesh the delta was drawn over.
561
571
  */
@@ -566,7 +576,7 @@ export function deltaRow(row: Json, att: MeshAttachment): Json {
566
576
  vertices: n,
567
577
  triangles: att.triangles.length / 3,
568
578
  hull: att.hull,
569
- bones: [...new Set(att.weights.flatMap((w) => w.map((e) => e.bone)))].sort(),
579
+ bones: meshBoundBones(att),
570
580
  max_influences: Math.max(...att.weights.map((w) => w.length)),
571
581
  mean_influences: pyRound(entries / n, 2),
572
582
  mode: 'delta',
@@ -13,7 +13,7 @@
13
13
  * | outcome | when | what it does |
14
14
  * | --- | --- | --- |
15
15
  * | not declared | the file states no requirement of that kind | the summary names the kind; not a pass, not a skip |
16
- * | refused | a bone, constraint, mesh or animation does not resolve, a field or bar is missing, a `follow` names a property its constraint does not drive | refused by name before anything is built ({@link readRequirements}, {@link resolveRequirements}) |
16
+ * | refused | a bone, constraint, mesh or animation does not resolve, a field or bar is missing, a `follow` names a property its constraint does not drive, a `contact` is held against its own bone's same point or an `aim` against a point of its own bone (issue #540) | refused by name before anything is built ({@link readRequirements}, {@link resolveRequirements}) |
17
17
  * | not measurable | it reads and the rig builds, and the quantity is undefined in the frames | `NOT MEASURABLE — <why>`, with the figures; the run does not PASS |
18
18
  * | measured | otherwise | `PASS` or `FAIL` against the author's bar, with the figures and the worst frame |
19
19
  *
@@ -253,7 +253,9 @@ const EXCEPTION_ABSENT: Record<ExceptionList, string> = {
253
253
  * in `not_swinging` and in `rises` or `rests`;
254
254
  * which parts they are is read against parts.json and the rig by `check`),
255
255
  * each entry's every field and bar by name, a key the format does not read,
256
- * and a name used twice. Resolving the names against the rig is
256
+ * a name used twice, and a `contact` against its own bone and point or an
257
+ * `aim` at a point of its own bone (issue #540: each reads 0 by construction,
258
+ * or no line at all). Resolving the names against the rig is
257
259
  * {@link resolveRequirements}'s.
258
260
  */
259
261
  export function readRequirements(path: string): RequirementsFile {
@@ -274,6 +276,9 @@ export function readRequirements(path: string): RequirementsFile {
274
276
  const field = (object: string, detail: string): void => {
275
277
  problems.push({ code: 'REQUIREMENTS_FIELD', object, detail });
276
278
  };
279
+ const selfTarget = (label: string, detail: string): void => {
280
+ problems.push({ code: 'REQUIREMENTS_SELF_TARGET', object: `${label} field "target"`, detail });
281
+ };
277
282
  if (raw.spec !== REQUIREMENTS_SPEC) field(`${at} field "spec"`, `is ${JSON.stringify(raw.spec)}; ${JSON.stringify(REQUIREMENTS_SPEC)} is required`);
278
283
  for (const k of Object.keys(raw)) if (!['spec', 'fps', 'targets', 'requirements', ...EXCEPTION_LISTS, 'may_fold'].includes(k) && !freeKey(k, raw[k])) field(`${at} field "${k}"`, 'is not a field this format reads (spec, fps, targets, requirements, not_planted, not_swinging, rises, rests, may_fold; note or *_note as a string; x-<name> as a record)');
279
284
  let fps = NaN;
@@ -331,6 +336,11 @@ export function readRequirements(path: string): RequirementsFile {
331
336
  let req: Requirement;
332
337
  if (kind === 'contact') {
333
338
  req = { ...common, kind, bone: str('bone'), point: point('point', r.point), target: target(), within_px: bar('within_px', (v) => v >= 0, 'a distance in stage px, 0 or more,') };
339
+ // Issue #540: a point against itself is 0 apart on every frame; the bone's other point is a reading (its length).
340
+ if ('bone' in req.target && req.bone.length > 0 && req.target.bone === req.bone && req.target.point === req.point) {
341
+ const other = req.point === 'tip' ? 'origin' : 'tip';
342
+ selfTarget(label, `contact of bone "${req.bone}" ${req.point} against bone "${req.target.bone}" ${req.target.point}, the same point: it measures 0 by construction, so a PASS says nothing — a different bone is required, or the bone's other point ("${other}")`);
343
+ }
334
344
  } else if (kind === 'follow') {
335
345
  const type = r.constraint_type;
336
346
  if (type !== 'ik' && type !== 'transform') field(`${label} field "constraint_type"`, `is ${JSON.stringify(type)}; "ik" or "transform" is required — a constraint resolves by name AND type, as in rig-c`);
@@ -349,6 +359,11 @@ export function readRequirements(path: string): RequirementsFile {
349
359
  };
350
360
  } else if (kind === 'aim') {
351
361
  req = { ...common, kind, bone: str('bone'), target: target(), within_degrees: bar('within_degrees', (v) => v >= 0 && v <= 180, 'an angle in degrees from 0 to 180') };
362
+ // Issue #540: the aimed bone's own tip lies on its axis (0 degrees on every frame) and its own origin gives no line at all.
363
+ if ('bone' in req.target && req.bone.length > 0 && req.target.bone === req.bone) {
364
+ const why = req.target.point === 'tip' ? 'its tip lies on its own axis, so the angle measures 0 by construction and a PASS says nothing' : 'its origin is where the line starts, so there is no line to aim along on any frame and nothing is measured';
365
+ selfTarget(label, `aim of bone "${req.bone}" axis against bone "${req.target.bone}" ${req.target.point}, a point of the aimed bone itself: ${why} — a different bone or a stage point is required`);
366
+ }
352
367
  } else if (kind === 'range') {
353
368
  const lo = bar('lo_degrees', () => true, 'an angle in degrees');
354
369
  const hi = bar('hi_degrees', () => true, 'an angle in degrees');
package/src/rig.ts CHANGED
@@ -766,6 +766,16 @@ export type RigCommand = 'rig' | 'build';
766
766
  /** The `why` of the `invariants.idleDrivesMeshes` that `idleKeys: 'direct'` declares. */
767
767
  export const IDLE_DRIVES_MESHES_WHY = 'painting rig: the idle is meant to deform the meshes it keys (rig-parts rig --idle-keys direct)';
768
768
 
769
+ /**
770
+ * The bones a mesh attachment binds: the sorted set of bone names its weights name (issue #536). Every
771
+ * `mesh_report.json` row's `bones` is this reading of the attachment the written `rig.json` holds — after the turn's
772
+ * twins and the stops' drawn links have taken their bones' places — so the row names what the emitted model binds in
773
+ * every mode; `remesh --delta`'s row (`deltaRow`, `src/remesh.ts`) takes the same function.
774
+ */
775
+ export function meshBoundBones(att: Pick<MeshAttachment, 'weights'>): string[] {
776
+ return [...new Set(att.weights.flatMap((w) => w.map((e) => e.bone)))].sort();
777
+ }
778
+
769
779
  /** One row of `mesh_report.json`: a lattice mesh's row is as it always was; a contour mesh's says so. */
770
780
  export type MeshReport = LatticeMeshReport | ContourMeshReport | AutoMeshReport | InfluenceMeshReport;
771
781
 
@@ -2544,6 +2554,12 @@ export function buildRig(
2544
2554
  // Only when the config has `turn`: every other build adds nothing here, so no byte moves.
2545
2555
  if (cfg.turn !== undefined) refuseIfAny(turnRiderProblems(cfg.turn, cfg, parts.parts));
2546
2556
  const turned = cfg.turn === undefined ? null : applyTurn(cfg.turn, parts.parts.map((p) => p.name), bones, slots, skin, cfg.constraints ?? []);
2557
+ // issue #536: every row names the bones the emitted attachment binds, read once the turn and the stops have
2558
+ // rebound the weights; a rig with neither rebinds nothing, so this reads back the names each row already holds.
2559
+ for (const row of meshReport) {
2560
+ const att = skin[row.part]?.[row.part];
2561
+ if (att !== undefined && 'type' in att) row.bones = meshBoundBones(att);
2562
+ }
2547
2563
 
2548
2564
  const name = `${cfg.key}_painting`;
2549
2565
  const rig: RigSpec = {