@vim3d/core 0.2.3 → 0.2.4
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/README.md +7 -0
- package/compile.d.ts +6 -1
- package/compile.js +55 -51
- package/contexts.d.ts +5 -1
- package/contexts.js +45 -0
- package/esm/compile.js +57 -54
- package/esm/contexts.js +42 -0
- package/esm/evaluate.js +8 -2
- package/esm/index.js +1 -0
- package/esm/model.js +2 -1
- package/esm/storage.js +575 -0
- package/evaluate.js +8 -2
- package/index.d.ts +2 -0
- package/index.js +6 -1
- package/model.d.ts +20 -4
- package/model.js +4 -2
- package/package.json +3 -2
- package/storage.d.ts +36 -0
- package/storage.js +581 -0
package/esm/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export const name = '@vim3d/core';
|
|
2
2
|
export { compileScene } from './compile.js';
|
|
3
3
|
export { evaluateFrame } from './evaluate.js';
|
|
4
|
+
export { fromStorageGraph, hashStorageGraph, serializeStorageGraph, toStorageGraph } from './storage.js';
|
|
4
5
|
export { BUILTIN_CONTEXTS, createContextRegistry } from './registry.js';
|
package/esm/model.js
CHANGED
|
@@ -26,8 +26,9 @@ export function defaults(kind) {
|
|
|
26
26
|
Object.assign(parameters, { fovy: 45, znear: 0.1, zfar: 1000 });
|
|
27
27
|
return { parameters, up: worldUp, light: 'point', visible: true, enabled: true };
|
|
28
28
|
}
|
|
29
|
+
export const isNumberLiteral = (text) => /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text);
|
|
29
30
|
export function readNumber(text, source) {
|
|
30
|
-
if (
|
|
31
|
+
if (!isNumberLiteral(text)) {
|
|
31
32
|
fail('invalid-number', 'Expected a finite number, got ' + JSON.stringify(text), source);
|
|
32
33
|
}
|
|
33
34
|
return finite(Number(text), 'Number', source);
|
package/esm/storage.js
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
import { channelOperators } from './ch-operators.js';
|
|
2
|
+
import { validSegment } from './channels.js';
|
|
3
|
+
import { finishScene } from './compile.js';
|
|
4
|
+
import { Extensions, validateExpressionSource, validateGeometrySource, validateScalarConnectionSource, } from './contexts.js';
|
|
5
|
+
import { bindExpression } from './expression.js';
|
|
6
|
+
import { comparePaths } from './graph.js';
|
|
7
|
+
import { channelPath, objectPath, plans, positionStep, propertyEdit, worldStep, } from './model.js';
|
|
8
|
+
import { createContextRegistry } from './registry.js';
|
|
9
|
+
import { EvaluationError, fail, } from './types.js';
|
|
10
|
+
const dataProp = '/data';
|
|
11
|
+
const linksProp = '/links';
|
|
12
|
+
const inputMarker = '$';
|
|
13
|
+
const scopeOf = (path) => path.split('/')[1];
|
|
14
|
+
const ownerOf = (path) => path.slice(0, path.lastIndexOf('/'));
|
|
15
|
+
const memberOf = (path) => path.slice(path.lastIndexOf('/') + 1);
|
|
16
|
+
const storeSpan = (span) => ({ ...span, end: span.end === Infinity ? null : span.end });
|
|
17
|
+
const loadSpan = (span) => ({ ...span, end: span.end === null ? Infinity : span.end });
|
|
18
|
+
export function toStorageGraph(scene) {
|
|
19
|
+
const plan = plans.get(scene);
|
|
20
|
+
if (!plan)
|
|
21
|
+
fail('invalid-scene', 'Scene was not created by compileScene or fromStorageGraph');
|
|
22
|
+
const pending = new Map();
|
|
23
|
+
function node(path, category) {
|
|
24
|
+
const props = new Map();
|
|
25
|
+
const entry = {
|
|
26
|
+
path, category, props, inputs: new Map(), outputs: new Map(), links: [],
|
|
27
|
+
route: address => scopeOf(address) === scopeOf(path) ? address : inputMarker + address.slice(1),
|
|
28
|
+
};
|
|
29
|
+
pending.set(path, entry);
|
|
30
|
+
return entry;
|
|
31
|
+
}
|
|
32
|
+
function property(entry, name, value) {
|
|
33
|
+
entry.props.set(name, { name, value });
|
|
34
|
+
}
|
|
35
|
+
function output(entry, name, type, value = {}) {
|
|
36
|
+
property(entry, name, value);
|
|
37
|
+
entry.outputs.set(name, { name, type });
|
|
38
|
+
}
|
|
39
|
+
function expression(entry, ast) {
|
|
40
|
+
return bindExpression(ast, entry.route);
|
|
41
|
+
}
|
|
42
|
+
const sceneData = {
|
|
43
|
+
fps: scene.fps, frameCount: scene.frameCount, ranges: scene.ranges,
|
|
44
|
+
contexts: plan.extensions.registry.contexts
|
|
45
|
+
.filter(({ stage }) => stage === 'evaluate' || stage === 'output').map(({ name }) => name).sort(comparePaths),
|
|
46
|
+
events: plan.events.map(({ object, frame, command, args, source }) => ({
|
|
47
|
+
object: objectPath(object), frame, command, args, source,
|
|
48
|
+
})),
|
|
49
|
+
};
|
|
50
|
+
const settings = node('/@scene', 'scene');
|
|
51
|
+
property(settings, dataProp, sceneData);
|
|
52
|
+
for (const object of plan.objects) {
|
|
53
|
+
const path = objectPath(object);
|
|
54
|
+
const entry = node(path, object.kind);
|
|
55
|
+
const { source, kind, parent, geometry, geometrySource, pathBindings, aimBindings } = object;
|
|
56
|
+
const { parameters, ...authored } = object.authored;
|
|
57
|
+
const data = {
|
|
58
|
+
kind, source, authored, parent: parent && objectPath(parent), geometry,
|
|
59
|
+
geometrySource: geometrySource && entry.route(geometrySource),
|
|
60
|
+
paths: pathBindings.map(({ curve, position, freq, ...span }) => storeSpan({
|
|
61
|
+
...span, curve: objectPath(curve), ...(position ? { position: expression(entry, position) } : { freq }),
|
|
62
|
+
})),
|
|
63
|
+
aims: aimBindings.map(({ target, ...span }) => storeSpan({ ...span, target: objectPath(target) })),
|
|
64
|
+
};
|
|
65
|
+
property(entry, dataProp, data);
|
|
66
|
+
for (const name of Object.keys(parameters).sort(comparePaths)) {
|
|
67
|
+
const drivers = (plan.drivers.get(path + '/' + name) ?? []).map(driver => driver.kind === 'expr' ? storeSpan({ ...driver, expression: expression(entry, driver.expression) })
|
|
68
|
+
: storeSpan({ ...driver, input: entry.route(driver.input) }));
|
|
69
|
+
output(entry, name, 'number', { value: parameters[name], drivers });
|
|
70
|
+
}
|
|
71
|
+
output(entry, 'worldMatrix', 'matrix4');
|
|
72
|
+
output(entry, 'localMatrix', 'matrix4');
|
|
73
|
+
output(entry, 'snapshot', 'object');
|
|
74
|
+
}
|
|
75
|
+
for (const channel of plan.channels) {
|
|
76
|
+
const path = channelPath(channel);
|
|
77
|
+
const entry = node(path, 'channel');
|
|
78
|
+
const { table, extend, ramp, live, source, operator } = channel;
|
|
79
|
+
property(entry, dataProp, {
|
|
80
|
+
table, extend, ramp, live, source,
|
|
81
|
+
operator: operator && { type: operator.definition.type, props: Object.entries(operator.props) },
|
|
82
|
+
});
|
|
83
|
+
for (const [name, port] of [...channel.ports].sort(([a], [b]) => comparePaths(a, b))) {
|
|
84
|
+
output(entry, name, 'number', { ...port, expression: port.expression && expression(entry, port.expression) });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const edges = new Map();
|
|
88
|
+
const rootEdges = [];
|
|
89
|
+
const boundaries = new Map();
|
|
90
|
+
const addEdge = (scope, edge) => {
|
|
91
|
+
if (!edges.has(scope))
|
|
92
|
+
edges.set(scope, []);
|
|
93
|
+
edges.get(scope).push(edge);
|
|
94
|
+
};
|
|
95
|
+
function boundary(scope, kind, portName, dataType) {
|
|
96
|
+
if (!boundaries.has(scope))
|
|
97
|
+
boundaries.set(scope, new Map());
|
|
98
|
+
const ports = boundaries.get(scope);
|
|
99
|
+
const key = kind + '/' + portName;
|
|
100
|
+
const existing = ports.get(key);
|
|
101
|
+
if (existing)
|
|
102
|
+
return { name: existing.name, created: false };
|
|
103
|
+
let index = ports.size;
|
|
104
|
+
let name;
|
|
105
|
+
do
|
|
106
|
+
name = '@boundary-' + index++;
|
|
107
|
+
while (pending.has('/' + scope + '/' + name) || plan.extensions.nodes.has('/' + scope + '/' + name)
|
|
108
|
+
|| [...ports.values()].some(port => port.name === name));
|
|
109
|
+
ports.set(key, { name, type: kind, props: [{ name: 'portName', value: portName }, { name: 'dataType', value: dataType }] });
|
|
110
|
+
return { name, created: true };
|
|
111
|
+
}
|
|
112
|
+
function link(to, role, from, type) {
|
|
113
|
+
const entry = pending.get(to);
|
|
114
|
+
const scope = scopeOf(to);
|
|
115
|
+
const port = JSON.stringify(role);
|
|
116
|
+
if (ownerOf(from) === to) {
|
|
117
|
+
entry.links.push({ port, from });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
let src = { node: memberOf(ownerOf(from)), port: memberOf(from) };
|
|
121
|
+
const sourceScope = scopeOf(from);
|
|
122
|
+
if (sourceScope !== scope) {
|
|
123
|
+
const outputPort = from.slice(sourceScope.length + 2);
|
|
124
|
+
const inputPort = from.slice(1);
|
|
125
|
+
const output = boundary(sourceScope, 'graphOutput', outputPort, type);
|
|
126
|
+
const input = boundary(scope, 'graphInput', inputPort, type);
|
|
127
|
+
if (output.created)
|
|
128
|
+
addEdge(sourceScope, { src, dst: { node: output.name, port: 'value' } });
|
|
129
|
+
if (input.created)
|
|
130
|
+
rootEdges.push({ src: { node: sourceScope, port: outputPort }, dst: { node: scope, port: inputPort } });
|
|
131
|
+
src = { node: input.name, port: 'value' };
|
|
132
|
+
}
|
|
133
|
+
const previous = entry.inputs.get(port);
|
|
134
|
+
entry.inputs.set(port, { name: port, type, ...(previous && { multi: true }) });
|
|
135
|
+
addEdge(scope, { src, dst: { node: memberOf(to), port } });
|
|
136
|
+
}
|
|
137
|
+
for (const [path, extension] of [...plan.extensions.nodes].sort(([a], [b]) => comparePaths(a, b))) {
|
|
138
|
+
const entry = node(path, 'extension');
|
|
139
|
+
const { definition, source, props, drivers } = extension;
|
|
140
|
+
const expressions = [];
|
|
141
|
+
for (const [input, driver] of [...drivers].sort(([a], [b]) => comparePaths(a, b))) {
|
|
142
|
+
if (driver.kind === 'wire')
|
|
143
|
+
link(path, ['connect', input], driver.from.address, driver.from.type);
|
|
144
|
+
else {
|
|
145
|
+
expressions.push([input, expression(entry, driver.expression), driver.source]);
|
|
146
|
+
for (const from of driver.references)
|
|
147
|
+
link(path, ['expression', input], from.address, from.type);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
property(entry, dataProp, { type: definition.type, source, props: [...props], expressions });
|
|
151
|
+
for (const [name, { type }] of definition.outputs)
|
|
152
|
+
output(entry, name, type);
|
|
153
|
+
}
|
|
154
|
+
for (const [to, inputs] of [...plan.inputs].sort(([a], [b]) => comparePaths(a, b))) {
|
|
155
|
+
for (const from of [...inputs].sort(comparePaths))
|
|
156
|
+
link(ownerOf(to), ['depend', memberOf(to)], from, 'number');
|
|
157
|
+
}
|
|
158
|
+
for (const { to, input, from } of [...plan.contextWires].sort((a, b) => comparePaths(a.to, b.to) || comparePaths(a.input, b.input) || comparePaths(a.from.address, b.from.address))) {
|
|
159
|
+
link(ownerOf(to), ['wire', memberOf(to), input], from.address, from.type);
|
|
160
|
+
}
|
|
161
|
+
const types = new Map();
|
|
162
|
+
const definitions = [];
|
|
163
|
+
const scopes = new Map();
|
|
164
|
+
for (const name of ['obj', 'ch', ...sceneData.contexts])
|
|
165
|
+
scopes.set(name, []);
|
|
166
|
+
let metadata;
|
|
167
|
+
function type(entry) {
|
|
168
|
+
const { category } = entry;
|
|
169
|
+
const inputs = [...entry.inputs.values()].sort((a, b) => comparePaths(a.name, b.name));
|
|
170
|
+
const outputs = [...entry.outputs.values()].sort((a, b) => comparePaths(a.name, b.name));
|
|
171
|
+
const props = [...entry.props.keys()].sort(comparePaths).map(name => ({ name, type: 'object' }));
|
|
172
|
+
const signature = JSON.stringify([category, inputs, outputs, props]);
|
|
173
|
+
let found = types.get(signature);
|
|
174
|
+
if (!found) {
|
|
175
|
+
const name = category + '-' + definitions.length;
|
|
176
|
+
found = 'scene:' + name;
|
|
177
|
+
types.set(signature, found);
|
|
178
|
+
definitions.push({ context: 'vim3d', category: 'scene', name, inputs, outputs, props });
|
|
179
|
+
}
|
|
180
|
+
return found;
|
|
181
|
+
}
|
|
182
|
+
for (const [path, entry] of [...pending].sort(([a], [b]) => comparePaths(a, b))) {
|
|
183
|
+
if (entry.links.length)
|
|
184
|
+
property(entry, linksProp, entry.links);
|
|
185
|
+
const stored = { name: memberOf(path), type: type(entry), props: [...entry.props.values()] };
|
|
186
|
+
if (path === settings.path)
|
|
187
|
+
metadata = stored;
|
|
188
|
+
else {
|
|
189
|
+
const scope = scopeOf(path);
|
|
190
|
+
if (!scopes.has(scope))
|
|
191
|
+
scopes.set(scope, []);
|
|
192
|
+
scopes.get(scope).push(stored);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const nodes = [...scopes].sort(([a], [b]) => comparePaths(a, b)).map(([name, nodes]) => ({ name, type: 'subnet', nodes: [...nodes, ...(boundaries.get(name)?.values() ?? [])], edges: edges.get(name) ?? [] }));
|
|
196
|
+
return JSON.parse(serializeStorageGraph({ context: 'vim3d', nodes: [metadata, ...nodes], edges: rootEdges, definitions }));
|
|
197
|
+
}
|
|
198
|
+
function invalid(message) {
|
|
199
|
+
fail('invalid-storage-graph', message);
|
|
200
|
+
}
|
|
201
|
+
function propsOf(node) {
|
|
202
|
+
const props = new Map();
|
|
203
|
+
for (const prop of node.props ?? []) {
|
|
204
|
+
if (!prop.name || props.has(prop.name))
|
|
205
|
+
invalid('Invalid or duplicate property on ' + node.name);
|
|
206
|
+
props.set(prop.name, prop);
|
|
207
|
+
}
|
|
208
|
+
return props;
|
|
209
|
+
}
|
|
210
|
+
export function fromStorageGraph(graph, options = {}) {
|
|
211
|
+
try {
|
|
212
|
+
return { value: load(JSON.parse(serializeStorageGraph(graph)), options) };
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (error instanceof EvaluationError)
|
|
216
|
+
return { diagnostics: [error.diagnostic] };
|
|
217
|
+
return { diagnostics: [{ code: 'invalid-storage-graph', message: 'Invalid Vim3D scene data' }] };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function load(graph, options) {
|
|
221
|
+
if (graph.context !== 'vim3d')
|
|
222
|
+
invalid('Expected a Vim3D graph');
|
|
223
|
+
const settings = graph.nodes.find(node => node.name === '@scene');
|
|
224
|
+
if (!settings)
|
|
225
|
+
invalid('Missing @scene settings');
|
|
226
|
+
const metadata = propsOf(settings).get(dataProp)?.value;
|
|
227
|
+
const { contexts, events, fps, frameCount, ranges } = metadata;
|
|
228
|
+
if (!(fps > 0) || !Number.isFinite(fps) || (frameCount !== undefined && (!Number.isSafeInteger(frameCount) || frameCount < 0))) {
|
|
229
|
+
invalid('Invalid scene timing');
|
|
230
|
+
}
|
|
231
|
+
const registry = createContextRegistry(options.contexts?.filter(({ name }) => contexts.includes(name)));
|
|
232
|
+
for (const name of contexts) {
|
|
233
|
+
if (!registry.get(name))
|
|
234
|
+
invalid('Missing host context /' + name);
|
|
235
|
+
}
|
|
236
|
+
const extensions = new Extensions(registry);
|
|
237
|
+
const objects = new Map();
|
|
238
|
+
const channels = new Map();
|
|
239
|
+
const drivers = new Map();
|
|
240
|
+
const inputs = new Map();
|
|
241
|
+
const contextWires = [];
|
|
242
|
+
const declarations = new Map(graph.definitions.map(def => [def.category + ':' + def.name, def]));
|
|
243
|
+
const nodes = new Map();
|
|
244
|
+
const links = [];
|
|
245
|
+
const boundaryNodes = new Map();
|
|
246
|
+
const inputPorts = new Map();
|
|
247
|
+
const outputPorts = new Map();
|
|
248
|
+
for (const scope of graph.nodes) {
|
|
249
|
+
if (scope === settings)
|
|
250
|
+
continue;
|
|
251
|
+
if (!validSegment(scope.name) || scope.type !== 'subnet')
|
|
252
|
+
invalid('Expected a context subnet');
|
|
253
|
+
const prefix = '/' + scope.name + '/';
|
|
254
|
+
for (const node of scope.nodes ?? []) {
|
|
255
|
+
const path = prefix + node.name;
|
|
256
|
+
if (!validSegment(node.name) || nodes.has(path) || boundaryNodes.has(path)) {
|
|
257
|
+
invalid('Invalid node in /' + scope.name + ': ' + node.name);
|
|
258
|
+
}
|
|
259
|
+
const props = propsOf(node);
|
|
260
|
+
if (node.type === 'graphInput' || node.type === 'graphOutput') {
|
|
261
|
+
const name = props.get('portName')?.value;
|
|
262
|
+
const type = props.get('dataType')?.value;
|
|
263
|
+
const ports = node.type === 'graphInput' ? inputPorts : outputPorts;
|
|
264
|
+
if (typeof name !== 'string' || !name || typeof type !== 'string' || ports.has(prefix + name)) {
|
|
265
|
+
invalid('Invalid boundary ' + path);
|
|
266
|
+
}
|
|
267
|
+
const boundary = { kind: node.type, name, type };
|
|
268
|
+
boundaryNodes.set(path, boundary);
|
|
269
|
+
ports.set(prefix + name, boundary);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
const def = declarations.get(node.type);
|
|
273
|
+
if (!def || def.context !== 'vim3d')
|
|
274
|
+
invalid('Missing node definition for ' + path);
|
|
275
|
+
nodes.set(path, { props, def });
|
|
276
|
+
}
|
|
277
|
+
for (const { src, dst } of scope.edges ?? []) {
|
|
278
|
+
if (!validSegment(src.node) || !validSegment(dst.node))
|
|
279
|
+
invalid('Expected scope-local edge endpoints');
|
|
280
|
+
const to = prefix + dst.node;
|
|
281
|
+
const from = prefix + src.node;
|
|
282
|
+
const output = boundaryNodes.get(to);
|
|
283
|
+
const input = boundaryNodes.get(from);
|
|
284
|
+
const sourceType = input ? input.type : nodes.get(from)?.def.outputs?.find(port => port.name === src.port)?.type;
|
|
285
|
+
const destType = output ? output.type : nodes.get(to)?.def.inputs?.find(port => port.name === dst.port)?.type;
|
|
286
|
+
if (!sourceType || sourceType !== destType)
|
|
287
|
+
invalid('Mismatched edge ports in /' + scope.name);
|
|
288
|
+
if (output) {
|
|
289
|
+
if (output.kind !== 'graphOutput' || input || dst.port !== 'value' || output.source)
|
|
290
|
+
invalid('Invalid graphOutput ' + to);
|
|
291
|
+
output.source = from + '/' + src.port;
|
|
292
|
+
}
|
|
293
|
+
else if (input) {
|
|
294
|
+
if (input.kind !== 'graphInput' || src.port !== 'value')
|
|
295
|
+
invalid('Invalid graphInput ' + from);
|
|
296
|
+
links.push({ to, port: dst.port, from: inputMarker + input.name });
|
|
297
|
+
}
|
|
298
|
+
else
|
|
299
|
+
links.push({ to, port: dst.port, from: from + '/' + src.port });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
for (const { src, dst } of graph.edges) {
|
|
303
|
+
if (!validSegment(src.node) || !validSegment(dst.node) || src.node === dst.node)
|
|
304
|
+
invalid('Expected an edge between context subnets');
|
|
305
|
+
const output = outputPorts.get('/' + src.node + '/' + src.port);
|
|
306
|
+
const input = inputPorts.get('/' + dst.node + '/' + dst.port);
|
|
307
|
+
if (!input || input.source || !output?.source || output.type !== input.type)
|
|
308
|
+
invalid('Invalid subnet connection');
|
|
309
|
+
input.source = output.source;
|
|
310
|
+
}
|
|
311
|
+
function prop(path, name) {
|
|
312
|
+
return nodes.get(path)?.props.get(name)?.value;
|
|
313
|
+
}
|
|
314
|
+
function resolve(owner, path) {
|
|
315
|
+
if (path.startsWith(inputMarker)) {
|
|
316
|
+
const port = path.slice(inputMarker.length);
|
|
317
|
+
const boundary = inputPorts.get('/' + scopeOf(owner) + '/' + port);
|
|
318
|
+
if (!boundary?.source)
|
|
319
|
+
invalid('Unconnected subnet input ' + port);
|
|
320
|
+
path = boundary.source;
|
|
321
|
+
}
|
|
322
|
+
else if (scopeOf(path) !== scopeOf(owner))
|
|
323
|
+
invalid('Cross-context read requires a subnet input');
|
|
324
|
+
const target = nodes.get(ownerOf(path));
|
|
325
|
+
if (!target?.props.has(memberOf(path)) || !target.def.outputs?.some(output => output.name === memberOf(path))) {
|
|
326
|
+
invalid('Missing output property ' + path);
|
|
327
|
+
}
|
|
328
|
+
return path;
|
|
329
|
+
}
|
|
330
|
+
const reads = new Map();
|
|
331
|
+
const scalarReads = new Set();
|
|
332
|
+
const offTimeRefs = [];
|
|
333
|
+
const rejectSource = (_code, message) => invalid(message);
|
|
334
|
+
function recordRead(target, from) {
|
|
335
|
+
if (!reads.has(target))
|
|
336
|
+
reads.set(target, new Set());
|
|
337
|
+
reads.get(target).add(from);
|
|
338
|
+
}
|
|
339
|
+
function readAddress(owner, member, from, name, source) {
|
|
340
|
+
const address = resolve(owner, from);
|
|
341
|
+
const scope = scopeOf(owner);
|
|
342
|
+
const target = scope === 'ch' || scope === 'obj' ? scope : 'extension';
|
|
343
|
+
const output = sourceAt(address);
|
|
344
|
+
const ramp = output.stage === 'ch' && !!prop(ownerOf(address), dataProp)?.ramp;
|
|
345
|
+
validateExpressionSource(target, output, name, ramp, rejectSource);
|
|
346
|
+
if (name === 'chf' || name === 'cht')
|
|
347
|
+
offTimeRefs.push({ path: address, source });
|
|
348
|
+
const kind = target === 'extension' ? 'expression' : output.stage === 'audio' ? 'wire' : 'depend';
|
|
349
|
+
recordRead(JSON.stringify([owner, kind, member]), from);
|
|
350
|
+
if (name === 'ch')
|
|
351
|
+
scalarReads.add(JSON.stringify([owner, member, from]));
|
|
352
|
+
return address;
|
|
353
|
+
}
|
|
354
|
+
const ast = (owner, member, expression, source) => bindExpression(expression, (address, name) => readAddress(owner, member, address, name, source));
|
|
355
|
+
function timedInput(owner, member, driver) {
|
|
356
|
+
const address = resolve(owner, driver.input);
|
|
357
|
+
const from = sourceAt(address);
|
|
358
|
+
if (from.stage !== (driver.kind === 'register' ? 'ch' : 'obj') || from.type !== 'number') {
|
|
359
|
+
invalid('Invalid ' + driver.kind + ' source: ' + address);
|
|
360
|
+
}
|
|
361
|
+
if (driver.kind === 'register' && (driver.freq !== 1 || driver.shift !== 0 || /^(rx|ry|rz)$/.test(member))) {
|
|
362
|
+
offTimeRefs.push({ path: address, source: driver.source });
|
|
363
|
+
}
|
|
364
|
+
recordRead(JSON.stringify([owner, 'depend', member]), driver.input);
|
|
365
|
+
return address;
|
|
366
|
+
}
|
|
367
|
+
function objectAt(path) {
|
|
368
|
+
const object = objects.get(path);
|
|
369
|
+
if (!object)
|
|
370
|
+
invalid('Missing object ' + path);
|
|
371
|
+
return object;
|
|
372
|
+
}
|
|
373
|
+
function sourceAt(path) {
|
|
374
|
+
const owner = ownerOf(path), member = memberOf(path), stage = scopeOf(path);
|
|
375
|
+
if (stage === 'ch')
|
|
376
|
+
return { address: path, path, port: 'value', type: 'number', stage };
|
|
377
|
+
if (stage === 'obj') {
|
|
378
|
+
if (member === 'worldMatrix' || member === 'localMatrix' || member === 'snapshot') {
|
|
379
|
+
return { address: path, path: owner + '/@world', port: member === 'worldMatrix' ? 'value' : member,
|
|
380
|
+
type: member === 'snapshot' ? 'object' : 'matrix4', stage };
|
|
381
|
+
}
|
|
382
|
+
return { address: path, path, port: 'value', type: 'number', stage };
|
|
383
|
+
}
|
|
384
|
+
return extensions.output(path, prop(owner, dataProp).source);
|
|
385
|
+
}
|
|
386
|
+
for (const path of nodes.keys()) {
|
|
387
|
+
if (scopeOf(path) === 'obj' || scopeOf(path) === 'ch')
|
|
388
|
+
continue;
|
|
389
|
+
const data = prop(path, dataProp);
|
|
390
|
+
const node = extensions.add(path, data.type, data.source);
|
|
391
|
+
node.props = new Map(data.props);
|
|
392
|
+
}
|
|
393
|
+
for (const [path, { def }] of nodes) {
|
|
394
|
+
const context = scopeOf(path);
|
|
395
|
+
const name = memberOf(path);
|
|
396
|
+
if (context === 'obj') {
|
|
397
|
+
const data = prop(path, dataProp);
|
|
398
|
+
const parameters = Object.create(null);
|
|
399
|
+
for (const { name: param, type } of def.outputs ?? []) {
|
|
400
|
+
if (type !== 'number')
|
|
401
|
+
continue;
|
|
402
|
+
const info = prop(path, param);
|
|
403
|
+
parameters[param] = info.value;
|
|
404
|
+
if (info.drivers.length)
|
|
405
|
+
drivers.set(path + '/' + param, info.drivers.map(driver => driver.kind === 'expr'
|
|
406
|
+
? loadSpan({ ...driver, expression: ast(path, param, driver.expression, driver.source) })
|
|
407
|
+
: loadSpan({ ...driver, input: timedInput(path, param, driver) })));
|
|
408
|
+
}
|
|
409
|
+
objects.set(path, {
|
|
410
|
+
id: objects.size, name, kind: data.kind, source: data.source, authored: { ...data.authored, parameters },
|
|
411
|
+
geometry: data.geometry, geometrySource: data.geometrySource && resolve(path, data.geometrySource),
|
|
412
|
+
pathBindings: [], aimBindings: [],
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
else if (context === 'ch') {
|
|
416
|
+
const data = prop(path, dataProp);
|
|
417
|
+
const { operator, ...config } = data;
|
|
418
|
+
const definition = operator && channelOperators.find(definition => definition.type === operator.type);
|
|
419
|
+
if (operator && !definition)
|
|
420
|
+
invalid('Unknown channel operator ' + operator.type);
|
|
421
|
+
const ports = new Map();
|
|
422
|
+
for (const { name: port } of def.outputs ?? []) {
|
|
423
|
+
const descriptor = prop(path, port);
|
|
424
|
+
ports.set(port, { ...descriptor, ...(descriptor.expression && {
|
|
425
|
+
expression: ast(path, port, descriptor.expression, descriptor.source),
|
|
426
|
+
}) });
|
|
427
|
+
}
|
|
428
|
+
channels.set(path, { ...config, name, id: channels.size, ports,
|
|
429
|
+
...(operator && { operator: { definition, props: Object.fromEntries(operator.props) } }),
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
for (const { port, from } of prop(path, linksProp) ?? [])
|
|
433
|
+
links.push({ to: path, port, from });
|
|
434
|
+
}
|
|
435
|
+
for (const [path, object] of objects) {
|
|
436
|
+
const { parent, paths, aims, geometrySource } = prop(path, dataProp);
|
|
437
|
+
if (parent)
|
|
438
|
+
object.parent = objectAt(parent);
|
|
439
|
+
object.pathBindings = paths.map(({ curve, position, freq, ...span }) => loadSpan({
|
|
440
|
+
...span, curve: objectAt(curve),
|
|
441
|
+
...(position ? { position: ast(path, memberOf(positionStep(object)), position, span.source) } : { freq }),
|
|
442
|
+
}));
|
|
443
|
+
object.aimBindings = aims.map(span => loadSpan({ ...span, target: objectAt(span.target) }));
|
|
444
|
+
if (geometrySource) {
|
|
445
|
+
if (object.kind !== 'geo' || object.geometry)
|
|
446
|
+
invalid('Invalid geometry destination: ' + path);
|
|
447
|
+
validateGeometrySource(path + '/geometry', sourceAt(object.geometrySource), rejectSource);
|
|
448
|
+
recordRead(JSON.stringify([path, 'wire', memberOf(worldStep(object))]), geometrySource);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
for (const [path] of extensions.nodes) {
|
|
452
|
+
for (const [input, expression, source] of prop(path, dataProp).expressions) {
|
|
453
|
+
const references = new Map();
|
|
454
|
+
const decoded = bindExpression(expression, (value, name) => {
|
|
455
|
+
const address = readAddress(path, input, value, name, source);
|
|
456
|
+
references.set(address, sourceAt(address));
|
|
457
|
+
return address;
|
|
458
|
+
});
|
|
459
|
+
extensions.input(path + '/' + input, 'number', { kind: 'expr', expression: decoded, references: [...references.values()], source }, source);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
const linkedReads = new Map();
|
|
463
|
+
function matchRead(key, target, from) {
|
|
464
|
+
if (!reads.get(key)?.has(from))
|
|
465
|
+
invalid('Stored links disagree with reads for ' + target);
|
|
466
|
+
if (!linkedReads.has(key))
|
|
467
|
+
linkedReads.set(key, new Set());
|
|
468
|
+
linkedReads.get(key).add(from);
|
|
469
|
+
}
|
|
470
|
+
for (const { to, port, from } of links) {
|
|
471
|
+
if (!nodes.has(to))
|
|
472
|
+
invalid('Missing edge destination ' + to);
|
|
473
|
+
const [kind, member, input] = JSON.parse(port);
|
|
474
|
+
const target = to + '/' + member;
|
|
475
|
+
const address = resolve(to, from);
|
|
476
|
+
const readKey = JSON.stringify([to, kind, member]);
|
|
477
|
+
if (kind === 'depend' || kind === 'expression')
|
|
478
|
+
matchRead(readKey, target, from);
|
|
479
|
+
if (kind === 'depend') {
|
|
480
|
+
if (!inputs.has(target))
|
|
481
|
+
inputs.set(target, new Set());
|
|
482
|
+
inputs.get(target).add(address);
|
|
483
|
+
}
|
|
484
|
+
else if (kind === 'wire') {
|
|
485
|
+
const output = sourceAt(address);
|
|
486
|
+
const object = objects.get(to);
|
|
487
|
+
const channel = channels.get(to);
|
|
488
|
+
if (object && target === worldStep(object)) {
|
|
489
|
+
if (input !== 'geometry')
|
|
490
|
+
invalid('Invalid geometry wire for ' + target);
|
|
491
|
+
validateGeometrySource(to + '/geometry', output, rejectSource);
|
|
492
|
+
}
|
|
493
|
+
else if (object && target === positionStep(object)) {
|
|
494
|
+
if (output.stage !== 'audio')
|
|
495
|
+
invalid('Invalid path expression wire for ' + target);
|
|
496
|
+
}
|
|
497
|
+
else {
|
|
498
|
+
if (!(object && Object.hasOwn(object.authored.parameters, member)) && !channel?.ports.has(member)) {
|
|
499
|
+
invalid('Invalid scalar wire for ' + target);
|
|
500
|
+
}
|
|
501
|
+
validateScalarConnectionSource(target, !!channel?.operator, output, rejectSource);
|
|
502
|
+
if (!scalarReads.has(JSON.stringify([to, member, from])))
|
|
503
|
+
invalid('Stored links disagree with reads for ' + target);
|
|
504
|
+
}
|
|
505
|
+
if (output.stage !== 'ch')
|
|
506
|
+
matchRead(readKey, target, from);
|
|
507
|
+
contextWires.push({ to: target, input, from: output });
|
|
508
|
+
}
|
|
509
|
+
else if (kind === 'connect') {
|
|
510
|
+
const source = prop(to, dataProp).source;
|
|
511
|
+
const from = sourceAt(address);
|
|
512
|
+
extensions.input(target, from.type, { kind: 'wire', from }, source);
|
|
513
|
+
}
|
|
514
|
+
else if (kind !== 'expression')
|
|
515
|
+
invalid('Unknown link on ' + to);
|
|
516
|
+
}
|
|
517
|
+
for (const [key, addresses] of reads) {
|
|
518
|
+
if (linkedReads.get(key)?.size !== addresses.size) {
|
|
519
|
+
const [owner, , member] = JSON.parse(key);
|
|
520
|
+
invalid('Stored links disagree with reads for ' + owner + '/' + member);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
const loadedEvents = events.map(({ object: path, ...event }) => {
|
|
524
|
+
const object = objectAt(path);
|
|
525
|
+
const edit = propertyEdit(event.command, event.args, object, event.source);
|
|
526
|
+
if (!edit)
|
|
527
|
+
invalid('Invalid event command ' + event.command);
|
|
528
|
+
return { ...event, object, edit };
|
|
529
|
+
});
|
|
530
|
+
return finishScene({ fps, frameCount, ranges }, {
|
|
531
|
+
objects: [...objects.values()], channels: [...channels.values()], drivers, events: loadedEvents, extensions, inputs, contextWires,
|
|
532
|
+
}, offTimeRefs);
|
|
533
|
+
}
|
|
534
|
+
function json(value) {
|
|
535
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
536
|
+
return JSON.stringify(value);
|
|
537
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
538
|
+
return Object.is(value, -0) ? '-0' : JSON.stringify(value);
|
|
539
|
+
if (Array.isArray(value))
|
|
540
|
+
return '[' + value.map(json).join(',') + ']';
|
|
541
|
+
if (value && typeof value === 'object') {
|
|
542
|
+
return '{' + Object.entries(value).filter(([, value]) => value !== undefined)
|
|
543
|
+
.sort(([a], [b]) => comparePaths(a, b)).map(([key, value]) => JSON.stringify(key) + ':' + json(value)).join(',') + '}';
|
|
544
|
+
}
|
|
545
|
+
return invalid('Expected finite JSON scene data');
|
|
546
|
+
}
|
|
547
|
+
function sorted(values, key) {
|
|
548
|
+
return values && [...values].sort((a, b) => comparePaths(key(a), key(b)));
|
|
549
|
+
}
|
|
550
|
+
function sortedNodes(nodes) {
|
|
551
|
+
return sorted(nodes, node => node.name)?.map(node => ({
|
|
552
|
+
...node,
|
|
553
|
+
props: sorted(node.props, prop => prop.name),
|
|
554
|
+
nodes: sortedNodes(node.nodes),
|
|
555
|
+
edges: sorted(node.edges, json),
|
|
556
|
+
}));
|
|
557
|
+
}
|
|
558
|
+
export function serializeStorageGraph(graph) {
|
|
559
|
+
return json({
|
|
560
|
+
...graph,
|
|
561
|
+
nodes: sortedNodes(graph.nodes),
|
|
562
|
+
edges: sorted(graph.edges, json),
|
|
563
|
+
definitions: sorted(graph.definitions, def => json([def.context, def.category, def.name]))?.map(def => ({
|
|
564
|
+
...def,
|
|
565
|
+
props: sorted(def.props, prop => prop.name),
|
|
566
|
+
inputs: sorted(def.inputs, port => port.name),
|
|
567
|
+
outputs: sorted(def.outputs, port => port.name),
|
|
568
|
+
})),
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
export async function hashStorageGraph(graph) {
|
|
572
|
+
const bytes = new TextEncoder().encode(serializeStorageGraph(graph));
|
|
573
|
+
const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes);
|
|
574
|
+
return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
|
|
575
|
+
}
|
package/evaluate.js
CHANGED
|
@@ -185,8 +185,14 @@ function evaluate(scene, frame, options) {
|
|
|
185
185
|
let worldPosition;
|
|
186
186
|
if (binding) {
|
|
187
187
|
const vertices = binding.curve.geometry.vertices;
|
|
188
|
-
const
|
|
189
|
-
|
|
188
|
+
const sample = binding.position ? expr(binding.position, frame, binding.source) : binding.freq * frame;
|
|
189
|
+
const coordinate = (0, types_js_1.finite)(sample + binding.shift, 'Path vertex index', binding.source);
|
|
190
|
+
const left = Math.floor(coordinate);
|
|
191
|
+
const index = (0, math_js_1.wrap)(left, vertices.length);
|
|
192
|
+
const weight = coordinate - left;
|
|
193
|
+
const vertex = !weight || vertices.length === 1 ? vertices[index]
|
|
194
|
+
: (0, math_js_1.add)((0, math_js_1.scale)(vertices[index], 1 - weight), (0, math_js_1.scale)(vertices[(index + 1) % vertices.length], weight));
|
|
195
|
+
worldPosition = (0, math_js_1.add)((0, math_js_1.point)(worldMatrices.get(binding.curve), vertex), binding.offset);
|
|
190
196
|
}
|
|
191
197
|
else {
|
|
192
198
|
const parent = positioned.parent ? worldMatrices.get(positioned.parent) : math_js_1.identity;
|
package/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
export declare const name = "@vim3d/core";
|
|
2
2
|
export { compileScene } from './compile.js';
|
|
3
3
|
export { evaluateFrame } from './evaluate.js';
|
|
4
|
+
export { fromStorageGraph, hashStorageGraph, serializeStorageGraph, toStorageGraph } from './storage.js';
|
|
5
|
+
export type { StorageGraph } from './storage.js';
|
|
4
6
|
export { BUILTIN_CONTEXTS, createContextRegistry } from './registry.js';
|
|
5
7
|
export type { ContextDefinition, ContextRegistry, ContextStage } from './registry.js';
|
|
6
8
|
export type { BinaryOperator, Expression, MathFunction, ReferenceFunction, UnaryOperator, Variable } from './expression.js';
|
package/index.js
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createContextRegistry = exports.BUILTIN_CONTEXTS = exports.evaluateFrame = exports.compileScene = exports.name = void 0;
|
|
3
|
+
exports.createContextRegistry = exports.BUILTIN_CONTEXTS = exports.toStorageGraph = exports.serializeStorageGraph = exports.hashStorageGraph = exports.fromStorageGraph = exports.evaluateFrame = exports.compileScene = exports.name = void 0;
|
|
4
4
|
exports.name = '@vim3d/core';
|
|
5
5
|
var compile_js_1 = require("./compile.js");
|
|
6
6
|
Object.defineProperty(exports, "compileScene", { enumerable: true, get: function () { return compile_js_1.compileScene; } });
|
|
7
7
|
var evaluate_js_1 = require("./evaluate.js");
|
|
8
8
|
Object.defineProperty(exports, "evaluateFrame", { enumerable: true, get: function () { return evaluate_js_1.evaluateFrame; } });
|
|
9
|
+
var storage_js_1 = require("./storage.js");
|
|
10
|
+
Object.defineProperty(exports, "fromStorageGraph", { enumerable: true, get: function () { return storage_js_1.fromStorageGraph; } });
|
|
11
|
+
Object.defineProperty(exports, "hashStorageGraph", { enumerable: true, get: function () { return storage_js_1.hashStorageGraph; } });
|
|
12
|
+
Object.defineProperty(exports, "serializeStorageGraph", { enumerable: true, get: function () { return storage_js_1.serializeStorageGraph; } });
|
|
13
|
+
Object.defineProperty(exports, "toStorageGraph", { enumerable: true, get: function () { return storage_js_1.toStorageGraph; } });
|
|
9
14
|
var registry_js_1 = require("./registry.js");
|
|
10
15
|
Object.defineProperty(exports, "BUILTIN_CONTEXTS", { enumerable: true, get: function () { return registry_js_1.BUILTIN_CONTEXTS; } });
|
|
11
16
|
Object.defineProperty(exports, "createContextRegistry", { enumerable: true, get: function () { return registry_js_1.createContextRegistry; } });
|