@vim3d/core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/contexts.js ADDED
@@ -0,0 +1,310 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Extensions = void 0;
4
+ exports.checkAudioFrame = checkAudioFrame;
5
+ exports.createContextEvaluation = createContextEvaluation;
6
+ const channels_js_1 = require("./channels.js");
7
+ const graph_js_1 = require("./graph.js");
8
+ const expression_js_1 = require("./expression.js");
9
+ const registry_js_1 = require("./registry.js");
10
+ const types_js_1 = require("./types.js");
11
+ const nodeType = /^[a-zA-Z][a-zA-Z0-9_-]*:[a-zA-Z][a-zA-Z0-9_-]*$/;
12
+ const propTypes = new Set(['string', 'number', 'boolean', 'object']);
13
+ const portTypes = new Set([...propTypes, 'vector3', 'matrix4']);
14
+ function isRecord(value) {
15
+ return value !== null && typeof value === 'object' &&
16
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
17
+ }
18
+ function matches(value, type) {
19
+ if (type === 'object')
20
+ return isRecord(value) || Array.isArray(value);
21
+ if (type === 'number')
22
+ return typeof value === 'number' && Number.isFinite(value);
23
+ if (type === 'vector3' || type === 'matrix4') {
24
+ return Array.isArray(value) && value.length === (type === 'vector3' ? 3 : 16) &&
25
+ Array.from(value).every(item => typeof item === 'number' && Number.isFinite(item));
26
+ }
27
+ return typeof value === type;
28
+ }
29
+ function copyValue(value, invalid, seen = new Set()) {
30
+ if (value === null)
31
+ return null;
32
+ if (typeof value === 'string' || typeof value === 'boolean' ||
33
+ (typeof value === 'number' && Number.isFinite(value)))
34
+ return value;
35
+ if ((!Array.isArray(value) && !isRecord(value)) || seen.has(value))
36
+ return invalid();
37
+ seen.add(value);
38
+ const copy = Array.isArray(value) ? Array.from(value, item => copyValue(item, invalid, seen))
39
+ : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyValue(item, invalid, seen)]));
40
+ seen.delete(value);
41
+ return (0, types_js_1.freeze)(copy);
42
+ }
43
+ function definitions(entries, types, kind, owner) {
44
+ if (!Array.isArray(entries))
45
+ (0, types_js_1.fail)('invalid-extension-definition', 'Expected ' + kind + ' definitions for ' + owner);
46
+ const map = new Map();
47
+ for (const entry of entries) {
48
+ if (!entry || typeof entry.name !== 'string' || !(0, channels_js_1.validSegment)(entry.name) || !types.has(entry.type) || map.has(entry.name)) {
49
+ (0, types_js_1.fail)('invalid-extension-definition', 'Invalid or duplicate ' + kind + ' on ' + owner + ': ' + entry?.name);
50
+ }
51
+ map.set(entry.name, { ...entry });
52
+ }
53
+ return map;
54
+ }
55
+ class Extensions {
56
+ registry;
57
+ types = new Map();
58
+ nodes = new Map();
59
+ constructor(registry) {
60
+ this.registry = registry;
61
+ for (const context of registry.contexts) {
62
+ const { name, stage, nodeTypes } = context;
63
+ if (stage === 'obj' || stage === 'ch' || stage === 'reserved')
64
+ continue;
65
+ const types = new Map();
66
+ for (const definition of nodeTypes) {
67
+ const { type, evaluate } = definition;
68
+ if (!nodeType.test(type) || typeof evaluate !== 'function')
69
+ (0, types_js_1.fail)('invalid-extension-definition', 'Invalid node type: ' + type);
70
+ if (types.has(type))
71
+ (0, types_js_1.fail)('duplicate-extension-type', 'Duplicate node type in /' + name + ': ' + type);
72
+ const owner = '/' + name + ' ' + type;
73
+ const inputs = definitions(definition.inputs, portTypes, 'input', owner);
74
+ const outputs = definitions(definition.outputs, portTypes, 'output', owner);
75
+ const props = definitions(definition.props, propTypes, 'prop', owner);
76
+ for (const [key, prop] of props) {
77
+ const invalid = () => (0, types_js_1.fail)('invalid-extension-definition', 'Invalid prop definition on ' + owner + ': ' + key);
78
+ if (prop.required !== undefined && typeof prop.required !== 'boolean')
79
+ invalid();
80
+ if (prop.default !== undefined) {
81
+ if (!matches(prop.default, prop.type))
82
+ invalid();
83
+ props.set(key, { ...prop, default: copyValue(prop.default, invalid) });
84
+ }
85
+ }
86
+ types.set(type, { type, inputs, outputs, props, evaluate });
87
+ }
88
+ this.types.set(name, types);
89
+ }
90
+ }
91
+ add(path, type, source) {
92
+ const [root, context, name, ...extra] = path.split('/');
93
+ if (root || !context || !(0, channels_js_1.validSegment)(name) || extra.length)
94
+ (0, types_js_1.fail)('invalid-path', 'Expected an extension node path: ' + path, source);
95
+ const registered = this.registry.get(context);
96
+ if (!registered)
97
+ (0, types_js_1.fail)('unknown-extension-context', 'Unknown extension context: /' + context, source);
98
+ const definition = this.types.get(context)?.get(type);
99
+ if (!definition)
100
+ (0, types_js_1.fail)('unknown-extension-type', 'Unknown node type in /' + context + ': ' + type, source);
101
+ if (this.nodes.has(path))
102
+ (0, types_js_1.fail)('duplicate-name', 'Name is already used: ' + path, source);
103
+ const props = new Map();
104
+ for (const [key, def] of definition.props)
105
+ if (def.default !== undefined)
106
+ props.set(key, def.default);
107
+ const node = { path, context, stage: registered.stage, definition, source, props, drivers: new Map() };
108
+ this.nodes.set(path, node);
109
+ return node;
110
+ }
111
+ property(address, args, text, source) {
112
+ const { node, key } = this.member(address, source);
113
+ const def = node.definition.props.get(key);
114
+ if (!def)
115
+ (0, types_js_1.fail)('unknown-extension-prop', 'Unknown prop: ' + address, source);
116
+ const invalid = () => (0, types_js_1.fail)('invalid-extension-prop', 'Expected ' + def.type + ' for ' + address, source);
117
+ let value = args[0];
118
+ if (def.type === 'object') {
119
+ const raw = text?.trimEnd().match(/^[ \t:]*(?:set|"set")[ \t]+(?:"[^"]*"|[^ \t]+)[ \t]+(.*)$/)?.[1];
120
+ const literal = raw?.match(/^(?:"(?:\\.|[^"\\])*"|[^"#])*/)?.[0];
121
+ try {
122
+ value = JSON.parse(literal);
123
+ }
124
+ catch {
125
+ invalid();
126
+ }
127
+ }
128
+ else {
129
+ if (args.length !== 1)
130
+ (0, types_js_1.fail)('invalid-operands', 'Expected one value for ' + address, source);
131
+ if (def.type === 'number')
132
+ value = args[0].trim() === '' ? NaN : Number(args[0]);
133
+ if (def.type === 'boolean')
134
+ value = args[0] === 'true' ? true : args[0] === 'false' ? false : undefined;
135
+ }
136
+ if (!matches(value, def.type))
137
+ invalid();
138
+ node.props.set(key, copyValue(value, invalid));
139
+ }
140
+ input(address, type, driver, source) {
141
+ const { node, key } = this.member(address, source);
142
+ const port = node.definition.inputs.get(key);
143
+ if (!port)
144
+ (0, types_js_1.fail)('unknown-extension-port', 'Unknown input port: ' + address, source);
145
+ if (port.type !== type)
146
+ (0, types_js_1.fail)('extension-port-type', 'Expected ' + port.type + ' at ' + address + ', got ' + type, source);
147
+ for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
148
+ if (!(0, registry_js_1.allowedSource)(node.stage, from.stage))
149
+ (0, types_js_1.fail)('extension-stage', address + ' cannot read ' + from.address, source);
150
+ }
151
+ if (node.drivers.has(key))
152
+ (0, types_js_1.fail)('overlapping-drivers', 'Input already has a driver: ' + address, source);
153
+ node.drivers.set(key, driver);
154
+ }
155
+ output(address, source) {
156
+ const { node, key } = this.member(address, source);
157
+ if (node.stage === 'output')
158
+ (0, types_js_1.fail)('extension-stage', 'Cannot read an output-stage node: ' + node.path, source);
159
+ const port = node.definition.outputs.get(key);
160
+ if (!port)
161
+ (0, types_js_1.fail)('unknown-extension-port', 'Unknown output port: ' + address, source);
162
+ return { address, path: node.path, port: key, type: port.type, stage: node.stage };
163
+ }
164
+ member(address, source) {
165
+ const [root, context, name, key, ...extra] = address.split('/');
166
+ if (root || !context || !name || !key || extra.length)
167
+ (0, types_js_1.fail)('invalid-path', 'Expected an extension member path: ' + address, source);
168
+ if (!this.registry.get(context))
169
+ (0, types_js_1.fail)('unknown-extension-context', 'Unknown extension context: /' + context, source);
170
+ const path = '/' + context + '/' + name;
171
+ const node = this.nodes.get(path);
172
+ if (!node)
173
+ (0, types_js_1.fail)('missing-target', 'Unknown extension node: ' + path, source);
174
+ return { node, key };
175
+ }
176
+ addToGraph(graph) {
177
+ for (const node of this.nodes.values()) {
178
+ const { definition, path, context, source } = node;
179
+ for (const [name, prop] of definition.props) {
180
+ if (prop.required && !node.props.has(name))
181
+ (0, types_js_1.fail)('missing-extension-prop', 'Missing required prop: ' + path + '/' + name, source);
182
+ }
183
+ const props = [...node.props.keys()].sort(graph_js_1.comparePaths).map(name => ({
184
+ name, type: definition.props.get(name).type, value: node.props.get(name),
185
+ }));
186
+ for (const input of [...node.drivers.keys()].sort(graph_js_1.comparePaths)) {
187
+ const driver = node.drivers.get(input);
188
+ if (driver.kind === 'expr') {
189
+ props.push({ name: 'expr/' + input, type: 'object', value: driver.expression });
190
+ }
191
+ }
192
+ graph.addNode(path, { context, type: definition.type, props,
193
+ inputs: [...definition.inputs.values()], outputs: [...definition.outputs.values()] }, source);
194
+ }
195
+ for (const { path, drivers } of this.nodes.values()) {
196
+ for (const [input, driver] of drivers) {
197
+ for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
198
+ graph.expose(from.path, { name: from.port, type: from.type });
199
+ graph.wire(path, input, from.path, from.port);
200
+ }
201
+ }
202
+ }
203
+ }
204
+ }
205
+ exports.Extensions = Extensions;
206
+ function checkAudioFrame(path, sampleFrame, frame) {
207
+ if (Math.abs(sampleFrame - frame) > 1e-9) {
208
+ (0, types_js_1.fail)('off-time-audio-reference', 'Audio features are available only at the evaluated frame: ' + path);
209
+ }
210
+ }
211
+ function createContextEvaluation(extensions, order, frame, time, fps, frameCount, options, readBuiltIn) {
212
+ const used = new Set([...extensions.nodes.values()].map(node => node.context));
213
+ const contextNames = extensions.registry.contexts.filter(({ stage, name }) => stage === 'evaluate' || stage === 'output' || used.has(name)).map(({ name }) => name).sort(graph_js_1.comparePaths);
214
+ let base;
215
+ let objects = new Map();
216
+ const values = new Map();
217
+ const snapshots = new Map();
218
+ const sorted = [...extensions.nodes.keys()].sort(graph_js_1.comparePaths);
219
+ const read = (path, sampleFrame) => {
220
+ if (path.startsWith('/ch/'))
221
+ return readBuiltIn(path, sampleFrame);
222
+ if (path.startsWith('/obj/')) {
223
+ const end = path.lastIndexOf('/');
224
+ const object = objects.get(path.slice(0, end));
225
+ const key = path.slice(end + 1);
226
+ if (key === 'snapshot')
227
+ return copyValue(object, () => (0, types_js_1.fail)('invalid-extension-input', 'Invalid object snapshot: ' + path));
228
+ if (key === 'worldMatrix' || key === 'localMatrix')
229
+ return object[key];
230
+ return object.parameters[key];
231
+ }
232
+ if (path.startsWith('/audio/'))
233
+ checkAudioFrame(path, sampleFrame, frame);
234
+ return values.get(path);
235
+ };
236
+ const snapshot = () => {
237
+ if (!contextNames.length)
238
+ return base;
239
+ const contexts = Object.fromEntries(contextNames.map(name => [name, []]));
240
+ for (const path of sorted) {
241
+ const node = snapshots.get(path);
242
+ if (node)
243
+ contexts[node.context].push(node);
244
+ }
245
+ return (0, types_js_1.freeze)({ ...base, contexts });
246
+ };
247
+ function run(stage) {
248
+ const inputSnapshot = stage === 'output' ? snapshot() : undefined;
249
+ for (const path of order) {
250
+ const node = extensions.nodes.get(path);
251
+ if (!node || node.stage !== stage)
252
+ continue;
253
+ const { definition, source, context } = node;
254
+ const inputs = (0, types_js_1.freeze)(Object.fromEntries([...node.drivers].map(([key, driver]) => [
255
+ key, driver.kind === 'wire' ? read(driver.from.address, frame) : (0, expression_js_1.evaluateExpression)(driver.expression, {
256
+ frame, fps, frameCount, source: driver.source, read: (address, sampleFrame) => read(address, sampleFrame),
257
+ }),
258
+ ])));
259
+ const props = (0, types_js_1.freeze)(Object.fromEntries(node.props));
260
+ const evaluate = definition.evaluate;
261
+ const audio = options.audio;
262
+ const name = path.slice('/audio/'.length);
263
+ const data = stage === 'audio' && audio
264
+ ? Object.hasOwn(audio, path) ? audio[path] : Object.hasOwn(audio, name) ? audio[name] : undefined
265
+ : undefined;
266
+ const ctx = (0, types_js_1.freeze)({ path, frame, time, fps, inputs, props, ...(inputSnapshot && { snapshot: inputSnapshot }) });
267
+ let result;
268
+ try {
269
+ result = stage === 'audio' ? evaluate(ctx, data) : evaluate(ctx);
270
+ }
271
+ catch (error) {
272
+ if (error instanceof types_js_1.EvaluationError || (stage !== 'evaluate' && stage !== 'output'))
273
+ throw error;
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ (0, types_js_1.fail)('plugin-error', `${path}: ${message}`, source);
276
+ }
277
+ const returned = result === undefined ? {} : result;
278
+ if (!isRecord(returned))
279
+ (0, types_js_1.fail)('invalid-extension-output', 'Expected an output record from ' + path, source);
280
+ for (const name of Object.keys(returned)) {
281
+ if (!definition.outputs.has(name))
282
+ (0, types_js_1.fail)('invalid-extension-output', 'Undeclared output: ' + path + '/' + name, source);
283
+ }
284
+ const outputs = Object.fromEntries([...definition.outputs].map(([name, { type }]) => {
285
+ const address = path + '/' + name;
286
+ const value = Object.hasOwn(returned, name) ? returned[name] : undefined;
287
+ const invalid = () => (0, types_js_1.fail)('invalid-extension-output', 'Expected ' + type + ' output at ' + address, source);
288
+ if (type === 'number' && typeof value === 'number' && !Number.isFinite(value)) {
289
+ (0, types_js_1.fail)('non-finite', address + ' must be finite', source);
290
+ }
291
+ if (!matches(value, type))
292
+ invalid();
293
+ const output = copyValue(value, invalid);
294
+ values.set(address, output);
295
+ return [name, output];
296
+ }));
297
+ snapshots.set(path, (0, types_js_1.freeze)({ path, context, type: definition.type, stage, props, inputs, outputs }));
298
+ }
299
+ }
300
+ return {
301
+ run, read,
302
+ finish(snapshotBase) {
303
+ base = snapshotBase;
304
+ objects = new Map(base.objects.map(object => [object.path, object]));
305
+ run('evaluate');
306
+ run('output');
307
+ return snapshot();
308
+ },
309
+ };
310
+ }