@vim3d/core 0.1.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/math.js ADDED
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.column = exports.normalize = exports.length = exports.cross = exports.dot = exports.scale = exports.sub = exports.add = exports.worldUp = exports.identity = void 0;
4
+ exports.euler = euler;
5
+ exports.decompose = decompose;
6
+ exports.matrix = matrix;
7
+ exports.direction = direction;
8
+ exports.point = point;
9
+ exports.multiply = multiply;
10
+ exports.inverseDirection = inverseDirection;
11
+ exports.aim = aim;
12
+ exports.wrap = wrap;
13
+ const types_js_1 = require("./types.js");
14
+ exports.identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
15
+ exports.worldUp = [0, 1, 0];
16
+ const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
17
+ exports.add = add;
18
+ const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
19
+ exports.sub = sub;
20
+ const scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s];
21
+ exports.scale = scale;
22
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
23
+ exports.dot = dot;
24
+ const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
25
+ exports.cross = cross;
26
+ const length = (a) => Math.hypot(...a);
27
+ exports.length = length;
28
+ const normalize = (a) => {
29
+ const n = (0, exports.length)(a);
30
+ return n === 0 ? [0, 0, 0] : [a[0] / n, a[1] / n, a[2] / n];
31
+ };
32
+ exports.normalize = normalize;
33
+ const column = (a, i) => [a[i * 4], a[i * 4 + 1], a[i * 4 + 2]];
34
+ exports.column = column;
35
+ const radians = Math.PI / 180;
36
+ function euler([x, y, z]) {
37
+ const [sx, sy, sz] = [x, y, z].map(a => Math.sin(a * radians));
38
+ const [cx, cy, cz] = [x, y, z].map(a => Math.cos(a * radians));
39
+ return [[cz * cy, sz * cy, -sy],
40
+ [cz * sy * sx - sz * cx, sz * sy * sx + cz * cx, cy * sx],
41
+ [cz * sy * cx + sz * sx, sz * sy * cx - cz * sx, cy * cx]];
42
+ }
43
+ function decompose(m, source) {
44
+ const cols = [(0, exports.column)(m, 0), (0, exports.column)(m, 1), (0, exports.column)(m, 2)];
45
+ const [sx, sy, sz] = cols.map(exports.length);
46
+ if (![sx, sy, sz].every(n => n > 0 && Number.isFinite(n)))
47
+ return;
48
+ const [x, y, z] = cols.map(exports.normalize);
49
+ if ([(0, exports.dot)(x, y), (0, exports.dot)(x, z), (0, exports.dot)(y, z)].some(n => Math.abs(n) > 1e-8))
50
+ return;
51
+ const sign = Math.sign((0, exports.dot)((0, exports.cross)(x, y), z));
52
+ const ry = Math.asin(Math.max(-1, Math.min(1, -x[2])));
53
+ const singular = Math.abs(Math.cos(ry)) <= 1e-8;
54
+ const rx = singular ? 0 : Math.atan2(y[2], z[2] * sign);
55
+ const rz = singular ? Math.atan2(-y[0], y[1]) : Math.atan2(x[1], x[0]);
56
+ return { rotation: [(0, types_js_1.finite)(rx / radians, 'Rotation', source), ry / radians, rz / radians],
57
+ scale: [sx, sy, sz * sign] };
58
+ }
59
+ function matrix(position, axes, sizes) {
60
+ return [...axes.flatMap((axis, i) => [...(0, exports.scale)(axis, sizes[i]), 0]), ...position, 1];
61
+ }
62
+ function direction(m, p) {
63
+ return (0, exports.add)((0, exports.add)((0, exports.scale)((0, exports.column)(m, 0), p[0]), (0, exports.scale)((0, exports.column)(m, 1), p[1])), (0, exports.scale)((0, exports.column)(m, 2), p[2]));
64
+ }
65
+ function point(m, p) {
66
+ return (0, exports.add)(direction(m, p), (0, exports.column)(m, 3));
67
+ }
68
+ function multiply(a, b) {
69
+ return matrix(point(a, (0, exports.column)(b, 3)), [direction(a, (0, exports.column)(b, 0)), direction(a, (0, exports.column)(b, 1)), direction(a, (0, exports.column)(b, 2))], [1, 1, 1]);
70
+ }
71
+ function inverseDirection(m, p, source) {
72
+ const [a, b, c] = [(0, exports.column)(m, 0), (0, exports.column)(m, 1), (0, exports.column)(m, 2)];
73
+ const u = (0, exports.cross)(b, c), v = (0, exports.cross)(c, a), w = (0, exports.cross)(a, b);
74
+ const det = (0, exports.dot)(a, u);
75
+ if (!det || !Number.isFinite(det))
76
+ (0, types_js_1.fail)('singular-parent', 'Constraint requires an invertible parent matrix', source);
77
+ return [(0, exports.dot)(u, p) / det, (0, exports.dot)(v, p) / det, (0, exports.dot)(w, p) / det];
78
+ }
79
+ function aim(parent, origin, target, up, forward, sizes, source) {
80
+ const delta = (0, exports.sub)(target, origin);
81
+ if ((0, exports.length)(delta) === 0)
82
+ return;
83
+ if (!sizes[1] || !sizes[2])
84
+ (0, types_js_1.fail)('zero-lookat-scale', 'Look-at requires nonzero Y and Z scale', source);
85
+ const d = (0, exports.normalize)(delta);
86
+ let hint = (0, exports.normalize)(up);
87
+ if ((0, exports.length)(hint) === 0 || Math.abs((0, exports.dot)(hint, d)) >= 1 - 1e-8) {
88
+ const candidates = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
89
+ hint = candidates.reduce((a, b) => Math.abs((0, exports.dot)(b, d)) < Math.abs((0, exports.dot)(a, d)) ? b : a);
90
+ }
91
+ const z = (0, exports.scale)(d, forward);
92
+ const y = (0, exports.cross)(z, (0, exports.normalize)((0, exports.cross)(hint, z)));
93
+ const localZ = (0, exports.scale)((0, exports.normalize)(inverseDirection(parent, z, source)), Math.sign(sizes[2]));
94
+ const projected = inverseDirection(parent, y, source);
95
+ const localY = (0, exports.scale)((0, exports.normalize)((0, exports.sub)(projected, (0, exports.scale)(localZ, (0, exports.dot)(localZ, projected)))), Math.sign(sizes[1]));
96
+ const localX = (0, exports.cross)(localY, localZ);
97
+ return [localX, (0, exports.cross)(localZ, localX), localZ];
98
+ }
99
+ function wrap(i, count) {
100
+ return (i % count + count) % count;
101
+ }
package/model.d.ts ADDED
@@ -0,0 +1,107 @@
1
+ import type { Expression } from './expression.js';
2
+ import type { Extensions } from './contexts.js';
3
+ import { type CompiledScene, type GeometrySnapshot, type LightKind, type Matrix4, type ObjectKind, type SourceLocation, type Vec3 } from './types.js';
4
+ export interface Authored {
5
+ parameters: Record<string, number>;
6
+ matrix?: Matrix4;
7
+ up: Vec3;
8
+ focus?: Vec3;
9
+ light: LightKind;
10
+ visible: boolean;
11
+ enabled: boolean;
12
+ }
13
+ export interface SceneObject {
14
+ id: number;
15
+ name: string;
16
+ kind: ObjectKind;
17
+ source: SourceLocation;
18
+ parent?: SceneObject;
19
+ geometry?: GeometrySnapshot;
20
+ geometrySource?: string;
21
+ authored: Authored;
22
+ pathBindings: PathBinding[];
23
+ aimBindings: AimBinding[];
24
+ }
25
+ export interface Table {
26
+ asset: string;
27
+ sampleRate?: number;
28
+ interpolation: 'step' | 'linear';
29
+ boundary: 'wrap' | 'clamp';
30
+ }
31
+ export interface Channel {
32
+ id: number;
33
+ name: string;
34
+ source: SourceLocation;
35
+ table?: Table;
36
+ live?: boolean;
37
+ ports: Map<string, ChannelPort>;
38
+ }
39
+ export interface ChannelPort {
40
+ samples?: number[];
41
+ expression?: Expression;
42
+ live?: boolean;
43
+ source: SourceLocation;
44
+ }
45
+ export interface ActiveRange {
46
+ start: number;
47
+ end: number;
48
+ source: SourceLocation;
49
+ }
50
+ export type Driver = ActiveRange & ({
51
+ kind: 'expr';
52
+ expression: Expression;
53
+ } | {
54
+ kind: 'ref';
55
+ input: string;
56
+ scale: number;
57
+ offset: number;
58
+ } | {
59
+ kind: 'register';
60
+ input: string;
61
+ scale: number;
62
+ offset: number;
63
+ freq: number;
64
+ shift: number;
65
+ });
66
+ export interface PathBinding extends ActiveRange {
67
+ curve: SceneObject;
68
+ freq: number;
69
+ shift: number;
70
+ offset: Vec3;
71
+ }
72
+ export interface AimBinding extends ActiveRange {
73
+ target: SceneObject;
74
+ }
75
+ export type PropertyEdit = (state: Authored) => void;
76
+ export interface Event {
77
+ frame: number;
78
+ object: SceneObject;
79
+ edit: PropertyEdit;
80
+ }
81
+ export interface Plan {
82
+ extensions: Extensions;
83
+ audioChannels: ReadonlySet<string>;
84
+ objects: SceneObject[];
85
+ channels: Channel[];
86
+ drivers: Map<string, Driver[]>;
87
+ events: Event[];
88
+ order: string[];
89
+ }
90
+ export declare const plans: WeakMap<CompiledScene, Plan>;
91
+ export declare const objectPath: (object: SceneObject) => string;
92
+ export declare const channelPath: (channel: Channel) => string;
93
+ export declare const positionStep: (object: SceneObject) => string;
94
+ export declare const worldStep: (object: SceneObject) => string;
95
+ export declare const translations: readonly ["tx", "ty", "tz"];
96
+ export declare const rotations: readonly ["rx", "ry", "rz"];
97
+ export declare const scales: readonly ["sx", "sy", "sz"];
98
+ export declare const vector: (p: Record<string, number>, keys: readonly [string, string, string]) => Vec3;
99
+ export declare const copyState: (state: Authored) => Authored;
100
+ export declare const active: (f: number, range: ActiveRange) => boolean;
101
+ export declare const isColor: (param: string) => boolean;
102
+ export declare function defaults(kind: ObjectKind): Authored;
103
+ export declare function readNumber(text: string, source: SourceLocation): number;
104
+ export declare function readFrame(text: string, source: SourceLocation): number;
105
+ export declare function checkArity(command: string, args: string[], counts: readonly number[], source: SourceLocation): void;
106
+ export declare function propertyEdit(command: string, args: string[], object: SceneObject, source: SourceLocation): PropertyEdit | undefined;
107
+ export declare const editCommands: Set<string>;
package/model.js ADDED
@@ -0,0 +1,181 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.editCommands = exports.isColor = exports.active = exports.copyState = exports.vector = exports.scales = exports.rotations = exports.translations = exports.worldStep = exports.positionStep = exports.channelPath = exports.objectPath = exports.plans = void 0;
4
+ exports.defaults = defaults;
5
+ exports.readNumber = readNumber;
6
+ exports.readFrame = readFrame;
7
+ exports.checkArity = checkArity;
8
+ exports.propertyEdit = propertyEdit;
9
+ const math_js_1 = require("./math.js");
10
+ const types_js_1 = require("./types.js");
11
+ exports.plans = new WeakMap();
12
+ const objectPath = (object) => '/obj/' + object.name;
13
+ exports.objectPath = objectPath;
14
+ const channelPath = (channel) => '/ch/' + channel.name;
15
+ exports.channelPath = channelPath;
16
+ const positionStep = (object) => (0, exports.objectPath)(object) + '/@position';
17
+ exports.positionStep = positionStep;
18
+ const worldStep = (object) => (0, exports.objectPath)(object) + '/@world';
19
+ exports.worldStep = worldStep;
20
+ exports.translations = ['tx', 'ty', 'tz'];
21
+ exports.rotations = ['rx', 'ry', 'rz'];
22
+ exports.scales = ['sx', 'sy', 'sz'];
23
+ const vector = (p, keys) => [p[keys[0]], p[keys[1]], p[keys[2]]];
24
+ exports.vector = vector;
25
+ const copyState = (state) => ({ ...state, parameters: { ...state.parameters } });
26
+ exports.copyState = copyState;
27
+ const active = (f, range) => f >= range.start && f <= range.end;
28
+ exports.active = active;
29
+ const isColor = (param) => /^(diff|amb|spec)[rgba]$/.test(param);
30
+ exports.isColor = isColor;
31
+ function defaults(kind) {
32
+ const parameters = {
33
+ tx: 0, ty: 0, tz: 0, rx: 0, ry: 0, rz: 0, sx: 1, sy: 1, sz: 1,
34
+ };
35
+ if (kind === 'geo' || kind === 'curve' || kind === 'light') {
36
+ Object.assign(parameters, { diffr: 1, diffg: 1, diffb: 1, diffa: 1,
37
+ ambr: 0, ambg: 0, ambb: 0, amba: 1, specr: 0, specg: 0, specb: 0, speca: 1 });
38
+ if (kind !== 'light')
39
+ parameters.shine = 0;
40
+ }
41
+ if (kind === 'camera')
42
+ Object.assign(parameters, { fovy: 45, znear: 0.1, zfar: 1000 });
43
+ return { parameters, up: math_js_1.worldUp, light: 'point', visible: true, enabled: true };
44
+ }
45
+ function readNumber(text, source) {
46
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) {
47
+ (0, types_js_1.fail)('invalid-number', 'Expected a finite number, got ' + JSON.stringify(text), source);
48
+ }
49
+ return (0, types_js_1.finite)(Number(text), 'Number', source);
50
+ }
51
+ function readFrame(text, source) {
52
+ const n = readNumber(text, source);
53
+ if (n < 0 || !Number.isSafeInteger(n) || !/^\+?\d+$/.test(text)) {
54
+ (0, types_js_1.fail)('invalid-frame', 'Expected a nonnegative integer frame, got ' + text, source);
55
+ }
56
+ return n;
57
+ }
58
+ function checkArity(command, args, counts, source) {
59
+ if (!counts.includes(args.length))
60
+ (0, types_js_1.fail)('invalid-operands', command + ': invalid argument count', source);
61
+ }
62
+ function propertyEdit(command, args, object, source) {
63
+ const numbers = (length) => {
64
+ checkArity(command, args, [length], source);
65
+ return args.map(s => readNumber(s, source));
66
+ };
67
+ const setRotation = (state, axes) => {
68
+ if (state.matrix)
69
+ (0, types_js_1.fail)('invalid-trs', 'Cannot rotate a matrix without TRS', source);
70
+ const trs = (0, math_js_1.decompose)((0, math_js_1.matrix)([0, 0, 0], axes, [1, 1, 1]), source);
71
+ exports.rotations.forEach((key, i) => { state.parameters[key] = trs.rotation[i]; });
72
+ };
73
+ switch (command) {
74
+ case 'position':
75
+ case 'translate':
76
+ case 'scale': {
77
+ const values = numbers(3);
78
+ return state => {
79
+ const keys = command === 'scale' ? exports.scales : exports.translations;
80
+ if (state.matrix && command === 'scale')
81
+ (0, types_js_1.fail)('invalid-trs', 'Cannot scale a matrix without TRS', source);
82
+ keys.forEach((key, i) => {
83
+ const original = state.parameters[key];
84
+ state.parameters[key] = (0, types_js_1.finite)(command === 'translate' ? original + values[i]
85
+ : command === 'scale' ? original * values[i] : values[i], key, source);
86
+ });
87
+ if (state.matrix)
88
+ state.matrix = [...state.matrix.slice(0, 12), ...(0, exports.vector)(state.parameters, exports.translations), 1];
89
+ };
90
+ }
91
+ case 'rotate': {
92
+ const [degrees, x, y, z] = numbers(4);
93
+ const axis = (0, math_js_1.normalize)([x, y, z]);
94
+ if (!axis.some(Boolean))
95
+ (0, types_js_1.fail)('invalid-rotation', 'Rotation axis must be nonzero', source);
96
+ const a = degrees * (Math.PI / 180);
97
+ return state => {
98
+ const rot = (v) => {
99
+ const c = Math.cos(a), s = Math.sin(a), p = (0, math_js_1.cross)(axis, v), k = (0, math_js_1.dot)(axis, v) * (1 - c);
100
+ return [v[0] * c + p[0] * s + k * axis[0], v[1] * c + p[1] * s + k * axis[1], v[2] * c + p[2] * s + k * axis[2]];
101
+ };
102
+ const [a1, a2, a3] = (0, math_js_1.euler)((0, exports.vector)(state.parameters, exports.rotations));
103
+ setRotation(state, [rot(a1), rot(a2), rot(a3)]);
104
+ };
105
+ }
106
+ case 'matrix': {
107
+ const m = numbers(16);
108
+ if (m[3] !== 0 || m[7] !== 0 || m[11] !== 0 || m[15] !== 1)
109
+ (0, types_js_1.fail)('invalid-matrix', 'Expected an affine matrix', source);
110
+ const trs = (0, math_js_1.decompose)(m, source);
111
+ return state => {
112
+ state.matrix = trs ? undefined : m;
113
+ exports.translations.forEach((key, i) => { state.parameters[key] = m[12 + i]; });
114
+ exports.rotations.forEach((key, i) => { state.parameters[key] = trs?.rotation[i] ?? 0; });
115
+ exports.scales.forEach((key, i) => { state.parameters[key] = trs?.scale[i] ?? Math.hypot(...(0, math_js_1.column)(m, i)); });
116
+ };
117
+ }
118
+ case 'diffuse':
119
+ case 'ambient':
120
+ case 'specular':
121
+ case 'shininess':
122
+ case 'fovy':
123
+ case 'znear':
124
+ case 'zfar': {
125
+ const prefix = command === 'diffuse' ? 'diff' : command === 'ambient' ? 'amb' : command === 'specular' ? 'spec' : undefined;
126
+ const keys = prefix ? [...'rgba'].map(c => prefix + c) : [command === 'shininess' ? 'shine' : command];
127
+ const values = numbers(keys.length);
128
+ if (!Object.hasOwn(object.authored.parameters, keys[0]))
129
+ (0, types_js_1.fail)('unsupported-parameter', 'Unsupported property: ' + command, source);
130
+ return state => { keys.forEach((key, i) => { state.parameters[key] = values[i]; }); };
131
+ }
132
+ case 'up':
133
+ case 'camera': {
134
+ if (object.kind !== 'camera')
135
+ (0, types_js_1.fail)('invalid-subject', command + ' requires a camera', source);
136
+ if (command === 'camera') {
137
+ if (args[0] !== 'lookat')
138
+ (0, types_js_1.fail)('invalid-operands', 'Expected camera lookat X Y Z', source);
139
+ args = args.slice(1);
140
+ }
141
+ const [x, y, z] = numbers(3);
142
+ const value = [x, y, z];
143
+ return state => {
144
+ if (command === 'up')
145
+ state.up = value;
146
+ if (command === 'camera')
147
+ state.focus = value;
148
+ if (state.focus) {
149
+ const axes = (0, math_js_1.aim)(math_js_1.identity, (0, exports.vector)(state.parameters, exports.translations), state.focus, state.up, -1, [1, 1, 1], source);
150
+ if (axes)
151
+ setRotation(state, axes);
152
+ }
153
+ };
154
+ }
155
+ case 'light': {
156
+ if (object.kind !== 'light')
157
+ (0, types_js_1.fail)('invalid-subject', 'light requires a light', source);
158
+ const [mode] = args;
159
+ checkArity(command, args, mode === 'spot' ? [1, 4] : [1], source);
160
+ const direction = args.slice(1).map(s => readNumber(s, source));
161
+ if (!['point', 'dir', 'directional', 'spot', 'on', 'off'].includes(mode)) {
162
+ (0, types_js_1.fail)('invalid-operands', 'Unsupported light mode: ' + mode, source);
163
+ }
164
+ return state => {
165
+ if (mode === 'on' || mode === 'off')
166
+ state.enabled = mode === 'on';
167
+ else
168
+ state.light = mode === 'dir' ? 'directional' : mode;
169
+ if (direction.length) {
170
+ const axes = (0, math_js_1.aim)(math_js_1.identity, [0, 0, 0], [direction[0], direction[1], direction[2]], math_js_1.worldUp, -1, [1, 1, 1], source);
171
+ if (axes)
172
+ setRotation(state, axes);
173
+ }
174
+ };
175
+ }
176
+ }
177
+ }
178
+ exports.editCommands = new Set([
179
+ 'position', 'translate', 'scale', 'rotate', 'matrix', 'diffuse', 'specular', 'ambient',
180
+ 'shininess', 'fovy', 'znear', 'zfar', 'up', 'camera', 'light',
181
+ ]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vim3d/core",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "A shared scene model for Vim3D.",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/vim3d/tree/master/js/packages/core",
@@ -20,6 +20,9 @@
20
20
  "bugs": {
21
21
  "url": "https://github.com/pyramation/vim3d/issues"
22
22
  },
23
+ "dependencies": {
24
+ "@vim3d/parser": "^0.2.1"
25
+ },
23
26
  "devDependencies": {
24
27
  "makage": "^0.8.0"
25
28
  },
package/registry.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import { type ExtensionContextDefinition, type ExtensionNodeType } from './types.js';
2
+ export type ContextStage = 'audio' | 'ch' | 'geo' | 'obj' | 'evaluate' | 'output' | 'reserved';
3
+ export interface ContextDefinition {
4
+ readonly name: string;
5
+ readonly stage: ContextStage;
6
+ readonly nodeTypes: readonly ExtensionNodeType[];
7
+ }
8
+ export declare const BUILTIN_CONTEXTS: readonly ContextDefinition[];
9
+ export interface ContextRegistry {
10
+ readonly contexts: readonly ContextDefinition[];
11
+ readonly get: (name: string) => ContextDefinition | undefined;
12
+ }
13
+ export declare function createContextRegistry(extensions?: readonly ExtensionContextDefinition[]): ContextRegistry;
14
+ export declare function allowedSource(target: ContextStage, source: ContextStage): boolean;
package/registry.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BUILTIN_CONTEXTS = void 0;
4
+ exports.createContextRegistry = createContextRegistry;
5
+ exports.allowedSource = allowedSource;
6
+ const types_js_1 = require("./types.js");
7
+ const ports = (type, ...names) => names.map(name => ({ name, type }));
8
+ const numeric = (defaults) => Object.entries(defaults)
9
+ .map(([name, value]) => ({ name, type: 'number', default: value }));
10
+ const audioSource = (type) => ({
11
+ type: 'audio:' + type,
12
+ inputs: [],
13
+ outputs: [...ports('object', 'signal'), ...ports('number', 'rms', 'peak')],
14
+ props: type === 'file' ? [{ name: 'asset', type: 'string', required: true }, ...numeric({ gain: 1 })]
15
+ : [{ name: 'device', type: 'string' }, ...numeric({ gain: 1 })],
16
+ evaluate: ({ path, props }, audio) => {
17
+ const gain = Math.abs(props.gain);
18
+ const rms = (0, types_js_1.finite)((audio?.rms ?? 0) * gain, path + '/rms');
19
+ const peak = (0, types_js_1.finite)((audio?.peak ?? 0) * gain, path + '/peak');
20
+ return { signal: { rms, peak }, rms, peak };
21
+ },
22
+ });
23
+ const audio = [
24
+ audioSource('file'), audioSource('mic'),
25
+ {
26
+ type: 'audio:fft',
27
+ inputs: ports('object', 'signal'),
28
+ outputs: [...ports('number', 'bass', 'mid', 'high', 'centroid', 'flux'), ...ports('object', 'spectrum')],
29
+ props: numeric({ fftSize: 2048, smoothing: 0.8 }),
30
+ evaluate: (_, data) => ({
31
+ bass: data?.bass ?? 0, mid: data?.mid ?? 0, high: data?.high ?? 0, centroid: data?.centroid ?? 0,
32
+ flux: data?.flux ?? 0, spectrum: data?.spectrum ?? [],
33
+ }),
34
+ },
35
+ {
36
+ type: 'audio:envelope',
37
+ inputs: ports('number', 'value'), outputs: ports('number', 'value'),
38
+ props: numeric({ attack: 0.01, release: 0.1 }),
39
+ evaluate: ({ inputs }, data) => ({ value: data?.rms ?? inputs.value ?? 0 }),
40
+ },
41
+ ];
42
+ const geo = [
43
+ {
44
+ type: 'geo:box', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ width: 1, height: 1, depth: 1 }),
45
+ evaluate: ({ props }) => ({ geometry: { primitive: 'box', args: [props.width, props.height, props.depth] } }),
46
+ },
47
+ {
48
+ type: 'geo:sphere', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ radius: 1, segments: 32 }),
49
+ evaluate: ({ props }) => ({ geometry: { primitive: 'sphere', args: [props.radius, props.radius, props.segments] } }),
50
+ },
51
+ {
52
+ type: 'geo:transform',
53
+ inputs: [...ports('object', 'geometry'), ...ports('number', 'tx', 'ty', 'tz', 'sx', 'sy', 'sz')],
54
+ outputs: ports('object', 'geometry'), props: [],
55
+ evaluate: ({ inputs }) => ({ geometry: {
56
+ kind: 'transform', geometry: inputs.geometry ?? null,
57
+ translate: [inputs.tx ?? 0, inputs.ty ?? 0, inputs.tz ?? 0], scale: [inputs.sx ?? 1, inputs.sy ?? 1, inputs.sz ?? 1],
58
+ } }),
59
+ },
60
+ {
61
+ type: 'geo:merge', inputs: ports('object', 'a', 'b'), outputs: ports('object', 'geometry'), props: [],
62
+ evaluate: ({ inputs }) => ({ geometry: { kind: 'merge', geometries: [inputs.a, inputs.b].filter(value => value !== undefined) } }),
63
+ },
64
+ ];
65
+ exports.BUILTIN_CONTEXTS = (0, types_js_1.freeze)([
66
+ { name: 'audio', stage: 'audio', nodeTypes: audio },
67
+ { name: 'ch', stage: 'ch', nodeTypes: [] },
68
+ { name: 'geo', stage: 'geo', nodeTypes: geo },
69
+ { name: 'obj', stage: 'obj', nodeTypes: [] },
70
+ { name: 'sim', stage: 'reserved', nodeTypes: [] },
71
+ ]);
72
+ function createContextRegistry(extensions = []) {
73
+ const contexts = new Map(exports.BUILTIN_CONTEXTS.map(context => [context.name, context]));
74
+ for (const context of extensions) {
75
+ if (typeof context.name !== 'string' || !/^[a-z][a-z0-9_-]*$/.test(context.name) ||
76
+ exports.BUILTIN_CONTEXTS.some(({ name }) => name === context.name)) {
77
+ (0, types_js_1.fail)('invalid-extension-context', 'Invalid or reserved extension context: ' + context.name);
78
+ }
79
+ if (contexts.has(context.name))
80
+ (0, types_js_1.fail)('duplicate-extension-context', 'Duplicate extension context: ' + context.name);
81
+ if ((context.stage !== 'evaluate' && context.stage !== 'output') || !Array.isArray(context.nodeTypes)) {
82
+ (0, types_js_1.fail)('invalid-extension-definition', 'Invalid stage or node types for /' + context.name);
83
+ }
84
+ contexts.set(context.name, Object.freeze({ ...context, nodeTypes: Object.freeze([...context.nodeTypes]) }));
85
+ }
86
+ return Object.freeze({ contexts: Object.freeze([...contexts.values()]), get: (name) => contexts.get(name) });
87
+ }
88
+ function allowedSource(target, source) {
89
+ switch (target) {
90
+ case 'audio': return source === 'audio';
91
+ case 'ch': return source === 'audio' || source === 'ch';
92
+ case 'geo': return source === 'audio' || source === 'ch' || source === 'geo';
93
+ case 'obj': return source === 'audio' || source === 'ch' || source === 'geo' || source === 'obj';
94
+ case 'evaluate':
95
+ case 'output': return source !== 'output' && source !== 'reserved';
96
+ case 'reserved': return false;
97
+ }
98
+ }