@vim3d/core 0.2.0 → 0.2.2

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/compile.js CHANGED
@@ -3,8 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.compileScene = compileScene;
4
4
  const parser_1 = require("@vim3d/parser");
5
5
  const channels_js_1 = require("./channels.js");
6
+ const ch_operators_js_1 = require("./ch-operators.js");
7
+ const contexts_js_1 = require("./contexts.js");
6
8
  const expression_js_1 = require("./expression.js");
7
9
  const graph_js_1 = require("./graph.js");
10
+ const registry_js_1 = require("./registry.js");
11
+ const ramp_js_1 = require("./ramp.js");
8
12
  const model_js_1 = require("./model.js");
9
13
  const types_js_1 = require("./types.js");
10
14
  const aliases = {
@@ -13,8 +17,11 @@ const aliases = {
13
17
  };
14
18
  const primitives = new Set(['cube', 'grid', 'sphere', 'ellipse', 'ellipseFace', 'circle', 'circleFace', 'ring']);
15
19
  const prefixes = { geo: 'geo', curve: 'curve', null: 'null', camera: 'cam', light: 'light', channel: 'ch' };
16
- const deferred = new Set(['parent', 'expr', 'register', 'ref', 'path', 'lookat', 'children']);
20
+ const deferred = new Set(['parent', 'expr', 'register', 'ref', 'path', 'lookat', 'children', 'connect', 'set', 'range']);
17
21
  const isChannel = (node) => 'ports' in node;
22
+ const isObject = (node) => 'authored' in node;
23
+ const isExtension = (node) => 'definition' in node;
24
+ const isBuiltInPath = (path) => /^\/(?:obj|ch)\//.test(path);
18
25
  const commandOf = (text) => Object.hasOwn(aliases, text) ? aliases[text] : text;
19
26
  const location = ({ file, line }) => ({ file, line });
20
27
  const prop = (name, value) => ({ name, type: typeof value, value });
@@ -74,7 +81,8 @@ function compileScene(source, options = {}) {
74
81
  return data instanceof Uint8Array ? decoder.decode(data) : data ?? null;
75
82
  },
76
83
  expandDirectives: true,
77
- reservedCommands: ['expr', 'parent'],
84
+ reservedCommands: ['expr', 'parent', 'range'],
85
+ preserveText: true,
78
86
  });
79
87
  if (expanded.problems.length)
