rig-parts 2.72.0 → 2.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/check.ts CHANGED
@@ -13,6 +13,7 @@ import { BEHIND_SEAM_LINE, behindTurnAnimations, measureBehindSeams, type Behind
13
13
  import { hasSourceStateMaps, measureSourceExposure, readSourceStateMaps, SOURCE_EXPOSURE_LINE, type SourceExposureMeasured } from './sourceexposure.ts';
14
14
  import { baseAnchorMoves, type AnchorRegion } from './baseanchor.ts';
15
15
  import { PHYSICS_CONTRIBUTES_LINE, measurePhysicsContribution, physicsLine, type PhysicsContributionLine } from './physicscontrib.ts';
16
+ import { FORCE_PHYSICS_TRACK_PROPERTIES, isSceneBoneProperty, UNSCALED_PHYSICS_TRACK_PROPERTIES } from './sceneclips.ts';
16
17
  /**
17
18
  * The check stage: build a rig through rig-c, gate it under both
18
19
  * profiles, render its idle, and measure the two things the gate cannot see —
@@ -652,12 +653,45 @@ export const NO_PARTS_SENTENCE = 'without --parts, a rig directory holding no pa
652
653
  */
653
654
  export const SOURCE_SENTENCE = '--source names the painting the rig was made from: the stage size itself, or any size assemble takes to the stage (width and height each the painting\'s times one rig_scale, truncated — parts.json\'s scale_rig_per_source when parts.json is read), resampled onto the stage as assemble resamples it (lanczos3, alpha dropped)';
654
655
 
656
+ const PLACEMENT_BONE_NAME = 'placement';
657
+
655
658
  /** The painting `--source` names, read and checked against the stage before anything is built. */
656
659
  export interface SourceInput {
657
660
  path: string;
658
661
  painting: Raster;
659
662
  }
660
663
 
664
+ /** Prefixed part exceptions forwarded from one character build's hash-bound `check/check.json` (issue #1679). */
665
+ export interface ComposedCharacterForwardedExceptions {
666
+ build: string;
667
+ not_swinging: string[];
668
+ rises: string[];
669
+ rests: string[];
670
+ not_planted: string[];
671
+ }
672
+
673
+ /** One character's manifest bound to a composed rig for `check`. */
674
+ export interface ComposedCharacterInput {
675
+ id: string;
676
+ partsHome: string;
677
+ offset: [number, number];
678
+ scale: number;
679
+ source?: string;
680
+ forwardedExceptions?: ComposedCharacterForwardedExceptions;
681
+ }
682
+
683
+ export interface ResolvedComposedCharacter {
684
+ id: string;
685
+ partsHome: string;
686
+ partsPath: string;
687
+ partsDir: string;
688
+ parts: PartsFile;
689
+ offset: [number, number];
690
+ scale: number;
691
+ source: SourceInput | null;
692
+ forwardedExceptions?: ComposedCharacterForwardedExceptions;
693
+ }
694
+
661
695
  export interface CheckInputs {
662
696
  rigDir: string;
663
697
  rigPath: string;
@@ -668,7 +702,7 @@ export interface CheckInputs {
668
702
  motion: Record<string, unknown>;
669
703
  /** Null when the rig directory holds no `parts.json` and no `--parts` was named (issue #77); {@link noParts} says why. */
670
704
  parts: PartsFile | null;
671
- /** Why `parts` is null, as the SKIP lines say it; null when `parts.json` was read. */
705
+ /** Why `parts` is null, as the SKIP lines say it; null when `parts.json` or `composedCharacters` was read. */
672
706
  noParts: string | null;
673
707
  stage: StageBox;
674
708
  rootBone: string;
@@ -678,6 +712,8 @@ export interface CheckInputs {
678
712
  noIdle: string | null;
679
713
  /** The painting `--source` named, or null without `--source`. */
680
714
  source: SourceInput | null;
715
+ /** Character manifests bound against a composed rig (issue #1679). */
716
+ composedCharacters?: ResolvedComposedCharacter[];
681
717
  }
682
718
 
683
719
  /** The inputs every line that reads both the parts and the idle takes: both present. */
@@ -735,9 +771,100 @@ function readJson(path: string, problems: Problem[]): Record<string, unknown> |
735
771
  * duration. `sourcePath` is `--source`, read and held to the stage here, so a
736
772
  * painting that is not this rig's is refused before anything is built.
737
773
  */
738
- export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?: string, set?: string, allSets = false): CheckInputs {
774
+ function validatePartsHomePngs(home: string, parts: PartsFile, problems: Problem[], prefixLabel = ''): void {
775
+ const who = (label: string): string => prefixLabel === '' ? label : `${prefixLabel} ${label}`;
776
+ for (const p of parts.parts) {
777
+ const png = join(home, partImageReference(p).path);
778
+ if (!existsSync(png)) {
779
+ problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: who(`part "${p.name}"`), detail: `${png} does not exist; parts.json lists it` });
780
+ continue;
781
+ }
782
+ const im = readPng(png);
783
+ if (im.width !== p.w || im.height !== p.h) {
784
+ problems.push({ code: 'CHECK_PART_PNG_MATCHES_BOX', object: who(`part "${p.name}"`), detail: `${png} is ${im.width}x${im.height}; parts.json's box is ${p.w}x${p.h}` });
785
+ }
786
+ }
787
+ for (const alt of parts.alternates ?? []) {
788
+ for (const r of alt.records) {
789
+ const png = join(home, partImageReference(r, alt.name).path);
790
+ if (!existsSync(png)) {
791
+ problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: who(`set "${alt.name}" part "${r.name}"`), detail: `${png} does not exist; parts.json lists it` });
792
+ continue;
793
+ }
794
+ const im = readPng(png);
795
+ if (im.width !== r.w || im.height !== r.h) {
796
+ problems.push({ code: 'CHECK_PART_PNG_MATCHES_BOX', object: who(`set "${alt.name}" part "${r.name}"`), detail: `${png} is ${im.width}x${im.height}; parts.json's box is ${r.w}x${r.h}` });
797
+ }
798
+ }
799
+ }
800
+ }
801
+
802
+ function resolveStandaloneComposedCharacter(
803
+ rigDir: string,
804
+ home: string,
805
+ slots: ReadonlySet<string>,
806
+ stage: StageBox | null,
807
+ parts: PartsFile,
808
+ problems: Problem[],
809
+ ): { id: string; offset: [number, number]; scale: number } | null {
810
+ if (parts.parts.length === 0 || parts.parts.every(p => slots.has(p.name))) return null;
811
+ const sceneReportPath = join(dirname(rigDir), 'scene.json');
812
+ if (existsSync(sceneReportPath) && statSync(sceneReportPath).isFile()) {
813
+ try {
814
+ const raw: unknown = JSON.parse(readFileSync(sceneReportPath, 'utf8'));
815
+ if (isRecord(raw) && (raw.spec === 'spine-parts-scene-report/1' || raw.spec === 'spine-parts-scene-report/2') && Array.isArray(raw.characters)) {
816
+ const rows = raw.characters.filter(isRecord).filter(row =>
817
+ typeof row.id === 'string' && Array.isArray(row.offset) && row.offset.length === 2 &&
818
+ typeof row.offset[0] === 'number' && typeof row.offset[1] === 'number' &&
819
+ Array.isArray(row.rig_size) && row.rig_size[0] === parts.rig_size[0] && row.rig_size[1] === parts.rig_size[1] &&
820
+ parts.parts.every(p => slots.has(`${String(row.id)}:${p.name}`)));
821
+ let matched = rows;
822
+ if (matched.length > 1) {
823
+ const sceneDir = typeof raw.scene === 'string' ? dirname(resolve(process.cwd(), raw.scene)) : dirname(rigDir);
824
+ const byBuild = matched.filter(row => typeof row.build === 'string' &&
825
+ (resolve(sceneDir, row.build) === home || resolve(dirname(rigDir), row.build) === home));
826
+ if (byBuild.length === 1) matched = byBuild;
827
+ }
828
+ if (matched.length === 1) {
829
+ const hit = matched[0];
830
+ return {
831
+ id: String(hit.id),
832
+ offset: [Number((hit.offset as unknown[])[0]), Number((hit.offset as unknown[])[1])],
833
+ scale: typeof hit.scale === 'number' && Number.isFinite(hit.scale) && hit.scale > 0 ? hit.scale : 1,
834
+ };
835
+ }
836
+ if (matched.length > 1) {
837
+ problems.push({
838
+ code: 'CHECK_PART_SLOT_PRESENT',
839
+ object: home,
840
+ detail: `matches ${matched.length} characters in ${sceneReportPath} (${matched.map(r => `"${String(r.id)}"`).join(', ')}); give the character's own build directory so its id, offset and scale resolve uniquely`,
841
+ });
842
+ return null;
843
+ }
844
+ }
845
+ } catch { /* Fall through to slot-prefix check below. */ }
846
+ }
847
+ const suffix = `:${parts.parts[0].name}`;
848
+ const prefixes = [...slots].filter((s): s is string => typeof s === 'string' && s.endsWith(suffix))
849
+ .map(s => s.slice(0, -suffix.length))
850
+ .filter(id => id.length > 0 && parts.parts.every(p => slots.has(`${id}:${p.name}`)));
851
+ if (prefixes.length === 1 && stage !== null && stage.width === parts.rig_size[0] && stage.height === parts.rig_size[1]) {
852
+ return { id: prefixes[0], offset: [0, 0], scale: 1 };
853
+ }
854
+ return null;
855
+ }
856
+
857
+ export function readCheckInputs(
858
+ rigDir: string,
859
+ partsHome?: string,
860
+ sourcePath?: string,
861
+ set?: string,
862
+ allSets = false,
863
+ characters?: readonly ComposedCharacterInput[],
864
+ ): CheckInputs {
739
865
  const dir = resolve(rigDir);
740
- const named = partsHome !== undefined;
866
+ const hasComposedList = characters !== undefined && characters.length > 0;
867
+ const named = !hasComposedList && partsHome !== undefined;
741
868
  const home = resolve(partsHome ?? rigDir);
742
869
  const problems: Problem[] = [];
743
870
  if (!existsSync(dir) || !statSync(dir).isDirectory()) {
@@ -747,61 +874,37 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
747
874
  const motionPath = join(dir, 'motion.json');
748
875
  const partsPath = join(home, 'parts.json');
749
876
  const partsDir = join(home, 'parts');
750
- if (home !== dir && (!existsSync(home) || !statSync(home).isDirectory())) {
877
+ if (!hasComposedList && home !== dir && (!existsSync(home) || !statSync(home).isDirectory())) {
751
878
  refuseIfAny([{ code: 'CHECK_INPUT_PRESENT', object: home, detail: `is not a directory; ${PARTS_HOME_SENTENCE}` }]);
752
879
  }
753
880
  const rig = readJson(rigPath, problems);
754
881
  const motion = readJson(motionPath, problems);
755
882
  let parts: PartsFile | null = null;
756
883
  let noParts: string | null = null;
757
- if (!existsSync(partsPath)) {
758
- // The usual miss is passing parts/ itself, or leaving --parts off after build; the parent is then named.
759
- const parent = dirname(home);
760
- const parentHolds = existsSync(join(parent, 'parts.json'));
761
- if (named || parentHolds) {
762
- const hint = parentHolds ? ` — ${parent} holds parts.json, so --parts ${parent} is the directory meant` : '';
763
- problems.push({
764
- code: 'CHECK_INPUT_PRESENT',
765
- object: partsPath,
766
- detail: `no such file; ${PARTS_HOME_SENTENCE} (the seam check composites the parts parts.json lists)${hint}`,
767
- });
768
- } else noParts = 'no parts.json: parts.json does not exist and no --parts was named, so there are no parts to composite and no See-through tags to choose regions by';
769
- }
770
- else {
771
- try {
772
- parts = readParts(partsPath);
773
- } catch (err) {
774
- if (err instanceof PartsError) problems.push(...err.problems);
775
- else throw err;
776
- }
777
- }
778
- if (parts !== null) {
779
- for (const p of parts.parts) {
780
- const png = join(home, partImageReference(p).path);
781
- if (!existsSync(png)) {
782
- problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: `part "${p.name}"`, detail: `${png} does not exist; parts.json lists it` });
783
- continue;
784
- }
785
- const im = readPng(png);
786
- if (im.width !== p.w || im.height !== p.h) {
787
- problems.push({ code: 'CHECK_PART_PNG_MATCHES_BOX', object: `part "${p.name}"`, detail: `${png} is ${im.width}x${im.height}; parts.json's box is ${p.w}x${p.h}` });
788
- }
789
- }
790
- for (const alt of parts.alternates ?? []) {
791
- for (const r of alt.records) {
792
- const png = join(home, partImageReference(r, alt.name).path);
793
- if (!existsSync(png)) {
794
- problems.push({ code: 'CHECK_PART_PNG_PRESENT', object: `set "${alt.name}" part "${r.name}"`, detail: `${png} does not exist; parts.json lists it` });
795
- continue;
796
- }
797
- const im = readPng(png);
798
- if (im.width !== r.w || im.height !== r.h) {
799
- problems.push({ code: 'CHECK_PART_PNG_MATCHES_BOX', object: `set "${alt.name}" part "${r.name}"`, detail: `${png} is ${im.width}x${im.height}; parts.json's box is ${r.w}x${r.h}` });
800
- }
884
+ if (!hasComposedList) {
885
+ if (!existsSync(partsPath)) {
886
+ // The usual miss is passing parts/ itself, or leaving --parts off after build; the parent is then named.
887
+ const parent = dirname(home);
888
+ const parentHolds = existsSync(join(parent, 'parts.json'));
889
+ if (named || parentHolds) {
890
+ const hint = parentHolds ? ` — ${parent} holds parts.json, so --parts ${parent} is the directory meant` : '';
891
+ problems.push({
892
+ code: 'CHECK_INPUT_PRESENT',
893
+ object: partsPath,
894
+ detail: `no such file; ${PARTS_HOME_SENTENCE} (the seam check composites the parts parts.json lists)${hint}`,
895
+ });
896
+ } else noParts = 'no parts.json: parts.json does not exist and no --parts was named, so there are no parts to composite and no See-through tags to choose regions by';
897
+ } else {
898
+ try {
899
+ parts = readParts(partsPath);
900
+ } catch (err) {
901
+ if (err instanceof PartsError) problems.push(...err.problems);
902
+ else throw err;
801
903
  }
802
904
  }
905
+ if (parts !== null) validatePartsHomePngs(home, parts, problems);
803
906
  }
804
- if (set !== undefined || allSets) {
907
+ if (!hasComposedList && (set !== undefined || allSets)) {
805
908
  if (parts === null) {
806
909
  problems.push({
807
910
  code: 'CHECK_INPUT_PRESENT',
@@ -827,6 +930,8 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
827
930
  }
828
931
  let stage: StageBox | null = null;
829
932
  let rootBone: string | null = null;
933
+ let standaloneComposed: { id: string; offset: [number, number]; scale: number } | null = null;
934
+ const slots = new Set((rig !== null && Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord).map((s) => String(s.name)));
830
935
  if (rig !== null) {
831
936
  const s = rig.skeleton;
832
937
  const nums = isRecord(s) && ['x', 'y', 'width', 'height'].every((k) => typeof s[k] === 'number' && Number.isFinite(s[k]));
@@ -834,24 +939,27 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
834
939
  problems.push({ code: 'CHECK_RIG_STAGE_PRESENT', object: `${rigPath} field "skeleton"`, detail: `is ${JSON.stringify(s)}; the stage box { x, y, width, height } is required — it is where parts.json's crop pixels sit in Spine's world` });
835
940
  } else {
836
941
  stage = { x: s.x as number, y: s.y as number, width: s.width as number, height: s.height as number };
837
- if (parts !== null && (stage.width !== parts.rig_size[0] || stage.height !== parts.rig_size[1])) {
838
- problems.push({
839
- code: 'CHECK_RIG_STAGE_IS_THE_CANVAS',
840
- object: `${rigPath} field "skeleton"`,
841
- detail: `is ${stage.width}x${stage.height}; parts.json's rig_size is ${parts.rig_size[0]}x${parts.rig_size[1]}, and the seam compares the two pixel for pixel`,
842
- });
843
- }
844
942
  }
845
- const slots = new Set((Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord).map((s) => s.name));
846
- if (parts !== null) {
847
- for (const p of parts.parts) {
848
- if (!slots.has(p.name)) {
943
+ if (!hasComposedList && parts !== null) {
944
+ const problemsBefore = problems.length;
945
+ standaloneComposed = resolveStandaloneComposedCharacter(dir, home, slots, stage, parts, problems);
946
+ if (standaloneComposed === null && problems.length === problemsBefore) {
947
+ if (stage !== null && (stage.width !== parts.rig_size[0] || stage.height !== parts.rig_size[1])) {
849
948
  problems.push({
850
- code: 'CHECK_PART_SLOT_PRESENT',
851
- object: `part "${p.name}"`,
852
- detail: `${rigPath} has no slot named "${p.name}"; the rig stage draws every part by the slot of its own name, and the judgement lines render a part alone by that slot`,
949
+ code: 'CHECK_RIG_STAGE_IS_THE_CANVAS',
950
+ object: `${rigPath} field "skeleton"`,
951
+ detail: `is ${stage.width}x${stage.height}; parts.json's rig_size is ${parts.rig_size[0]}x${parts.rig_size[1]}, and the seam compares the two pixel for pixel`,
853
952
  });
854
953
  }
954
+ for (const p of parts.parts) {
955
+ if (!slots.has(p.name)) {
956
+ problems.push({
957
+ code: 'CHECK_PART_SLOT_PRESENT',
958
+ object: `part "${p.name}"`,
959
+ detail: `${rigPath} has no slot named "${p.name}"; the rig stage draws every part by the slot of its own name, and the judgement lines render a part alone by that slot`,
960
+ });
961
+ }
962
+ }
855
963
  }
856
964
  }
857
965
  const bones = rig.bones;
@@ -859,6 +967,88 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
859
967
  if (isRecord(first) && typeof first.name === 'string') rootBone = first.name;
860
968
  else problems.push({ code: 'CHECK_RIG_ROOT_BONE', object: `${rigPath} field "bones"`, detail: 'has no first bone with a name; the setup-pose render keys the root bone' });
861
969
  }
970
+ const composedCharacters: ResolvedComposedCharacter[] = [];
971
+ const readSourceFor = (givenPath: string | undefined, targetStage: StageBox | null, rigScale: number | null): SourceInput | null => {
972
+ if (givenPath === undefined) return null;
973
+ const path = resolve(givenPath);
974
+ let out: SourceInput | null = null;
975
+ if (!existsSync(path) || !statSync(path).isFile()) {
976
+ problems.push({ code: 'CHECK_INPUT_PRESENT', object: path, detail: `no such file; ${SOURCE_SENTENCE}` });
977
+ } else {
978
+ try {
979
+ out = { path, painting: readPng(path) };
980
+ } catch (err) {
981
+ problems.push({ code: 'CHECK_SOURCE_PNG', object: path, detail: `does not read as a PNG: ${(err as Error).message.split('\n')[0]}; ${SOURCE_SENTENCE}` });
982
+ }
983
+ }
984
+ if (out !== null && targetStage !== null) {
985
+ const why = sourceSizeProblem(out.painting.width, out.painting.height, targetStage, rigScale);
986
+ if (why !== null) problems.push({ code: 'CHECK_SOURCE_SIZE', object: `--source ${path}`, detail: why });
987
+ }
988
+ return out;
989
+ };
990
+ if (hasComposedList) {
991
+ for (const c of characters!) {
992
+ const cHome = resolve(c.partsHome);
993
+ const cPartsPath = join(cHome, 'parts.json');
994
+ const cPartsDir = join(cHome, 'parts');
995
+ let cParts: PartsFile | null = null;
996
+ if (!existsSync(cHome) || !statSync(cHome).isDirectory()) {
997
+ problems.push({ code: 'CHECK_INPUT_PRESENT', object: cHome, detail: `is not a directory; ${PARTS_HOME_SENTENCE}` });
998
+ continue;
999
+ }
1000
+ if (!existsSync(cPartsPath)) {
1001
+ problems.push({ code: 'CHECK_INPUT_PRESENT', object: cPartsPath, detail: `no such file; ${PARTS_HOME_SENTENCE}` });
1002
+ continue;
1003
+ }
1004
+ try {
1005
+ cParts = readParts(cPartsPath);
1006
+ } catch (err) {
1007
+ if (err instanceof PartsError) problems.push(...err.problems);
1008
+ else throw err;
1009
+ }
1010
+ if (cParts === null) continue;
1011
+ validatePartsHomePngs(cHome, cParts, problems, `character "${c.id}"`);
1012
+ for (const p of cParts.parts) {
1013
+ const slotName = `${c.id}:${p.name}`;
1014
+ if (rig !== null && !slots.has(slotName)) {
1015
+ problems.push({
1016
+ code: 'CHECK_PART_SLOT_PRESENT',
1017
+ object: `character "${c.id}" part "${p.name}"`,
1018
+ detail: `${rigPath} has no slot named "${slotName}"; composed check resolves each character's parts under "<id>:<part>"`,
1019
+ });
1020
+ }
1021
+ }
1022
+ const charOrigStage: StageBox = { x: -cParts.rig_size[0] / 2, y: 0, width: cParts.rig_size[0], height: cParts.rig_size[1] };
1023
+ const cSource = readSourceFor(c.source, charOrigStage, cParts.scale_rig_per_source);
1024
+ composedCharacters.push({
1025
+ id: c.id,
1026
+ partsHome: cHome,
1027
+ partsPath: cPartsPath,
1028
+ partsDir: cPartsDir,
1029
+ parts: cParts,
1030
+ offset: [c.offset[0], c.offset[1]],
1031
+ scale: c.scale,
1032
+ source: cSource,
1033
+ ...(c.forwardedExceptions === undefined ? {} : { forwardedExceptions: c.forwardedExceptions }),
1034
+ });
1035
+ }
1036
+ } else if (standaloneComposed !== null && parts !== null) {
1037
+ const charOrigStage: StageBox = { x: -parts.rig_size[0] / 2, y: 0, width: parts.rig_size[0], height: parts.rig_size[1] };
1038
+ const cSource = readSourceFor(sourcePath, charOrigStage, parts.scale_rig_per_source);
1039
+ composedCharacters.push({
1040
+ id: standaloneComposed.id,
1041
+ partsHome: home,
1042
+ partsPath,
1043
+ partsDir,
1044
+ parts,
1045
+ offset: standaloneComposed.offset,
1046
+ scale: standaloneComposed.scale,
1047
+ source: cSource,
1048
+ });
1049
+ parts = null;
1050
+ noParts = null;
1051
+ }
862
1052
  let idleDuration: number | null = null;
863
1053
  let noIdle: string | null = null;
864
1054
  if (motion !== null) {
@@ -872,23 +1062,9 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
872
1062
  problems.push({ code: 'CHECK_IDLE_PRESENT', object: `${motionPath} animation "idle" field "duration"`, detail: `is ${JSON.stringify(idle.duration)}; a positive number of seconds is required` });
873
1063
  } else idleDuration = idle.duration;
874
1064
  }
875
- let source: SourceInput | null = null;
876
- if (sourcePath !== undefined) {
877
- const path = resolve(sourcePath);
878
- if (!existsSync(path) || !statSync(path).isFile()) {
879
- problems.push({ code: 'CHECK_INPUT_PRESENT', object: path, detail: `no such file; ${SOURCE_SENTENCE}` });
880
- } else {
881
- try {
882
- source = { path, painting: readPng(path) };
883
- } catch (err) {
884
- problems.push({ code: 'CHECK_SOURCE_PNG', object: path, detail: `does not read as a PNG: ${(err as Error).message.split('\n')[0]}; ${SOURCE_SENTENCE}` });
885
- }
886
- }
887
- if (source !== null && stage !== null) {
888
- const why = sourceSizeProblem(source.painting.width, source.painting.height, stage, parts === null ? null : parts.scale_rig_per_source);
889
- if (why !== null) problems.push({ code: 'CHECK_SOURCE_SIZE', object: `--source ${path}`, detail: why });
890
- }
891
- }
1065
+ const source: SourceInput | null = hasComposedList || standaloneComposed !== null
1066
+ ? null
1067
+ : readSourceFor(sourcePath, stage, parts === null ? null : parts.scale_rig_per_source);
892
1068
  refuseIfAny(problems);
893
1069
  return {
894
1070
  rigDir: dir,
@@ -905,6 +1081,7 @@ export function readCheckInputs(rigDir: string, partsHome?: string, sourcePath?:
905
1081
  idleDuration,
906
1082
  noIdle,
907
1083
  source,
1084
+ ...(composedCharacters.length === 0 ? {} : { composedCharacters }),
908
1085
  };
909
1086
  }
910
1087
 
@@ -1936,6 +2113,15 @@ export function rigToFrameMap(stage: StageBox, rigH: number, vp: Viewport, centr
1936
2113
  return { sx: f(s), sy: f(s), tx: f((stage.x - vp.x) * s + c), ty: f((vp.y + vp.height - (stage.y + cropToSpineY(0, rigH))) * s + c) };
1937
2114
  }
1938
2115
 
2116
+ /** {@link rigToFrameMap} for a character placed on a composed canvas at `charScale`. Identical to {@link rigToFrameMap} at `charScale === 1`. */
2117
+ export function placedRigToFrameMap(stage: StageBox, rigH: number, vp: Viewport, charScale = 1, centres = true): ScaleTranslate {
2118
+ if (charScale === 1) return rigToFrameMap(stage, rigH, vp, centres);
2119
+ const eff = charScale * vp.scale;
2120
+ const f = Math.fround;
2121
+ const c = centres ? 0.5 * (eff - 1) : 0;
2122
+ return { sx: f(eff), sy: f(eff), tx: f((stage.x - vp.x) * vp.scale + c), ty: f((vp.y + vp.height - (stage.y + cropToSpineY(0, charScale * rigH))) * vp.scale + c) };
2123
+ }
2124
+
1939
2125
  /**
1940
2126
  * {@link rigToFrameMap} turned round, from frame pixel indices to rig pixel
1941
2127
  * indices: u = (frame - t - 0.5 (s - 1)) / s, rounded to float32 as the
@@ -1948,6 +2134,20 @@ export function frameToRigMap(stage: StageBox, rigH: number, vp: Viewport): Scal
1948
2134
  return { sx: f(1 / s), sy: f(1 / s), tx: f(vp.x - stage.x - c / s), ty: f(stage.y + cropToSpineY(0, rigH) - (vp.y + vp.height) - c / s) };
1949
2135
  }
1950
2136
 
2137
+ /** {@link frameToRigMap} for a character placed on a composed canvas at `charScale`. */
2138
+ export function placedFrameToRigMap(stage: StageBox, rigH: number, vp: Viewport, charScale = 1): ScaleTranslate {
2139
+ if (charScale === 1) return frameToRigMap(stage, rigH, vp);
2140
+ const eff = charScale * vp.scale;
2141
+ const f = Math.fround;
2142
+ const c = 0.5 * (eff - 1);
2143
+ return {
2144
+ sx: f(1 / eff),
2145
+ sy: f(1 / eff),
2146
+ tx: f((vp.x - stage.x) / charScale - c / eff),
2147
+ ty: f((stage.y + cropToSpineY(0, charScale * rigH) - (vp.y + vp.height)) / charScale - c / eff),
2148
+ };
2149
+ }
2150
+
1951
2151
  /**
1952
2152
  * The seam figures: the setup-pose frame vs the flat composite carried onto the
1953
2153
  * frame's pixel grid.
@@ -2457,8 +2657,8 @@ function canonicalDenominator(seam: SeamFigures): number {
2457
2657
  return denominator;
2458
2658
  }
2459
2659
 
2460
- function seamReading(seam: SeamFigures, viewport: Viewport): SeamReading {
2461
- return { mean: seam.mean, display_mean: round3(seam.mean), denominator_px: seam.denominator ?? viewport.pixelWidth * viewport.pixelHeight - (seam.border?.framePx ?? 0), px_over_40: seam.over40, px_over_80: seam.over80, frame_scale: viewport.scale, viewport };
2660
+ function seamReading(seam: SeamFigures, viewport: Viewport, charScale = 1): SeamReading {
2661
+ return { mean: seam.mean, display_mean: round3(seam.mean), denominator_px: seam.denominator ?? viewport.pixelWidth * viewport.pixelHeight - (seam.border?.framePx ?? 0), px_over_40: seam.over40, px_over_80: seam.over80, frame_scale: charScale === 1 ? viewport.scale : round6(charScale * viewport.scale), viewport };
2462
2662
  }
2463
2663
 
2464
2664
  /**
@@ -2838,7 +3038,7 @@ export function blackRig(rig: Record<string, unknown>): Record<string, unknown>
2838
3038
  * #209), through the same bilinear `warpAffine` in float32, the border reading
2839
3039
  * as no art; then rounded to 8 bits, as assemble's composite is.
2840
3040
  */
2841
- export function sourceFigures(open: Raster, black: Raster, vp: Viewport, background: readonly [number, number, number, number], stage: StageBox, srcr: Raster): RecompositeFigures {
3041
+ export function sourceFigures(open: Raster, black: Raster, vp: Viewport, background: readonly [number, number, number, number], stage: StageBox, srcr: Raster, map?: ScaleTranslate): RecompositeFigures {
2842
3042
  const problems: Problem[] = [];
2843
3043
  for (const [label, f] of [['the setup-pose frame', open], ['the black-tinted setup-pose frame', black]] as const) {
2844
3044
  if (f.width !== vp.pixelWidth || f.height !== vp.pixelHeight) problems.push({ code: 'CHECK_SOURCE_GRID', object: label, detail: `is ${f.width}x${f.height}; frames.json's viewport is ${vp.pixelWidth}x${vp.pixelHeight}` });
@@ -2862,7 +3062,7 @@ export function sourceFigures(open: Raster, black: Raster, vp: Viewport, backgro
2862
3062
  ink.data[p * 4 + 3] = 255 * (1 - Math.min(1, through));
2863
3063
  }
2864
3064
  // The seam's map turned round, centre to centre (issue #209).
2865
- const warped = warpAffine(ink, frameToRigMap(stage, H, vp), W, H, 'bilinear');
3065
+ const warped = warpAffine(ink, map ?? frameToRigMap(stage, H, vp), W, H, 'bilinear');
2866
3066
  const to8 = (v: number): number => Math.min(255, Math.max(0, Math.round(v)));
2867
3067
  const can = newRaster(W, H);
2868
3068
  const cover = newRaster(W, H);
@@ -2901,7 +3101,7 @@ export function sourceLine(fig: RecompositeFigures, painting: Raster, stage: Sta
2901
3101
  // ---------------------------------------------------------------------------
2902
3102
 
2903
3103
  /** One judgement line (issue #11): its status, the figures it measured, and the bars it held them to — or why it measured nothing. */
2904
- export type JudgementLine = { status: 'PASS' | 'FAIL'; [figure: string]: unknown } | { status: 'SKIP'; reason: string };
3104
+ export type JudgementLine = { status: 'PASS' | 'FAIL'; [figure: string]: unknown } | { status: 'SKIP'; reason: string; [figure: string]: unknown };
2905
3105
 
2906
3106
  /** The judgement lines, in the order check.json and the console carry them. */
2907
3107
  export const JUDGEMENT_LINES = ['BREATH_VISIBLE', 'BLINK_NO_HOLE', 'CHAIN_LAG', 'TIP_OVER_ROOT', 'STILL_REGIONS_DARK', 'TEXTURE_STRETCH'] as const;
@@ -3038,9 +3238,66 @@ export interface CheckFigures {
3038
3238
  /** Issue #1314: omitted unless behind_seams is declared; undeclared preserves existing check.json bytes. */
3039
3239
  [BEHIND_SEAM_LINE]?: BehindSeamsMeasured;
3040
3240
  [SOURCE_EXPOSURE_LINE]?: SourceExposureMeasured;
3241
+ /** Per-character manifest readings on a composed rig (issue #1679), in scene character declaration order. */
3242
+ characters?: Record<string, ComposedCharacterCheckFigures>;
3041
3243
  PASS: boolean;
3042
3244
  }
3043
3245
 
3246
+ export const COMPOSED_CHARACTER_BAR_IDS = [
3247
+ 'seam',
3248
+ 'BREATH_VISIBLE',
3249
+ 'BLINK_NO_HOLE',
3250
+ 'TIP_OVER_ROOT',
3251
+ 'STILL_REGIONS_DARK',
3252
+ 'FEET_STAY_LEVEL',
3253
+ 'STRESS_OFF_CHAIN',
3254
+ 'LIMB_ONE_BONE',
3255
+ 'SEAM_OVER_RANGE',
3256
+ 'SEAM_OVER_MOTION',
3257
+ ] as const;
3258
+
3259
+ export type ComposedCharacterBarId = (typeof COMPOSED_CHARACTER_BAR_IDS)[number];
3260
+ export type ComposedCharacterBarOutcomes = Record<ComposedCharacterBarId, CheckBarOutcome>;
3261
+
3262
+ /** Per-character manifest figures recorded under `check.json`'s `characters.<id>` on a composed rig (issue #1679). */
3263
+ export interface ComposedCharacterCheckFigures {
3264
+ offset: [number, number];
3265
+ scale?: number;
3266
+ bar_outcomes: ComposedCharacterBarOutcomes;
3267
+ seam_mean: number | null;
3268
+ seam_px_over_40: number | null;
3269
+ seam_px_over_80: number | null;
3270
+ seam_frame_scale: number | null;
3271
+ seam_scope?: SeamScope;
3272
+ seam_border?: { frame_px_left_out: number; px_over_40_left_out: number };
3273
+ seam_pairs?: SeamPairRow[];
3274
+ BREATH_VISIBLE: JudgementLine;
3275
+ BLINK_NO_HOLE: JudgementLine;
3276
+ TIP_OVER_ROOT: JudgementLine;
3277
+ STILL_REGIONS_DARK: JudgementLine;
3278
+ [LEVEL_LINE]?: LevelLine;
3279
+ [STRESS_LINE]?: JudgementLine;
3280
+ [LIMB_LINE]?: LimbLine;
3281
+ [SWEEP_LINE]?: SweepLine;
3282
+ [MOTION_SEAM_LINE]?: MotionSeamLine;
3283
+ [PHYSICS_CONTRIBUTES_LINE]?: PhysicsContributionLine;
3284
+ RECOMPOSITE_HOLES: ReportedLine;
3285
+ SETUP_POSE_VS_SOURCE?: ReportedLine;
3286
+ skipped?: { seam?: string };
3287
+ }
3288
+
3289
+ export interface ComposedCharacterReport {
3290
+ id: string;
3291
+ offset: [number, number];
3292
+ scale: number;
3293
+ figures: ComposedCharacterCheckFigures;
3294
+ seamViewport: Viewport | null;
3295
+ motionSeam: MotionSeamLine;
3296
+ backgroundRows: MotionBackgroundRow[];
3297
+ physics: PhysicsContributionLine;
3298
+ sweepSteps: Map<string, { left: number; right: number }>;
3299
+ }
3300
+
3044
3301
  /** One alternate set's setup-pose check record under `--set` or `--all-sets` (issue #454). */
3045
3302
  export interface SetCheckFigures {
3046
3303
  render_px: string;
@@ -3360,6 +3617,7 @@ function checkBarSkipReason(fig: Readonly<Record<string, unknown>>, id: Exclude<
3360
3617
  }
3361
3618
  case BEHIND_SEAM_LINE: return fig[id] === undefined ? 'undeclared' : 'no-complete-threshold-reading';
3362
3619
  case MOTION_SEAM_LINE: {
3620
+ if (!hasParts) return 'no-parts';
3363
3621
  const motion = fig[id];
3364
3622
  if (!isRecord(motion) || !isRecord(motion.roots)) return 'no-root-gate';
3365
3623
  return Array.isArray(motion.animations) && motion.animations.length === 0 ? 'no-animation' : 'no-complete-root-reading';
@@ -3453,6 +3711,10 @@ export interface CheckReport {
3453
3711
  * printed on every row; `check.json` carries it only for a joint whose cap is short ({@link SweepPose}).
3454
3712
  */
3455
3713
  sweepSteps?: Map<string, { left: number; right: number }>;
3714
+ /** Additional `no-parts` bar SKIPs printed on the console so console and `bar_outcomes` agree (issue #1679). */
3715
+ noPartsBars?: Array<{ bar: CheckBarId; reason: string }>;
3716
+ /** Per-character reports when checking bound character manifests against a composed rig (issue #1679). */
3717
+ characterReports?: ComposedCharacterReport[];
3456
3718
  }
3457
3719
 
3458
3720
  /**
@@ -4350,6 +4612,15 @@ export interface LimbLine {
4350
4612
  parts: LimbRow[];
4351
4613
  }
4352
4614
 
4615
+ function rigTurnTwin(part: string, bone: string): string {
4616
+ const colon = part.indexOf(':');
4617
+ if (colon < 0) return turnTwin(part, bone);
4618
+ const prefix = part.slice(0, colon + 1);
4619
+ const stem = part.slice(colon + 1);
4620
+ const boneStem = bone.startsWith(prefix) ? bone.slice(prefix.length) : bone;
4621
+ return `${prefix}${turnTwin(stem, boneStem)}`;
4622
+ }
4623
+
4353
4624
  /** The line from parts.json's limb records and rig.json's slots and skins; each FAIL row adds one `CHECK_LIMB_ONE_BONE` problem naming the part and every second bone. Null when no part is a limb's. */
4354
4625
  export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problems: Problem[], meshReport: unknown = []): LimbLine | null {
4355
4626
  const limbParts = parts.parts.filter((p) => p.limb !== undefined);
@@ -4362,11 +4633,11 @@ export function limbLine(parts: PartsFile, rig: Record<string, unknown>, problem
4362
4633
  .flatMap(row => Array.isArray(row.regions) ? row.regions.filter(isRecord) : [])
4363
4634
  .flatMap(region => typeof region.bone === 'string' && region.bone.length > 0 ? [region.bone] : []))]
4364
4635
  : [];
4365
- const own = new Set([l.bone, turnTwin(p.name, l.bone), ...regionBones.flatMap(bone => [bone, turnTwin(p.name, bone)]), ...(l.band === undefined ? [] : [l.band.upper, turnTwin(p.name, l.band.upper)])]);
4636
+ const own = new Set([l.bone, rigTurnTwin(p.name, l.bone), ...regionBones.flatMap(bone => [bone, rigTurnTwin(p.name, bone)]), ...(l.band === undefined ? [] : [l.band.upper, rigTurnTwin(p.name, l.band.upper)])]);
4366
4637
  const slot = slots.find((sl) => sl.name === p.name);
4367
4638
  const bound = slot === undefined ? new Set<string>() : boundBones(rig, p.name);
4368
4639
  const others = [...bound].filter((b) => !own.has(b));
4369
- const fail = others.length > 0 || bound.size === 0 || (l.band !== undefined && (![l.bone, turnTwin(p.name, l.bone)].some((b) => bound.has(b)) || ![l.band.upper, turnTwin(p.name, l.band.upper)].some((b) => bound.has(b))));
4640
+ const fail = others.length > 0 || bound.size === 0 || (l.band !== undefined && (![l.bone, rigTurnTwin(p.name, l.bone)].some((b) => bound.has(b)) || ![l.band.upper, rigTurnTwin(p.name, l.band.upper)].some((b) => bound.has(b))));
4370
4641
  if (fail) {
4371
4642
  problems.push({
4372
4643
  code: `CHECK_${LIMB_LINE}`,
@@ -4605,6 +4876,7 @@ export function sweepCopy(
4605
4876
  stage: StageBox,
4606
4877
  rigH: number,
4607
4878
  files: ReadonlySet<string> = new Set(),
4879
+ charScale = 1,
4608
4880
  ): { rig: Record<string, unknown>; motion: Record<string, unknown>; slots: string[]; images: Array<[string, Raster]> } {
4609
4881
  const bones = (Array.isArray(rig.bones) ? rig.bones : []).filter(isRecord);
4610
4882
  const world = setupWorld(rig);
@@ -4622,13 +4894,15 @@ export function sweepCopy(
4622
4894
  const m = world.get(parent) as BoneTransform;
4623
4895
  const name = underlaySlotName(j.part, taken);
4624
4896
  taken.add(name);
4625
- const [x, y] = toBoneLocal(m, stage.x + u.box[0] + u.box[2] / 2, stage.y + cropToSpineY(u.box[1] + u.box[3] / 2, rigH));
4897
+ const [x, y] = toBoneLocal(m, stage.x + charScale * (u.box[0] + u.box[2] / 2), stage.y + charScale * cropToSpineY(u.box[1] + u.box[3] / 2, rigH));
4626
4898
  const turn = normaliseDegrees(-m.worldRotation);
4627
- skin[name] = { [name]: turn === 0 ? { image: `${name}.png`, x, y } : { image: `${name}.png`, x, y, rotation: turn } };
4899
+ const scaled = charScale === 1 ? {} : { scaleX: charScale, scaleY: charScale };
4900
+ const safeFile = `${name.replaceAll(':', '.')}.png`;
4901
+ skin[name] = { [name]: turn === 0 ? { image: safeFile, x, y, ...scaled } : { image: safeFile, x, y, rotation: turn, ...scaled } };
4628
4902
  const mine = new Set(limbSlots(j.limb));
4629
4903
  slots.splice(slots.findIndex((s) => mine.has(String(s.name))), 0, { name, bone: parent, attachment: name });
4630
4904
  added.push(name);
4631
- images.push([`${name}.png`, u.image]);
4905
+ images.push([safeFile, u.image]);
4632
4906
  for (const a of sweepAngles(j.range)) {
4633
4907
  animations[sweepAnimationName(j.part, a)] = { duration: STILL_DURATION, loop: false, tracks: [{ bone: j.bone, property: 'rotate', keys: [{ t: 0, v: [a] }, { t: STILL_DURATION, v: [a] }] }] };
4634
4908
  }
@@ -4697,6 +4971,7 @@ export function sweepLine(
4697
4971
  problems: Problem[],
4698
4972
  step: (j: SweepJoint, bare: FrameSet) => { left: number; right: number } | null = () => null,
4699
4973
  printed: Map<string, { left: number; right: number }> = new Map(),
4974
+ charScale = 1,
4700
4975
  ): SweepLine {
4701
4976
  const seen: { grid: FrameSet | null } = { grid: null };
4702
4977
  const rows: SweepRow[] = joints.map((j, i) => {
@@ -4725,7 +5000,7 @@ export function sweepLine(
4725
5000
  const vp = bare.viewport;
4726
5001
  const f = seamFigures(under.frames[0].image, bare.frames[0].image, { x: 0, y: 0, width: vp.pixelWidth, height: vp.pixelHeight }, vp, bare.background, { sx: 1, sy: 1, tx: 0, ty: 0 });
4727
5002
  const mean = round3(f.mean);
4728
- const scale = round6(vp.scale);
5003
+ const scale = round6(charScale * vp.scale);
4729
5004
  // Issues #360 and #598: a disc or ball cap promises the disc covered at every pose, so one pixel over the level there is a FAIL of its own.
4730
5005
  const discFail = j.shape !== undefined && f.over40 > 0 && !seamFails(mean, f.over40, scale);
4731
5006
  const fail = seamFails(mean, f.over40, scale) || discFail;
@@ -4756,7 +5031,7 @@ export function sweepLine(
4756
5031
  const g = seen.grid;
4757
5032
  return {
4758
5033
  status: rows.some((r) => r.status === 'FAIL') ? 'FAIL' : 'PASS',
4759
- frame_scale: g === null ? null : round6(g.viewport.scale),
5034
+ frame_scale: g === null ? null : round6(charScale * g.viewport.scale),
4760
5035
  physics_left_out: physicsLeftOut,
4761
5036
  bar: { mean: SEAM_MEAN_BAR, rig_px_over_40: SEAM_PX_BAR, level: SEAM_PX_LEVEL },
4762
5037
  joints: rows,
@@ -5253,18 +5528,26 @@ function motionRootCandidates(parts: PartsFile, rig: Record<string, unknown>): M
5253
5528
  const identity = (bone: Record<string, unknown>, parent: string): boolean =>
5254
5529
  keys(bone, ['name', 'parent', 'x', 'y']) && bone.parent === parent && bone.x === 0 && bone.y === 0;
5255
5530
  const generatedBodyTurn = (part: PartRecord, slot: Record<string, unknown>, parent: string): boolean => {
5256
- const twin = turnTwin(part.name, parent);
5531
+ const colon = part.name.indexOf(':');
5532
+ const prefix = colon < 0 ? '' : part.name.slice(0, colon + 1);
5533
+ const stem = colon < 0 ? part.name : part.name.slice(colon + 1);
5534
+ const twin = rigTurnTwin(part.name, parent);
5257
5535
  if (slot.bone !== twin) return false;
5258
5536
  const children = bones.filter(bone => bone.name === twin);
5259
- const controls = bones.filter(bone => bone.name === TURN_BONE);
5260
- if (children.length !== 1 || !identity(children[0], parent) ||
5261
- controls.length !== 1 || !identity(controls[0], ROOT_BONE)) return false;
5537
+ const turnBone = `${prefix}${TURN_BONE}`;
5538
+ const controls = bones.filter(bone => bone.name === turnBone);
5539
+ const controlOk = colon < 0
5540
+ ? controls.length === 1 && identity(controls[0], ROOT_BONE)
5541
+ : controls.length === 1 && keys(controls[0], ['name', 'parent', 'x', 'y']) &&
5542
+ (controls[0].parent === ROOT_BONE || controls[0].parent === `${prefix}${PLACEMENT_BONE_NAME}` || controls[0].parent === `${prefix}${ROOT_BONE}`);
5543
+ if (children.length !== 1 || !identity(children[0], parent) || !controlOk) return false;
5544
+ const expectedConstraint = `${prefix}${turnConstraintName(stem)}`;
5262
5545
  const constraints = (Array.isArray(rig.constraints) ? rig.constraints : []).filter(isRecord)
5263
- .filter(constraint => constraint.name === turnConstraintName(part.name));
5546
+ .filter(constraint => constraint.name === expectedConstraint);
5264
5547
  if (constraints.length !== 1) return false;
5265
5548
  const constraint = constraints[0];
5266
5549
  if (!keys(constraint, ['type', 'name', 'bones', 'source', 'localSource', 'additive', 'properties']) ||
5267
- constraint.type !== 'transform' || constraint.source !== TURN_BONE ||
5550
+ constraint.type !== 'transform' || constraint.source !== turnBone ||
5268
5551
  constraint.localSource !== true || constraint.additive !== true || !Array.isArray(constraint.bones) ||
5269
5552
  constraint.bones.length === 0 || constraint.bones.some(name => typeof name !== 'string') ||
5270
5553
  new Set(constraint.bones).size !== constraint.bones.length || !constraint.bones.includes(twin)) return false;
@@ -5273,7 +5556,7 @@ function motionRootCandidates(parts: PartsFile, rig: Record<string, unknown>): M
5273
5556
  const targets = bones.filter(bone => bone.name === name);
5274
5557
  if (targets.length !== 1 || typeof targets[0].parent !== 'string') return false;
5275
5558
  const carrier = targets[0].parent;
5276
- return targets[0].name === turnTwin(part.name, carrier) && identity(targets[0], carrier) &&
5559
+ return targets[0].name === rigTurnTwin(part.name, carrier) && identity(targets[0], carrier) &&
5277
5560
  bones.filter(bone => bone.name === carrier).length === 1;
5278
5561
  })) return false;
5279
5562
  const properties = constraint.properties;
@@ -5302,7 +5585,7 @@ function motionRootCandidates(parts: PartsFile, rig: Record<string, unknown>): M
5302
5585
  const parent = named[0].parent;
5303
5586
  const slot = binding(root);
5304
5587
  if (slot === null) continue;
5305
- const twin = turnTwin(root.name, l.bone);
5588
+ const twin = rigTurnTwin(root.name, l.bone);
5306
5589
  const twinBones = bones.filter(b => b.name === twin);
5307
5590
  if (slot.bone !== l.bone && !(slot.bone === twin && twinBones.length === 1 && twinBones[0].parent === l.bone)) {
5308
5591
  bad(object, 'slot binds "' + String(slot.bone) + '"; the declared bone "' + l.bone + '" or its named turn child is required');
@@ -6993,7 +7276,30 @@ function renderExtremes(build: string, out: string, animations: readonly string[
6993
7276
  * MEASURABLE is a problem. Without it nothing here reads, writes or prints
6994
7277
  * anything it did not before.
6995
7278
  */
6996
- 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, _requirementsAs: string | undefined = requirements, config?: InputFileRecord, windBand?: string, noExtremes = false, supportSource?: string, supportFigure?: Mask, assemblyRules?: AssemblyRules, loopSeam?: LoopSeamRequest, previewIdle = false): CheckReport {
7279
+ export function runCheck(
7280
+ rigDir: string,
7281
+ outDir: string,
7282
+ rigc: RigcRunner,
7283
+ partsHome?: string,
7284
+ mode: PackMode = DEFAULT_PACK_MODE,
7285
+ source?: string,
7286
+ requirements?: string,
7287
+ seamPairsAsked = false,
7288
+ keepStills = false,
7289
+ set?: string,
7290
+ allSets = false,
7291
+ environment?: string,
7292
+ _requirementsAs: string | undefined = requirements,
7293
+ config?: InputFileRecord,
7294
+ windBand?: string,
7295
+ noExtremes = false,
7296
+ supportSource?: string,
7297
+ supportFigure?: Mask,
7298
+ assemblyRules?: AssemblyRules,
7299
+ loopSeam?: LoopSeamRequest,
7300
+ previewIdle = false,
7301
+ characters?: readonly ComposedCharacterInput[],
7302
+ ): CheckReport {
6997
7303
  const out = resolve(outDir);
6998
7304
  if (loopSeam !== undefined || previewIdle) rmSync(join(out, 'check.json'), { force: true });
6999
7305
  if (previewIdle && loopSeam !== undefined) throw new PartsError([{
@@ -7018,7 +7324,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7018
7324
  }
7019
7325
  };
7020
7326
  const readInputs = (): CheckInputs => {
7021
- const inputs = readCheckInputs(rigDir, partsHome, source, set, allSets);
7327
+ const inputs = readCheckInputs(rigDir, partsHome, source, set, allSets, characters);
7022
7328
  if (loopSeam !== undefined && inputs.idleDuration === null) {
7023
7329
  throw new PartsError([{ code: 'CHECK_IDLE_PRESENT', object: `${inputs.motionPath} animation "idle"`, detail: `--loop-seam-bar requires an idle with positive duration; ${inputs.noIdle}` }]);
7024
7330
  }
@@ -7047,6 +7353,16 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7047
7353
  inp = got as CheckInputs;
7048
7354
  const file = reqFile as RequirementsFile;
7049
7355
  const ready = inp;
7356
+ const reqParts: PartsFile | null = ready.parts !== null ? ready.parts : (ready.composedCharacters?.length ?? 0) > 0
7357
+ ? {
7358
+ ...ready.composedCharacters![0].parts,
7359
+ parts: ready.composedCharacters!.flatMap(c => prefixCharacterParts(c.parts, c.id, ready.rig).parts),
7360
+ }
7361
+ : null;
7362
+ const reqPartsDirMap = new Map<string, string>();
7363
+ for (const c of ready.composedCharacters ?? []) {
7364
+ for (const p of c.parts.parts) reqPartsDirMap.set(`${c.id}:${p.name}`, c.partsDir);
7365
+ }
7050
7366
  take(() => resolveRequirements(file, ready.rig, ready.motion, ready.rootBone));
7051
7367
  if (file.setup_painting !== undefined) take(() => {
7052
7368
  refuseIfAny(setupPaintingBounds(file.setup_painting as SetupPainting, ready.stage.width, ready.stage.height));
@@ -7062,12 +7378,13 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7062
7378
  if (file.boundary_colour !== undefined && ready.parts !== null && ready.idleDuration !== null) {
7063
7379
  take(() => refuseIfAny(boundaryColourSizeProblems(ready)));
7064
7380
  }
7065
- take(() => refuseIfAny(exceptionProblems(file, ready.parts, ready.noParts)));
7381
+ take(() => refuseIfAny(exceptionProblems(file, reqParts, ready.noParts)));
7066
7382
  // A seam's pairs are read off parts.json's art (issue #111); both resolvers' problems are named in one refusal.
7067
7383
  if (file.requirements.some((r) => r.kind === 'seam') || file.motion_seams !== undefined) {
7068
- const parts = ready.parts;
7384
+ const parts = reqParts;
7069
7385
  seams = take(() => resolveSeams(file, parts === null ? null : parts.parts.map((p) => p.name), ready.noParts, (n) => {
7070
7386
  const rec = (parts as PartsFile).parts.find((p) => p.name === n) as PartRecord;
7387
+ const ready = { partsDir: reqPartsDirMap.get(n) ?? inp.partsDir };
7071
7388
  return placedArt(rec.x, rec.y, readPng(join(dirname(ready.partsDir), partImageReference(rec).path)));
7072
7389
  }));
7073
7390
  }
@@ -7214,7 +7531,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7214
7531
  }
7215
7532
  if (!Array.isArray(meshReport)) refuseIfAny([{ code: 'CHECK_INPUT_IS_JSON', object: meshReportPath, detail: 'an array of per-part mesh reports is required' }]);
7216
7533
  }
7217
- const limbs = inp.parts === null ? null : limbLine(inp.parts, inp.rig, limbProblems, meshReport);
7534
+ let limbs = inp.parts === null ? null : limbLine(inp.parts, inp.rig, limbProblems, meshReport);
7218
7535
  const levelProblems: Problem[] = [];
7219
7536
  try {
7220
7537
  if (inp.idleDuration !== null) {
@@ -7634,9 +7951,11 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7634
7951
  }
7635
7952
  }
7636
7953
  }
7637
- if (seamRequired && reqFile !== null) motionSeam.required = motionSeamRequired(motionSeam, backgroundRows, reqFile.path, motionRootProblems, motionCellEvidence);
7954
+ if (seamRequired && reqFile !== null && (inp.composedCharacters?.length ?? 0) === 0) {
7955
+ motionSeam.required = motionSeamRequired(motionSeam, backgroundRows, reqFile.path, motionRootProblems, motionCellEvidence);
7956
+ }
7638
7957
  const declaredPairKeys = new Set(motionSeam.pairs.map((p) => [p.a, p.b].sort().join('|')));
7639
- const figureOpenings: FigureOpeningReading =
7958
+ let figureOpenings: FigureOpeningReading =
7640
7959
  inp.parts === null
7641
7960
  ? { status: 'SKIP', reason: inp.noParts ?? 'no parts.json', fps: IDLE_FPS, cell: 0, pairs: 0, animations: [], warnings: 0, openings: [] }
7642
7961
  : readFigurePairOpenings(buildDir, animationNames, declaredPairKeys, IDLE_FPS);
@@ -7948,6 +8267,55 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7948
8267
  const reqProblems: Problem[] = [];
7949
8268
  const reqBlock = reqFile === null || reqRecord === null ? null : { file: reqRecord, ...measureRequirements(inp, reqFile, buildDir, out, rigc, reqProblems, seams ?? new Map(), measured) };
7950
8269
 
8270
+ const composedList = inp.composedCharacters ?? [];
8271
+ let characterReports: ComposedCharacterReport[] | undefined;
8272
+ let charactersMap: Record<string, ComposedCharacterCheckFigures> | undefined;
8273
+ let composedSeamFrameScale: number | null = null;
8274
+ const composedProblems: Problem[] = [];
8275
+ if (composedList.length > 0) {
8276
+ const composedRes = runComposedCharacters({
8277
+ characters: composedList,
8278
+ inp,
8279
+ out,
8280
+ buildDir,
8281
+ pack,
8282
+ mode,
8283
+ rigc,
8284
+ measured,
8285
+ env,
8286
+ idle,
8287
+ reqFile,
8288
+ seams,
8289
+ seamPairsAsked,
8290
+ seamRequired,
8291
+ motionCellEvidence,
8292
+ keepStills,
8293
+ });
8294
+ characterReports = composedRes.reports;
8295
+ charactersMap = composedRes.charactersMap;
8296
+ composedProblems.push(...composedRes.problems);
8297
+ seam = composedRes.seam;
8298
+ seamViewport = composedRes.seamViewport;
8299
+ composedSeamFrameScale = composedRes.seamFrameScale;
8300
+ seamScope = composedRes.seamScope;
8301
+ seamPairs = composedRes.seamPairs;
8302
+ breath = composedRes.breath;
8303
+ blink = composedRes.blink;
8304
+ tip = composedRes.tip;
8305
+ still = composedRes.still;
8306
+ level = composedRes.level;
8307
+ stress = composedRes.stress;
8308
+ limbs = composedRes.limbs;
8309
+ sweep = composedRes.sweep;
8310
+ for (const [k, v] of composedRes.sweepSteps) sweepSteps.set(k, v);
8311
+ motionSeam = composedRes.motionSeam;
8312
+ physics = composedRes.physics;
8313
+ sourceRead = composedRes.sourceRead;
8314
+ Object.assign(skipReasons, composedRes.skipReasons);
8315
+ const allDeclaredPairKeys = new Set(characterReports.flatMap(cr => cr.motionSeam.pairs.map(p => [p.a, p.b].sort().join('|'))));
8316
+ figureOpenings = readFigurePairOpenings(buildDir, animationNames, allDeclaredPairKeys, IDLE_FPS);
8317
+ }
8318
+
7951
8319
  const skipped: { loop?: string; seam?: string } = {};
7952
8320
  if (inp.noIdle !== null) skipped.loop = inp.noIdle;
7953
8321
  else if (loopSeamEvidence === null && loop !== null && loop.max === LOOP_MAX_BAR && loopPhysics !== null && loopPhysics.length > 0) {
@@ -7966,7 +8334,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7966
8334
  seam_mean: seam === null ? null : round3(seam.mean),
7967
8335
  seam_px_over_40: seam === null ? null : seam.over40,
7968
8336
  seam_px_over_80: seam === null ? null : seam.over80,
7969
- seam_frame_scale: seam === null || seamViewport === null ? null : round6(seamViewport.scale),
8337
+ seam_frame_scale: seam === null || seamViewport === null ? null : (composedList.length > 0 ? (composedSeamFrameScale ?? round6(seamViewport.scale)) : round6(seamViewport.scale)),
7970
8338
  ...(seamScope === undefined ? {} : { seam_scope: seamScope }),
7971
8339
  ...(seam === null || seam.border === null ? {} : { seam_border: { frame_px_left_out: seam.border.framePx, px_over_40_left_out: seam.border.over40 } }),
7972
8340
  ...(seamPairs === null ? {} : { seam_pairs: seamPairs }),
@@ -7985,7 +8353,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
7985
8353
  ...(motionSeam.pairs.length === 0 && motionSeam.roots === undefined && motionSeam.required === undefined ? {} : { [MOTION_SEAM_LINE]: motionSeam }),
7986
8354
  ...(stripped === null || idle === null ? {} : { [CLOTH_LINE]: cloth }),
7987
8355
  ...(physics.status === 'SKIP' ? {} : { [PHYSICS_CONTRIBUTES_LINE]: physics }),
7988
- RECOMPOSITE_HOLES: inp.parts === null ? { status: 'SKIP', reason: inp.noParts ?? '' } : holesLine(inp.parts),
8356
+ RECOMPOSITE_HOLES: composedList.length > 0 ? characterReports![0].figures.RECOMPOSITE_HOLES : inp.parts === null ? { status: 'SKIP', reason: inp.noParts ?? '' } : holesLine(inp.parts),
7989
8357
  ...(figureOpenings.status === 'SKIP' ? {} : { figure_openings: figureOpenings }),
7990
8358
  ...(sourceRead === null ? {} : { [SOURCE_LINE]: sourceRead }),
7991
8359
  ...(windBandRead === null ? {} : { [WIND_BAND_LINE]: windBandRead }),
@@ -8001,6 +8369,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8001
8369
  ...(sourceExposure === null ? {} : { [SOURCE_EXPOSURE_LINE]: sourceExposure }),
8002
8370
  ...(cutMaterial === null ? {} : { [CUT_MATERIAL_LINE]: cutMaterial }),
8003
8371
  ...(reqBlock === null ? {} : { requirements: reqBlock }),
8372
+ ...(charactersMap === undefined ? {} : { characters: charactersMap }),
8004
8373
  };
8005
8374
  const barProblems: Problem[] = [];
8006
8375
  if (!htmlGreen) barProblems.push(...rigcFailed(packedBuildLabel(mode), build, gateHtml));
@@ -8012,7 +8381,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8012
8381
  detail: `max |d| ${loop.max}/255, first at pixel ${loop.x},${loop.y} of ${loopSet.viewport.pixelWidth}x${loopSet.viewport.pixelHeight}; ${LOOP_MAX_BAR} is required — the idle's last key must equal its first`,
8013
8382
  });
8014
8383
  }
8015
- if (readings.seam_mean !== null && readings.seam_px_over_40 !== null && readings.seam_frame_scale !== null && seamFigureFailed(readings)) {
8384
+ if (composedList.length === 0 && readings.seam_mean !== null && readings.seam_px_over_40 !== null && readings.seam_frame_scale !== null && seamFigureFailed(readings)) {
8016
8385
  const worst = seamPairs === null || seamPairs.length === 0 ? null : seamPairs[0];
8017
8386
  barProblems.push({
8018
8387
  code: 'CHECK_SEAM_WITHIN_BAR',
@@ -8042,10 +8411,14 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8042
8411
  const rank = (q: Problem): number => JUDGEMENT_LINES.findIndex((n) => q.code === `CHECK_${n}`);
8043
8412
  problems.sort((a, b) => rank(a) - rank(b));
8044
8413
  problems.unshift(...barProblems);
8045
- problems.push(...cutMaterialProblems, ...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
8414
+ problems.push(...composedProblems, ...cutMaterialProblems, ...foldProblems, ...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems, ...reqProblems);
8415
+ const baseBarOutcomes = checkBarOutcomes(readings, skipReasons, stretchFailedWithoutReading);
8416
+ const finalBarOutcomes: CheckBarOutcomes = characterReports === undefined
8417
+ ? baseBarOutcomes
8418
+ : mergeComposedBarOutcomes(baseBarOutcomes, characterReports);
8046
8419
  const figures: CheckFigures = {
8047
8420
  spec: CHECK_SPEC,
8048
- bar_outcomes: checkBarOutcomes(readings, skipReasons, stretchFailedWithoutReading),
8421
+ bar_outcomes: finalBarOutcomes,
8049
8422
  build: { model_sha256: modelSha256 },
8050
8423
  ...readings,
8051
8424
  PASS: problems.length === 0,
@@ -8064,6 +8437,7 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8064
8437
  if (reason === null) bars.measured.push(bar);
8065
8438
  else bars.skipped.push({ bar, reason });
8066
8439
  };
8440
+ const noPartsBars: Array<{ bar: CheckBarId; reason: string }> = [];
8067
8441
  tally('loop', skipped.loop ?? null);
8068
8442
  tally('seam', skipped.seam ?? null);
8069
8443
  for (const n of JUDGEMENT_LINES) {
@@ -8080,15 +8454,34 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8080
8454
  if (sourceExposure !== null) tally(SOURCE_EXPOSURE_LINE, sourceExposure.status === 'REPORTED' ? 'no declared limit; a measurement, never a pass' : null);
8081
8455
  // Issue #348: the level bar where it is written; a line whose every foot no frame posed says SKIP and is not measured.
8082
8456
  if (level !== null) tally(LEVEL_LINE, level.status === 'SKIP' ? (level.reason ?? '') : null);
8457
+ else if (inp.noParts !== null && finalBarOutcomes[LEVEL_LINE].status === 'SKIP' && finalBarOutcomes[LEVEL_LINE].reason === 'no-parts') {
8458
+ noPartsBars.push({ bar: LEVEL_LINE, reason: inp.noParts });
8459
+ tally(LEVEL_LINE, inp.noParts);
8460
+ }
8083
8461
  // Issue #347: the stress bar is counted where it is written — on every rig with a handwear part and an idle.
8084
8462
  if (stress !== null) tally(STRESS_LINE, stress.status === 'SKIP' ? stress.reason : null);
8463
+ else if (inp.noParts !== null && finalBarOutcomes[STRESS_LINE].status === 'SKIP' && finalBarOutcomes[STRESS_LINE].reason === 'no-parts') {
8464
+ noPartsBars.push({ bar: STRESS_LINE, reason: inp.noParts });
8465
+ tally(STRESS_LINE, inp.noParts);
8466
+ }
8085
8467
  // Issue #349: the limb bar where it is written; it reads rig.json, so it always measures.
8086
8468
  if (limbs !== null) tally(LIMB_LINE, null);
8469
+ else if (inp.noParts !== null && finalBarOutcomes[LIMB_LINE].status === 'SKIP' && finalBarOutcomes[LIMB_LINE].reason === 'no-parts') {
8470
+ noPartsBars.push({ bar: LIMB_LINE, reason: inp.noParts });
8471
+ tally(LIMB_LINE, inp.noParts);
8472
+ }
8087
8473
  // Issue #360: the range bar where it is written; a joint it cannot read fails, so it always measures.
8088
8474
  if (sweep !== null) tally(SWEEP_LINE, null);
8475
+ else if (inp.noParts !== null && finalBarOutcomes[SWEEP_LINE].status === 'SKIP' && finalBarOutcomes[SWEEP_LINE].reason === 'no-parts') {
8476
+ noPartsBars.push({ bar: SWEEP_LINE, reason: inp.noParts });
8477
+ tally(SWEEP_LINE, inp.noParts);
8478
+ }
8089
8479
  // Issue #941: the required bar never SKIPs (an unmeasured line or pair is its refusal), so it counts the line measured.
8090
8480
  if (motionSeam.required !== undefined) tally(MOTION_SEAM_LINE, null);
8091
8481
  else if (motionSeam.roots !== undefined) tally(MOTION_SEAM_LINE, motionSeam.roots.status === 'SKIP' ? (motionSeam.roots.reason ?? 'no body-root reading') : null);
8482
+ else if (inp.noParts !== null && finalBarOutcomes[MOTION_SEAM_LINE].status === 'SKIP' && finalBarOutcomes[MOTION_SEAM_LINE].reason === 'no-parts') {
8483
+ tally(MOTION_SEAM_LINE, inp.noParts);
8484
+ }
8092
8485
  return {
8093
8486
  figures,
8094
8487
  gateHtml,
@@ -8111,6 +8504,8 @@ export function runCheck(rigDir: string, outDir: string, rigc: RigcRunner, parts
8111
8504
  behindSeams,
8112
8505
  ...(sweepSteps.size === 0 ? {} : { sweepSteps }),
8113
8506
  ...(windBandRead === null ? {} : { windBand: windBandRead }),
8507
+ ...(noPartsBars.length === 0 ? {} : { noPartsBars }),
8508
+ ...(characterReports === undefined ? {} : { characterReports }),
8114
8509
  };
8115
8510
  } finally {
8116
8511
  if (previewIdle) rmSync(idleDir, { recursive: true, force: true });
@@ -8437,8 +8832,25 @@ function plantedFeet(parts: PartsFile, notPlanted: readonly string[]): { all: Pa
8437
8832
  }
8438
8833
 
8439
8834
  /** The sentence a feet half carries when every footwear part is declared not planted (issue #231). */
8440
- function noneHeldText(declared: readonly string[]): string {
8441
- return `every ${tagWords(FEET_TAGS)} part (${declared.map((n) => `"${n}"`).join(', ')}) is declared not planted by the scene file's not_planted, so there are no feet to hold still`;
8835
+ function noneHeldText(declared: readonly string[], forwardedFrom?: Readonly<Record<string, string>>): string {
8836
+ const hasForwarded = declared.some((n) => forwardedFrom?.[n] !== undefined);
8837
+ if (!hasForwarded) {
8838
+ return `every ${tagWords(FEET_TAGS)} part (${declared.map((n) => `"${n}"`).join(', ')}) is declared not planted by the scene file's not_planted, so there are no feet to hold still`;
8839
+ }
8840
+ const listed = declared.map((n) => {
8841
+ const srcBuild = forwardedFrom?.[n];
8842
+ return srcBuild !== undefined
8843
+ ? `"${n}" (forwarded from build "${srcBuild}" check/check.json)`
8844
+ : `"${n}" (scene requirements)`;
8845
+ });
8846
+ return `every ${tagWords(FEET_TAGS)} part (${listed.join(', ')}) is declared not planted, so there are no feet to hold still`;
8847
+ }
8848
+
8849
+ function breathForwardedBlock(declared: readonly string[], forwardedNotPlanted?: Readonly<Record<string, string>>): Record<string, unknown> {
8850
+ const entries = declared
8851
+ .filter((n) => forwardedNotPlanted?.[n] !== undefined)
8852
+ .map((n) => [n, forwardedNotPlanted![n]] as const);
8853
+ return entries.length === 0 ? {} : { forwarded_from_build: { not_planted: Object.fromEntries(entries) } };
8442
8854
  }
8443
8855
 
8444
8856
  /**
@@ -8464,15 +8876,33 @@ function noneHeldText(declared: readonly string[]): string {
8464
8876
  * or a physics response to the world inside the torso's box passed the bar
8465
8877
  * for a torso that did not breathe.
8466
8878
  */
8467
- function breathLine(inp: FullInputs, isolated: Isolate, pair: BreathPairRender, problems: Problem[], notPlanted: readonly string[], skipped: ReadingSkip<'BREATH_VISIBLE'>): JudgementLine {
8879
+ function breathLine(
8880
+ inp: FullInputs,
8881
+ isolated: Isolate,
8882
+ pair: BreathPairRender,
8883
+ problems: Problem[],
8884
+ notPlanted: readonly string[],
8885
+ skipped: ReadingSkip<'BREATH_VISIBLE'>,
8886
+ forwardedNotPlanted?: Readonly<Record<string, string>>,
8887
+ ): JudgementLine {
8468
8888
  const torso = partsTagged(inp.parts, TORSO_TAGS);
8469
8889
  const { all: allFeet, held: feet, declared } = plantedFeet(inp.parts, notPlanted);
8890
+ const fwdBlock = breathForwardedBlock(declared, forwardedNotPlanted);
8470
8891
  const noTorso = `no part comes from a See-through ${tagWords(TORSO_TAGS)} layer, so there is no torso to see breathe`;
8471
8892
  const noFeet = `no part comes from a See-through ${tagWords(FEET_TAGS)} layer, so there are no feet to hold still`;
8472
8893
  // Issue #323: a figure without one of the two halves still has the other read; with neither, the SKIP it always was.
8473
- if (torso.length === 0 && feet.length === 0) return skipped(`${noTorso}${declared.length === 0 ? '' : `; ${declared.map((n) => `"${n}"`).join(', ')} declared not planted`}`, 'no-eligible-region');
8474
- if (torso.length === 0) return oneHalf(inp, isolated, pair, problems, 'feet', feet, noTorso, declared, skipped);
8475
- if (allFeet.length === 0) return oneHalf(inp, isolated, pair, problems, 'torso', torso, noFeet, [], skipped);
8894
+ if (torso.length === 0 && feet.length === 0) {
8895
+ const declaredWords = declared.map((n) => {
8896
+ const srcBuild = forwardedNotPlanted?.[n];
8897
+ return srcBuild !== undefined ? `"${n}" (forwarded from build "${srcBuild}" check/check.json)` : `"${n}"`;
8898
+ });
8899
+ const got = skipped(`${noTorso}${declaredWords.length === 0 ? '' : `; ${declaredWords.join(', ')} declared not planted`}`, 'no-eligible-region');
8900
+ return Object.keys(fwdBlock).length === 0
8901
+ ? got
8902
+ : { ...got, ...(declared.length === 0 ? {} : { declared_not_planted: declared }), ...fwdBlock };
8903
+ }
8904
+ if (torso.length === 0) return oneHalf(inp, isolated, pair, problems, 'feet', feet, noTorso, declared, skipped, forwardedNotPlanted);
8905
+ if (allFeet.length === 0) return oneHalf(inp, isolated, pair, problems, 'torso', torso, noFeet, [], skipped, forwardedNotPlanted);
8476
8906
  const H = inp.parts.rig_size[1];
8477
8907
  const tr = torsoBreath(inp, torso, pair);
8478
8908
  const fs = feet.length === 0 ? null : isolated('feet', feet);
@@ -8492,6 +8922,7 @@ function breathLine(inp: FullInputs, isolated: Isolate, pair: BreathPairRender,
8492
8922
  return {
8493
8923
  status: ok ? 'PASS' : 'FAIL',
8494
8924
  ...(declared.length === 0 ? {} : { declared_not_planted: declared }),
8925
+ ...fwdBlock,
8495
8926
  torso_parts: torso.map((p) => p.name),
8496
8927
  torso_heat_mean: mean,
8497
8928
  torso_floor: BREATH_TORSO_MEAN_FLOOR,
@@ -8509,8 +8940,20 @@ function breathLine(inp: FullInputs, isolated: Isolate, pair: BreathPairRender,
8509
8940
  * `halves_measured`, says `1 of 2` — after `declared_not_planted` when the scene
8510
8941
  * file declares some of the feet read (issue #231), which stays the first.
8511
8942
  */
8512
- function oneHalf(inp: FullInputs, isolated: Isolate, pair: BreathPairRender, problems: Problem[], half: 'torso' | 'feet', ps: readonly PartRecord[], reason: string, declared: readonly string[], skipped: ReadingSkip<'BREATH_VISIBLE'>): JudgementLine {
8943
+ function oneHalf(
8944
+ inp: FullInputs,
8945
+ isolated: Isolate,
8946
+ pair: BreathPairRender,
8947
+ problems: Problem[],
8948
+ half: 'torso' | 'feet',
8949
+ ps: readonly PartRecord[],
8950
+ reason: string,
8951
+ declared: readonly string[],
8952
+ skipped: ReadingSkip<'BREATH_VISIBLE'>,
8953
+ forwardedNotPlanted?: Readonly<Record<string, string>>,
8954
+ ): JudgementLine {
8513
8955
  const H = inp.parts.rig_size[1];
8956
+ const fwdBlock = breathForwardedBlock(declared, forwardedNotPlanted);
8514
8957
  if (half === 'torso') {
8515
8958
  // Issue #411: the torso half is the breath alone.
8516
8959
  const tr = torsoBreath(inp, ps, pair);
@@ -8544,6 +8987,7 @@ function oneHalf(inp: FullInputs, isolated: Isolate, pair: BreathPairRender, pro
8544
8987
  return {
8545
8988
  status: ok ? 'PASS' : 'FAIL',
8546
8989
  ...(declared.length === 0 ? {} : { declared_not_planted: [...declared] }),
8990
+ ...fwdBlock,
8547
8991
  halves_measured: '1 of 2',
8548
8992
  torso_status: 'SKIP',
8549
8993
  torso_reason: reason,
@@ -8684,6 +9128,11 @@ export interface TipExceptions {
8684
9128
  not_swinging: readonly string[];
8685
9129
  rises: readonly string[];
8686
9130
  rests: readonly string[];
9131
+ forwardedFrom?: {
9132
+ not_swinging?: Readonly<Record<string, string>>;
9133
+ rises?: Readonly<Record<string, string>>;
9134
+ rests?: Readonly<Record<string, string>>;
9135
+ };
8687
9136
  }
8688
9137
 
8689
9138
  const NO_TIP_EXCEPTIONS: TipExceptions = { path: '', not_swinging: [], rises: [], rests: [] };
@@ -8914,9 +9363,10 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8914
9363
  risesRead.set(name, dir.chains.join('; '));
8915
9364
  return;
8916
9365
  }
9366
+ const risesBuild = excepted.forwardedFrom?.rises?.[name];
8917
9367
  refused.push({
8918
9368
  code: 'REQUIREMENTS_TIP_EXCEPTION',
8919
- object: `${excepted.path} field "rises"[${i}]`,
9369
+ object: risesBuild !== undefined ? `build "${risesBuild}" check/check.json field "declared_rises"` : `${excepted.path} field "rises"[${i}]`,
8920
9370
  detail: `names part "${name}", whose tip is not up: ${'none' in dir ? dir.none : `its chain runs ${dir.toward} — ${dir.chains.join('; ')}`}; a part declared rises must be carried by a chain whose last link runs up at the setup pose — from its origin along its length, or, a last link with no length, from the link before's origin to its own`,
8921
9371
  });
8922
9372
  });
@@ -8928,7 +9378,15 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8928
9378
  let failed = false;
8929
9379
  for (const p of swing) {
8930
9380
  if (excepted.not_swinging.includes(p.name)) {
8931
- rows.push({ ...checkRow('TIP_OVER_ROOT.parts', 'part', false, [p.name]), part: p.name, unmeasured: "declared not swinging by the scene file's not_swinging, so it is not held to the bar" });
9381
+ const fromBuild = excepted.forwardedFrom?.not_swinging?.[p.name];
9382
+ rows.push({
9383
+ ...checkRow('TIP_OVER_ROOT.parts', 'part', false, [p.name]),
9384
+ part: p.name,
9385
+ ...(fromBuild === undefined ? {} : { forwarded_from_build: fromBuild }),
9386
+ unmeasured: fromBuild !== undefined
9387
+ ? `declared not swinging by build "${fromBuild}" check/check.json (not_swinging), so it is not held to the bar`
9388
+ : "declared not swinging by the scene file's not_swinging, so it is not held to the bar",
9389
+ });
8932
9390
  continue;
8933
9391
  }
8934
9392
  // Issue #349: a limb segment is rigid on its one bone and turns at its joint; it does not hang, so no tip trails a root.
@@ -8951,7 +9409,12 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
8951
9409
  const held = shown.map((f, i) => (f === null ? null : { rest: f.rest, triangles: f.triangles, posed: toCarrier(i, f.posed) }));
8952
9410
  const c = hang === null ? w : halfTravels(art, p, inp.stage, held, rises ? 'up' : 'down');
8953
9411
  // A part not declared writes the row it wrote before issue #231; a declared one says which half is its tip's.
8954
- const said = { ...(rests ? { declared: 'rests' } : {}), ...(rises ? { tip_half: tipHalf, tip_read: risesRead.get(p.name) as string } : {}) };
9412
+ const rowForwardedFrom = (rises ? excepted.forwardedFrom?.rises?.[p.name] : undefined) ?? (rests ? excepted.forwardedFrom?.rests?.[p.name] : undefined);
9413
+ const said = {
9414
+ ...(rests ? { declared: 'rests' } : {}),
9415
+ ...(rises ? { tip_half: tipHalf, tip_read: risesRead.get(p.name) as string } : {}),
9416
+ ...(rowForwardedFrom === undefined ? {} : { forwarded_from_build: rowForwardedFrom }),
9417
+ };
8955
9418
  if (w.root === null || w.tip === null || c.root === null || c.tip === null) {
8956
9419
  const half = w.root === null || c.root === null ? rootHalf : tipHalf;
8957
9420
  rows.push({ ...checkRow('TIP_OVER_ROOT.parts', 'part', false, [p.name]), part: p.name, ...said, unmeasured: shown[0] === null ? 'its slot shows no attachment on idle frame 0' : `on idle frame 0 the ${half} half of its box holds no art its attachment draws` });
@@ -9029,7 +9492,16 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
9029
9492
  ...(excepted.rises.length === 0 ? {} : { declared_rises: swing.filter((p) => excepted.rises.includes(p.name)).map((p) => p.name) }),
9030
9493
  ...(excepted.rests.length === 0 ? {} : { declared_rests: swing.filter((p) => excepted.rests.includes(p.name)).map((p) => p.name) }),
9031
9494
  };
9032
- const figures = { ...declared, instrument: TIP_INSTRUMENT, parts: rows, ratio_floor: TIP_RATIO_FLOOR,
9495
+ const fwdNotSwinging = Object.fromEntries(swing.filter((p) => excepted.forwardedFrom?.not_swinging?.[p.name] !== undefined).map((p) => [p.name, excepted.forwardedFrom!.not_swinging![p.name]]));
9496
+ const fwdRises = Object.fromEntries(swing.filter((p) => excepted.forwardedFrom?.rises?.[p.name] !== undefined).map((p) => [p.name, excepted.forwardedFrom!.rises![p.name]]));
9497
+ const fwdRests = Object.fromEntries(swing.filter((p) => excepted.forwardedFrom?.rests?.[p.name] !== undefined).map((p) => [p.name, excepted.forwardedFrom!.rests![p.name]]));
9498
+ const forwardedMap = {
9499
+ ...(Object.keys(fwdNotSwinging).length === 0 ? {} : { not_swinging: fwdNotSwinging }),
9500
+ ...(Object.keys(fwdRises).length === 0 ? {} : { rises: fwdRises }),
9501
+ ...(Object.keys(fwdRests).length === 0 ? {} : { rests: fwdRests }),
9502
+ };
9503
+ const forwardedBlock = Object.keys(forwardedMap).length === 0 ? {} : { forwarded_from_build: forwardedMap };
9504
+ const figures = { ...declared, ...forwardedBlock, instrument: TIP_INSTRUMENT, parts: rows, ratio_floor: TIP_RATIO_FLOOR,
9033
9505
  ...(excepted.rests.length === 0 ? {} : { rest_ratio_ceiling: TIP_REST_RATIO_CEILING }) };
9034
9506
  if (measured === 0) {
9035
9507
  const reasons = rows.map((r) => {
@@ -9037,7 +9509,7 @@ function tipLine(inp: FullInputs, geometryPath: string, frames: number, problems
9037
9509
  return `${String(r.part)}: ${String(r.unmeasured)}${travel}`;
9038
9510
  });
9039
9511
  return { ...skipped(`none of ${quoteParts(swing)} could be measured: ${reasons.join('; ')}`, 'no-reading'),
9040
- ...(belowGrid === 0 ? {} : figures) };
9512
+ ...(belowGrid === 0 ? { ...declared, ...forwardedBlock } : figures) };
9041
9513
  }
9042
9514
  return { status: failed ? 'FAIL' : 'PASS', ...figures };
9043
9515
  }
@@ -9435,16 +9907,123 @@ function sig4(x: number): number {
9435
9907
  */
9436
9908
  function idleDrivenSlots(motion: Record<string, unknown>): Set<string> {
9437
9909
  const anims = isRecord(motion.animations) ? motion.animations : {};
9910
+ const groups = isRecord(motion.groups) ? motion.groups : {};
9438
9911
  const idle = isRecord(anims.idle) ? anims.idle : {};
9439
9912
  const named = new Set<string>();
9440
9913
  for (const key of ['deform', 'sequence', 'tracks']) {
9441
9914
  const list = idle[key];
9442
9915
  if (!Array.isArray(list)) continue;
9443
- for (const t of list) if (isRecord(t) && typeof t.slot === 'string') named.add(t.slot);
9916
+ for (const t of list) {
9917
+ if (!isRecord(t)) continue;
9918
+ if (typeof t.slot === 'string') named.add(t.slot);
9919
+ else if (key === 'tracks' && typeof t.group === 'string' && typeof t.property === 'string' &&
9920
+ !isSceneBoneProperty(t.property) && !UNSCALED_PHYSICS_TRACK_PROPERTIES.includes(t.property) &&
9921
+ !FORCE_PHYSICS_TRACK_PROPERTIES.includes(t.property) && Array.isArray(groups[t.group])) {
9922
+ for (const m of groups[t.group] as unknown[]) if (typeof m === 'string') named.add(m);
9923
+ }
9924
+ }
9444
9925
  }
9445
9926
  return named;
9446
9927
  }
9447
9928
 
9929
+ function sliderChannelsForProperty(prop: string): ReadonlyArray<{ prop: string; idx: number; rest: number }> {
9930
+ switch (prop) {
9931
+ case 'rotate': return [{ prop: 'rotate', idx: 0, rest: 0 }];
9932
+ case 'x': return [{ prop: 'translatex', idx: 0, rest: 0 }, { prop: 'translate', idx: 0, rest: 0 }];
9933
+ case 'y': return [{ prop: 'translatey', idx: 0, rest: 0 }, { prop: 'translate', idx: 1, rest: 0 }];
9934
+ case 'scaleX':
9935
+ case 'scalex': return [{ prop: 'scalex', idx: 0, rest: 1 }, { prop: 'scale', idx: 0, rest: 1 }];
9936
+ case 'scaleY':
9937
+ case 'scaley': return [{ prop: 'scaley', idx: 0, rest: 1 }, { prop: 'scale', idx: 1, rest: 1 }];
9938
+ case 'shearX':
9939
+ case 'shearx': return [{ prop: 'shearx', idx: 0, rest: 0 }, { prop: 'shear', idx: 0, rest: 0 }];
9940
+ case 'shearY':
9941
+ case 'sheary': return [{ prop: 'sheary', idx: 0, rest: 0 }, { prop: 'shear', idx: 1, rest: 0 }];
9942
+ default: return [];
9943
+ }
9944
+ }
9945
+
9946
+ function animKeysBoneChannelAwayFromRest(
9947
+ anim: Record<string, unknown>,
9948
+ groups: Record<string, unknown>,
9949
+ bone: string,
9950
+ sliderProp: string,
9951
+ ): boolean {
9952
+ const channels = sliderChannelsForProperty(sliderProp);
9953
+ if (channels.length === 0 || !Array.isArray(anim.tracks)) return false;
9954
+ for (const rawTrack of anim.tracks) {
9955
+ if (!isRecord(rawTrack) || typeof rawTrack.property !== 'string' || !Array.isArray(rawTrack.keys)) continue;
9956
+ const direct = rawTrack.bone === bone;
9957
+ const viaGroup = !direct && typeof rawTrack.group === 'string' && Array.isArray(groups[rawTrack.group]) &&
9958
+ (groups[rawTrack.group] as unknown[]).includes(bone);
9959
+ if (!direct && !viaGroup) continue;
9960
+ for (const ch of channels) {
9961
+ if (rawTrack.property !== ch.prop) continue;
9962
+ for (const k of rawTrack.keys) {
9963
+ if (!isRecord(k)) continue;
9964
+ if (direct) {
9965
+ if (Array.isArray(k.v) && typeof k.v[ch.idx] === 'number' && k.v[ch.idx] !== ch.rest) return true;
9966
+ if (typeof k.v === 'number' && ch.idx === 0 && k.v !== ch.rest) return true;
9967
+ if (isRecord(k.derive) && typeof k.derive.degrees === 'number' && k.derive.degrees !== 0) return true;
9968
+ } else {
9969
+ if (Array.isArray(k.v) && typeof k.v[ch.idx] === 'number' && k.v[ch.idx] !== ch.rest) return true;
9970
+ if (isRecord(k.v)) {
9971
+ const mv = k.v[bone];
9972
+ if (Array.isArray(mv) && typeof mv[ch.idx] === 'number' && mv[ch.idx] !== ch.rest) return true;
9973
+ if (typeof mv === 'number' && ch.idx === 0 && mv !== ch.rest) return true;
9974
+ }
9975
+ if (isRecord(k.derive) && typeof k.derive.degrees === 'number' && k.derive.degrees !== 0) {
9976
+ if (typeof k.derive.depth === 'number' || (isRecord(k.derive.depth) && typeof k.derive.depth[bone] === 'number')) return true;
9977
+ }
9978
+ }
9979
+ }
9980
+ }
9981
+ }
9982
+ return false;
9983
+ }
9984
+
9985
+ /**
9986
+ * Slots driven on the idle through a slider constraint whose input bone channel
9987
+ * the idle keys away from rest (issue #1679), mapped to the dial bone(s) that drive each.
9988
+ */
9989
+ function idleSliderDrivenSlots(rig: Record<string, unknown>, motion: Record<string, unknown>): Map<string, string[]> {
9990
+ const out = new Map<string, string[]>();
9991
+ const anims = isRecord(motion.animations) ? motion.animations : {};
9992
+ const groups = isRecord(motion.groups) ? motion.groups : {};
9993
+ const idle = isRecord(anims.idle) ? anims.idle : null;
9994
+ if (idle === null) return out;
9995
+ const sliders = (Array.isArray(rig.constraints) ? rig.constraints : []).filter(isRecord).filter(
9996
+ (c) => c.type === 'slider' && typeof c.bone === 'string' && typeof c.animation === 'string' && c.mix !== 0 && c.scale !== 0,
9997
+ );
9998
+ for (const c of sliders) {
9999
+ const dialBone = c.bone as string;
10000
+ const animName = c.animation as string;
10001
+ const sliderProp = typeof c.property === 'string' ? c.property : 'rotate';
10002
+ if (!animKeysBoneChannelAwayFromRest(idle, groups, dialBone, sliderProp)) continue;
10003
+ const target = isRecord(anims[animName]) ? anims[animName] : null;
10004
+ if (target === null) continue;
10005
+ const addSlot = (slot: string): void => {
10006
+ const list = out.get(slot);
10007
+ if (list === undefined) out.set(slot, [dialBone]);
10008
+ else if (!list.includes(dialBone)) list.push(dialBone);
10009
+ };
10010
+ for (const key of ['deform', 'sequence', 'tracks'] as const) {
10011
+ const list = target[key];
10012
+ if (!Array.isArray(list)) continue;
10013
+ for (const entry of list) {
10014
+ if (!isRecord(entry)) continue;
10015
+ if (typeof entry.slot === 'string') addSlot(entry.slot);
10016
+ else if (key === 'tracks' && typeof entry.group === 'string' && typeof entry.property === 'string' &&
10017
+ !isSceneBoneProperty(entry.property) && !UNSCALED_PHYSICS_TRACK_PROPERTIES.includes(entry.property) &&
10018
+ !FORCE_PHYSICS_TRACK_PROPERTIES.includes(entry.property) && Array.isArray(groups[entry.group])) {
10019
+ for (const m of groups[entry.group] as unknown[]) if (typeof m === 'string') addSlot(m);
10020
+ }
10021
+ }
10022
+ }
10023
+ }
10024
+ return out;
10025
+ }
10026
+
9448
10027
  /**
9449
10028
  * Whether every attachment the default skin gives a slot is carried by one
9450
10029
  * bone alone: a region or an unweighted mesh on a slot of that bone, or a mesh
@@ -9498,7 +10077,16 @@ interface StillHalf {
9498
10077
  * features go; `footwear` on top) is reported per slot, `crossing`, with no
9499
10078
  * bar ({@link crossingOf}). No render grid enters either half.
9500
10079
  */
9501
- export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | null, geometryPath: string, problems: Problem[], notPlanted: readonly string[] = [], skipped: ReadingSkip<'STILL_REGIONS_DARK'> = skip): JudgementLine {
10080
+ export function stillLine(
10081
+ inp: FullInputs,
10082
+ idle: FrameSet,
10083
+ geo: IdleGeometry | null,
10084
+ geometryPath: string,
10085
+ problems: Problem[],
10086
+ notPlanted: readonly string[] = [],
10087
+ skipped: ReadingSkip<'STILL_REGIONS_DARK'> = skip,
10088
+ forwardedNotPlanted?: Readonly<Record<string, string>>,
10089
+ ): JudgementLine {
9502
10090
  const slotParts = checkSlotParts(inp.rig, inp.parts.parts.map(p => p.name), inp.parts.alternates?.map(set => set.name) ?? []);
9503
10091
  const face = partsTagged(inp.parts, FACE_TAGS);
9504
10092
  const { all: allFeet, held: feet, declared } = plantedFeet(inp.parts, notPlanted);
@@ -9587,16 +10175,21 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
9587
10175
  };
9588
10176
  const firstOf = (names: readonly string[]): number => Math.min(...names.map((n) => slots.findIndex((sl) => sl.name === n)).filter((i) => i >= 0));
9589
10177
 
9590
- const faceHalf = (): Record<string, unknown> | string => {
9591
- if (face.length === 0) return `no part comes from a See-through ${tagWords(FACE_TAGS)} layer`;
10178
+ type FaceHalfResult =
10179
+ | { kind: 'measured'; block: Record<string, unknown> }
10180
+ | { kind: 'all-driven'; reason: string; block: Record<string, unknown> }
10181
+ | { kind: 'unmeasured'; reason: string };
10182
+
10183
+ const faceHalf = (): FaceHalfResult => {
10184
+ if (face.length === 0) return { kind: 'unmeasured', reason: `no part comes from a See-through ${tagWords(FACE_TAGS)} layer` };
9592
10185
  const head = headBoneOf(inp);
9593
- if (!('bone' in head)) return `no head bone to measure it in: ${head.none}`;
10186
+ if (!('bone' in head)) return { kind: 'unmeasured', reason: `no head bone to measure it in: ${head.none}` };
9594
10187
  const track = boneTrackOf(geo, geometryPath, idle, head.bone);
9595
- if (typeof track === 'string') return track;
10188
+ if (typeof track === 'string') return { kind: 'unmeasured', reason: track };
9596
10189
  const maps: FrameMap[] = [];
9597
10190
  for (const f of track.frames) {
9598
10191
  const m = setupToFrame(track.setup, f);
9599
- if (m === null) return `the head bone "${head.bone}" has a singular setup transform, so there is no head frame to carry the face into`;
10192
+ if (m === null) return { kind: 'unmeasured', reason: `the head bone "${head.bone}" has a singular setup transform, so there is no head frame to carry the face into` };
9600
10193
  maps.push(m);
9601
10194
  }
9602
10195
  const entries = [track.setup, ...track.frames];
@@ -9607,9 +10200,9 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
9607
10200
  const swept: WorldBox[] = [];
9608
10201
  for (const p of features) {
9609
10202
  const ft = boneTrackOf(geo, geometryPath, idle, slotBone.get(p.name) ?? '');
9610
- if (typeof ft === 'string') return `no track for feature "${p.name}"'s bone: ${ft}`;
10203
+ if (typeof ft === 'string') return { kind: 'unmeasured', reason: `no track for feature "${p.name}"'s bone: ${ft}` };
9611
10204
  const sb = sweptBox(partWorldBox(p, H, inp.stage), ft, track);
9612
- if (sb === null) return `feature "${p.name}"'s bone or the head bone "${head.bone}" has a singular transform on a frame, so where the feature goes in the head's frame is not known`;
10205
+ if (sb === null) return { kind: 'unmeasured', reason: `feature "${p.name}"'s bone or the head bone "${head.bone}" has a singular transform on a frame, so where the feature goes in the head's frame is not known` };
9613
10206
  swept.push(sb);
9614
10207
  }
9615
10208
  const faceNames = face.map((p) => p.name);
@@ -9624,15 +10217,41 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
9624
10217
  return false;
9625
10218
  });
9626
10219
  };
9627
- const drivenNames = idleDrivenSlots(inp.motion);
9628
- const driven: string[] = [];
9629
- const still = [...faceNames];
10220
+ const directDriven = idleDrivenSlots(inp.motion);
10221
+ const sliderDriven = idleSliderDrivenSlots(inp.rig, inp.motion);
10222
+ const candidates = [...faceNames];
9630
10223
  for (const sl of slots.slice(first + 1)) {
9631
- if (still.includes(sl.name) || !record.has(sl.name) || !ridesOnly(inp.rig, sl.name, sl.bone, head.bone) || !overFace(sl.name)) continue;
9632
- if (drivenNames.has(sl.name)) driven.push(sl.name);
9633
- else still.push(sl.name);
10224
+ if (candidates.includes(sl.name) || !record.has(sl.name) || !ridesOnly(inp.rig, sl.name, sl.bone, head.bone) || !overFace(sl.name)) continue;
10225
+ candidates.push(sl.name);
10226
+ }
10227
+ const driven: string[] = [];
10228
+ const still: string[] = [];
10229
+ const sliderDrivenRecord: Record<string, string[]> = {};
10230
+ for (const name of candidates) {
10231
+ const dials = sliderDriven.get(name);
10232
+ if (directDriven.has(name) || dials !== undefined) {
10233
+ driven.push(name);
10234
+ if (dials !== undefined) sliderDrivenRecord[name] = dials;
10235
+ } else {
10236
+ still.push(name);
10237
+ }
9634
10238
  }
10239
+ const sliderBlock = Object.keys(sliderDrivenRecord).length === 0 ? {} : { slider_driven_slots: sliderDrivenRecord };
9635
10240
  const h = half(still, first, maps, entryMax, coordFloor, regionOf(new Set(face.map((p) => index.get(p.name) as number)), swept));
10241
+ if (still.length === 0) {
10242
+ const drivenDesc = driven.map((slot) => {
10243
+ const dials = sliderDrivenRecord[slot];
10244
+ return dials !== undefined
10245
+ ? `"${slot}" (slider dial ${dials.map((d) => `"${d}"`).join(', ')})`
10246
+ : `"${slot}" (idle slot track)`;
10247
+ }).join(', ');
10248
+ const reason = `every face still-set slot is driven on the idle: ${drivenDesc}`;
10249
+ return {
10250
+ kind: 'all-driven',
10251
+ reason,
10252
+ block: { parts: faceNames, head_bone: head.bone, unmeasured: reason, driven_slots: driven, ...sliderBlock, crossing: h.figures.crossing },
10253
+ };
10254
+ }
9636
10255
  for (const o of h.over) {
9637
10256
  problems.push({
9638
10257
  code: 'CHECK_STILL_REGIONS_DARK',
@@ -9640,12 +10259,12 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
9640
10259
  detail: `its art moves ${sig4(o.max)} rig px relative to that bone at idle frame ${o.frame} (RMS over the still set ${sig4(h.rms)}); at most ${sig4(h.tolerance)} rig px is required — the arithmetic's own rounding, so nothing may move — a mesh over the face weighted to a bone the head does not carry, or the face mesh deformed by another bone`,
9641
10260
  });
9642
10261
  }
9643
- return { parts: faceNames, head_bone: head.bone, ...h.figures, driven_slots: driven };
10262
+ return { kind: 'measured', block: { parts: faceNames, head_bone: head.bone, ...h.figures, driven_slots: driven, ...sliderBlock } };
9644
10263
  };
9645
10264
 
9646
10265
  const feetHalf = (): Record<string, unknown> | string => {
9647
10266
  if (allFeet.length === 0) return `no part comes from a See-through ${tagWords(FEET_TAGS)} layer`;
9648
- if (feet.length === 0) return noneHeldText(declared);
10267
+ if (feet.length === 0) return noneHeldText(declared, forwardedNotPlanted);
9649
10268
  const names = feet.map((p) => p.name);
9650
10269
  const h = half(names, firstOf(names), poses.map(() => null), 1, 0, regionOf(new Set(feet.map((p) => index.get(p.name) as number)), []));
9651
10270
  for (const o of h.over) {
@@ -9660,11 +10279,29 @@ export function stillLine(inp: FullInputs, idle: FrameSet, geo: IdleGeometry | n
9660
10279
 
9661
10280
  const f = faceHalf();
9662
10281
  const t = feetHalf();
9663
- if (typeof f === 'string' && typeof t === 'string') return skipped(`face: ${f}; feet: ${t}`, eligible ? 'no-reading' : 'no-eligible-region');
9664
- const failed = problems.some((q) => q.code === 'CHECK_STILL_REGIONS_DARK');
10282
+ const fwdFeetEntries = declared
10283
+ .filter((n) => forwardedNotPlanted?.[n] !== undefined)
10284
+ .map((n) => [n, forwardedNotPlanted![n]] as const);
10285
+ const fwdFeetBlock = fwdFeetEntries.length === 0 ? {} : { forwarded_from_build: { not_planted: Object.fromEntries(fwdFeetEntries) } };
9665
10286
  // Issue #231: a declaration is the feet half's first figure, measured or not.
9666
- const said = declared.length === 0 ? {} : { declared_not_planted: declared };
9667
- return { status: failed ? 'FAIL' : 'PASS', face: typeof f === 'string' ? { unmeasured: f } : f, feet: typeof t === 'string' ? { ...said, unmeasured: t } : { ...said, ...t } };
10287
+ const said = declared.length === 0 ? {} : { declared_not_planted: declared, ...fwdFeetBlock };
10288
+ if (f.kind === 'unmeasured' && typeof t === 'string') {
10289
+ const got = skipped(`face: ${f.reason}; feet: ${t}`, eligible ? 'no-reading' : 'no-eligible-region');
10290
+ return Object.keys(fwdFeetBlock).length === 0 ? got : { ...got, feet: { ...said, unmeasured: t } };
10291
+ }
10292
+ if (f.kind === 'all-driven' && typeof t === 'string') {
10293
+ return {
10294
+ ...skipped(`face: ${f.reason}; feet: ${t}`, 'no-eligible-region'),
10295
+ face: f.block,
10296
+ feet: { ...said, unmeasured: t },
10297
+ };
10298
+ }
10299
+ const failed = problems.some((q) => q.code === 'CHECK_STILL_REGIONS_DARK');
10300
+ return {
10301
+ status: failed ? 'FAIL' : 'PASS',
10302
+ face: f.kind === 'unmeasured' ? { unmeasured: f.reason } : f.block,
10303
+ feet: typeof t === 'string' ? { ...said, unmeasured: t } : { ...said, ...t },
10304
+ };
9668
10305
  }
9669
10306
 
9670
10307
  function fmt3(x: number): string {
@@ -10050,7 +10687,7 @@ function bandSiteLabel(site: RegionBandSite): string {
10050
10687
  }
10051
10688
 
10052
10689
  function bandTargetShare(part: string, targetBone: string, bindings: readonly StepBinding[]): number {
10053
- const twin = turnTwin(part, targetBone);
10690
+ const twin = rigTurnTwin(part, targetBone);
10054
10691
  const stopped = `${targetBone}_d`;
10055
10692
  let share = 0;
10056
10693
  for (const b of bindings) {
@@ -10961,3 +11598,1490 @@ function scanMotionSeamCellSidecarFile(path: string, expectedSha256: string, bad
10961
11598
  }
10962
11599
  return summaries;
10963
11600
  }
11601
+
11602
+ // ---------------------------------------------------------------------------
11603
+ // composed character manifest checks (issue #1679)
11604
+ // ---------------------------------------------------------------------------
11605
+
11606
+ function prefixCharacterParts(parts: PartsFile, id: string, rig: Readonly<Record<string, unknown>>): PartsFile {
11607
+ const bones = new Set((Array.isArray(rig.bones) ? rig.bones : []).filter(isRecord).map(b => String(b.name)));
11608
+ const rootTarget = bones.has(`${id}:${ROOT_BONE}`) ? `${id}:${ROOT_BONE}` : ROOT_BONE;
11609
+ const mapBone = (b: string): string => b === ROOT_BONE ? rootTarget : `${id}:${b}`;
11610
+ const mapPart = (n: string): string => `${id}:${n}`;
11611
+ const mapRecord = (p: PartRecord): PartRecord => ({
11612
+ ...p,
11613
+ name: mapPart(p.name),
11614
+ ...(p.limb === undefined
11615
+ ? {}
11616
+ : {
11617
+ limb: {
11618
+ ...p.limb,
11619
+ bone: mapBone(p.limb.bone),
11620
+ ...(p.limb.band === undefined ? {} : { band: { ...p.limb.band, upper: mapBone(p.limb.band.upper) } }),
11621
+ },
11622
+ }),
11623
+ });
11624
+ return {
11625
+ ...parts,
11626
+ parts: parts.parts.map(mapRecord),
11627
+ ...(parts.motion_seams === undefined
11628
+ ? {}
11629
+ : { motion_seams: parts.motion_seams.map(s => ({ ...s, part: mapPart(s.part), neighbour: mapPart(s.neighbour) })) }),
11630
+ ...(parts.alternates === undefined
11631
+ ? {}
11632
+ : {
11633
+ alternates: parts.alternates.map(alt => ({
11634
+ ...alt,
11635
+ slots: Object.fromEntries(Object.entries(alt.slots).map(([k, v]) => [mapPart(k), mapPart(v)])),
11636
+ ...(alt.hides === undefined ? {} : { hides: alt.hides.map(mapPart) }),
11637
+ ...(alt.front === undefined ? {} : { front: alt.front.map(mapPart) }),
11638
+ ...(alt.parts === undefined ? {} : { parts: alt.parts.map(mapPart) }),
11639
+ ...(alt.drawn === undefined ? {} : { drawn: Object.fromEntries(Object.entries(alt.drawn).map(([b, deg]) => [mapBone(b), deg])) }),
11640
+ records: alt.records.map(mapRecord),
11641
+ })),
11642
+ }),
11643
+ };
11644
+ }
11645
+
11646
+ function scopeCharacterRig(
11647
+ rig: Record<string, unknown>,
11648
+ motion: Record<string, unknown>,
11649
+ id: string,
11650
+ ): { rig: Record<string, unknown>; motion: Record<string, unknown>; onlyCharacterInRig: boolean } {
11651
+ const prefix = `${id}:`;
11652
+ const allSlots = (Array.isArray(rig.slots) ? rig.slots : []).filter(isRecord);
11653
+ const onlyCharacterInRig = allSlots.length > 0 && allSlots.every(s => typeof s.name === 'string' && s.name.startsWith(prefix));
11654
+ if (onlyCharacterInRig) return { rig, motion, onlyCharacterInRig: true };
11655
+
11656
+ const slots = allSlots.filter(s => typeof s.name === 'string' && s.name.startsWith(prefix));
11657
+ const slotNames = new Set(slots.map(s => String(s.name)));
11658
+ const skins = isRecord(rig.skins) ? rig.skins : {};
11659
+ const defaultSkin = isRecord(skins.default) ? skins.default : {};
11660
+ const scopedSkin = Object.fromEntries(Object.entries(defaultSkin).filter(([k]) => slotNames.has(k)));
11661
+ const hasMesh = Object.values(scopedSkin).some(drawings =>
11662
+ isRecord(drawings) && Object.values(drawings).some(att => isRecord(att) && att.type === 'mesh'));
11663
+ const bones = (Array.isArray(rig.bones) ? rig.bones : []).filter(isRecord)
11664
+ .filter(b => b.name === ROOT_BONE || (typeof b.name === 'string' && b.name.startsWith(prefix)));
11665
+ const constraints = (Array.isArray(rig.constraints) ? rig.constraints : []).filter(isRecord)
11666
+ .filter(c => typeof c.name === 'string' && c.name.startsWith(prefix));
11667
+ const stops = (Array.isArray(rig.stops) ? rig.stops : []).filter(isRecord)
11668
+ .filter(st => typeof st.chain === 'string' && st.chain.startsWith(prefix));
11669
+
11670
+ let scopedInvariants: Record<string, unknown> | undefined;
11671
+ if (isRecord(rig.invariants)) {
11672
+ const inv: Record<string, unknown> = {};
11673
+ if (Array.isArray(rig.invariants.detached)) {
11674
+ const det = rig.invariants.detached.filter(d => isRecord(d) && typeof d.bone === 'string' && d.bone.startsWith(prefix));
11675
+ if (det.length > 0) inv.detached = det;
11676
+ }
11677
+ if ((rig.invariants.idleDrivesMeshes === true || isRecord(rig.invariants.idleDrivesMeshes)) && hasMesh) {
11678
+ inv.idleDrivesMeshes = rig.invariants.idleDrivesMeshes;
11679
+ }
11680
+ if (Array.isArray(rig.invariants.deformMayFold)) {
11681
+ const dmf = rig.invariants.deformMayFold.filter(e => isRecord(e) && typeof e.slot === 'string' && slotNames.has(e.slot));
11682
+ if (dmf.length > 0) inv.deformMayFold = dmf;
11683
+ } else if (isRecord(rig.invariants.deformMayFold)) {
11684
+ const dmf = Object.fromEntries(Object.entries(rig.invariants.deformMayFold).filter(([sl]) => slotNames.has(sl)));
11685
+ if (Object.keys(dmf).length > 0) inv.deformMayFold = dmf;
11686
+ }
11687
+ if (Array.isArray(rig.invariants.axes)) {
11688
+ const ax = rig.invariants.axes.filter(a => isRecord(a) && typeof a.name === 'string' && a.name.startsWith(prefix));
11689
+ if (ax.length > 0) inv.axes = ax;
11690
+ }
11691
+ if (Array.isArray(rig.invariants.deformSliderCombinations)) {
11692
+ const comb = rig.invariants.deformSliderCombinations.filter(cb =>
11693
+ isRecord(cb) && Array.isArray(cb.inputs) && cb.inputs.length > 0 &&
11694
+ cb.inputs.every(inp => isRecord(inp) && typeof inp.slider === 'string' && inp.slider.startsWith(prefix)));
11695
+ if (comb.length > 0) inv.deformSliderCombinations = comb;
11696
+ }
11697
+ if (rig.invariants.meshSlots !== undefined || rig.invariants.meshTriangles !== undefined) {
11698
+ let meshSlots = 0;
11699
+ let meshTriangles = 0;
11700
+ for (const drawings of Object.values(scopedSkin)) {
11701
+ if (!isRecord(drawings)) continue;
11702
+ let slotHasMesh = false;
11703
+ for (const att of Object.values(drawings)) {
11704
+ if (isRecord(att) && att.type === 'mesh') {
11705
+ slotHasMesh = true;
11706
+ const gen = isRecord(att.generator) ? att.generator : null;
11707
+ const tris = gen !== null && gen.kind === 'grid' && typeof gen.cols === 'number' && typeof gen.rows === 'number'
11708
+ ? 2 * (gen.cols - 1) * (gen.rows - 1)
11709
+ : Array.isArray(att.triangles) ? att.triangles.length / 3 : 0;
11710
+ if (tris > meshTriangles) meshTriangles = tris;
11711
+ }
11712
+ }
11713
+ if (slotHasMesh) meshSlots++;
11714
+ }
11715
+ if (rig.invariants.meshSlots !== undefined) inv.meshSlots = meshSlots;
11716
+ if (rig.invariants.meshTriangles !== undefined) inv.meshTriangles = meshTriangles;
11717
+ }
11718
+ if (Object.keys(inv).length > 0) scopedInvariants = inv;
11719
+ }
11720
+
11721
+ const scopedRig: Record<string, unknown> = {
11722
+ ...rig,
11723
+ bones,
11724
+ slots,
11725
+ skins: { ...skins, default: scopedSkin },
11726
+ ...(constraints.length === 0 ? {} : { constraints }),
11727
+ ...(stops.length === 0 ? {} : { stops }),
11728
+ };
11729
+ if (constraints.length === 0) delete scopedRig.constraints;
11730
+ if (stops.length === 0) delete scopedRig.stops;
11731
+ if (scopedInvariants === undefined) delete scopedRig.invariants;
11732
+ else scopedRig.invariants = scopedInvariants;
11733
+
11734
+ const rawGroups = isRecord(motion.groups) ? motion.groups : undefined;
11735
+ const scopedGroups: Record<string, string[]> = {};
11736
+ if (rawGroups !== undefined) {
11737
+ for (const [k, v] of Object.entries(rawGroups)) {
11738
+ if (!Array.isArray(v)) continue;
11739
+ if (k.startsWith(prefix)) {
11740
+ scopedGroups[k] = v.filter((m): m is string => typeof m === 'string');
11741
+ } else {
11742
+ const kept = v.filter((m): m is string => typeof m === 'string' && (m === ROOT_BONE || m.startsWith(prefix)));
11743
+ if (kept.length > 0) scopedGroups[k] = kept;
11744
+ }
11745
+ }
11746
+ }
11747
+ const keptGroupSet = new Map(Object.entries(scopedGroups).map(([k, v]) => [k, new Set(v)]));
11748
+ const easings = isRecord(motion.easings)
11749
+ ? Object.fromEntries(Object.entries(motion.easings).filter(([k]) => !k.includes(':') || k.startsWith(prefix)))
11750
+ : undefined;
11751
+ const rawAnims = isRecord(motion.animations) ? motion.animations : {};
11752
+ const scopeTrack = (t: unknown): Record<string, unknown> | null => {
11753
+ if (!isRecord(t)) return null;
11754
+ if (typeof t.bone === 'string') return t.bone === ROOT_BONE || t.bone.startsWith(prefix) ? t : null;
11755
+ if (typeof t.group === 'string') {
11756
+ const members = keptGroupSet.get(t.group);
11757
+ if (members === undefined) return null;
11758
+ if (t.group.startsWith(prefix) || !Array.isArray(t.keys)) return t;
11759
+ const filterMap = (rec: Record<string, unknown>): Record<string, unknown> =>
11760
+ Object.fromEntries(Object.entries(rec).filter(([m]) => members.has(m)));
11761
+ return {
11762
+ ...t,
11763
+ keys: t.keys.map(k => !isRecord(k) ? k : {
11764
+ ...k,
11765
+ ...(isRecord(k.v) ? { v: filterMap(k.v) } : {}),
11766
+ ...(isRecord(k.derive) && isRecord(k.derive.depth) ? { derive: { ...k.derive, depth: filterMap(k.derive.depth) } } : {}),
11767
+ }),
11768
+ };
11769
+ }
11770
+ for (const k of ['slot', 'physics', 'ik', 'transform', 'path', 'slider']) {
11771
+ if (typeof t[k] === 'string') return (t[k] as string).startsWith(prefix) ? t : null;
11772
+ }
11773
+ return null;
11774
+ };
11775
+ const scopedAnims: Record<string, unknown> = {};
11776
+ for (const [animName, anim] of Object.entries(rawAnims)) {
11777
+ if (!isRecord(anim)) continue;
11778
+ if (animName !== 'idle' && animName.includes(':') && !animName.startsWith(prefix)) continue;
11779
+ const tracks = Array.isArray(anim.tracks) ? anim.tracks.map(scopeTrack).filter((tr): tr is Record<string, unknown> => tr !== null) : [];
11780
+ const deform = Array.isArray(anim.deform) ? anim.deform.filter(d => isRecord(d) && typeof d.slot === 'string' && slotNames.has(d.slot)) : undefined;
11781
+ const sequence = Array.isArray(anim.sequence) ? anim.sequence.filter(sq => isRecord(sq) && typeof sq.slot === 'string' && slotNames.has(sq.slot)) : undefined;
11782
+ const hasContent = tracks.length > 0 || (deform !== undefined && deform.length > 0) || (sequence !== undefined && sequence.length > 0);
11783
+ if (animName !== 'idle' && !animName.startsWith(prefix) && !hasContent) continue;
11784
+ const nextAnim: Record<string, unknown> = { ...anim, tracks };
11785
+ if (deform !== undefined) {
11786
+ if (deform.length > 0) nextAnim.deform = deform;
11787
+ else delete nextAnim.deform;
11788
+ }
11789
+ if (sequence !== undefined) {
11790
+ if (sequence.length > 0) nextAnim.sequence = sequence;
11791
+ else delete nextAnim.sequence;
11792
+ }
11793
+ scopedAnims[animName] = nextAnim;
11794
+ }
11795
+
11796
+ const scopedMotion: Record<string, unknown> = {
11797
+ ...motion,
11798
+ animations: scopedAnims,
11799
+ };
11800
+ if (rawGroups !== undefined) scopedMotion.groups = scopedGroups;
11801
+ if (easings !== undefined) scopedMotion.easings = easings;
11802
+ return { rig: scopedRig, motion: scopedMotion, onlyCharacterInRig: false };
11803
+ }
11804
+
11805
+ function stripCharacterSlotPrefixForSeam(
11806
+ rig: Record<string, unknown>,
11807
+ motion: Record<string, unknown>,
11808
+ id: string,
11809
+ ): { rig: Record<string, unknown>; motion: Record<string, unknown>; unprefixSlot: (name: string) => string } {
11810
+ const prefix = `${id}:`;
11811
+ const unprefixSlot = (name: string): string => name.startsWith(prefix) ? name.slice(prefix.length) : name;
11812
+ const slots = (Array.isArray(rig.slots) ? rig.slots : []).map(s =>
11813
+ isRecord(s) && typeof s.name === 'string' ? { ...s, name: unprefixSlot(s.name) } : s);
11814
+ const skins = isRecord(rig.skins) ? rig.skins : {};
11815
+ const defaultSkin = isRecord(skins.default)
11816
+ ? Object.fromEntries(Object.entries(skins.default).map(([slot, drawings]) => [unprefixSlot(slot), drawings]))
11817
+ : skins.default;
11818
+ const constraints = Array.isArray(rig.constraints)
11819
+ ? rig.constraints.map(con =>
11820
+ isRecord(con) && con.type === 'path' && typeof con.slot === 'string'
11821
+ ? { ...con, slot: unprefixSlot(con.slot) }
11822
+ : con)
11823
+ : undefined;
11824
+ let invariants = rig.invariants;
11825
+ if (isRecord(rig.invariants) && rig.invariants.deformMayFold !== undefined) {
11826
+ if (Array.isArray(rig.invariants.deformMayFold)) {
11827
+ invariants = {
11828
+ ...rig.invariants,
11829
+ deformMayFold: rig.invariants.deformMayFold.map(e =>
11830
+ isRecord(e) && typeof e.slot === 'string' ? { ...e, slot: unprefixSlot(e.slot) } : e),
11831
+ };
11832
+ } else if (isRecord(rig.invariants.deformMayFold)) {
11833
+ invariants = {
11834
+ ...rig.invariants,
11835
+ deformMayFold: Object.fromEntries(Object.entries(rig.invariants.deformMayFold).map(([sl, v]) => [unprefixSlot(sl), v])),
11836
+ };
11837
+ }
11838
+ }
11839
+ const seamRig: Record<string, unknown> = {
11840
+ ...rig,
11841
+ slots,
11842
+ skins: { ...skins, default: defaultSkin },
11843
+ ...(constraints === undefined ? {} : { constraints }),
11844
+ ...(invariants === undefined ? {} : { invariants }),
11845
+ };
11846
+
11847
+ const slotGroups = new Set<string>();
11848
+ const rawAnims = isRecord(motion.animations) ? motion.animations : {};
11849
+ for (const anim of Object.values(rawAnims)) {
11850
+ if (!isRecord(anim) || !Array.isArray(anim.tracks)) continue;
11851
+ for (const tr of anim.tracks) {
11852
+ if (!isRecord(tr) || typeof tr.group !== 'string' || typeof tr.property !== 'string') continue;
11853
+ if (!isSceneBoneProperty(tr.property) &&
11854
+ !UNSCALED_PHYSICS_TRACK_PROPERTIES.includes(tr.property) &&
11855
+ !FORCE_PHYSICS_TRACK_PROPERTIES.includes(tr.property)) {
11856
+ slotGroups.add(tr.group);
11857
+ }
11858
+ }
11859
+ }
11860
+ const groups = isRecord(motion.groups)
11861
+ ? Object.fromEntries(Object.entries(motion.groups).map(([g, members]) => [
11862
+ g,
11863
+ slotGroups.has(g) && Array.isArray(members) ? members.map(m => typeof m === 'string' ? unprefixSlot(m) : m) : members,
11864
+ ]))
11865
+ : undefined;
11866
+ const mapSlotRecord = (rec: Record<string, unknown>): Record<string, unknown> =>
11867
+ Object.fromEntries(Object.entries(rec).map(([k, v]) => [unprefixSlot(k), v]));
11868
+ const animations: Record<string, unknown> = {};
11869
+ for (const [animName, anim] of Object.entries(rawAnims)) {
11870
+ if (!isRecord(anim)) {
11871
+ animations[animName] = anim;
11872
+ continue;
11873
+ }
11874
+ const tracks = Array.isArray(anim.tracks)
11875
+ ? anim.tracks.map(tr => {
11876
+ if (!isRecord(tr)) return tr;
11877
+ if (typeof tr.slot === 'string') return { ...tr, slot: unprefixSlot(tr.slot) };
11878
+ if (typeof tr.group === 'string' && slotGroups.has(tr.group) && Array.isArray(tr.keys)) {
11879
+ return {
11880
+ ...tr,
11881
+ keys: tr.keys.map(k => !isRecord(k) ? k : {
11882
+ ...k,
11883
+ ...(isRecord(k.v) ? { v: mapSlotRecord(k.v) } : {}),
11884
+ ...(isRecord(k.derive) && isRecord(k.derive.depth) ? { derive: { ...k.derive, depth: mapSlotRecord(k.derive.depth) } } : {}),
11885
+ }),
11886
+ };
11887
+ }
11888
+ return tr;
11889
+ })
11890
+ : anim.tracks;
11891
+ const deform = Array.isArray(anim.deform)
11892
+ ? anim.deform.map(d => isRecord(d) && typeof d.slot === 'string' ? { ...d, slot: unprefixSlot(d.slot) } : d)
11893
+ : undefined;
11894
+ const sequence = Array.isArray(anim.sequence)
11895
+ ? anim.sequence.map(sq => isRecord(sq) && typeof sq.slot === 'string' ? { ...sq, slot: unprefixSlot(sq.slot) } : sq)
11896
+ : undefined;
11897
+ animations[animName] = {
11898
+ ...anim,
11899
+ tracks,
11900
+ ...(deform === undefined ? {} : { deform }),
11901
+ ...(sequence === undefined ? {} : { sequence }),
11902
+ };
11903
+ }
11904
+ const seamMotion: Record<string, unknown> = {
11905
+ ...motion,
11906
+ ...(groups === undefined ? {} : { groups }),
11907
+ animations,
11908
+ };
11909
+ return { rig: seamRig, motion: seamMotion, unprefixSlot };
11910
+ }
11911
+
11912
+ function unplaceCharacterRig(
11913
+ rig: Record<string, unknown>,
11914
+ id: string,
11915
+ shiftX: number,
11916
+ shiftY: number,
11917
+ scale: number,
11918
+ ): Record<string, unknown> {
11919
+ if (shiftX === 0 && shiftY === 0 && scale === 1) return rig;
11920
+ const pivotName = `${id}:${PLACEMENT_BONE_NAME}`;
11921
+ const bones = (Array.isArray(rig.bones) ? rig.bones : []).map(b => {
11922
+ if (!isRecord(b) || typeof b.name !== 'string' || b.name === ROOT_BONE || b.name === pivotName || b.name === `${id}:${ROOT_BONE}`) return b;
11923
+ const first = b.parent === ROOT_BONE || b.parent === pivotName;
11924
+ const rawX = typeof b.x === 'number' ? b.x : 0;
11925
+ const rawY = typeof b.y === 'number' ? b.y : 0;
11926
+ return {
11927
+ ...b,
11928
+ x: (first ? rawX - shiftX : rawX) / scale,
11929
+ y: (first ? rawY - shiftY : rawY) / scale,
11930
+ ...(typeof b.length === 'number' ? { length: b.length / scale } : {}),
11931
+ };
11932
+ });
11933
+ return { ...rig, bones };
11934
+ }
11935
+
11936
+ function unplaceGeometryFile(srcPath: string, destPath: string, shiftX: number, shiftY: number, scale: number): void {
11937
+ const raw: unknown = JSON.parse(readFileSync(srcPath, 'utf8'));
11938
+ if (!isRecord(raw)) {
11939
+ copyFileSync(srcPath, destPath);
11940
+ return;
11941
+ }
11942
+ const mapVerts = (vs: unknown): unknown => {
11943
+ if (!Array.isArray(vs)) return vs;
11944
+ return vs.map((v, i) => typeof v === 'number' ? ((i % 2 === 0 ? v - shiftX : v - shiftY) / scale) : v);
11945
+ };
11946
+ const mapBones = (bs: unknown): unknown => {
11947
+ if (!Array.isArray(bs)) return bs;
11948
+ return bs.map(b => isRecord(b) && typeof b.worldX === 'number' && typeof b.worldY === 'number'
11949
+ ? { ...b, worldX: (b.worldX - shiftX) / scale, worldY: (b.worldY - shiftY) / scale }
11950
+ : b);
11951
+ };
11952
+ const out: Record<string, unknown> = {
11953
+ ...raw,
11954
+ ...(Array.isArray(raw.rest)
11955
+ ? { rest: raw.rest.map(r => isRecord(r) ? { ...r, vertices: mapVerts(r.vertices) } : r) }
11956
+ : {}),
11957
+ ...(isRecord(raw.setup)
11958
+ ? { setup: { ...raw.setup, bones: mapBones(raw.setup.bones) } }
11959
+ : {}),
11960
+ ...(Array.isArray(raw.frames)
11961
+ ? {
11962
+ frames: raw.frames.map(f => isRecord(f)
11963
+ ? {
11964
+ ...f,
11965
+ bones: mapBones(f.bones),
11966
+ ...(Array.isArray(f.attachments)
11967
+ ? { attachments: f.attachments.map(a => isRecord(a) ? { ...a, vertices: mapVerts(a.vertices) } : a) }
11968
+ : {}),
11969
+ }
11970
+ : f),
11971
+ }
11972
+ : {}),
11973
+ };
11974
+ writeFileSync(destPath, JSON.stringify(out));
11975
+ }
11976
+
11977
+ function levelFeetForCharacter(parts: PartsFile, rig: Record<string, unknown>, id: string): LevelFoot[] {
11978
+ const carriers = new Set([ROOT_BONE, `${id}:${ROOT_BONE}`, `${id}:${PLACEMENT_BONE_NAME}`]);
11979
+ return levelFeet(parts, rig).filter(f => !carriers.has(f.bone));
11980
+ }
11981
+
11982
+ function measureOneComposedCharacter(
11983
+ c: ResolvedComposedCharacter,
11984
+ ctx: {
11985
+ inp: CheckInputs;
11986
+ out: string;
11987
+ buildDir: string;
11988
+ pack: readonly PackLine[];
11989
+ mode: PackMode;
11990
+ rigc: RigcRunner;
11991
+ measured: RigcRunner;
11992
+ env: CheckEnvironment | null;
11993
+ idle: FrameSet | null;
11994
+ reqFile: RequirementsFile | null;
11995
+ seams: Map<string, SeamPair[]> | null;
11996
+ seamPairsAsked: boolean;
11997
+ seamRequired: boolean;
11998
+ keepStills: boolean;
11999
+ meshReport: unknown;
12000
+ multiCharacter: boolean;
12001
+ },
12002
+ ): { report: ComposedCharacterReport; problems: Problem[] } {
12003
+ const { inp, out, mode, rigc, measured, env, reqFile, seams, seamPairsAsked, seamRequired, keepStills, meshReport, multiCharacter } = ctx;
12004
+ const prefParts = prefixCharacterParts(c.parts, c.id, inp.rig);
12005
+ const [charW, charH] = prefParts.rig_size;
12006
+ const s = c.scale;
12007
+ const [ox, oy] = c.offset;
12008
+ const charStage: StageBox = {
12009
+ x: inp.stage.x + ox,
12010
+ y: inp.stage.y + cropToSpineY(oy + s * charH, inp.stage.height),
12011
+ width: s * charW,
12012
+ height: s * charH,
12013
+ };
12014
+ const origStage: StageBox = { x: -charW / 2, y: 0, width: charW, height: charH };
12015
+ const shiftX = charStage.x - s * origStage.x;
12016
+ const shiftY = charStage.y;
12017
+ const identityPlacement = s === 1 && ox === 0 && oy === 0 && inp.stage.width === charW && inp.stage.height === charH;
12018
+
12019
+ const { rig: charRig, motion: charMotion, onlyCharacterInRig } = scopeCharacterRig(inp.rig, inp.motion, c.id);
12020
+ const charAnimNames = isRecord(charMotion.animations) ? Object.keys(charMotion.animations) : [];
12021
+ const charStripped = withoutPhysics(charRig, charMotion);
12022
+ const seg = diagnosticSegment(c.id);
12023
+ const scratchDir = join(out, `_char_${seg}`);
12024
+ rmSync(scratchDir, { recursive: true, force: true });
12025
+ mkdirSync(scratchDir, { recursive: true });
12026
+
12027
+ const problems: Problem[] = [];
12028
+ const charSkipReasons: CheckBarSkipReasons = {};
12029
+ const readingSkip = <Id extends keyof CheckBarSkipReasons>(id: Id): ReadingSkip<Id> => (reason, code) => {
12030
+ charSkipReasons[id] = code;
12031
+ return skip(reason);
12032
+ };
12033
+ const lacking = [inp.noIdle].filter((r): r is string => r !== null).join('; ');
12034
+
12035
+ try {
12036
+ const images = typeof inp.rig.images === 'string' ? resolve(inp.rigDir, inp.rig.images) : inp.rig.images;
12037
+ let charBuildDir = ctx.buildDir;
12038
+ let charIdle = ctx.idle;
12039
+ if (!onlyCharacterInRig) {
12040
+ charBuildDir = join(scratchDir, 'build');
12041
+ const rigFile = join(scratchDir, 'rig.json');
12042
+ const motionFile = join(scratchDir, 'motion.json');
12043
+ writeFileSync(rigFile, JSON.stringify({ ...charRig, images }));
12044
+ writeFileSync(motionFile, JSON.stringify(charMotion));
12045
+ const b = rigc(['build', '--rig', rigFile, '--motion', motionFile, '--out', charBuildDir, ...packedBuildArgs(mode)]);
12046
+ if (b.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (character "${c.id}")`, b, buildGateLines(b.out)));
12047
+ if (inp.idleDuration !== null) {
12048
+ const charIdleDir = join(scratchDir, 'idle');
12049
+ const ir = measured(['render', '--candidate', charBuildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--geometry', '--out', charIdleDir]);
12050
+ if (ir.status !== 0) refuseIfAny(rigcFailed(`render --animation idle --geometry (character "${c.id}")`, ir, ir.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12051
+ charIdle = readFrameSet(charIdleDir);
12052
+ }
12053
+ }
12054
+
12055
+ const scaledParts: PartsFile = s === 1
12056
+ ? prefParts
12057
+ : { ...prefParts, rig_size: [charStage.width, charStage.height], parts: prefParts.parts.map(p => ({ ...p, x: p.x * s, y: p.y * s, w: p.w * s, h: p.h * s })) };
12058
+
12059
+ const charInputsScaled: FullInputs | null = inp.idleDuration === null ? null : {
12060
+ ...inp,
12061
+ rig: charRig,
12062
+ motion: charMotion,
12063
+ partsPath: c.partsPath,
12064
+ partsDir: c.partsDir,
12065
+ parts: scaledParts,
12066
+ noParts: null,
12067
+ stage: charStage,
12068
+ idleDuration: inp.idleDuration,
12069
+ source: c.source,
12070
+ };
12071
+
12072
+ const unplacedRig = unplaceCharacterRig(charRig, c.id, shiftX, shiftY, s);
12073
+ const charInputsOrig: FullInputs | null = inp.idleDuration === null ? null : {
12074
+ ...inp,
12075
+ rig: unplacedRig,
12076
+ motion: charMotion,
12077
+ partsPath: c.partsPath,
12078
+ partsDir: c.partsDir,
12079
+ parts: prefParts,
12080
+ noParts: null,
12081
+ stage: origStage,
12082
+ idleDuration: inp.idleDuration,
12083
+ source: c.source,
12084
+ };
12085
+
12086
+ // 1. LIMB_ONE_BONE
12087
+ const limbProblems: Problem[] = [];
12088
+ const limbs = limbLine(prefParts, charRig, limbProblems, meshReport);
12089
+
12090
+ // 2. FEET_STAY_LEVEL
12091
+ const feet = levelFeetForCharacter(prefParts, charRig, c.id);
12092
+ let level: LevelLine | null = null;
12093
+ const levelProblems: Problem[] = [];
12094
+ if (feet.length > 0 && charAnimNames.length > 0) {
12095
+ const levelScratch = join(scratchDir, 'level');
12096
+ mkdirSync(levelScratch, { recursive: true });
12097
+ if (charStripped === null) {
12098
+ const fr = measured(['render', '--candidate', charBuildDir, '--folds', '--geometry', '--fps', String(IDLE_FPS), '--max', String(FOLD_RENDER_MAX), '--out', levelScratch]);
12099
+ if (fr.status !== 0) refuseIfAny(rigcFailed(`render --folds --geometry --fps ${IDLE_FPS} (character "${c.id}")`, fr, fr.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12100
+ const sets = readJson(join(levelScratch, 'frames.json'), []);
12101
+ const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
12102
+ const levelReadings = charAnimNames.map(name => {
12103
+ const dir = join(levelScratch, String((listed.find(x => x.animation === name) as Record<string, unknown>).dir));
12104
+ return { animation: name, set: readFrameSet(dir), geometryPath: join(dir, GEOMETRY_FILE) };
12105
+ });
12106
+ level = levelLine(feet, charRig, levelReadings, IDLE_FPS, 0, levelProblems);
12107
+ } else {
12108
+ const keyedNames = isRecord(charStripped.motion.animations) ? Object.keys(charStripped.motion.animations) : [];
12109
+ let levelReadings: LevelReading[] = [];
12110
+ if (keyedNames.length > 0) {
12111
+ const keyedDir = join(levelScratch, 'keyed');
12112
+ mkdirSync(keyedDir, { recursive: true });
12113
+ writeFileSync(join(keyedDir, 'rig.json'), JSON.stringify({ ...charStripped.rig, images }));
12114
+ writeFileSync(join(keyedDir, 'motion.json'), JSON.stringify(charStripped.motion));
12115
+ const kb = rigc(['build', '--rig', join(keyedDir, 'rig.json'), '--motion', join(keyedDir, 'motion.json'), '--out', join(keyedDir, 'build'), ...packedBuildArgs(mode)]);
12116
+ if (kb.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (character "${c.id}" level physics-off)`, kb, buildGateLines(kb.out)));
12117
+ const frOff = rigc(['render', '--candidate', join(keyedDir, 'build'), '--folds', '--geometry', '--fps', String(IDLE_FPS), '--max', String(FOLD_RENDER_MAX), '--out', join(keyedDir, 'render')]);
12118
+ if (frOff.status !== 0) refuseIfAny(rigcFailed(`render --folds --geometry (character "${c.id}" level physics-off)`, frOff, frOff.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12119
+ const sets = readJson(join(keyedDir, 'render', 'frames.json'), []);
12120
+ const listed = sets !== null && Array.isArray(sets.sets) ? sets.sets.filter(isRecord) : [];
12121
+ levelReadings = keyedNames.map(name => {
12122
+ const dir = join(keyedDir, 'render', String((listed.find(x => x.animation === name) as Record<string, unknown>).dir));
12123
+ return { animation: name, set: readFrameSet(dir), geometryPath: join(dir, GEOMETRY_FILE) };
12124
+ });
12125
+ }
12126
+ level = levelLine(feet, charRig, levelReadings, IDLE_FPS, charStripped.physics.length, levelProblems);
12127
+ }
12128
+ }
12129
+
12130
+ // 3. BREATH_VISIBLE, TIP_OVER_ROOT, STILL_REGIONS_DARK, PHYSICS_CONTRIBUTES
12131
+ const fwd = c.forwardedExceptions;
12132
+ const sceneNotPlanted = reqFile === null ? [] : reqFile.not_planted.filter(n => n.startsWith(`${c.id}:`));
12133
+ const notPlanted = [...new Set([...(fwd?.not_planted ?? []), ...sceneNotPlanted])];
12134
+ const forwardedNotPlanted = fwd === undefined || fwd.not_planted.length === 0
12135
+ ? undefined
12136
+ : Object.fromEntries(fwd.not_planted.map(n => [n, fwd.build]));
12137
+ let breath: JudgementLine = skip(lacking);
12138
+ let tip: JudgementLine = skip(lacking);
12139
+ let still: JudgementLine = skip(lacking);
12140
+ let physics: PhysicsContributionLine = charIdle === null
12141
+ ? physicsLine([], IDLE_FPS, 0, 'none', "rig-c's default environment", inp.noIdle ?? 'no idle')
12142
+ : physicsLine([], IDLE_FPS, 0, 'none', "rig-c's default environment", 'no physics');
12143
+
12144
+ if (charInputsScaled !== null && charInputsOrig !== null && charIdle !== null) {
12145
+ const isoDir = join(scratchDir, 'isolated');
12146
+ const isolated = (label: string, ps: readonly PartRecord[]): FrameSet => {
12147
+ const dir = join(isoDir, label);
12148
+ const r = measured(['render', '--candidate', charBuildDir, '--animation', 'idle', '--fps', String(IDLE_FPS), '--max', String(IDLE_MAX_PX), '--slot', ps.map(p => p.name).join(','), '--out', dir]);
12149
+ 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:'))));
12150
+ return readFrameSet(dir);
12151
+ };
12152
+ const prefix = `${c.id}:`;
12153
+ const carrierExclusions = new Set([ROOT_BONE, `${prefix}${ROOT_BONE}`, `${prefix}${PLACEMENT_BONE_NAME}`]);
12154
+ const breathPair = (ps: readonly PartRecord[]): BreathPair | null => {
12155
+ const tracks = breathTracks(charMotion).filter(t => t.bone.startsWith(prefix) && !carrierExclusions.has(t.bone));
12156
+ if (tracks.length === 0) return null;
12157
+ const dir = join(isoDir, BREATH_SCRATCH);
12158
+ const anims = isRecord(charMotion.animations) ? charMotion.animations : {};
12159
+ const idleAnim = isRecord(anims.idle) ? anims.idle : {};
12160
+ let name = BREATH_ANIMATION;
12161
+ while (name in anims) name = `${name}_`;
12162
+ const kept = (Array.isArray(idleAnim.tracks) ? idleAnim.tracks : []).map(t => (isRecord(t) && isBreathTrack(t, tracks) ? heldTrack(t) : t));
12163
+ mkdirSync(dir, { recursive: true });
12164
+ writeFileSync(join(dir, 'rig.json'), JSON.stringify({ ...charRig, images }));
12165
+ writeFileSync(join(dir, 'motion.json'), JSON.stringify({ ...charMotion, animations: { ...anims, [name]: { ...idleAnim, tracks: kept } } }));
12166
+ const b = rigc(['build', '--rig', join(dir, 'rig.json'), '--motion', join(dir, 'motion.json'), '--out', join(dir, 'build'), ...packedBuildArgs(mode)]);
12167
+ if (b.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (BREATH_VISIBLE's copy, character "${c.id}")`, b, buildGateLines(b.out)));
12168
+ const slots = ps.map(p => p.name).join(',');
12169
+ const render = (animation: string, label: string): FrameSet => {
12170
+ 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)]);
12171
+ 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:'))));
12172
+ return readFrameSet(join(dir, label));
12173
+ };
12174
+ return { with: render('idle', 'with'), without: render(name, 'without'), tracks: tracks.map(t => `${t.bone} ${t.property}`) };
12175
+ };
12176
+
12177
+ breath = breathLine(charInputsScaled, isolated, breathPair, problems, notPlanted, readingSkip('BREATH_VISIBLE'), forwardedNotPlanted);
12178
+
12179
+ const rawGeoPath = join(charIdle.dir, GEOMETRY_FILE);
12180
+ let geoPath = rawGeoPath;
12181
+ if (!identityPlacement && existsSync(rawGeoPath)) {
12182
+ geoPath = join(scratchDir, 'unplaced_geometry.json');
12183
+ unplaceGeometryFile(rawGeoPath, geoPath, shiftX, shiftY, s);
12184
+ }
12185
+ const sceneNotSwinging = reqFile === null ? [] : reqFile.not_swinging.filter(n => n.startsWith(prefix));
12186
+ const sceneRises = reqFile === null ? [] : reqFile.rises.filter(n => n.startsWith(prefix));
12187
+ const sceneRests = reqFile === null ? [] : reqFile.rests.filter(n => n.startsWith(prefix));
12188
+ const mergedNotSwinging = [...new Set([...(fwd?.not_swinging ?? []), ...sceneNotSwinging])];
12189
+ const mergedRises = [...new Set([...(fwd?.rises ?? []), ...sceneRises])];
12190
+ const mergedRests = [...new Set([...(fwd?.rests ?? []), ...sceneRests])];
12191
+ const tipEx: TipExceptions = mergedNotSwinging.length === 0 && mergedRises.length === 0 && mergedRests.length === 0
12192
+ ? NO_TIP_EXCEPTIONS
12193
+ : {
12194
+ path: reqFile?.path ?? `${fwd?.build ?? ''}/check/check.json`,
12195
+ not_swinging: mergedNotSwinging,
12196
+ rises: mergedRises,
12197
+ rests: mergedRests,
12198
+ ...(fwd === undefined ? {} : {
12199
+ forwardedFrom: {
12200
+ ...(fwd.not_swinging.length === 0 ? {} : { not_swinging: Object.fromEntries(fwd.not_swinging.map(n => [n, fwd.build])) }),
12201
+ ...(fwd.rises.length === 0 ? {} : { rises: Object.fromEntries(fwd.rises.map(n => [n, fwd.build])) }),
12202
+ ...(fwd.rests.length === 0 ? {} : { rests: Object.fromEntries(fwd.rests.map(n => [n, fwd.build])) }),
12203
+ },
12204
+ }),
12205
+ };
12206
+ tip = tipLine(charInputsOrig, geoPath, charIdle.written, problems, tipEx, readingSkip('TIP_OVER_ROOT'));
12207
+ const unplacedGeo = readGeometry(geoPath, charIdle.written);
12208
+ still = stillLine(charInputsOrig, charIdle, unplacedGeo, geoPath, problems, notPlanted, readingSkip('STILL_REGIONS_DARK'), forwardedNotPlanted);
12209
+
12210
+ const rest = attachmentPoses(geoPath, charIdle.written)[0] ?? new Map<string, PosedAttachment>();
12211
+ const baseRenderer = officialRenderer();
12212
+ const charPhysicsRenderer: typeof baseRenderer = s === 1 && shiftX === 0 && shiftY === 0
12213
+ ? baseRenderer
12214
+ : {
12215
+ ...baseRenderer,
12216
+ sampleAnimation: (poser, animation, sampleFps, opts) =>
12217
+ baseRenderer.sampleAnimation(poser, animation, sampleFps, opts).map(frame =>
12218
+ frame.attachments === undefined
12219
+ ? frame
12220
+ : {
12221
+ ...frame,
12222
+ attachments: frame.attachments.map(att => ({
12223
+ ...att,
12224
+ vertices: att.vertices.map((v, idx) => ((idx % 2 === 0 ? v - shiftX : v - shiftY) / s)),
12225
+ })),
12226
+ }),
12227
+ };
12228
+ physics = measurePhysicsContribution(charPhysicsRenderer, charBuildDir, charRig, charMotion, prefParts.parts.map(p => ({
12229
+ name: p.name,
12230
+ w: p.w,
12231
+ h: p.h,
12232
+ bound: boundBones(charRig, p.name),
12233
+ rest: rest.get(p.name) === undefined ? undefined : { vertices: (rest.get(p.name) as PosedAttachment).rest, triangles: (rest.get(p.name) as PosedAttachment).triangles },
12234
+ art: () => placedArt(p.x, p.y, readPng(join(dirname(c.partsDir), partImageReference(p).path))),
12235
+ })), origStage, charIdle.fps);
12236
+ }
12237
+
12238
+ // 4. STRESS_OFF_CHAIN
12239
+ let stress: JudgementLine | null = null;
12240
+ const stressProblems: Problem[] = [];
12241
+ const stressTagged = charIdle === null ? [] : partsTagged(prefParts, STRESS_TAGS);
12242
+ if (stressTagged.length > 0) {
12243
+ const plan = stressPlan(charRig, charMotion, stressTagged);
12244
+ const stressDir = join(scratchDir, 'stress');
12245
+ if (plan.read.length > 0) {
12246
+ mkdirSync(stressDir, { recursive: true });
12247
+ const base = charStripped === null ? charRig : charStripped.rig;
12248
+ const stressAnims = stressAnimations(plan);
12249
+ writeFileSync(join(stressDir, 'rig.json'), JSON.stringify({ ...withoutSliders(base, stressAnims), images }));
12250
+ writeFileSync(join(stressDir, 'motion.json'), JSON.stringify({ ...(charStripped === null ? charMotion : charStripped.motion), animations: stressAnims }));
12251
+ const sb = rigc(['build', '--rig', join(stressDir, 'rig.json'), '--motion', join(stressDir, 'motion.json'), '--out', join(stressDir, 'build'), '--profile', 'spine']);
12252
+ if (sb.status !== 0) refuseIfAny(rigcFailed(`build (${STRESS_LINE}'s turned copy, character "${c.id}")`, sb, buildGateLines(sb.out)));
12253
+ const sr = rigc(['render', '--candidate', join(stressDir, 'build'), '--fps', String(IDLE_FPS), '--max', String(FOLD_RENDER_MAX), '--geometry', '--out', join(stressDir, 'render')]);
12254
+ if (sr.status !== 0) refuseIfAny(rigcFailed(`render --geometry (${STRESS_LINE}'s turned copy, character "${c.id}")`, sr, sr.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12255
+ }
12256
+ const sets = plan.read.length > 0 ? readStressSets(join(stressDir, 'render'), Object.keys(stressAnimations(plan))) : new Map<string, IdleGeometry>();
12257
+ stress = stressLine(plan, a => sets.get(a) as IdleGeometry, stressProblems);
12258
+ }
12259
+
12260
+ // 5. SEAM_OVER_RANGE
12261
+ let sweep: SweepLine | null = null;
12262
+ const sweepProblems: Problem[] = [];
12263
+ const sweepSteps = new Map<string, { left: number; right: number }>();
12264
+ const joints = sweepJoints(prefParts);
12265
+ if (joints.length > 0) {
12266
+ const sweepDir = join(scratchDir, 'sweep');
12267
+ mkdirSync(sweepDir, { recursive: true });
12268
+ const base = charStripped === null ? charRig : charStripped.rig;
12269
+ const slotNames = (Array.isArray(base.slots) ? base.slots : []).filter(isRecord).map(sl => String(sl.name));
12270
+ const limbSlots = (limb: string): string[] => {
12271
+ const mine = new Set(prefParts.parts.filter(p => p.limb?.name === limb).map(p => p.name));
12272
+ return slotNames.filter(n => mine.has(n));
12273
+ };
12274
+ const pngs = new Map<string, Raster>();
12275
+ const png = (name: string): Raster => {
12276
+ const hit = pngs.get(name);
12277
+ if (hit !== undefined) return hit;
12278
+ const r = readPng(join(dirname(c.partsDir), partImageReference(prefParts.parts.find(p => p.name === name) as PartRecord).path));
12279
+ pngs.set(name, r);
12280
+ return r;
12281
+ };
12282
+ const under = joints.map(j => sweepUnderlay(prefParts, png, j));
12283
+ const unread = joints.map((j, i) => sweepUnread(j, base, limbSlots(j.limb), under[i].px));
12284
+ const imagesFrom = typeof inp.rig.images === 'string' ? resolve(inp.rigDir, inp.rig.images) : null;
12285
+ const imagesDir = join(sweepDir, 'images');
12286
+ mkdirSync(imagesDir, { recursive: true });
12287
+ if (imagesFrom !== null && existsSync(imagesFrom)) cpSync(imagesFrom, imagesDir, { recursive: true });
12288
+ const files = new Set(readdirSync(imagesDir).filter(f => f.endsWith('.png')).map(f => f.slice(0, -'.png'.length)));
12289
+ const copy = sweepCopy(base, charStripped === null ? charMotion : charStripped.motion, joints, under.map((u, i) => (unread[i] === null ? u : null)), limbSlots, charStage, charH, files, s);
12290
+ const sets = new Map<string, { under: FrameSet; bare: FrameSet }>();
12291
+ if (copy.slots.length > 0) {
12292
+ for (const [file, image] of copy.images) writePng(join(imagesDir, file), image);
12293
+ const sweepAnims = isRecord(copy.motion.animations) ? copy.motion.animations : {};
12294
+ writeFileSync(join(sweepDir, 'rig.json'), JSON.stringify({ ...withoutSliders(copy.rig, sweepAnims), images: imagesDir }));
12295
+ writeFileSync(join(sweepDir, 'motion.json'), JSON.stringify(copy.motion));
12296
+ const sb = rigc(['build', '--rig', join(sweepDir, 'rig.json'), '--motion', join(sweepDir, 'motion.json'), '--out', join(sweepDir, 'build'), '--profile', 'spine']);
12297
+ if (sb.status !== 0) refuseIfAny(rigcFailed(`build (${SWEEP_LINE}'s bent copy, character "${c.id}")`, sb, buildGateLines(sb.out)));
12298
+ const maxSide = Math.ceil(Math.max(charStage.width, charStage.height));
12299
+ for (const [label, hide] of [['under', []], ['bare', ['--hide', copy.slots.join(',')]]] as const) {
12300
+ const r = rigc(['render', '--candidate', join(sweepDir, 'build'), '--fps', String(STILL_FPS), '--max', String(maxSide), ...hide, '--out', join(sweepDir, label)]);
12301
+ if (r.status !== 0) refuseIfAny(rigcFailed(`render (${SWEEP_LINE}'s bent copy, character "${c.id}")`, r, r.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12302
+ }
12303
+ const named = (label: string, animation: string): FrameSet => {
12304
+ const sidecar = join(sweepDir, label, 'frames.json');
12305
+ const raw = readJson(sidecar, []);
12306
+ const listed = raw !== null && Array.isArray(raw.sets) ? raw.sets.filter(isRecord) : [];
12307
+ const hit = listed.find(x => x.animation === animation);
12308
+ if (hit === undefined || typeof hit.dir !== 'string') return sidecarProblem(sidecar, `names no frame set for animation ${JSON.stringify(animation)}`);
12309
+ return readFrameSet(join(sweepDir, label, hit.dir));
12310
+ };
12311
+ joints.forEach((j, i) => {
12312
+ if (unread[i] !== null) return;
12313
+ for (const a of sweepAngles(j.range)) {
12314
+ const name = sweepAnimationName(j.part, a);
12315
+ sets.set(name, { under: named('under', name), bare: named('bare', name) });
12316
+ }
12317
+ });
12318
+ }
12319
+ const axes = joints.map(j => sweepAxis(base, j));
12320
+ const stepOf = (j: SweepJoint, bare: FrameSet): { left: number; right: number } | null => {
12321
+ const axis = axes[joints.indexOf(j)];
12322
+ return axis === null ? null : contourStep(bare.frames[0].image, bare.background, placedRigToFrameMap(charStage, charH, bare.viewport, s), j.at, axis, j.radius);
12323
+ };
12324
+ sweep = sweepLine(joints, under.map(u => u.px), unread, a => sets.get(a) as { under: FrameSet; bare: FrameSet }, charStripped === null ? 0 : charStripped.physics.length, sweepProblems, stepOf, sweepSteps, s);
12325
+ }
12326
+
12327
+ // 6. SEAM_OVER_MOTION
12328
+ let motionSeam: MotionSeamLine;
12329
+ let backgroundRows: MotionBackgroundRow[] = [];
12330
+ const motionRootProblems: Problem[] = [];
12331
+ {
12332
+ const fps = IDLE_FPS;
12333
+ const prefix = `${c.id}:`;
12334
+ // rigc render --seam splits each entry on ":", so slot names holding "<id>:" are
12335
+ // stripped on a colon-free slot copy of this character's rig and mapped back 1-to-1.
12336
+ const uncolon = stripCharacterSlotPrefixForSeam(charRig, charMotion, c.id);
12337
+ let uncolonBuild: { dir: string; pack: readonly PackLine[] } | null = null;
12338
+ const ensureUncolonBuild = (): { dir: string; pack: readonly PackLine[] } => {
12339
+ if (uncolonBuild !== null) return uncolonBuild;
12340
+ const root = join(scratchDir, 'seam_uncolon');
12341
+ mkdirSync(root, { recursive: true });
12342
+ const dir = join(root, 'build');
12343
+ const rigFile = join(root, 'rig.json');
12344
+ const motionFile = join(root, 'motion.json');
12345
+ writeFileSync(rigFile, JSON.stringify({ ...uncolon.rig, images }));
12346
+ writeFileSync(motionFile, JSON.stringify(uncolon.motion));
12347
+ const b = rigc(['build', '--rig', rigFile, '--motion', motionFile, '--out', dir, ...packedBuildArgs(mode)]);
12348
+ if (b.status !== 0) refuseIfAny(rigcFailed(`${packedBuildLabel(mode)} (seam copy, character "${c.id}")`, b, buildGateLines(b.out)));
12349
+ uncolonBuild = { dir, pack: parsePackLines(buildGateLines(b.out)) };
12350
+ return uncolonBuild;
12351
+ };
12352
+ const seamReqs = reqFile === null || seams === null ? [] : reqFile.requirements.flatMap(r =>
12353
+ r.kind === 'seam' && seams.has(r.name) && r.part.startsWith(prefix) && r.neighbour.startsWith(prefix)
12354
+ ? [{ name: r.name, part: r.part, neighbour: r.neighbour }]
12355
+ : []);
12356
+ const reqMotionSeams = reqFile?.motion_seams?.filter(r => r.part.startsWith(prefix) && r.neighbour.startsWith(prefix));
12357
+ const selection = motionSeamSelection(prefParts, seamReqs, charRig, candidates => {
12358
+ const base = ensureUncolonBuild();
12359
+ const setupDir = join(scratchDir, 'seam_root_setup');
12360
+ rmSync(setupDir, { recursive: true, force: true });
12361
+ mkdirSync(setupDir, { recursive: true });
12362
+ let candidate = base.dir;
12363
+ if (isRecord(uncolon.motion.animations) && Object.keys(uncolon.motion.animations).length > 0) {
12364
+ const motionFile = join(setupDir, 'motion.json');
12365
+ const rigFile = join(setupDir, 'rig.json');
12366
+ writeFileSync(rigFile, JSON.stringify({ ...uncolon.rig, images }));
12367
+ writeFileSync(motionFile, JSON.stringify({ ...uncolon.motion, animations: {} }));
12368
+ candidate = join(setupDir, 'build');
12369
+ const compiled = rigc(['build', '--rig', rigFile, '--motion', motionFile, '--out', candidate, ...packedBuildArgs(mode)]);
12370
+ if (compiled.status !== 0) refuseIfAny(rigcFailed(`build (body-root setup observation, character "${c.id}")`, compiled, buildGateLines(compiled.out)));
12371
+ const checkProblems: Problem[] = [];
12372
+ const original = readJson(join(base.dir, 'skeleton.json'), checkProblems);
12373
+ const setup = readJson(join(candidate, 'skeleton.json'), checkProblems);
12374
+ const changed = ['bones', 'slots', 'skins', 'ik', 'transform', 'path', 'physics'].filter(key =>
12375
+ JSON.stringify(original?.[key]) !== JSON.stringify(setup?.[key]));
12376
+ const pages = parsePackLines(compiled.out.split('\n')).map(page => page.page);
12377
+ if (original === null || setup === null || !isRecord(setup.animations) || Object.keys(setup.animations).length > 0 || changed.length > 0 ||
12378
+ JSON.stringify(pages) !== JSON.stringify(base.pack.map(page => page.page)) ||
12379
+ pages.some(page => !existsSync(join(candidate, page)) || !readFileSync(join(base.dir, page)).equals(readFileSync(join(candidate, page))))) {
12380
+ checkProblems.push({
12381
+ code: 'CHECK_MOTION_SEAM_ROOT',
12382
+ object: `character "${c.id}" stock setup observation`,
12383
+ detail: 'requires unchanged default bones/slots/skins/constraints and atlas PNG bytes, with no animation; differing default fields: ' + changed.join(', '),
12384
+ });
12385
+ }
12386
+ refuseIfAny(checkProblems);
12387
+ }
12388
+ const renderDir = join(setupDir, 'render');
12389
+ const rawCandidates: MotionSeamPair[] = candidates.map(pair => ({
12390
+ ...pair,
12391
+ pair: `${uncolon.unprefixSlot(pair.a)}|${uncolon.unprefixSlot(pair.b)}`,
12392
+ a: uncolon.unprefixSlot(pair.a),
12393
+ b: uncolon.unprefixSlot(pair.b),
12394
+ }));
12395
+ const list = rawCandidates.map(pair => pair.a + ':' + pair.b).join(',');
12396
+ const rendered = rigc(['render', '--candidate', candidate, '--seam', list, '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--out', renderDir]);
12397
+ if (rendered.status !== 0) refuseIfAny(rigcFailed(`render --seam (body-root setup observation, character "${c.id}")`, rendered, rendered.out.split('\n').filter(line => line.includes('FAIL') || line.includes('rigc:'))));
12398
+ const rawSetupRows = readMotionRootSetup(renderDir, fps, rawCandidates);
12399
+ const rawToPref = new Map(rawCandidates.map((rc, idx) => [rc.pair, candidates[idx].pair]));
12400
+ return rawSetupRows.map(row => ({ ...row, pair: rawToPref.get(row.pair) ?? row.pair }));
12401
+ }, reqMotionSeams);
12402
+ const { pairs, unmeasuredRoots } = selection;
12403
+ const slotNames = new Set((Array.isArray(charRig.slots) ? charRig.slots : []).filter(isRecord).map(sl => String(sl.name)));
12404
+ for (const p of pairs) {
12405
+ const missing = [p.a, p.b].filter(n => !slotNames.has(n));
12406
+ if (missing.length > 0) p.unread = `names ${missing.map(n => `slot "${n}"`).join(' and ')}, which rig.json does not have`;
12407
+ }
12408
+ const read = pairs.filter(p => p.unread === undefined);
12409
+ if (pairs.length === 0) {
12410
+ motionSeam = motionSeamLine([], charAnimNames, fps, [], unmeasuredRoots.length === 0
12411
+ ? 'no neighbour pair is declared: parts.json holds no limb segment below a joint (config.limbs) and no --requirements seam names two parts'
12412
+ : undefined, motionRootProblems, unmeasuredRoots);
12413
+ } else if (charAnimNames.length === 0) {
12414
+ motionSeam = motionSeamLine(pairs, [], fps, [], 'motion.json holds no animation to read the declared pairs in', motionRootProblems, unmeasuredRoots);
12415
+ } else if (read.length === 0) {
12416
+ motionSeam = motionSeamLine(pairs, charAnimNames, fps, [], undefined, motionRootProblems, unmeasuredRoots);
12417
+ } else {
12418
+ const base = ensureUncolonBuild();
12419
+ const activeDest = join(scratchDir, 'seam_motion');
12420
+ const rawPairs: MotionSeamPair[] = pairs.map(p => ({
12421
+ ...p,
12422
+ pair: `${uncolon.unprefixSlot(p.a)}|${uncolon.unprefixSlot(p.b)}`,
12423
+ a: uncolon.unprefixSlot(p.a),
12424
+ b: uncolon.unprefixSlot(p.b),
12425
+ }));
12426
+ const rawRead = rawPairs.filter(p => p.unread === undefined);
12427
+ const list = rawRead.map(p => `${p.a}:${p.b}`).join(',');
12428
+ const hasRoots = rawRead.some(p => p.root !== undefined);
12429
+ const r = measured(['render', '--candidate', base.dir, '--seam', list, ...(seamRequired ? ['--seam-cells'] : []), '--fps', String(fps), '--max', String(FOLD_RENDER_MAX), '--geometry', '--out', activeDest]);
12430
+ if (r.status !== 0) refuseIfAny(rigcFailed(`render --seam ${list} --fps ${fps} (character "${c.id}")`, r, r.out.split('\n').filter(l => l.includes('FAIL') || l.includes('rigc:'))));
12431
+ const activeWorldRows: MotionSeamWorldRow[] = [];
12432
+ const rawRows = readMotionSeams(activeDest, charAnimNames, fps, rawRead, {}, charStripped !== null && env === null ? activeWorldRows : undefined, hasRoots ? motionRootDrawOrderReader(activeDest) : undefined);
12433
+ enrichMotionSeamPoses(activeDest, uncolon.rig, prefParts, rawPairs, rawRows);
12434
+ const rawToPref = new Map(rawPairs.map((rp, idx) => [rp.pair, pairs[idx]]));
12435
+ if (seamRequired) {
12436
+ const uncolonSlotParts = checkSlotParts(uncolon.rig, c.parts.parts.map(p => p.name), c.parts.alternates?.map(set => set.name) ?? []);
12437
+ const prefSlotParts = checkSlotParts(charRig, prefParts.parts.map(p => p.name), prefParts.alternates?.map(set => set.name) ?? []);
12438
+ const rawBgRows = readMotionSeamBackground(activeDest, charAnimNames, fps, rawRead, uncolonSlotParts);
12439
+ backgroundRows = rawBgRows.map(row => {
12440
+ const prefPair = rawToPref.get(row.pair);
12441
+ return {
12442
+ ...row,
12443
+ pair: prefPair?.pair ?? row.pair,
12444
+ hits: row.hits.map(hit => hit.cells === undefined ? hit : {
12445
+ ...hit,
12446
+ cells: hit.cells.map(cell => {
12447
+ const setupTop = cell.setupTop === null ? null : `${prefix}${cell.setupTop}`;
12448
+ const setupUnder = cell.setupUnder === null ? null : `${prefix}${cell.setupUnder}`;
12449
+ return {
12450
+ ...checkSlotRow('seam_cells.frames[].cells', false, setupTop ?? '', prefSlotParts),
12451
+ x: cell.x,
12452
+ y: cell.y,
12453
+ setupTop,
12454
+ setupUnder,
12455
+ class: setupTop === null ? 'background' : prefSlotParts.has(setupTop) ? 'figure' : 'other',
12456
+ };
12457
+ }),
12458
+ }),
12459
+ };
12460
+ });
12461
+ }
12462
+ const mappedRows = rawRows.map(row => {
12463
+ const prefPair = rawToPref.get(row.pair);
12464
+ if (prefPair === undefined) return row;
12465
+ const subjects = [prefPair.a, prefPair.b];
12466
+ return {
12467
+ ...row,
12468
+ pair: prefPair.pair,
12469
+ ...(row.joint_contact === undefined
12470
+ ? {}
12471
+ : {
12472
+ joint_contact: {
12473
+ ...row.joint_contact,
12474
+ reasons: row.joint_contact.reasons.map(reason => ({
12475
+ ...reason,
12476
+ ...checkRow('SEAM_OVER_MOTION.rows[].joint_contact.reasons', 'pair', false, subjects),
12477
+ })),
12478
+ },
12479
+ }),
12480
+ ...(row.cells === undefined
12481
+ ? {}
12482
+ : {
12483
+ cells: row.cells.map(cell => ({
12484
+ ...cell,
12485
+ ...checkRow('SEAM_OVER_MOTION.rows[].cells', 'pair', false, subjects),
12486
+ })),
12487
+ }),
12488
+ };
12489
+ });
12490
+ motionSeam = motionSeamLine(pairs, charAnimNames, fps, mappedRows, undefined, motionRootProblems, unmeasuredRoots);
12491
+ }
12492
+ }
12493
+
12494
+ // 7. Setup pose still: seam, BLINK_NO_HOLE, SETUP_POSE_VS_SOURCE
12495
+ const stillDir = join(scratchDir, 'still');
12496
+ mkdirSync(stillDir, { recursive: true });
12497
+ const eyes = partsTagged(prefParts, EYE_TAGS);
12498
+ const slotBone = new Map((Array.isArray(charRig.slots) ? charRig.slots : []).filter(isRecord).map(sl => [String(sl.name), String(sl.bone)]));
12499
+ const shut = blinkTracks(charMotion, eyeBones(charRig, eyes.map(p => slotBone.get(p.name) ?? '')));
12500
+ const animations: Record<string, unknown> = {
12501
+ still: { duration: STILL_DURATION, loop: false, tracks: [{ bone: inp.rootBone, property: 'rotate', keys: [{ t: 0, v: [0] }, { t: STILL_DURATION, v: [0] }] }] },
12502
+ };
12503
+ if (eyes.length > 0 && shut.length > 0) {
12504
+ animations[BLINK_ANIMATION] = {
12505
+ duration: STILL_DURATION,
12506
+ loop: false,
12507
+ tracks: shut.filter((b, i) => shut.findIndex(a => JSON.stringify(a.target) === JSON.stringify(b.target)) === i).map(b => ({ ...b.target, property: 'scaley', keys: [{ t: 0, v: [b.closed] }, { t: STILL_DURATION, v: [b.closed] }] })),
12508
+ };
12509
+ }
12510
+ const stillRig = { ...withoutSliders(charRig, animations), images };
12511
+ writeFileSync(join(stillDir, 'rig.json'), JSON.stringify(stillRig));
12512
+ writeFileSync(join(stillDir, 'motion.json'), JSON.stringify({ ...charMotion, animations }));
12513
+ const sb = rigc(['build', '--rig', join(stillDir, 'rig.json'), '--motion', join(stillDir, 'motion.json'), '--out', join(stillDir, 'build'), '--profile', 'spine']);
12514
+ if (sb.status !== 0) refuseIfAny(rigcFailed(`build (the setup-pose still, character "${c.id}")`, sb, buildGateLines(sb.out)));
12515
+ const maxSide = Math.ceil(Math.max(1, Math.max(charStage.width, charStage.height)));
12516
+ const sr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), '--out', join(stillDir, 'render')]);
12517
+ if (sr.status !== 0) refuseIfAny(rigcFailed(`render (the setup-pose still, character "${c.id}")`, sr, sr.out.split('\n').filter(l => l.includes('FAIL'))));
12518
+ const stillSet = readFrameSet(join(stillDir, 'render'));
12519
+ if (keepStills && !multiCharacter) retainCheckRender(join(stillDir, 'render'), join(out, 'setup_still_auto'));
12520
+
12521
+ const states: SeamStateBounds[] = [seamStateBounds(join(stillDir, 'build'), 'base')];
12522
+ const exactSourceGrid = s === 1 && Number.isSafeInteger(ox) && Number.isSafeInteger(oy) && Number.isSafeInteger(charStage.width) && Number.isSafeInteger(charStage.height);
12523
+ let union: Viewport;
12524
+ let canonicalSet: FrameSet;
12525
+ if (exactSourceGrid) {
12526
+ union = seamUnionViewport(charStage, states);
12527
+ const cr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(Math.max(union.width, union.height)), '--viewport', [union.x, union.y, union.width, union.height].join(','), '--geometry', '--out', join(stillDir, 'seam')]);
12528
+ if (cr.status !== 0) refuseIfAny(rigcFailed(`render (the source-grid setup seam, character "${c.id}")`, cr, cr.out.split('\n').filter(l => l.includes('FAIL'))));
12529
+ canonicalSet = readFrameSet(join(stillDir, 'seam'));
12530
+ seamCanonicalViewport(charStage, canonicalSet.viewport, JSON.parse(readFileSync(join(stillDir, 'seam', 'frames.json'), 'utf8')) as unknown, union);
12531
+ } else {
12532
+ const b = states[0].bounds;
12533
+ const minX = Math.min(charStage.x, b?.minX ?? charStage.x);
12534
+ const minY = Math.min(charStage.y, b?.minY ?? charStage.y);
12535
+ const maxX = Math.max(charStage.x + charStage.width, b?.maxX ?? charStage.x + charStage.width);
12536
+ const maxY = Math.max(charStage.y + charStage.height, b?.maxY ?? charStage.y + charStage.height);
12537
+ const left = Math.floor(minX - charStage.x);
12538
+ const bottom = Math.floor(minY - charStage.y);
12539
+ const right = Math.max(left + 1, Math.ceil(maxX - charStage.x));
12540
+ const top = Math.max(bottom + 1, Math.ceil(maxY - charStage.y));
12541
+ const uw = right - left;
12542
+ const uh = top - bottom;
12543
+ union = { x: charStage.x + left, y: charStage.y + bottom, width: uw, height: uh, scale: 1, pixelWidth: uw, pixelHeight: uh };
12544
+ const cr = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(Math.max(uw, uh)), '--viewport', [union.x, union.y, union.width, union.height].join(','), '--geometry', '--out', join(stillDir, 'seam')]);
12545
+ if (cr.status !== 0) refuseIfAny(rigcFailed(`render (the scaled setup seam, character "${c.id}")`, cr, cr.out.split('\n').filter(l => l.includes('FAIL'))));
12546
+ canonicalSet = readFrameSet(join(stillDir, 'seam'));
12547
+ }
12548
+ if (keepStills && !multiCharacter) retainCheckRender(join(stillDir, 'seam'), join(out, STILL_DIR));
12549
+
12550
+ const domain = {
12551
+ viewport: canonicalSet.viewport,
12552
+ authored: charStage,
12553
+ numerator: prefParts.scene === undefined ? 'whole-union' as const : 'authored-scene-interior' as const,
12554
+ states,
12555
+ };
12556
+ const rigSlotOrder = (Array.isArray(charRig.slots) ? charRig.slots : []).filter(isRecord).map(sl => String(sl.name));
12557
+ const composite = flatComposite(prefParts, c.partsDir, stillSet.background, rigSlotOrder);
12558
+ const autoMap = placedRigToFrameMap(charStage, charH, stillSet.viewport, s);
12559
+ const autoSeam = seamFigures(composite, stillSet.frames[0].image, charStage, stillSet.viewport, stillSet.background, autoMap, prefParts.scene !== undefined);
12560
+ const placed = resolvePlacedAlpha(basePlacements(prefParts, rigSlotOrder), c.partsDir);
12561
+ const basePopulation = createSeamPopulation(placed, prefParts.rig_size, canonicalSet.viewport);
12562
+ const canonicalMap = placedRigToFrameMap(charStage, charH, canonicalSet.viewport, s);
12563
+ const seam = seamFigures(composite, canonicalSet.frames[0].image, charStage, canonicalSet.viewport, canonicalSet.background, canonicalMap, prefParts.scene !== undefined, undefined, exactSourceGrid, basePopulation.observe);
12564
+ const seamFrameScale = round6(s * canonicalSet.viewport.scale);
12565
+ const wholeReading = seamReading(seam, canonicalSet.viewport, s);
12566
+ const seamScope: SeamScope = {
12567
+ mode: 'source-grid/base',
12568
+ domain,
12569
+ denominator_px: exactSourceGrid ? canonicalDenominator(seam) : wholeReading.denominator_px,
12570
+ auto_frame_raw: seamReading(autoSeam, stillSet.viewport, s),
12571
+ whole: wholeReading,
12572
+ population: basePopulation.finish(),
12573
+ };
12574
+ const baseRows = basePopulation.rows(seam);
12575
+ seamScope.whole_pairs = baseRows.map(({ row: { picture: _picture, ...raw } }) => raw);
12576
+ const seamMean = round3(seam.mean);
12577
+ const charSeamFailed = seamFails(seamMean, seam.over40, seamFrameScale);
12578
+ let seamPairs: SeamPairRow[] | null = null;
12579
+ if (seamPairsAsked || charSeamFailed) {
12580
+ const pairOutDir = multiCharacter ? join(out, SEAM_DIR, seg) : join(out, SEAM_DIR);
12581
+ mkdirSync(pairOutDir, { recursive: true });
12582
+ seamPairs = baseRows.map(({ row, pixels }) => {
12583
+ const picture = multiCharacter ? `${SEAM_DIR}/${seg}/${basename(row.picture)}` : row.picture;
12584
+ const mappedRow = { ...row, picture };
12585
+ writePng(join(out, picture), seamPicture(canonicalSet.frames[0].image, mappedRow, pixels));
12586
+ return mappedRow;
12587
+ });
12588
+ }
12589
+ if (charSeamFailed) {
12590
+ const worst = seamPairs === null || seamPairs.length === 0 ? null : seamPairs[0];
12591
+ problems.unshift({
12592
+ code: 'CHECK_SEAM_WITHIN_BAR',
12593
+ object: `character "${c.id}" setup-pose render vs the flat composite of parts/ (offset [${ox}, ${oy}], scale ${s})`,
12594
+ detail:
12595
+ `mean |d| ${seamMean}/255 and ${seam.over40} frame px over ${SEAM_PX_LEVEL} (${seam.over80} over ${SEAM_PX_LEVEL_HIGH}) at frame scale ${seamFrameScale}, ${seamRigPxText(seam.over40, seamFrameScale)} rig px (the count / s²); mean <= ${SEAM_MEAN_BAR.toFixed(1)} and <= ${SEAM_PX_BAR} rig px over ${SEAM_PX_LEVEL} are required` +
12596
+ (worst === null
12597
+ ? `; no pixel is over ${SEAM_PX_LEVEL}, so the mean alone fails and there is no pair to name`
12598
+ : `; worst of ${(seamPairs as SeamPairRow[]).length} pair(s): ${seamPairText(worst)}`),
12599
+ });
12600
+ }
12601
+
12602
+ let sourceRead: ReportedLine | null = null;
12603
+ if (c.source !== null) {
12604
+ writeFileSync(join(stillDir, BLACK_RIG), JSON.stringify(blackRig(stillRig)));
12605
+ const kb = rigc(['build', '--rig', join(stillDir, BLACK_RIG), '--motion', join(stillDir, 'motion.json'), '--out', join(stillDir, 'black_build'), '--profile', 'spine']);
12606
+ if (kb.status !== 0) refuseIfAny(rigcFailed(`build (the setup-pose still, black-tinted, character "${c.id}")`, kb, buildGateLines(kb.out)));
12607
+ const kr = rigc(['render', '--candidate', join(stillDir, 'black_build'), '--animation', 'still', '--fps', String(STILL_FPS), '--max', String(maxSide), '--out', join(stillDir, 'black')]);
12608
+ if (kr.status !== 0) refuseIfAny(rigcFailed(`render (the setup-pose still, black-tinted, character "${c.id}")`, kr, kr.out.split('\n').filter(l => l.includes('FAIL'))));
12609
+ const blackSet = readFrameSet(join(stillDir, 'black'));
12610
+ if (!sameViewport(stillSet.viewport, blackSet.viewport) || stillSet.background.join(',') !== blackSet.background.join(',')) {
12611
+ refuseIfAny([{ code: 'CHECK_SOURCE_GRID', object: `character "${c.id}" black-tinted setup-pose still`, detail: `is on ${JSON.stringify(blackSet.viewport)} over ${JSON.stringify(blackSet.background)}; the setup-pose still is on ${JSON.stringify(stillSet.viewport)} over ${JSON.stringify(stillSet.background)}` }]);
12612
+ }
12613
+ const srcr = sourceInRig(c.source.painting, charW, charH);
12614
+ const invMap = placedFrameToRigMap(charStage, charH, stillSet.viewport, s);
12615
+ const fig = sourceFigures(stillSet.frames[0].image, blackSet.frames[0].image, stillSet.viewport, stillSet.background, origStage, srcr, invMap);
12616
+ sourceRead = sourceLine(fig, c.source.painting, origStage, stillSet.viewport);
12617
+ }
12618
+
12619
+ let blink: JudgementLine = skip(lacking);
12620
+ if (charInputsScaled !== null && charIdle !== null) {
12621
+ const scaledEyes = eyes.map(p => ({ ...p, x: p.x * s, y: p.y * s, w: p.w * s, h: p.h * s }));
12622
+ const blinkSkip = readingSkip('BLINK_NO_HOLE');
12623
+ if (scaledEyes.length === 0) blink = blinkSkip(`no part comes from a See-through ${tagWords(EYE_TAGS)} layer, so there is no eye to look behind`, 'no-eye-parts');
12624
+ else if (shut.length === 0) blink = blinkSkip(`no idle "scaley" track on the bones of ${quoteParts(scaledEyes)} goes below its first key, so the idle has no blink`, 'no-blink-track');
12625
+ else {
12626
+ const br = rigc(['render', '--candidate', join(stillDir, 'build'), '--animation', BLINK_ANIMATION, '--fps', String(STILL_FPS), '--max', String(maxSide), '--out', join(stillDir, 'blink')]);
12627
+ if (br.status !== 0) refuseIfAny(rigcFailed(`render (the setup pose with the eyes shut, "${BLINK_ANIMATION}", character "${c.id}")`, br, br.out.split('\n').filter(l => l.includes('FAIL'))));
12628
+ blink = blinkLine(charInputsScaled, scaledEyes, shut, stillSet, readFrameSet(join(stillDir, 'blink')), charIdle, charStage.height, problems);
12629
+ if (blink.status === 'SKIP') charSkipReasons.BLINK_NO_HOLE = 'no-reading';
12630
+ }
12631
+ }
12632
+
12633
+ problems.push(...levelProblems, ...stressProblems, ...limbProblems, ...sweepProblems, ...motionRootProblems);
12634
+
12635
+ const charRawForOutcomes: Record<string, unknown> = {
12636
+ gate_spine_html_green: true,
12637
+ loop_max_diff: charIdle === null ? null : 0,
12638
+ seam_mean: seamMean,
12639
+ seam_px_over_40: seam.over40,
12640
+ seam_px_over_80: seam.over80,
12641
+ seam_frame_scale: seamFrameScale,
12642
+ BREATH_VISIBLE: breath,
12643
+ BLINK_NO_HOLE: blink,
12644
+ CHAIN_LAG: { status: 'PASS' },
12645
+ TIP_OVER_ROOT: tip,
12646
+ STILL_REGIONS_DARK: still,
12647
+ TEXTURE_STRETCH: { status: 'PASS' },
12648
+ ...(charAnimNames.length === 0 ? {} : { [FOLD_LINE]: { status: 'PASS' } }),
12649
+ ...(level === null ? {} : { [LEVEL_LINE]: level }),
12650
+ ...(stress === null ? {} : { [STRESS_LINE]: stress }),
12651
+ ...(limbs === null ? {} : { [LIMB_LINE]: limbs }),
12652
+ ...(sweep === null ? {} : { [SWEEP_LINE]: sweep }),
12653
+ ...(motionSeam.pairs.length === 0 && motionSeam.roots === undefined && motionSeam.required === undefined ? {} : { [MOTION_SEAM_LINE]: motionSeam }),
12654
+ };
12655
+ const fullOutcomes = checkBarOutcomes(charRawForOutcomes, charSkipReasons, false);
12656
+ const charBarOutcomes = Object.fromEntries(COMPOSED_CHARACTER_BAR_IDS.map(id => [id, fullOutcomes[id]])) as ComposedCharacterBarOutcomes;
12657
+
12658
+ const charFigures: ComposedCharacterCheckFigures = {
12659
+ offset: [ox, oy],
12660
+ ...(s === 1 ? {} : { scale: s }),
12661
+ bar_outcomes: charBarOutcomes,
12662
+ seam_mean: seamMean,
12663
+ seam_px_over_40: seam.over40,
12664
+ seam_px_over_80: seam.over80,
12665
+ seam_frame_scale: seamFrameScale,
12666
+ seam_scope: seamScope,
12667
+ ...(seam.border === null ? {} : { seam_border: { frame_px_left_out: seam.border.framePx, px_over_40_left_out: seam.border.over40 } }),
12668
+ ...(seamPairs === null ? {} : { seam_pairs: seamPairs }),
12669
+ BREATH_VISIBLE: breath,
12670
+ BLINK_NO_HOLE: blink,
12671
+ TIP_OVER_ROOT: tip,
12672
+ STILL_REGIONS_DARK: still,
12673
+ ...(level === null ? {} : { [LEVEL_LINE]: level }),
12674
+ ...(stress === null ? {} : { [STRESS_LINE]: stress }),
12675
+ ...(limbs === null ? {} : { [LIMB_LINE]: limbs }),
12676
+ ...(sweep === null ? {} : { [SWEEP_LINE]: sweep }),
12677
+ ...(motionSeam.pairs.length === 0 && motionSeam.roots === undefined && motionSeam.required === undefined ? {} : { [MOTION_SEAM_LINE]: motionSeam }),
12678
+ ...(physics.status === 'SKIP' ? {} : { [PHYSICS_CONTRIBUTES_LINE]: physics }),
12679
+ RECOMPOSITE_HOLES: holesLine(prefParts),
12680
+ ...(sourceRead === null ? {} : { SETUP_POSE_VS_SOURCE: sourceRead }),
12681
+ };
12682
+
12683
+ return {
12684
+ report: {
12685
+ id: c.id,
12686
+ offset: [ox, oy],
12687
+ scale: s,
12688
+ figures: charFigures,
12689
+ seamViewport: canonicalSet.viewport,
12690
+ motionSeam,
12691
+ backgroundRows,
12692
+ physics,
12693
+ sweepSteps,
12694
+ },
12695
+ problems,
12696
+ };
12697
+ } finally {
12698
+ rmSync(scratchDir, { recursive: true, force: true });
12699
+ }
12700
+ }
12701
+
12702
+ const SILENT_SKIP_REASONS = new Set<CheckBarSkipReason>([
12703
+ 'no-hanging-footwear',
12704
+ 'no-handwear',
12705
+ 'no-limb-segments',
12706
+ 'no-joint-range',
12707
+ 'no-root-gate',
12708
+ 'undeclared',
12709
+ 'no-animation',
12710
+ ]);
12711
+
12712
+ function aggregateCharacterBarOutcome(outcomes: readonly CheckBarOutcome[]): CheckBarOutcome {
12713
+ if (outcomes.some(o => o.status === 'FAIL')) return { status: 'FAIL' };
12714
+ if (outcomes.some(o => o.status === 'PASS')) return { status: 'PASS' };
12715
+ const loud = outcomes.find((o): o is Extract<CheckBarOutcome, { status: 'SKIP' }> => o.status === 'SKIP' && !SILENT_SKIP_REASONS.has(o.reason));
12716
+ if (loud !== undefined) return loud;
12717
+ return outcomes[0];
12718
+ }
12719
+
12720
+ function mergeComposedBarOutcomes(base: CheckBarOutcomes, reports: readonly ComposedCharacterReport[]): CheckBarOutcomes {
12721
+ const out: CheckBarOutcomes = { ...base };
12722
+ for (const id of COMPOSED_CHARACTER_BAR_IDS) {
12723
+ out[id] = aggregateCharacterBarOutcome(reports.map(r => r.figures.bar_outcomes[id]));
12724
+ }
12725
+ if (base[MOTION_SEAM_LINE].status === 'FAIL') out[MOTION_SEAM_LINE] = { status: 'FAIL' };
12726
+ return out;
12727
+ }
12728
+
12729
+ function mergeMultiCharacterJudgementDeclarations(
12730
+ id: 'BREATH_VISIBLE' | 'TIP_OVER_ROOT' | 'STILL_REGIONS_DARK',
12731
+ chosen: JudgementLine,
12732
+ reports: readonly ComposedCharacterReport[],
12733
+ ): JudgementLine {
12734
+ if (reports.length <= 1) return chosen;
12735
+ const stringArr = (v: unknown): string[] => Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
12736
+ const strMap = (v: unknown): Record<string, string> => isRecord(v)
12737
+ ? Object.fromEntries(Object.entries(v).filter((e): e is [string, string] => typeof e[1] === 'string'))
12738
+ : {};
12739
+ const strArrMap = (v: unknown): Record<string, string[]> => isRecord(v)
12740
+ ? Object.fromEntries(Object.entries(v).filter((e): e is [string, string[]] => Array.isArray(e[1]) && e[1].every(x => typeof x === 'string')))
12741
+ : {};
12742
+ if (id === 'TIP_OVER_ROOT') {
12743
+ const notSwinging = [...new Set(reports.flatMap(r => stringArr(r.figures.TIP_OVER_ROOT.declared_not_swinging)))];
12744
+ const rises = [...new Set(reports.flatMap(r => stringArr(r.figures.TIP_OVER_ROOT.declared_rises)))];
12745
+ const rests = [...new Set(reports.flatMap(r => stringArr(r.figures.TIP_OVER_ROOT.declared_rests)))];
12746
+ const fwdNs: Record<string, string> = {};
12747
+ const fwdRi: Record<string, string> = {};
12748
+ const fwdRe: Record<string, string> = {};
12749
+ for (const r of reports) {
12750
+ const f = isRecord(r.figures.TIP_OVER_ROOT.forwarded_from_build) ? r.figures.TIP_OVER_ROOT.forwarded_from_build : {};
12751
+ Object.assign(fwdNs, strMap(f.not_swinging));
12752
+ Object.assign(fwdRi, strMap(f.rises));
12753
+ Object.assign(fwdRe, strMap(f.rests));
12754
+ }
12755
+ const fwdMap = {
12756
+ ...(Object.keys(fwdNs).length === 0 ? {} : { not_swinging: fwdNs }),
12757
+ ...(Object.keys(fwdRi).length === 0 ? {} : { rises: fwdRi }),
12758
+ ...(Object.keys(fwdRe).length === 0 ? {} : { rests: fwdRe }),
12759
+ };
12760
+ if (notSwinging.length === 0 && rises.length === 0 && rests.length === 0 && Object.keys(fwdMap).length === 0) return chosen;
12761
+ const { status: _s, reason: _r, declared_not_swinging: _a, declared_rises: _b, declared_rests: _c, forwarded_from_build: _d, ...rest } = chosen;
12762
+ const extra = {
12763
+ ...(notSwinging.length === 0 ? {} : { declared_not_swinging: notSwinging }),
12764
+ ...(rises.length === 0 ? {} : { declared_rises: rises }),
12765
+ ...(rests.length === 0 ? {} : { declared_rests: rests }),
12766
+ ...(Object.keys(fwdMap).length === 0 ? {} : { forwarded_from_build: fwdMap }),
12767
+ ...rest,
12768
+ };
12769
+ return chosen.status === 'SKIP' ? { status: 'SKIP', reason: chosen.reason, ...extra } : { status: chosen.status, ...extra };
12770
+ }
12771
+ if (id === 'BREATH_VISIBLE') {
12772
+ const notPlanted = [...new Set(reports.flatMap(r => stringArr(r.figures.BREATH_VISIBLE.declared_not_planted)))];
12773
+ const fwdNp: Record<string, string> = {};
12774
+ for (const r of reports) {
12775
+ const f = isRecord(r.figures.BREATH_VISIBLE.forwarded_from_build) ? r.figures.BREATH_VISIBLE.forwarded_from_build : {};
12776
+ Object.assign(fwdNp, strMap(f.not_planted));
12777
+ }
12778
+ if (notPlanted.length === 0 && Object.keys(fwdNp).length === 0) return chosen;
12779
+ const { status: _s, reason: _r, declared_not_planted: _a, forwarded_from_build: _b, ...rest } = chosen;
12780
+ const extra = {
12781
+ ...(notPlanted.length === 0 ? {} : { declared_not_planted: notPlanted }),
12782
+ ...(Object.keys(fwdNp).length === 0 ? {} : { forwarded_from_build: { not_planted: fwdNp } }),
12783
+ ...rest,
12784
+ };
12785
+ return chosen.status === 'SKIP' ? { status: 'SKIP', reason: chosen.reason, ...extra } : { status: chosen.status, ...extra };
12786
+ }
12787
+ const allSliderDriven: Record<string, string[]> = {};
12788
+ const allNotPlanted: string[] = [];
12789
+ const allFwdNp: Record<string, string> = {};
12790
+ for (const r of reports) {
12791
+ const st = r.figures.STILL_REGIONS_DARK;
12792
+ if (isRecord(st.face)) Object.assign(allSliderDriven, strArrMap(st.face.slider_driven_slots));
12793
+ if (isRecord(st.feet)) {
12794
+ for (const n of stringArr(st.feet.declared_not_planted)) if (!allNotPlanted.includes(n)) allNotPlanted.push(n);
12795
+ const ff = isRecord(st.feet.forwarded_from_build) ? st.feet.forwarded_from_build : {};
12796
+ Object.assign(allFwdNp, strMap(ff.not_planted));
12797
+ }
12798
+ }
12799
+ if (Object.keys(allSliderDriven).length === 0 && allNotPlanted.length === 0 && Object.keys(allFwdNp).length === 0) return chosen;
12800
+ const nextFace = isRecord(chosen.face) && Object.keys(allSliderDriven).length > 0
12801
+ ? { ...chosen.face, slider_driven_slots: allSliderDriven }
12802
+ : chosen.face;
12803
+ const nextFeet = isRecord(chosen.feet) && (allNotPlanted.length > 0 || Object.keys(allFwdNp).length > 0)
12804
+ ? (() => {
12805
+ const { declared_not_planted: _a, forwarded_from_build: _b, ...fRest } = chosen.feet;
12806
+ return {
12807
+ ...(allNotPlanted.length === 0 ? {} : { declared_not_planted: allNotPlanted }),
12808
+ ...(Object.keys(allFwdNp).length === 0 ? {} : { forwarded_from_build: { not_planted: allFwdNp } }),
12809
+ ...fRest,
12810
+ };
12811
+ })()
12812
+ : chosen.feet;
12813
+ return {
12814
+ ...chosen,
12815
+ ...(nextFace === undefined ? {} : { face: nextFace }),
12816
+ ...(nextFeet === undefined ? {} : { feet: nextFeet }),
12817
+ };
12818
+ }
12819
+
12820
+ function runComposedCharacters(ctx: {
12821
+ characters: readonly ResolvedComposedCharacter[];
12822
+ inp: CheckInputs;
12823
+ out: string;
12824
+ buildDir: string;
12825
+ pack: readonly PackLine[];
12826
+ mode: PackMode;
12827
+ rigc: RigcRunner;
12828
+ measured: RigcRunner;
12829
+ env: CheckEnvironment | null;
12830
+ idle: FrameSet | null;
12831
+ reqFile: RequirementsFile | null;
12832
+ seams: Map<string, SeamPair[]> | null;
12833
+ seamPairsAsked: boolean;
12834
+ seamRequired: boolean;
12835
+ motionCellEvidence: MotionCellSidecar;
12836
+ keepStills: boolean;
12837
+ }): {
12838
+ reports: ComposedCharacterReport[];
12839
+ charactersMap: Record<string, ComposedCharacterCheckFigures>;
12840
+ problems: Problem[];
12841
+ seam: SeamFigures | null;
12842
+ seamViewport: Viewport | null;
12843
+ seamFrameScale: number | null;
12844
+ seamScope: SeamScope | undefined;
12845
+ seamPairs: SeamPairRow[] | null;
12846
+ breath: JudgementLine;
12847
+ blink: JudgementLine;
12848
+ tip: JudgementLine;
12849
+ still: JudgementLine;
12850
+ level: LevelLine | null;
12851
+ stress: JudgementLine | null;
12852
+ limbs: LimbLine | null;
12853
+ sweep: SweepLine | null;
12854
+ sweepSteps: Map<string, { left: number; right: number }>;
12855
+ motionSeam: MotionSeamLine;
12856
+ physics: PhysicsContributionLine;
12857
+ sourceRead: ReportedLine | null;
12858
+ skipReasons: CheckBarSkipReasons;
12859
+ } {
12860
+ const meshReportPath = join(ctx.inp.rigDir, 'mesh_report.json');
12861
+ let meshReport: unknown = [];
12862
+ if (existsSync(meshReportPath)) {
12863
+ try {
12864
+ meshReport = JSON.parse(readFileSync(meshReportPath, 'utf8')) as unknown;
12865
+ } catch (err) {
12866
+ refuseIfAny([{ code: 'CHECK_INPUT_IS_JSON', object: meshReportPath, detail: `does not parse as JSON: ${(err as Error).message}` }]);
12867
+ }
12868
+ if (!Array.isArray(meshReport)) refuseIfAny([{ code: 'CHECK_INPUT_IS_JSON', object: meshReportPath, detail: 'an array of per-part mesh reports is required' }]);
12869
+ }
12870
+
12871
+ const multiCharacter = ctx.characters.length > 1;
12872
+ const reports: ComposedCharacterReport[] = [];
12873
+ const problems: Problem[] = [];
12874
+ const charactersMap: Record<string, ComposedCharacterCheckFigures> = {};
12875
+ const sweepSteps = new Map<string, { left: number; right: number }>();
12876
+
12877
+ for (const c of ctx.characters) {
12878
+ const res = measureOneComposedCharacter(c, { ...ctx, meshReport, multiCharacter });
12879
+ reports.push(res.report);
12880
+ problems.push(...res.problems);
12881
+ charactersMap[c.id] = res.report.figures;
12882
+ for (const [k, v] of res.report.sweepSteps) sweepSteps.set(k, v);
12883
+ }
12884
+
12885
+ const pickJudgement = <Id extends 'BREATH_VISIBLE' | 'BLINK_NO_HOLE' | 'TIP_OVER_ROOT' | 'STILL_REGIONS_DARK'>(id: Id, skipReasons: CheckBarSkipReasons): JudgementLine => {
12886
+ const agg = aggregateCharacterBarOutcome(reports.map(r => r.figures.bar_outcomes[id]));
12887
+ if (agg.status !== 'SKIP') return reports.find(r => r.figures[id].status === agg.status)!.figures[id];
12888
+ const skipReason = agg.reason;
12889
+ const chosen = reports.find(r => {
12890
+ const o = r.figures.bar_outcomes[id];
12891
+ return o.status === 'SKIP' && o.reason === skipReason;
12892
+ }) ?? reports[0];
12893
+ if (skipReason !== 'no-idle' && skipReason !== 'no-parts') {
12894
+ skipReasons[id] = skipReason as NonNullable<CheckBarSkipReasons[Id]>;
12895
+ }
12896
+ return chosen.figures[id];
12897
+ };
12898
+
12899
+ const skipReasons: CheckBarSkipReasons = {};
12900
+ const breath = mergeMultiCharacterJudgementDeclarations('BREATH_VISIBLE', pickJudgement('BREATH_VISIBLE', skipReasons), reports);
12901
+ const blink = pickJudgement('BLINK_NO_HOLE', skipReasons);
12902
+ const tip = mergeMultiCharacterJudgementDeclarations('TIP_OVER_ROOT', pickJudgement('TIP_OVER_ROOT', skipReasons), reports);
12903
+ const still = mergeMultiCharacterJudgementDeclarations('STILL_REGIONS_DARK', pickJudgement('STILL_REGIONS_DARK', skipReasons), reports);
12904
+
12905
+ // Seam representative (worst failing character if any failed, else worst rig-px error).
12906
+ const worstSeamReport = [...reports].sort((a, b) => {
12907
+ const aFail = a.figures.bar_outcomes.seam.status === 'FAIL' ? 1 : 0;
12908
+ const bFail = b.figures.bar_outcomes.seam.status === 'FAIL' ? 1 : 0;
12909
+ if (aFail !== bFail) return bFail - aFail;
12910
+ const aRigPx = seamRigPx(a.figures.seam_px_over_40 ?? 0, a.figures.seam_frame_scale ?? 1);
12911
+ const bRigPx = seamRigPx(b.figures.seam_px_over_40 ?? 0, b.figures.seam_frame_scale ?? 1);
12912
+ if (aRigPx !== bRigPx) return bRigPx - aRigPx;
12913
+ return (b.figures.seam_mean ?? 0) - (a.figures.seam_mean ?? 0);
12914
+ })[0];
12915
+ const seam: SeamFigures = {
12916
+ mean: worstSeamReport.figures.seam_mean ?? 0,
12917
+ over40: worstSeamReport.figures.seam_px_over_40 ?? 0,
12918
+ over80: worstSeamReport.figures.seam_px_over_80 ?? 0,
12919
+ border: worstSeamReport.figures.seam_border === undefined ? null : { framePx: worstSeamReport.figures.seam_border.frame_px_left_out, over40: worstSeamReport.figures.seam_border.px_over_40_left_out },
12920
+ counted: [],
12921
+ countedDiff: [],
12922
+ map: { sx: 1, sy: 1, tx: 0, ty: 0 },
12923
+ };
12924
+ const seamViewport = worstSeamReport.seamViewport;
12925
+ const seamFrameScale = worstSeamReport.figures.seam_frame_scale;
12926
+ const seamScope = !multiCharacter ? worstSeamReport.figures.seam_scope : undefined;
12927
+ const allSeamPairs = reports.flatMap(r => r.figures.seam_pairs ?? []);
12928
+ const seamPairs = allSeamPairs.length > 0 ? allSeamPairs : null;
12929
+
12930
+ // FEET_STAY_LEVEL
12931
+ const withLevel = reports.map(r => r.figures[LEVEL_LINE]).filter((l): l is LevelLine => l !== undefined);
12932
+ let level: LevelLine | null = null;
12933
+ if (withLevel.length === 1) level = withLevel[0];
12934
+ else if (withLevel.length > 1) {
12935
+ const agg = aggregateCharacterBarOutcome(reports.map(r => r.figures.bar_outcomes[LEVEL_LINE]));
12936
+ level = {
12937
+ ...withLevel[0],
12938
+ status: agg.status,
12939
+ ...(agg.status === 'SKIP' ? { reason: withLevel.find(l => l.status === 'SKIP')?.reason ?? agg.reason } : {}),
12940
+ animations: [...new Set(withLevel.flatMap(l => l.animations))],
12941
+ physics_left_out: withLevel.reduce((n, l) => n + l.physics_left_out, 0),
12942
+ feet: withLevel.flatMap(l => l.feet),
12943
+ };
12944
+ if (agg.status !== 'SKIP') delete (level as { reason?: string }).reason;
12945
+ }
12946
+
12947
+ // STRESS_OFF_CHAIN
12948
+ const withStress = reports.filter(r => r.figures[STRESS_LINE] !== undefined);
12949
+ let stress: JudgementLine | null = null;
12950
+ if (withStress.length === 1) stress = withStress[0].figures[STRESS_LINE]!;
12951
+ else if (withStress.length > 1) {
12952
+ const agg = aggregateCharacterBarOutcome(reports.map(r => r.figures.bar_outcomes[STRESS_LINE]));
12953
+ stress = agg.status === 'FAIL'
12954
+ ? withStress.find(r => r.figures[STRESS_LINE]!.status === 'FAIL')!.figures[STRESS_LINE]!
12955
+ : agg.status === 'PASS'
12956
+ ? withStress.find(r => r.figures[STRESS_LINE]!.status === 'PASS')!.figures[STRESS_LINE]!
12957
+ : withStress[0].figures[STRESS_LINE]!;
12958
+ }
12959
+
12960
+ // LIMB_ONE_BONE
12961
+ const withLimbs = reports.map(r => r.figures[LIMB_LINE]).filter((l): l is LimbLine => l !== undefined);
12962
+ const limbs: LimbLine | null = withLimbs.length === 0 ? null : {
12963
+ status: withLimbs.some(l => l.status === 'FAIL') ? 'FAIL' : 'PASS',
12964
+ parts: withLimbs.flatMap(l => l.parts),
12965
+ };
12966
+
12967
+ // SEAM_OVER_RANGE
12968
+ const withSweep = reports.map(r => r.figures[SWEEP_LINE]).filter((l): l is SweepLine => l !== undefined);
12969
+ const sweep: SweepLine | null = withSweep.length === 0 ? null : withSweep.length === 1 ? withSweep[0] : {
12970
+ status: withSweep.some(l => l.status === 'FAIL') ? 'FAIL' : 'PASS',
12971
+ frame_scale: withSweep[0].frame_scale,
12972
+ physics_left_out: withSweep.reduce((n, l) => n + l.physics_left_out, 0),
12973
+ bar: withSweep[0].bar,
12974
+ joints: withSweep.flatMap(l => l.joints),
12975
+ };
12976
+
12977
+ // SEAM_OVER_MOTION
12978
+ let motionSeam: MotionSeamLine;
12979
+ if (reports.length === 1) motionSeam = reports[0].motionSeam;
12980
+ else {
12981
+ const allPairs = reports.flatMap(r => r.motionSeam.pairs);
12982
+ const allRows = reports.flatMap(r => r.motionSeam.rows);
12983
+ const allAnims = [...new Set(reports.flatMap(r => r.motionSeam.animations))];
12984
+ const rootsList = reports.map(r => r.motionSeam.roots).filter((rt): rt is NonNullable<MotionSeamLine['roots']> => rt !== undefined);
12985
+ const unmeasuredRoots = rootsList.flatMap(rt => rt.unmeasured ?? []);
12986
+ if (allPairs.length === 0 && rootsList.length === 0) {
12987
+ motionSeam = reports[0].motionSeam;
12988
+ } else {
12989
+ const dummyProblems: Problem[] = [];
12990
+ motionSeam = motionSeamLine(allPairs, allAnims, IDLE_FPS, allRows, undefined, dummyProblems, unmeasuredRoots);
12991
+ if (rootsList.length > 0 && motionSeam.roots === undefined) {
12992
+ const rootFail = rootsList.some(rt => rt.status === 'FAIL');
12993
+ const rootPass = !rootFail && rootsList.some(rt => rt.status === 'PASS');
12994
+ motionSeam.roots = {
12995
+ ...rootsList[0],
12996
+ status: rootFail ? 'FAIL' : rootPass ? 'PASS' : 'SKIP',
12997
+ pairs: rootsList.flatMap(rt => rt.pairs),
12998
+ failed: rootsList.reduce((n, rt) => n + rt.failed, 0),
12999
+ ...(unmeasuredRoots.length === 0 ? {} : { unmeasured: unmeasuredRoots }),
13000
+ ...(!rootFail && !rootPass ? { reason: rootsList.find(rt => rt.reason !== undefined)?.reason } : {}),
13001
+ };
13002
+ if (rootFail || rootPass) delete motionSeam.roots.reason;
13003
+ } else if (rootsList.length > 0 && motionSeam.roots !== undefined) {
13004
+ // When one character has measured PASS roots and another has unmeasured roots without FAIL, aggregate bar rule says PASS if any character passed and none failed.
13005
+ const aggSeamMotion = aggregateCharacterBarOutcome(reports.map(r => r.figures.bar_outcomes[MOTION_SEAM_LINE]));
13006
+ if (aggSeamMotion.status === 'PASS' && motionSeam.roots.status === 'SKIP') {
13007
+ motionSeam.roots = { ...motionSeam.roots, status: 'PASS' };
13008
+ delete motionSeam.roots.reason;
13009
+ }
13010
+ }
13011
+ }
13012
+ }
13013
+ if (ctx.seamRequired && ctx.reqFile !== null) {
13014
+ const allBgRows = reports.flatMap(r => r.backgroundRows);
13015
+ const reqBlock = motionSeamRequired(
13016
+ reports.length === 1 ? { ...motionSeam } : motionSeam,
13017
+ allBgRows,
13018
+ ctx.reqFile.path,
13019
+ problems,
13020
+ ctx.motionCellEvidence,
13021
+ );
13022
+ motionSeam = { ...motionSeam, required: reqBlock };
13023
+ for (const r of reports) {
13024
+ const prefix = `${r.id}:`;
13025
+ const charReqPairs = reqBlock.pairs.filter(p => p.pair.startsWith(prefix));
13026
+ if (charReqPairs.length === 0 && reports.length > 1) continue;
13027
+ const charFailed = charReqPairs.reduce((n, p) => n + (p.background_frames > 0 ? 1 : 0), 0) +
13028
+ r.motionSeam.pairs.filter(p => p.unread !== undefined).length +
13029
+ (reports.length === 1 && reqBlock.pairs.length === 0 ? reqBlock.failed : 0);
13030
+ const charReq: MotionSeamRequired = reports.length === 1
13031
+ ? reqBlock
13032
+ : {
13033
+ status: charFailed === 0 ? 'PASS' : 'FAIL',
13034
+ mode: 'gap-open',
13035
+ bar_px: 0,
13036
+ pairs: charReqPairs,
13037
+ failed: charFailed,
13038
+ ...(charReqPairs.some(p => (p.open_frames?.length ?? 0) > 0) && reqBlock.cells !== undefined ? { cells: reqBlock.cells } : {}),
13039
+ };
13040
+ r.motionSeam = { ...r.motionSeam, required: charReq };
13041
+ r.figures[MOTION_SEAM_LINE] = r.motionSeam;
13042
+ r.figures.bar_outcomes[MOTION_SEAM_LINE] = {
13043
+ status: r.motionSeam.roots?.status === 'FAIL' || charReq.status === 'FAIL' ? 'FAIL' : 'PASS',
13044
+ };
13045
+ }
13046
+ }
13047
+
13048
+ // PHYSICS_CONTRIBUTES
13049
+ const activePhysics = reports.map(r => r.physics).filter(p => p.status !== 'SKIP');
13050
+ const physics: PhysicsContributionLine = activePhysics.length === 0
13051
+ ? reports[0].physics
13052
+ : activePhysics.length === 1
13053
+ ? activePhysics[0]
13054
+ : physicsLine(
13055
+ activePhysics.flatMap(p => p.rows),
13056
+ activePhysics[0].fps,
13057
+ activePhysics[0].frames,
13058
+ activePhysics[0].poser,
13059
+ activePhysics[0].world,
13060
+ );
13061
+
13062
+ const sourceRead = reports.length === 1 ? (reports[0].figures.SETUP_POSE_VS_SOURCE ?? null) : null;
13063
+
13064
+ return {
13065
+ reports,
13066
+ charactersMap,
13067
+ problems,
13068
+ seam,
13069
+ seamViewport,
13070
+ seamFrameScale,
13071
+ seamScope,
13072
+ seamPairs,
13073
+ breath,
13074
+ blink,
13075
+ tip,
13076
+ still,
13077
+ level,
13078
+ stress,
13079
+ limbs,
13080
+ sweep,
13081
+ sweepSteps,
13082
+ motionSeam,
13083
+ physics,
13084
+ sourceRead,
13085
+ skipReasons,
13086
+ };
13087
+ }