@rig-c/parts 2.43.0 → 2.44.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.
@@ -0,0 +1,139 @@
1
+ /** Scene-authored clips use final names and Core's motion parser and poser. */
2
+ import { CompileError } from '@rig-c/core/errors';
3
+ import { parseMotionSpec, type MotionSpec as CoreMotion } from '@rig-c/core/motion';
4
+ import { CoreInputError, poseRawAnimation, readModel, type RawPose } from '@rig-c/core/core';
5
+ import { PartsError, refuseIfAny, type Problem } from './errors.ts';
6
+ import type { MotionSpec } from './motion.ts';
7
+ import type { RigSpec } from './rig.ts';
8
+
9
+ export type SceneAnimations = CoreMotion['animations'];
10
+
11
+ /** Core owns shape, required numbers, key times and all target families. */
12
+ export function readSceneAnimations(raw: unknown, where: string): SceneAnimations {
13
+ try {
14
+ return parseMotionSpec({ spec: 'rigc-motion/1', archetype: 'scene', cut: 'scene', easings: {}, groups: {}, animations: raw }, where).animations;
15
+ } catch (err) {
16
+ if (!(err instanceof CompileError) || err.code === undefined) throw err;
17
+ throw new PartsError([{ code: err.code, object: 'scene.animations', detail: err.message }]);
18
+ }
19
+ }
20
+
21
+ /** Core slider source properties and the bone timeline channels that feed them. */
22
+ function sliderInputChannel(source: unknown, property: string): number | null {
23
+ switch (source) {
24
+ case 'rotate': return property === 'rotate' ? 0 : null;
25
+ case 'x': return property === 'translatex' || property === 'translate' ? 0 : null;
26
+ case 'y': return property === 'translatey' ? 0 : property === 'translate' ? 1 : null;
27
+ case 'scaleX': return property === 'scalex' || property === 'scale' ? 0 : null;
28
+ case 'scaleY': return property === 'scaley' ? 0 : property === 'scale' ? 1 : null;
29
+ case 'shearY': return property === 'sheary' ? 0 : property === 'shear' ? 1 : null;
30
+ default: return null; // Core names unsupported slider source properties at its gate.
31
+ }
32
+ }
33
+
34
+ /** Append timelines without changing existing idle payloads or character physics. */
35
+ export function mergeSceneAnimations(rig: RigSpec, motion: MotionSpec, clips: SceneAnimations): void {
36
+ const problems: Problem[] = [];
37
+ const animations = motion.animations as unknown as SceneAnimations;
38
+ for (const [name, clip] of Object.entries(clips)) {
39
+ const existing = Object.hasOwn(animations, name) ? animations[name] : undefined;
40
+ if (existing !== undefined && name !== 'idle') {
41
+ problems.push({ code: 'SCENE_ANIMATION_NAME_FREE', object: `scene.animations.${name}`, detail: `already names an imported animation; only idle may be extended` });
42
+ continue;
43
+ }
44
+ if (existing !== undefined && clip.duration !== existing.duration) {
45
+ problems.push({ code: 'SCENE_DURATION_AGREES', object: `scene.animations.${name}.duration`, detail: `is ${clip.duration}; composed idle declares ${existing.duration}; equal durations are required, without retiming` });
46
+ continue;
47
+ }
48
+ // Bounds belong to the actual final slider, never to a guessed dial-name list.
49
+ // `from` is the declared bottom and `max` the editor's declared top (Core's RigSliderConstraint).
50
+ for (const track of clip.tracks) {
51
+ if (track.group !== undefined && (!Object.hasOwn(motion.groups, track.group) || !Array.isArray(motion.groups[track.group]))) {
52
+ problems.push({ code: 'CE_COMPILE_ANIMATION_GROUP_UNKNOWN', object: `scene.animations.${name}`,
53
+ detail: `animation "${name}": unknown group "${track.group}"; an own declared group is required` });
54
+ continue;
55
+ }
56
+ const targets = track.bone === undefined ? (track.group === undefined ? [] : motion.groups[track.group]) : [track.bone];
57
+ for (const bone of targets) for (const slider of rig.constraints ?? []) {
58
+ if (slider.type !== 'slider' || slider.bone !== bone) continue;
59
+ const channel = sliderInputChannel(slider.property, track.property);
60
+ if (channel === null) continue;
61
+ const from = slider.from, max = slider.max;
62
+ if (typeof from !== 'number' || !Number.isFinite(from) || typeof max !== 'number' || !Number.isFinite(max) || from > max) {
63
+ problems.push({ code: 'SCENE_DIAL_RANGE_DECLARED', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}"`, detail: `has no readable declared range: from ${String(from)}, max ${String(max)}; declare both bounds before keying this dial` });
64
+ continue;
65
+ }
66
+ for (const key of track.keys) {
67
+ if (key.derive !== undefined) {
68
+ problems.push({ code: 'SCENE_DIAL_KEY_DECLARED', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}" key t=${key.t}`,
69
+ detail: `uses derive on the slider's ${String(slider.property)} input; declare an explicit numeric v in [${from}, ${max}] so its own bounds can be checked` });
70
+ continue;
71
+ }
72
+ const value = key.v !== null && typeof key.v === 'object' && !Array.isArray(key.v) ? key.v[bone] : key.v;
73
+ if (!Array.isArray(value)) continue; // Core refuses missing/malformed values; derived slider inputs were refused above.
74
+ const v = value[channel];
75
+ if (typeof v === 'number' && (v < from || v > max)) problems.push({
76
+ code: 'SCENE_DIAL_KEY_RANGE', object: `scene.animations.${name} bone "${bone}" slider "${String(slider.name)}" key t=${key.t}`,
77
+ detail: `value ${v} is outside declared range [${from}, ${max}]`,
78
+ });
79
+ }
80
+ }
81
+ }
82
+ if (existing === undefined) Object.defineProperty(animations, name, { value: structuredClone(clip), enumerable: true, configurable: true, writable: true });
83
+ else {
84
+ // Core rejects overlapping property claims after expansion, including group/bone collisions.
85
+ // Keep the existing idle metadata; every timeline collection is appended in producer order.
86
+ for (const field of ['tracks', 'deform', 'ik', 'transform', 'sequence', 'events', 'drawOrder'] as const) {
87
+ const added = clip[field];
88
+ if (added !== undefined) Object.assign(existing, { [field]: [...(existing[field] ?? []), ...structuredClone(added)] });
89
+ }
90
+ }
91
+ }
92
+ refuseIfAny(problems);
93
+ }
94
+
95
+ /** Add character context to Core's existing unknown-bone sentence, without changing its code. */
96
+ export function sceneBoneContext(line: string, ids: readonly string[]): string {
97
+ const bone = /keys unknown bone "([^"]+)"/.exec(line)?.[1];
98
+ const id = bone === undefined ? undefined : ids.find(id => bone.startsWith(`${id}:`));
99
+ return id === undefined ? line : `${line}; character "${id}" declares no bone "${bone}"`;
100
+ }
101
+
102
+ /** Time and fired events are not pose state. Geometry includes alpha, deforms and invisible bones. */
103
+ export function scenePoseState(pose: RawPose): string {
104
+ return JSON.stringify({ bones: pose.bones, slots: pose.slots, drawOrder: pose.drawOrder, drawn: pose.drawn, clips: pose.clips, clipped: pose.clipped });
105
+ }
106
+
107
+ /** A throwaway keyed-pose view; simulation is retained in the emitted document. */
108
+ export function sceneKeyedModel(modelText: string) {
109
+ const raw = JSON.parse(modelText) as Record<string, unknown>;
110
+ // Remove simulation only from the read view, retaining all non-physics constraints and timelines.
111
+ const constraints = raw.constraints as Array<{ kind: string; name: string }>;
112
+ const physics = constraints.filter(c => c.kind === 'physics').map(c => c.name);
113
+ raw.constraints = constraints.filter(c => c.kind !== 'physics');
114
+ for (const skin of raw.skins as Array<{ constraints?: Record<string, unknown> }>) if (skin.constraints !== undefined) skin.constraints = { ...skin.constraints, physics: [] };
115
+ for (const animation of Object.values(raw.animations as Record<string, { constraints: Record<string, unknown> }>)) animation.constraints = { ...animation.constraints, physics: [] };
116
+ const doc = readModel(JSON.stringify(raw), 'composed scene model');
117
+ return { doc, physics };
118
+ }
119
+
120
+ /** Measure the actual gated poses at both endpoints, without wrapping duration to zero.
121
+ * Physics is omitted only from this observation, as in check's keyed-loop bar;
122
+ * the gated/emitted motion and physics constraints are never edited.
123
+ */
124
+ export function sceneClipLoopProblems(modelText: string, clips: SceneAnimations): Problem[] {
125
+ try {
126
+ const { doc, physics } = sceneKeyedModel(modelText);
127
+ const problems: Problem[] = [];
128
+ for (const [name, clip] of Object.entries(clips)) {
129
+ const poses = poseRawAnimation(doc, name, [clip.duration]);
130
+ if (poses.length !== 2 || poses[0].animationTime !== 0 || poses[1].trackTime !== clip.duration || scenePoseState(poses[0]) !== scenePoseState(poses[1])) {
131
+ problems.push({ code: 'SCENE_ANIMATION_LOOP_CLOSES', object: `scene.animations.${name}`, detail: `posed samples at t=0 and t=${clip.duration} differ; identical endpoint poses are required (physics left out: ${physics.join(', ') || 'none'})` });
132
+ }
133
+ }
134
+ return problems;
135
+ } catch (err) {
136
+ if (!(err instanceof CoreInputError)) throw err;
137
+ return [{ code: 'SCENE_ANIMATION_POSE_READABLE', object: 'scene.animations', detail: err.message }];
138
+ }
139
+ }