Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Merge the semantics of field and driver expressions (issue #98, part 2)

Nguyen Xuan An9a6cca757950
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 851627a3..2506aef1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,7 +2,7 @@
## Unreleased
-- Use one expression language for fields and drivers (issue #98). `src/expression.js` now holds what `src/mesh-fields.js` and `src/motion-expression.js` shared by copy: the node and depth limits, number literals, the table of math operators with their operand counts, and the lifting of an operator over numbers or vectors. Each file is now a dialect that adds only its own sources (attributes, noise and vectors for fields; `time` and node reads for motion). Recipe syntax is unchanged. 160,000 random expressions, plus hostile and malformed ones, give the same values, reads and error messages as before, except that the operator list in a field's "unknown operator" message is in a new order. The two languages still differ where they did: a field turns `div` by zero, a negative `sqrt` and an overflowing `pow` into 0, a motion expression keeps them as a non-finite error; `if` is true above 0 in motion and not 0 in fields; `smoothstep` with equal edges is a step in fields. Fixed-arity calls keep field evaluation at the old speed (about 70 ms for 200,000 elements). The bundle did not shrink: `entry:agent-scene+lazy` grew by about 385 bytes gzip, because the two copies compressed against each other.
+- Use one expression language for fields and drivers (issue #98). `src/expression.js` holds the limits, number literals, operator table, syntax and hostile-input checks; `src/mesh-fields.js` (per mesh element: attributes, noise, random, vectors) and `src/motion-expression.js` (per time: `time`, node reads) only add their own inputs, and each rejects the other's with a message that names the context. **This changes driver expressions** (neither language was released): an operator with one operand may be written bare, `{"neg": x}`, in drivers as in fields; `if` takes its second operand when the condition is not 0 (a driver used above 0); `sqrt` of a negative, `pow` overflow and `mod` by 0 give 0 instead of an error; `smoothstep` with equal edges is a step; `div` by 0 is still a non-finite error in a driver, because a hostile-input test pins it, and 0 in a field. Drivers gain `ceil`, `round`, `sign`, `lte`, `gte`, `eq`, `and`, `or`, `not` and booleans; fields gain `atan2` and `saturate`. The unknown-operator hint of fields lists operators in a new order. Error messages for a malformed driver changed in wording and are all TypeErrors. The MCP schema for drivers now points at the field language instead of listing operators (schemas 183,741 to 183,762 bytes), and the `scene_capabilities` budget rises from 3,050 to 3,100 bytes for two operator names.
- Add `decimate`, `remesh` and generated levels of detail (issue #40). `decimate` (a `ratio` of triangles) is a quadric edge collapse of our own that keeps open boundaries, the borders between tags and the tags themselves; it measured 0.25 to 0.85 of the Hausdorff error of meshoptimizer 1.3.0 on the same meshes and adds no dependency, but takes about 2.5 s on 100k triangles where meshoptimizer takes 0.09 s. `remesh` (`voxelSize` or `resolution`, at most 192 per side and 4,194,304 cells, checked before allocation) builds a closed quad surface from a BVH signed distance with surface nets. Both are edits and stack nodes, in the MCP schemas, and load on demand with the mesh code. `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` (also in `67js/addons/mesh`) return levels with a measured error for runtime selection (issue #37). Four decimate and two remesh cases join the Blender comparison, compared by volume, area and Hausdorff distance because face counts differ.
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 644c2e22..056b447b 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 3050,
+ "scene_capabilities": 3100,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/agent-motion.md b/docs/agent-motion.md
index ba83869a..cc91fdc8 100644
--- a/docs/agent-motion.md
+++ b/docs/agent-motion.md
@@ -165,15 +165,12 @@ Not covered yet: `use_*` switches on `child_of`, `limit_scale`, `copy_transforms
XYZ in degrees) or `{ "kind": "material", "id", "property" }` for `emission`, `metallic` and `roughness`, or with a
`component` for `color` and `emissiveColor` (`x`, `y`, `z` for red, green, blue). A driven property cannot also have a track.
-An expression is JSON data and is never run as code: a number, the string `"time"`, a read of another node
-`{ "node", "property", "component", "space" }`, or one operator object such as `{ "mul": ["time", 2] }`. Operators: `add`,
-`mul`, `min`, `max` (2 to 8 operands), `sub`, `div`, `pow`, `mod`, `atan2`, `gt`, `lt`, `neg`, `abs`, `sin`, `cos` (radians),
-`sqrt`, `floor`, `fract`, `saturate`, `clamp(x, low, high)`, `mix(a, b, t)`, `smoothstep(low, high, x)` and
-`if(condition, then, otherwise)`. An expression has at most 64 parts and 8 levels, and a result that is not finite is an
-error. It is the motion dialect of the one expression language in `src/expression.js`: the operator names, operand counts, limits and
-hostile-input checks are shared with the field expressions of the mesh addon. Two edge cases differ on purpose. A motion expression
-keeps plain arithmetic, so `div` by zero, a negative `sqrt` and `pow` overflow give a non-finite result that is an error, where a
-field gives 0. And `if` takes `then` when the condition is above 0, where a field takes it when the condition is not 0.
+An expression is JSON data and is never run as code. It is the motion context of the one expression language described in
+[field expressions](mesh.md#field-expressions): the same operators with the same results, the same syntax, and limits of 64
+parts and 8 levels. Where a field reads mesh attributes, a driver reads `"time"` (seconds) or a node
+`{ "node", "property", "component", "space" }`, for example `{ "mul": ["time", 2] }`; vectors, attributes and noise are field
+inputs and are rejected here with a message that says so. `sin` and `cos` take radians. One difference remains: `div` by zero
+gives 0 in a field but is a non-finite result in a driver, which is an error, so a mistaken driver is reported.
### Evaluation order
diff --git a/docs/mesh.md b/docs/mesh.md
index 7b585e83..ffb23978 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -210,8 +210,9 @@ as Blender's Apply modifier, which leaves the result unchanged.
A field expression is plain JSON that computes one number, or one vector, for each point or face of a mesh. It is
data and never code: `src/mesh-fields.js` reads it against a fixed table of operators, compiles it once into
-closures over typed arrays, and checks the limits before it evaluates anything. It is the field dialect of the one
-expression language in `src/expression.js`, which motion drivers share (see [agent motion](agent-motion.md)). No string is executed, and no input
+closures over typed arrays, and checks the limits before it evaluates anything. This is the one expression language of the
+engine, in `src/expression.js`; motion drivers use it with `time` and node reads in place of attributes (see
+[agent motion](agent-motion.md)). No string is executed, and no input
string is used as a property name, so a recipe written by an agent that follows injected instructions cannot run code
or reach `__proto__` or `constructor`. The same expression gives the same bytes on every run.
@@ -221,13 +222,15 @@ or reach `__proto__` or `constructor`. The same expression gives the same bytes
{ "gt": [{ "dot": [{ "attr": "normal" }, [0, 1, 0]] }, 0.9] }
```
-A number is a constant, `true` and `false` are 1 and 0, and an array of three numbers is a constant vector.
+A number is a constant, `true` and `false` are 1 and 0, and an array of three numbers is a constant vector. An operator takes
+its operands as an array; one with a single operand may write it bare, `{ "neg": x }`.
Operators that take numbers also take vectors and work on each component; a number spreads to all three.
| Group | Operators |
| --- | --- |
-| Math | `add` `mul` `min` `max` (2 to 8 operands), `sub` `div` `mod` `pow`, `clamp` `mix` `smoothstep` (3), `neg` `abs` `sqrt` `sin` `cos` `floor` `ceil` `round` `fract` `sign` (1). `div` and `mod` by 0 give 0. |
+| Math | `add` `mul` `min` `max` (2 to 8 operands), `sub` `div` `mod` `pow` `atan2`, `clamp` `mix` `smoothstep` (3), `neg` `abs` `sqrt` `sin` `cos` `floor` `ceil` `round` `fract` `sign` `saturate` (1). `div` and `mod` by 0, a negative `sqrt` and an overflowing `pow` give 0; `smoothstep` with equal edges is a step. |
| Comparison and logic | `lt` `lte` `gt` `gte` `eq` give 1 or 0; `and` `or` `not`; `if: [condition, a, b]` |
+| Motion only | `"time"` and `{ "node", "property", "component", "space" }` read time and node values in a driver; a field rejects them, and a driver rejects the field inputs below. |
| Vectors | `vec: [x, y, z]`, `dot` `cross` `distance`, `length` `normalize`, `x` `y` `z` read a component |
| Attributes | `{ "attr": "position" \| "normal" }` with optional `component`, `{ "attr": "index" }`, `{ "attr": "tag", "name": "top" }` |
| Random | `{ "noise": { "scale", "seed", "octaves", "at" } }` smooth value noise in 0 to 1 at a position (default the element's), `{ "random": { "seed" } }` a number in 0 to 1 per element |
diff --git a/docs/parity.md b/docs/parity.md
index 375de635..cf9cc976 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -117,7 +117,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Physics > Particle Instance Modifier | missing | No particle system. | | #63 |
| Modeling > Modifiers > Physics > Particle System Modifier | missing | No particle system. | | #63 |
| Modeling > Modifiers > Physics > Soft Body Modifier | missing | No soft bodies. | | #62 |
-| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they share one evaluator, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |
+| Modeling > Modifiers > Geometry Nodes Modifier | partial | Bounded JSON field expressions drive `set_position`, `displace`, a `field` selection rule and `instances`; they are one language, `src/expression.js`, with motion drivers. There is no node graph, no loops, no custom node groups, and no realize, curve or volume nodes. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [pillar-court task](../bench/agent-modeling/tasks.mjs) | #43 |
| Modeling > Geometry Nodes | partial | Fields over attributes, noise and math (position, normal, index, tags), Set Position, Instance on Points (grid, scatter, surface) and Displace. Noise is not Blender's noise function, and there is no Blender comparison for instancing. Issue #43 chose bounded JSON expressions and not a visual editor. | [src/mesh-fields.js](../src/mesh-fields.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js) | #43 |
| Modeling > Transform | partial | Node transforms, and `translate` on a selection with falloff. There is no rotate or scale on a selection. | | |
| Sculpting & Painting > Brushes | out of scope | Brush settings for a hand. Strokes have explicit parameters. | | |
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 7401b2b2..17bf993e 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -33,7 +33,7 @@ const nodeFields = {
rotation: quaternion.optional().describe('Nonzero local XYZW quaternion. The backend normalizes it.'),
scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),
};
-const fieldExpression = z.union([finite, z.boolean(), vector3, z.record(z.string(), z.unknown())]).describe('Field expression, plain JSON and never code. A number, a boolean or [x,y,z] is a constant; an object holds one operator: math add mul sub div mod pow min max clamp mix smoothstep neg abs sqrt sin cos floor ceil round fract sign; comparison lt lte gt gte eq; logic and or not if [cond,a,b]; vectors vec [x,y,z] dot cross distance length normalize x y z; sources {"attr":"position"|"normal"|"index"|"tag","component":"x"|"y"|"z","name":tag}, {"noise":{"scale":3,"seed":7,"octaves":1}} in 0..1, {"random":{"seed":1}} per element in 0..1. Example: {"mul":[{"attr":"position","component":"y"},0.5]}. At most 64 nodes, depth 12, 250000 elements.');
+const fieldExpression = z.union([finite, z.boolean(), vector3, z.record(z.string(), z.unknown())]).describe('Field expression, plain JSON and never code; driver expressions use the same language. A number, a boolean or [x,y,z] is a constant; an object holds one operator: math add mul sub div mod pow atan2 min max clamp saturate mix smoothstep neg abs sqrt sin cos floor ceil round fract sign; comparison lt lte gt gte eq; logic and or not if [cond,a,b]; vectors vec [x,y,z] dot cross distance length normalize x y z; sources {"attr":"position"|"normal"|"index"|"tag","component":"x"|"y"|"z","name":tag}, {"noise":{"scale":3,"seed":7,"octaves":1}} in 0..1, {"random":{"seed":1}} per element in 0..1. Example: {"mul":[{"attr":"position","component":"y"},0.5]}. At most 64 nodes, depth 12, 250000 elements.');
const instanceCount = z.number().int().min(1).max(2048);
const instanceSpec = z.strictObject({
grid: z.strictObject({ counts: z.tuple([instanceCount, instanceCount, instanceCount]), spacing: vector3 }).optional().describe('Grid of counts[0] x counts[1] x counts[2] points centred on the group.'),
@@ -345,8 +345,8 @@ const expression = z.lazy(() => z.union([
z.number().min(-1e6).max(1e6),
z.literal('time'),
z.strictObject({ node: identifier, property: z.enum(['translation', 'rotation', 'scale']), component: axisName, space: z.enum(['local', 'world']).optional() }),
- z.record(z.string().max(24), z.array(expression).min(1).max(8)),
-])).describe('Number, "time", {"node","property","component","space"} read, or one operator such as {"mul":[2,"time"]}. Operators: add mul min max sub div pow mod atan2 gt lt neg abs sin cos sqrt floor fract saturate clamp mix smoothstep if. At most 64 parts, 8 deep.');
+ z.record(z.string().max(24), z.union([z.array(expression).min(1).max(8), expression])),
+])).describe('Number, "time", {"node","property","component","space"} read, or an operator like {"mul":[2,"time"]}, {"neg":x} too. Operators as in field expressions (scene_capabilities), no vectors, attributes or noise. At most 64 parts, 8 deep.');
const influence = z.union([unit, expression]).optional().describe('0 to 1 blend of the constraint, or an expression.');
const constraint = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('copy_location'), node: identifier, target: identifier, axes: axisNames.optional(), invert: axisNames.optional(), offset: z.boolean().optional(), space: constraintSpace, influence }),
diff --git a/src/expression.js b/src/expression.js
index a4eff30c..5f75b1ff 100644
--- a/src/expression.js
+++ b/src/expression.js
@@ -1,23 +1,34 @@
-// One bounded expression language, two dialects. An expression is JSON data, never code: it is read by walking plain
-// objects against a fixed table of operators held in a Map, compiled once into closures and checked against its limits
-// before anything runs. No string is executed or used as a property name.
+import { denseArray } from './motion-validation.js';
+
+// One bounded expression language. An expression is JSON data, never code: it is read by walking plain objects against
+// a fixed table of operators held in a Map, compiled once into closures and checked against its limits before
+// anything runs. No string is executed or used as a property name.
+//
+// The operators are the same everywhere, and so are their results: `div`, `mod` and `pow` give 0 instead of a
+// non-finite number, `sqrt` of a negative is 0, `if` takes its second operand when the condition is not 0, and
+// `smoothstep` with equal edges is a step. An operator's operands are an array, `{"add": [1, 2]}`; an operator with one
+// operand may also write it bare, `{"neg": x}`.
//
-// This module owns what both dialects share: the limits check, number literals, the walk, and the table of math
-// operators with their operand counts. A dialect adds what only it has:
-// - `src/mesh-fields.js`: element attributes, noise and vectors, evaluated once per mesh element.
-// - `src/motion-expression.js`: motion time and node reads, evaluated once per sampled time.
+// What differs is the context an expression runs in, and so the inputs it may read:
+// - field (`src/mesh-fields.js`): per mesh element. Attributes, noise, random, vectors and vector operators.
+// - motion (`src/motion-expression.js`): per sampled time. `time` and reads of node values.
+// A context rejects the other's inputs with a message that says so.
//
// A compiled value is { kind: 'scalar', evaluate(argument) } or { kind: 'vector', parts: [evaluateX, evaluateY,
-// evaluateZ] }. The argument is whatever the dialect evaluates over: an element index or a motion context. Only the
-// field dialect makes vectors.
+// evaluateZ] }. The argument is an element index or a motion context. Only fields make vectors.
//
-// A dialect is { maxNodes, maxDepth, messages: { nodes, depth, number }, reject(message, state), compileOther(node,
-// state, depth) }. `reject` returns the Error to throw for a message. `state` holds `dialect` and `nodeCount` plus
-// anything the dialect needs while compiling.
+// A dialect is { name, accepts, maxNodes, maxDepth, operators, sourceNames, reject(message, state), compileInput(node,
+// state, depth) }. `accepts` completes "use ...", `operators` is a Map, `reject` returns the Error to throw, and
+// `compileInput` returns a compiled value for an input of its own context or undefined. `state` holds `dialect` and
+// `nodeCount` plus anything the dialect needs while compiling.
export const MAX_LITERAL = 1e6;
export const MAX_OPERANDS = 8;
export const COMPONENTS = Object.freeze({ x: 0, y: 1, z: 2 });
+const MAX_REPORTED_KEY_LENGTH = 24;
+const VECTOR_OPERATOR_NAMES = Object.freeze(['vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z']);
+const FIELD_INPUT_NAMES = new Set([...VECTOR_OPERATOR_NAMES, 'attr', 'noise', 'random']);
+const OPERAND_WORDS = new Map([[1, 'one operand'], [2, 'two operands'], [3, 'three operands']]);
export const scalarValue = evaluate => ({ kind: 'scalar', evaluate });
export const constantScalar = number => scalarValue(() => number);
@@ -31,60 +42,19 @@ export function isBoundedNumber(value) {
return typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= MAX_LITERAL;
}
-/** Compile one node. Counts it, checks the limits and number literals, and hands every other node to the dialect. */
-export function compileNode(node, state, depth) {
- const { dialect } = state;
- state.nodeCount += 1;
- if (state.nodeCount > dialect.maxNodes) throw dialect.reject(dialect.messages.nodes, state);
- if (depth > dialect.maxDepth) throw dialect.reject(dialect.messages.depth, state);
- if (typeof node === 'number') {
- if (!isBoundedNumber(node)) throw dialect.reject(dialect.messages.number, state);
- return constantScalar(node);
- }
- return dialect.compileOther(node, state, depth);
+export function isPlainObject(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const prototype = Object.getPrototypeOf(value);
+ return prototype === Object.prototype || prototype === null;
}
-/**
- * The math operators both languages have, as pure functions of numbers with the operand counts they take. The two
- * languages disagree on the edge cases of a few of them, so each dialect passes its own `semantics`: divide, modulo,
- * power, squareRoot and smoothstep. A comparison gives 1 or 0. `if` is not here: what counts as true differs.
- */
-export function createMathOperators({ divide, modulo, power, squareRoot, smoothstep }) {
- const entry = (min, max, compute) => ({ min, max, compute });
- return new Map([
- ['add', entry(2, MAX_OPERANDS, (left, right) => left + right)],
- ['mul', entry(2, MAX_OPERANDS, (left, right) => left * right)],
- ['min', entry(2, MAX_OPERANDS, Math.min)],
- ['max', entry(2, MAX_OPERANDS, Math.max)],
- ['sub', entry(2, 2, (left, right) => left - right)],
- ['div', entry(2, 2, divide)],
- ['mod', entry(2, 2, modulo)],
- ['pow', entry(2, 2, power)],
- ['clamp', entry(3, 3, (input, low, high) => Math.min(high, Math.max(low, input)))],
- ['mix', entry(3, 3, (start, end, fraction) => start + (end - start) * fraction)],
- ['smoothstep', entry(3, 3, smoothstep)],
- ['neg', entry(1, 1, number => -number)],
- ['abs', entry(1, 1, Math.abs)],
- ['sqrt', entry(1, 1, squareRoot)],
- ['sin', entry(1, 1, Math.sin)],
- ['cos', entry(1, 1, Math.cos)],
- ['floor', entry(1, 1, Math.floor)],
- ['fract', entry(1, 1, number => number - Math.floor(number))],
- ['lt', entry(2, 2, (left, right) => (left < right ? 1 : 0))],
- ['gt', entry(2, 2, (left, right) => (left > right ? 1 : 0))],
- ]);
+export function describeKey(key) {
+ const clipped = key.length > MAX_REPORTED_KEY_LENGTH ? `${key.slice(0, MAX_REPORTED_KEY_LENGTH)}...` : key;
+ return JSON.stringify(clipped);
}
-/**
- * Turn an operator's pure function of numbers into a builder over compiled operands. A number operand gives a number.
- * Where an operand is a vector, the function runs on each component and a number is spread to all three.
- * Operators with more than three operands fold left to right: add, mul, min, max.
- */
-export function buildLifted({ max, compute }) {
- const lifted = lift(compute);
- if (max <= 3) return lifted;
- return operands => operands.slice(1).reduce((total, next) => lifted([total, next]), operands[0]);
-}
+// ---------------------------------------------------------------------------------------------------------------
+// Operators.
// Fixed-arity calls, not a spread: fields run this once per mesh element.
function applyAcross(compute, evaluators) {
@@ -94,12 +64,173 @@ function applyAcross(compute, evaluators) {
return argument => compute(first(argument), second(argument), third(argument));
}
-function lift(compute) {
- return operands => {
+/**
+ * Build an operator from a pure function of numbers. Where an operand is a vector, the function runs on each component
+ * and a number is spread to all three. Operators with more than three operands fold left to right: add, mul, min, max.
+ */
+export function liftOperator(min, max, compute) {
+ const lifted = operands => {
if (operands.every(operand => operand.kind === 'scalar')) {
return scalarValue(applyAcross(compute, operands.map(operand => operand.evaluate)));
}
const vectorPart = axis => applyAcross(compute, operands.map(operand => partsOf(operand)[axis]));
return vectorValue(vectorPart(0), vectorPart(1), vectorPart(2));
};
+ const build = max <= 3 ? lifted : operands => operands.slice(1).reduce((total, next) => lifted([total, next]), operands[0]);
+ return { min, max, build };
+}
+
+export function requireScalar(value, label) {
+ if (value.kind !== 'scalar') throw new TypeError(`${label} needs a number, not a vector.`);
+ return value.evaluate;
+}
+
+function compareOperator(compute) {
+ const build = ([left, right]) => {
+ const leftEvaluate = requireScalar(left, 'a comparison');
+ const rightEvaluate = requireScalar(right, 'a comparison');
+ return scalarValue(argument => (compute(leftEvaluate(argument), rightEvaluate(argument)) ? 1 : 0));
+ };
+ return { min: 2, max: 2, build };
+}
+
+function logicOperator(isAnd) {
+ const build = operands => {
+ const evaluators = operands.map(operand => requireScalar(operand, 'a logic operator'));
+ return scalarValue(argument => {
+ for (const evaluate of evaluators) {
+ const isTrue = evaluate(argument) !== 0;
+ if (isAnd && !isTrue) return 0;
+ if (!isAnd && isTrue) return 1;
+ }
+ return isAnd ? 1 : 0;
+ });
+ };
+ return { min: 2, max: MAX_OPERANDS, build };
+}
+
+function notOperator() {
+ const build = ([operand]) => {
+ const evaluate = requireScalar(operand, 'not');
+ return scalarValue(argument => (evaluate(argument) === 0 ? 1 : 0));
+ };
+ return { min: 1, max: 1, build };
+}
+
+function ifOperator() {
+ const build = ([condition, whenTrue, whenFalse]) => {
+ const test = requireScalar(condition, 'if');
+ const [trueX, trueY, trueZ] = partsOf(whenTrue);
+ const [falseX, falseY, falseZ] = partsOf(whenFalse);
+ if (whenTrue.kind === 'scalar' && whenFalse.kind === 'scalar') {
+ return scalarValue(argument => (test(argument) !== 0 ? trueX(argument) : falseX(argument)));
+ }
+ return vectorValue(
+ argument => (test(argument) !== 0 ? trueX(argument) : falseX(argument)),
+ argument => (test(argument) !== 0 ? trueY(argument) : falseY(argument)),
+ argument => (test(argument) !== 0 ? trueZ(argument) : falseZ(argument)),
+ );
+ };
+ return { min: 3, max: 3, build };
+}
+
+function finiteOrZero(number) {
+ return Number.isFinite(number) ? number : 0;
+}
+
+function smoothstep(edgeStart, edgeEnd, input) {
+ if (edgeStart === edgeEnd) return input < edgeStart ? 0 : 1;
+ const fraction = Math.min(1, Math.max(0, (input - edgeStart) / (edgeEnd - edgeStart)));
+ return fraction * fraction * (3 - 2 * fraction);
+}
+
+/** A new Map of the operators every context has; a dialect adds its own to it. */
+export function createOperators() {
+ return new Map([
+ ['add', liftOperator(2, MAX_OPERANDS, (left, right) => left + right)],
+ ['mul', liftOperator(2, MAX_OPERANDS, (left, right) => left * right)],
+ ['min', liftOperator(2, MAX_OPERANDS, Math.min)],
+ ['max', liftOperator(2, MAX_OPERANDS, Math.max)],
+ ['sub', liftOperator(2, 2, (left, right) => left - right)],
+ ['div', liftOperator(2, 2, (left, right) => (right === 0 ? 0 : left / right))],
+ ['mod', liftOperator(2, 2, (left, right) => (right === 0 ? 0 : left - right * Math.floor(left / right)))],
+ ['pow', liftOperator(2, 2, (base, exponent) => finiteOrZero(Math.pow(base, exponent)))],
+ ['atan2', liftOperator(2, 2, Math.atan2)],
+ ['clamp', liftOperator(3, 3, (input, low, high) => Math.min(high, Math.max(low, input)))],
+ ['mix', liftOperator(3, 3, (start, end, fraction) => start + (end - start) * fraction)],
+ ['smoothstep', liftOperator(3, 3, smoothstep)],
+ ['neg', liftOperator(1, 1, number => -number)],
+ ['abs', liftOperator(1, 1, Math.abs)],
+ ['sqrt', liftOperator(1, 1, number => (number < 0 ? 0 : Math.sqrt(number)))],
+ ['sin', liftOperator(1, 1, Math.sin)],
+ ['cos', liftOperator(1, 1, Math.cos)],
+ ['floor', liftOperator(1, 1, Math.floor)],
+ ['ceil', liftOperator(1, 1, Math.ceil)],
+ ['round', liftOperator(1, 1, Math.round)],
+ ['fract', liftOperator(1, 1, number => number - Math.floor(number))],
+ ['sign', liftOperator(1, 1, Math.sign)],
+ ['saturate', liftOperator(1, 1, number => Math.min(1, Math.max(0, number)))],
+ ['lt', compareOperator((left, right) => left < right)],
+ ['lte', compareOperator((left, right) => left <= right)],
+ ['gt', compareOperator((left, right) => left > right)],
+ ['gte', compareOperator((left, right) => left >= right)],
+ ['eq', compareOperator((left, right) => left === right)],
+ ['and', logicOperator(true)],
+ ['or', logicOperator(false)],
+ ['not', notOperator()],
+ ['if', ifOperator()],
+ ]);
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// The walk.
+
+function describeOperandCount({ min, max }) {
+ return min === max ? OPERAND_WORDS.get(min) : `${min} to ${max} operands`;
+}
+
+function compileOperator(name, operand, state, depth) {
+ const { dialect } = state;
+ const operator = dialect.operators.get(name);
+ if (!operator) {
+ const names = [...dialect.operators.keys(), ...dialect.sourceNames];
+ throw dialect.reject(`unknown operator ${describeKey(name)}. Use one of ${names.join(', ')}.`, state);
+ }
+ const isBare = operator.max === 1 && !(Array.isArray(operand) && operand.length === 1);
+ const operands = isBare ? [operand] : operand;
+ const arityMessage = `${name} takes ${describeOperandCount(operator)}.`;
+ if (!Array.isArray(operands)) throw dialect.reject(arityMessage, state);
+ denseArray(operands, MAX_OPERANDS, `${name} operands`);
+ if (operands.length < operator.min || operands.length > operator.max) throw dialect.reject(arityMessage, state);
+ return operator.build(operands.map(child => compileNode(child, state, depth + 1)));
+}
+
+// The context an input belongs to, when it is not an operator.
+function contextOfInput(node) {
+ if (node === 'time' || (isPlainObject(node) && Object.hasOwn(node, 'node'))) return 'motion';
+ if (Array.isArray(node) || (isPlainObject(node) && (Object.hasOwn(node, 'attr') || FIELD_INPUT_NAMES.has(Object.keys(node)[0])))) return 'field';
+ return null;
+}
+
+/** Compile one node. Counts it, checks the limits and literals, then reads an input or an operator. */
+export function compileNode(node, state, depth) {
+ const { dialect } = state;
+ state.nodeCount += 1;
+ if (state.nodeCount > dialect.maxNodes) throw dialect.reject(`more than ${dialect.maxNodes} nodes.`, state);
+ if (depth > dialect.maxDepth) throw dialect.reject(`nests deeper than ${dialect.maxDepth} levels.`, state);
+ if (typeof node === 'number') {
+ if (!isBoundedNumber(node)) throw dialect.reject(`a number must be finite and within ${MAX_LITERAL}.`, state);
+ return constantScalar(node);
+ }
+ if (typeof node === 'boolean') return constantScalar(node ? 1 : 0);
+ const input = dialect.compileInput(node, state, depth);
+ if (input) return input;
+ const foreignContext = contextOfInput(node);
+ if (foreignContext && foreignContext !== dialect.name) {
+ throw dialect.reject(`this is a ${foreignContext} input and a ${dialect.name} expression cannot use it. A ${dialect.name} expression takes ${dialect.accepts}.`, state);
+ }
+ if (!isPlainObject(node)) throw dialect.reject(`use ${dialect.accepts}.`, state);
+ const keys = Object.keys(node);
+ if (keys.length !== 1) throw dialect.reject(`an operator object has exactly one key, such as {"add": [1, 2]}; got ${keys.length}.`, state);
+ return compileOperator(keys[0], node[keys[0]], state, depth);
}
diff --git a/src/mesh-fields.js b/src/mesh-fields.js
index dc85154d..b421e9fa 100644
--- a/src/mesh-fields.js
+++ b/src/mesh-fields.js
@@ -2,12 +2,11 @@ import { TAG_PREFIX, meshTags } from './mesh-data.js';
import { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK, FIELD_ATTRIBUTES } from './mesh-operations.js';
import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';
import {
- COMPONENTS, MAX_LITERAL, MAX_OPERANDS, buildLifted, compileNode, constantScalar, createMathOperators, isBoundedNumber, partsOf,
- scalarValue, vectorValue,
+ COMPONENTS, compileNode, createOperators, describeKey, isBoundedNumber, isPlainObject, requireScalar, scalarValue, vectorValue,
} from './expression.js';
-// Bounded field expressions: a small JSON language that computes one value per mesh element (a number, or a vector
-// of three numbers) from attributes, noise and math. Agents may be following instructions injected into their input,
+// Bounded field expressions: the field context of the one expression language in expression.js. It computes one value
+// per mesh element (a number, or a vector of three numbers) from attributes, noise and math. Agents may be following instructions injected into their input,
// so an expression is data and never code: it is read by walking plain objects against a fixed table of operators,
// compiled once into closures over typed arrays, and checked against its limits before anything is evaluated.
// No string is ever executed or used as a property name: operators come from a Map, and the only other strings
@@ -23,7 +22,6 @@ import {
const MAX_NOISE_OCTAVES = 4;
const MAX_NOISE_SCALE = 1000;
const MAX_SEED = 0x7fffffff;
-const MAX_REPORTED_KEY_LENGTH = 24;
const TAG_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
const KIND_NAMES = Object.freeze({ scalar: 'number', vector: 'vector' });
@@ -31,11 +29,6 @@ function fieldError(message) {
return new TypeError(`Field expression: ${message}`);
}
-function describeKey(key) {
- const clipped = key.length > MAX_REPORTED_KEY_LENGTH ? `${key.slice(0, MAX_REPORTED_KEY_LENGTH)}...` : key;
- return JSON.stringify(clipped);
-}
-
// ---------------------------------------------------------------------------------------------------------------
// Hashing and noise. Integer hashing keeps results identical on every platform.
@@ -90,63 +83,18 @@ function fractalNoise(x, y, z, seed, octaves) {
// ---------------------------------------------------------------------------------------------------------------
// Field operators: the math operators come from expression.js, lifted to vectors. What is here is the part only
// fields have: vectors, comparisons and logic that need numbers, and the safe edge cases that keep a value finite.
-
-function requireScalar(value, label) {
- if (value.kind !== 'scalar') throw fieldError(`${label} needs a number, not a vector.`);
- return value.evaluate;
-}
+// ---------------------------------------------------------------------------------------------------------------
+// Vector operators, the part of the language only fields have. The scalar operators come from expression.js.
function requireVector(value, label) {
if (value.kind !== 'vector') throw fieldError(`${label} needs a vector.`);
return value.parts;
}
-function compareScalars(compute) {
- return ([left, right]) => {
- const leftEvaluate = requireScalar(left, 'a comparison');
- const rightEvaluate = requireScalar(right, 'a comparison');
- return scalarValue(index => (compute(leftEvaluate(index), rightEvaluate(index)) ? 1 : 0));
- };
-}
-
-function branch([condition, whenTrue, whenFalse]) {
- const test = requireScalar(condition, 'if');
- const [trueX, trueY, trueZ] = partsOf(whenTrue);
- const [falseX, falseY, falseZ] = partsOf(whenFalse);
- if (whenTrue.kind === 'scalar' && whenFalse.kind === 'scalar') {
- return scalarValue(index => (test(index) !== 0 ? trueX(index) : falseX(index)));
- }
- return vectorValue(
- index => (test(index) !== 0 ? trueX(index) : falseX(index)),
- index => (test(index) !== 0 ? trueY(index) : falseY(index)),
- index => (test(index) !== 0 ? trueZ(index) : falseZ(index)),
- );
-}
-
function finiteOrZero(number) {
return Number.isFinite(number) ? number : 0;
}
-function smoothstep(edgeStart, edgeEnd, input) {
- if (edgeStart === edgeEnd) return input < edgeStart ? 0 : 1;
- const fraction = Math.min(1, Math.max(0, (input - edgeStart) / (edgeEnd - edgeStart)));
- return fraction * fraction * (3 - 2 * fraction);
-}
-
-function combineLogic(isAnd) {
- return args => {
- const evaluators = args.map(argument => requireScalar(argument, 'a logic operator'));
- return scalarValue(index => {
- for (const evaluate of evaluators) {
- const truthy = evaluate(index) !== 0;
- if (isAnd && !truthy) return 0;
- if (!isAnd && truthy) return 1;
- }
- return isAnd ? 1 : 0;
- });
- };
-}
-
function dotValues([left, right]) {
const [leftX, leftY, leftZ] = requireVector(left, 'dot');
const [rightX, rightY, rightZ] = requireVector(right, 'dot');
@@ -196,63 +144,27 @@ function selectComponent(componentIndex) {
return ([operand]) => scalarValue(requireVector(operand, 'a component read')[componentIndex]);
}
-// Where the two dialects disagree, a field expression stays finite: a division by zero or the square root of a
-// negative number gives 0 rather than an error.
-const fieldSemantics = Object.freeze({
- divide: (left, right) => (right === 0 ? 0 : left / right),
- modulo: (left, right) => (right === 0 ? 0 : left - right * Math.floor(left / right)),
- power: (base, exponent) => finiteOrZero(Math.pow(base, exponent)),
- squareRoot: number => (number < 0 ? 0 : Math.sqrt(number)),
- smoothstep,
-});
-
-const fieldOperator = (min, max, build) => ({ min, max, build });
-const unaryOperator = build => fieldOperator(1, 1, build);
+const vectorOperator = (min, max, build) => ({ min, max, build });
// Operators live in a Map so that input keys such as "__proto__" or "constructor" are plain unknown names.
-const OPERATORS = new Map();
-for (const [name, { min, max, compute }] of createMathOperators(fieldSemantics)) {
- const isComparison = name === 'lt' || name === 'gt';
- const build = isComparison ? compareScalars(compute) : buildLifted({ max, compute });
- OPERATORS.set(name, fieldOperator(min, max, build));
-}
-OPERATORS.set('if', fieldOperator(3, 3, branch));
-for (const [name, compute] of [['ceil', Math.ceil], ['round', Math.round], ['sign', Math.sign]]) {
- OPERATORS.set(name, unaryOperator(buildLifted({ max: 1, compute })));
-}
-OPERATORS.set('lte', fieldOperator(2, 2, compareScalars((left, right) => left <= right)));
-OPERATORS.set('gte', fieldOperator(2, 2, compareScalars((left, right) => left >= right)));
-OPERATORS.set('eq', fieldOperator(2, 2, compareScalars((left, right) => left === right)));
-OPERATORS.set('and', fieldOperator(2, MAX_OPERANDS, combineLogic(true)));
-OPERATORS.set('or', fieldOperator(2, MAX_OPERANDS, combineLogic(false)));
-OPERATORS.set('not', unaryOperator(([operand]) => {
- const evaluate = requireScalar(operand, 'not');
- return scalarValue(index => (evaluate(index) === 0 ? 1 : 0));
-}));
-OPERATORS.set('vec', fieldOperator(3, 3, buildVector));
-OPERATORS.set('dot', fieldOperator(2, 2, dotValues));
-OPERATORS.set('cross', fieldOperator(2, 2, crossValues));
-OPERATORS.set('distance', fieldOperator(2, 2, distanceValues));
-OPERATORS.set('length', unaryOperator(lengthValue));
-OPERATORS.set('normalize', unaryOperator(normalizeValue));
-OPERATORS.set('x', unaryOperator(selectComponent(0)));
-OPERATORS.set('y', unaryOperator(selectComponent(1)));
-OPERATORS.set('z', unaryOperator(selectComponent(2)));
+const OPERATORS = createOperators();
+OPERATORS.set('vec', vectorOperator(3, 3, buildVector));
+OPERATORS.set('dot', vectorOperator(2, 2, dotValues));
+OPERATORS.set('cross', vectorOperator(2, 2, crossValues));
+OPERATORS.set('distance', vectorOperator(2, 2, distanceValues));
+OPERATORS.set('length', vectorOperator(1, 1, lengthValue));
+OPERATORS.set('normalize', vectorOperator(1, 1, normalizeValue));
+OPERATORS.set('x', vectorOperator(1, 1, selectComponent(0)));
+OPERATORS.set('y', vectorOperator(1, 1, selectComponent(1)));
+OPERATORS.set('z', vectorOperator(1, 1, selectComponent(2)));
export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };
const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random']);
export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);
-
// ---------------------------------------------------------------------------------------------------------------
// Compiling an expression against an element context: { count, positions(), normals(), tag(name) }.
-function isPlainObject(value) {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
- const prototype = Object.getPrototypeOf(value);
- return prototype === Object.prototype || prototype === null;
-}
-
function integerInRange(value, minimum, maximum, label) {
if (!Number.isInteger(value) || value < minimum || value > maximum) throw fieldError(`${label} must be an integer from ${minimum} to ${maximum}.`);
return value;
@@ -290,7 +202,7 @@ function compileAttribute(node, context) {
function compileNoise(node, state, depth) {
const settings = node.noise;
- if (!isPlainObject(settings) || Object.keys(node).length !== 1) throw fieldError('noise takes { scale, seed, octaves, at }.');
+ if (!isPlainObject(settings)) throw fieldError('noise takes { scale, seed, octaves, at }.');
onlyKeys(settings, ['scale', 'seed', 'octaves', 'at'], 'noise');
const scale = settings.scale ?? 1;
if (typeof scale !== 'number' || !(scale > 0) || scale > MAX_NOISE_SCALE) throw fieldError(`noise scale must be above 0 and at most ${MAX_NOISE_SCALE}.`);
@@ -303,56 +215,41 @@ function compileNoise(node, state, depth) {
function compileRandom(node) {
const settings = node.random;
- if (!isPlainObject(settings) || Object.keys(node).length !== 1) throw fieldError('random takes { seed }.');
+ if (!isPlainObject(settings)) throw fieldError('random takes { seed }.');
onlyKeys(settings, ['seed'], 'random');
const seed = integerInRange(settings.seed ?? 0, 0, MAX_SEED, 'random seed');
return scalarValue(index => seededRandom(index, 0, seed));
}
-function compileOperator(operator, name, operand, state, depth) {
- let compiledArguments;
- if (operator.max === 1) {
- compiledArguments = [compileNode(operand, state, depth + 1)];
- } else {
- if (!Array.isArray(operand) || operand.length < operator.min || operand.length > operator.max) {
- throw fieldError(`${name} needs ${operator.min === operator.max ? operator.min : `${operator.min} to ${operator.max}`} arguments in an array.`);
- }
- compiledArguments = operand.map(argument => compileNode(argument, state, depth + 1));
+function compileVectorLiteral(node) {
+ if (node.length !== 3 || !node.every(isBoundedNumber)) {
+ throw fieldError('a vector literal is three finite numbers; build one from expressions with "vec".');
}
- return operator.build(compiledArguments);
+ const [literalX, literalY, literalZ] = node;
+ return vectorValue(() => literalX, () => literalY, () => literalZ);
}
-function compileOther(node, state, depth) {
- if (typeof node === 'boolean') return constantScalar(node ? 1 : 0);
- if (Array.isArray(node)) {
- if (node.length !== 3 || !node.every(isBoundedNumber)) {
- throw fieldError('a vector literal is three finite numbers; build one from expressions with "vec".');
- }
- const [literalX, literalY, literalZ] = node;
- return vectorValue(() => literalX, () => literalY, () => literalZ);
- }
- if (!isPlainObject(node)) throw fieldError('each node is a number, a boolean, a vector of three numbers or an object with one operator.');
- const keys = Object.keys(node);
+// Inputs only a field has: a vector literal, an attribute, noise and random. Anything else is an operator.
+function compileInput(node, state, depth) {
+ if (Array.isArray(node)) return compileVectorLiteral(node);
+ if (!isPlainObject(node)) return undefined;
if (Object.hasOwn(node, 'attr')) return compileAttribute(node, state.context);
- if (keys.length !== 1) throw fieldError(`a node holds exactly one operator; got ${keys.length}.`);
- const name = keys[0];
- if (name === 'noise') return compileNoise(node, state, depth);
- if (name === 'random') return compileRandom(node);
- const operator = OPERATORS.get(name);
- if (!operator) throw fieldError(`unknown operator ${describeKey(name)}. Use one of ${FIELD_OPERATORS.join(', ')}.`);
- return compileOperator(operator, name, node[name], state, depth);
+ const keys = Object.keys(node);
+ if (keys.length !== 1) return undefined;
+ if (keys[0] === 'noise') return compileNoise(node, state, depth);
+ if (keys[0] === 'random') return compileRandom(node);
+ return undefined;
}
const FIELD_DIALECT = Object.freeze({
+ name: 'field',
+ accepts: 'a number, a boolean, a vector of three numbers, an attribute, noise, random or an operator object',
maxNodes: MAX_FIELD_NODES,
maxDepth: MAX_FIELD_DEPTH,
- messages: Object.freeze({
- nodes: `more than ${MAX_FIELD_NODES} nodes.`,
- depth: `nesting deeper than ${MAX_FIELD_DEPTH}.`,
- number: `numbers must be finite and within ${MAX_LITERAL}.`,
- }),
+ operators: OPERATORS,
+ sourceNames: SOURCE_KEYS,
reject: fieldError,
- compileOther,
+ compileInput,
});
/**
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index 4ff27814..3ed8bc60 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -47,8 +47,8 @@ export const MAX_FIELD_ELEMENTS = 250_000;
export const MAX_FIELD_WORK = 8_000_000;
export const FIELD_ATTRIBUTES = Object.freeze(['position', 'normal', 'index', 'tag']);
export const FIELD_OPERATOR_NAMES = Object.freeze([
- 'add', 'mul', 'min', 'max', 'sub', 'div', 'mod', 'pow', 'clamp', 'mix', 'smoothstep',
- 'neg', 'abs', 'sqrt', 'sin', 'cos', 'floor', 'ceil', 'round', 'fract', 'sign',
+ 'add', 'mul', 'min', 'max', 'sub', 'div', 'mod', 'pow', 'atan2', 'clamp', 'mix', 'smoothstep',
+ 'neg', 'abs', 'sqrt', 'sin', 'cos', 'floor', 'ceil', 'round', 'fract', 'sign', 'saturate',
'lt', 'lte', 'gt', 'gte', 'eq', 'and', 'or', 'not', 'if',
'vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z',
'attr', 'noise', 'random',
diff --git a/src/motion-expression.js b/src/motion-expression.js
index 3ad11596..49040038 100644
--- a/src/motion-expression.js
+++ b/src/motion-expression.js
@@ -1,49 +1,24 @@
-import { denseArray, knownKeys } from './motion-validation.js';
-import {
- COMPONENTS, MAX_LITERAL, MAX_OPERANDS, buildLifted, compileNode, createMathOperators, scalarValue,
-} from './expression.js';
+import { knownKeys } from './motion-validation.js';
+import { COMPONENTS, compileNode, createOperators, isPlainObject, liftOperator, scalarValue } from './expression.js';
-// Bounded motion expressions: a small JSON language for drivers and constraint influence. An expression is data, never
-// code. It is read by walking plain objects against a fixed table of operators, compiled once into closures and checked
-// against its limits before anything runs. No string is executed, and operator names come from a Map.
-// This is the motion dialect of the one expression language in expression.js; mesh-fields.js is the field dialect.
+// Bounded motion expressions: the motion context of the one expression language in expression.js, for drivers and
+// constraint influence. An expression is data, never code. See that file for the operators and how they behave.
//
// { "mul": [{ "node": "wheel", "property": "rotation", "component": "x" }, 0.01] }
// { "clamp": [{ "mul": ["time", 0.5] }, 0, 1] }
//
-// A number is a constant and the string "time" is the motion time in seconds. A node read takes a component (x, y or z)
-// of a node's translation, scale, or rotation (Euler XYZ in degrees), in "local" (default) or "world" space.
-// Operators: add mul min max (2 to 8 operands), sub div pow mod atan2 gt lt (2), neg abs sin cos sqrt floor fract
-// saturate (1), clamp(x, low, high) mix(a, b, t) smoothstep(low, high, x) if(condition, then, otherwise) (3).
-// sin and cos take radians; gt, lt and if use 1 and 0 for true and false.
+// The string "time" is the motion time in seconds. A node read takes a component (x, y or z) of a node's translation,
+// scale, or rotation (Euler XYZ in degrees), in "local" (default) or "world" space. Vectors, attributes and noise
+// belong to fields and are rejected here. sin and cos take radians.
export const MAX_EXPRESSION_NODES = 64;
export const MAX_EXPRESSION_DEPTH = 8;
const READ_PROPERTIES = ['translation', 'rotation', 'scale'];
-const OPERAND_COUNT_TEXT = new Map([[1, 'one operand'], [2, 'two operands'], [3, 'three operands']]);
-// Where the two dialects disagree, a motion expression keeps plain arithmetic: a division by zero or the square root
-// of a negative number gives a non-finite value, which `evaluate` rejects instead of hiding it as the field dialect does.
-const motionSemantics = Object.freeze({
- divide: (left, right) => left / right,
- modulo: (left, right) => left - right * Math.floor(left / right),
- power: Math.pow,
- squareRoot: Math.sqrt,
- smoothstep: (low, high, value) => {
- const fraction = Math.min(1, Math.max(0, (value - low) / (high - low)));
- return fraction * fraction * (3 - 2 * fraction);
- },
-});
-
-const OPERATORS = createMathOperators(motionSemantics);
-OPERATORS.set('saturate', { min: 1, max: 1, compute: value => Math.min(1, Math.max(0, value)) });
-OPERATORS.set('atan2', { min: 2, max: 2, compute: Math.atan2 });
-OPERATORS.set('if', { min: 3, max: 3, compute: (condition, thenValue, otherwiseValue) => (condition > 0 ? thenValue : otherwiseValue) });
-
-function describeOperandCount(operator) {
- if (operator.min === operator.max) return OPERAND_COUNT_TEXT.get(operator.min);
- return `${operator.min} to ${operator.max} operands`;
-}
+// The one operator that differs from fields. A driver that divides by zero is a mistake the agent should hear about:
+// the result is non-finite and `evaluate` rejects it, where a field turns it into 0.
+const OPERATORS = createOperators();
+OPERATORS.set('div', liftOperator(2, 2, (left, right) => left / right));
function compileRead(input, state) {
const { label, nodeIds } = state;
@@ -58,38 +33,21 @@ function compileRead(input, state) {
return scalarValue(context => context.read(input.node, input.property, component, space));
}
-function compileOperator(input, state, depth) {
- const { label } = state;
- const keys = Object.keys(input);
- if (keys.length !== 1) throw new TypeError(`${label}: an operator object has exactly one key, such as {"add": [1, 2]}.`);
- const [name] = keys;
- const operands = denseArray(input[name], MAX_OPERANDS, `${label} ${name} operands`).map(operand => compileNode(operand, state, depth + 1));
- const operator = OPERATORS.get(name);
- if (!operator) throw new RangeError(`${label}: unknown operator ${JSON.stringify(name.slice(0, 24))}.`);
- if (operands.length < operator.min || operands.length > operator.max) {
- throw new RangeError(`${label}: ${name} takes ${describeOperandCount(operator)}.`);
- }
- return buildLifted(operator)(operands);
-}
-
-function compileOther(input, state, depth) {
- if (input === 'time') return scalarValue(context => context.time);
- if (!input || Object.getPrototypeOf(input) !== Object.prototype) {
- throw new TypeError(`${state.label}: use a number, "time", a node read or an operator object.`);
- }
- return Object.hasOwn(input, 'node') ? compileRead(input, state) : compileOperator(input, state, depth);
+function compileInput(node, state) {
+ if (node === 'time') return scalarValue(context => context.time);
+ if (isPlainObject(node) && Object.hasOwn(node, 'node')) return compileRead(node, state);
+ return undefined;
}
const MOTION_DIALECT = Object.freeze({
+ name: 'motion',
+ accepts: 'a number, "time", a node read or an operator object',
maxNodes: MAX_EXPRESSION_NODES,
maxDepth: MAX_EXPRESSION_DEPTH,
- messages: Object.freeze({
- nodes: ` has more than ${MAX_EXPRESSION_NODES} parts.`,
- depth: ` nests deeper than ${MAX_EXPRESSION_DEPTH} levels.`,
- number: `: a number must be finite and within ${MAX_LITERAL}.`,
- }),
- reject: (message, state) => new RangeError(`${state.label}${message}`),
- compileOther,
+ operators: OPERATORS,
+ sourceNames: Object.freeze(['time', 'node']),
+ reject: (message, state) => new TypeError(`${state.label}: ${message}`),
+ compileInput,
});
/**
diff --git a/tests/expression.test.js b/tests/expression.test.js
new file mode 100644
index 00000000..4b5086d6
--- /dev/null
+++ b/tests/expression.test.js
@@ -0,0 +1,52 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { compileMotionExpression } from '../src/motion-expression.js';
+import { evaluateField, pointSetContext, validateField } from '../src/mesh-fields.js';
+
+const nodeIds = new Set(['wheel']);
+const motionValue = (expression, time = 0) => {
+ const compiled = compileMotionExpression(expression, nodeIds, 'Driver');
+ return compiled.evaluate({ time, read: () => 0 });
+};
+const fieldValue = expression => {
+ const points = new Float64Array([0, 0, 0]);
+ return evaluateField(expression, pointSetContext(points, points)).values[0];
+};
+const bothContexts = expression => [motionValue(expression), fieldValue(expression)];
+
+test('both contexts give the same result for the same operator', () => {
+ const cases = [
+ [{ if: [-1, 10, 20] }, 10],
+ [{ if: [0, 10, 20] }, 20],
+ [{ smoothstep: [1, 1, 0.5] }, 0],
+ [{ smoothstep: [1, 1, 2] }, 1],
+ [{ sqrt: [-4] }, 0],
+ [{ pow: [-8, 0.5] }, 0],
+ [{ mod: [5, 0] }, 0],
+ [{ sqrt: 9 }, 3],
+ [{ neg: [3] }, -3],
+ [{ neg: 3 }, -3],
+ [{ and: [1, 2] }, 1],
+ [{ lte: [2, 2] }, 1],
+ [{ atan2: [0, 1] }, 0],
+ [{ saturate: [5] }, 1],
+ [{ add: [true, 1] }, 2],
+ ];
+ for (const [expression, expected] of cases) {
+ assert.deepEqual(bothContexts(expression), [expected, expected], JSON.stringify(expression));
+ }
+});
+
+test('a division by zero is 0 in a field and an error in a driver', () => {
+ assert.equal(fieldValue({ div: [1, 0] }), 0);
+ assert.throws(() => motionValue({ div: [1, 0] }), /finite/);
+});
+
+test('each context rejects the other context\'s inputs and says so', () => {
+ assert.throws(() => motionValue({ attr: 'position' }), /field input.*motion expression/);
+ assert.throws(() => motionValue({ noise: { scale: 2 } }), /field input/);
+ assert.throws(() => motionValue({ dot: [1, 2] }), /field input/);
+ assert.throws(() => motionValue([1, 2, 3]), /field input/);
+ assert.throws(() => validateField('time'), /motion input.*field expression/);
+ assert.throws(() => validateField({ node: 'wheel', property: 'translation', component: 'x' }), /motion input/);
+});