3D engine that AI agents drive
Add mesh shape field inputs and whole-domain field operators (#699)
Nguyen Xuan An05202d4bd209
diff --git a/changes/699.md b/changes/699.mdnew file mode 100644index 00000000..d49ecd0f--- /dev/null+++ b/changes/699.md@@ -0,0 +1 @@+- Field expressions read face area, edge angle, island index and neighbour counts, and accumulate, statistic, blur, sample index and rank over a whole mesh domain (#699)diff --git a/changes/699.size.md b/changes/699.size.mdnew file mode 100644index 00000000..e463dab4--- /dev/null+++ b/changes/699.size.md@@ -0,0 +1,4 @@+- entry:mesh: four mesh-shape field inputs and five whole-domain field operators (face area, edge angle, island, neighbours, accumulate, statistic, blur, sample index, rank) add about 2.4 KB gzip, an agent-facing modeling capability whose errors name the field and the fix.+- scene:agent-scene: the field names and capability notes add about 0.3 KB gzip.+- scene:agent-scene+lazy: the same code, counted in the lazy bundle.+- goal:agent-scene: the scene is already over its goal; the growth is the field names and capability notes agents read, and the field code itself sits in the mesh entry.diff --git a/docs/mesh.md b/docs/mesh.mdindex 81406e5a..9009f693 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -287,6 +287,8 @@ Operators that take numbers also take vectors and work on each component; a numb| Vectors | `vec: [x, y, z]`, `dot` `cross` `distance`, `length` `normalize`, `x` `y` `z` read a component || Rotation | `rotate: [vector, axis, angle]` turns a vector about an axis (radians; a zero axis does nothing); `align: [direction]` gives the Euler angles (X then Y then Z, radians) that turn +Y onto the direction; `transform: [point, move, euler, size]` scales, rotates, then moves a point (only the point is required) || Attributes | `{ "attr": "position" \| "normal" }` with optional `component`, `{ "attr": "index" }`, `{ "attr": "tag", "name": "top" }` |+| Mesh shape | `{ "faceArea": {} }` area of the face (over points, the mean of the faces around); `{ "edgeAngle": {} }` the sharpest angle between two faces over the element's edges, in radians, 0 on a border; `{ "island": {} }` the index of the connected piece, counted by its first vertex; `{ "neighbors": { "read": "edges" \| "faces" } }` how many edges (default) or faces touch the element. They need a mesh, so a point set rejects them. |+| Whole domain | Each takes one object and reads every element before it answers. `{ "accumulate": { "value", "group" } }` running total in index order, restarted for each whole-number `group`; `{ "statistic": { "value", "mode": "min" \| "max" \| "mean" \| "sum" \| "range", "group" } }` that statistic over all elements or the group; `{ "blur": { "value", "iterations": 1 to 32, "weight": 0 to 1 } }` mixes the value with the mean of its neighbours (edges over points, shared edges over faces) once per iteration; `{ "sampleIndex": { "value", "index" } }` the value at the element `index` names, clamped to the range; `{ "rank": { "value", "descending" } }` the position of the element when sorted by the value, ties in index order (Blender's Sort Elements index). `value` and `group` are number expressions. || 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 |Limits, checked before evaluation: 64 nodes, depth 12, 250,000 elements, and 8,000,000 node-evaluations (nodes timesdiff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 00aac47f..b0b584e3 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -210,6 +210,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,rotation: 'rotate [v, axis, rad]; align [dir]: Euler of +Y to dir; transform [p, move, euler, size].',+ meshShape: 'faceArea {}; edgeAngle {} (radians, 0 on a border); island {}; neighbors {read edges|faces}. Over points faceArea is the mean of the faces around. A point set has no mesh and rejects them.',+ wholeDomain: 'accumulate {value, group}; statistic {value, mode min|max|mean|sum|range, group}; blur {value, iterations 1-32, weight 0-1}; sampleIndex {value, index} (clamped); rank {value, descending} (Sort Elements index). value and group are number expressions.',surfaces: 'nearest {surface, at, read distance|point|normal}; raycast {surface, at, direction, read hit|distance|point|normal, miss}. at defaults to position; rays go forward. surface: geometry id (instances where) or record (mesh edits). attr group + name reads a vertex group.',}),instancing: Object.freeze({diff --git a/src/field-mesh-inputs.js b/src/field-mesh-inputs.jsnew file mode 100644index 00000000..9a2b29a5--- /dev/null+++ b/src/field-mesh-inputs.js@@ -0,0 +1,362 @@+import { MAX_FIELD_ELEMENTS, registerFieldSource } from './mesh-fields.js';+import { compileNode, constantScalar, isPlainObject, scalarValue } from './expression.js';+import { faceNormals } from './mesh-normals.js';++// Field inputs that read the shape of the mesh, and field operators that need every element at once. Both are+// registered as sources, so each takes one settings object. The topology (edges, neighbours, islands) is built once+// per mesh, in element order, so the same mesh always gives the same bytes. Edge angles are unsigned radians, 0 on a+// border; edge domain fields wait for a later change.+//+// { "faceArea": {} } area of the face; over points, the mean of the faces around+// { "edgeAngle": {} } sharpest angle between faces over the element's edges+// { "island": {} } index of the connected piece, counted by first vertex+// { "neighbors": { "read": "edges" | "faces" } } how many edges or faces touch the element+// { "accumulate": { "value", "group" } } running total in index order, restarted for each group+// { "statistic": { "value", "mode", "group" } } min, max, mean, sum or range over all elements or a group+// { "blur": { "value", "iterations", "weight" } } mix a value with the mean of its neighbours+// { "sampleIndex": { "value", "index" } } the value of the element another expression names+// { "rank": { "value", "descending" } } position of the element when sorted by the value++const MAX_BLUR_ITERATIONS = 32;+const STATISTIC_MODES = Object.freeze(['min', 'max', 'mean', 'sum', 'range']);+const NEIGHBOR_READS = Object.freeze(['edges', 'faces']);++function fieldError(message) {+ return new TypeError(`Field expression: ${message}`);+}++function onlyKeys(settings, allowed, label) {+ for (const key of Object.keys(settings)) {+ if (!allowed.includes(key)) throw fieldError(`${label} does not take ${JSON.stringify(key.slice(0, 24))}; fields: ${allowed.join(', ') || 'none'}.`);+ }+}++function settingsOf(node, name, allowed) {+ const settings = node[name];+ if (!isPlainObject(settings)) throw fieldError(`${name} takes an object${allowed.length ? ` { ${allowed.join(', ')} }` : ', written {}'}.`);+ onlyKeys(settings, allowed, name);+ return settings;+}++// ---------------------------------------------------------------------------------------------------------------+// Topology.++const topologies = new WeakMap();++function sortedUnique(numbers) {+ numbers.sort((left, right) => left - right);+ return numbers.filter((number, position) => position === 0 || number !== numbers[position - 1]);+}++function collectEdges(mesh) {+ const { vertexCount, faceCount, faceOffsets, cornerVertices } = mesh;+ const edgeIds = new Map();+ const edgeEnds = [];+ const edgeFaces = [];+ const cornerEdges = new Int32Array(cornerVertices.length).fill(-1);+ for (let face = 0; face < faceCount; face++) {+ const start = faceOffsets[face];+ const end = faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const from = cornerVertices[corner];+ const to = cornerVertices[corner + 1 < end ? corner + 1 : start];+ if (from === to) continue;+ const key = Math.min(from, to) * vertexCount + Math.max(from, to);+ let edge = edgeIds.get(key);+ if (edge === undefined) {+ edge = edgeEnds.length;+ edgeIds.set(key, edge);+ edgeEnds.push([from, to]);+ edgeFaces.push([]);+ }+ cornerEdges[corner] = edge;+ const faces = edgeFaces[edge];+ if (faces[faces.length - 1] !== face) faces.push(face);+ }+ }+ return { edgeEnds, edgeFaces, cornerEdges };+}++function pointNeighborLists(mesh, edgeEnds) {+ const neighbors = Array.from({ length: mesh.vertexCount }, () => []);+ for (const [from, to] of edgeEnds) {+ neighbors[from].push(to);+ neighbors[to].push(from);+ }+ return neighbors;+}++// Faces that share an edge. An edge with more than two faces joins them in face order, a chain, so the work stays linear.+function faceNeighborLists(mesh, edgeFaces) {+ const neighbors = Array.from({ length: mesh.faceCount }, () => []);+ for (const faces of edgeFaces) {+ for (let position = 1; position < faces.length; position++) {+ neighbors[faces[position - 1]].push(faces[position]);+ neighbors[faces[position]].push(faces[position - 1]);+ }+ }+ return neighbors.map(sortedUnique);+}++function incidentFaceCounts(mesh) {+ const counts = new Float64Array(mesh.vertexCount);+ const lastFace = new Int32Array(mesh.vertexCount).fill(-1);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const vertex = mesh.cornerVertices[corner];+ if (lastFace[vertex] === face) continue;+ lastFace[vertex] = face;+ counts[vertex]++;+ }+ }+ return counts;+}++function edgeAngles(mesh, topology) {+ const { normals } = faceNormals(mesh);+ const pointAngles = new Float64Array(mesh.vertexCount);+ const edgeAngleValues = new Float64Array(topology.edgeEnds.length);+ topology.edgeFaces.forEach((faces, edge) => {+ if (faces.length !== 2) return;+ const [first, second] = faces;+ const cosine = normals[first * 3] * normals[second * 3] + normals[first * 3 + 1] * normals[second * 3 + 1] + normals[first * 3 + 2] * normals[second * 3 + 2];+ const angle = Math.acos(Math.min(1, Math.max(-1, cosine)));+ edgeAngleValues[edge] = angle;+ for (const vertex of topology.edgeEnds[edge]) pointAngles[vertex] = Math.max(pointAngles[vertex], angle);+ });+ const faceAngles = new Float64Array(mesh.faceCount);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const edge = topology.cornerEdges[corner];+ if (edge >= 0) faceAngles[face] = Math.max(faceAngles[face], edgeAngleValues[edge]);+ }+ }+ return { point: pointAngles, face: faceAngles };+}++function findRoot(parents, vertex) {+ let root = vertex;+ while (parents[root] !== root) root = parents[root];+ let walker = vertex;+ while (parents[walker] !== root) {+ const next = parents[walker];+ parents[walker] = root;+ walker = next;+ }+ return root;+}++// Roots are always the smallest vertex of a piece, so the labels depend only on the mesh.+function islandIndices(mesh) {+ const parents = Uint32Array.from({ length: mesh.vertexCount }, (_, vertex) => vertex);+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const rootA = findRoot(parents, mesh.cornerVertices[corner]);+ const rootB = findRoot(parents, mesh.cornerVertices[corner + 1 < end ? corner + 1 : start]);+ if (rootA === rootB) continue;+ parents[Math.max(rootA, rootB)] = Math.min(rootA, rootB);+ }+ }+ return labelIslands(mesh, parents);+}++function labelIslands(mesh, parents) {+ const labels = new Map();+ const point = new Float64Array(mesh.vertexCount);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const root = findRoot(parents, vertex);+ if (!labels.has(root)) labels.set(root, labels.size);+ point[vertex] = labels.get(root);+ }+ const face = new Float64Array(mesh.faceCount);+ for (let faceIndex = 0; faceIndex < mesh.faceCount; faceIndex++) {+ face[faceIndex] = point[mesh.cornerVertices[mesh.faceOffsets[faceIndex]]];+ }+ return { point, face };+}++function topologyOf(mesh) {+ if (!topologies.has(mesh)) {+ const topology = collectEdges(mesh);+ topology.pointNeighbors = pointNeighborLists(mesh, topology.edgeEnds);+ topology.faceNeighbors = faceNeighborLists(mesh, topology.edgeFaces);+ topologies.set(mesh, topology);+ }+ return topologies.get(mesh);+}++// The mesh and domain a context stands for; null while only validating. Point sets have no faces or edges.+function meshOf(context, label) {+ if (context.validationOnly) return null;+ if (!context.mesh) throw fieldError(`${label} reads the faces and edges of a mesh, which a point set does not have. Use it in a mesh edit, a face selection or an instance rule over a mesh.`);+ return context;+}++// ---------------------------------------------------------------------------------------------------------------+// Inputs.++function faceAreaValues(mesh, domain) {+ const { areas } = faceNormals(mesh);+ if (domain === 'face') return areas;+ const sums = new Float64Array(mesh.vertexCount);+ const counts = incidentFaceCounts(mesh);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) sums[mesh.cornerVertices[corner]] += areas[face];+ }+ return sums.map((sum, vertex) => (counts[vertex] ? sum / counts[vertex] : 0));+}++function neighborValues(mesh, domain, read) {+ const topology = topologyOf(mesh);+ if (domain === 'point') {+ return read === 'edges' ? Float64Array.from(topology.pointNeighbors, list => list.length) : incidentFaceCounts(mesh);+ }+ if (read === 'faces') return Float64Array.from(topology.faceNeighbors, list => list.length);+ return Float64Array.from({ length: mesh.faceCount }, (_, face) => mesh.faceOffsets[face + 1] - mesh.faceOffsets[face]);+}++function meshInput(name, allowed, computeValues) {+ return (node, state) => {+ const settings = settingsOf(node, name, allowed);+ const context = meshOf(state.context, name);+ if (!context) return constantScalar(0);+ const values = computeValues(context.mesh, context.domain, settings);+ return scalarValue(index => values[index]);+ };+}++function compileNeighbors(node, state) {+ const settings = settingsOf(node, 'neighbors', ['read']);+ const read = settings.read ?? 'edges';+ if (!NEIGHBOR_READS.includes(read)) throw fieldError(`neighbors read must be one of ${NEIGHBOR_READS.join(', ')}.`);+ const context = meshOf(state.context, 'neighbors');+ if (!context) return constantScalar(0);+ const values = neighborValues(context.mesh, context.domain, read);+ return scalarValue(index => values[index]);+}++// ---------------------------------------------------------------------------------------------------------------+// Operators over every element.++function elementCount(context, label) {+ if (context.count > MAX_FIELD_ELEMENTS) throw new RangeError(`Field expression: ${context.count} elements is over the limit of ${MAX_FIELD_ELEMENTS}, so ${label} cannot run. Select fewer elements.`);+ return context.count;+}++function evaluateEverywhere(settings, key, state, depth, label, { optional = false } = {}) {+ if (settings[key] === undefined) {+ if (optional) return null;+ throw fieldError(`${label} needs "${key}": a number expression, such as {"attr":"index"}.`);+ }+ const compiled = compileNode(settings[key], state, depth + 1);+ if (compiled.kind !== 'scalar') throw fieldError(`${label} "${key}" needs a number, not a vector; read one component with x, y or z.`);+ const count = elementCount(state.context, label);+ const values = new Float64Array(count);+ for (let index = 0; index < count; index++) {+ const value = compiled.evaluate(index);+ values[index] = Number.isFinite(value) ? value : 0;+ }+ return values;+}++function groupKeys(groupValues, count) {+ return groupValues ? Array.from({ length: count }, (_, index) => Math.round(groupValues[index])) : new Array(count).fill(0);+}++function compileAccumulate(node, state, depth) {+ const settings = settingsOf(node, 'accumulate', ['value', 'group']);+ const values = evaluateEverywhere(settings, 'value', state, depth, 'accumulate');+ const keys = groupKeys(evaluateEverywhere(settings, 'group', state, depth, 'accumulate', { optional: true }), values.length);+ const totals = new Map();+ const running = new Float64Array(values.length);+ for (let index = 0; index < values.length; index++) {+ const total = (totals.get(keys[index]) ?? 0) + values[index];+ totals.set(keys[index], total);+ running[index] = total;+ }+ return scalarValue(index => running[index]);+}++function summarize(mode, group) {+ if (mode === 'mean') return group.sum / group.count;+ if (mode === 'range') return group.max - group.min;+ return group[mode];+}++function compileStatistic(node, state, depth) {+ const settings = settingsOf(node, 'statistic', ['value', 'mode', 'group']);+ const mode = settings.mode ?? 'mean';+ if (!STATISTIC_MODES.includes(mode)) throw fieldError(`statistic mode must be one of ${STATISTIC_MODES.join(', ')}.`);+ const values = evaluateEverywhere(settings, 'value', state, depth, 'statistic');+ const keys = groupKeys(evaluateEverywhere(settings, 'group', state, depth, 'statistic', { optional: true }), values.length);+ const groups = new Map();+ for (let index = 0; index < values.length; index++) {+ const group = groups.get(keys[index]) ?? { min: Infinity, max: -Infinity, sum: 0, count: 0 };+ group.min = Math.min(group.min, values[index]);+ group.max = Math.max(group.max, values[index]);+ group.sum += values[index];+ group.count++;+ groups.set(keys[index], group);+ }+ const results = Float64Array.from(keys, key => summarize(mode, groups.get(key)));+ return scalarValue(index => results[index]);+}++function compileBlur(node, state, depth) {+ const settings = settingsOf(node, 'blur', ['value', 'iterations', 'weight']);+ const iterations = settings.iterations ?? 1;+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_BLUR_ITERATIONS) throw fieldError(`blur iterations must be an integer from 1 to ${MAX_BLUR_ITERATIONS}.`);+ const weight = settings.weight ?? 1;+ if (typeof weight !== 'number' || !(weight >= 0 && weight <= 1)) throw fieldError('blur weight must be a number from 0 to 1.');+ let current = evaluateEverywhere(settings, 'value', state, depth, 'blur');+ const context = meshOf(state.context, 'blur');+ if (!context) return constantScalar(0);+ const topology = topologyOf(context.mesh);+ const neighbors = context.domain === 'point' ? topology.pointNeighbors : topology.faceNeighbors;+ for (let iteration = 0; iteration < iterations; iteration++) {+ const next = new Float64Array(current.length);+ for (let index = 0; index < current.length; index++) {+ const around = neighbors[index];+ let sum = 0;+ for (const neighbor of around) sum += current[neighbor];+ next[index] = around.length ? current[index] + (sum / around.length - current[index]) * weight : current[index];+ }+ current = next;+ }+ const blurred = current;+ return scalarValue(index => blurred[index]);+}++function compileSampleIndex(node, state, depth) {+ const settings = settingsOf(node, 'sampleIndex', ['value', 'index']);+ const values = evaluateEverywhere(settings, 'value', state, depth, 'sampleIndex');+ const indices = evaluateEverywhere(settings, 'index', state, depth, 'sampleIndex');+ const last = values.length - 1;+ return scalarValue(index => (last < 0 ? 0 : values[Math.min(last, Math.max(0, Math.round(indices[index])))]));+}++function compileRank(node, state, depth) {+ const settings = settingsOf(node, 'rank', ['value', 'descending']);+ if (settings.descending !== undefined && typeof settings.descending !== 'boolean') throw fieldError('rank descending must be true or false.');+ const values = evaluateEverywhere(settings, 'value', state, depth, 'rank');+ const direction = settings.descending ? -1 : 1;+ const order = Array.from({ length: values.length }, (_, index) => index);+ order.sort((left, right) => direction * (values[left] - values[right]) || left - right);+ const ranks = new Float64Array(values.length);+ order.forEach((element, position) => {+ ranks[element] = position;+ });+ return scalarValue(index => ranks[index]);+}++registerFieldSource('faceArea', meshInput('faceArea', [], faceAreaValues));+registerFieldSource('edgeAngle', meshInput('edgeAngle', [], (mesh, domain) => edgeAngles(mesh, topologyOf(mesh))[domain]));+registerFieldSource('island', meshInput('island', [], (mesh, domain) => islandIndices(mesh)[domain]));+registerFieldSource('neighbors', compileNeighbors);+registerFieldSource('accumulate', compileAccumulate);+registerFieldSource('statistic', compileStatistic);+registerFieldSource('blur', compileBlur);+registerFieldSource('sampleIndex', compileSampleIndex);+registerFieldSource('rank', compileRank);diff --git a/src/mesh-fields.js b/src/mesh-fields.jsindex 0173d6f0..b66c672d 100644--- a/src/mesh-fields.js+++ b/src/mesh-fields.js@@ -164,13 +164,16 @@ export function registerFieldOperator(name, operator) {}export { MAX_FIELD_NODES, MAX_FIELD_DEPTH, MAX_FIELD_ELEMENTS, MAX_FIELD_WORK };-const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random', 'nearest', 'raycast']);+const SOURCE_KEYS = ['attr', 'noise', 'random', 'nearest', 'raycast'];// Inputs that other modules supply (the surface inputs register themselves), so a bundle that never reads one does not carry its code.const FIELD_SOURCES = new Map();export function registerFieldSource(name, compile) {FIELD_SOURCES.set(name, compile);+ if (SOURCE_KEYS.includes(name)) return;+ SOURCE_KEYS.push(name);+ FIELD_OPERATORS.push(name);}// Every operator and input name; registerFieldOperator adds the late ones.export const FIELD_OPERATORS = [...OPERATORS.keys(), ...SOURCE_KEYS];@@ -298,7 +301,7 @@ export function validateField(expression, { kind } = {}) {}const EMPTY = new Float64Array(0);-const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY, group: () => EMPTY, loadSurface: null });+const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY, group: () => EMPTY, loadSurface: null, validationOnly: true });function finiteValues(source, count, width) {const values = new Float64Array(count * width);@@ -315,6 +318,8 @@ export function meshFieldContext(mesh, domain, loadSurface) {const isPoint = domain === 'point';const cache = {};return {+ mesh,+ domain,count: isPoint ? mesh.vertexCount : mesh.faceCount,positions: () => (cache.positions ??= isPoint ? mesh.positions : faceCentroids(mesh)),normals: () => (cache.normals ??= isPoint ? vertexNormals(mesh) : faceNormals(mesh).normals),diff --git a/src/mesh-instances.js b/src/mesh-instances.jsindex 899bce50..279a04e3 100644--- a/src/mesh-instances.js+++ b/src/mesh-instances.js@@ -5,6 +5,7 @@ import { MAX_CURVE_POINTS, curveLength, filletCurve, resampleCurve } from './curimport { createTriangleSurfaceIndex } from './mesh-query.js';import './mesh-field-surfaces.js';import './field-rotation.js';+import './field-mesh-inputs.js';import {checkedPlace, clampedSize, eulerQuaternion, mergeRealizedInstances, meshPoints, pickVariant, thinByDensity, thinBySpacing,} from './mesh-instance-placement.js';diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex edc34d1b..5e3d8533 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -98,6 +98,7 @@ export const FIELD_OPERATOR_NAMES = /* @__PURE__ */ Object.freeze(['vec', 'dot', 'cross', 'distance', 'length', 'normalize', 'x', 'y', 'z','rotate', 'align', 'transform','attr', 'noise', 'random', 'nearest', 'raycast',+ 'faceArea', 'edgeAngle', 'island', 'neighbors', 'accumulate', 'statistic', 'blur', 'sampleIndex', 'rank',]);export const INSTANCE_SOURCES = /* @__PURE__ */ Object.freeze(['grid', 'scatter', 'surface', 'curve']);export const MAX_INSTANCE_CANDIDATES = 2048;diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex 9eac6397..53be97f3 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -28,6 +28,7 @@ import { triangulatedSurface } from './mesh-surface-distance.js';import { createTriangleSurfaceIndex } from './mesh-query.js';import './mesh-field-surfaces.js';import './field-rotation.js';+import './field-mesh-inputs.js';import './mesh-hull-modifiers.js';import './mesh-ocean-modifier.js';import './mesh-build-modifier.js';diff --git a/tests/field-mesh-inputs.test.js b/tests/field-mesh-inputs.test.jsnew file mode 100644index 00000000..5fcc6562--- /dev/null+++ b/tests/field-mesh-inputs.test.js@@ -0,0 +1,129 @@+import './support/load-agent-scene-modules.mjs';+import assert from 'node:assert/strict';+import test from 'node:test';+import { box } from '../src/geometry.js';+import { meshFromGeometry, applyMeshEdits } from '../src/mesh.js';+import { MAX_FIELD_ELEMENTS, compileField, evaluateField, meshFieldContext, pointSetContext, validateField } from '../src/mesh-fields.js';++// Three triangles. 0 and 1 share the edge from vertex 0 to vertex 1 at a right angle; 2 stands apart with area 2.+function folded() {+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 10, 0, 0, 12, 0, 0, 10, 0, 2]);+ const indices = new Uint32Array([0, 1, 2, 0, 3, 1, 4, 5, 6]);+ return meshFromGeometry({ positions, indices }, { quads: false, tags: 'none' });+}++function faceValues(expression, mesh = folded()) {+ return Array.from(evaluateField(expression, meshFieldContext(mesh, 'face'), { kind: 'scalar' }).values);+}++function pointValues(expression, mesh = folded()) {+ return Array.from(evaluateField(expression, meshFieldContext(mesh, 'point'), { kind: 'scalar' }).values);+}++function assertClose(actual, expected, label) {+ assert.equal(actual.length, expected.length, `${label} length`);+ actual.forEach((value, index) => assert.ok(Math.abs(value - expected[index]) < 1e-6, `${label}[${index}] ${value} vs ${expected[index]}`));+}++test('faceArea reads the area of a face and the mean around a point', () => {+ assertClose(faceValues({ faceArea: {} }), [0.5, 0.5, 2], 'faces');+ const points = pointValues({ faceArea: {} });+ assertClose(points.slice(0, 2), [0.5, 0.5], 'shared points');+ assertClose(points.slice(4), [2, 2, 2], 'apart points');+});++test('edgeAngle is the sharpest angle between faces over the edges, 0 on a border', () => {+ assertClose(faceValues({ edgeAngle: {} }), [Math.PI / 2, Math.PI / 2, 0], 'faces');+ assertClose(pointValues({ edgeAngle: {} }), [Math.PI / 2, Math.PI / 2, 0, 0, 0, 0, 0], 'points');+ const cubeAngles = faceValues({ edgeAngle: {} }, meshFromGeometry(box(0, 1)));+ cubeAngles.forEach(angle => assert.ok(Math.abs(angle - Math.PI / 2) < 1e-6, `cube edge ${angle}`));+});++test('island counts connected pieces by their first vertex', () => {+ assert.deepEqual(faceValues({ island: {} }), [0, 0, 1]);+ assert.deepEqual(pointValues({ island: {} }), [0, 0, 0, 0, 1, 1, 1]);+});++test('neighbors counts edges or faces that touch the element', () => {+ assert.deepEqual(pointValues({ neighbors: {} }), [3, 3, 2, 2, 2, 2, 2]);+ assert.deepEqual(pointValues({ neighbors: { read: 'faces' } }), [2, 2, 1, 1, 1, 1, 1]);+ assert.deepEqual(faceValues({ neighbors: { read: 'faces' } }), [1, 1, 0]);+ assert.deepEqual(faceValues({ neighbors: { read: 'edges' } }), [3, 3, 3]);+});++test('accumulate adds up in index order and restarts for each group', () => {+ assertClose(faceValues({ accumulate: { value: { faceArea: {} } } }), [0.5, 1, 3], 'running');+ assertClose(faceValues({ accumulate: { value: { faceArea: {} }, group: { island: {} } } }), [0.5, 1, 2], 'grouped');+});++test('statistic gives min, max, mean, sum or range to every element or group', () => {+ const area = { faceArea: {} };+ assertClose(faceValues({ statistic: { value: area, mode: 'max' } }), [2, 2, 2], 'max');+ assertClose(faceValues({ statistic: { value: area, mode: 'min' } }), [0.5, 0.5, 0.5], 'min');+ assertClose(faceValues({ statistic: { value: area, mode: 'sum' } }), [3, 3, 3], 'sum');+ assertClose(faceValues({ statistic: { value: area, mode: 'range' } }), [1.5, 1.5, 1.5], 'range');+ assertClose(faceValues({ statistic: { value: area } }), [1, 1, 1], 'mean by default');+ assertClose(faceValues({ statistic: { value: area, mode: 'mean', group: { island: {} } } }), [0.5, 0.5, 2], 'grouped mean');+});++test('blur mixes a value with the mean of its neighbours for a bounded number of iterations', () => {+ const index = { attr: 'index' };+ assertClose(faceValues({ blur: { value: index } }), [1, 0, 2], 'one step');+ assertClose(faceValues({ blur: { value: index, weight: 0.5 } }), [0.5, 0.5, 2], 'half weight');+ assertClose(faceValues({ blur: { value: index, iterations: 2 } }), [0, 1, 2], 'two steps swap a pair');+ assertClose(pointValues({ blur: { value: index } }), [2, 5 / 3, 0.5, 0.5, 5.5, 5, 4.5], 'points');+});++test('sampleIndex reads another element, clamped to the range', () => {+ const tens = { mul: [{ attr: 'index' }, 10] };+ assert.deepEqual(faceValues({ sampleIndex: { value: tens, index: { sub: [2, { attr: 'index' }] } } }), [20, 10, 0]);+ assert.deepEqual(faceValues({ sampleIndex: { value: tens, index: 99 } }), [20, 20, 20]);+ assert.deepEqual(faceValues({ sampleIndex: { value: tens, index: -4 } }), [0, 0, 0]);+});++test('rank gives the position of each element when sorted, ties kept in index order', () => {+ const area = { faceArea: {} };+ assert.deepEqual(faceValues({ rank: { value: area } }), [0, 1, 2]);+ assert.deepEqual(faceValues({ rank: { value: area, descending: true } }), [1, 2, 0]);+ assert.deepEqual(faceValues({ rank: { value: { neg: { attr: 'index' } } } }), [2, 1, 0]);+});++test('the operators compose with the rest of the language', () => {+ const large = { gt: [{ faceArea: {} }, { statistic: { value: { faceArea: {} }, mode: 'mean' } }] };+ assert.deepEqual(faceValues(large), [0, 0, 1]);+});++test('geometry edited by these fields has the same bytes on every run', () => {+ const edit = [{+ op: 'set_position',+ select: { field: { gt: [{ edgeAngle: {} }, 1] } },+ offset: { vec: [0, { blur: { value: { faceArea: {} }, iterations: 2 } }, 0] },+ }];+ const first = applyMeshEdits(folded(), edit).mesh;+ const second = applyMeshEdits(folded(), edit).mesh;+ assert.equal(Buffer.from(first.positions.buffer).toString('hex'), Buffer.from(second.positions.buffer).toString('hex'));+ assert.notDeepEqual(Array.from(first.positions), Array.from(folded().positions));+ for (const expression of [{ island: {} }, { accumulate: { value: { faceArea: {} } } }, { rank: { value: { faceArea: {} } } }]) {+ const repeated = [faceValues(expression), faceValues(expression)].map(values => Buffer.from(Float64Array.from(values).buffer).toString('hex'));+ assert.equal(repeated[0], repeated[1]);+ }+});++test('errors name the field and the fix', () => {+ assert.throws(() => validateField({ faceArea: 3 }), /faceArea takes an object, written \{\}/);+ assert.throws(() => validateField({ island: { seed: 1 } }), /island does not take "seed"/);+ assert.throws(() => validateField({ neighbors: { read: 'corners' } }), /neighbors read must be one of edges, faces/);+ assert.throws(() => validateField({ statistic: { value: 1, mode: 'median' } }), /statistic mode must be one of min, max, mean, sum, range/);+ assert.throws(() => validateField({ statistic: {} }), /statistic needs "value": a number expression/);+ assert.throws(() => validateField({ blur: { value: 1, iterations: 33 } }), /blur iterations must be an integer from 1 to 32/);+ assert.throws(() => validateField({ blur: { value: 1, iterations: 1.5 } }), /blur iterations/);+ assert.throws(() => validateField({ blur: { value: 1, weight: 2 } }), /blur weight must be a number from 0 to 1/);+ assert.throws(() => validateField({ sampleIndex: { value: 1 } }), /sampleIndex needs "index"/);+ assert.throws(() => validateField({ rank: { value: 1, descending: 'yes' } }), /rank descending must be true or false/);+ assert.throws(() => validateField({ accumulate: { value: [1, 2, 3] } }), /accumulate "value" needs a number, not a vector; read one component with x, y or z/);+ assert.equal(validateField({ blur: { value: { faceArea: {} } } }), 'scalar');+ const points = pointSetContext(new Float32Array(6), new Float32Array(6));+ assert.throws(() => evaluateField({ island: {} }, points), /island reads the faces and edges of a mesh, which a point set does not have/);+ const crowded = { ...meshFieldContext(folded(), 'face'), count: MAX_FIELD_ELEMENTS + 1 };+ assert.throws(() => compileField({ rank: { value: 1 } }, crowded), /over the limit of 250000, so rank cannot run/);+});