3D engine that AI agents drive
Add screw, wireframe and skin modifiers (Part of #42)
Nguyen Xuan Ande7a3b8d2c71
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 609f51ba..1b423b49 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Add the `screw`, `wireframe` and `skin` modifiers as edits and stack nodes (part of issue #42). `screw` revolves the edges of a mesh about an axis with steps, iterations and lift, and `wireframe` leaves a rim on every face with thickness, offset and even offset; both match Blender 5.2 on counts, area and positions (`wireframe` on three cases, `screw` on two). `skin` is a simple version, a closed square tube per edge with a radius per vertex and no branch solver. Sizes are bounded and the errors say what to lower. Details are in `scene_capabilities` `meshModifiers`, and the modifier entry of the tool schemas is now an open object so it no longer grows with each modifier.- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.- Fix the automatic floor skipping a lone flat object (part of issue #53). A lone part never counts as the recipe's own floor, so a gear lying flat, which spans its whole scene and is the lowest geometry, now gets a floor and a contact shadow (before, `agentGroundPlacement` returned null for it). The surface judge on the six cold recipes goes from 0 before the floor, to 6 with the first rule, to 7 with this fix (gear 0 to 1; one call per task, so direction only). A flat object with a hub on it is still read as a plate. Core did not change.diff --git a/docs/mesh.md b/docs/mesh.mdindex 6e49687e..22d24181 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -197,7 +197,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` and `cast` 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` and `skin` nodes (up to 16) evaluated after theedits without changing them, as Blender's modifier stack. Every prefix (the edit result, then each node) is cachedby its recipe text in a least-recently-used cache bounded at 64 entries and 64 MiB, so changing a late node reusesthe earlier work. Results list one entry per node with `cached: true` when reused. `meshCacheStats()` reports hits@@ -208,7 +208,7 @@ as Blender's Apply modifier, which leaves the result unchanged.### Whole-mesh modifiers-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform` and `cast` 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` and `skin` 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 || --- | --- | --- |@@ -218,8 +218,11 @@ as Blender's Apply modifier, which leaves the result unchanged.| `smooth` | `factor` (0.5), `iterations` (1, up to 64) | Moves each vertex `factor / 2` toward the mean of its edge neighbours. || `simple_deform` | `mode`, `axis` (z), `angle` (45) or `factor` (0.5) | Twist and bend take `angle` degrees, taper and stretch take `factor`, both measured over the mesh extent along the axis. A mesh with no extent along it stays as it is. || `cast` | `factor` (0.5), `size` (0) | Blends vertices toward a sphere about the local origin; size 0 uses the mean vertex distance. |+| `screw` | `axis` (z), `angle` (360), `steps` (16, up to 256), `iterations` (1, up to 64), `lift` (0) | Revolves every edge of the mesh about the axis through the origin, as Blender Screw; the faces of the input are dropped. A whole number of turns with no lift closes the ring. |+| `wireframe` | `thickness` (0.02), `offset` (0), `evenOffset` (true), `replace` (true) | Leaves a rim of that width on every face, as Blender Wireframe; `offset` -1 to 1 moves the strut from inside to outside the surface. |+| `skin` | `radius` (0.1, a number or a scalar field per vertex) | A closed square tube on every edge. A simple version: tubes that meet overlap, and there is no branch solver. |-`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. Not yet: `screw`, `skin`, `wireframe`, `lattice`, `curve`, `hook`, `wave`, `shrinkwrap`, `weighted_normal`, `smooth_by_angle` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.+`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `skin` is not compared with Blender. Not yet: `lattice`, `curve`, `hook`, `wave`, `shrinkwrap`, `weighted_normal`, `smooth_by_angle` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.### Field expressionsdiff --git a/docs/parity.md b/docs/parity.mdindex 2779e91f..8bc0fc07 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -3,7 +3,7 @@This ledger compares 67js with each feature in the [Blender 5.2 manual](https://docs.blender.org/manual/en/latest/).It is the record for the goal in issue #23. Use `npm run parity` to print the coverage of each section.-Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 11 done, 16 partial, 33 missing and 1 out of scope, 8 of the done rows compared with Blender, 18% of the in-scope rows done.+Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 11 done, 21 partial, 28 missing and 1 out of scope, 8 of the done rows compared with Blender, 18% of the in-scope rows done.## How to read it@@ -82,14 +82,14 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| 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 > Screw Modifier | partial | `lathe` covers a full turn. There is no stack node or screw offset. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |-| Modeling > Modifiers > Generate > Skin Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #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) | || Modeling > Modifiers > Generate > Subdivision Surface Modifier | done | `subdivide` edit and stack node: Catmull-Clark to 4 levels, semi-sharp creases, sharp boundaries, tags, UVs. Counts, area and positions match Blender; volume differs under 1% on four cases. | [src/mesh-subdivide.js](../src/mesh-subdivide.js), [tests/blender-golden.test.js](../tests/blender-golden.test.js), [tests/mesh-subdivide.test.js](../tests/mesh-subdivide.test.js), [pebble task](../bench/agent-modeling/tasks.mjs) | #39 || Modeling > Modifiers > Generate > Triangulate Modifier | done | `triangulate` edit and stack node with `minVertices`. Quads split on the shorter diagonal, larger faces by ear clipping; Blender's method options are not exposed. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | || Modeling > Modifiers > Generate > Volume to Mesh Modifier | missing | No volume objects. | | || Modeling > Modifiers > Generate > Weld Modifier | done | `weld` edit and stack node (distance, all vertices). Connected mode and vertex groups are not supported. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |-| Modeling > Modifiers > Generate > Wireframe Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |+| Modeling > Modifiers > Generate > Wireframe Modifier | partial | `wireframe` edit and stack node: `thickness`, `offset`, `evenOffset` and `replace`. Counts, area and positions match Blender on 3 cases (closed cube, keep original, open quad). No boundary struts, no crease weight and no vertex groups. | [mesh-generator-modifiers](../tests/mesh-generator-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 || Modeling > Modifiers > Deform > Armature Modifier | partial | A node `skin` binds a recipe mesh to an armature with automatic weights, and imported rigs keep GPU skinning. No envelope mode and no hand-edited weights. | [rigging](../tests/rigging.test.js), [skinning](../tests/skinning.test.js) | #46 || Modeling > Modifiers > Deform > Cast Modifier | partial | `cast` edit and stack node, sphere shape about the origin with `factor` and `size`. No cylinder or cuboid shape, no radius limit, no control object. | [mesh-modifiers](../tests/mesh-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 || Modeling > Modifiers > Deform > Curve Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |diff --git a/scripts/blender-golden.py b/scripts/blender-golden.pyindex 33de87fb..3c69433d 100644--- a/scripts/blender-golden.py+++ b/scripts/blender-golden.py@@ -521,7 +521,29 @@ def add_cast(mesh_object, edit, _inputs):modifier.use_radius_as_size = False+def add_screw(mesh_object, edit, _inputs):+ modifier = mesh_object.modifiers.new("Screw", "SCREW")+ modifier.axis = edit.get("axis", "z").upper()+ modifier.angle = radians(edit.get("angle", 360))+ modifier.steps = edit.get("steps", 16)+ modifier.render_steps = modifier.steps+ modifier.iterations = edit.get("iterations", 1)+ modifier.screw_offset = edit.get("lift", 0)+ modifier.use_merge_vertices = False+++def add_wireframe(mesh_object, edit, _inputs):+ modifier = mesh_object.modifiers.new("Wireframe", "WIREFRAME")+ modifier.thickness = edit.get("thickness", 0.02)+ modifier.offset = edit.get("offset", 0)+ modifier.use_even_offset = edit.get("evenOffset", True)+ modifier.use_replace = edit.get("replace", True)+ modifier.use_boundary = False++MODIFIERS = {+ "screw": add_screw,+ "wireframe": add_wireframe,"weld": add_weld,"triangulate": add_triangulate,"edge_split": add_edge_split,diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex a62b1c8a..af9a6188 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -346,12 +346,7 @@ const stackNodes = [voxelSize: z.number().positive().optional().describe('Edge of one grid cell. Give this or resolution.'),resolution: z.number().int().min(4).max(192).optional().describe('Cells along the longest side. Give this or voxelSize.'),}).describe('Voxel remesh like Blender Remesh: a closed quad surface of even cells. The mesh must be closed (fill_holes first); tags and attributes are dropped. Over 192 cells per side is refused.'),- z.strictObject({- op: z.enum(Object.keys(MODIFIER_OPERATIONS)),- distance: z.number().optional(), minVertices: z.number().int().optional(), angle: z.number().optional(),- factor: z.number().optional(), iterations: z.number().int().optional(), size: z.number().optional(),- mode: z.string().optional(), axis: z.string().optional(),- }),+ z.looseObject({ op: z.enum(Object.keys(MODIFIER_OPERATIONS)) }),];const meshStack = z.array(z.discriminatedUnion('op', stackNodes)).max(16);const meshEdits = z.array(z.discriminatedUnion('op', [...meshEdit.options, ...stackNodes])).max(64);diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 337f6cf5..249c3bc5 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -130,6 +130,9 @@ export const MESH_MODIFIER_NOTES = Object.freeze({smooth: 'factor 0.5 (-2 to 2) steps toward the neighbour mean; iterations 1 to 64.',simple_deform: 'mode twist or bend use angle (45 degrees), taper or stretch use factor (0.5); axis x, y or z (z).',cast: 'sphere about the origin: factor 0 to 1 (0.5), size radius (0 = mean vertex distance).',+ screw: 'revolves every edge of the mesh (the profile; its faces are dropped) about the x, y or z axis (z) through the origin: angle 360 degrees per iteration, steps 16 (1 to 256) per iteration, iterations 1 to 64, lift 0 rise per iteration along the axis. A whole number of turns with no lift closes the ring. Vertices stay in step-major order.',+ wireframe: 'keeps a rim of width thickness (0.02) on every face, as Blender Wireframe: offset -1 to 1 (0) moves the strut from inside to outside the surface, evenOffset true makes struts as wide as the thickness, replace true drops the original faces. Open edges get no extra strut.',+ skin: 'a square tube along every edge, radius 0.1 or a scalar field per vertex (above zero), closed by end caps. Simple version: tubes that meet overlap and there is no branch solver, so it is partial against Blender.',});// Organic shaping edits. Details stay here so the tool schemas stay small.diff --git a/src/mesh-generator-modifiers.js b/src/mesh-generator-modifiers.jsnew file mode 100644index 00000000..5c49d1a5--- /dev/null+++ b/src/mesh-generator-modifiers.js@@ -0,0 +1,261 @@+import { createMeshData } from './mesh-data.js';+import { vertexNormals, faceNormals } from './mesh-normals.js';+import { evaluateField, meshFieldContext } from './mesh-fields.js';++// Modifiers that build new surface from the mesh they are given: screw revolves its edges, wireframe turns its faces into+// struts and skin puts a square tube on every edge. Each one checks the size of its result against the limits before it+// allocates, and each says in its error what to change.++export const MAX_SCREW_STEPS = 256;+export const MAX_SCREW_ITERATIONS = 64;+const AXIS_NAMES = Object.freeze({ x: 0, y: 1, z: 2 });+const FULL_TURN_TOLERANCE = 1e-6;+const MINIMUM_EDGE_LENGTH = 1e-12;++function limitError(operation, vertices, faces, { maxVertices, maxFaces }, advice) {+ if (vertices > maxVertices || faces > maxFaces) {+ throw new RangeError(`${operation} would make ${vertices} vertices and ${faces} faces, over the limit of ${maxVertices} vertices and ${maxFaces} faces. ${advice}`);+ }+}++function meshFromQuads(positions, quads) {+ const faceOffsets = new Uint32Array(quads.length / 4 + 1);+ for (let face = 0; face < faceOffsets.length; face++) faceOffsets[face] = face * 4;+ return createMeshData({ positions: Float32Array.from(positions), faceOffsets, cornerVertices: Uint32Array.from(quads) });+}++function rotateAboutAxis(point, axisIndex, angle) {+ const first = (axisIndex + 1) % 3;+ const second = (axisIndex + 2) % 3;+ const cosine = Math.cos(angle);+ const sine = Math.sin(angle);+ const rotated = [...point];+ rotated[first] = point[first] * cosine - point[second] * sine;+ rotated[second] = point[first] * sine + point[second] * cosine;+ return rotated;+}++/**+ * Blender's Screw: every edge of the mesh is revolved about the axis through the origin, `steps` per iteration, turning by+ * `angle` degrees and rising by `lift` along the axis in each iteration. The faces of the input are not kept. A whole number of+ * turns with no lift closes the ring instead of repeating the first copy.+ */+export function screwMesh(mesh, { axis, angle, steps, iterations, lift }, limits) {+ const totalSteps = steps * iterations;+ const turns = angle * iterations / 360;+ const isClosed = lift === 0 && Math.abs(turns) >= 1 - FULL_TURN_TOLERANCE && Math.abs(turns - Math.round(turns)) < FULL_TURN_TOLERANCE;+ const copies = isClosed ? totalSteps : totalSteps + 1;+ limitError('screw', mesh.vertexCount * copies, mesh.edgeCount * totalSteps, limits, 'Lower steps or iterations, or revolve a smaller profile.');+ const axisIndex = AXIS_NAMES[axis];+ const stepAngle = angle * Math.PI / 180 / steps;+ const stepLift = lift / steps;+ const positions = [];+ for (let copy = 0; copy < copies; copy++) {+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const point = [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+ const moved = rotateAboutAxis(point, axisIndex, stepAngle * copy);+ moved[axisIndex] += stepLift * copy;+ positions.push(...moved);+ }+ }+ const quads = [];+ for (let step = 0; step < totalSteps; step++) {+ const current = step * mesh.vertexCount;+ const following = ((step + 1) % copies) * mesh.vertexCount;+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ quads.push(current + first, current + second, following + second, following + first);+ }+ }+ return { mesh: meshFromQuads(positions, quads), result: { steps: totalSteps, closed: isClosed } };+}++function crossProduct(first, second) {+ return [+ first[1] * second[2] - first[2] * second[1],+ first[2] * second[0] - first[0] * second[2],+ first[0] * second[1] - first[1] * second[0],+ ];+}++function normalized(vector) {+ const length = Math.hypot(...vector);+ return length > 0 ? vector.map(component => component / length) : vector;+}++/**+ * Blender's Wireframe: each face keeps a rim of width `thickness` along its edges. A vertex gets an inner and an outer copy+ * along its normal, split by `offset` (-1 puts the strut inside the surface, 1 outside), and each face edge becomes an inner+ * and an outer quad to the face's inset corners. `evenOffset` insets corners so every strut is as wide as the thickness.+ */+export function wireframeMesh(mesh, { thickness, offset, evenOffset, replace }, limits) {+ const keptVertices = replace ? 0 : mesh.vertexCount;+ const keptFaces = replace ? 0 : mesh.faceCount;+ limitError('wireframe', keptVertices + mesh.vertexCount * 2 + mesh.cornerCount, keptFaces + mesh.cornerCount * 2, limits, 'Use a mesh with fewer faces.');+ const normals = vertexNormals(mesh);+ const faceNormalValues = faceNormals(mesh).normals;+ const half = thickness / 2;+ const positions = [];+ if (!replace) positions.push(...mesh.positions);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ for (const shift of [(offset - 1) * half, (1 + offset) * half]) {+ for (let axis = 0; axis < 3; axis++) positions.push(mesh.positions[vertex * 3 + axis] + normals[vertex * 3 + axis] * shift);+ }+ }+ const cornerBase = keptVertices + mesh.vertexCount * 2;+ const pointAt = vertex => [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ const faceNormal = [...faceNormalValues.subarray(face * 3, face * 3 + 3)];+ for (let corner = start; corner < end; corner++) {+ const vertex = mesh.cornerVertices[corner];+ const previous = pointAt(mesh.cornerVertices[corner === start ? end - 1 : corner - 1]);+ const next = pointAt(mesh.cornerVertices[corner + 1 === end ? start : corner + 1]);+ const here = pointAt(vertex);+ const incoming = normalized(here.map((value, axis) => value - previous[axis]));+ const outgoing = normalized(next.map((value, axis) => value - here[axis]));+ const insideIncoming = crossProduct(faceNormal, incoming);+ const insideOutgoing = crossProduct(faceNormal, outgoing);+ const sum = insideIncoming.map((value, axis) => value + insideOutgoing[axis]);+ const alignment = insideIncoming[0] * insideOutgoing[0] + insideIncoming[1] * insideOutgoing[1] + insideIncoming[2] * insideOutgoing[2];+ const inset = evenOffset ? sum.map(value => value * half / Math.max(1 + alignment, 1e-3)) : normalized(sum).map(value => value * half);+ for (let axis = 0; axis < 3; axis++) {+ positions.push(here[axis] + normals[vertex * 3 + axis] * offset * half + inset[axis]);+ }+ }+ }+ const innerOf = vertex => keptVertices + vertex * 2;+ const outerOf = vertex => keptVertices + vertex * 2 + 1;+ const faceOffsets = [0];+ const cornerVertices = [];+ const addFace = vertices => {+ cornerVertices.push(...vertices);+ faceOffsets.push(cornerVertices.length);+ };+ if (!replace) {+ for (let face = 0; face < mesh.faceCount; face++) {+ addFace(Array.from(mesh.cornerVertices.subarray(mesh.faceOffsets[face], mesh.faceOffsets[face + 1])));+ }+ }+ 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 nextCorner = corner + 1 === end ? start : corner + 1;+ const here = mesh.cornerVertices[corner];+ const next = mesh.cornerVertices[nextCorner];+ addFace([cornerBase + corner, cornerBase + nextCorner, innerOf(next), innerOf(here)]);+ addFace([cornerBase + nextCorner, cornerBase + corner, outerOf(here), outerOf(next)]);+ }+ }+ return {+ mesh: createMeshData({+ positions: Float32Array.from(positions), faceOffsets: Uint32Array.from(faceOffsets), cornerVertices: Uint32Array.from(cornerVertices),+ }),+ result: {},+ };+}++function perpendicularFrame(direction) {+ const smallest = direction.map(Math.abs).indexOf(Math.min(...direction.map(Math.abs)));+ const reference = [0, 0, 0];+ reference[smallest] = 1;+ const first = normalized(crossProduct(direction, reference));+ const second = crossProduct(direction, first);+ return [first, second];+}++/** One radius per vertex, from a number or a field expression, each of which must be above zero. */+function skinRadii(mesh, radius) {+ if (typeof radius === 'number') return new Float64Array(mesh.vertexCount).fill(radius);+ const { values } = evaluateField(radius, meshFieldContext(mesh, 'point'), { kind: 'scalar' });+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!(values[vertex] > 0) || !Number.isFinite(values[vertex])) {+ throw new RangeError(`skin radius must be above zero at every vertex; vertex ${vertex} has ${values[vertex]}. Change the radius field, for example wrap it in max.`);+ }+ }+ return values;+}++/**+ * A simple Skin: a square tube along every edge of the mesh, as wide as the radius of its two end vertices, closed by an+ * end cap. Tubes that meet at a vertex overlap rather than being joined into one hull, so this is not Blender's branch solver.+ */+export function skinMesh(mesh, { radius }, limits) {+ limitError('skin', mesh.edgeCount * 8, mesh.edgeCount * 6, limits, 'Skin a mesh with fewer edges.');+ const radii = skinRadii(mesh, radius);+ const positions = [];+ const quads = [];+ const caps = [];+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const firstVertex = mesh.edgeVertices[edge * 2];+ const secondVertex = mesh.edgeVertices[edge * 2 + 1];+ const start = [mesh.positions[firstVertex * 3], mesh.positions[firstVertex * 3 + 1], mesh.positions[firstVertex * 3 + 2]];+ const finish = [mesh.positions[secondVertex * 3], mesh.positions[secondVertex * 3 + 1], mesh.positions[secondVertex * 3 + 2]];+ const direction = finish.map((value, axis) => value - start[axis]);+ if (Math.hypot(...direction) < MINIMUM_EDGE_LENGTH) throw new RangeError(`skin edge ${edge} has no length. Weld the mesh first.`);+ const [across, up] = perpendicularFrame(normalized(direction));+ const base = positions.length / 3;+ for (const [point, size] of [[start, radii[firstVertex]], [finish, radii[secondVertex]]]) {+ for (const [acrossSign, upSign] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {+ for (let axis = 0; axis < 3; axis++) positions.push(point[axis] + (across[axis] * acrossSign + up[axis] * upSign) * size);+ }+ }+ for (let side = 0; side < 4; side++) {+ const following = (side + 1) % 4;+ quads.push(base + side, base + following, base + 4 + following, base + 4 + side);+ }+ caps.push([base + 3, base + 2, base + 1, base], [base + 4, base + 5, base + 6, base + 7]);+ }+ const faceOffsets = [0];+ const cornerVertices = [];+ for (let index = 0; index < quads.length; index += 4) {+ cornerVertices.push(quads[index], quads[index + 1], quads[index + 2], quads[index + 3]);+ faceOffsets.push(cornerVertices.length);+ }+ for (const cap of caps) {+ cornerVertices.push(...cap);+ faceOffsets.push(cornerVertices.length);+ }+ return {+ mesh: createMeshData({+ positions: Float32Array.from(positions), faceOffsets: Uint32Array.from(faceOffsets), cornerVertices: Uint32Array.from(cornerVertices),+ }),+ result: { tubes: mesh.edgeCount },+ };+}++export function normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField }) {+ switch (edit.op) {+ case 'screw':+ normalized.axis = edit.axis ?? 'z';+ if (!Object.hasOwn(AXIS_NAMES, normalized.axis)) throw new TypeError(`Mesh edit ${index} (axis must be x, y or z)`);+ normalized.angle = edit.angle === undefined ? 360 : finiteNumber(edit.angle, index, 'angle', { minimum: -3600, maximum: 3600 });+ normalized.steps = edit.steps === undefined ? 16 : integerInRange(edit.steps, index, 'steps', 1, MAX_SCREW_STEPS);+ normalized.iterations = edit.iterations === undefined ? 1 : integerInRange(edit.iterations, index, 'iterations', 1, MAX_SCREW_ITERATIONS);+ normalized.lift = edit.lift === undefined ? 0 : finiteNumber(edit.lift, index, 'lift', { minimum: -1e4, maximum: 1e4 });+ break;+ case 'wireframe':+ normalized.thickness = edit.thickness === undefined ? 0.02 : finiteNumber(edit.thickness, index, 'thickness', { minimum: 0, maximum: 1e3, exclusiveMinimum: true });+ normalized.offset = edit.offset === undefined ? 0 : finiteNumber(edit.offset, index, 'offset', { minimum: -1, maximum: 1 });+ normalized.evenOffset = edit.evenOffset ?? true;+ normalized.replace = edit.replace ?? true;+ if (typeof normalized.evenOffset !== 'boolean' || typeof normalized.replace !== 'boolean') {+ throw new TypeError(`Mesh edit ${index} (evenOffset and replace must be booleans)`);+ }+ break;+ case 'skin':+ if (edit.radius === undefined) {+ normalized.radius = 0.1;+ } else if (typeof edit.radius === 'number') {+ normalized.radius = finiteNumber(edit.radius, index, 'radius', { minimum: 0, maximum: 1e3, exclusiveMinimum: true });+ } else {+ normalized.radius = checkedField(edit.radius, index, 'radius', 'scalar');+ }+ break;+ }+}++export const GENERATOR_RUNNERS = Object.freeze({ screw: screwMesh, wireframe: wireframeMesh, skin: skinMesh });diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.jsindex 2945e648..ba32979a 100644--- a/src/mesh-modifiers.js+++ b/src/mesh-modifiers.js@@ -2,6 +2,7 @@ import { withPositions } from './mesh-field-edits.js';import { mergeByDistance } from './mesh-ops.js';import { triangulateFaces, splitSharpEdges } from './mesh-restructure.js';import { MODIFIER_OPERATIONS } from './mesh-operations.js';+import { normalizeGeneratorEdit, GENERATOR_RUNNERS } from './mesh-generator-modifiers.js';// The whole-mesh modifiers as recipe operations: validation of their fields and running them on MeshData. Smooth, cast and// simple_deform only move vertices; weld, triangulate and edge_split change the faces (see mesh-restructure.js).@@ -43,7 +44,11 @@ function normalizeSimpleDeform(edit, normalized, index, finiteNumber) {}/** Fill in `normalized` for a modifier edit, throwing a TypeError that names the edit when a field is wrong. */-export function normalizeModifierEdit(edit, normalized, index, { finiteNumber }) {+export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, checkedField }) {+ if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) {+ normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField });+ return;+ }switch (edit.op) {case 'weld':normalized.distance = edit.distance === undefined ? 0.001 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1e3, exclusiveMinimum: true });@@ -170,6 +175,7 @@ function simpleDeformPositions(mesh, { mode, axis, angle, factor }) {/** Run a modifier edit. Returns { mesh, result } where result holds the counts to report. */export function runModifierEdit(mesh, edit, { maxVertices, maxFaces }) {+ if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) return GENERATOR_RUNNERS[edit.op](mesh, edit, { maxVertices, maxFaces });switch (edit.op) {case 'weld': {const merged = mergeByDistance(mesh, edit.distance);diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 96c271d4..86af55ba 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -12,6 +12,9 @@ export const MODIFIER_OPERATIONS = Object.freeze({smooth: { fields: ['factor', 'iterations'], tags: [] },simple_deform: { fields: ['mode', 'axis', 'angle', 'factor'], tags: [] },cast: { fields: ['factor', 'size'], tags: [] },+ screw: { fields: ['axis', 'angle', 'steps', 'iterations', 'lift'], tags: [] },+ wireframe: { fields: ['thickness', 'offset', 'evenOffset', 'replace'], tags: [] },+ skin: { fields: ['radius'], tags: [] },});export const MESH_EDIT_OPERATIONS = Object.freeze({diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex 20ac2e98..7a11dcea 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -280,7 +280,7 @@ export function normalizeMeshEdits(edits) {break;}if (CUT_OPERATIONS.includes(edit.op)) normalizeCutEdit(edit, normalized, index, { finiteNumber, vector });- if (isModifierOperation(edit.op)) normalizeModifierEdit(edit, normalized, index, { finiteNumber });+ if (isModifierOperation(edit.op)) normalizeModifierEdit(edit, normalized, index, { finiteNumber, checkedField });return normalized;});}diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.jsonindex 6406e695..e28e5822 100644--- a/tests/fixtures/blender/cases.json+++ b/tests/fixtures/blender/cases.json@@ -17,6 +17,10 @@"vertices": [[1,-0.5,-0.5],[2,-0.5,-0.5],[2,0.5,-0.5],[1,0.5,-0.5],[1,-0.5,0.5],[2,-0.5,0.5],[2,0.5,0.5],[1,0.5,0.5]],"faces": [[0,3,2,1],[4,5,6,7],[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7]]},+ "profile-quad": {+ "vertices": [[1,0,0],[2,0,0],[2,0,1],[1,0,1]],+ "faces": [[0,1,2,3]]+ },"grid": {"vertices": [[0,0,0],[1,0,0],[2,0,0],[3,0,0],[0,1,0],[1,1,0],[2,1,0],[3,1,0],[0,2,0],[1,2,0],[2,2,0],[3,2,0],[0,3,0],[1,3,0],[2,3,0],[3,3,0]],"faces": [[0,1,5,4],[1,2,6,5],[2,3,7,6],[4,5,9,8],[5,6,10,9],[6,7,11,10],[8,9,13,12],[9,10,14,13],[10,11,15,14]]@@ -140,6 +144,11 @@{ "id": "cast-cube-mean", "input": "cube", "edit": {"op":"cast","factor":1} },{ "id": "cast-cylinder-size", "input": "cylinder", "edit": {"op":"cast","factor":0.6,"size":1.5} },{ "id": "cast-sphere-bumpy", "input": "sphere-bumpy", "edit": {"op":"cast","factor":0.5} },+ { "id": "screw-quad-full-turn", "input": "profile-quad", "edit": {"op":"screw","axis":"z","angle":360,"steps":8} },+ { "id": "screw-quad-lift", "input": "profile-quad", "edit": {"op":"screw","axis":"z","angle":90,"steps":4,"iterations":2,"lift":2} },+ { "id": "wireframe-cube", "input": "cube", "edit": {"op":"wireframe","thickness":0.1} },+ { "id": "wireframe-cube-outside-keep", "input": "cube", "edit": {"op":"wireframe","thickness":0.1,"offset":-1,"replace":false} },+ { "id": "wireframe-quad-open", "input": "profile-quad", "edit": {"op":"wireframe","thickness":0.1} },{ "id": "decimate-bowl-half", "input": "bowl-open", "compare": "surface", "edit": {"op":"decimate","ratio":0.5} },{ "id": "remesh-sphere", "input": "sphere-bumpy", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.1} },{ "id": "remesh-torus", "input": "torus-fine", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.08} },diff --git a/tests/fixtures/blender/differences.json b/tests/fixtures/blender/differences.jsonindex 21e45bfe..6a026a2f 100644--- a/tests/fixtures/blender/differences.json+++ b/tests/fixtures/blender/differences.json@@ -1,4 +1,10 @@{+ "screw-quad-full-turn": {+ "volume": "The swept strips are an open surface, so its volume depends only on which way each strip is wound. 67js winds every strip from the lower to the higher vertex index of its edge. Counts, area and positions match."+ },+ "screw-quad-lift": {+ "volume": "The swept strips are an open surface, so its volume depends only on which way each strip is wound. 67js winds every strip from the lower to the higher vertex index of its edge. Counts, area and positions match."+ },"bevel-cube-all-round": {"vertexCount": "Where three rounded edges meet, 67js fills the corner with a triangular patch and Blender uses a quad grid with one centre triangle per corner.","faceCount": "The triangular corner patch of 67js has more faces than the quad grid of Blender.",diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.jsonindex 4dfca5ae..f9706c8c 100644--- a/tests/fixtures/blender/golden.json+++ b/tests/fixtures/blender/golden.json@@ -31098,6 +31098,906 @@]]},+ "screw-quad-full-turn": {+ "vertexCount": 32,+ "edgeCount": 64,+ "faceCount": 32,+ "faceSizes": {+ "4": 32+ },+ "volume": 8.485281,+ "area": 35.339367,+ "positions": [+ [+ -2.0,+ -0.0,+ 0.0+ ],+ [+ -2.0,+ -0.0,+ 1.0+ ],+ [+ -1.41421,+ -1.41421,+ 0.0+ ],+ [+ -1.41421,+ -1.41421,+ 1.0+ ],+ [+ -1.41421,+ 1.41421,+ 0.0+ ],+ [+ -1.41421,+ 1.41421,+ 1.0+ ],+ [+ -1.0,+ -0.0,+ 0.0+ ],+ [+ -1.0,+ -0.0,+ 1.0+ ],+ [+ -0.70711,+ -0.70711,+ 0.0+ ],+ [+ -0.70711,+ -0.70711,+ 1.0+ ],+ [+ -0.70711,+ 0.70711,+ 0.0+ ],+ [+ -0.70711,+ 0.70711,+ 1.0+ ],+ [+ 0.0,+ -2.0,+ 0.0+ ],+ [+ 0.0,+ -2.0,+ 1.0+ ],+ [+ 0.0,+ -1.0,+ 0.0+ ],+ [+ 0.0,+ -1.0,+ 1.0+ ],+ [+ -0.0,+ 1.0,+ 0.0+ ],+ [+ -0.0,+ 1.0,+ 1.0+ ],+ [+ -0.0,+ 2.0,+ 0.0+ ],+ [+ -0.0,+ 2.0,+ 1.0+ ],+ [+ 0.70711,+ -0.70711,+ 0.0+ ],+ [+ 0.70711,+ -0.70711,+ 1.0+ ],+ [+ 0.70711,+ 0.70711,+ 0.0+ ],+ [+ 0.70711,+ 0.70711,+ 1.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ],+ [+ 1.41421,+ -1.41421,+ 0.0+ ],+ [+ 1.41421,+ -1.41421,+ 1.0+ ],+ [+ 1.41421,+ 1.41421,+ 0.0+ ],+ [+ 1.41421,+ 1.41421,+ 1.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 1.0+ ]+ ]+ },+ "screw-quad-lift": {+ "vertexCount": 36,+ "edgeCount": 68,+ "faceCount": 32,+ "faceSizes": {+ "4": 32+ },+ "volume": 4.847324,+ "area": 21.443963,+ "positions": [+ [+ -2.0,+ -0.0,+ 4.0+ ],+ [+ -2.0,+ -0.0,+ 5.0+ ],+ [+ -1.84776,+ 0.76537,+ 3.5+ ],+ [+ -1.84776,+ 0.76537,+ 4.5+ ],+ [+ -1.41421,+ 1.41421,+ 3.0+ ],+ [+ -1.41421,+ 1.41421,+ 4.0+ ],+ [+ -1.0,+ -0.0,+ 4.0+ ],+ [+ -1.0,+ -0.0,+ 5.0+ ],+ [+ -0.92388,+ 0.38268,+ 3.5+ ],+ [+ -0.92388,+ 0.38268,+ 4.5+ ],+ [+ -0.76537,+ 1.84776,+ 2.5+ ],+ [+ -0.76537,+ 1.84776,+ 3.5+ ],+ [+ -0.70711,+ 0.70711,+ 3.0+ ],+ [+ -0.70711,+ 0.70711,+ 4.0+ ],+ [+ -0.38268,+ 0.92388,+ 2.5+ ],+ [+ -0.38268,+ 0.92388,+ 3.5+ ],+ [+ -0.0,+ 1.0,+ 2.0+ ],+ [+ -0.0,+ 1.0,+ 3.0+ ],+ [+ -0.0,+ 2.0,+ 2.0+ ],+ [+ -0.0,+ 2.0,+ 3.0+ ],+ [+ 0.38268,+ 0.92388,+ 1.5+ ],+ [+ 0.38268,+ 0.92388,+ 2.5+ ],+ [+ 0.70711,+ 0.70711,+ 1.0+ ],+ [+ 0.70711,+ 0.70711,+ 2.0+ ],+ [+ 0.76537,+ 1.84776,+ 1.5+ ],+ [+ 0.76537,+ 1.84776,+ 2.5+ ],+ [+ 0.92388,+ 0.38268,+ 0.5+ ],+ [+ 0.92388,+ 0.38268,+ 1.5+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ],+ [+ 1.41421,+ 1.41421,+ 1.0+ ],+ [+ 1.41421,+ 1.41421,+ 2.0+ ],+ [+ 1.84776,+ 0.76537,+ 0.5+ ],+ [+ 1.84776,+ 0.76537,+ 1.5+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 1.0+ ]+ ]+ },+ "wireframe-cube": {+ "vertexCount": 40,+ "edgeCount": 96,+ "faceCount": 48,+ "faceSizes": {+ "4": 48+ },+ "volume": 0.033486,+ "area": 2.76394,+ "positions": [+ [+ -0.52887,+ -0.52887,+ -0.52887+ ],+ [+ -0.52887,+ -0.52887,+ 0.52887+ ],+ [+ -0.52887,+ 0.52887,+ -0.52887+ ],+ [+ -0.52887,+ 0.52887,+ 0.52887+ ],+ [+ -0.5,+ -0.45,+ -0.45+ ],+ [+ -0.5,+ -0.45,+ 0.45+ ],+ [+ -0.5,+ 0.45,+ -0.45+ ],+ [+ -0.5,+ 0.45,+ 0.45+ ],+ [+ -0.47113,+ -0.47113,+ -0.47113+ ],+ [+ -0.47113,+ -0.47113,+ 0.47113+ ],+ [+ -0.47113,+ 0.47113,+ -0.47113+ ],+ [+ -0.47113,+ 0.47113,+ 0.47113+ ],+ [+ -0.45,+ -0.5,+ -0.45+ ],+ [+ -0.45,+ -0.5,+ 0.45+ ],+ [+ -0.45,+ -0.45,+ -0.5+ ],+ [+ -0.45,+ -0.45,+ 0.5+ ],+ [+ -0.45,+ 0.45,+ -0.5+ ],+ [+ -0.45,+ 0.45,+ 0.5+ ],+ [+ -0.45,+ 0.5,+ -0.45+ ],+ [+ -0.45,+ 0.5,+ 0.45+ ],+ [+ 0.45,+ -0.5,+ -0.45+ ],+ [+ 0.45,+ -0.5,+ 0.45+ ],+ [+ 0.45,+ -0.45,+ -0.5+ ],+ [+ 0.45,+ -0.45,+ 0.5+ ],+ [+ 0.45,+ 0.45,+ -0.5+ ],+ [+ 0.45,+ 0.45,+ 0.5+ ],+ [+ 0.45,+ 0.5,+ -0.45+ ],+ [+ 0.45,+ 0.5,+ 0.45+ ],+ [+ 0.47113,+ -0.47113,+ -0.47113+ ],+ [+ 0.47113,+ -0.47113,+ 0.47113+ ],+ [+ 0.47113,+ 0.47113,+ -0.47113+ ],+ [+ 0.47113,+ 0.47113,+ 0.47113+ ],+ [+ 0.5,+ -0.45,+ -0.45+ ],+ [+ 0.5,+ -0.45,+ 0.45+ ],+ [+ 0.5,+ 0.45,+ -0.45+ ],+ [+ 0.5,+ 0.45,+ 0.45+ ],+ [+ 0.52887,+ -0.52887,+ -0.52887+ ],+ [+ 0.52887,+ -0.52887,+ 0.52887+ ],+ [+ 0.52887,+ 0.52887,+ -0.52887+ ],+ [+ 0.52887,+ 0.52887,+ 0.52887+ ]+ ]+ },+ "wireframe-cube-outside-keep": {+ "vertexCount": 48,+ "edgeCount": 108,+ "faceCount": 54,+ "faceSizes": {+ "4": 54+ },+ "volume": 1.031486,+ "area": 8.597995,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ -0.47113,+ -0.42113,+ -0.42113+ ],+ [+ -0.47113,+ -0.42113,+ 0.42113+ ],+ [+ -0.47113,+ 0.42113,+ -0.42113+ ],+ [+ -0.47113,+ 0.42113,+ 0.42113+ ],+ [+ -0.44226,+ -0.44226,+ -0.44226+ ],+ [+ -0.44226,+ -0.44226,+ 0.44226+ ],+ [+ -0.44226,+ 0.44226,+ -0.44226+ ],+ [+ -0.44226,+ 0.44226,+ 0.44226+ ],+ [+ -0.42113,+ -0.47113,+ -0.42113+ ],+ [+ -0.42113,+ -0.47113,+ 0.42113+ ],+ [+ -0.42113,+ -0.42113,+ -0.47113+ ],+ [+ -0.42113,+ -0.42113,+ 0.47113+ ],+ [+ -0.42113,+ 0.42113,+ -0.47113+ ],+ [+ -0.42113,+ 0.42113,+ 0.47113+ ],+ [+ -0.42113,+ 0.47113,+ -0.42113+ ],+ [+ -0.42113,+ 0.47113,+ 0.42113+ ],+ [+ 0.42113,+ -0.47113,+ -0.42113+ ],+ [+ 0.42113,+ -0.47113,+ 0.42113+ ],+ [+ 0.42113,+ -0.42113,+ -0.47113+ ],+ [+ 0.42113,+ -0.42113,+ 0.47113+ ],+ [+ 0.42113,+ 0.42113,+ -0.47113+ ],+ [+ 0.42113,+ 0.42113,+ 0.47113+ ],+ [+ 0.42113,+ 0.47113,+ -0.42113+ ],+ [+ 0.42113,+ 0.47113,+ 0.42113+ ],+ [+ 0.44226,+ -0.44226,+ -0.44226+ ],+ [+ 0.44226,+ -0.44226,+ 0.44226+ ],+ [+ 0.44226,+ 0.44226,+ -0.44226+ ],+ [+ 0.44226,+ 0.44226,+ 0.44226+ ],+ [+ 0.47113,+ -0.42113,+ -0.42113+ ],+ [+ 0.47113,+ -0.42113,+ 0.42113+ ],+ [+ 0.47113,+ 0.42113,+ -0.42113+ ],+ [+ 0.47113,+ 0.42113,+ 0.42113+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "wireframe-quad-open": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 8,+ "faceSizes": {+ "4": 8+ },+ "volume": 0.057,+ "area": 0.537401,+ "positions": [+ [+ 1.0,+ -0.05,+ 0.0+ ],+ [+ 1.0,+ -0.05,+ 1.0+ ],+ [+ 1.0,+ 0.05,+ 0.0+ ],+ [+ 1.0,+ 0.05,+ 1.0+ ],+ [+ 1.05,+ 0.0,+ 0.05+ ],+ [+ 1.05,+ 0.0,+ 0.95+ ],+ [+ 1.95,+ 0.0,+ 0.05+ ],+ [+ 1.95,+ 0.0,+ 0.95+ ],+ [+ 2.0,+ -0.05,+ 0.0+ ],+ [+ 2.0,+ -0.05,+ 1.0+ ],+ [+ 2.0,+ 0.05,+ 0.0+ ],+ [+ 2.0,+ 0.05,+ 1.0+ ]+ ]+ },"decimate-bowl-half": {"faceCount": 592,"volume": 4.097792,diff --git a/tests/mesh-generator-modifiers.test.js b/tests/mesh-generator-modifiers.test.jsnew file mode 100644index 00000000..9ffb11d4--- /dev/null+++ b/tests/mesh-generator-modifiers.test.js@@ -0,0 +1,78 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { box } from '../src/geometry.js';+import { editMesh, validateTopology, meshFromGeometry, applyMeshEdits, evaluateMeshStack, normalizeMeshEdits } from '../src/mesh.js';+import { createMeshData } from '../src/mesh-data.js';++const cube = () => meshFromGeometry(box(0, 1));+const run = (mesh, edit, limits) => applyMeshEdits(mesh, [edit], limits);++function profileQuad() {+ return createMeshData({+ positions: Float32Array.from([1, 0, 0, 2, 0, 0, 2, 0, 1, 1, 0, 1]),+ faceOffsets: Uint32Array.from([0, 4]),+ cornerVertices: Uint32Array.from([0, 1, 2, 3]),+ });+}++test('screw closes a full turn into a ring and keeps the last copy open for a partial turn', () => {+ const ring = run(profileQuad(), { op: 'screw', angle: 360, steps: 8 }).mesh;+ assert.equal(ring.vertexCount, 32);+ assert.equal(ring.faceCount, 32);+ validateTopology(editMesh(ring));+ const partial = run(profileQuad(), { op: 'screw', angle: 90, steps: 4, iterations: 2, lift: 2 }).mesh;+ assert.equal(partial.vertexCount, 36);+ assert.equal(partial.faceCount, 32);+ assert.equal(partial.positions[(4 * 4 + 0) * 3 + 2], 2, 'after one iteration of four steps the profile has risen by the lift');+});++test('screw turns about the chosen axis and a negative angle turns the other way', () => {+ const forward = run(profileQuad(), { op: 'screw', axis: 'z', angle: 90, steps: 1 }).mesh;+ assert.ok(Math.abs(forward.positions[4 * 3]) < 1e-6);+ assert.ok(Math.abs(forward.positions[4 * 3 + 1] - 1) < 1e-6);+ const backward = run(profileQuad(), { op: 'screw', axis: 'z', angle: -90, steps: 1 }).mesh;+ assert.ok(Math.abs(backward.positions[4 * 3 + 1] + 1) < 1e-6);+});++test('screw names the limit and what to change when it would make too many vertices', () => {+ assert.throws(() => run(profileQuad(), { op: 'screw', steps: 256, iterations: 64 }, { maxVertices: 1000, maxFaces: 1000 }), /screw would make .* Lower steps or iterations/);+ assert.throws(() => normalizeMeshEdits([{ op: 'screw', steps: 257 }]), /steps must be an integer from 1 to 256/);+ assert.throws(() => normalizeMeshEdits([{ op: 'screw', axis: 'w' }]), /axis must be x, y or z/);+});++test('wireframe makes two quads per face edge, stays closed and puts the strut either side of the surface', () => {+ const frame = run(cube(), { op: 'wireframe', thickness: 0.1 }).mesh;+ assert.equal(frame.vertexCount, 40);+ assert.equal(frame.faceCount, 48);+ validateTopology(editMesh(frame));+ const kept = run(cube(), { op: 'wireframe', thickness: 0.1, replace: false }).mesh;+ assert.equal(kept.vertexCount, 48);+ assert.equal(kept.faceCount, 54);+ const reach = Math.max(...frame.positions.map(Math.abs));+ assert.ok(Math.abs(reach - 0.5289) < 1e-3);+});++test('wireframe refuses a result over the limits and bad fields', () => {+ assert.throws(() => run(cube(), { op: 'wireframe' }, { maxVertices: 10, maxFaces: 1000 }), /wireframe would make 40 vertices/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', thickness: 0 }]), /thickness must be a number above 0/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', offset: 2 }]), /offset must be a number from -1 to 1/);+ assert.throws(() => normalizeMeshEdits([{ op: 'wireframe', replace: 'yes' }]), /booleans/);+});++test('skin puts a closed square tube on every edge and takes a radius per vertex from a field', () => {+ const skinned = run(cube(), { op: 'skin', radius: 0.05 }).mesh;+ assert.equal(skinned.vertexCount, 12 * 8);+ assert.equal(skinned.faceCount, 12 * 6);+ const fat = run(cube(), { op: 'skin', radius: { add: [0.1, { mul: [0.1, { attr: 'position', component: 'z' }] }] } }).mesh;+ const upperReach = Math.max(...Array.from({ length: fat.vertexCount }, (_, vertex) => fat.positions[vertex * 3]));+ assert.ok(upperReach > 0.6 && upperReach < 0.7);+ assert.throws(() => run(cube(), { op: 'skin', radius: { mul: [0, { attr: 'position', component: 'z' }] } }), /radius must be above zero at every vertex/);+ assert.throws(() => run(cube(), { op: 'skin' }, { maxVertices: 50, maxFaces: 1000 }), /skin would make 96 vertices/);+ assert.throws(() => normalizeMeshEdits([{ op: 'skin', radius: -1 }]), /radius must be a number above 0/);+});++test('the generating modifiers run as stack nodes', () => {+ const outcome = evaluateMeshStack(cube(), [{ op: 'wireframe', thickness: 0.1 }, { op: 'skin', radius: 0.01 }]);+ assert.equal(outcome.results.length, 2);+ assert.ok(outcome.mesh.faceCount > 48);+});