Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Fields: sample other surfaces with nearest and raycast, and read vertex groups back (issue #597)

Nguyen Xuan Anb8522b07355f
diff --git a/changes/597-field-surface-sampling.md b/changes/597-field-surface-sampling.md
new file mode 100644
index 00000000..9a60c5a2
--- /dev/null
+++ b/changes/597-field-surface-sampling.md
@@ -0,0 +1 @@
+- Fields can read other surfaces: `nearest` (distance, point or normal of the closest point on a surface) and `raycast` (hit, distance, point or normal along a direction, with a `miss` value), plus `attr: group` to read a vertex group back. In `instances` the surface is a geometry id, so a scatter can avoid a path mesh and follow terrain; in `set_position`, `displace`, `vertex_group` and `vertex_color` it is a geometry record, and `vertex_group` stores the result by name (#597)
diff --git a/changes/597-field-surface-sampling.size.md b/changes/597-field-surface-sampling.size.md
new file mode 100644
index 00000000..af1a6b91
--- /dev/null
+++ b/changes/597-field-surface-sampling.size.md
@@ -0,0 +1,6 @@
+- entry:light-bake: its field-selection code now carries the surface inputs of fields (about 840 bytes gzip, `src/mesh-field-surfaces.js`); the BVH query itself stays in the mesh chunk.
+- entry:light-bake-gpu: the same field module growth as entry:light-bake, in its shared mesh-selection path.
+- entry:ground-bounce: the same field module growth, about 840 bytes gzip.
+- entry:floor-sky-visibility: the same field module growth, about 840 bytes gzip.
+- entry:water-reflection: the same field module growth, about 840 bytes gzip.
+- scene:agent-scene+lazy: the surface inputs and the BVH query wrapper load only with the mesh chunk and buy scatter that avoids paths and follows terrain, plus density maps stored as vertex groups; the core bundle shrinks by 4 bytes because new capability text is paid for by shorter notes.
diff --git a/docs/parity.md b/docs/parity.md
index 9f677156..7b0e631f 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -81,7 +81,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Generate > Mirror Modifier | done | Stack node with axis and merge. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |
| Modeling > Modifiers > Generate > Multiresolution Modifier | missing | No multiresolution. | | |
| Modeling > Modifiers > Generate > Remesh Modifier | partial | Voxel mode as `remesh` (voxel size or resolution), as an edit or a stack node, compared with Blender on 2 shared fixtures. Blocks, smooth and sharp modes are missing. | [blender golden](../tests/blender-golden.test.js), [decimate](../tests/mesh-decimate.test.js) | #40 |
-| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. No minimum distance or density map, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #42 |
+| Modeling > Modifiers > Generate > Scatter on Surface Modifier | partial | `instances` with a `surface` source scatters a node at seeded, area-weighted points with yaw, scale and normal alignment, and `where` filters them. Its `where` can read a path mesh with `nearest` and a terrain with `raycast`. No minimum distance or density map, and `addons/clutter` and `addons/grass` still scatter in code. | [src/mesh-instances.js](../src/mesh-instances.js), [tests/mesh-fields.test.js](../tests/mesh-fields.test.js) | #42 |
| Modeling > Modifiers > Generate > Screw Modifier | partial | `screw` edit and stack node revolves every edge of the mesh about x, y or z with `angle`, `steps`, `iterations` and a `lift` along the axis; a whole number of turns closes the ring. Counts, area and positions match Blender on 2 cases (the volume of the open strips differs by winding). No merge option, no object axis, no normal calculation and no separate render steps. `lathe` stays the way to revolve a profile. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Generate > Skin Modifier | partial | `skin` edit and stack node: a square tube on every edge of the mesh, radius a number or a scalar field per vertex, closed by end caps. Simple version: tubes that meet overlap, there is no branch solver, no loose ends marking and no Blender comparison. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js) | #42 |
| Modeling > Modifiers > Generate > Solidify Modifier | done | Stack node with thickness, offset and even thickness. | [mesh-stack](../tests/mesh-stack.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |
@@ -249,6 +249,8 @@ The goal also needs this work, and no page in the Blender manual covers it.
| Terrain and navigation | partial | Terrain has round holes (`addons/terrain` `holes`, recipe geometry `terrain`), still with 4 splat layers (more would need a shader change and 136 MiB at 8 layers of 1K). `addons/navmesh` builds a walkable grid from triangles with a slope limit, agent radius, holes and obstacle footprints, A* with string pulling and budgets; `scene_inspect` `path` returns walking keyframes. Evidence: tests/terrain-holes.test.js, tests/navmesh.test.js, suite tasks terrain-hole-walk and terrain-path-walk. | #64 |
| Tool cost and errors | partial | Lint and errors exist. No budget limits schema size, and not every error is checked. | #65, #66 |
| Branches and labelled images | partial | `scene_apply` `branch` forks a variant over a deduplicated snapshot store (8 branches, scene and revision untouched), `scene_review` shots take a `branch`, `scene_restore` `branch` keeps one. `labels: true` on `scene_look` and `scene_review` prints part names, tags and lint problems and returns them with pixel positions. Procedural scenes only; two suite tasks (`best-of-three`, `render-pick`) measured 22 runs and agents never called `branch`, so no call saving is shown. | #67 |
+| Field surface sampling (Geometry Proximity, Raycast, Sample Nearest Surface) | partial | Field inputs `nearest` (read distance, point or normal) and `raycast` (constant direction, read hit, distance, point or normal, a `miss` value, forward from `at`, so lift `at` to drop points onto terrain). The surface is a geometry id in `instances` `where` and a geometry record in `set_position`, `displace`, `vertex_group` and `vertex_color`. First hit only, no index or group target, no sampling of other attributes or UVs, no Blender comparison. Evidence: tests/mesh-field-surfaces.test.js. | #597 |
+| Capture Attribute and Store Named Attribute | partial | `vertex_group` (number) and `vertex_color` (vector) store a field result under a name, and the field input `attr: group` with a `name` reads that group back in a later edit. Groups hold a number from 0 to 1 per vertex, at most 32, with no other attribute types or domains. Evidence: tests/mesh-field-surfaces.test.js. | #597, #613 |
| Geometry node data types | missing | Blender 5.2 has Matrix (12 nodes), Rotation (11), List (6), Bundle and Closure nodes, and Repeat, Simulation and For Each zones. Fields have none of them, and "Modeling > Geometry Nodes" is the only row. Compare `bench/parity/blender-inventory-report.md`. | #43 |
| Rigid body shapes and joints | missing | Blender has cylinder, cone and compound shapes and piston, generic, generic spring and motor joints. Physics has box, ball, capsule, convex and trimesh shapes with fixed, revolute, prismatic and spherical joints. | #61 |
| Light probes | partial | Blender has sphere, plane and volume probes. `bake.probes` gives specular sphere probes only; there are no plane or irradiance volume probes. | #52 |
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 707d8f66..70571e86 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -156,19 +156,19 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
// Vertex colors and groups. Details stay here so the tool schemas stay small.
export const MESH_ATTRIBUTE_NOTES = Object.freeze({
- vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. At most 32 groups. displace takes group: name and scales each move by the weight; cloth sheets take pinGroup: name and hold vertices of weight 0.5 or more. Put it after the shape edits: a stack node that rebuilds the mesh (mirror, array and so on) drops groups.',
- vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Shown by the renderer and written as COLOR_0 in a GLB; it multiplies the material color.',
+ vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. Max 32 groups. displace takes group: name and scales each move by the weight; cloth takes pinGroup. Put it after shape edits: a stack node that rebuilds the mesh drops groups.',
+ vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Drawn, written as COLOR_0 in a GLB, and multiplies the material color.',
});
// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.
export const MESH_SHAPE_KEY_NOTES = Object.freeze({
- shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices (set_position, displace, sculpt, simple_deform, lattice, hook and so on) run on the finished mesh, after the stack. A key that adds or removes vertices is refused. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target of the mesh. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes } (weight 0 to 1; keys add up); a GLB export writes the targets, their names (mesh.extras.targetNames) and the weights. Normals stay those of the base mesh.',
+ shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices (set_position, displace, sculpt, simple_deform, lattice, hook and so on) run on the finished mesh, after the stack. A key that adds or removes vertices is refused. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes } (0 to 1; keys add up); a GLB export writes the targets, names (mesh.extras.targetNames) and weights. Normals stay the base mesh normals.',
});
// Organic shaping edits. Details stay here so the tool schemas stay small.
export const MESH_SCULPT_NOTES = Object.freeze({
- sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius. For bulges, dents and softened forms.',
- shrinkwrap: 'target is a primitive record placed by translation, rotation and scale. mode nearest (default) moves each selected vertex to the closest point; project moves it along direction (needed) to the first hit. offset (default 0) stands it off along the normal, on the side it came from. maxDistance limits the search; onMiss error (default) or keep. To lay a flat grid sheet onto a curved target as a decal, use enough cells to follow the curve, then solidify.',
+ sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius.',
+ shrinkwrap: 'target is a primitive record placed by translation, rotation and scale. mode nearest (default) moves each selected vertex to the closest point; project moves it along direction (needed) to the first hit. offset (default 0) stands it off along the normal, on the side it came from. maxDistance limits the search; onMiss error (default) or keep. For a decal, use enough grid cells to follow the curve, then solidify.',
});
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
@@ -176,8 +176,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),
camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, default 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its width and height. fStop (0.7 to 64) turns on depth of field focused on target; 1.4 or lower is full blur, and effects.depthOfField.blur must stay 0. Orthographic and shifted cameras render with the rasterizer, not the path tracer.',
terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',
- placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start, on a decoded copy of its own; scene_apply set-motion tracks move the node as usual and scene time seeks the clip. Copies of one asset share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy of its own (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds its wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',
- navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a node translation track with interpolation LINEAR. radius 0.3 m is how far the walker position stays from holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y, such as half the walker height. Ground and avoided nodes are read at their authored pose. Errors name an unwalkable start or goal, or one that cannot be reached.',
+ placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start on a decoded copy of its own; set-motion tracks move the node and scene time seeks the clip. Copies share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',
+ navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a translation track with interpolation LINEAR. radius 0.3 m keeps the walker off holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y (half the walker height). Ground and avoided nodes are read at their authored pose. Errors name an unwalkable or unreachable end.',
meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),
meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),
meshModifiers: MESH_MODIFIER_NOTES,
@@ -187,6 +187,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
fieldExpressions: Object.freeze({
operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,
maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,
+ 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({ sources: INSTANCE_SOURCES, maxCandidatePoints: MAX_INSTANCE_CANDIDATES }),
operations: Object.freeze([
@@ -282,7 +283,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
}),
// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.
particles: Object.freeze({
- emitter: 'System node keeps its geometry as the particle shape (keep it low-poly); node transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y where particles land and rest).',
+ emitter: 'System node keeps its geometry as the particle shape (keep it low-poly); its transform does not move particles. Fields (defaults): node, seed (1), count (100), rate (per second; omit for a burst at 0), lifetime, speed, size (each number or [min, max]; 1, 1, 0.05), direction ([0,1,0]), spread (cone degrees, 30), emitter { shape point|box|sphere|disc, position, halfExtents, radius }, scale constant|shrink|grow, drag (1/s, 0), floor (world y where particles land and rest).',
hair: 'type hair grows strands from a read-only root surface node into node (its own geometry is ignored). Fields (defaults): surface, seed, count, length (m, number or [min, max], 0.1), segments (1-8, 4), width (m, 0.004), droop (0.5), lean (0.2), sway (tip travel m, off), swayRate (Hz, 0.5). Triangular tapering tubes, no UVs.',
sectionFields: 'systems, gravity ([0,-9.81,0]), wind (m/s; moves emitter particles only with drag > 0, and sets the hair sway direction)',
notes: 'A particle is a pure function of seed, index and time; raising count keeps earlier ones. No collision but the floor, no bounce, rotation, colour or alpha; no hair collision, combing or clumping. Report: maxAlive and endsAt per system.',
diff --git a/src/mesh-attribute-edits.js b/src/mesh-attribute-edits.js
index 2db8130f..d5020bd0 100644
--- a/src/mesh-attribute-edits.js
+++ b/src/mesh-attribute-edits.js
@@ -95,7 +95,7 @@ function gradientFractions(mesh, gradient) {
}
/** Set the weight of a named group for the vertices of the selected faces; other vertices keep their weight (0 in a new group). */
-export function setVertexGroup(mesh, { select, name, weight, field, gradient }) {
+export function setVertexGroup(mesh, { select, name, weight, field, gradient }, loadSurface) {
const attributeName = GROUP_PREFIX + name;
const existing = mesh.attributes.point[attributeName];
if (!existing && vertexGroupNames(mesh).length >= MAX_VERTEX_GROUPS) {
@@ -103,7 +103,7 @@ export function setVertexGroup(mesh, { select, name, weight, field, gradient })
}
const weights = existing ? Float32Array.from(existing.data) : new Float32Array(mesh.vertexCount);
const flags = selectedVertices(mesh, select);
- const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point'), { kind: 'scalar' }).values;
+ const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point', loadSurface), { kind: 'scalar' }).values;
const fractions = gradient ? gradientFractions(mesh, gradient) : null;
let assignedVertices = 0;
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
@@ -118,11 +118,11 @@ export function setVertexGroup(mesh, { select, name, weight, field, gradient })
}
/** Set the corner colors of the selected faces; corners of other faces keep their color (white when the mesh had none). */
-export function setVertexColor(mesh, { select, color, field, gradient }) {
+export function setVertexColor(mesh, { select, color, field, gradient }, loadSurface) {
const existing = mesh.attributes.corner[COLOR_ATTRIBUTE];
const colors = existing?.size === 3 ? Float32Array.from(existing.data) : new Float32Array(mesh.cornerCount * 3).fill(1);
const faceMask = select ? selectFaces(mesh, select) : null;
- const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point'), { kind: 'vector' }).values;
+ const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point', loadSurface), { kind: 'vector' }).values;
const fractions = gradient ? gradientFractions(mesh, gradient) : null;
let assignedCorners = 0;
for (let face = 0; face < mesh.faceCount; face++) {
diff --git a/src/mesh-field-edits.js b/src/mesh-field-edits.js
index 82e847b6..defbe301 100644
--- a/src/mesh-field-edits.js
+++ b/src/mesh-field-edits.js
@@ -35,8 +35,8 @@ export function selectedVertices(mesh, rule) {
* Blender's Set Position: `position` (a vector expression, default the current position) and then `offset` (a vector
* expression added to it) for the vertices of the selected faces.
*/
-export function setPosition(mesh, { select, position, offset }) {
- const context = meshFieldContext(mesh, 'point');
+export function setPosition(mesh, { select, position, offset }, loadSurface) {
+ const context = meshFieldContext(mesh, 'point', loadSurface);
const target = position === undefined ? null : evaluateField(position, context, { kind: 'vector' }).values;
const shift = offset === undefined ? null : evaluateField(offset, context, { kind: 'vector' }).values;
const flags = selectedVertices(mesh, select);
@@ -57,8 +57,8 @@ export function setPosition(mesh, { select, position, offset }) {
* Blender's Displace modifier with a field as the texture: each vertex of the selected faces moves by
* (field - midlevel) * strength along its normal or an axis.
*/
-export function displaceMesh(mesh, { select, field, strength = 1, midlevel = 0.5, direction = 'normal', group }) {
- const context = meshFieldContext(mesh, 'point');
+export function displaceMesh(mesh, { select, field, strength = 1, midlevel = 0.5, direction = 'normal', group }, loadSurface) {
+ const context = meshFieldContext(mesh, 'point', loadSurface);
const { values } = evaluateField(field, context, { kind: 'scalar' });
const normals = direction === 'normal' ? vertexNormals(mesh) : null;
const axis = AXIS_DIRECTIONS.get(direction);
diff --git a/src/mesh-field-surfaces.js b/src/mesh-field-surfaces.js
new file mode 100644
index 00000000..3354e964
--- /dev/null
+++ b/src/mesh-field-surfaces.js
@@ -0,0 +1,129 @@
+import { compileNode, constantScalar, isBoundedNumber, isPlainObject, scalarValue, vectorValue } from './expression.js';
+
+// Field inputs that read another surface: "nearest" (Geometry Proximity and Sample Nearest Surface) and "raycast"
+// (Raycast). The surface is named by the caller's context: a geometry id when instances scatter, a geometry record
+// inside a mesh edit. The surface sits in the same local space as the elements asking, and answers come from a
+// triangle BVH, so the same input always gives the same value.
+//
+// { "nearest": { "surface": "path", "read": "distance" } }
+// { "raycast": { "surface": "terrain", "at": { "add": [{ "attr": "position" }, [0, 100, 0] ] }, "direction": [0, -1, 0], "read": "point" } }
+
+const NEAREST_READS = Object.freeze(['distance', 'point', 'normal']);
+const RAYCAST_READS = Object.freeze(['hit', 'distance', 'point', 'normal']);
+const VECTOR_READS = new Set(['point', 'normal']);
+export const MAX_SURFACE_TRIANGLE_TESTS = 20_000_000;
+
+function surfaceError(message) {
+ return new TypeError(`Field expression: ${message}`);
+}
+
+function onlyKeys(settings, allowed, label) {
+ for (const key of Object.keys(settings)) {
+ if (!allowed.includes(key)) throw surfaceError(`${label} does not take ${JSON.stringify(key.slice(0, 24))}; fields: ${allowed.join(', ')}.`);
+ }
+}
+
+/**
+ * Build the lookup a context hands to surface inputs, with one shared work budget. `loadSurface(surface)` returns a
+ * mesh query index (nearest and project); it is called once per distinct surface. The caller builds the index, so
+ * contexts that never read a surface do not pull the query code into their bundle.
+ */
+export function createSurfaceLookup(loadSurface) {
+ const indices = new Map();
+ const budget = { remaining: MAX_SURFACE_TRIANGLE_TESTS };
+ return {
+ budget,
+ indexOf(surface) {
+ if (!loadSurface) throw new RangeError('This context has no surfaces to sample.');
+ const key = typeof surface === 'string' ? surface : JSON.stringify(surface);
+ if (!indices.has(key)) indices.set(key, loadSurface(surface));
+ return indices.get(key);
+ },
+ };
+}
+
+function checkedSurface(settings, label) {
+ const surface = settings.surface;
+ if (typeof surface !== 'string' && !isPlainObject(surface)) throw surfaceError(`${label} needs a surface: a geometry id or a geometry record.`);
+ return surface;
+}
+
+function checkedRead(settings, allowed, fallback, label) {
+ const read = settings.read ?? fallback;
+ if (!allowed.includes(read)) throw surfaceError(`${label} read must be one of ${allowed.join(', ')}.`);
+ return read;
+}
+
+function atParts(settings, state, depth, label, positionInput) {
+ const at = settings.at === undefined ? positionInput() : compileNode(settings.at, state, depth + 1);
+ if (at.kind !== 'vector') throw surfaceError(`${label} "at" needs a vector.`);
+ return at.parts;
+}
+
+// Run the query once per element and share the answer between the three parts of a vector read.
+function readResult(read, queryAt, miss) {
+ const missingValue = miss ?? 0;
+ const cache = { index: -1, found: null };
+ const foundAt = index => {
+ if (cache.index !== index) {
+ cache.found = queryAt(index);
+ cache.index = index;
+ }
+ return cache.found;
+ };
+ if (!VECTOR_READS.has(read)) {
+ return scalarValue(index => {
+ const found = foundAt(index);
+ if (read === 'hit') return found ? 1 : 0;
+ return found ? found.distance : missingValue;
+ });
+ }
+ const part = axis => index => {
+ const found = foundAt(index);
+ return found ? found[read][axis] : missingValue;
+ };
+ return vectorValue(part(0), part(1), part(2));
+}
+
+function chargedQuery(state, run) {
+ const { budget } = state.context.surfaceLookup;
+ const result = run(budget.remaining);
+ budget.remaining -= result.triangleTests;
+ if (budget.remaining <= 0) throw new RangeError('Field expression searched too many surface triangles. Use fewer elements or a simpler surface.');
+ return result.hit;
+}
+
+export function compileNearest(node, state, depth, positionInput) {
+ const settings = node.nearest;
+ if (!isPlainObject(settings)) throw surfaceError('nearest takes { surface, at, read }.');
+ onlyKeys(settings, ['surface', 'at', 'read'], 'nearest');
+ const surface = checkedSurface(settings, 'nearest');
+ const read = checkedRead(settings, NEAREST_READS, 'distance', 'nearest');
+ const [partX, partY, partZ] = atParts(settings, state, depth, 'nearest', positionInput);
+ const lookup = state.context.surfaceLookup;
+ if (!lookup) return VECTOR_READS.has(read) ? vectorValue(() => 0, () => 0, () => 0) : constantScalar(0);
+ const surfaceIndex = lookup.indexOf(surface);
+ return readResult(read, index => chargedQuery(state, remaining => surfaceIndex.nearest([partX(index), partY(index), partZ(index)], { maxTriangleTests: remaining })), 0);
+}
+
+export function compileRaycast(node, state, depth, positionInput) {
+ const settings = node.raycast;
+ if (!isPlainObject(settings)) throw surfaceError('raycast takes { surface, at, direction, read, miss }.');
+ onlyKeys(settings, ['surface', 'at', 'direction', 'read', 'miss', 'maxDistance'], 'raycast');
+ const surface = checkedSurface(settings, 'raycast');
+ const read = checkedRead(settings, RAYCAST_READS, 'hit', 'raycast');
+ const direction = settings.direction;
+ if (!Array.isArray(direction) || direction.length !== 3 || !direction.every(isBoundedNumber) || direction.every(component => component === 0)) {
+ throw surfaceError('raycast direction needs three numbers, not all 0.');
+ }
+ if (settings.miss !== undefined && !isBoundedNumber(settings.miss)) throw surfaceError('raycast miss must be a number.');
+ if (settings.maxDistance !== undefined && !(isBoundedNumber(settings.maxDistance) && settings.maxDistance > 0)) throw surfaceError('raycast maxDistance must be above 0.');
+ const [partX, partY, partZ] = atParts(settings, state, depth, 'raycast', positionInput);
+ const lookup = state.context.surfaceLookup;
+ if (!lookup) return VECTOR_READS.has(read) ? vectorValue(() => 0, () => 0, () => 0) : constantScalar(0);
+ const surfaceIndex = lookup.indexOf(surface);
+ const maxDistance = settings.maxDistance ?? Infinity;
+ return readResult(read, index => chargedQuery(state, remaining => surfaceIndex.project({
+ origin: [partX(index), partY(index), partZ(index)], direction, maxDistance, maxTriangleTests: remaining,
+ })), settings.miss);
+}
diff --git a/src/mesh-fields.js b/src/mesh-fields.js
index b421e9fa..92786fc7 100644
--- a/src/mesh-fields.js
+++ b/src/mesh-fields.js
@@ -1,4 +1,5 @@
-import { TAG_PREFIX, meshTags } from './mesh-data.js';
+import { TAG_PREFIX, meshTags, vertexGroupWeights } from './mesh-data.js';
+import { compileNearest, compileRaycast, createSurfaceLookup } from './mesh-field-surfaces.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 {
@@ -159,7 +160,7 @@ 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']);
+const SOURCE_KEYS = Object.freeze(['attr', 'noise', 'random', 'nearest', 'raycast']);
export const FIELD_OPERATORS = Object.freeze([...OPERATORS.keys(), ...SOURCE_KEYS]);
// ---------------------------------------------------------------------------------------------------------------
@@ -183,6 +184,13 @@ function compileAttribute(node, context) {
if (node.component !== undefined || node.name !== undefined) throw fieldError('index takes no component or name.');
return scalarValue(index => index);
}
+ if (node.attr === 'group') {
+ if (typeof node.name !== 'string' || !TAG_NAME_PATTERN.test(node.name) || node.component !== undefined) {
+ throw fieldError('group needs the name of a vertex group.');
+ }
+ const weights = context.group(node.name);
+ return scalarValue(index => weights[index]);
+ }
if (node.attr === 'tag') {
if (typeof node.name !== 'string' || !TAG_NAME_PATTERN.test(node.name) || node.component !== undefined) {
throw fieldError('tag needs a name of 1 to 48 letters, digits, dots, dashes or underscores.');
@@ -238,12 +246,15 @@ function compileInput(node, state, depth) {
if (keys.length !== 1) return undefined;
if (keys[0] === 'noise') return compileNoise(node, state, depth);
if (keys[0] === 'random') return compileRandom(node);
+ const positionInput = () => compileAttribute({ attr: 'position' }, state.context);
+ if (keys[0] === 'nearest') return compileNearest(node, state, depth, positionInput);
+ if (keys[0] === 'raycast') return compileRaycast(node, state, depth, positionInput);
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',
+ accepts: 'a number, a boolean, a vector of three numbers, an attribute, noise, random, nearest, raycast or an operator object',
maxNodes: MAX_FIELD_NODES,
maxDepth: MAX_FIELD_DEPTH,
operators: OPERATORS,
@@ -275,7 +286,7 @@ export function validateField(expression, { kind } = {}) {
}
const EMPTY = new Float64Array(0);
-const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY });
+const VALIDATION_CONTEXT = Object.freeze({ count: 0, positions: () => EMPTY, normals: () => EMPTY, tag: () => EMPTY, group: () => EMPTY, surfaceLookup: null });
function finiteValues(source, count, width) {
const values = new Float64Array(count * width);
@@ -287,7 +298,7 @@ function finiteValues(source, count, width) {
// Contexts: the elements an expression runs over.
/** A mesh domain: "point" (one element per vertex) or "face" (one per face). Face values average from points and back. */
-export function meshFieldContext(mesh, domain) {
+export function meshFieldContext(mesh, domain, loadSurface) {
if (domain !== 'point' && domain !== 'face') throw fieldError('domain must be point or face.');
const isPoint = domain === 'point';
const cache = {};
@@ -295,6 +306,11 @@ export function meshFieldContext(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),
+ surfaceLookup: createSurfaceLookup(loadSurface),
+ group: name => {
+ const weights = vertexGroupWeights(mesh, name);
+ return isPoint ? weights : faceGroupAverage(mesh, weights);
+ },
tag: name => {
const attribute = mesh.attributes.face[TAG_PREFIX + name];
if (!attribute) throw new RangeError(`Unknown tag ${name}. Known tags: ${meshTags(mesh).join(', ') || 'none'}.`);
@@ -303,6 +319,18 @@ export function meshFieldContext(mesh, domain) {
};
}
+function faceGroupAverage(mesh, pointWeights) {
+ const averages = new Float64Array(mesh.faceCount);
+ for (let face = 0; face < mesh.faceCount; face++) {
+ const start = mesh.faceOffsets[face];
+ const end = mesh.faceOffsets[face + 1];
+ let sum = 0;
+ for (let corner = start; corner < end; corner++) sum += pointWeights[mesh.cornerVertices[corner]];
+ averages[face] = sum / (end - start);
+ }
+ return averages;
+}
+
function pointTagAverage(mesh, faceValues) {
const sums = new Float64Array(mesh.vertexCount);
const counts = new Uint32Array(mesh.vertexCount);
@@ -318,11 +346,15 @@ function pointTagAverage(mesh, faceValues) {
}
/** A free point set (instance candidates): positions and optional normals, flat arrays of three numbers per point. */
-export function pointSetContext(positions, normals) {
+export function pointSetContext(positions, normals, loadSurface) {
return {
count: positions.length / 3,
positions: () => positions,
normals: () => normals,
+ surfaceLookup: createSurfaceLookup(loadSurface),
+ group: name => {
+ throw new RangeError(`Unknown vertex group ${name}. Point sets carry no groups.`);
+ },
tag: name => {
throw new RangeError(`Unknown tag ${name}. Point sets carry no tags.`);
},
diff --git a/src/mesh-instances.js b/src/mesh-instances.js
index 94d4de69..b711a7a4 100644
--- a/src/mesh-instances.js
+++ b/src/mesh-instances.js
@@ -1,6 +1,7 @@
import { quat } from 'gl-matrix';
import { INSTANCE_SOURCES, MAX_INSTANCE_CANDIDATES } from './mesh-operations.js';
import { evaluateField, pointSetContext, seededRandom } from './mesh-fields.js';
+import { createTriangleSurfaceIndex } from './mesh-query.js';
// Instance on points: a node with an `instances` record becomes a group node plus one child node per point, all
// sharing the node's geometry and material, so the renderer draws them in one instanced call. Points come from a
@@ -152,7 +153,7 @@ function candidatePoints(spec, seed, resolveSurface) {
return surfacePoints(resolveSurface(source.geometry), count, seed);
}
-function keptIndices(spec, points) {
+function keptIndices(spec, points, resolveSurface) {
const count = points.positions.length / 3;
const kept = [];
if (spec.where === undefined) {
@@ -160,7 +161,11 @@ function keptIndices(spec, points) {
return kept;
}
const normals = points.normals ?? Float64Array.from({ length: count * 3 }, (unused, position) => UP[position % 3]);
- const { values } = evaluateField(spec.where, pointSetContext(points.positions, normals), { kind: 'scalar' });
+ const loadSurface = surface => {
+ if (typeof surface !== 'string') throw instanceError('a where field reads a surface by its geometry id.');
+ return createTriangleSurfaceIndex(resolveSurface(surface));
+ };
+ const { values } = evaluateField(spec.where, pointSetContext(points.positions, normals, loadSurface), { kind: 'scalar' });
for (let index = 0; index < count; index++) {
if (values[index] !== 0) kept.push(index);
}
@@ -219,7 +224,7 @@ export function expandInstancedNodes(nodes, { resolveSurface, maxNodes }) {
const seed = checkedSpec(spec);
const points = candidatePoints(spec, seed, resolveSurface);
expanded.push(group);
- for (const [slot, candidate] of keptIndices(spec, points).entries()) {
+ for (const [slot, candidate] of keptIndices(spec, points, resolveSurface).entries()) {
const scale = instanceScale(spec, seed, candidate);
expanded.push({
id: `${node.id}.${slot}`, parent: node.id, geometry, material,
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index f1cf9d9b..5025d84b 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -78,13 +78,13 @@ export const MAX_FIELD_NODES = 64;
export const MAX_FIELD_DEPTH = 12;
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_ATTRIBUTES = Object.freeze(['position', 'normal', 'index', 'tag', 'group']);
export const FIELD_OPERATOR_NAMES = Object.freeze([
'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',
+ 'attr', 'noise', 'random', 'nearest', 'raycast',
]);
export const INSTANCE_SOURCES = Object.freeze(['grid', 'scatter', 'surface']);
export const MAX_INSTANCE_CANDIDATES = 2048;
diff --git a/src/mesh-query.js b/src/mesh-query.js
index 5b03668f..3e751f25 100644
--- a/src/mesh-query.js
+++ b/src/mesh-query.js
@@ -607,3 +607,8 @@ export function createMeshPairQuery(indexA, indexB, options = {}) {
},
});
}
+
+/** A query index over indexed triangles in any typed or plain arrays, for callers that hold render geometry or MeshData triangles. */
+export function createTriangleSurfaceIndex({ positions, indices }) {
+ return createMeshQueryIndex({ positions: Float32Array.from(positions), indices: Uint32Array.from(indices) });
+}
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index ae260c3c..be6274e2 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -20,6 +20,8 @@ import { decimateMesh } from './mesh-decimate.js';
import { isModifierOperation, normalizeModifierEdit, runModifierEdit } from './mesh-modifiers.js';
import { sculptMesh, checkSculptBudget } from './mesh-sculpt.js';
import { shrinkwrapMesh } from './mesh-shrinkwrap.js';
+import { triangulatedSurface } from './mesh-surface-distance.js';
+import { createTriangleSurfaceIndex } from './mesh-query.js';
import { remeshMesh, remeshGridSize, MAX_REMESH_RESOLUTION } from './mesh-remesh.js';
import {
MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES, SCULPT_STROKE_TYPES, MAX_SCULPT_STROKES, SHRINKWRAP_MODES,
@@ -368,7 +370,16 @@ function runShrinkwrap(current, edit, resolveCutter) {
}
/** Run one normalized edit on MeshData and describe what it did. */
+// Field inputs that read another surface take a geometry record here, built by the same resolver as a boolean cutter.
+function surfaceLoader(resolveCutter) {
+ return surface => {
+ if (!resolveCutter || typeof surface === 'string') throw new TypeError('A mesh edit field reads a surface given as a geometry record such as { "type": "terrain", ... }, not an id.');
+ return createTriangleSurfaceIndex(triangulatedSurface(resolveCutter(surface)));
+ };
+}
+
function runEdit(current, edit, index, { resolveCutter, limits }) {
+ const loadSurface = surfaceLoader(resolveCutter);
const result = { op: edit.op };
if (edit.name) result.name = edit.name;
if (isModifierOperation(edit.op)) {
@@ -447,7 +458,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
if (edit.op === 'set_position' || edit.op === 'displace') {
let outcome;
try {
- outcome = edit.op === 'set_position' ? setPosition(current, edit) : displaceMesh(current, edit);
+ outcome = edit.op === 'set_position' ? setPosition(current, edit, loadSurface) : displaceMesh(current, edit, loadSurface);
} catch (error) {
throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
}
@@ -457,7 +468,7 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
if (edit.op === 'vertex_group' || edit.op === 'vertex_color') {
let outcome;
try {
- outcome = edit.op === 'vertex_group' ? setVertexGroup(current, edit) : setVertexColor(current, edit);
+ outcome = edit.op === 'vertex_group' ? setVertexGroup(current, edit, loadSurface) : setVertexColor(current, edit, loadSurface);
} catch (error) {
throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
}
diff --git a/tests/mesh-field-surfaces.test.js b/tests/mesh-field-surfaces.test.js
new file mode 100644
index 00000000..a582a0b3
--- /dev/null
+++ b/tests/mesh-field-surfaces.test.js
@@ -0,0 +1,84 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { grid as gridGeometry } from '../src/geometry.js';
+import { meshFromGeometry, applyMeshEdits } from '../src/mesh.js';
+import { vertexGroupWeights } from '../src/mesh-data.js';
+import { expandInstancedNodes } from '../src/mesh-instances.js';
+import { validateField } from '../src/mesh-fields.js';
+
+// A quad on a slope, y = 0.5 x, from x -10 to 10 and z -halfDepth to halfDepth. The terrain is wide, the path a strip of it.
+function slopedQuad(halfDepth) {
+ const heightAt = coordinate => coordinate * 0.5;
+ const positions = new Float32Array([
+ -10, heightAt(-10), -halfDepth, 10, heightAt(10), -halfDepth, 10, heightAt(10), halfDepth, -10, heightAt(-10), halfDepth,
+ ]);
+ const normals = new Float32Array([-0.4472, 0.8944, 0, -0.4472, 0.8944, 0, -0.4472, 0.8944, 0, -0.4472, 0.8944, 0]);
+ return { positions, normals, indices: new Uint32Array([0, 2, 1, 0, 3, 2]) };
+}
+
+const terrain = slopedQuad(10);
+const surfaces = { terrain, path: slopedQuad(1) };
+const options = { maxNodes: 4096, resolveSurface: id => surfaces[id] };
+const grass = { id: 'grass', geometry: 'blade', material: 'green' };
+const AWAY_FROM_PATH = { gt: [{ nearest: { surface: 'path', read: 'distance' } }, 2] };
+
+function placements(spec) {
+ return expandInstancedNodes([{ ...grass, instances: spec }], options).filter(node => node.parent === 'grass').map(node => node.translation);
+}
+
+test('scatter on terrain avoids a path mesh and follows the terrain height', () => {
+ const kept = placements({ surface: { geometry: 'terrain', count: 400 }, seed: 4, where: AWAY_FROM_PATH });
+ assert.ok(kept.length > 100 && kept.length < 400, `kept ${kept.length} of 400`);
+ for (const [x, y, z] of kept) {
+ assert.ok(Math.abs(z) > 2 - 1e-6, `point at z ${z} is on the path`);
+ assert.ok(Math.abs(y - x * 0.5) < 1e-4, 'point is off the terrain slope');
+ }
+});
+
+test('results repeat for the same seed and change with another', () => {
+ const spec = { surface: { geometry: 'terrain', count: 100 }, seed: 9, where: AWAY_FROM_PATH };
+ assert.deepEqual(placements(spec), placements(spec));
+ assert.notDeepEqual(placements(spec), placements({ ...spec, seed: 10 }));
+});
+
+test('a raycast keeps a box scatter that has terrain below it and drops the rest', () => {
+ const hits = placements({
+ scatter: { count: 300, min: [-20, 0, -5], max: [20, 0, 5] }, seed: 2,
+ where: { raycast: { surface: 'terrain', at: { add: [{ attr: 'position' }, [0, 50, 0]] }, direction: [0, -1, 0], read: 'hit' } },
+ });
+ assert.ok(hits.length > 50 && hits.length < 300);
+ for (const [x] of hits) assert.ok(Math.abs(x) <= 10 + 1e-6);
+});
+
+test('a mesh edit snaps a flat grid to terrain height and stores proximity as a named group', () => {
+ const sheet = meshFromGeometry(gridGeometry(4));
+ const terrainRecord = { type: 'terrain-stand-in' };
+ const resolveCutter = record => {
+ assert.deepEqual(record, terrainRecord);
+ return meshFromGeometry(terrain);
+ };
+ const above = { add: [{ attr: 'position' }, [0, 50, 0]] };
+ const result = applyMeshEdits(sheet, [
+ { op: 'set_position', position: { raycast: { surface: terrainRecord, at: above, direction: [0, -1, 0], read: 'point' } } },
+ { op: 'vertex_group', name: 'nearby', field: { saturate: { sub: [1, { nearest: { surface: terrainRecord, at: { add: [{ attr: 'position' }, [0, 1, 0]] }, read: 'distance' } }] } } },
+ { op: 'vertex_group', name: 'copy', field: { attr: 'group', name: 'nearby' } },
+ ], { resolveCutter });
+ for (let vertex = 0; vertex < result.mesh.vertexCount; vertex++) {
+ const x = result.mesh.positions[vertex * 3];
+ assert.ok(Math.abs(result.mesh.positions[vertex * 3 + 1] - x * 0.5) < 1e-4);
+ }
+ assert.deepEqual(vertexGroupWeights(result.mesh, 'copy'), vertexGroupWeights(result.mesh, 'nearby'));
+});
+
+test('surface inputs are validated without a surface and reject bad records', () => {
+ assert.equal(validateField({ nearest: { surface: 'path' } }), 'scalar');
+ assert.equal(validateField({ nearest: { surface: 'path', read: 'normal' } }), 'vector');
+ assert.throws(() => validateField({ nearest: { read: 'distance' } }), /needs a surface/);
+ assert.throws(() => validateField({ nearest: { surface: 'path', read: 'height' } }), /read must be one of/);
+ assert.throws(() => validateField({ raycast: { surface: 'path' } }), /direction/);
+ assert.throws(() => validateField({ raycast: { surface: 'path', direction: [0, 0, 0] } }), /direction/);
+ assert.throws(() => validateField({ nearest: { surface: 'path', code: 'x' } }), /does not take/);
+ const sheet = meshFromGeometry(gridGeometry(2));
+ assert.throws(() => applyMeshEdits(sheet, [{ op: 'vertex_group', name: 'a', field: { nearest: { surface: 'path' } } }]), /geometry record/);
+});