3D engine that AI agents drive
Add geometry masks: curvature, edge and occlusion measures for vertex groups (#708)
Nguyen Xuan An6b571cf0d103
diff --git a/changes/708-masks.md b/changes/708-masks.mdnew file mode 100644index 00000000..e37bd103--- /dev/null+++ b/changes/708-masks.md@@ -0,0 +1 @@+- Mesh edits gain geometry masks: vertex_group measure curvature, edge or occlusion, and vertex_color gradients along a group, so a mesh with no UVs can carry edge wear and dirt (#708)diff --git a/changes/708-masks.size.md b/changes/708-masks.size.mdnew file mode 100644index 00000000..d1a65d46--- /dev/null+++ b/changes/708-masks.size.md@@ -0,0 +1,2 @@+- scene:agent-scene: the measure and group-gradient text sits in scene_capabilities (agents read it to use the masks), and the measures with their validation are part of the mesh edit code, which the agent scene always loads+- goal:agent-scene: the bundle is over its goal already; the growth is agent-facing capability (edge wear and cavity dirt on a mesh with no UVs) with a rendered proofdiff --git a/docs/mesh.md b/docs/mesh.mdindex 973b183e..05ad5c8a 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -305,13 +305,21 @@ Uses:the texture: each vertex moves by `(field - midlevel) * strength` along `normal` (default), `x`, `y` or `z`.`displace` also takes `group`, the name of a vertex group: each move is scaled by the vertex's weight.- Both are also stack nodes, so a late change reuses the cached earlier nodes.-- `vertex_group` (`name`, `select`, and one of `weight`, `field` or `gradient`) writes the weights, 0 to 1, of a named group for the+- `vertex_group` (`name`, `select`, and one of `weight`, `field`, `gradient` or `measure`) writes the weights, 0 to 1, of a named group for thevertices of the selected faces; the others keep theirs (0 in a new group). `gradient` is `{ "axis": "y", "range": [0, 1], "weights": [0, 1] }`,a straight blend between the weights at the two ends of the range along the axis. Up to 32 groups. `displace` reads one with`group`, and a cloth sheet holds the vertices of weight 0.5 or more with `pinGroup` (see [physics.md](physics.md)). Groups arepoint attributes: run `vertex_group` after the shape edits, because a stack node that rebuilds the mesh (`mirror`, `array`) drops them.+ `measure` fills the group from the mesh itself, so a mesh with no UVs can tell an edge from a cavity: `curvature` (`gain` 2, 0.1 to 16) is 0.5 on a flat+ surface, above it on a convex bulge and below it in a concave dent; `edge` (`angle` 30 degrees, 1 to 179) is 1 on a convex fold at or past the angle and 0+ elsewhere, and a concave fold gives 0; `occlusion` (`rays` 32, 1 to 128; `distance` in metres, default a quarter of the bounding box diagonal; `seed` 0) is the+ share of cosine-weighted rays from the vertex that hit the mesh within `distance`, 1 deep in a cavity. All three are deterministic: the same mesh and seed give+ the same bytes. Occlusion casts at most 2 million rays in all and names the fix when a `select` holds too many vertices; it needs vertices where the detail is, so+ cut the mesh first (`subdivide_edges`). Edge wear needs the geometry to carry the fold: bevel the edge and cut the faces so a vertex sits on it.- `vertex_color` (`select`, and one of `color`, `field` or `gradient`) sets the corner colors of the selected faces. `color` is`[r, g, b]` from 0 to 1, `field` a vector expression of the vertex, and `gradient` is `{ "axis": "y", "range": [0, 1], "colors": [[0, 0, 1], [1, 0, 0]] }`.+ `gradient` can also follow a vertex group instead of an axis: `{ "group": "wear", "colors": [dirt, paint, metal] }` blends two colors from weight 0 to 1, or three at+ weights 0, 0.5 and 1, so `curvature` gives dirt in the dents, paint on flat faces and bare metal on the convex edges.The renderer multiplies the material color by it and a GLB export writes it as `COLOR_0`. Faces not selected stay white until painted.- `instances` on a recipe node repeats its geometry at points; see [agent-scene.md](agent-scene.md#instances-on-points).diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 387e6029..b67f51a9 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -168,8 +168,8 @@ 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. One of weight (1), field 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. 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.',+ vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs. One of weight (1), field, gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] } or measure curvature (gain 0.1-16, 2; 0.5 flat, up convex), edge (angle 1-179 deg, 30; convex folds) or occlusion (rays 1-128, 32; distance m; seed). Max 32 groups. displace takes group: name and scales each move by the weight; cloth takes pinGroup. 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] } or { group, colors } of 2 or 3 stops along a vertex group's weights (edge wear: curvature group, colors [dirt, paint, metal]). Drawn, written as COLOR_0 in a GLB, and multiplies the material color.',});// UV projection and packing edits. Details stay here so the tool schemas stay small.diff --git a/src/mesh-attribute-edits.js b/src/mesh-attribute-edits.jsindex 3ee20c38..62562520 100644--- a/src/mesh-attribute-edits.js+++ b/src/mesh-attribute-edits.js@@ -1,4 +1,5 @@-import { createMeshData, GROUP_PREFIX, vertexGroupNames } from './mesh-data.js';+import { createMeshData, GROUP_PREFIX, vertexGroupNames, vertexGroupWeights } from './mesh-data.js';+import { MASK_MEASURES, MASK_LIMITS, checkOcclusionWork, measureVertexMask } from './mesh-masks.js';import { evaluateField, meshFieldContext } from './mesh-fields.js';import { selectedVertices } from './mesh-field-edits.js';import { selectFaces } from './mesh-select.js';@@ -17,11 +18,23 @@ function unitNumber(value, index, label, finiteNumber) {return finiteNumber(value, index, label, { minimum: 0, maximum: 1 });}+function normalizeGroupGradient(gradient, normalized, index, readValue) {+ for (const key of Object.keys(gradient)) {+ if (!['group', 'colors'].includes(key)) throw editField(index, `gradient.${key}`, gradient[key], `one of the group gradient fields group, colors; remove "${key}"`);+ }+ if (typeof gradient.group !== 'string' || gradient.group === '') throw editField(index, 'gradient.group', gradient.group, 'the name of a vertex group, such as "wear"');+ if (!Array.isArray(gradient.colors) || gradient.colors.length < 2 || gradient.colors.length > 3) {+ throw editField(index, 'gradient.colors', gradient.colors, 'two colors (weight 0 then 1) or three (weight 0, 0.5 then 1), such as [[0.1, 0.1, 0.1], [0.8, 0.1, 0.1], [0.8, 0.8, 0.8]]');+ }+ normalized.gradient = { group: gradient.group, colors: gradient.colors.map((value, stop) => readValue(value, `gradient.colors[${stop}]`)) };+}+function normalizeGradient(gradient, normalized, index, { finiteNumber, valuesKey, readValue }) {const example = valuesKey === 'weights' ? '[0, 1]' : '[[1, 0, 0], [0, 0, 1]]';if (!gradient || typeof gradient !== 'object' || Array.isArray(gradient)) {throw editField(index, 'gradient', gradient, `an object such as { "axis": "z", "range": [0, 1], "${valuesKey}": ${example} }`);}+ if (gradient.group !== undefined && valuesKey === 'colors') return normalizeGroupGradient(gradient, normalized, index, readValue);for (const key of Object.keys(gradient)) {if (!['axis', 'range', valuesKey].includes(key)) throw editField(index, `gradient.${key}`, gradient[key], `one of the gradient fields axis, range, ${valuesKey}; remove "${key}"`);}@@ -41,10 +54,36 @@ function rejectSecondSource(edit, index, sources) {return given[0];}+const MEASURE_SETTINGS = Object.freeze({ curvature: ['gain'], edge: ['angle'], occlusion: ['rays', 'distance', 'seed'] });++function normalizeMeasure(edit, normalized, index, finiteNumber) {+ if (!MASK_MEASURES.includes(edit.measure)) throw editField(index, 'measure', edit.measure, `one of ${MASK_MEASURES.join(', ')}`);+ normalized.measure = edit.measure;+ const allowed = MEASURE_SETTINGS[edit.measure];+ for (const setting of Object.keys(MASK_LIMITS).filter(name => Array.isArray(MASK_LIMITS[name])).concat('distance')) {+ if (edit[setting] === undefined) continue;+ if (!allowed.includes(setting)) throw editField(index, setting, edit[setting], `left out, because measure "${edit.measure}" takes ${allowed.join(', ')}`);+ if (setting === 'distance') {+ normalized.distance = finiteNumber(edit.distance, index, 'distance', { minimum: 0, exclusiveMinimum: true });+ } else if (setting === 'rays' || setting === 'seed') {+ const [minimum, maximum] = MASK_LIMITS[setting];+ if (!Number.isInteger(edit[setting]) || edit[setting] < minimum || edit[setting] > maximum) {+ throw editField(index, setting, edit[setting], `a whole number from ${minimum} to ${maximum}`);+ }+ normalized[setting] = edit[setting];+ } else {+ const [minimum, maximum] = MASK_LIMITS[setting];+ normalized[setting] = finiteNumber(edit[setting], index, setting, { minimum, maximum });+ }+ }+}+/** Validate a vertex_group edit: a required name and at most one of weight, field or gradient (default weight 1). */export function normalizeVertexGroupEdit(edit, normalized, index, { finiteNumber, checkedField }) {- const source = rejectSecondSource(edit, index, ['weight', 'field', 'gradient']);- if (source === 'field') {+ const source = rejectSecondSource(edit, index, ['weight', 'field', 'gradient', 'measure']);+ if (source === 'measure') {+ normalizeMeasure(edit, normalized, index, finiteNumber);+ } else if (source === 'field') {normalized.field = checkedField(edit.field, index, 'field', 'scalar');} else if (source === 'gradient') {normalizeGradient(edit.gradient, normalized, index, {@@ -92,8 +131,19 @@ function gradientFractions(mesh, gradient) {return fractions;}+// Colors along the weights of a vertex group: two stops sit at weight 0 and 1, three at 0, 0.5 and 1.+function groupStops(mesh, { group, colors }) {+ const weights = vertexGroupWeights(mesh, group);+ const lastStop = colors.length - 1;+ return (vertex, channel) => {+ const position = Math.min(1, Math.max(0, weights[vertex])) * lastStop;+ const lower = Math.min(lastStop - 1, Math.floor(position));+ return colors[lower][channel] + (colors[lower + 1][channel] - colors[lower][channel]) * (position - lower);+ };+}+/** 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 }, loadSurface) {+export function setVertexGroup(mesh, { select, name, weight, field, gradient, measure, ...measureSettings }, loadSurface) {const attributeName = GROUP_PREFIX + name;const existing = mesh.attributes.point[attributeName];if (!existing && vertexGroupNames(mesh).length >= MAX_VERTEX_GROUPS) {@@ -102,13 +152,16 @@ 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', loadSurface), { kind: 'scalar' }).values;- const fractions = gradient ? gradientFractions(mesh, gradient) : null;+ const fractions = gradient?.axis ? gradientFractions(mesh, gradient) : null;+ if (measure === 'occlusion') checkOcclusionWork(flags.reduce((count, flag) => count + (flag ? 1 : 0), 0), measureSettings.rays ?? 32);+ const measured = measure ? measureVertexMask(mesh, measure, measureSettings, flags) : null;let assignedVertices = 0;for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {if (!flags[vertex]) continue;assignedVertices++;let value = weight;if (fieldValues) value = fieldValues[vertex];+ if (measured) value = measured[vertex];if (fractions) value = gradient.weights[0] + (gradient.weights[1] - gradient.weights[0]) * fractions[vertex];weights[vertex] = Math.min(1, Math.max(0, value));}@@ -121,7 +174,8 @@ export function setVertexColor(mesh, { select, color, field, gradient }, loadSurconst 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', loadSurface), { kind: 'vector' }).values;- const fractions = gradient ? gradientFractions(mesh, gradient) : null;+ const fractions = gradient?.axis ? gradientFractions(mesh, gradient) : null;+ const stopped = gradient?.group === undefined ? null : groupStops(mesh, gradient);let assignedCorners = 0;for (let face = 0; face < mesh.faceCount; face++) {if (faceMask && !faceMask[face]) continue;@@ -132,6 +186,7 @@ export function setVertexColor(mesh, { select, color, field, gradient }, loadSurlet value = color?.[channel];if (fieldValues) value = fieldValues[vertex * 3 + channel];if (fractions) value = gradient.colors[0][channel] + (gradient.colors[1][channel] - gradient.colors[0][channel]) * fractions[vertex];+ if (stopped) value = stopped(vertex, channel);colors[corner * 3 + channel] = Math.min(1, Math.max(0, value));}}diff --git a/src/mesh-masks.js b/src/mesh-masks.jsnew file mode 100644index 00000000..1b560e65--- /dev/null+++ b/src/mesh-masks.js@@ -0,0 +1,171 @@+import { faceCentroids, faceNormals, vertexNormals } from './mesh-normals.js';+import { edgeCornerTable, cornerFaces } from './mesh-topology.js';+import { seededRandom } from './mesh-fields.js';+import { createMeshQueryIndex } from './mesh-query.js';+import { triangulatedSurface } from './mesh-surface-distance.js';+import { meshBounds } from './mesh-data.js';++// Geometry masks: one weight from 0 to 1 for each vertex, measured from the mesh itself, so a material can tell an+// edge from a cavity on a mesh that has no UVs. They are written into a vertex group (the vertex_group edit with a+// `measure`), and a vertex_color gradient reads that group. Every measure is deterministic: the same mesh and the same+// seed give the same bytes.+//+// curvature 0.5 on a flat surface, up to 1 on a convex bulge and down to 0 in a concave dent.+// edge 1 on a convex edge sharper than `angle`, 0 away from edges (concave edges give 0).+// occlusion the share of `rays` cosine-weighted rays that hit the mesh within `distance`; 1 deep in a cavity, 0 in the open.++export const MASK_MEASURES = Object.freeze(['curvature', 'edge', 'occlusion']);+export const MASK_LIMITS = Object.freeze({+ gain: Object.freeze([0.1, 16]),+ angle: Object.freeze([1, 179]),+ rays: Object.freeze([1, 128]),+ seed: Object.freeze([0, 2147483647]),+ maxRayCasts: 2_000_000,+ maxTriangleTests: 20_000_000,+});+export const MASK_DEFAULTS = Object.freeze({ gain: 2, angle: 30, rays: 32, seed: 0 });++const RAY_START_OFFSET = 1e-4;+const DEFAULT_DISTANCE_SHARE = 0.25;++function clampUnit(value) {+ return Math.min(1, Math.max(0, value));+}++/** Signed curvature from the edges around each vertex: how far the neighbours fall below the tangent plane. */+function measureCurvature(mesh, gain) {+ const normals = vertexNormals(mesh);+ const normalSums = new Float64Array(mesh.vertexCount);+ const lengthSums = new Float64Array(mesh.vertexCount);+ const positions = mesh.positions;+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ const deltaX = positions[second * 3] - positions[first * 3];+ const deltaY = positions[second * 3 + 1] - positions[first * 3 + 1];+ const deltaZ = positions[second * 3 + 2] - positions[first * 3 + 2];+ const length = Math.hypot(deltaX, deltaY, deltaZ);+ if (length === 0) continue;+ normalSums[first] += deltaX * normals[first * 3] + deltaY * normals[first * 3 + 1] + deltaZ * normals[first * 3 + 2];+ normalSums[second] -= deltaX * normals[second * 3] + deltaY * normals[second * 3 + 1] + deltaZ * normals[second * 3 + 2];+ lengthSums[first] += length;+ lengthSums[second] += length;+ }+ const weights = new Float32Array(mesh.vertexCount);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const convexity = lengthSums[vertex] > 0 ? -normalSums[vertex] / lengthSums[vertex] : 0;+ weights[vertex] = clampUnit(0.5 + gain * convexity);+ }+ return weights;+}++/** The sharpest convex fold among the edges of each vertex, as a share of `angleDegrees`. */+function measureEdge(mesh, angleDegrees) {+ const { normals } = faceNormals(mesh);+ const centroids = faceCentroids(mesh);+ const facesOfCorners = cornerFaces(mesh);+ const { edgeOffsets, edgeCorners } = edgeCornerTable(mesh);+ const limit = (angleDegrees * Math.PI) / 180;+ const weights = new Float32Array(mesh.vertexCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (edgeOffsets[edge + 1] - edgeOffsets[edge] !== 2) continue;+ const faceA = facesOfCorners[edgeCorners[edgeOffsets[edge]]];+ const faceB = facesOfCorners[edgeCorners[edgeOffsets[edge] + 1]];+ const alongA = normals[faceA * 3] * (centroids[faceB * 3] - centroids[faceA * 3])+ + normals[faceA * 3 + 1] * (centroids[faceB * 3 + 1] - centroids[faceA * 3 + 1])+ + normals[faceA * 3 + 2] * (centroids[faceB * 3 + 2] - centroids[faceA * 3 + 2]);+ if (alongA >= 0) continue;+ const cosine = normals[faceA * 3] * normals[faceB * 3] + normals[faceA * 3 + 1] * normals[faceB * 3 + 1] + normals[faceA * 3 + 2] * normals[faceB * 3 + 2];+ const share = clampUnit(Math.acos(Math.max(-1, Math.min(1, cosine))) / limit);+ for (const vertex of [mesh.edgeVertices[edge * 2], mesh.edgeVertices[edge * 2 + 1]]) {+ weights[vertex] = Math.max(weights[vertex], share);+ }+ }+ return weights;+}++// A cosine-weighted direction in the hemisphere around a unit normal, from two numbers in 0 to 1.+function hemisphereDirection(normalX, normalY, normalZ, firstRandom, secondRandom) {+ const useY = Math.abs(normalX) > 0.9;+ let tangentX = useY ? 0 : 1;+ let tangentY = useY ? 1 : 0;+ const tangentDot = tangentX * normalX + tangentY * normalY;+ tangentX -= tangentDot * normalX;+ tangentY -= tangentDot * normalY;+ const tangentZ = -tangentDot * normalZ;+ const tangentLength = Math.hypot(tangentX, tangentY, tangentZ);+ tangentX /= tangentLength;+ tangentY /= tangentLength;+ const unitTangentZ = tangentZ / tangentLength;+ const bitangentX = normalY * unitTangentZ - normalZ * tangentY;+ const bitangentY = normalZ * tangentX - normalX * unitTangentZ;+ const bitangentZ = normalX * tangentY - normalY * tangentX;+ const radius = Math.sqrt(firstRandom);+ const angle = 2 * Math.PI * secondRandom;+ const sideways = radius * Math.cos(angle);+ const forwards = radius * Math.sin(angle);+ const upwards = Math.sqrt(Math.max(0, 1 - firstRandom));+ return [+ tangentX * sideways + bitangentX * forwards + normalX * upwards,+ tangentY * sideways + bitangentY * forwards + normalY * upwards,+ unitTangentZ * sideways + bitangentZ * forwards + normalZ * upwards,+ ];+}++/** The share of rays from each selected vertex that hit the mesh within `distance`. Other vertices stay 0. */+function measureOcclusion(mesh, selectedFlags, { rays, distance, seed }) {+ const normals = vertexNormals(mesh);+ const bounds = meshBounds(mesh);+ const extent = Math.hypot(bounds.max[0] - bounds.min[0], bounds.max[1] - bounds.min[1], bounds.max[2] - bounds.min[2]);+ const reach = distance ?? extent * DEFAULT_DISTANCE_SHARE;+ const surface = triangulatedSurface(mesh);+ const index = createMeshQueryIndex({ positions: new Float32Array(surface.positions), indices: surface.indices });+ const weights = new Float32Array(mesh.vertexCount);+ let triangleTests = 0;+ try {+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!selectedFlags[vertex]) continue;+ const normalX = normals[vertex * 3];+ const normalY = normals[vertex * 3 + 1];+ const normalZ = normals[vertex * 3 + 2];+ if (normalX === 0 && normalY === 0 && normalZ === 0) continue;+ const origin = [+ mesh.positions[vertex * 3] + normalX * extent * RAY_START_OFFSET,+ mesh.positions[vertex * 3 + 1] + normalY * extent * RAY_START_OFFSET,+ mesh.positions[vertex * 3 + 2] + normalZ * extent * RAY_START_OFFSET,+ ];+ let blocked = 0;+ for (let ray = 0; ray < rays; ray++) {+ const direction = hemisphereDirection(normalX, normalY, normalZ, seededRandom(vertex, ray * 2, seed), seededRandom(vertex, ray * 2 + 1, seed));+ const found = index.project({ origin, direction, maxDistance: reach, maxTriangleTests: MASK_LIMITS.maxTriangleTests - triangleTests });+ triangleTests += found.triangleTests;+ if (found.hit) blocked++;+ }+ weights[vertex] = blocked / rays;+ }+ } finally {+ index.dispose();+ }+ return weights;+}++/** Cost check for an occlusion measure, before any ray is cast. Throws a RangeError that says what to pass. */+export function checkOcclusionWork(selectedVertexCount, rays) {+ if (selectedVertexCount * rays > MASK_LIMITS.maxRayCasts) {+ throw new RangeError(`Occlusion would cast ${selectedVertexCount * rays} rays; the limit is ${MASK_LIMITS.maxRayCasts}. Pass fewer rays, or a select that holds fewer vertices.`);+ }+}++/**+ * One weight in 0 to 1 for every vertex of the mesh. `settings` holds the numbers the edit validated: gain (curvature),+ * angle in degrees (edge), rays, distance in metres (default a quarter of the bounding box diagonal) and seed (occlusion).+ * Occlusion measures only the vertices flagged in `selectedFlags`.+ */+export function measureVertexMask(mesh, measure, settings, selectedFlags) {+ if (measure === 'curvature') return measureCurvature(mesh, settings.gain ?? MASK_DEFAULTS.gain);+ if (measure === 'edge') return measureEdge(mesh, settings.angle ?? MASK_DEFAULTS.angle);+ if (measure === 'occlusion') {+ return measureOcclusion(mesh, selectedFlags, { rays: settings.rays ?? MASK_DEFAULTS.rays, distance: settings.distance, seed: settings.seed ?? MASK_DEFAULTS.seed });+ }+ throw new RangeError(`Unknown measure ${measure}. Use one of ${MASK_MEASURES.join(', ')}.`);+}diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 778af523..0422da7f 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -70,7 +70,7 @@ export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({circularize: { fields: ['verts', 'factor', 'regular'], tags: [] },set_position: { fields: ['select', 'position', 'offset'], tags: [] },displace: { fields: ['select', 'field', 'strength', 'midlevel', 'direction', 'group'], tags: [] },- vertex_group: { fields: ['select', 'name', 'weight', 'field', 'gradient'], tags: [] },+ vertex_group: { fields: ['select', 'name', 'weight', 'field', 'gradient', 'measure', 'gain', 'angle', 'rays', 'distance', 'seed'], tags: [] },vertex_color: { fields: ['select', 'color', 'field', 'gradient'], tags: [] },decimate: { fields: ['ratio'], tags: [] },remesh: { fields: ['voxelSize', 'resolution'], tags: [] },diff --git a/tests/mesh-masks.test.js b/tests/mesh-masks.test.jsnew file mode 100644index 00000000..5b2a97e8--- /dev/null+++ b/tests/mesh-masks.test.js@@ -0,0 +1,160 @@+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 { vertexGroupWeights } from '../src/mesh-data.js';+import { checkOcclusionWork } from '../src/mesh-masks.js';++// A box cut into squares, so a vertex lies on a face, on an edge or at a corner.+function cutBox(cuts = 3) {+ return applyMeshEdits(meshFromGeometry(box(0, 1)), [{ op: 'subdivide_edges', edges: { all: true }, cuts }]).mesh;+}++function measured(edit, base = cutBox()) {+ const mesh = applyMeshEdits(base, [{ op: 'vertex_group', name: 'mask', ...edit }]).mesh;+ return { mesh, weights: vertexGroupWeights(mesh, 'mask') };+}++function sameBytes(first, second) {+ return Buffer.from(first.buffer).equals(Buffer.from(second.buffer));+}++test('the measures give back one weight from 0 to 1 for every vertex', () => {+ for (const measure of ['curvature', 'edge', 'occlusion']) {+ const { mesh, weights } = measured({ measure });+ assert.equal(weights.length, mesh.vertexCount, measure);+ assert.ok(weights.every(weight => weight >= 0 && weight <= 1), measure);+ }+});++test('edge is high on the convex folds of a box and falls to 0 away from them', () => {+ const { weights } = measured({ measure: 'edge', angle: 45 });+ assert.ok(weights.some(weight => weight === 1), 'a 90 degree fold passes a 45 degree limit');+ assert.ok(weights.some(weight => weight === 0), 'a flat face has no fold');+ const wide = measured({ measure: 'edge', angle: 179 }).weights;+ assert.ok(Math.max(...wide) < 0.6, 'a 90 degree fold is half of 179 degrees');+});++test('edge ignores a concave fold', () => {+ const room = applyMeshEdits(cutBox(), [{ op: 'flip_normals' }]).mesh;+ const { weights } = measured({ measure: 'edge' }, room);+ assert.ok(weights.every(weight => weight === 0), 'seen from inside, every fold of the box is concave');+});++test('curvature is 0.5 on a flat face and above it on a convex corner', () => {+ const { mesh, weights } = measured({ measure: 'curvature' });+ let corners = 0;+ let flats = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const touching = [0, 1, 2].filter(axis => Math.abs(Math.abs(mesh.positions[vertex * 3 + axis]) - 0.5) < 1e-6).length;+ if (touching === 3) {+ assert.ok(weights[vertex] > 0.9, `corner ${vertex} is ${weights[vertex]}`);+ corners++;+ }+ if (touching === 1) {+ assert.ok(Math.abs(weights[vertex] - 0.5) < 1e-6, `face vertex ${vertex} is ${weights[vertex]}`);+ flats++;+ }+ }+ assert.ok(corners === 8 && flats > 0);+});++test('curvature is below 0.5 inside a concave box', () => {+ const room = applyMeshEdits(cutBox(), [{ op: 'flip_normals' }]).mesh;+ const { weights } = measured({ measure: 'curvature' }, room);+ assert.ok(Math.min(...weights) < 0.1);+ assert.ok(Math.max(...weights) < 0.55);+});++test('a larger curvature gain saturates sooner', () => {+ const soft = measured({ measure: 'curvature', gain: 0.5 }).weights;+ const hard = measured({ measure: 'curvature', gain: 8 }).weights;+ assert.ok(soft.every((weight, vertex) => hard[vertex] >= weight - 1e-6));+ assert.ok(soft.some((weight, vertex) => hard[vertex] > weight + 0.1));+});++// A box with a deep groove cut into its top: the groove floor sees little sky.+function grooved() {+ return applyMeshEdits(cutBox(7), [+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.15, depth: -0.3 },+ ]).mesh;+}++test('occlusion is higher at the bottom of a pocket than on the open top', () => {+ const pocket = grooved();+ const { mesh, weights } = measured({ measure: 'occlusion', rays: 48, distance: 1, seed: 7 }, pocket);+ let floor = 0;+ let floorCount = 0;+ let outside = 0;+ let outsideCount = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const height = mesh.positions[vertex * 3 + 1];+ if (Math.abs(height - 0.2) < 0.01 && Math.abs(mesh.positions[vertex * 3]) < 0.1 && Math.abs(mesh.positions[vertex * 3 + 2]) < 0.1) {+ floor += weights[vertex];+ floorCount++;+ }+ if (height < -0.49) {+ outside += weights[vertex];+ outsideCount++;+ }+ }+ assert.ok(floorCount > 0 && outsideCount > 0);+ assert.ok(floor / floorCount > outside / outsideCount, `pocket floor ${floor / floorCount}, bottom ${outside / outsideCount}`);+});++test('every measure gives the same bytes for the same mesh and seed, and occlusion changes with the seed', () => {+ for (const measure of ['curvature', 'edge', 'occlusion']) {+ assert.ok(sameBytes(measured({ measure }, grooved()).weights, measured({ measure }, grooved()).weights), measure);+ }+ const edit = { measure: 'occlusion', rays: 8, distance: 2 };+ assert.ok(sameBytes(measured({ ...edit, seed: 5 }, grooved()).weights, measured({ ...edit, seed: 5 }, grooved()).weights));+ assert.ok(!sameBytes(measured({ ...edit, seed: 5 }, grooved()).weights, measured({ ...edit, seed: 6 }, grooved()).weights));+});++test('select limits which vertices a measure writes', () => {+ const some = measured({ measure: 'edge', select: { tag: 'top' } }).weights;+ const all = measured({ measure: 'edge' }).weights;+ const count = weights => weights.filter(weight => weight === 1).length;+ assert.ok(count(some) > 0 && count(some) < count(all));+});++test('invalid measure edits say what to pass', () => {+ const run = edit => () => applyMeshEdits(cutBox(), [{ op: 'vertex_group', name: 'mask', ...edit }]);+ assert.throws(run({ measure: 'rust' }), /one of curvature, edge, occlusion/);+ assert.throws(run({ measure: 'edge', rays: 8 }), /measure "edge" takes angle/);+ assert.throws(run({ measure: 'curvature', gain: 100 }), /gain/);+ assert.throws(run({ measure: 'occlusion', rays: 0 }), /whole number from 1 to 128/);+ assert.throws(run({ measure: 'occlusion', distance: -1 }), /distance/);+ assert.throws(run({ measure: 'edge', weight: 1 }), /only one of/);+});++test('occlusion refuses work over the ray limit and says how to shrink it', () => {+ assert.throws(() => checkOcclusionWork(20000, 128), /fewer rays/);+ assert.doesNotThrow(() => checkOcclusionWork(10000, 128));+});++test('a vertex_color gradient follows the weights of a group, in three stops', () => {+ const stops = [[0.1, 0.1, 0.1], [0.8, 0.1, 0.1], [0.9, 0.9, 0.9]];+ const mesh = applyMeshEdits(cutBox(), [+ { op: 'vertex_group', name: 'wear', measure: 'curvature' },+ { op: 'vertex_color', gradient: { group: 'wear', colors: stops } },+ ]).mesh;+ const weights = vertexGroupWeights(mesh, 'wear');+ const colors = mesh.attributes.corner.color.data;+ for (let corner = 0; corner < mesh.cornerCount; corner++) {+ const position = weights[mesh.cornerVertices[corner]] * 2;+ const lower = Math.min(1, Math.floor(position));+ for (let channel = 0; channel < 3; channel++) {+ const expected = stops[lower][channel] + (stops[lower + 1][channel] - stops[lower][channel]) * (position - lower);+ assert.ok(Math.abs(colors[corner * 3 + channel] - expected) < 1e-5);+ }+ }+});++test('a vertex_color group gradient names the fix for an unknown group or a bad gradient', () => {+ const run = gradient => () => applyMeshEdits(cutBox(), [{ op: 'vertex_color', gradient }]);+ assert.throws(run({ group: 'nope', colors: [[0, 0, 0], [1, 1, 1]] }), /Unknown vertex group nope/);+ assert.throws(run({ group: 'wear', colors: [[0, 0, 0]] }), /two colors/);+ assert.throws(run({ group: 'wear', axis: 'y', colors: [[0, 0, 0], [1, 1, 1]] }), /group gradient fields/);+});