Skip to content

3D engine that AI agents drive

Add smooth_laplacian and warp mesh deform edits (#2142)

Nguyen Xuan Anfbfbc406d943
diff --git a/changes/2142.md b/changes/2142.md
new file mode 100644
index 00000000..448d5c38
--- /dev/null
+++ b/changes/2142.md
@@ -0,0 +1 @@
+- Mesh edits `smooth_laplacian` (volume-keeping smoothing with a pinned boundary and optional vertex group weights) and `warp` (carry one point to another with a radius, curve and twist) join the deform modifiers, as edits and stack nodes (#2142).
diff --git a/changes/2142.size.md b/changes/2142.size.md
new file mode 100644
index 00000000..2e6e13f2
--- /dev/null
+++ b/changes/2142.size.md
@@ -0,0 +1,3 @@
+- goal:agent-scene: 232 bytes gzip for two agent-facing deform edits, smooth_laplacian and warp, that organic parts need and no existing edit covers
+- scene:agent-scene: 232 bytes gzip for the smooth_laplacian and warp edits and their capability notes
+- scene:agent-scene+lazy: 1212 bytes gzip for the smooth_laplacian and warp edit code and their capability notes
diff --git a/docs/mesh.md b/docs/mesh.md
index d13609f8..63a7c6e6 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -211,7 +211,7 @@ These three (and `bevel`, below) work as edits and as stack nodes:
### Modifier stack
-A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `build`, `weighted_normal` and `smooth_by_angle` nodes (up to 16) evaluated after the
+A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `smooth_laplacian`, `warp`, `build`, `weighted_normal` and `smooth_by_angle` nodes (up to 16) evaluated after the
edits without changing them, as Blender's modifier stack. Every prefix (the edit result, then each node) is cached
by its recipe text in a least-recently-used cache bounded at 64 entries and 64 MiB, so changing a late node reuses
the earlier work. Results list one entry per node with `cached: true` when reused. `meshCacheStats()` reports hits
@@ -225,7 +225,7 @@ as Blender's Apply modifier, which leaves the result unchanged.
A recipe `mesh` geometry may carry `shapeKeys` (up to 16), named offsets from the finished mesh that become glTF morph targets.
A key is `{ "name": "blink", "offsets": [{ "select": { "tag": "lid" }, "offset": [0, -0.1, 0] }] }`, a list of moves like the
`translate` edit, or `{ "name": "squash", "edits": [...] }`, mesh edits that only move vertices (`set_position`, `displace`,
-`sculpt`, `simple_deform`, `lattice`, `hook`, `wave`) run on the mesh after the stack. A key that adds or removes vertices is
+`sculpt`, `simple_deform`, `lattice`, `hook`, `wave`, `smooth_laplacian`, `warp`) run on the mesh after the stack. A key that adds or removes vertices is
refused with the vertex counts. `value` (0 to 1) is the weight without motion.
Animate a key with the existing morph track: `{ "kind": "morph", "id": "blink", "property": "weight", "keyframes": [...] }`. Weights
@@ -234,7 +234,7 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.
### Whole-mesh modifiers
-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `bounding_box`, `convex_hull`, `ocean`, `build`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
+`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `smooth_laplacian`, `warp`, `bounding_box`, `convex_hull`, `ocean`, `build`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
| op | fields | does |
| --- | --- | --- |
@@ -250,6 +250,8 @@ Normals stay those of the base mesh. Test: `tests/mesh-shape-keys.test.js`.
| `lattice` | `divisions` ([2,2,2], 2 to 8), `moves` (up to 64 of `{ point, offset }`) | A grid of control points over the mesh bounds; each move shifts one point and vertices follow the trilinear blend. |
| `curve` | `path` (2 to 64 points), `axis` (x) | Bends the mesh along a Catmull-Rom path; the coordinate along the axis is the distance from the path start. |
| `hook` | `center`, `radius` (1), `translation`, `strength` (1), `falloff` (smooth) | Pulls the vertices within the radius by the translation, weighted by the falloff. |
+| `smooth_laplacian` | `factor` (0.5, above 0 to 1), `iterations` (1, 1 to 64), `preserveVolume` (true), `pinBoundary` (true), `group` | Smoothing that does not melt a closed mesh: each iteration is a shrinking step and an inflating step (Taubin), so a sphere keeps its volume. `preserveVolume: false` is plain shrinking Laplacian smoothing. The rim of an open mesh stays put unless `pinBoundary` is false; a vertex `group` scales each vertex's step. Not Blender's Smooth Laplacian, which solves a different system. |
+| `warp` | `from`, `to`, `radius` (1), `curve` (smooth, linear or constant), `twist` (0 degrees) | Carries the vertices within the radius of `from` toward `to`, weighted by the curve: the vertex at `from` lands on `to` and vertices beyond the radius do not move. A twist turns them about the axis from `from` to `to`, by the weight times the angle. |
| `wave` | `height` (0.5), `width` (1.5), `narrowness` (1.5), `speed` (0.25), `time` (0), `timeOffset`, `start`, `cyclic` (true), `axes` (xy), `normal` | A travelling gaussian ripple along z, equal to Blender Wave at the same frame. |
| `weighted_normal` | `angle` (30), `weight` (50, 1 to 100) | Stores one shading normal per corner: faces around a vertex share it unless the edge is sharp or bends more than the angle, each face counting by its area to the power weight / 50. Put it last in the stack. |
| `smooth_by_angle` | `angle` (30), `ignoreSharp` (false) | Marks edges bending more than the angle sharp and the others smooth, over the geometry `smoothAngle`; sharp edges made by hand, and the 12 of a box, stay sharp unless `ignoreSharp` is set. |
diff --git a/docs/parity.md b/docs/parity.md
index e395914e..f4fb8729 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -103,10 +103,10 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Deform > Simple Deform Modifier | partial | `simple_deform` edit and stack node: twist, bend, taper and stretch about x, y or z over the whole mesh extent. No limits, lock axes, origin object or vertex groups. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Deform > Smooth Modifier | done | `smooth` edit and stack node (factor and iterations over every vertex). Per-axis switches and vertex groups are not supported. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |
| Modeling > Modifiers > Deform > Smooth Corrective Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Deform > Smooth Laplacian Modifier | missing | No equivalent. | | |
+| Modeling > Modifiers > Deform > Smooth Laplacian Modifier | partial | `smooth_laplacian` edit and stack node: Taubin shrink and inflate steps keep the volume of a closed mesh (20 iterations on a sphere), the rim of an open mesh is pinned, and a vertex group weights each step. Not the Blender solver, no Blender comparison. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #2142 |
| Modeling > Modifiers > Deform > Surface Deform Modifier | missing | `addons/surface-attachment` binds points, not whole meshes. | | |
| Modeling > Modifiers > Deform > Volume Displace Modifier | missing | No volume objects. | | |
-| Modeling > Modifiers > Deform > Warp Modifier | missing | No equivalent. | | |
+| Modeling > Modifiers > Deform > Warp Modifier | partial | `warp` edit and stack node: a `from` point carried to a `to` point with a radius, a smooth, linear or constant curve and an optional twist about the axis between them. No warp objects, no texture falloff and no Blender comparison. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #2142 |
| Modeling > Modifiers > Deform > Wave Modifier | partial | `wave` edit and stack node: height, width, narrowness, speed, frame `time`, offset, start, cyclic, x and y axes and along the normal. Positions match Blender at the same frame on 2 cases. No falloff, lifetime or damping, no texture and no vertex groups. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Normals > Normal Edit Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Normals > Weighted Normal Modifier | partial | `weighted_normal` edit and stack node: face area weighting with a `weight` from 1 to 100 (power weight / 50) inside smooth groups bounded by sharp edges and an `angle`, stored as one normal per corner that the render uses. No corner angle or face influence modes, no keep-sharp switch, no vertex groups and no Blender comparison of normals. | [mesh-normal-modifiers](../tests/mesh-normal-modifiers.test.js) | #42 |
@@ -139,7 +139,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Armatures > Structure | partial | Imported rigs keep their hierarchy, and recipes author one. A rig exports to GLB with its bones and a baked walk clip; Blender 5.2 opens it as 1 armature, 21 bones, 14 vertex-grouped meshes and 1 action. | [gltf](../tests/gltf.test.js), [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Skinning | partial | Four-influence GPU skinning, with automatic binding by distance to the bone segments. Not heat diffusion, so two limbs that pass close can share weights; `scene_inspect` reports unweighted vertices, bones with no vertices and joint axis problems. | [skinning](../tests/skinning.test.js), [rigging](../tests/rigging.test.js) | #46 |
| Animation & Rigging > Armatures > Posing | partial | Layers, masks, additive poses and IK in code. MCP asset recipes take `motion.layers` (clips, masks, weights, additive, rename retarget) beside IK; no foot tilt on slopes or full-body IK. | [skeleton-pose](../tests/skeleton-pose.test.js), [agent-asset-ik](../tests/agent-asset-ik.test.js) | #58, #59 |
-| Animation & Rigging > Lattice | missing | No lattice. | | #42 |
+| Animation & Rigging > Lattice | partial | The `lattice` edit and stack node exist (see Modeling > Modifiers > Deform > Lattice Modifier); no lattice object. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js) | #42 |
| Animation & Rigging > Constraints > Interface | out of scope | Interface for a mouse. | | |
| Animation & Rigging > Constraints > Motion Tracking | out of scope | Motion tracking is out of scope in `docs/goal.md`. | | |
| Animation & Rigging > Constraints > Transform > Copy Location Constraint | partial | `copy_location` in `motion.constraints`: axes, invert, offset, world or local space, influence. Matches Blender where tested. | [agent-motion-constraints](../tests/agent-motion-constraints.test.js), [src/expression.js](../src/expression.js) | #58, #98 |
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 4f6d11c5..1a3fdd55 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -192,6 +192,8 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
lattice: 'divisions [2,2,2] (2-8) control points over the mesh bounds; moves up to 64 of {point:[i,j,k], offset:[x,y,z]}; trilinear blend.',
curve: 'bends the mesh along path, 2 to 64 points [x,y,z] through a Catmull-Rom spline. The coordinate along axis (x) is the distance from the path start, the other two become offsets in a twist-free frame; past the ends the mesh continues straight. Model the mesh along the axis starting at 0.',
hook: 'vertices within radius 1 of center [0,0,0] move by translation [0,0,0] times strength 0-1 (1); falloff smooth, linear or constant.',
+ smooth_laplacian: 'smoothing that keeps a closed mesh from shrinking: factor above 0 up to 1 (0.5), iterations 1-64 (1), preserveVolume true (false is plain shrinking Laplacian), pinBoundary true keeps the rim of an open mesh, group names a vertex group that scales each vertex step.',
+ warp: 'moves the vertices within radius 1 of point from toward point to, weighted by curve smooth (default), linear or constant, so the vertex at from lands on to and vertices beyond the radius stay; twist in degrees (0) also turns them about the from-to axis.',
wave: 'a gaussian ripple of height 0.5 along z (normal true: along the vertex normal) travelling from start [0,0] over axes xy (default), x or y; width 1.5, narrowness 0-50 (1.5), speed 0.25 per frame, time 0 (a frame), timeOffset 0, cyclic true repeats it. Matches Blender Wave.',
weighted_normal: 'corner normals weighted by face area ^ (weight/50), weight 1-100 (50), smoothed across edges under angle 30 that are not sharp. Put it last in the stack.',
smooth_by_angle: 'edges bending over angle 30 (0-180) become sharp, others smooth, over smoothAngle; ignoreSharp true also clears hand-made sharp edges.',
diff --git a/src/mesh-deform-modifiers.js b/src/mesh-deform-modifiers.js
index fa862e75..664c7b28 100644
--- a/src/mesh-deform-modifiers.js
+++ b/src/mesh-deform-modifiers.js
@@ -2,19 +2,25 @@ import { withPositions } from './mesh-field-edits.js';
import { vertexNormals } from './mesh-normals.js';
import { invalidField } from './field-error.js';
import { editField, editInteger, editBoolean, editAxis } from './mesh-edit-field.js';
+import { vertexGroupWeights } from './mesh-data.js';
// Modifiers that only move vertices, each from a few numbers: lattice (a coarse grid of moved control points), curve (bend
-// along a path), hook (pull the vertices near a point) and wave (a travelling ripple). Every list is bounded, and the
+// along a path), hook (pull the vertices near a point), wave (a travelling ripple), smooth_laplacian (smoothing that keeps
+// volume) and warp (carry a point to another with a falloff). Every list is bounded, and the
// errors name the field and the limit.
export const MAX_LATTICE_DIVISIONS = 8;
export const MAX_LATTICE_MOVES = 64;
export const MAX_CURVE_POINTS = 64;
export const HOOK_FALLOFFS = Object.freeze(['smooth', 'linear', 'constant']);
+export const MAX_LAPLACIAN_ITERATIONS = 64;
export const WAVE_AXES = Object.freeze(['xy', 'x', 'y']);
const AXIS_NAMES = Object.freeze({ x: 0, y: 1, z: 2 });
const CURVE_SAMPLES_PER_SEGMENT = 16;
const MINIMUM_SPAN = 1e-9;
+const GROUP_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
+// Taubin's pass band: the shrinking step of size factor is followed by an inflating step that cancels it on smooth shapes.
+const TAUBIN_PASS_BAND = 0.1;
function meshBounds(mesh) {
const low = [Infinity, Infinity, Infinity];
@@ -115,6 +121,105 @@ export function waveDeform(mesh, { height, width, narrowness, speed, time, timeO
return positions;
}
+/** Vertices on an edge that only one face uses: the rim of an open mesh. */
+function boundaryVertices(mesh) {
+ const faceCounts = new Map();
+ 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 first = mesh.cornerVertices[corner];
+ const second = mesh.cornerVertices[corner + 1 < end ? corner + 1 : start];
+ const key = Math.min(first, second) * mesh.vertexCount + Math.max(first, second);
+ faceCounts.set(key, (faceCounts.get(key) ?? 0) + 1);
+ }
+ }
+ const pinned = new Uint8Array(mesh.vertexCount);
+ for (const [key, count] of faceCounts) {
+ if (count !== 1) continue;
+ pinned[Math.floor(key / mesh.vertexCount)] = 1;
+ pinned[key % mesh.vertexCount] = 1;
+ }
+ return pinned;
+}
+
+function laplacianStep(mesh, positions, sums, counts, stepSizes) {
+ sums.fill(0);
+ counts.fill(0);
+ for (let edge = 0; edge < mesh.edgeCount; edge++) {
+ const first = mesh.edgeVertices[edge * 2];
+ const second = mesh.edgeVertices[edge * 2 + 1];
+ for (let axis = 0; axis < 3; axis++) {
+ sums[first * 3 + axis] += positions[second * 3 + axis];
+ sums[second * 3 + axis] += positions[first * 3 + axis];
+ }
+ counts[first]++;
+ counts[second]++;
+ }
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ if (counts[vertex] === 0 || stepSizes[vertex] === 0) continue;
+ for (let axis = 0; axis < 3; axis++) {
+ const index = vertex * 3 + axis;
+ positions[index] += stepSizes[vertex] * (sums[index] / counts[vertex] - positions[index]);
+ }
+ }
+}
+
+/**
+ * Laplacian smoothing that keeps volume. Plain smoothing pulls every vertex toward the mean of its neighbours and so shrinks a
+ * closed mesh; with preserveVolume each iteration is a shrinking step of size factor followed by an inflating step (Taubin's
+ * lambda and mu), which cancels the shrink for a smooth shape. Group weights scale each vertex's step, and the rim of an open
+ * mesh stays where it is unless pinBoundary is false.
+ */
+export function smoothLaplacianDeform(mesh, { factor, iterations, preserveVolume, pinBoundary, group }) {
+ const weights = group === undefined ? null : vertexGroupWeights(mesh, group);
+ const pinned = pinBoundary ? boundaryVertices(mesh) : null;
+ const shrinkSizes = new Float64Array(mesh.vertexCount);
+ const inflateSizes = new Float64Array(mesh.vertexCount);
+ const inflateFactor = 1 / (TAUBIN_PASS_BAND - 1 / factor);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const weight = (weights ? weights[vertex] : 1) * (pinned && pinned[vertex] ? 0 : 1);
+ shrinkSizes[vertex] = factor * weight;
+ inflateSizes[vertex] = preserveVolume ? inflateFactor * weight : 0;
+ }
+ const positions = Float64Array.from(mesh.positions);
+ const sums = new Float64Array(positions.length);
+ const counts = new Uint32Array(mesh.vertexCount);
+ for (let iteration = 0; iteration < iterations; iteration++) {
+ laplacianStep(mesh, positions, sums, counts, shrinkSizes);
+ if (preserveVolume) laplacianStep(mesh, positions, sums, counts, inflateSizes);
+ }
+ return Float32Array.from(positions);
+}
+
+function rotateAbout(offset, axis, angle) {
+ const cosine = Math.cos(angle);
+ const sine = Math.sin(angle);
+ const along = dotProduct(axis, offset);
+ const across = crossProduct(axis, offset);
+ return offset.map((value, component) => value * cosine + across[component] * sine + axis[component] * along * (1 - cosine));
+}
+
+/**
+ * Carry the mesh from point `from` to point `to`: a vertex within `radius` of `from` moves by (to - from) times the curve
+ * weight, so the vertex at `from` lands on `to` and vertices beyond the radius stay. A twist turns each vertex about the
+ * axis from `from` toward `to` by that many degrees times the same weight.
+ */
+export function warpDeform(mesh, { from, to, radius, curve, twist }) {
+ const shift = to.map((value, axis) => value - from[axis]);
+ const shiftLength = Math.hypot(...shift);
+ const direction = shiftLength > MINIMUM_SPAN ? shift.map(component => component / shiftLength) : null;
+ const positions = new Float32Array(mesh.positions);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const offset = [0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis] - from[axis]);
+ const weight = hookWeight(curve, Math.hypot(...offset), radius);
+ if (weight === 0) continue;
+ const turned = twist !== 0 && direction ? rotateAbout(offset, direction, twist * Math.PI / 180 * weight) : offset;
+ for (let axis = 0; axis < 3; axis++) positions[vertex * 3 + axis] = from[axis] + turned[axis] + shift[axis] * weight;
+ }
+ return positions;
+}
+
function catmullRom(before, from, to, after, fraction) {
const squared = fraction * fraction;
const cubed = squared * fraction;
@@ -272,8 +377,33 @@ function normalizeWave(edit, normalized, index, { finiteNumber }) {
if (!WAVE_AXES.includes(normalized.axes)) throw editField(index, 'axes', normalized.axes, `one of ${WAVE_AXES.join(', ')}`);
}
-const NORMALIZERS = Object.freeze({ lattice: normalizeLattice, curve: normalizeCurve, hook: normalizeHook, wave: normalizeWave });
-const DEFORMERS = Object.freeze({ lattice: latticeDeform, curve: curveDeform, hook: hookDeform, wave: waveDeform });
+function normalizeSmoothLaplacian(edit, normalized, index, { finiteNumber }) {
+ normalized.factor = edit.factor === undefined ? 0.5 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1, exclusiveMinimum: true });
+ normalized.iterations = edit.iterations === undefined ? 1 : editInteger(edit.iterations, index, 'iterations', 1, MAX_LAPLACIAN_ITERATIONS);
+ normalized.preserveVolume = edit.preserveVolume ?? true;
+ normalized.pinBoundary = edit.pinBoundary ?? true;
+ editBoolean(normalized.preserveVolume, index, 'preserveVolume');
+ editBoolean(normalized.pinBoundary, index, 'pinBoundary');
+ if (edit.group === undefined) return;
+ if (typeof edit.group !== 'string' || !GROUP_NAME_PATTERN.test(edit.group)) {
+ throw editField(index, 'group', edit.group, '1 to 48 letters, digits, dots, dashes or underscores naming a vertex group, such as "mask"');
+ }
+ normalized.group = edit.group;
+}
+
+function normalizeWarp(edit, normalized, index, { finiteNumber }) {
+ normalized.from = checkedVector(edit.from, index, 'from', finiteNumber);
+ normalized.to = checkedVector(edit.to, index, 'to', finiteNumber);
+ normalized.radius = edit.radius === undefined ? 1 : finiteNumber(edit.radius, index, 'radius', { minimum: 0, maximum: 1e4, exclusiveMinimum: true });
+ normalized.curve = edit.curve ?? 'smooth';
+ if (!HOOK_FALLOFFS.includes(normalized.curve)) throw editField(index, 'curve', normalized.curve, `one of ${HOOK_FALLOFFS.join(', ')}`);
+ normalized.twist = edit.twist === undefined ? 0 : finiteNumber(edit.twist, index, 'twist', { minimum: -3600, maximum: 3600 });
+ const apart = Math.hypot(...normalized.to.map((value, axis) => value - normalized.from[axis])) > MINIMUM_SPAN;
+ if (normalized.twist !== 0 && !apart) throw editField(index, 'twist', edit.twist, 'left out, or with "to" apart from "from", because the twist turns about the axis between them');
+}
+
+const NORMALIZERS = Object.freeze({ lattice: normalizeLattice, curve: normalizeCurve, hook: normalizeHook, wave: normalizeWave, smooth_laplacian: normalizeSmoothLaplacian, warp: normalizeWarp });
+const DEFORMERS = Object.freeze({ lattice: latticeDeform, curve: curveDeform, hook: hookDeform, wave: waveDeform, smooth_laplacian: smoothLaplacianDeform, warp: warpDeform });
export const isDeformModifier = operation => Object.hasOwn(DEFORMERS, operation);
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index 6a86c588..61387393 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -18,6 +18,8 @@ export const MODIFIER_OPERATIONS = /* @__PURE__ */ Object.freeze({
lattice: { fields: ['divisions', 'moves'], tags: [] },
curve: { fields: ['path', 'axis'], tags: [] },
hook: { fields: ['center', 'radius', 'translation', 'strength', 'falloff'], tags: [] },
+ smooth_laplacian: { fields: ['factor', 'iterations', 'preserveVolume', 'pinBoundary', 'group'], tags: [] },
+ warp: { fields: ['from', 'to', 'radius', 'curve', 'twist'], tags: [] },
wave: { fields: ['height', 'width', 'narrowness', 'speed', 'time', 'timeOffset', 'start', 'cyclic', 'axes', 'normal'], tags: [] },
weighted_normal: { fields: ['angle', 'weight'], tags: [] },
smooth_by_angle: { fields: ['angle', 'ignoreSharp'], tags: [] },
diff --git a/tests/mesh-deform-modifiers.test.js b/tests/mesh-deform-modifiers.test.js
index f499a476..92a35875 100644
--- a/tests/mesh-deform-modifiers.test.js
+++ b/tests/mesh-deform-modifiers.test.js
@@ -1,8 +1,9 @@
import assert from 'node:assert/strict';
import test from 'node:test';
-import { box } from '../src/geometry.js';
+import { box, icoSphere, grid } from '../src/geometry.js';
import { editMesh, validateTopology, meshFromGeometry, applyMeshEdits, evaluateMeshStack, normalizeMeshEdits } from '../src/mesh.js';
import { createMeshData } from '../src/mesh-data.js';
+import { withPositions } from '../src/mesh-field-edits.js';
const cube = () => meshFromGeometry(box(0, 1));
const run = (mesh, edit) => applyMeshEdits(mesh, [edit]).mesh;
@@ -97,3 +98,109 @@ test('the deforming modifiers run as stack nodes', () => {
assert.equal(outcome.results.length, 4);
validateTopology(editMesh(outcome.mesh));
});
+
+// The enclosed volume of a closed mesh from the signed volumes of the tetrahedra its faces make with the origin.
+function enclosedVolume(mesh) {
+ let volume = 0;
+ for (let face = 0; face < mesh.faceCount; face++) {
+ const corners = Array.from(mesh.cornerVertices.subarray(mesh.faceOffsets[face], mesh.faceOffsets[face + 1]));
+ const point = vertex => [0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis]);
+ for (let fan = 1; fan + 1 < corners.length; fan++) {
+ const [first, second, third] = [point(corners[0]), point(corners[fan]), point(corners[fan + 1])];
+ volume += (first[0] * (second[1] * third[2] - second[2] * third[1]) - first[1] * (second[0] * third[2] - second[2] * third[0]) + first[2] * (second[0] * third[1] - second[1] * third[0])) / 6;
+ }
+ }
+ return Math.abs(volume);
+}
+
+test('smooth_laplacian keeps the volume of a closed sphere where plain smooth shrinks it, and is deterministic', () => {
+ const ball = meshFromGeometry(icoSphere(3));
+ const before = enclosedVolume(ball);
+ const kept = run(ball, { op: 'smooth_laplacian', factor: 0.5, iterations: 20 });
+ const plain = run(ball, { op: 'smooth', factor: 0.5, iterations: 20 });
+ const keptLoss = 1 - enclosedVolume(kept) / before;
+ const plainLoss = 1 - enclosedVolume(plain) / before;
+ assert.ok(Math.abs(keptLoss) < 0.02, `smooth_laplacian lost ${(keptLoss * 100).toFixed(2)} percent`);
+ assert.ok(plainLoss > 0.05 && plainLoss > Math.abs(keptLoss) * 5, `plain smooth lost ${(plainLoss * 100).toFixed(2)} percent`);
+ assert.deepEqual(run(ball, { op: 'smooth_laplacian', iterations: 20 }).positions, run(ball, { op: 'smooth_laplacian', iterations: 20 }).positions);
+ const shrunk = run(ball, { op: 'smooth_laplacian', factor: 0.5, iterations: 20, preserveVolume: false });
+ assert.ok(enclosedVolume(shrunk) < before * 0.95, 'preserveVolume false shrinks like plain smoothing');
+});
+
+test('smooth_laplacian pins the boundary of an open mesh and weights steps by a vertex group', () => {
+ const sheet = meshFromGeometry(grid(6));
+ const bumpyPositions = new Float32Array(sheet.positions);
+ for (let vertex = 0; vertex < sheet.vertexCount; vertex++) bumpyPositions[vertex * 3 + 2] = (vertex % 3) * 0.2;
+ const bumpy = withPositions(sheet, bumpyPositions);
+ const smoothed = run(bumpy, { op: 'smooth_laplacian', iterations: 5 });
+ const rim = vertex => Math.abs(Math.abs(sheet.positions[vertex * 3]) - 0.5) < 1e-6 || Math.abs(Math.abs(sheet.positions[vertex * 3 + 1]) - 0.5) < 1e-6;
+ let rimCount = 0;
+ let movedInside = 0;
+ for (let vertex = 0; vertex < sheet.vertexCount; vertex++) {
+ const moved = [0, 1, 2].some(axis => smoothed.positions[vertex * 3 + axis] !== bumpy.positions[vertex * 3 + axis]);
+ if (rim(vertex)) {
+ rimCount++;
+ assert.equal(moved, false, `rim vertex ${vertex} stayed`);
+ } else if (moved) movedInside++;
+ }
+ assert.ok(rimCount > 0 && movedInside > 0, 'the rim is found and the inside smooths');
+ const freed = run(bumpy, { op: 'smooth_laplacian', iterations: 5, pinBoundary: false });
+ assert.ok(Array.from({ length: sheet.vertexCount }, (_, vertex) => vertex).some(vertex => rim(vertex) && freed.positions[vertex * 3 + 2] !== bumpy.positions[vertex * 3 + 2]), 'pinBoundary false lets the rim move');
+});
+
+test('smooth_laplacian leaves vertices whose group weight is zero where they are', () => {
+ const sheet = meshFromGeometry(grid(8));
+ const grouped = run(sheet, { op: 'vertex_group', name: 'mask', gradient: { axis: 'x', range: [-0.5, 0.5], weights: [0, 1] } });
+ const bumpyPositions = new Float32Array(grouped.positions);
+ for (let vertex = 0; vertex < grouped.vertexCount; vertex++) bumpyPositions[vertex * 3 + 2] = (vertex % 3) * 0.2;
+ const bumpy = withPositions(grouped, bumpyPositions);
+ const smoothed = run(bumpy, { op: 'smooth_laplacian', iterations: 3, group: 'mask' });
+ const weights = bumpy.attributes.point['group:mask'].data;
+ let movedWeighted = 0;
+ for (let vertex = 0; vertex < bumpy.vertexCount; vertex++) {
+ const moved = smoothed.positions[vertex * 3 + 2] !== bumpy.positions[vertex * 3 + 2];
+ if (weights[vertex] === 0) assert.equal(moved, false, `vertex ${vertex} has weight 0`);
+ else if (moved) movedWeighted++;
+ }
+ assert.ok(movedWeighted > 0, 'weighted vertices smooth');
+});
+
+test('smooth_laplacian names its bad fields and unknown groups', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_laplacian', iterations: 0 }]), /edits\[0\]\.iterations: got 0; expected a whole number from 1 to 64/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_laplacian', factor: 0 }]), /edits\[0\]\.factor/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_laplacian', preserveVolume: 'yes' }]), /edits\[0\]\.preserveVolume/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_laplacian', group: '' }]), /edits\[0\]\.group/);
+ assert.throws(() => run(cube(), { op: 'smooth_laplacian', group: 'nothing' }), /Mesh edit 0 \(smooth_laplacian\): Unknown vertex group nothing/);
+});
+
+test('warp lands the vertex at the from point on the target and leaves vertices beyond the radius', () => {
+ const warped = run(beam(), { op: 'warp', from: [0, -0.5, -0.5], to: [0, -0.5, 1.5], radius: 1.2 });
+ near(warped.positions[2], 1.5, 'the vertex at from lands on to');
+ near(warped.positions[0], 0, 'x did not change');
+ for (let vertex = 0; vertex < warped.vertexCount; vertex++) {
+ const distance = Math.hypot(beam().positions[vertex * 3], beam().positions[vertex * 3 + 1] + 0.5, beam().positions[vertex * 3 + 2] + 0.5);
+ const moved = [0, 1, 2].some(axis => warped.positions[vertex * 3 + axis] !== beam().positions[vertex * 3 + axis]);
+ assert.equal(moved, distance < 1.2, `vertex ${vertex} at distance ${distance.toFixed(2)}`);
+ }
+ validateTopology(editMesh(warped));
+});
+
+test('warp twists about the axis between the points and names its bad fields', () => {
+ const twisted = run(beam(), { op: 'warp', from: [0, 0, 0], to: [4, 0, 0], radius: 10, curve: 'constant', twist: 90 });
+ near(twisted.positions[0 * 3 + 0], 4, 'the origin-side vertices moved along x by the full shift');
+ near(twisted.positions[1], 0.5, 'the vertex (0,-0.5,-0.5) turned 90 degrees about x to (0, 0.5, -0.5), then shifted');
+ near(twisted.positions[2], -0.5, 'z of the turned vertex');
+ assert.throws(() => normalizeMeshEdits([{ op: 'warp', from: [0, 0, 0] }]), /edits\[0\]\.to: got undefined; expected an array of three numbers/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'warp', from: [0, 0, 0], to: [1, 0, 0], radius: -1 }]), /edits\[0\]\.radius/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'warp', from: [0, 0, 0], to: [1, 0, 0], curve: 'sharp' }]), /edits\[0\]\.curve: got "sharp"; expected one of/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'warp', from: [1, 1, 1], to: [1, 1, 1], twist: 30 }]), /edits\[0\]\.twist/);
+});
+
+test('smooth_laplacian and warp run as stack nodes', () => {
+ const outcome = evaluateMeshStack(meshFromGeometry(icoSphere(2)), [
+ { op: 'warp', from: [0, 0, 1], to: [0, 0, 1.5], radius: 0.8 },
+ { op: 'smooth_laplacian', iterations: 4 },
+ ]);
+ assert.equal(outcome.results.length, 2);
+ validateTopology(editMesh(outcome.mesh));
+});