skia-motion-runtime 0.0.0-stage → 3.0.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,384 @@
1
+ // The schema and graph validator are shared by the CLI and the mobile asset loader.
2
+ export const SCHEMA = 'skac.machine/1';
3
+ export const VALUE_TYPES = ['boolean', 'number', 'enum', 'trigger'];
4
+ export const BINDS = ['in', 'out', 'both'];
5
+ export const LOOPS = ['once', 'loop', 'pingpong'];
6
+ export const EASES = ['linear', 'out', 'inOut', 'in'];
7
+ export const OPS = ['==', '!=', '<', '<=', '>', '>='];
8
+ export const HIT_KINDS = ['tap']; // down and up wait for a gesture model in both runtimes (M2)
9
+ /** Rive's cap, kept: a layer changes state at most this often in one instant (rive-runtime state_machine_instance.cpp). */
10
+ export const MAX_CHANGES = 100;
11
+
12
+ const KEYS = {
13
+ root: ['schema', 'values', 'clocks', 'layers', 'hits'],
14
+ value: ['type', 'default', 'options', 'bind'],
15
+ clock: ['wrap_ms', 'step_hz'],
16
+ layer: ['name', 'entry', 'clock', 'states', 'transitions'],
17
+ state: ['clip', 'loop', 'speed', 'blend', 'reason', 'on_enter', 'on_exit'],
18
+ blend: ['by', 'keys'],
19
+ transition: ['from', 'to', 'when', 'exit_at', 'duration_ms', 'ease', 'on_start', 'on_end'],
20
+ entry: ['to', 'when'],
21
+ action: ['set', 'to', 'fire'],
22
+ hit: ['part', 'on', 'set', 'to', 'fire'],
23
+ };
24
+
25
+ export const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
26
+ const typeOfLiteral = (v) => (typeof v === 'boolean' ? 'boolean' : typeof v === 'number' && Number.isFinite(v) ? 'number' : typeof v === 'string' ? 'string' : null);
27
+
28
+ /**
29
+ * Judge a parsed machine. Returns `{problems, warnings}`: each `{where, error, hint}`. `clipNames`, when given, are the
30
+ * clips `<Name>.clips.ts` exports; with `clips` their lengths are also checked against wrapping clocks.
31
+ * @param {unknown} m
32
+ * @param {{clips?: Record<string, {ms: number}>, clipNames?: string[]}} [opts]
33
+ */
34
+ export const validateMachine = (m, { clips, clipNames = clips && Object.keys(clips) } = {}) => {
35
+ const problems = [];
36
+ const warnings = [];
37
+ const bad = (where, error, hint) => problems.push({ where, error, hint });
38
+ const unknownKeys = (obj, allowed, where) => {
39
+ for (const k of Object.keys(obj)) {
40
+ if (!allowed.includes(k)) bad(where, `unknown key "${k}"`, `allowed here: ${allowed.join(', ')}. A newer skac may know it: check \`skac --version\``);
41
+ }
42
+ };
43
+
44
+ if (!isObj(m)) {
45
+ bad('', 'the machine is not a JSON object', `start from {"schema":"${SCHEMA}","values":{},"layers":[]}`);
46
+ return { problems, warnings };
47
+ }
48
+ unknownKeys(m, KEYS.root, '');
49
+ if (m.schema !== SCHEMA) {
50
+ const major = typeof m.schema === 'string' && m.schema.startsWith('skac.machine/') ? m.schema : null;
51
+ bad('schema', `schema is ${JSON.stringify(m.schema)}`, major ? `this skac reads ${SCHEMA}; update skac to read ${major}` : `set "schema": "${SCHEMA}"`);
52
+ }
53
+
54
+ // Values.
55
+ const values = isObj(m.values) ? m.values : {};
56
+ if (m.values !== undefined && !isObj(m.values)) bad('values', 'values is not an object', 'like "values": {"live": {"type": "boolean"}}');
57
+ for (const [name, v] of Object.entries(values)) {
58
+ const where = `values.${name}`;
59
+ if (!isObj(v)) { bad(where, 'a value is not an object', 'like {"type": "boolean", "default": false}'); continue; }
60
+ unknownKeys(v, KEYS.value, where);
61
+ if (!VALUE_TYPES.includes(v.type)) { bad(where, `type ${JSON.stringify(v.type)} is not one of ${VALUE_TYPES.join(', ')}`, 'string, colour, image and list values are not in skac.machine/1'); continue; }
62
+ if (v.bind !== undefined && !BINDS.includes(v.bind)) bad(where, `bind ${JSON.stringify(v.bind)} is not one of ${BINDS.join(', ')}`, '"in": the app writes it; "out": the machine writes it and the app reads it; "both"');
63
+ if (v.type === 'enum') {
64
+ if (!Array.isArray(v.options) || v.options.length < 2 || !v.options.every((o) => typeof o === 'string')) {
65
+ bad(where, 'an enum needs "options", two or more strings', 'like "options": ["idle", "happy", "sad"]');
66
+ } else if (new Set(v.options).size !== v.options.length) bad(where, 'enum options repeat', 'name each option once');
67
+ } else if (v.options !== undefined) bad(where, `"options" belongs to an enum, not a ${v.type}`, 'remove "options"');
68
+ if (v.type === 'trigger') {
69
+ if (v.default !== undefined) bad(where, 'a trigger has no default', 'remove "default": a trigger is fired, never held');
70
+ } else if (v.default !== undefined) {
71
+ const want = v.type === 'enum' ? 'string' : v.type;
72
+ if (typeOfLiteral(v.default) !== want) bad(where, `default ${JSON.stringify(v.default)} is not a ${v.type}`, `give a ${v.type} default`);
73
+ else if (v.type === 'enum' && Array.isArray(v.options) && !v.options.includes(v.default)) bad(where, `default "${v.default}" is not an option`, `pick one of ${v.options.join(', ')}`);
74
+ }
75
+ }
76
+ const valueType = (n) => (isObj(values[n]) ? values[n].type : undefined);
77
+
78
+ // Clocks.
79
+ const clocks = isObj(m.clocks) ? m.clocks : {};
80
+ if (m.clocks !== undefined && !isObj(m.clocks)) bad('clocks', 'clocks is not an object', 'like "clocks": {"ambient": {"wrap_ms": 64000, "step_hz": 30}}');
81
+ for (const [name, c] of Object.entries(clocks)) {
82
+ const where = `clocks.${name}`;
83
+ if (!isObj(c)) { bad(where, 'a clock is not an object', 'like {"wrap_ms": 64000, "step_hz": 30}'); continue; }
84
+ unknownKeys(c, KEYS.clock, where);
85
+ if (c.wrap_ms !== undefined && !(typeof c.wrap_ms === 'number' && c.wrap_ms > 0)) bad(where, 'wrap_ms is not a positive number', 'the length in ms after which the clock starts again, or leave it out');
86
+ if (!(typeof c.step_hz === 'number' && c.step_hz > 0 && c.step_hz <= 240)) bad(where, 'step_hz is not a rate from 1 to 240', 'how often the app steps this clock, like 30; the CLI simulates it at that rate');
87
+ }
88
+
89
+ // A literal or a value name on the right of a condition or action, checked against the type it must have.
90
+ const operand = (rhs, type, where, options, assignment = false) => {
91
+ const enumOptions = type === 'enum' && Array.isArray(options) ? options : undefined;
92
+ if (typeof rhs === 'string' && values[rhs] !== undefined && !enumOptions?.includes(rhs)) {
93
+ if (valueType(rhs) !== type) bad(where, `"${rhs}" is a ${valueType(rhs)}, compared with a ${type}`, 'compare values of one type');
94
+ else if (assignment && enumOptions && Array.isArray(values[rhs].options)) {
95
+ const missing = values[rhs].options.filter((option) => !enumOptions.includes(option));
96
+ if (missing.length) bad(where, `enum "${rhs}" can write undeclared options: ${missing.join(', ')}`, 'use an enum with only options the destination declares');
97
+ }
98
+ return;
99
+ }
100
+ const want = type === 'enum' ? 'string' : type;
101
+ if (typeOfLiteral(rhs) !== want) bad(where, `${JSON.stringify(rhs)} is not a ${type} or the name of a value`, `give a ${type}`);
102
+ else if (enumOptions && !enumOptions.includes(rhs)) bad(where, `"${rhs}" is not an option of the enum`, `pick one of ${enumOptions.join(', ')}`);
103
+ };
104
+
105
+ const conditions = (when, where) => {
106
+ if (when === undefined) return [];
107
+ if (!Array.isArray(when)) { bad(where, '"when" is not a list', 'like "when": [["live", "==", true]]'); return []; }
108
+ const triggers = [];
109
+ when.forEach((c, i) => {
110
+ const w = `${where}[${i}]`;
111
+ if (!Array.isArray(c) || (c.length !== 1 && c.length !== 3)) { bad(w, 'a condition is not [value] or [value, op, operand]', 'like ["live", "==", true], or ["tap"] for a trigger'); return; }
112
+ const [lhs, op, rhs] = c;
113
+ const t = valueType(lhs);
114
+ if (!t) { bad(w, `no value named ${JSON.stringify(lhs)}`, `declare it under "values"`); return; }
115
+ if (c.length === 1) {
116
+ if (t !== 'trigger') bad(w, `["${lhs}"] alone works for a trigger, and ${lhs} is a ${t}`, `like ["${lhs}", "==", ${t === 'boolean' ? 'true' : '…'}]`);
117
+ else triggers.push(lhs);
118
+ return;
119
+ }
120
+ if (t === 'trigger') { bad(w, `${lhs} is a trigger: write ["${lhs}"]`, 'a trigger is true for the one instant it fires'); return; }
121
+ if (!OPS.includes(op)) { bad(w, `operator ${JSON.stringify(op)} is not one of ${OPS.join(' ')}`, 'use one of them'); return; }
122
+ if (t !== 'number' && !['==', '!='].includes(op)) bad(w, `${op} compares numbers, and ${lhs} is a ${t}`, 'use == or !=');
123
+ operand(rhs, t, w, values[lhs].options);
124
+ });
125
+ return triggers;
126
+ };
127
+
128
+ const actions = (list, where) => {
129
+ if (list === undefined) return;
130
+ if (!Array.isArray(list)) { bad(where, 'actions are not a list', 'like [{"set": "mood", "to": "happy"}]'); return; }
131
+ list.forEach((a, i) => {
132
+ const w = `${where}[${i}]`;
133
+ if (!isObj(a)) { bad(w, 'an action is not an object', 'like {"set": "mood", "to": "happy"} or {"fire": "done"}'); return; }
134
+ unknownKeys(a, KEYS.action, w);
135
+ if (a.fire !== undefined) {
136
+ if (a.set !== undefined || a.to !== undefined) bad(w, 'an action either sets or fires', 'split it into two actions');
137
+ if (valueType(a.fire) !== 'trigger') bad(w, `"${a.fire}" is not a trigger`, 'fire a trigger value; set the others');
138
+ return;
139
+ }
140
+ const t = valueType(a.set);
141
+ if (!t) { bad(w, `no value named ${JSON.stringify(a.set)}`, 'declare it under "values"'); return; }
142
+ if (t === 'trigger') { bad(w, `"${a.set}" is a trigger`, `write {"fire": "${a.set}"}`); return; }
143
+ if (a.to === undefined) { bad(w, 'a set action has no "to"', 'give the new value'); return; }
144
+ operand(a.to, t, w, values[a.set].options, true);
145
+ });
146
+ };
147
+
148
+ // Layers.
149
+ if (!Array.isArray(m.layers) || m.layers.length === 0) bad('layers', 'there are no layers', 'add {"name": "main", "entry": "idle", "states": {"idle": {"clip": "idle"}}}');
150
+ const layers = Array.isArray(m.layers) ? m.layers : [];
151
+ const layerNames = new Set();
152
+ const graphs = [];
153
+ layers.forEach((L, li) => {
154
+ const lw = `layers[${li}]`;
155
+ if (!isObj(L)) { bad(lw, 'a layer is not an object', 'like {"name": "main", "entry": "idle", "states": {...}}'); return; }
156
+ unknownKeys(L, KEYS.layer, lw);
157
+ if (typeof L.name !== 'string' || !L.name) bad(lw, 'a layer has no name', 'name it');
158
+ else if (layerNames.has(L.name)) bad(lw, `layer name "${L.name}" repeats`, 'name each layer once');
159
+ else layerNames.add(L.name);
160
+ const where = typeof L.name === 'string' && L.name ? `layers.${L.name}` : lw;
161
+ if (L.clock !== undefined && !isObj(clocks[L.clock])) bad(`${where}.clock`, `no clock named ${JSON.stringify(L.clock)}`, 'declare it under "clocks", or leave "clock" out for the frame clock');
162
+ const wrap = typeof L.clock === 'string' ? clocks[L.clock]?.wrap_ms : undefined;
163
+ const states = isObj(L.states) ? L.states : {};
164
+ const names = Object.keys(states);
165
+ if (!names.length) bad(`${where}.states`, 'the layer has no states', 'add one: "idle": {"clip": "idle"}');
166
+ if (names.includes('exit') || names.includes('*')) bad(`${where}.states`, '"exit" and "*" are reserved', 'rename the state');
167
+ for (const [sn, s] of Object.entries(states)) {
168
+ const sw = `${where}.states.${sn}`;
169
+ if (!isObj(s)) { bad(sw, 'a state is not an object', 'like {"clip": "idle", "loop": "loop"}'); continue; }
170
+ unknownKeys(s, KEYS.state, sw);
171
+ if (s.clip !== undefined && s.blend !== undefined) bad(sw, 'a state plays a clip or a blend, not both', 'keep one');
172
+ if (s.clip !== undefined) {
173
+ if (typeof s.clip !== 'string') bad(sw, 'clip is not a name', 'the name of a clip in <Name>.clips.ts');
174
+ else if (clipNames && !clipNames.includes(s.clip)) bad(sw, `no clip named "${s.clip}"`, clipNames.length ? `clips: ${clipNames.join(', ')}` : 'export it from <Name>.clips.ts');
175
+ }
176
+ if (s.loop !== undefined && !LOOPS.includes(s.loop)) bad(sw, `loop ${JSON.stringify(s.loop)} is not one of ${LOOPS.join(', ')}`, 'once plays and holds its last frame');
177
+ if (s.speed !== undefined && !(typeof s.speed === 'number' && s.speed > 0)) bad(sw, 'speed is not a positive number', '1 is normal speed; play a reversed clip for backward');
178
+ if (s.reason !== undefined && typeof s.reason !== 'string') bad(sw, 'reason is not text', 'say why this loop may keep the screen drawing');
179
+ const checkPeriod = (clip, where) => {
180
+ if (!clipNames?.includes(clip) || !Number.isFinite(wrap) || wrap <= 0 || (s.loop !== 'loop' && s.loop !== 'pingpong')) return;
181
+ const period = clips?.[clip]?.ms * (s.loop === 'pingpong' ? 2 : 1) / (s.speed ?? 1);
182
+ if (!Number.isFinite(period) || period <= 0) return;
183
+ const laps = Math.max(1, Math.round(wrap / period));
184
+ if (Math.abs(wrap - laps * period) > 1e-6) {
185
+ warnings.push({ where, error: `clip "${clip}" has a ${period} ms period that does not divide ${L.clock}.wrap_ms (${wrap} ms)`,
186
+ hint: 'use a period that fits a whole number of times in the clock wrap' });
187
+ }
188
+ };
189
+ if (typeof s.clip === 'string') checkPeriod(s.clip, sw);
190
+ if (s.blend !== undefined) {
191
+ const b = s.blend;
192
+ if (!isObj(b)) bad(sw, 'blend is not an object', 'like {"by": "level", "keys": [[0, "empty"], [1, "full"]]}');
193
+ else {
194
+ unknownKeys(b, KEYS.blend, `${sw}.blend`);
195
+ if (valueType(b.by) !== 'number') bad(`${sw}.blend`, `blend "by" ${JSON.stringify(b.by)} is not a number value`, 'a 1D blend follows one number value');
196
+ const keys = Array.isArray(b.keys) ? b.keys : [];
197
+ if (keys.length < 2 || !keys.every((k) => Array.isArray(k) && k.length === 2 && typeof k[0] === 'number' && typeof k[1] === 'string')) {
198
+ bad(`${sw}.blend`, 'keys are not two or more [number, clip] pairs', 'like [[0, "empty"], [1, "full"]]');
199
+ } else {
200
+ for (let i = 1; i < keys.length; i++) if (!(keys[i][0] > keys[i - 1][0])) bad(`${sw}.blend`, 'key values do not rise', 'order the keys by their numbers, each above the last');
201
+ if (clipNames) for (const [, c] of keys) {
202
+ if (!clipNames.includes(c)) bad(`${sw}.blend`, `no clip named "${c}"`, `clips: ${clipNames.join(', ')}`);
203
+ else checkPeriod(c, `${sw}.blend`);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ actions(s.on_enter, `${sw}.on_enter`);
209
+ actions(s.on_exit, `${sw}.on_exit`);
210
+ }
211
+
212
+ // Entry: a state name, or a list of {to, when} where the last has no condition.
213
+ const entryTargets = [];
214
+ if (typeof L.entry === 'string') entryTargets.push(L.entry);
215
+ else if (Array.isArray(L.entry) && L.entry.length) {
216
+ L.entry.forEach((e, i) => {
217
+ const ew = `${where}.entry[${i}]`;
218
+ if (!isObj(e)) { bad(ew, 'an entry branch is not an object', 'like {"to": "on", "when": [["on", "==", true]]}'); return; }
219
+ unknownKeys(e, KEYS.entry, ew);
220
+ entryTargets.push(e.to);
221
+ conditions(e.when, `${ew}.when`);
222
+ if (i === L.entry.length - 1 && e.when !== undefined) bad(ew, 'the last entry branch has a condition', 'end with {"to": "<state>"} so the layer always starts somewhere');
223
+ });
224
+ } else bad(`${where}.entry`, 'the layer has no entry', `like "entry": "${names[0] || 'idle'}"`);
225
+ for (const t of entryTargets) if (!names.includes(t)) bad(`${where}.entry`, `entry goes to "${t}", which is not a state`, `states: ${names.join(', ')}`);
226
+
227
+ // Transitions.
228
+ const edges = []; // {from, to, instant, triggers}
229
+ const setsOf = (list) => (Array.isArray(list) ? list : []).map((a) => (isObj(a) ? a.set ?? a.fire : undefined)).filter((n) => typeof n === 'string');
230
+ const exitWrites = new Map(names.map((n) => [n, setsOf(states[n]?.on_exit)]));
231
+ const transitions = Array.isArray(L.transitions) ? L.transitions : [];
232
+ if (L.transitions !== undefined && !Array.isArray(L.transitions)) bad(`${where}.transitions`, 'transitions are not a list', 'like [{"from": "idle", "to": "hop", "when": [["tap"]]}]');
233
+ transitions.forEach((t, ti) => {
234
+ const tw = `${where}.transitions[${ti}]`;
235
+ if (!isObj(t)) { bad(tw, 'a transition is not an object', 'like {"from": "idle", "to": "hop", "when": [["tap"]]}'); return; }
236
+ unknownKeys(t, KEYS.transition, tw);
237
+ if (t.from !== '*' && !names.includes(t.from)) bad(tw, `from "${t.from}" is not a state`, `use a state or "*" (any state): ${names.join(', ')}`);
238
+ if (t.to !== 'exit' && !names.includes(t.to)) bad(tw, `to "${t.to}" is not a state`, `use a state or "exit": ${names.join(', ')}`);
239
+ const triggers = conditions(t.when, `${tw}.when`);
240
+ if (t.exit_at !== undefined) {
241
+ if (!(typeof t.exit_at === 'number' && t.exit_at > 0)) bad(tw, 'exit_at is not a positive share of the clip', '1 waits for the whole clip; 2 for two laps of a loop');
242
+ if (L.clock !== undefined) bad(tw, 'exit_at on a layer that runs on a named clock', 'the app steps that clock, so its exit times are not known ahead; use a condition, or move the state to a frame-clock layer');
243
+ }
244
+ const noCondition = !Array.isArray(t.when) || t.when.length === 0;
245
+ if (noCondition && t.exit_at === undefined) bad(tw, 'the transition has no condition and no exit_at, so it fires the instant it is reached', 'add "exit_at": 1 to play the clip first, or a condition');
246
+ if (t.duration_ms !== undefined && !(typeof t.duration_ms === 'number' && t.duration_ms >= 0)) bad(tw, 'duration_ms is not a number of ms', 'like 200; 0 cuts');
247
+ if (t.ease !== undefined && !EASES.includes(t.ease)) bad(tw, `ease ${JSON.stringify(t.ease)} is not one of ${EASES.join(', ')}`, 'out suits most UI');
248
+ if (t.to === 'exit' && t.duration_ms) bad(tw, 'a transition to exit has no mix', 'remove duration_ms: the layer holds its pose');
249
+ actions(t.on_start, `${tw}.on_start`);
250
+ actions(t.on_end, `${tw}.on_end`);
251
+ const writes = [...setsOf(t.on_start), ...setsOf(t.on_end), ...setsOf(states[t.to]?.on_enter)];
252
+ edges.push({ from: t.from, to: t.to, instant: t.exit_at === undefined && !t.duration_ms, triggers, when: Array.isArray(t.when) ? t.when : [], writes });
253
+ });
254
+ graphs.push({ name: L.name, where, names, entryTargets, edges, states, exitWrites });
255
+ });
256
+
257
+ // Hits.
258
+ if (m.hits !== undefined && !Array.isArray(m.hits)) bad('hits', 'hits are not a list', 'like [{"part": "button", "on": "tap", "fire": "tap"}]');
259
+ (Array.isArray(m.hits) ? m.hits : []).forEach((h, i) => {
260
+ const hw = `hits[${i}]`;
261
+ if (!isObj(h)) { bad(hw, 'a hit is not an object', 'like {"part": "button", "on": "tap", "fire": "tap"}'); return; }
262
+ unknownKeys(h, KEYS.hit, hw);
263
+ if (typeof h.part !== 'string' || !h.part) bad(hw, 'a hit has no part', 'name a part box the clips return');
264
+ if (!HIT_KINDS.includes(h.on)) bad(hw, `on ${JSON.stringify(h.on)} is not one of ${HIT_KINDS.join(', ')}`, 'tap is a press and release on the part; down and up are not played yet');
265
+ actions([{ ...(h.set !== undefined ? { set: h.set, to: h.to } : {}), ...(h.fire !== undefined ? { fire: h.fire } : {}) }], hw);
266
+ if (h.set === undefined && h.fire === undefined) bad(hw, 'a hit neither sets nor fires', 'add "fire": "<trigger>" or "set" and "to"');
267
+ });
268
+
269
+ // A string operand names a value unless it is an option of the enum it is compared with, as compile reads it.
270
+ const vals = isObj(m.values) ? m.values : {};
271
+ const isRef = (owner, x) => typeof x === 'string' && x in vals && !((isObj(vals[owner]) && Array.isArray(vals[owner].options)) ? vals[owner].options : []).includes(x);
272
+ if (!problems.length) for (const g of graphs) analyse(g, warnings, problems, isRef);
273
+ return { problems, warnings, graphs };
274
+ };
275
+
276
+ /** Two conditions on one value that cannot both hold, for literal operands; an operand naming a value proves nothing. */
277
+ const contradicts = (a, b, isRef) => {
278
+ if (a.length !== 3 || b.length !== 3 || a[0] !== b[0]) return false;
279
+ const [, oa, va] = a;
280
+ const [, ob, vb] = b;
281
+ if (isRef(a[0], va) || isRef(b[0], vb)) return false;
282
+ if (typeof va !== typeof vb) return false;
283
+ if (oa === '==' && ob === '==') return va !== vb;
284
+ if ((oa === '==' && ob === '!=') || (oa === '!=' && ob === '==')) return va === vb;
285
+ if (typeof va === 'number') {
286
+ const lo = (op, v) => (op === '>' ? [v, true] : op === '>=' ? [v, false] : op === '==' ? [v, false] : [-Infinity, false]);
287
+ const hi = (op, v) => (op === '<' ? [v, true] : op === '<=' ? [v, false] : op === '==' ? [v, false] : [Infinity, false]);
288
+ const [l1, lx1] = lo(oa, va); const [l2, lx2] = lo(ob, vb);
289
+ const [h1, hx1] = hi(oa, va); const [h2, hx2] = hi(ob, vb);
290
+ const l = l1 > l2 ? [l1, lx1] : l2 > l1 ? [l2, lx2] : [l1, lx1 || lx2];
291
+ const h = h1 < h2 ? [h1, hx1] : h2 < h1 ? [h2, hx2] : [h1, hx1 || hx2];
292
+ return l[0] > h[0] || (l[0] === h[0] && (l[1] || h[1]));
293
+ }
294
+ return false;
295
+ };
296
+
297
+ /** Assign each state to a strongly connected component of the instant-transition graph. */
298
+ const componentsOf = (out) => {
299
+ const index = new Map();
300
+ const component = new Map();
301
+ const pending = [];
302
+ const visit = (state) => {
303
+ const id = index.size;
304
+ index.set(state, id);
305
+ pending.push(state);
306
+ let low = id;
307
+ for (const { to } of out.get(state)) {
308
+ if (!index.has(to)) low = Math.min(low, visit(to));
309
+ else if (!component.has(to)) low = Math.min(low, index.get(to));
310
+ }
311
+ if (low === id) {
312
+ let member;
313
+ do { member = pending.pop(); component.set(member, id); } while (member !== state);
314
+ }
315
+ return low;
316
+ };
317
+ for (const state of out.keys()) if (!index.has(state)) visit(state);
318
+ return component;
319
+ };
320
+
321
+ /**
322
+ * Reachable states, dead ends and zero-time cycles of one layer. A zero-time cycle is a loop of transitions that take
323
+ * no time (no exit_at, no mix) and read no trigger, whose conditions can hold in sequence. A trigger breaks a cycle,
324
+ * since a layer takes each trigger once per instant.
325
+ */
326
+ const analyse = (g, warnings, problems, isRef) => {
327
+ const any = g.edges.filter((e) => e.from === '*');
328
+ const reach = new Set();
329
+ const stack = [...g.entryTargets];
330
+ while (stack.length) {
331
+ const s = stack.pop();
332
+ if (reach.has(s) || s === 'exit') continue;
333
+ reach.add(s);
334
+ for (const e of g.edges) if ((e.from === s || e.from === '*') && !reach.has(e.to)) stack.push(e.to);
335
+ }
336
+ g.reachable = g.names.filter((n) => reach.has(n));
337
+ g.unreachable = g.names.filter((n) => !reach.has(n));
338
+ for (const n of g.unreachable) {
339
+ problems.push({ where: `${g.where}.states.${n}`, error: `state "${n}" is never reached`, hint: 'add a transition to it, or remove it' });
340
+ }
341
+ g.deadEnds = g.reachable.filter((n) => !any.length && !g.edges.some((e) => e.from === n));
342
+ for (const n of g.deadEnds) {
343
+ warnings.push({ where: `${g.where}.states.${n}`, error: `state "${n}" has no way out`, hint: 'fine for a final state; otherwise add a transition, or an any-state ("*") one' });
344
+ }
345
+ const out = new Map(g.reachable.map((s) => [s, []]));
346
+ g.edges.forEach((e, id) => {
347
+ if (!e.instant || e.triggers.length || !out.has(e.to)) return;
348
+ const sources = e.from === '*' ? g.reachable.filter((s) => s !== e.to) : [e.from];
349
+ for (const from of sources) out.get(from)?.push({ ...e, id, from, writes: [...e.writes, ...g.exitWrites.get(from)] });
350
+ });
351
+ const component = componentsOf(out);
352
+ for (const [from, edges] of out) out.set(from, edges.filter((e) => component.get(from) === component.get(e.to)));
353
+ const cycles = [];
354
+ const seen = new Set();
355
+ const walk = (start, s, path, known) => {
356
+ for (const e of out.get(s)) {
357
+ const conds = [...known, ...e.when];
358
+ if (conds.some((a, i) => conds.slice(i + 1).some((b) => contradicts(a, b, isRef)))) continue;
359
+ const loop = [...path, e];
360
+ if (e.to === start) {
361
+ const key = JSON.stringify(loop.map((p) => JSON.stringify([p.from, p.id])).sort());
362
+ if (!seen.has(key)) {
363
+ seen.add(key);
364
+ // An action on the loop that writes a value its conditions read can end it, or start it: then it is a warning.
365
+ const read = new Set(loop.flatMap((p) => p.when.flatMap((c) => [c[0], ...(isRef(c[0], c[2]) ? [c[2]] : [])])));
366
+ cycles.push({ states: [start, ...loop.map((p) => p.to)], uncertain: loop.some((p) => p.writes.some((w) => read.has(w))) });
367
+ }
368
+ } else if (!path.some((p) => p.to === e.to)) {
369
+ // Once an edge writes a value, earlier guards on that value no longer constrain later guards.
370
+ walk(start, e.to, loop, conds.filter((c) => !e.writes.includes(c[0])));
371
+ }
372
+ }
373
+ };
374
+ for (const n of g.reachable) walk(n, n, [], []);
375
+ g.zeroTimeCycles = cycles.filter((c) => !c.uncertain).map((c) => c.states);
376
+ for (const c of cycles) {
377
+ const entry = { where: `${g.where}.transitions`, error: `states ${c.states.join(' -> ')} can loop with no time passing`,
378
+ hint: 'make the conditions exclusive, read a trigger, or give one transition an exit_at or a duration_ms' };
379
+ if (c.uncertain) {
380
+ warnings.push({ ...entry, error: `${entry.error}, depending on actions that write values read by its conditions`,
381
+ hint: `check it with --trace; the runtime stops a layer at ${MAX_CHANGES} changes in one instant` });
382
+ } else problems.push(entry);
383
+ }
384
+ };
@@ -0,0 +1,158 @@
1
+ import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
2
+ import type { ForwardedRef } from 'react';
3
+ import { AppState, StyleSheet, View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from 'react-native';
4
+ import { Canvas, Picture, Skia, createPicture, type SkImage } from 'react-native-skia';
5
+ import { useDerivedValue, type SharedValue } from 'react-native-reanimated';
6
+ import { assetClips, assetMarkerEvents, parseAsset, type MotionAsset, type AssetMarkerEvent } from './asset';
7
+ import { decodeAssetImages, drawAsset, prepareAssetDrawing, rebindAssetMeshShaders, type AssetImages, type DrawableAsset } from './asset-draw';
8
+ import { useMachine, type MachineHandle } from './useMachine';
9
+ import type { Pose, StateEntry } from '../templates/motion/machine';
10
+
11
+ export { parseAsset, type MotionAsset, type AssetMarkerEvent } from './asset';
12
+
13
+ let nextAssetKey = 0;
14
+
15
+ export type LoadedMotionAsset = Readonly<{
16
+ key: number;
17
+ machine: MotionAsset['machine'];
18
+ markers: MotionAsset['markers'];
19
+ drawing: DrawableAsset;
20
+ images: AssetImages;
21
+ clips: ReturnType<typeof assetClips>;
22
+ }>;
23
+
24
+ /** Prepare one file for reuse by independent player instances. Keep the result while those players are mounted. */
25
+ export function loadMotionAsset(source: string): LoadedMotionAsset {
26
+ const asset = parseAsset(source);
27
+ const images = decodeAssetImages(asset);
28
+ return {
29
+ key: nextAssetKey++,
30
+ machine: asset.machine,
31
+ markers: asset.markers,
32
+ drawing: prepareAssetDrawing(asset, images),
33
+ images,
34
+ clips: assetClips(asset),
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Prepare a file before mounting it. Skia versions with asynchronous raster decoding perform
40
+ * that work off the JS thread. Upload is opt-in and can retain textures until the file is released.
41
+ */
42
+ export async function preloadMotionAsset(
43
+ source: string | LoadedMotionAsset,
44
+ { uploadImages = false }: { uploadImages?: boolean } = {},
45
+ ): Promise<LoadedMotionAsset> {
46
+ const loaded = typeof source === 'string' ? loadMotionAsset(source) : source;
47
+ const warmed = new Map<SkImage, SkImage>();
48
+ const images: [string, SkImage][] = [];
49
+ let changed = false;
50
+ for (const [name, image] of Object.entries(loaded.images)) {
51
+ let ready = warmed.get(image);
52
+ if (!ready) {
53
+ // Neither method is available at the 3.0 peer dependency floor.
54
+ const preloadable = image as SkImage & { makeRasterImage?: () => Promise<SkImage> };
55
+ ready = await preloadable.makeRasterImage?.() ?? image;
56
+ if (uploadImages) {
57
+ const uploadable = ready as SkImage & { makeTextureImage?: () => SkImage };
58
+ try {
59
+ ready = uploadable.makeTextureImage?.() ?? ready;
60
+ } catch {
61
+ // A reduced or unsupported backend can still upload the raster image when drawn.
62
+ }
63
+ }
64
+ warmed.set(image, ready);
65
+ }
66
+ images.push([name, ready]);
67
+ changed ||= ready !== image;
68
+ }
69
+ if (!warmed.size) return loaded;
70
+ const ready = Object.fromEntries(images);
71
+ return { ...loaded, images: ready, drawing: changed ? rebindAssetMeshShaders(loaded.drawing, ready) : loaded.drawing };
72
+ }
73
+
74
+ export type MotionPlayerHandle = Pick<MachineHandle, 'set' | 'fire' | 'setOnUI' | 'readOnUI'>;
75
+
76
+ export type MotionPlayerProps = {
77
+ source: string | LoadedMotionAsset;
78
+ width?: number;
79
+ height?: number;
80
+ live?: boolean;
81
+ reduced?: boolean;
82
+ style?: StyleProp<ViewStyle>;
83
+ onMarker?: (marker: AssetMarkerEvent) => void;
84
+ };
85
+
86
+ type LoadedProps = Omit<MotionPlayerProps, 'source'> & { loaded: LoadedMotionAsset; playerRef: ForwardedRef<MotionPlayerHandle> };
87
+
88
+ function AssetPicture({ drawing, images, pose, width, height }: {
89
+ drawing: DrawableAsset;
90
+ images: AssetImages;
91
+ pose: SharedValue<Pose>;
92
+ width: number;
93
+ height: number;
94
+ }) {
95
+ const picture = useDerivedValue(() => createPicture(
96
+ (canvas) => drawAsset(canvas, drawing, pose.value.channels, width, height, images),
97
+ Skia.XYWHRect(0, 0, width, height),
98
+ ), [drawing, images, pose, width, height]);
99
+ return <Picture picture={picture} />;
100
+ }
101
+
102
+ function LoadedPlayer({ loaded, playerRef, width, height, live, reduced, style, onMarker }: LoadedProps) {
103
+ const { markers, drawing, images, clips } = loaded;
104
+ const [viewport, setViewport] = useState({ width: 0, height: 0 });
105
+ const onLayout = useCallback(({ nativeEvent }: LayoutChangeEvent) => {
106
+ const { width, height } = nativeEvent.layout;
107
+ setViewport((current) => current.width === width && current.height === height ? current : { width, height });
108
+ }, []);
109
+ const measured = viewport.width > 0 && viewport.height > 0;
110
+ const [foreground, setForeground] = useState(() => !AppState.currentState || AppState.currentState === 'active');
111
+ useEffect(() => {
112
+ const subscription = AppState.addEventListener('change', (state) => setForeground(state === 'active'));
113
+ return () => subscription.remove();
114
+ }, []);
115
+ const markerCallback = useRef(onMarker);
116
+ useEffect(() => {
117
+ markerCallback.current = onMarker;
118
+ return () => { markerCallback.current = undefined; };
119
+ }, [onMarker]);
120
+ const onStateEntries = useCallback((entries: StateEntry[]) => {
121
+ for (const marker of assetMarkerEvents(loaded, entries)) markerCallback.current?.(marker);
122
+ }, [loaded]);
123
+ const machine = useMachine(loaded.machine, clips, {
124
+ live: measured && foreground && (live ?? true),
125
+ reduced,
126
+ onStateEntries: markers?.length && onMarker ? onStateEntries : undefined,
127
+ });
128
+ useImperativeHandle(playerRef, () => ({
129
+ set: machine.set, fire: machine.fire, setOnUI: machine.setOnUI, readOnUI: machine.readOnUI,
130
+ }), [machine.set, machine.fire, machine.setOnUI, machine.readOnUI]);
131
+ const hostStyle = StyleSheet.flatten(style);
132
+ const grows = (hostStyle?.flex ?? 0) > 0 || (hostStyle?.flexGrow ?? 0) > 0;
133
+ const hasSize = (width ?? hostStyle?.width) != null || (height ?? hostStyle?.height) != null;
134
+ const defaults: ViewStyle | undefined = grows ? undefined : {
135
+ aspectRatio: drawing.artboard.width / drawing.artboard.height,
136
+ ...(hasSize ? {} : { width: '100%' }),
137
+ };
138
+ const explicitSize = {
139
+ ...(width !== undefined && { width }),
140
+ ...(height !== undefined && { height }),
141
+ };
142
+ // Measure a regular View. Early Skia v3 releases don't report Canvas onLayout on native.
143
+ return (
144
+ <View style={[defaults, style, explicitSize]} onLayout={onLayout}>
145
+ {measured && (
146
+ <Canvas style={StyleSheet.absoluteFill}>
147
+ <AssetPicture drawing={drawing} images={images} pose={machine.pose} width={viewport.width} height={viewport.height} />
148
+ </Canvas>
149
+ )}
150
+ </View>
151
+ );
152
+ }
153
+
154
+ export const MotionPlayer = forwardRef<MotionPlayerHandle, MotionPlayerProps>(function MotionPlayer({ source, ...props }, ref) {
155
+ // The inner hook owns one machine snapshot per loaded file. An updated file starts at t=0.
156
+ const loaded = useMemo(() => typeof source === 'string' ? loadMotionAsset(source) : source, [source]);
157
+ return <LoadedPlayer key={loaded.key} loaded={loaded} playerRef={ref} {...props} />;
158
+ });