@vim3d/core 0.2.1 → 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/esm/contexts.js CHANGED
@@ -1,11 +1,22 @@
1
1
  import { validSegment } from './channels.js';
2
2
  import { comparePaths } from './graph.js';
3
3
  import { evaluateExpression } from './expression.js';
4
- import { allowedSource } from './registry.js';
4
+ import { allowedSource, geoTransformDefaults } from './registry.js';
5
+ import { applyRange } from './ranges.js';
5
6
  import { EvaluationError, fail, freeze, } from './types.js';
6
7
  const nodeType = /^[a-zA-Z][a-zA-Z0-9_-]*:[a-zA-Z][a-zA-Z0-9_-]*$/;
7
8
  const propTypes = new Set(['string', 'number', 'boolean', 'object']);
8
9
  const portTypes = new Set([...propTypes, 'vector3', 'matrix4']);
10
+ export function jsonProp(text, invalid) {
11
+ const raw = text?.trimEnd().match(/^[ \t:]*(?:set|"set")[ \t]+(?:"[^"]*"|[^ \t]+)[ \t]+(.*)$/)?.[1];
12
+ const literal = raw?.match(/^(?:"(?:\\.|[^"\\])*"|[^"#])*/)?.[0];
13
+ try {
14
+ return JSON.parse(literal);
15
+ }
16
+ catch {
17
+ return invalid();
18
+ }
19
+ }
9
20
  function isRecord(value) {
10
21
  return value !== null && typeof value === 'object' &&
11
22
  (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
@@ -111,14 +122,7 @@ export class Extensions {
111
122
  const invalid = () => fail('invalid-extension-prop', 'Expected ' + def.type + ' for ' + address, source);
112
123
  let value = args[0];
113
124
  if (def.type === 'object') {
114
- const raw = text?.trimEnd().match(/^[ \t:]*(?:set|"set")[ \t]+(?:"[^"]*"|[^ \t]+)[ \t]+(.*)$/)?.[1];
115
- const literal = raw?.match(/^(?:"(?:\\.|[^"\\])*"|[^"#])*/)?.[0];
116
- try {
117
- value = JSON.parse(literal);
118
- }
119
- catch {
120
- invalid();
121
- }
125
+ value = jsonProp(text, invalid);
122
126
  }
123
127
  else {
124
128
  if (args.length !== 1)
@@ -156,6 +160,13 @@ export class Extensions {
156
160
  fail('unknown-extension-port', 'Unknown output port: ' + address, source);
157
161
  return { address, path: node.path, port: key, type: port.type, stage: node.stage };
158
162
  }
163
+ numericPort(address, source) {
164
+ const { node, key } = this.member(address, source);
165
+ if (node.definition.inputs.get(key)?.type !== 'number' && node.definition.outputs.get(key)?.type !== 'number') {
166
+ fail('extension-port-type', 'Expected a numeric port at ' + address, source);
167
+ }
168
+ return address;
169
+ }
159
170
  member(address, source) {
160
171
  const [root, context, name, key, ...extra] = address.split('/');
161
172
  if (root || !context || !name || !key || extra.length)
@@ -202,7 +213,7 @@ export function checkAudioFrame(path, sampleFrame, frame) {
202
213
  fail('off-time-audio-reference', 'Audio features are available only at the evaluated frame: ' + path);
203
214
  }
204
215
  }
205
- export function createContextEvaluation(extensions, order, frame, time, fps, frameCount, options, readBuiltIn) {
216
+ export function createContextEvaluation(extensions, order, frame, time, fps, frameCount, options, readBuiltIn, ranges) {
206
217
  const used = new Set([...extensions.nodes.values()].map(node => node.context));
207
218
  const contextNames = extensions.registry.contexts.filter(({ stage, name }) => stage === 'evaluate' || stage === 'output' || used.has(name)).map(({ name }) => name).sort(comparePaths);
208
219
  let base;
@@ -210,9 +221,9 @@ export function createContextEvaluation(extensions, order, frame, time, fps, fra
210
221
  const values = new Map();
211
222
  const snapshots = new Map();
212
223
  const sorted = [...extensions.nodes.keys()].sort(comparePaths);
213
- const read = (path, sampleFrame) => {
224
+ const read = (path, sampleFrame, rampPosition) => {
214
225
  if (path.startsWith('/ch/'))
215
- return readBuiltIn(path, sampleFrame);
226
+ return readBuiltIn(path, sampleFrame, rampPosition);
216
227
  if (path.startsWith('/obj/')) {
217
228
  const end = path.lastIndexOf('/');
218
229
  const object = objects.get(path.slice(0, end));
@@ -245,11 +256,19 @@ export function createContextEvaluation(extensions, order, frame, time, fps, fra
245
256
  if (!node || node.stage !== stage)
246
257
  continue;
247
258
  const { definition, source, context } = node;
248
- const inputs = freeze(Object.fromEntries([...node.drivers].map(([key, driver]) => [
249
- key, driver.kind === 'wire' ? read(driver.from.address, frame) : evaluateExpression(driver.expression, {
250
- frame, fps, frameCount, source: driver.source, read: (address, sampleFrame) => read(address, sampleFrame),
251
- }),
252
- ])));
259
+ const inputs = Object.fromEntries([...node.drivers].map(([key, driver]) => {
260
+ const value = driver.kind === 'wire' ? read(driver.from.address, frame) : evaluateExpression(driver.expression, {
261
+ frame, fps, frameCount, source: driver.source, read: (address, sampleFrame, u) => read(address, sampleFrame, u),
262
+ });
263
+ return [key, typeof value === 'number' ? applyRange(ranges, path + '/' + key, value) : value];
264
+ }));
265
+ if (ranges && stage === 'geo' && definition.type === 'geo:transform') {
266
+ for (const [key, fallback] of Object.entries(geoTransformDefaults)) {
267
+ const address = path + '/' + key;
268
+ if (ranges[address] && !Object.hasOwn(inputs, key))
269
+ inputs[key] = applyRange(ranges, address, fallback);
270
+ }
271
+ }
253
272
  const props = freeze(Object.fromEntries(node.props));
254
273
  const evaluate = definition.evaluate;
255
274
  const audio = options.audio;
@@ -284,7 +303,7 @@ export function createContextEvaluation(extensions, order, frame, time, fps, fra
284
303
  }
285
304
  if (!matches(value, type))
286
305
  invalid();
287
- const output = copyValue(value, invalid);
306
+ const output = typeof value === 'number' ? applyRange(ranges, address, value) : copyValue(value, invalid);
288
307
  values.set(address, output);
289
308
  return [name, output];
290
309
  }));
package/esm/evaluate.js CHANGED
@@ -1,9 +1,13 @@
1
- import { sample } from './channels.js';
1
+ import { cyclic, sample } from './channels.js';
2
+ import { createChannelSampler } from './ch-operators.js';
2
3
  import { checkAudioFrame, createContextEvaluation } from './contexts.js';
4
+ import { applyRange } from './ranges.js';
5
+ import { sampleRamp } from './ramp.js';
3
6
  import { evaluateExpression } from './expression.js';
4
7
  import { add, aim, column, euler, identity, inverseDirection, matrix, multiply, normalize, point, scale, sub, worldUp, wrap } from './math.js';
5
8
  import { active, channelPath, copyState, isColor, objectPath, plans, positionStep, rotations, scales, translations, vector, worldStep } from './model.js';
6
9
  import { EvaluationError, fail, finite, freeze } from './types.js';
10
+ const channelHistories = new WeakMap();
7
11
  export function evaluateFrame(scene, frame, options = {}) {
8
12
  try {
9
13
  if (!Number.isSafeInteger(frame) || frame < 0 || (scene.frameCount !== undefined && frame >= scene.frameCount)) {
@@ -69,14 +73,30 @@ function evaluate(scene, frame, options) {
69
73
  worlds.set(worldStep(object), object);
70
74
  }
71
75
  const outputs = new Map();
76
+ const operators = new Map();
77
+ let histories;
78
+ if (!scene.liveChannels.length && !options?.liveChannels && !options?.audio) {
79
+ histories = channelHistories.get(scene);
80
+ if (!histories) {
81
+ histories = new Map();
82
+ channelHistories.set(scene, histories);
83
+ }
84
+ }
72
85
  for (const channel of plan.channels) {
73
86
  for (const [name, port] of channel.ports) {
74
- outputs.set(channelPath(channel) + '/' + name, { channel, name, port, cache: new Map() });
87
+ const path = channelPath(channel) + '/' + name;
88
+ outputs.set(path, { channel, name, port, cache: new Map() });
89
+ if (channel.operator)
90
+ operators.set(path, createChannelSampler(q => applyRange(scene.ranges, channelPath(channel) + '/input/value', expr(port.expression, q, port.source)), frameCount, port.source, histories && (() => {
91
+ const history = histories.get(path) ?? [];
92
+ histories.set(path, history);
93
+ return history;
94
+ })));
75
95
  }
76
96
  }
77
- const contexts = createContextEvaluation(plan.extensions, plan.order, frame, time, fps, frameCount, options, read);
97
+ const contexts = createContextEvaluation(plan.extensions, plan.order, frame, time, fps, frameCount, options, read, scene.ranges);
78
98
  const expr = (ast, q, source) => evaluateExpression(ast, { frame: q, fps, frameCount, source, read });
79
- function read(path, q) {
99
+ function read(path, q, rampPosition) {
80
100
  if (path.startsWith('/audio/'))
81
101
  return contexts.read(path, q);
82
102
  if (path.startsWith('/obj/')) {
@@ -88,6 +108,10 @@ function evaluate(scene, frame, options) {
88
108
  q = frame;
89
109
  }
90
110
  const { channel, name, port, cache } = outputs.get(path);
111
+ if (channel.extend)
112
+ q = cyclic(channel.extend) ? wrap(q, frameCount) : Math.max(0, Math.min(frameCount === undefined ? Infinity : frameCount - 1, q));
113
+ if (channel.ramp)
114
+ return applyRange(scene.ranges, path, sampleRamp(channel.ramp, rampPosition ?? 0));
91
115
  const value = cache.get(q);
92
116
  if (value !== undefined)
93
117
  return value;
@@ -97,9 +121,21 @@ function evaluate(scene, frame, options) {
97
121
  fail('off-time-live-channel', 'Live channel does not support off-time reads: ' + path, port.source);
98
122
  result = readLivePort(options, channel, name, path, port.source);
99
123
  }
124
+ else if (channel.operator) {
125
+ const { definition, props } = channel.operator;
126
+ const sampler = operators.get(path);
127
+ const sampleOperator = (at) => finite(definition.sample(props, at, fps, port.source, sampler), path, port.source);
128
+ if (channel.extend && cyclic(channel.extend) && !Number.isInteger(q) && definition.usesHistory?.(props, fps)) {
129
+ const left = Math.floor(q), t = q - left;
130
+ result = finite((1 - t) * sampleOperator(left) + t * sampleOperator(wrap(left + 1, frameCount)), path, port.source);
131
+ }
132
+ else
133
+ result = sampleOperator(q);
134
+ }
100
135
  else {
101
136
  result = channel.table ? sample(channel.table, port, q, fps) : expr(port.expression, q, port.source);
102
137
  }
138
+ result = applyRange(scene.ranges, path, result);
103
139
  cache.set(q, result);
104
140
  return result;
105
141
  }
@@ -132,7 +168,8 @@ function evaluate(scene, frame, options) {
132
168
  value = binding.scale * at(frame) + binding.offset;
133
169
  }
134
170
  finite(value, path, binding?.source ?? object.source);
135
- values[name] = isColor(name) ? Math.min(1, Math.max(0, value)) : value;
171
+ values[name] = isColor(name) && !scene.ranges?.[path]
172
+ ? Math.min(1, Math.max(0, value)) : applyRange(scene.ranges, path, value);
136
173
  }
137
174
  const worldPositions = new Map();
138
175
  const localMatrices = new Map();
@@ -176,7 +213,9 @@ function evaluate(scene, frame, options) {
176
213
  const localPosition = pathBinding
177
214
  ? inverseDirection(parent, sub(worldPositions.get(object), column(parent, 3)), pathBinding.source)
178
215
  : vector(authored.parameters, translations);
179
- const local = authored.matrix ?? matrix(localPosition, axes, sizes);
216
+ const local = authored.matrix
217
+ ? [...authored.matrix.slice(0, 12), ...localPosition, 1]
218
+ : matrix(localPosition, axes, sizes);
180
219
  const world = multiply(parent, local);
181
220
  for (const component of [...local, ...world])
182
221
  finite(component, 'Final matrix component', binding?.source ?? object.source);
package/esm/expression.js CHANGED
@@ -3,18 +3,25 @@ const variables = ['$F', '$T', '$FPS', '$NFRAMES', '$PI', '$TAU', '$E'];
3
3
  const lerp = (a, b, u) => a + (b - a) * u;
4
4
  const unit = (u) => Math.max(0, Math.min(1, u));
5
5
  const smooth = (u) => u * u * (3 - 2 * u);
6
+ function boundedLerp(a, b, u) {
7
+ if (u <= 0)
8
+ return a;
9
+ if (u >= 1)
10
+ return b;
11
+ return Math.max(Math.min(a, b), Math.min(Math.max(a, b), lerp(a, b, u)));
12
+ }
6
13
  function noise(x, seed = 0) {
7
14
  const i = Math.floor(x);
8
15
  if (![i, i + 1, seed].every(Number.isSafeInteger))
9
16
  return NaN;
10
- const hash = (j) => {
11
- let n = j ^ seed;
12
- n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
13
- n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
14
- return 2 * ((n ^ (n >>> 16)) >>> 0) / 4294967295 - 1;
15
- };
17
+ const hash = (j) => 2 * mix32(j ^ seed) / 4294967295 - 1;
16
18
  return lerp(hash(i), hash(i + 1), smooth(x - i));
17
19
  }
20
+ function mix32(n) {
21
+ n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
22
+ n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
23
+ return (n ^ (n >>> 16)) >>> 0;
24
+ }
18
25
  const functions = {
19
26
  sin: [1, 1, Math.sin], cos: [1, 1, Math.cos], tan: [1, 1, Math.tan],
20
27
  atan2: [2, 2, (y, x) => x === 0 && y === 0 ? NaN : Math.atan2(y, x)],
@@ -22,7 +29,24 @@ const functions = {
22
29
  round: [1, 1, Math.round], min: [1, Infinity, Math.min], max: [1, Infinity, Math.max],
23
30
  clamp: [3, 3, (x, lo, hi) => lo <= hi ? Math.max(lo, Math.min(hi, x)) : NaN],
24
31
  lerp: [3, 3, lerp],
25
- fit: [5, 5, (x, a, b, c, d) => a < b ? lerp(c, d, unit((x - a) / (b - a))) : NaN],
32
+ fit: [5, 5, (x, a, b, c, d) => {
33
+ if (a >= b)
34
+ return NaN;
35
+ if (x <= a)
36
+ return c;
37
+ if (x >= b)
38
+ return d;
39
+ return boundedLerp(c, d, (x - a) / (b - a));
40
+ }],
41
+ fit01: [3, 3, (x, c, d) => boundedLerp(c, d, x)],
42
+ fit10: [3, 3, (x, c, d) => boundedLerp(d, c, x)],
43
+ fit11: [3, 3, (x, c, d) => boundedLerp(c, d, (x + 1) / 2)],
44
+ efit: [5, 5, (x, a, b, c, d) => a !== b ? lerp(c, d, (x - a) / (b - a)) : NaN],
45
+ rand: [1, 1, seed => mix32(seed) / 4294967296],
46
+ sign: [1, 1, x => x === 0 ? 0 : Math.sign(x)],
47
+ deg: [1, 1, x => x * (180 / Math.PI)],
48
+ rad: [1, 1, x => x * (Math.PI / 180)],
49
+ modulo: [2, 2, (a, b) => a - b * Math.floor(a / b)],
26
50
  smoothstep: [3, 3, (a, b, x) => a < b ? smooth(unit((x - a) / (b - a))) : NaN],
27
51
  pow: [2, 2, Math.pow], sqrt: [1, 1, Math.sqrt], exp: [1, 1, Math.exp],
28
52
  log: [1, 1, Math.log], noise: [1, 2, noise],
@@ -64,7 +88,7 @@ export function parseExpression(text, source) {
64
88
  return { kind: 'number', value: finite(Number(word), 'Number literal', source) };
65
89
  if (variables.includes(word))
66
90
  return { kind: 'variable', name: word };
67
- if (word === 'ch' || word === 'chf' || word === 'cht') {
91
+ if (word === 'ch' || word === 'chf' || word === 'cht' || word === 'chramp') {
68
92
  expect('(');
69
93
  const path = current;
70
94
  if (!/^['"]/.test(path))
@@ -141,6 +165,8 @@ export function evaluateExpression(ast, context) {
141
165
  break;
142
166
  case 'reference': {
143
167
  const time = node.time ? visit(node.time) : frame;
168
+ if (node.name === 'chramp')
169
+ return read(node.path, frame, time);
144
170
  return read(node.path, finite(node.name === 'cht' ? time * fps : time, 'Sample frame', source));
145
171
  }
146
172
  case 'unary': return node.op === '-' ? -visit(node.operand) : visit(node.operand);
package/esm/graph.js CHANGED
@@ -98,7 +98,7 @@ export class GraphBuilder {
98
98
  edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
99
99
  return { name: source.name, type: output.type };
100
100
  });
101
- return { ...node, inputs: [...inputs, ...typedInputs] };
101
+ return { ...node, inputs: [...new Map([...node.inputs, ...inputs, ...typedInputs].map(port => [port.name, port])).values()] };
102
102
  });
103
103
  return { order, graph: { name: 'scene', nodes, edges } };
104
104
  }
package/esm/ramp.js ADDED
@@ -0,0 +1,36 @@
1
+ import { fail } from './types.js';
2
+ export function rampStops(value, source) {
3
+ const invalid = () => fail('invalid-ramp', 'Expected distinct ramp stops with finite values and positions in [0, 1]', source);
4
+ if (!Array.isArray(value) || !value.length)
5
+ return invalid();
6
+ const stops = value.map(stop => {
7
+ if (!stop || typeof stop !== 'object' || Array.isArray(stop))
8
+ return invalid();
9
+ const { pos, value, interp = 'linear' } = stop;
10
+ if (!Number.isFinite(pos) || pos < 0 || pos > 1 || !Number.isFinite(value) ||
11
+ (interp !== 'linear' && interp !== 'smooth' && interp !== 'constant'))
12
+ return invalid();
13
+ return { pos, value, interp };
14
+ }).sort((a, b) => a.pos - b.pos);
15
+ if (stops.some((stop, i) => i > 0 && stop.pos === stops[i - 1].pos))
16
+ return invalid();
17
+ return stops;
18
+ }
19
+ export function sampleRamp(stops, u) {
20
+ const x = Math.max(0, Math.min(1, u));
21
+ if (x <= stops[0].pos)
22
+ return stops[0].value;
23
+ for (let i = 1; i < stops.length; i++) {
24
+ const left = stops[i - 1], right = stops[i];
25
+ if (x === right.pos)
26
+ return right.value;
27
+ if (x > right.pos)
28
+ continue;
29
+ if (left.interp === 'constant')
30
+ return left.value;
31
+ const t = (x - left.pos) / (right.pos - left.pos);
32
+ const w = left.interp === 'smooth' ? t * t * (3 - 2 * t) : t;
33
+ return left.value * (1 - w) + right.value * w;
34
+ }
35
+ return stops[stops.length - 1].value;
36
+ }
package/esm/ranges.js ADDED
@@ -0,0 +1,9 @@
1
+ import { fail } from './types.js';
2
+ export function applyRange(ranges, path, value) {
3
+ const range = ranges?.[path];
4
+ if (!range || (value >= range.min && value <= range.max))
5
+ return value;
6
+ if (range.mode === 'error')
7
+ fail('range-violation', `${path} is ${value}, outside [${range.min}, ${range.max}]`, range.source);
8
+ return Math.max(range.min, Math.min(range.max, value));
9
+ }
package/esm/registry.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { channelOperators } from './ch-operators.js';
1
2
  import { fail, finite, freeze, } from './types.js';
2
3
  const ports = (type, ...names) => names.map(name => ({ name, type }));
3
4
  const numeric = (defaults) => Object.entries(defaults)
@@ -34,6 +35,7 @@ const audio = [
34
35
  evaluate: ({ inputs }, data) => ({ value: data?.rms ?? inputs.value ?? 0 }),
35
36
  },
36
37
  ];
38
+ export const geoTransformDefaults = freeze({ tx: 0, ty: 0, tz: 0, sx: 1, sy: 1, sz: 1 });
37
39
  const geo = [
38
40
  {
39
41
  type: 'geo:box', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ width: 1, height: 1, depth: 1 }),
@@ -45,11 +47,12 @@ const geo = [
45
47
  },
46
48
  {
47
49
  type: 'geo:transform',
48
- inputs: [...ports('object', 'geometry'), ...ports('number', 'tx', 'ty', 'tz', 'sx', 'sy', 'sz')],
50
+ inputs: [...ports('object', 'geometry'), ...ports('number', ...Object.keys(geoTransformDefaults))],
49
51
  outputs: ports('object', 'geometry'), props: [],
50
52
  evaluate: ({ inputs }) => ({ geometry: {
51
53
  kind: 'transform', geometry: inputs.geometry ?? null,
52
- translate: [inputs.tx ?? 0, inputs.ty ?? 0, inputs.tz ?? 0], scale: [inputs.sx ?? 1, inputs.sy ?? 1, inputs.sz ?? 1],
54
+ translate: [inputs.tx ?? geoTransformDefaults.tx, inputs.ty ?? geoTransformDefaults.ty, inputs.tz ?? geoTransformDefaults.tz],
55
+ scale: [inputs.sx ?? geoTransformDefaults.sx, inputs.sy ?? geoTransformDefaults.sy, inputs.sz ?? geoTransformDefaults.sz],
53
56
  } }),
54
57
  },
55
58
  {
@@ -59,7 +62,7 @@ const geo = [
59
62
  ];
60
63
  export const BUILTIN_CONTEXTS = freeze([
61
64
  { name: 'audio', stage: 'audio', nodeTypes: audio },
62
- { name: 'ch', stage: 'ch', nodeTypes: [] },
65
+ { name: 'ch', stage: 'ch', nodeTypes: channelOperators },
63
66
  { name: 'geo', stage: 'geo', nodeTypes: geo },
64
67
  { name: 'obj', stage: 'obj', nodeTypes: [] },
65
68
  { name: 'sim', stage: 'reserved', nodeTypes: [] },
package/evaluate.js CHANGED
@@ -2,11 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluateFrame = evaluateFrame;
4
4
  const channels_js_1 = require("./channels.js");
5
+ const ch_operators_js_1 = require("./ch-operators.js");
5
6
  const contexts_js_1 = require("./contexts.js");
7
+ const ranges_js_1 = require("./ranges.js");
8
+ const ramp_js_1 = require("./ramp.js");
6
9
  const expression_js_1 = require("./expression.js");
7
10
  const math_js_1 = require("./math.js");
8
11
  const model_js_1 = require("./model.js");
9
12
  const types_js_1 = require("./types.js");
13
+ const channelHistories = new WeakMap();
10
14
  function evaluateFrame(scene, frame, options = {}) {
11
15
  try {
12
16
  if (!Number.isSafeInteger(frame) || frame < 0 || (scene.frameCount !== undefined && frame >= scene.frameCount)) {
@@ -72,14 +76,30 @@ function evaluate(scene, frame, options) {
72
76
  worlds.set((0, model_js_1.worldStep)(object), object);
73
77
  }
74
78
  const outputs = new Map();
79
+ const operators = new Map();
80
+ let histories;
81
+ if (!scene.liveChannels.length && !options?.liveChannels && !options?.audio) {
82
+ histories = channelHistories.get(scene);
83
+ if (!histories) {
84
+ histories = new Map();
85
+ channelHistories.set(scene, histories);
86
+ }
87
+ }
75
88
  for (const channel of plan.channels) {
76
89
  for (const [name, port] of channel.ports) {
77
- outputs.set((0, model_js_1.channelPath)(channel) + '/' + name, { channel, name, port, cache: new Map() });
90
+ const path = (0, model_js_1.channelPath)(channel) + '/' + name;
91
+ outputs.set(path, { channel, name, port, cache: new Map() });
92
+ if (channel.operator)
93
+ operators.set(path, (0, ch_operators_js_1.createChannelSampler)(q => (0, ranges_js_1.applyRange)(scene.ranges, (0, model_js_1.channelPath)(channel) + '/input/value', expr(port.expression, q, port.source)), frameCount, port.source, histories && (() => {
94
+ const history = histories.get(path) ?? [];
95
+ histories.set(path, history);
96
+ return history;
97
+ })));
78
98
  }
79
99
  }
80
- const contexts = (0, contexts_js_1.createContextEvaluation)(plan.extensions, plan.order, frame, time, fps, frameCount, options, read);
100
+ const contexts = (0, contexts_js_1.createContextEvaluation)(plan.extensions, plan.order, frame, time, fps, frameCount, options, read, scene.ranges);
81
101
  const expr = (ast, q, source) => (0, expression_js_1.evaluateExpression)(ast, { frame: q, fps, frameCount, source, read });
82
- function read(path, q) {
102
+ function read(path, q, rampPosition) {
83
103
  if (path.startsWith('/audio/'))
84
104
  return contexts.read(path, q);
85
105
  if (path.startsWith('/obj/')) {
@@ -91,6 +111,10 @@ function evaluate(scene, frame, options) {
91
111
  q = frame;
92
112
  }
93
113
  const { channel, name, port, cache } = outputs.get(path);
114
+ if (channel.extend)
115
+ q = (0, channels_js_1.cyclic)(channel.extend) ? (0, math_js_1.wrap)(q, frameCount) : Math.max(0, Math.min(frameCount === undefined ? Infinity : frameCount - 1, q));
116
+ if (channel.ramp)
117
+ return (0, ranges_js_1.applyRange)(scene.ranges, path, (0, ramp_js_1.sampleRamp)(channel.ramp, rampPosition ?? 0));
94
118
  const value = cache.get(q);
95
119
  if (value !== undefined)
96
120
  return value;
@@ -100,9 +124,21 @@ function evaluate(scene, frame, options) {
100
124
  (0, types_js_1.fail)('off-time-live-channel', 'Live channel does not support off-time reads: ' + path, port.source);
101
125
  result = readLivePort(options, channel, name, path, port.source);
102
126
  }
127
+ else if (channel.operator) {
128
+ const { definition, props } = channel.operator;
129
+ const sampler = operators.get(path);
130
+ const sampleOperator = (at) => (0, types_js_1.finite)(definition.sample(props, at, fps, port.source, sampler), path, port.source);
131
+ if (channel.extend && (0, channels_js_1.cyclic)(channel.extend) && !Number.isInteger(q) && definition.usesHistory?.(props, fps)) {
132
+ const left = Math.floor(q), t = q - left;
133
+ result = (0, types_js_1.finite)((1 - t) * sampleOperator(left) + t * sampleOperator((0, math_js_1.wrap)(left + 1, frameCount)), path, port.source);
134
+ }
135
+ else
136
+ result = sampleOperator(q);
137
+ }
103
138
  else {
104
139
  result = channel.table ? (0, channels_js_1.sample)(channel.table, port, q, fps) : expr(port.expression, q, port.source);
105
140
  }
141
+ result = (0, ranges_js_1.applyRange)(scene.ranges, path, result);
106
142
  cache.set(q, result);
107
143
  return result;
108
144
  }
@@ -135,7 +171,8 @@ function evaluate(scene, frame, options) {
135
171
  value = binding.scale * at(frame) + binding.offset;
136
172
  }
137
173
  (0, types_js_1.finite)(value, path, binding?.source ?? object.source);
138
- values[name] = (0, model_js_1.isColor)(name) ? Math.min(1, Math.max(0, value)) : value;
174
+ values[name] = (0, model_js_1.isColor)(name) && !scene.ranges?.[path]
175
+ ? Math.min(1, Math.max(0, value)) : (0, ranges_js_1.applyRange)(scene.ranges, path, value);
139
176
  }
140
177
  const worldPositions = new Map();
141
178
  const localMatrices = new Map();
@@ -179,7 +216,9 @@ function evaluate(scene, frame, options) {
179
216
  const localPosition = pathBinding
180
217
  ? (0, math_js_1.inverseDirection)(parent, (0, math_js_1.sub)(worldPositions.get(object), (0, math_js_1.column)(parent, 3)), pathBinding.source)
181
218
  : (0, model_js_1.vector)(authored.parameters, model_js_1.translations);
182
- const local = authored.matrix ?? (0, math_js_1.matrix)(localPosition, axes, sizes);
219
+ const local = authored.matrix
220
+ ? [...authored.matrix.slice(0, 12), ...localPosition, 1]
221
+ : (0, math_js_1.matrix)(localPosition, axes, sizes);
183
222
  const world = (0, math_js_1.multiply)(parent, local);
184
223
  for (const component of [...local, ...world])
185
224
  (0, types_js_1.finite)(component, 'Final matrix component', binding?.source ?? object.source);
package/expression.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type SourceLocation } from './types.js';
2
2
  declare const variables: readonly ["$F", "$T", "$FPS", "$NFRAMES", "$PI", "$TAU", "$E"];
3
3
  export type Variable = typeof variables[number];
4
- export type ReferenceFunction = 'ch' | 'chf' | 'cht';
4
+ export type ReferenceFunction = 'ch' | 'chf' | 'cht' | 'chramp';
5
5
  export type UnaryOperator = '+' | '-';
6
6
  export type BinaryOperator = '+' | '-' | '*' | '/' | '%' | '^';
7
7
  export type Expression = {
@@ -44,6 +44,15 @@ declare const functions: {
44
44
  clamp: [number, number, (x: number, lo: number, hi: number) => number];
45
45
  lerp: [number, number, (a: number, b: number, u: number) => number];
46
46
  fit: [number, number, (x: number, a: number, b: number, c: number, d: number) => number];
47
+ fit01: [number, number, (x: number, c: number, d: number) => number];
48
+ fit10: [number, number, (x: number, c: number, d: number) => number];
49
+ fit11: [number, number, (x: number, c: number, d: number) => number];
50
+ efit: [number, number, (x: number, a: number, b: number, c: number, d: number) => number];
51
+ rand: [number, number, (seed: number) => number];
52
+ sign: [number, number, (x: number) => number];
53
+ deg: [number, number, (x: number) => number];
54
+ rad: [number, number, (x: number) => number];
55
+ modulo: [number, number, (a: number, b: number) => number];
47
56
  smoothstep: [number, number, (a: number, b: number, x: number) => number];
48
57
  pow: [number, number, (x: number, y: number) => number];
49
58
  sqrt: [number, number, (x: number) => number];
@@ -59,7 +68,7 @@ interface ExpressionContext {
59
68
  fps: number;
60
69
  frameCount?: number;
61
70
  source: SourceLocation;
62
- read: (path: string, frame: number) => number;
71
+ read: (path: string, frame: number, rampPosition?: number) => number;
63
72
  }
64
73
  export declare function evaluateExpression(ast: Expression, context: ExpressionContext): number;
65
74
  export {};
package/expression.js CHANGED
@@ -8,18 +8,25 @@ const variables = ['$F', '$T', '$FPS', '$NFRAMES', '$PI', '$TAU', '$E'];
8
8
  const lerp = (a, b, u) => a + (b - a) * u;
9
9
  const unit = (u) => Math.max(0, Math.min(1, u));
10
10
  const smooth = (u) => u * u * (3 - 2 * u);
11
+ function boundedLerp(a, b, u) {
12
+ if (u <= 0)
13
+ return a;
14
+ if (u >= 1)
15
+ return b;
16
+ return Math.max(Math.min(a, b), Math.min(Math.max(a, b), lerp(a, b, u)));
17
+ }
11
18
  function noise(x, seed = 0) {
12
19
  const i = Math.floor(x);
13
20
  if (![i, i + 1, seed].every(Number.isSafeInteger))
14
21
  return NaN;
15
- const hash = (j) => {
16
- let n = j ^ seed;
17
- n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
18
- n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
19
- return 2 * ((n ^ (n >>> 16)) >>> 0) / 4294967295 - 1;
20
- };
22
+ const hash = (j) => 2 * mix32(j ^ seed) / 4294967295 - 1;
21
23
  return lerp(hash(i), hash(i + 1), smooth(x - i));
22
24
  }
25
+ function mix32(n) {
26
+ n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
27
+ n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
28
+ return (n ^ (n >>> 16)) >>> 0;
29
+ }
23
30
  const functions = {
24
31
  sin: [1, 1, Math.sin], cos: [1, 1, Math.cos], tan: [1, 1, Math.tan],
25
32
  atan2: [2, 2, (y, x) => x === 0 && y === 0 ? NaN : Math.atan2(y, x)],
@@ -27,7 +34,24 @@ const functions = {
27
34
  round: [1, 1, Math.round], min: [1, Infinity, Math.min], max: [1, Infinity, Math.max],
28
35
  clamp: [3, 3, (x, lo, hi) => lo <= hi ? Math.max(lo, Math.min(hi, x)) : NaN],
29
36
  lerp: [3, 3, lerp],
30
- fit: [5, 5, (x, a, b, c, d) => a < b ? lerp(c, d, unit((x - a) / (b - a))) : NaN],
37
+ fit: [5, 5, (x, a, b, c, d) => {
38
+ if (a >= b)
39
+ return NaN;
40
+ if (x <= a)
41
+ return c;
42
+ if (x >= b)
43
+ return d;
44
+ return boundedLerp(c, d, (x - a) / (b - a));
45
+ }],
46
+ fit01: [3, 3, (x, c, d) => boundedLerp(c, d, x)],
47
+ fit10: [3, 3, (x, c, d) => boundedLerp(d, c, x)],
48
+ fit11: [3, 3, (x, c, d) => boundedLerp(c, d, (x + 1) / 2)],
49
+ efit: [5, 5, (x, a, b, c, d) => a !== b ? lerp(c, d, (x - a) / (b - a)) : NaN],
50
+ rand: [1, 1, seed => mix32(seed) / 4294967296],
51
+ sign: [1, 1, x => x === 0 ? 0 : Math.sign(x)],
52
+ deg: [1, 1, x => x * (180 / Math.PI)],
53
+ rad: [1, 1, x => x * (Math.PI / 180)],
54
+ modulo: [2, 2, (a, b) => a - b * Math.floor(a / b)],
31
55
  smoothstep: [3, 3, (a, b, x) => a < b ? smooth(unit((x - a) / (b - a))) : NaN],
32
56
  pow: [2, 2, Math.pow], sqrt: [1, 1, Math.sqrt], exp: [1, 1, Math.exp],
33
57
  log: [1, 1, Math.log], noise: [1, 2, noise],
@@ -69,7 +93,7 @@ function parseExpression(text, source) {
69
93
  return { kind: 'number', value: (0, types_js_1.finite)(Number(word), 'Number literal', source) };
70
94
  if (variables.includes(word))
71
95
  return { kind: 'variable', name: word };
72
- if (word === 'ch' || word === 'chf' || word === 'cht') {
96
+ if (word === 'ch' || word === 'chf' || word === 'cht' || word === 'chramp') {
73
97
  expect('(');
74
98
  const path = current;
75
99
  if (!/^['"]/.test(path))
@@ -146,6 +170,8 @@ function evaluateExpression(ast, context) {
146
170
  break;
147
171
  case 'reference': {
148
172
  const time = node.time ? visit(node.time) : frame;
173
+ if (node.name === 'chramp')
174
+ return read(node.path, frame, time);
149
175
  return read(node.path, (0, types_js_1.finite)(node.name === 'cht' ? time * fps : time, 'Sample frame', source));
150
176
  }
151
177
  case 'unary': return node.op === '-' ? -visit(node.operand) : visit(node.operand);
package/graph.js CHANGED
@@ -102,7 +102,7 @@ class GraphBuilder {
102
102
  edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
103
103
  return { name: source.name, type: output.type };
104
104
  });
105
- return { ...node, inputs: [...inputs, ...typedInputs] };
105
+ return { ...node, inputs: [...new Map([...node.inputs, ...inputs, ...typedInputs].map(port => [port.name, port])).values()] };
106
106
  });
107
107
  return { order, graph: { name: 'scene', nodes, edges } };
108
108
  }
package/index.d.ts CHANGED
@@ -4,4 +4,4 @@ export { evaluateFrame } from './evaluate.js';
4
4
  export { BUILTIN_CONTEXTS, createContextRegistry } from './registry.js';
5
5
  export type { ContextDefinition, ContextRegistry, ContextStage } from './registry.js';
6
6
  export type { BinaryOperator, Expression, MathFunction, ReferenceFunction, UnaryOperator, Variable } from './expression.js';
7
- export type { AudioFrameData, CameraSnapshot, ChannelSnapshot, CompiledScene, CompileOptions, ContextNodeSnapshot, ContextValue, ContextValues, Diagnostic, EvaluateFrameOptions, EvaluateOptions, EvaluationGraph, ExtensionContextDefinition, ExtensionContextStage, ExtensionNodeEvalContext, ExtensionNodeType, ExtensionPropDefinition, FrameSnapshot, GeometrySnapshot, GraphEdge, GraphEndpoint, GraphNode, GraphPort, GraphPortType, GraphProp, LightKind, LightSnapshot, LiveChannelInput, LiveChannelSample, MaterialSnapshot, Matrix4, ObjectKind, ObjectSnapshot, Result, SceneSource, SourceLocation, Vec3, } from './types.js';
7
+ export type { AudioFrameData, CameraSnapshot, ChannelSnapshot, CompiledScene, CompileOptions, ContextNodeSnapshot, ContextValue, ContextValues, Diagnostic, EvaluateFrameOptions, EvaluateOptions, EvaluationGraph, ExtensionContextDefinition, ExtensionContextStage, ExtensionNodeEvalContext, ExtensionNodeType, ExtensionPropDefinition, FrameSnapshot, GeometrySnapshot, GraphEdge, GraphEndpoint, GraphNode, GraphPort, GraphPortType, GraphProp, LightKind, LightSnapshot, LiveChannelInput, LiveChannelSample, MaterialSnapshot, Matrix4, ObjectKind, ObjectSnapshot, ParameterRange, Result, SceneSource, SourceLocation, Vec3, } from './types.js';
package/model.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { Expression } from './expression.js';
2
2
  import type { Extensions } from './contexts.js';
3
+ import type { ChannelOperatorDefinition } from './ch-operators.js';
4
+ import type { RampStop } from './ramp.js';
3
5
  import { type CompiledScene, type GeometrySnapshot, type LightKind, type Matrix4, type ObjectKind, type SourceLocation, type Vec3 } from './types.js';
4
6
  export interface Authored {
5
7
  parameters: Record<string, number>;
@@ -26,13 +28,19 @@ export interface Table {
26
28
  asset: string;
27
29
  sampleRate?: number;
28
30
  interpolation: 'step' | 'linear';
29
- boundary: 'wrap' | 'clamp';
31
+ boundary: 'wrap' | 'clamp' | 'cycle' | 'hold';
30
32
  }
31
33
  export interface Channel {
32
34
  id: number;
33
35
  name: string;
34
36
  source: SourceLocation;
35
37
  table?: Table;
38
+ extend?: Table['boundary'];
39
+ ramp?: readonly RampStop[];
40
+ operator?: {
41
+ definition: ChannelOperatorDefinition;
42
+ props: Record<string, string | number>;
43
+ };
36
44
  live?: boolean;
37
45
  ports: Map<string, ChannelPort>;
38
46
  }