80
88
  return { diagnostics: expanded.problems.map(problem => ({
@@ -89,6 +97,8 @@ function compileScene(source, options = {}) {
89
97
  }
90
98
  }
91
99
  function compile(lines, root, fps, options) {
100
+ const registry = (0, registry_js_1.createContextRegistry)(options.contexts);
101
+ const extensions = new contexts_js_1.Extensions(registry);
92
102
  const objects = [];
93
103
  const channels = [];
94
104
  const objNames = new Map();
@@ -99,6 +109,26 @@ function compile(lines, root, fps, options) {
99
109
  const pending = [];
100
110
  const timed = [];
101
111
  let nextId = 0;
112
+ for (const [name, portNames] of Object.entries(options.liveChannels ?? {})) {
113
+ if (!(0, channels_js_1.validSegment)(name))
114
+ (0, types_js_1.fail)('invalid-live-channel', 'Invalid live channel name: ' + name, root);
115
+ if (!Array.isArray(portNames) || !portNames.length) {
116
+ (0, types_js_1.fail)('invalid-live-channel', 'Live channel must declare at least one port: ' + name, root);
117
+ }
118
+ const ports = new Map();
119
+ for (const portName of portNames) {
120
+ if (typeof portName !== 'string' || !(0, channels_js_1.validSegment)(portName)) {
121
+ (0, types_js_1.fail)('invalid-live-channel', 'Invalid live channel port name: ' + String(portName), root);
122
+ }
123
+ if (ports.has(portName)) {
124
+ (0, types_js_1.fail)('invalid-live-channel', 'Duplicate live channel port: /ch/' + name + '/' + portName, root);
125
+ }
126
+ ports.set(portName, { live: true, source: root });
127
+ }
128
+ const channel = { id: nextId++, name, source: root, live: true, ports };
129
+ channels.push(channel);
130
+ chNames.set(name, channel);
131
+ }
102
132
  function nextName(type, names) {
103
133
  let n = counters.get(type) ?? 0;
104
134
  let name;
@@ -126,12 +156,14 @@ function compile(lines, root, fps, options) {
126
156
  return node;
127
157
  }
128
158
  const getObject = (name, source) => lookup(name, 'obj', source);
129
- const channelOutput = (path, source) => {
159
+ const channelOutput = (path, source, ramp = false) => {
130
160
  const parts = path.split('/');
131
161
  if (parts[0] || parts[1] !== 'ch' || (parts.length !== 3 && parts.length !== 4)) {
132
162
  (0, types_js_1.fail)('invalid-path', 'Expected a channel output path: ' + path, source);
133
163
  }
134
164
  const node = lookup(parts[2], 'ch', source);
165
+ if (ramp && !node.ramp)
166
+ (0, types_js_1.fail)('invalid-ramp', 'chramp requires a ch:ramp node: ' + path, source);
135
167
  if (parts.length === 3 && (node.ports.size !== 1 || !node.ports.has('value'))) {
136
168
  (0, types_js_1.fail)('ambiguous-channel', 'Channel shorthand requires a sole value port: ' + path, source);
137
169
  }
@@ -140,6 +172,14 @@ function compile(lines, root, fps, options) {
140
172
  (0, types_js_1.fail)('missing-target', 'Unknown channel port: ' + path, source);
141
173
  return (0, model_js_1.channelPath)(node) + '/' + name;
142
174
  };
175
+ const channelInput = (path, source) => {
176
+ const explicit = /^\/ch\/([^/]+)\/input\/value$/.exec(path);
177
+ if (!explicit)
178
+ return channelOutput(path, source);
179
+ if (!chNames.get(explicit[1])?.operator)
180
+ (0, types_js_1.fail)('missing-target', 'Unknown operator input: ' + path, source);
181
+ return channelOutput('/ch/' + explicit[1] + '/value', source);
182
+ };
143
183
  const scalar = (node, param, source) => {
144
184
  if (!Object.hasOwn(node.authored.parameters, param)) {
145
185
  (0, types_js_1.fail)('unsupported-parameter', 'Unsupported parameter: ' + (0, model_js_1.objectPath)(node) + '/' + param, source);
@@ -152,6 +192,30 @@ function compile(lines, root, fps, options) {
152
192
  (0, types_js_1.fail)('invalid-path', 'Expected an object parameter path: ' + path, source);
153
193
  return scalar(getObject(name, source), param, source);
154
194
  };
195
+ const extensionAddress = (path, source) => {
196
+ if (!path?.startsWith('/'))
197
+ (0, types_js_1.fail)('invalid-path', 'Expected an absolute path: ' + path, source);
198
+ return normalizePath(path, '/', source);
199
+ };
200
+ const extensionSource = (address, source) => {
201
+ if (address.startsWith('/ch/')) {
202
+ const path = channelOutput(address, source);
203
+ return { address: path, path, type: 'number', port: 'value', stage: 'ch' };
204
+ }
205
+ if (address.startsWith('/obj/')) {
206
+ const [, , name, member, ...extra] = address.split('/');
207
+ if (!member || extra.length)
208
+ (0, types_js_1.fail)('invalid-path', 'Expected an object output path: ' + address, source);
209
+ const object = getObject(name, source);
210
+ if (member === 'worldMatrix' || member === 'localMatrix' || member === 'snapshot') {
211
+ return { address, path: (0, model_js_1.worldStep)(object), port: member === 'worldMatrix' ? 'value' : member,
212
+ type: member === 'snapshot' ? 'object' : 'matrix4', stage: 'obj' };
213
+ }
214
+ const path = scalar(object, member, source);
215
+ return { address: path, path, type: 'number', port: 'value', stage: 'obj' };
216
+ }
217
+ return extensions.output(address, source);
218
+ };
155
219
  let current = addObject('camera', root, 'Cam0');
156
220
  let viewCamera;
157
221
  let backgroundColor;
@@ -171,6 +235,28 @@ function compile(lines, root, fps, options) {
171
235
  else if (curve && command !== 'end') {
172
236
  (0, types_js_1.fail)('invalid-curve', 'Expected a curve vertex or end', source);
173
237
  }
238
+ else if (command === 'node') {
239
+ (0, model_js_1.checkArity)(command, args, [2], source);
240
+ const path = extensionAddress(args[0], source);
241
+ const definition = path.startsWith('/ch/') ? ch_operators_js_1.channelOperators.find(operator => operator.type === args[1]) : undefined;
242
+ if (path.startsWith('/ch/') && (args[1] === 'ch:ramp' || definition)) {
243
+ const [, , name, ...extra] = path.split('/');
244
+ if (!(0, channels_js_1.validSegment)(name) || extra.length)
245
+ (0, types_js_1.fail)('invalid-path', 'Expected a channel node path: ' + path, source);
246
+ if (chNames.has(name))
247
+ (0, types_js_1.fail)('duplicate-name', 'Name is already used: ' + path, source);
248
+ const channel = { id: nextId++, name, source, ports: new Map([['value', { source }]]) };
249
+ if (definition)
250
+ channel.operator = { definition, props: Object.assign(Object.create(null), Object.fromEntries(definition.props.flatMap(p => p.default === undefined ? [] : [[p.name, p.default]]))) };
251
+ else
252
+ channel.ramp = [];
253
+ chNames.set(name, channel);
254
+ channels.push(channel);
255
+ current = channel;
256
+ }
257
+ else
258
+ current = extensions.add(path, args[1], source);
259
+ }
174
260
  else if (command === 'begin') {
175
261
  (0, model_js_1.checkArity)(command, args, [0, 1], source);
176
262
  if (args.length && args[0] !== 'draw')
@@ -214,13 +300,16 @@ function compile(lines, root, fps, options) {
214
300
  }
215
301
  else if (command === 'select') {
216
302
  (0, model_js_1.checkArity)(command, args, [1], source);
217
- current = lookup(args[0], 'either', source);
303
+ const address = args[0].startsWith('/') && !isBuiltInPath(args[0]) ? extensionAddress(args[0], source) : args[0];
304
+ current = extensions.nodes.get(address) ?? lookup(args[0], 'either', source);
218
305
  }
219
306
  else if (command === 'name') {
220
307
  (0, model_js_1.checkArity)(command, args, [1], source);
221
308
  const [name] = args;
222
309
  if (!(0, channels_js_1.validSegment)(name))
223
310
  (0, types_js_1.fail)('invalid-name', 'Invalid name: ' + name, source);
311
+ if (isExtension(current))
312
+ (0, types_js_1.fail)('invalid-subject', 'name requires an object or channel', source);
224
313
  if (isChannel(current))
225
314
  rename(chNames, current, name, source);
226
315
  else
@@ -265,10 +354,10 @@ function compile(lines, root, fps, options) {
265
354
  timed.push({ frame, source, command: eventCommand, args: values, objectCount: nextId });
266
355
  }
267
356
  else if (deferred.has(command)) {
268
- pending.push({ command, args, source, current });
357
+ pending.push({ command, args, source, current, text: line.text });
269
358
  }
270
359
  else if (model_js_1.editCommands.has(command)) {
271
- if (isChannel(current))
360
+ if (!isObject(current))
272
361
  (0, types_js_1.fail)('invalid-subject', command + ' requires an object', source);
273
362
  (0, model_js_1.propertyEdit)(command, args, current, source)(current.authored);
274
363
  }
@@ -285,12 +374,15 @@ function compile(lines, root, fps, options) {
285
374
  child.parent = args[1] === '/obj' ? undefined : getObject(args[1], source);
286
375
  }
287
376
  const graph = new graph_js_1.GraphBuilder();
377
+ const ranges = Object.create(null);
288
378
  const expressionPorts = new Map();
289
379
  for (const channel of channels) {
290
380
  for (const [name, port] of channel.ports)
291
381
  expressionPorts.set((0, model_js_1.channelPath)(channel) + '/' + name, { node: channel, name, port });
292
382
  }
293
383
  const inputs = new Map();
384
+ const offTimeRefs = [];
385
+ const contextWires = [];
294
386
  const depend = (path, on) => {
295
387
  if (!inputs.has(path))
296
388
  inputs.set(path, new Set());
@@ -298,37 +390,180 @@ function compile(lines, root, fps, options) {
298
390
  };
299
391
  const bind = (text, path, source) => (0, expression_js_1.bindExpression)((0, expression_js_1.parseExpression)(text, source), (ref, name) => {
300
392
  const address = normalizePath(ref, path.slice(0, path.lastIndexOf('/')), source);
393
+ if (name === 'chramp' && !address.startsWith('/ch/'))
394
+ (0, types_js_1.fail)('invalid-ramp', 'chramp requires a ch:ramp node: ' + address, source);
395
+ const targetStage = path.startsWith('/ch/') ? 'ch' : 'obj';
396
+ if (!isBuiltInPath(address) && registry.get(address.split('/')[1])) {
397
+ const from = extensionSource(address, source);
398
+ if (!(0, registry_js_1.allowedSource)(targetStage, from.stage)) {
399
+ (0, types_js_1.fail)('extension-stage', 'Built-in nodes cannot read ' + address, source);
400
+ }
401
+ if (from.stage !== 'audio' || name !== 'ch') {
402
+ (0, types_js_1.fail)('off-time-extension-reference', 'Only ch() can read built-in audio scalars: ' + address, source);
403
+ }
404
+ if (from.type !== 'number')
405
+ (0, types_js_1.fail)('extension-port-type', 'Expected a number at ' + from.address, source);
406
+ if (!contextWires.some(wire => wire.to === path && wire.from.address === from.address)) {
407
+ contextWires.push({ to: path, input: from.address, from });
408
+ }
409
+ return from.address;
410
+ }
301
411
  if (address.startsWith('/obj/')) {
302
412
  if (path.startsWith('/ch/'))
303
413
  (0, types_js_1.fail)('channel-object-reference', 'Channel expressions cannot read object parameters: ' + address, source);
304
414
  if (name !== 'ch')
305
415
  (0, types_js_1.fail)('off-time-object-reference', name + ' requires a channel: ' + address, source);
306
416
  }
307
- const input = address.startsWith('/ch/') ? channelOutput(address, source) : objectScalar(address, source);
417
+ const input = address.startsWith('/ch/') ? channelOutput(address, source, name === 'chramp') : objectScalar(address, source);
418
+ if (name === 'chf' || name === 'cht')
419
+ offTimeRefs.push({ path: input, source });
308
420
  depend(path, input);
309
421
  return input;
310
422
  });
311
- for (const { command, args, source, current } of pending) {
423
+ const driveScalar = (path, expression, source) => {
424
+ if (path.startsWith('/ch/')) {
425
+ const { node, port } = expressionPorts.get(path);
426
+ if (node.ramp || port.samples || port.expression || port.live)
427
+ (0, types_js_1.fail)('overlapping-drivers', 'Channel already has a driver: ' + path, source);
428
+ port.expression = expression;
429
+ port.source = source;
430
+ }
431
+ else
432
+ addDriver(path, { kind: 'expr', expression, ...range([], 0, source) });
433
+ };
434
+ for (const { command, args, source, current, text: lineText } of pending) {
312
435
  if (command === 'parent')
313
436
  continue;
314
437
  const numberAt = (i, fallback) => args[i] === undefined ? fallback : (0, model_js_1.readNumber)(args[i], source);
315
- if (command === 'expr') {
438
+ if (command === 'range') {
439
+ (0, model_js_1.checkArity)(command, args, [3, 4], source);
440
+ const address = extensionAddress(args[0], source);
441
+ let path;
442
+ if (address.startsWith('/ch/')) {
443
+ if (address.endsWith('/input/value')) {
444
+ channelInput(address, source);
445
+ path = address;
446
+ }
447
+ else
448
+ path = channelOutput(address, source);
449
+ }
450
+ else if (address.startsWith('/obj/'))
451
+ path = objectScalar(address, source);
452
+ else
453
+ path = extensions.numericPort(address, source);
454
+ const min = (0, model_js_1.readNumber)(args[1], source), max = (0, model_js_1.readNumber)(args[2], source);
455
+ const mode = args[3] ?? 'clamp';
456
+ if (min > max || (mode !== 'clamp' && mode !== 'error')) {
457
+ (0, types_js_1.fail)('invalid-range', 'Expected MIN <= MAX and mode clamp or error', source);
458
+ }
459
+ if (ranges[path])
460
+ (0, types_js_1.fail)('overlapping-ranges', 'Range already declared for ' + path, source);
461
+ ranges[path] = { min, max, mode, source };
462
+ }
463
+ else if (command === 'set') {
464
+ const [target] = args;
465
+ if (!target)
466
+ (0, types_js_1.fail)('invalid-operands', 'Expected set KEY VALUE', source);
467
+ if (!target.startsWith('/') && !isExtension(current) && !isChannel(current)) {
468
+ (0, types_js_1.fail)('invalid-subject', 'set requires a context node', source);
469
+ }
470
+ const address = target.startsWith('/') ? extensionAddress(target, source)
471
+ : (isChannel(current) ? (0, model_js_1.channelPath)(current) : current.path) + '/' + target;
472
+ if (address.startsWith('/ch/')) {
473
+ const [, , name, key, ...extra] = address.split('/');
474
+ const node = chNames.get(name);
475
+ if (!node || extra.length)
476
+ (0, types_js_1.fail)('unknown-extension-prop', 'Unknown prop: ' + address, source);
477
+ if (key === 'extend' || key === 'boundary') {
478
+ (0, model_js_1.checkArity)(command, args, [2], source);
479
+ const mode = args[1];
480
+ if (node.live || !(0, channels_js_1.boundaryMode)(mode) || (!node.table && (0, channels_js_1.cyclic)(mode) && options.frameCount === undefined)) {
481
+ (0, types_js_1.fail)('invalid-channel-extend', 'Invalid extend mode for ' + address, source);
482
+ }
483
+ if (node.table)
484
+ node.table.boundary = mode;
485
+ else
486
+ node.extend = mode;
487
+ }
488
+ else if (node.ramp && key === 'stops') {
489
+ node.ramp = (0, ramp_js_1.rampStops)((0, contexts_js_1.jsonProp)(lineText, () => (0, types_js_1.fail)('invalid-ramp', 'Expected JSON ramp stops', source)), source);
490
+ }
491
+ else {
492
+ const spec = node.operator?.definition.props.find(p => p.name === key);
493
+ if (!spec)
494
+ (0, types_js_1.fail)('unknown-extension-prop', 'Unknown prop: ' + address, source);
495
+ (0, model_js_1.checkArity)(command, args, [2], source);
496
+ node.operator.props[key] = spec.type === 'number' ? (0, model_js_1.readNumber)(args[1], source) : args[1];
497
+ }
498
+ }
499
+ else
500
+ extensions.property(address, args.slice(1), lineText, source);
501
+ }
502
+ else if (command === 'connect') {
503
+ (0, model_js_1.checkArity)(command, args, [2], source);
504
+ const to = extensionAddress(args[1], source);
505
+ const from = extensionSource(extensionAddress(args[0], source), source);
506
+ if (isBuiltInPath(to)) {
507
+ if (from.stage === 'audio' || from.stage === 'ch') {
508
+ if (from.type !== 'number')
509
+ (0, types_js_1.fail)('extension-port-type', 'Expected a numeric output at ' + from.address, source);
510
+ const path = to.startsWith('/ch/') ? channelInput(to, source) : objectScalar(to, source);
511
+ const operator = expressionPorts.get(path)?.node.operator;
512
+ if (from.stage === 'ch' && to.startsWith('/ch/') && !operator) {
513
+ (0, types_js_1.fail)('extension-stage', 'Expected a channel operator input: ' + to, source);
514
+ }
515
+ driveScalar(path, { kind: 'reference', name: 'ch', path: from.address }, source);
516
+ if (from.stage === 'ch')
517
+ depend(path, from.path);
518
+ contextWires.push({ to: path, input: operator ? 'value' : from.address, from });
519
+ continue;
520
+ }
521
+ const [, context, name, input, extra] = to.split('/');
522
+ if (context !== 'obj' || input !== 'geometry' || extra !== undefined || from.stage !== 'geo') {
523
+ (0, types_js_1.fail)('extension-stage', 'connect cannot drive this built-in input: ' + to, source);
524
+ }
525
+ const object = getObject(name, source);
526
+ if (object.kind !== 'geo')
527
+ (0, types_js_1.fail)('invalid-subject', 'A geometry connection requires a geometry object', source);
528
+ if (from.type !== 'object')
529
+ (0, types_js_1.fail)('extension-port-type', 'Expected object geometry at ' + to, source);
530
+ if (object.geometry || object.geometrySource)
531
+ (0, types_js_1.fail)('overlapping-drivers', 'Geometry already assigned: ' + to, source);
532
+ object.geometrySource = from.address;
533
+ contextWires.push({ to: (0, model_js_1.worldStep)(object), input, from });
534
+ }
535
+ else
536
+ extensions.input(to, from.type, { kind: 'wire', from }, source);
537
+ }
538
+ else if (command === 'expr') {
316
539
  (0, model_js_1.checkArity)(command, args, [2], source);
317
540
  const [target, text] = args;
318
541
  if (!target.startsWith('/'))
319
542
  (0, types_js_1.fail)('invalid-path', 'Expression targets must be absolute', source);
320
543
  const address = normalizePath(target, '/', source);
321
- const path = address.startsWith('/ch/') ? channelOutput(address, source) : objectScalar(address, source);
322
- const expression = bind(text, path, source);
323
- if (path.startsWith('/ch/')) {
324
- const { port } = expressionPorts.get(path);
325
- if (port.samples || port.expression)
326
- (0, types_js_1.fail)('overlapping-drivers', 'Channel already has a driver: ' + path, source);
327
- port.expression = expression;
328
- port.source = source;
544
+ if (!isBuiltInPath(address) && (registry.get(address.split('/')[1]) || options.contexts?.length)) {
545
+ const references = new Map();
546
+ const owner = address.slice(0, address.lastIndexOf('/'));
547
+ const expression = (0, expression_js_1.bindExpression)((0, expression_js_1.parseExpression)(text, source), (ref, name) => {
548
+ const address = normalizePath(ref, owner, source);
549
+ if (name === 'chramp')
550
+ channelOutput(address, source, true);
551
+ const from = extensionSource(address, source);
552
+ if (name !== 'ch' && !from.address.startsWith('/ch/')) {
553
+ (0, types_js_1.fail)('off-time-extension-reference', name + ' requires a channel: ' + from.address, source);
554
+ }
555
+ if (from.type !== 'number')
556
+ (0, types_js_1.fail)('extension-port-type', 'Expected a number at ' + from.address, source);
557
+ if (name === 'chf' || name === 'cht')
558
+ offTimeRefs.push({ path: from.address, source });
559
+ references.set(from.address, from);
560
+ return from.address;
561
+ });
562
+ extensions.input(address, 'number', { kind: 'expr', expression, references: [...references.values()], source }, source);
563
+ continue;
329
564
  }
330
- else
331
- addDriver(path, { kind: 'expr', expression, ...range([], 0, source) });
565
+ const path = address.startsWith('/ch/') ? channelInput(address, source) : objectScalar(address, source);
566
+ driveScalar(path, bind(text, path, source), source);
332
567
  }
333
568
  else if (command === 'register' || command === 'ref') {
334
569
  const register = command === 'register';
@@ -344,6 +579,9 @@ function compile(lines, root, fps, options) {
344
579
  const common = { input, scale: numberAt(end + 1, 1), offset: numberAt(end + 2, 0), ...range(args, end + 4, source) };
345
580
  const freq = numberAt(end, 1);
346
581
  const shift = numberAt(end + 3, 0);
582
+ if (register && (freq !== 1 || shift !== 0 || args[1] === 'rx' || args[1] === 'ry' || args[1] === 'rz')) {
583
+ offTimeRefs.push({ path: input, source });
584
+ }
347
585
  addDriver(path, register ? { kind: 'register', freq, shift, ...common } : { kind: 'ref', ...common });
348
586
  depend(path, input);
349
587
  }
@@ -361,7 +599,7 @@ function compile(lines, root, fps, options) {
361
599
  else {
362
600
  (0, model_js_1.checkArity)(command, args, [2, 4], source);
363
601
  const target = getObject(args[1], source);
364
- if (command === 'children' && (args[0] !== 'lookat' || isChannel(current))) {
602
+ if (command === 'children' && (args[0] !== 'lookat' || !isObject(current))) {
365
603
  (0, types_js_1.fail)('invalid-subject', 'Expected children lookat TARGET with an object current', source);
366
604
  }
367
605
  const activeRange = range(args, 2, source);
@@ -377,8 +615,11 @@ function compile(lines, root, fps, options) {
377
615
  }
378
616
  function validateState(object, state, source) {
379
617
  if (state.matrix && (object.aimBindings.length || object.pathBindings.length ||
380
- [...model_js_1.translations, ...model_js_1.rotations, ...model_js_1.scales].some(p => drivers.has((0, model_js_1.objectPath)(object) + '/' + p)))) {
381
- (0, types_js_1.fail)('invalid-trs', 'Drivers and constraints require a non-sheared, nonsingular TRS matrix', source);
618
+ [...model_js_1.rotations, ...model_js_1.scales].some(p => {
619
+ const target = (0, model_js_1.objectPath)(object) + '/' + p;
620
+ return drivers.has(target) || ranges[target];
621
+ }))) {
622
+ (0, types_js_1.fail)('invalid-trs', 'Rotation and scale drivers and ranges, and constraints, require a non-sheared, nonsingular TRS matrix', source);
382
623
  }
383
624
  }
384
625
  for (const object of objects)
@@ -395,7 +636,7 @@ function compile(lines, root, fps, options) {
395
636
  const command = commandOf(event.command);
396
637
  if (!model_js_1.editCommands.has(command))
397
638
  (0, types_js_1.fail)('forbidden-event-command', 'at cannot execute ' + event.command, source);
398
- if (isChannel(selected) || selected.id >= objectCount)
639
+ if (!isObject(selected) || selected.id >= objectCount)
399
640
  (0, types_js_1.fail)('event-missing-target', 'No current object is available at the event source', source);
400
641
  const edit = (0, model_js_1.propertyEdit)(command, args, selected, source);
401
642
  edit(state.get(selected));
@@ -424,10 +665,28 @@ function compile(lines, root, fps, options) {
424
665
  }
425
666
  }
426
667
  for (const [path, { node, name, port }] of expressionPorts) {
427
- if (!port.samples && !port.expression)
668
+ const extend = node.extend ? [prop('extend', node.extend)] : [];
669
+ if (node.ramp) {
670
+ if (!node.ramp.length)
671
+ (0, types_js_1.fail)('invalid-ramp', 'Missing ramp stops for ' + (0, model_js_1.channelPath)(node), port.source);
672
+ graph.add(path, 'ch:ramp', 'number', [prop('target', path), prop('stops', node.ramp), ...extend], port.source);
673
+ continue;
674
+ }
675
+ if (!port.samples && !port.expression && !port.live)
428
676
  (0, types_js_1.fail)('missing-channel-driver', 'Missing driver for ' + path, port.source);
429
- graph.add(path, node.table ? 'source:table' : 'source:expression', 'number', [prop('target', path), prop('port', name), ...(node.table ? [prop('asset', node.table.asset),
430
- prop('sampling', node.table)] : [prop('ast', port.expression)])], port.source);
677
+ if (node.operator) {
678
+ const { definition, props } = node.operator;
679
+ definition.validate(props, message => (0, types_js_1.fail)('invalid-channel-operator', (0, model_js_1.channelPath)(node) + ': ' + message, node.source));
680
+ graph.addNode(path, { context: 'ch', type: definition.type, inputs: definition.inputs, outputs: definition.outputs,
681
+ props: [prop('target', path), prop('expr/value', port.expression), ...Object.entries(props).map(([key, value]) => prop(key, value)), ...extend],
682
+ }, node.source);
683
+ continue;
684
+ }
685
+ const nodeType = node.table ? 'source:table' : port.live ? 'source:live' : 'source:expression';
686
+ const nodeProps = node.table
687
+ ? [prop('asset', node.table.asset), prop('sampling', node.table)]
688
+ : port.live ? [] : [prop('ast', port.expression)];
689
+ graph.add(path, nodeType, 'number', [prop('target', path), prop('port', name), ...nodeProps, ...extend], port.source);
431
690
  }
432
691
  for (const object of objects) {
433
692
  const path = (0, model_js_1.objectPath)(object);
@@ -463,9 +722,44 @@ function compile(lines, root, fps, options) {
463
722
  for (const [path, dependencies] of inputs)
464
723
  for (const input of dependencies)
465
724
  graph.depend(path, input);
725
+ extensions.addToGraph(graph);
726
+ for (const { to, input, from } of contextWires)
727
+ graph.wire(to, input, from.path, from.port);
466
728
  const finished = graph.finish();
467
- const scene = (0, types_js_1.freeze)({ fps, ...(options.frameCount !== undefined && { frameCount: options.frameCount }),
729
+ const livePorts = new Set();
730
+ for (const path of finished.order) {
731
+ const entry = expressionPorts.get(path);
732
+ if (!entry)
733
+ continue;
734
+ if (entry.port.live || [...(inputs.get(path) ?? [])].some(dep => livePorts.has(dep))) {
735
+ livePorts.add(path);
736
+ }
737
+ }
738
+ for (const ref of offTimeRefs) {
739
+ if (livePorts.has(ref.path)) {
740
+ (0, types_js_1.fail)('off-time-live-channel', 'Live channel does not support off-time reads: ' + ref.path, ref.source);
741
+ }
742
+ }
743
+ const liveChannels = channels.filter(channel => channel.live).map(model_js_1.channelPath).sort(graph_js_1.comparePaths);
744
+ const audioChannels = new Set(contextWires.filter(({ to, from }) => to.startsWith('/ch/') && from.stage === 'audio').map(({ to }) => to));
745
+ for (const path of finished.order) {
746
+ if (path.startsWith('/ch/') && [...(inputs.get(path) ?? [])].some(input => audioChannels.has(input))) {
747
+ audioChannels.add(path);
748
+ }
749
+ }
750
+ for (const [path, { node }] of expressionPorts) {
751
+ if (!livePorts.has(path) && !audioChannels.has(path))
752
+ continue;
753
+ if (node.extend || node.operator?.definition.usesHistory?.(node.operator.props, fps)) {
754
+ (0, types_js_1.fail)('off-time-channel-operator', 'Channel requires unavailable off-frame input: ' + path, node.source);
755
+ }
756
+ }
757
+ const scene = (0, types_js_1.freeze)({
758
+ fps,
759
+ ...(options.frameCount !== undefined && { frameCount: options.frameCount }),
468
760
  graph: finished.graph,
761
+ ...(Object.keys(ranges).length && { ranges }),
762
+ liveChannels,
469
763
  ...((viewCamera || backgroundColor || display) && { view: {
470
764
  ...(viewCamera && { camera: (0, model_js_1.objectPath)(viewCamera) }),
471
765
  ...(backgroundColor && { backgroundColor }),
@@ -474,7 +768,7 @@ function compile(lines, root, fps, options) {
474
768
  });
475
769
  objects.sort((a, b) => (0, graph_js_1.comparePaths)((0, model_js_1.objectPath)(a), (0, model_js_1.objectPath)(b)));
476
770
  channels.sort((a, b) => (0, graph_js_1.comparePaths)((0, model_js_1.channelPath)(a), (0, model_js_1.channelPath)(b)));
477
- model_js_1.plans.set(scene, { objects, channels, drivers, events, order: finished.order });
771
+ model_js_1.plans.set(scene, { objects, channels, drivers, events, order: finished.order, extensions, audioChannels });
478
772
  return scene;
479
773
  }
480
774
  function rename(names, node, name, source) {
package/contexts.d.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { type GraphBuilder } from './graph.js';
2
+ import { type Expression } from './expression.js';
3
+ import { type ContextRegistry, type ContextStage } from './registry.js';
4
+ import { type AudioFrameData, type ContextValue, type ContextValues, type EvaluateFrameOptions, type ExtensionNodeType, type ExtensionPropDefinition, type FrameSnapshot, type GraphPort, type ParameterRange, type SourceLocation } from './types.js';
5
+ export declare function jsonProp(text: string, invalid: () => never): unknown;
6
+ interface NodeDefinition {
7
+ type: string;
8
+ inputs: Map<string, GraphPort>;
9
+ outputs: Map<string, GraphPort>;
10
+ props: Map<string, ExtensionPropDefinition>;
11
+ evaluate: (ctx: Parameters<ExtensionNodeType['evaluate']>[0], audio?: AudioFrameData) => ContextValues | void;
12
+ }
13
+ export interface ExtensionSource {
14
+ address: string;
15
+ path: string;
16
+ port: string;
17
+ type: GraphPort['type'];
18
+ stage: ContextStage;
19
+ }
20
+ type InputDriver = {
21
+ kind: 'wire';
22
+ from: ExtensionSource;
23
+ } | {
24
+ kind: 'expr';
25
+ expression: Expression;
26
+ references: ExtensionSource[];
27
+ source: SourceLocation;
28
+ };
29
+ export interface ExtensionNode {
30
+ path: string;
31
+ context: string;
32
+ stage: ContextStage;
33
+ definition: NodeDefinition;
34
+ source: SourceLocation;
35
+ props: Map<string, ContextValue>;
36
+ drivers: Map<string, InputDriver>;
37
+ }
38
+ export declare class Extensions {
39
+ readonly registry: ContextRegistry;
40
+ private readonly types;
41
+ readonly nodes: Map<string, ExtensionNode>;
42
+ constructor(registry: ContextRegistry);
43
+ add(path: string, type: string, source: SourceLocation): ExtensionNode;
44
+ property(address: string, args: string[], text: string, source: SourceLocation): void;
45
+ input(address: string, type: GraphPort['type'], driver: InputDriver, source: SourceLocation): void;
46
+ output(address: string, source: SourceLocation): ExtensionSource;
47
+ numericPort(address: string, source: SourceLocation): string;
48
+ private member;
49
+ addToGraph(graph: GraphBuilder): void;
50
+ }
51
+ export declare function checkAudioFrame(path: string, sampleFrame: number, frame: number): void;
52
+ export declare function createContextEvaluation(extensions: Extensions, order: readonly string[], frame: number, time: number, fps: number, frameCount: number | undefined, options: EvaluateFrameOptions, readBuiltIn: (path: string, frame: number, rampPosition?: number) => number, ranges: Readonly<Record<string, ParameterRange>> | undefined): {
53
+ run: (stage: "audio" | "geo" | "evaluate" | "output") => void;
54
+ read: (path: string, sampleFrame: number, rampPosition?: number) => ContextValue;
55
+ finish(snapshotBase: FrameSnapshot): FrameSnapshot;
56
+ };
57
+ export {};