3D engine that AI agents drive
Add poke, dual, tris_to_quads, symmetrize, scale_elements and extrude_edges mesh edits
Nguyen Xuan Ane23525cdd62c
diff --git a/changes/703.md b/changes/703.mdnew file mode 100644index 00000000..423efa4b--- /dev/null+++ b/changes/703.md@@ -0,0 +1 @@+- `mesh_edit` gains `poke`, `dual`, `tris_to_quads`, `symmetrize`, `scale_elements` and `extrude_edges` (#703)diff --git a/changes/703.size.md b/changes/703.size.mdnew file mode 100644index 00000000..5b7122c6--- /dev/null+++ b/changes/703.size.md@@ -0,0 +1,5 @@+- entry:mesh: poke, dual, tris to quads, symmetrize, scale elements and extrude edges are modeling edits agents lacked (2815 bytes gzip); the lead approved growth for modeling capabilities+- scene:agent-scene: the six edit names and their validators ship in the core bundle (75 bytes gzip)+- scene:agent-scene+lazy: the same edits ship in the lazy bundle (2823 bytes gzip)+- goal:agent-scene: the capability is worth 75 bytes gzip over the goal; lead approved growth for modeling features+- tool:mesh_edit: six new op names in the op enum (76 bytes); field detail stays in the meshEdit.<op> capabilities topicdiff --git a/docs/mesh.md b/docs/mesh.mdindex b01d4f0b..620ef51c 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -385,6 +385,25 @@ Open boundaries reported by lint (`boundary-edge`) are fixed with `fill_holes`.(`holes_fill`, `dissolve_*`, `bisect_plane`, `bridge_loops`, `grid_fill`, `subdivide_edges`) where the meaning matches, and`point` and `normal` are Blender's `plane_co` and `plane_no`.+### Reshaping tools++These edits change how a surface is divided or shaped. Elements are visited in index order and ties break toward the+lower index, so the same input always gives the same bytes. Faces they keep carry their tags and attributes.++| Edit | Fields | Tags | What it does |+| --- | --- | --- | --- |+| `poke` | `select`, `offset` (default 0), `relative` | `poke` | Replaces each selected face with a triangle fan around a centre vertex at the face's average point, moved `offset` along the face normal (times the face's average corner distance when `relative`). |+| `dual` | none | `dual` | One vertex at each face centre and one face around each vertex, wound the same way as the original. Needs a closed mesh with consistent winding; the new faces carry no attributes. |+| `tris_to_quads` | `select`, `angle` (default 40) | `merged` | Joins adjacent selected triangles whose normals differ by at most `angle` degrees into convex quads, the most rectangular pairs first; each triangle joins once. |+| `symmetrize` | `axis` (default x), `keep` (`positive` or `negative`), `distance` | `mirrored` | Cuts faces that cross the plane through the origin, drops the other half and mirrors the kept half. Left and right (top and bottom, front and back) tags swap on the mirrored half. |+| `scale_elements` | `select`, `scale` (above 0) | none | Scales each group of selected faces that share a vertex about the group's average vertex position. Unselected neighbours follow along shared vertices. |+| `extrude_edges` | `edges`, `offset` | `side` | Copies the vertices of the selected edges, moves the copies by `offset` and joins each edge to its copy with a quad. Select a surface boundary with `{ "open": true }`. |++`dual` and `symmetrize` leave a closed surface closed. `extrude_edges` on interior edges adds a fin, so a closed+mesh is no longer closed afterwards. `extrude_vertices` is not offered: a mesh derives its edges from faces and cannot+hold a loose edge. The size of `poke` and `extrude_edges` is checked before they allocate. The `meshEdit.<op>`+capabilities topic lists the exact fields.+### Subdivide`subdivide` is Catmull-Clark subdivision with semi-sharp creases, as an edit or as a stack node, on the rules Pixardiff --git a/docs/parity.md b/docs/parity.mdindex a199dcb1..b79be725 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -47,7 +47,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Meshes > Primitives | partial | Box, cylinder, sphere and torus. There is no plane, grid, cone, ico sphere or monkey primitive. | | || Modeling > Meshes > Tools | partial | The operations behind extrude and loop cut exist as edits. Spin is covered only by `lathe`. | | #41 || Modeling > Meshes > Selecting | partial | Rules: all, tag, normal, inside, faces, and, or, not, grow, boundary. There is no loop, linked, similar or sharp edge selection. | | #41 |-| Modeling > Meshes > Editing | partial | 26 edits, including extrude, inset, bevel, loop cut, boolean, merge, bisect, bridge, fill, grid fill, dissolve, edge subdivision and a knife by projected polyline. All but the knife match Blender on fixtures; the knife is compared only with a straight plane cut. | [Blender results](../tests/fixtures/blender/golden.json) | #41 |+| Modeling > Meshes > Editing | partial | 32 edits, including extrude, inset, bevel, loop cut, boolean, merge, bisect, bridge, fill, grid fill, dissolve, edge subdivision, a knife by projected polyline, poke, dual, tris to quads, symmetrize, scale elements and extrude edges. All but the knife and the six newest match Blender on fixtures (those six have unit tests; Blender cases are open in #703); the knife is compared only with a straight plane cut. | [Blender results](../tests/fixtures/blender/golden.json) | #41 || Modeling > Meshes > Properties | partial | `smoothAngle` and face tags. There is no sharp edge attribute or crease. | | #39 || Modeling > Meshes > UVs | partial | `uv_unwrap` with LSCM, axis charts and shelf packing. Patterns can not use the result yet. | | #50 || Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. With `{ geometry: true }` (always on in `mesh_inspect`) it also warns of crossing parts, a solid cutting itself, thin walls, floating parts and near-symmetry, using the BVH within face budgets. Checks are heuristics on parts, not Blender's exact Select Non-Manifold or Intersect checks. | [tests/mesh-lint-geometry.test.js](../tests/mesh-lint-geometry.test.js), [src/mesh-lint-geometry.js](../src/mesh-lint-geometry.js) | #66 |diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex ef846d3c..30927342 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -386,6 +386,12 @@ const meshEdit = z.discriminatedUnion('op', [op: z.literal('knife_project'), name: editName,path: z.array(vector3).min(2).max(256).describe('Polyline in the mesh\'s local space.'), direction: vector3.describe('Direction the line is projected along, for example [0,0,-1].'),}).describe('Cut along a polyline projected along a direction, through front and back faces. Split faces get <name>.cut.'),+ z.strictObject({ op: z.literal('poke'), select: selectRule.optional(), name: editName, offset: finite.optional().describe('Move each new centre along the face normal. Defaults to 0.'), relative: z.boolean().optional().describe('Scale offset by the face\'s average corner distance.') }).describe('Replace each selected face with a triangle fan around a centre vertex, tagged <name>.poke.'),+ z.strictObject({ op: z.literal('dual'), name: editName }).describe('Dual mesh: a vertex per face centre, a face per vertex, tagged <name>.dual. Needs a closed, consistently wound mesh.'),+ z.strictObject({ op: z.literal('tris_to_quads'), select: selectRule.optional(), name: editName, angle: bounded(0, 180).optional().describe('Largest angle in degrees between the two triangle normals. Defaults to 40.') }).describe('Join adjacent triangles into convex quads, best-shaped first, tagged <name>.merged.'),+ z.strictObject({ op: z.literal('symmetrize'), name: editName, axis: z.enum(['x', 'y', 'z']).optional(), keep: z.enum(['positive', 'negative']).optional().describe('Side of the plane kept and mirrored. Defaults to positive.'), distance: bounded(0, 1).optional().describe('Vertices this close to the plane count as on it. Defaults to 0.0001.') }).describe('Cut at the plane through the origin, drop the other half and mirror the kept half. Mirrored faces get <name>.mirrored.'),+ z.strictObject({ op: z.literal('scale_elements'), select: selectRule.optional(), scale: finite.describe('Factor above 0 about each connected group of selected faces.') }).describe('Scale connected groups of selected faces about their own centres.'),+ z.strictObject({ op: z.literal('extrude_edges'), name: editName, edges: edgeRule.describe('Edges to extrude, usually {"open":true} for a boundary.'), offset: vector3.describe('Where the copied vertices move.') }).describe('Extrude edges into quads, tagged <name>.side.'),z.strictObject({ op: z.literal('tag'), select: selectRule, name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).describe('Tag to add to the selected faces.') }),z.strictObject({op: z.literal('boolean'), name: editName,diff --git a/src/mesh-cut-edits.js b/src/mesh-cut-edits.jsindex 4eb4ba73..54210d22 100644--- a/src/mesh-cut-edits.js+++ b/src/mesh-cut-edits.js@@ -19,7 +19,7 @@ export const CUT_OPERATIONS = Object.freeze([]);const MAX_PATH_POINTS = 256;-const EDGE_RULE_HINT = 'an edge rule such as { "all": true }, { "angle": 30 }, { "along": [x, y, z] } or { "open": true }';+export const EDGE_RULE_HINT = 'an edge rule such as { "all": true }, { "angle": 30 }, { "along": [x, y, z] } or { "open": true }';function booleanField(value, index, label) {return editBoolean(value, index, label) ?? false;diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 68ad9d6a..edc34d1b 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -57,6 +57,12 @@ export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({subdivide_edges: { fields: ['edges', 'name', 'cuts'], tags: ['split'] },grid_fill: { fields: ['edges', 'name'], tags: ['fill'] },knife_project: { fields: ['name', 'path', 'direction'], tags: ['cut'] },+ poke: { fields: ['select', 'name', 'offset', 'relative'], tags: ['poke'] },+ dual: { fields: ['name'], tags: ['dual'] },+ tris_to_quads: { fields: ['select', 'name', 'angle'], tags: ['merged'] },+ symmetrize: { fields: ['name', 'axis', 'keep', 'distance'], tags: ['mirrored'] },+ scale_elements: { fields: ['select', 'scale'], tags: [] },+ extrude_edges: { fields: ['edges', 'name', 'offset'], tags: ['side'] },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: [] },diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex c64a3349..d19f0a3d 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -12,6 +12,7 @@ import { mirrorMesh, arrayMesh, solidifyMesh } from './mesh-stack.js';import { bevelEdges } from './mesh-bevel.js';import { loopCut } from './mesh-loopcut.js';import { CUT_OPERATIONS, normalizeCutEdit, runCutEdit, checkCutBudget } from './mesh-cut-edits.js';+import { RESHAPE_OPERATIONS, normalizeReshapeEdit, runReshapeEdit, checkReshapeBudget } from './mesh-reshape-edits.js';import { unwrapUv } from './mesh-uv.js';import { projectUv, packUvIslands, UV_PROJECTION_MODES } from './mesh-uv-project.js';import { runKernel, KernelDeferred } from './kernel-offload.js';@@ -324,6 +325,7 @@ export function normalizeMeshEdits(edits) {break;}if (CUT_OPERATIONS.includes(edit.op)) normalizeCutEdit(edit, normalized, index, { finiteNumber, vector });+ if (RESHAPE_OPERATIONS.includes(edit.op)) normalizeReshapeEdit(edit, normalized, index, { finiteNumber, vector });if (isModifierOperation(edit.op)) normalizeModifierEdit(edit, normalized, index, { finiteNumber, checkedField });return normalized;});@@ -339,6 +341,7 @@ function checkSubdivideBudget(mesh, edit, limits, index) {function checkArrayBudget(mesh, edit, limits, index) {checkCutBudget(mesh, edit, limits, index);+ checkReshapeBudget(mesh, edit, limits, index);if (edit.op === 'sculpt') {try {checkSculptBudget(mesh, edit.strokes.length);@@ -474,10 +477,10 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {result.tags = tagSummary(outcome.mesh, edit.name);return { mesh: outcome.mesh, result };}- if (CUT_OPERATIONS.includes(edit.op)) {+ if (CUT_OPERATIONS.includes(edit.op) || RESHAPE_OPERATIONS.includes(edit.op)) {let outcome;try {- outcome = runCutEdit(current, edit);+ outcome = CUT_OPERATIONS.includes(edit.op) ? runCutEdit(current, edit) : runReshapeEdit(current, edit);} catch (error) {throw editFailure(error, index, `${edit.op}`);}diff --git a/src/mesh-reshape-edits.js b/src/mesh-reshape-edits.jsnew file mode 100644index 00000000..a2cebfdb--- /dev/null+++ b/src/mesh-reshape-edits.js@@ -0,0 +1,100 @@+import { selectEdges, edgeFaces } from './mesh-bevel.js';+import { selectFaces, countSelected } from './mesh-select.js';+import { invalidField } from './field-error.js';+import { editField, editRuleObject } from './mesh-edit-field.js';+import { EDGE_RULE_HINT } from './mesh-cut-edits.js';+import { pokeFaces, dualMesh, trisToQuads, symmetrizeMesh, scaleElements, extrudeEdges } from './mesh-reshape.js';++// The reshaping edits as recipe operations: validation of their fields and running them on MeshData. The geometry+// lives in mesh-reshape.js; this file only connects it to the edit log.++export const RESHAPE_OPERATIONS = Object.freeze(['poke', 'dual', 'tris_to_quads', 'symmetrize', 'scale_elements', 'extrude_edges']);++const SYMMETRIZE_SIDES = Object.freeze(['positive', 'negative']);+const MAX_SCALE = 1000;++/** Fill in `normalized` for a reshaping edit, throwing a TypeError that names the edit when a field is wrong. */+export function normalizeReshapeEdit(edit, normalized, index, { finiteNumber, vector }) {+ switch (edit.op) {+ case 'poke':+ normalized.offset = edit.offset === undefined ? 0 : finiteNumber(edit.offset, index, 'offset');+ if (edit.relative !== undefined && typeof edit.relative !== 'boolean') throw editField(index, 'relative', edit.relative, 'true or false');+ normalized.relative = edit.relative ?? false;+ break;+ case 'tris_to_quads':+ normalized.angle = edit.angle === undefined ? 40 : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });+ break;+ case 'symmetrize':+ if (edit.axis !== undefined && !['x', 'y', 'z'].includes(edit.axis)) throw editField(index, 'axis', edit.axis, 'one of "x", "y", "z"');+ normalized.axis = edit.axis ?? 'x';+ if (edit.keep !== undefined && !SYMMETRIZE_SIDES.includes(edit.keep)) throw editField(index, 'keep', edit.keep, `one of ${SYMMETRIZE_SIDES.map(side => `"${side}"`).join(', ')}`);+ normalized.keep = edit.keep ?? 'positive';+ normalized.distance = edit.distance === undefined ? 1e-4 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1 });+ break;+ case 'scale_elements':+ normalized.scale = finiteNumber(edit.scale, index, 'scale', { minimum: 0, maximum: MAX_SCALE, exclusiveMinimum: true });+ break;+ case 'extrude_edges':+ normalized.edges = editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);+ normalized.offset = vector(edit.offset, index, 'offset');+ break;+ }+}++/** Refuse an extrude_edges that would grow past the limits, before it allocates anything. */+export function checkReshapeBudget(mesh, edit, limits, index) {+ if (edit.op === 'poke') {+ const mask = selectFaces(mesh, edit.select);+ let corners = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ if (mask[face]) corners += mesh.faceOffsets[face + 1] - mesh.faceOffsets[face];+ }+ const faces = mesh.faceCount - countSelected(mask) + corners;+ if (faces > limits.maxFaces) {+ throw editField(index, 'select', edit.select, `a rule that keeps the mesh within ${limits.maxFaces} faces (this edit would make ${faces}), such as { "tag": "top" }`, RangeError);+ }+ }+ if (edit.op === 'extrude_edges') {+ const edges = countSelected(selectEdges(mesh, edit.edges, edgeFaces(mesh)));+ if (mesh.faceCount + edges > limits.maxFaces || mesh.vertexCount + edges * 2 > limits.maxVertices) {+ throw editField(index, 'edges', edit.edges, `a rule that keeps the mesh within ${limits.maxVertices} vertices and ${limits.maxFaces} faces (this edit would add up to ${edges * 2} vertices and ${edges} faces), such as { "open": true }`, RangeError);+ }+ }+}++function faceMaskOf(mesh, rule) {+ const mask = selectFaces(mesh, rule);+ if (countSelected(mask) === 0) throw invalidField('select', rule, 'a rule that matches at least one face, such as { "all": true } (check tags and counts with mesh_inspect)');+ return mask;+}++/** Run a reshaping edit. Returns { mesh, result } where result holds the counts to report. */+export function runReshapeEdit(mesh, edit) {+ switch (edit.op) {+ case 'poke': {+ const outcome = pokeFaces(mesh, faceMaskOf(mesh, edit.select), { offset: edit.offset, relative: edit.relative, name: edit.name });+ return { mesh: outcome.mesh, result: { pokedFaces: outcome.pokedFaces } };+ }+ case 'dual': {+ const outcome = dualMesh(mesh, { name: edit.name });+ return { mesh: outcome.mesh, result: { dualVertices: outcome.dualVertices, dualFaces: outcome.dualFaces } };+ }+ case 'tris_to_quads': {+ const outcome = trisToQuads(mesh, faceMaskOf(mesh, edit.select), { angle: edit.angle, name: edit.name });+ return { mesh: outcome.mesh, result: { joinedPairs: outcome.joinedPairs } };+ }+ case 'symmetrize': {+ const outcome = symmetrizeMesh(mesh, { axis: edit.axis, keep: edit.keep, distance: edit.distance, name: edit.name });+ return { mesh: outcome.mesh, result: { removedFaces: outcome.removedFaces } };+ }+ case 'scale_elements': {+ const outcome = scaleElements(mesh, faceMaskOf(mesh, edit.select), { scale: edit.scale });+ return { mesh: outcome.mesh, result: { movedVertices: outcome.movedVertices, islands: outcome.islands } };+ }+ case 'extrude_edges': {+ const outcome = extrudeEdges(mesh, selectEdges(mesh, edit.edges, edgeFaces(mesh)), { offset: edit.offset, name: edit.name });+ return { mesh: outcome.mesh, result: { extrudedEdges: outcome.extrudedEdges } };+ }+ }+ throw new TypeError(`Not a reshaping edit: ${edit.op}`);+}diff --git a/src/mesh-reshape.js b/src/mesh-reshape.jsnew file mode 100644index 00000000..bd71aab0--- /dev/null+++ b/src/mesh-reshape.js@@ -0,0 +1,319 @@+import { createMeshData, TAG_PREFIX } from './mesh-data.js';+import { MeshBuilder, mirrorMesh } from './mesh-stack.js';+import { faceNormals } from './mesh-normals.js';+import { facePolygons, buildPolygonMesh, edgeFaces } from './mesh-polygons.js';+import { bisectPlane } from './mesh-bisect.js';+import { dissolveEdges } from './mesh-dissolve.js';+import { UnionFind } from './mesh-topology.js';++// Reshaping edits after Blender's poke, dual mesh, tris to quads, symmetrize, scale elements and extrude edges.+// Every edit is deterministic: elements are visited in index order and ties break toward the lower index.++const AXIS_INDEX = Object.freeze({ x: 0, y: 1, z: 2 });++function positionOf(mesh, vertex) {+ return [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+}++function faceVertices(mesh, face) {+ const vertices = [];+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) vertices.push(mesh.cornerVertices[corner]);+ return vertices;+}++function faceCenter(mesh, face) {+ const center = [0, 0, 0];+ const vertices = faceVertices(mesh, face);+ for (const vertex of vertices) {+ for (let axis = 0; axis < 3; axis++) center[axis] += mesh.positions[vertex * 3 + axis] / vertices.length;+ }+ return center;+}++/**+ * Replace each selected face with a triangle fan around a new centre vertex. The centre sits at the face's average+ * point, moved `offset` along the face normal (times the average corner distance when `relative`). The triangles keep+ * the face's attributes and get the tag `<name>.poke`; a corner at the centre takes the middle of its triangle's base.+ */+export function pokeFaces(mesh, faceMask, { offset = 0, relative = false, name = 'poke' } = {}) {+ const { normals } = faceNormals(mesh);+ const extraPositions = [];+ const polygons = facePolygons(mesh);+ const result = [];+ let poked = 0;+ polygons.forEach((polygon, face) => {+ if (!faceMask[face]) {+ result.push(polygon);+ return;+ }+ const center = faceCenter(mesh, face);+ const vertices = polygon.vertices;+ let scale = offset;+ if (relative) {+ const meanDistance = vertices.reduce((sum, vertex) => sum + Math.hypot(...positionOf(mesh, vertex).map((value, axis) => value - center[axis])), 0) / vertices.length;+ scale = offset * meanDistance;+ }+ extraPositions.push(center.map((value, axis) => value + normals[face * 3 + axis] * scale));+ const centerVertex = mesh.vertexCount + extraPositions.length - 1;+ for (let index = 0; index < vertices.length; index++) {+ const next = (index + 1) % vertices.length;+ result.push({+ vertices: [vertices[index], vertices[next], centerVertex],+ sourceFace: face,+ sourceCorners: [polygon.sourceCorners[index], polygon.sourceCorners[next], { from: polygon.sourceCorners[index], to: polygon.sourceCorners[next], t: 0.5 }],+ sourceEdges: [polygon.sourceEdges[index], -1, -1],+ tags: [`${name}.poke`],+ });+ }+ poked++;+ });+ if (poked === 0) throw new RangeError('The selection holds no face to poke.');+ return { mesh: buildPolygonMesh(mesh, result, extraPositions), pokedFaces: poked };+}++/**+ * Dual mesh: one vertex at the centre of every face and one face around every vertex, wound the same way as the+ * original. The mesh must be closed with consistent winding, so that the faces around each vertex form one ring.+ * Dual faces are new, so they carry no attributes and get the tag `<name>.dual`.+ */+export function dualMesh(mesh, { name = 'dual' } = {}) {+ const halfEdgeKey = (from, to) => from * mesh.vertexCount + to;+ const faceOfHalfEdge = new Map();+ const cornersOfVertex = Array.from({ length: mesh.vertexCount }, () => []);+ for (let face = 0; face < mesh.faceCount; face++) {+ const vertices = faceVertices(mesh, face);+ vertices.forEach((vertex, index) => {+ const next = vertices[(index + 1) % vertices.length];+ const key = halfEdgeKey(vertex, next);+ if (faceOfHalfEdge.has(key)) throw new RangeError(`Faces ${faceOfHalfEdge.get(key)} and ${face} both run from vertex ${vertex} to vertex ${next}; dual needs consistent winding. Run flip_normals on the faces that point the wrong way.`);+ faceOfHalfEdge.set(key, face);+ cornersOfVertex[vertex].push({ face, previous: vertices[(index + vertices.length - 1) % vertices.length] });+ });+ }+ const builder = new MeshBuilder(mesh);+ const centers = Array.from({ length: mesh.faceCount }, (_, face) => builder.addVertex(...faceCenter(mesh, face)));+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const corners = cornersOfVertex[vertex];+ if (corners.length === 0) continue;+ const previousOf = new Map(corners.map(({ face, previous }) => [face, previous]));+ const ring = [];+ let face = corners[0].face;+ do {+ ring.push(face);+ const neighbor = faceOfHalfEdge.get(halfEdgeKey(vertex, previousOf.get(face)));+ if (neighbor === undefined) throw new RangeError(`Vertex ${vertex} lies on an open boundary; dual needs a closed mesh. Run fill_holes first.`);+ face = neighbor;+ } while (face !== corners[0].face && ring.length <= corners.length);+ if (ring.length !== corners.length) throw new RangeError(`The faces around vertex ${vertex} do not form one ring (a pinched or non-manifold vertex); dual needs a manifold mesh. Run merge_by_distance or split the mesh.`);+ builder.addFace(ring.map(ringFace => centers[ringFace]), { tags: [`${name}.dual`] });+ }+ return { mesh: builder.build(), dualFaces: builder.faceSources.length, dualVertices: mesh.faceCount };+}++function cornerAngleDegrees(origin, first, second) {+ const a = first.map((value, axis) => value - origin[axis]);+ const b = second.map((value, axis) => value - origin[axis]);+ const dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2];+ const cross = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];+ return Math.atan2(Math.hypot(...cross), dot) * 180 / Math.PI;+}++// Joined quad [apex of A, p, apex of B, q] for triangles A = (apex, p, q) and B = (apex, q, p) over the shared edge p-q.+function quadCandidate(mesh, edge, faceA, faceB, normals, maxAngle) {+ const sharedFrom = mesh.edgeVertices[edge * 2];+ const sharedTo = mesh.edgeVertices[edge * 2 + 1];+ const verticesA = faceVertices(mesh, faceA);+ const verticesB = faceVertices(mesh, faceB);+ const startA = verticesA.findIndex(vertex => !(vertex === sharedFrom || vertex === sharedTo));+ const apexA = verticesA[startA];+ const p = verticesA[(startA + 1) % 3];+ const q = verticesA[(startA + 2) % 3];+ const apexB = verticesB.find(vertex => vertex !== p && vertex !== q);+ const quad = [apexA, p, apexB, q];+ const dotNormals = normals[faceA * 3] * normals[faceB * 3] + normals[faceA * 3 + 1] * normals[faceB * 3 + 1] + normals[faceA * 3 + 2] * normals[faceB * 3 + 2];+ if (Math.acos(Math.max(-1, Math.min(1, dotNormals))) * 180 / Math.PI > maxAngle) return null;+ const points = quad.map(vertex => positionOf(mesh, vertex));+ let cost = 0;+ for (let corner = 0; corner < 4; corner++) {+ const angle = cornerAngleDegrees(points[corner], points[(corner + 3) % 4], points[(corner + 1) % 4]);+ if (angle >= 179) return null;+ cost += Math.abs(angle - 90);+ }+ // A concave quad has a corner turning the other way from the face normal.+ const normalX = normals[faceA * 3] + normals[faceB * 3];+ const normalY = normals[faceA * 3 + 1] + normals[faceB * 3 + 1];+ const normalZ = normals[faceA * 3 + 2] + normals[faceB * 3 + 2];+ for (let corner = 0; corner < 4; corner++) {+ const before = points[(corner + 3) % 4];+ const here = points[corner];+ const after = points[(corner + 1) % 4];+ const first = here.map((value, axis) => value - before[axis]);+ const second = after.map((value, axis) => value - here[axis]);+ const turn = (first[1] * second[2] - first[2] * second[1]) * normalX + (first[2] * second[0] - first[0] * second[2]) * normalY + (first[0] * second[1] - first[1] * second[0]) * normalZ;+ if (turn <= 0) return null;+ }+ return { edge, faceA, faceB, cost };+}++/**+ * Join pairs of adjacent selected triangles into quads. A pair qualifies when its face normals differ by at most+ * `angle` degrees and the quad is convex; the best (closest to rectangular) pairs are taken first and each triangle+ * joins at most once. Joined faces get the tag `<name>.merged`.+ */+export function trisToQuads(mesh, faceMask, { angle = 40, name = 'tris' } = {}) {+ const { normals } = faceNormals(mesh);+ const table = edgeFaces(mesh);+ const candidates = [];+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const faces = table.faces[edge];+ if (faces.length !== 2) continue;+ const [faceA, faceB] = faces;+ if (!faceMask[faceA] || !faceMask[faceB]) continue;+ if (mesh.faceOffsets[faceA + 1] - mesh.faceOffsets[faceA] !== 3 || mesh.faceOffsets[faceB + 1] - mesh.faceOffsets[faceB] !== 3) continue;+ const candidate = quadCandidate(mesh, edge, faceA, faceB, normals, angle);+ if (candidate) candidates.push(candidate);+ }+ candidates.sort((first, second) => first.cost - second.cost || first.edge - second.edge);+ const taken = new Uint8Array(mesh.faceCount);+ const edgeMask = new Uint8Array(mesh.edgeCount);+ let joined = 0;+ for (const { edge, faceA, faceB } of candidates) {+ if (taken[faceA] || taken[faceB]) continue;+ taken[faceA] = 1;+ taken[faceB] = 1;+ edgeMask[edge] = 1;+ joined++;+ }+ if (joined === 0) throw new RangeError(`No two adjacent selected triangles join into a convex quad within ${angle} degrees. Select triangles (triangulate first), or raise angle.`);+ return { mesh: dissolveEdges(mesh, edgeMask, { name }).mesh, joinedPairs: joined };+}++function withoutTags(mesh, tagNames) {+ const attributes = { ...mesh.attributes, face: { ...mesh.attributes.face } };+ for (const tag of tagNames) delete attributes.face[TAG_PREFIX + tag];+ return createMeshData({+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,+ });+}++/**+ * Make the mesh symmetric across the plane through the origin perpendicular to `axis`: keep the half on the `keep`+ * side ("positive" or "negative"), cut faces that cross the plane, drop the other half and mirror the kept half over+ * it. Mirrored faces get `<name>.mirrored` and swap their left/right (top/bottom, front/back) tags.+ */+export function symmetrizeMesh(mesh, { axis = 'x', keep = 'positive', distance = 1e-4, name = 'symmetrize' } = {}) {+ const axisIndex = AXIS_INDEX[axis];+ const sign = keep === 'positive' ? 1 : -1;+ // 1 on the kept side, -1 on the dropped side, 0 within `distance` of the plane.+ const sideOf = (source, vertex) => {+ const coordinate = source.positions[vertex * 3 + axisIndex] * sign;+ if (coordinate > distance) return 1;+ return coordinate < -distance ? -1 : 0;+ };+ let straddles = false;+ for (let face = 0; face < mesh.faceCount && !straddles; face++) {+ const sides = faceVertices(mesh, face).map(vertex => sideOf(mesh, vertex));+ straddles = sides.includes(1) && sides.includes(-1);+ }+ let current = mesh;+ if (straddles) {+ const normal = [0, 0, 0];+ normal[axisIndex] = 1;+ const cutName = `${name}.cut`;+ const cut = bisectPlane(mesh, { point: [0, 0, 0], normal, distance, name: cutName });+ current = withoutTags(cut.mesh, [`${cutName}.inner`, `${cutName}.outer`]);+ }+ const kept = facePolygons(current).filter(polygon => polygon.vertices.every(vertex => sideOf(current, vertex) >= 0));+ const hasKeptSide = kept.some(polygon => polygon.vertices.some(vertex => sideOf(current, vertex) === 1));+ if (!hasKeptSide) {+ throw new RangeError(`No face lies on the ${keep} side of the ${axis} axis, so there is nothing to mirror. Use keep "${keep === 'positive' ? 'negative' : 'positive'}" or another axis.`);+ }+ const removedFaces = current.faceCount - kept.length;+ const half = buildPolygonMesh(current, kept);+ return { mesh: mirrorMesh(half, { axis, merge: distance, name }), removedFaces };+}++/**+ * Scale the vertices of the selected faces about their centre. Faces that share a vertex scale together as one+ * island, about the average of the island's vertices, so a connected selection keeps its shape. Neighbouring faces+ * that are not selected follow along their shared vertices.+ */+export function scaleElements(mesh, faceMask, { scale }) {+ const groups = new UnionFind(mesh.vertexCount);+ const selected = new Uint8Array(mesh.vertexCount);+ let selectedFaces = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ if (!faceMask[face]) continue;+ selectedFaces++;+ const vertices = faceVertices(mesh, face);+ for (const vertex of vertices) {+ selected[vertex] = 1;+ groups.union(vertices[0], vertex);+ }+ }+ if (selectedFaces === 0) throw new RangeError('The selection holds no face to scale.');+ const sums = new Map();+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!selected[vertex]) continue;+ const root = groups.find(vertex);+ if (!sums.has(root)) sums.set(root, { total: [0, 0, 0], count: 0 });+ const island = sums.get(root);+ for (let axis = 0; axis < 3; axis++) island.total[axis] += mesh.positions[vertex * 3 + axis];+ island.count++;+ }+ const positions = Float32Array.from(mesh.positions);+ let movedVertices = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!selected[vertex]) continue;+ const island = sums.get(groups.find(vertex));+ for (let axis = 0; axis < 3; axis++) {+ const center = island.total[axis] / island.count;+ positions[vertex * 3 + axis] = center + (mesh.positions[vertex * 3 + axis] - center) * scale;+ }+ movedVertices++;+ }+ const scaled = createMeshData({+ positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes: mesh.attributes,+ });+ return { mesh: scaled, movedVertices, islands: sums.size };+}++/**+ * Extrude the selected edges: every vertex on a selected edge is copied and moved by `offset`, and each edge gets a+ * quad between it and its copy, tagged `<name>.side`. The new quad is wound against the first face of its edge so a+ * boundary edge continues the surface. Select boundary edges with { "open": true } to grow a surface outward.+ */+export function extrudeEdges(mesh, edgeMask, { offset, name = 'extrude' }) {+ const table = edgeFaces(mesh);+ const polygons = facePolygons(mesh);+ const extraPositions = [];+ const copyOf = new Map();+ const copyVertex = vertex => {+ if (!copyOf.has(vertex)) {+ extraPositions.push(positionOf(mesh, vertex).map((value, axis) => value + offset[axis]));+ copyOf.set(vertex, mesh.vertexCount + extraPositions.length - 1);+ }+ return copyOf.get(vertex);+ };+ let extruded = 0;+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (!edgeMask[edge]) continue;+ const face = table.faces[edge][0];+ let from = -1;+ let to = -1;+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ if (mesh.cornerEdges[corner] !== edge) continue;+ from = mesh.cornerVertices[corner];+ to = mesh.cornerVertices[corner + 1 === mesh.faceOffsets[face + 1] ? mesh.faceOffsets[face] : corner + 1];+ }+ polygons.push({+ vertices: [to, from, copyVertex(from), copyVertex(to)],+ sourceFace: -1, sourceCorners: null, sourceEdges: null, tags: [`${name}.side`],+ });+ extruded++;+ }+ if (extruded === 0) throw new RangeError('The rule selects no edge. For a surface boundary use { "open": true }.');+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), extrudedEdges: extruded };+}diff --git a/tests/actionable-errors-mesh-edits.test.js b/tests/actionable-errors-mesh-edits.test.jsindex 4c24bd36..e4bc42fc 100644--- a/tests/actionable-errors-mesh-edits.test.js+++ b/tests/actionable-errors-mesh-edits.test.js@@ -49,6 +49,12 @@ const CASES = [['src/mesh-cut-edits.js', 'dissolve_edges rule as a list', badEdit({ op: 'dissolve_edges', edges: [] }), 'edits[0].edges', '[]'],['src/mesh-cut-edits.js', 'subdivide_edges cuts too many', badEdit({ op: 'subdivide_edges', edges: { all: true }, cuts: 99 }), 'edits[0].cuts', '99'],['src/mesh-cut-edits.js', 'dissolve_faces rule selects nothing', badEdit({ op: 'dissolve_faces', select: { faces: [] } }), 'edits[0].select', '{"faces":[]}'],+ ['src/mesh-reshape-edits.js', 'poke offset as text', badEdit({ op: 'poke', offset: 'far' }), 'edits[0].offset', '"far"'],+ ['src/mesh-reshape-edits.js', 'tris_to_quads angle too wide', badEdit({ op: 'tris_to_quads', angle: 500 }), 'edits[0].angle', '500'],+ ['src/mesh-reshape-edits.js', 'symmetrize axis unknown', badEdit({ op: 'symmetrize', axis: 'w' }), 'edits[0].axis', '"w"'],+ ['src/mesh-reshape-edits.js', 'symmetrize keep unknown', badEdit({ op: 'symmetrize', keep: 'both' }), 'edits[0].keep', '"both"'],+ ['src/mesh-reshape-edits.js', 'scale_elements without a scale', badEdit({ op: 'scale_elements' }), 'edits[0].scale', 'undefined'],+ ['src/mesh-reshape-edits.js', 'extrude_edges offset with one number', badEdit({ op: 'extrude_edges', edges: { open: true }, offset: [1] }), 'edits[0].offset', '[1]'],['src/mesh-deform-modifiers.js', 'lattice divisions too high', badEdit({ op: 'lattice', divisions: [9, 2, 2] }), 'edits[0].divisions', '9'],['src/mesh-deform-modifiers.js', 'lattice move without an offset', badEdit({ op: 'lattice', moves: [{ point: [0, 0, 0] }] }), 'edits[0].moves[0].offset', 'undefined'],['src/mesh-deform-modifiers.js', 'lattice move point out of the grid', badEdit({ op: 'lattice', divisions: [2, 2, 2], moves: [{ point: [2, 0, 0], offset: [0, 0, 1] }] }), 'edits[0].moves[0].point', '2'],@@ -138,6 +144,9 @@ const RAW_THROWS_LEFT = {'src/mesh-cut-edits.js': ['`Not a cutting edit: ${edit.op}`);',],+ 'src/mesh-reshape-edits.js': [+ '`Not a reshaping edit: ${edit.op}`);',+ ],'src/mesh-deform-modifiers.js': [],'src/mesh-generator-modifiers.js': ['`${operation} would make ${vertices} ver',diff --git a/tests/mesh-reshape.test.js b/tests/mesh-reshape.test.jsnew file mode 100644index 00000000..772e51a3--- /dev/null+++ b/tests/mesh-reshape.test.js@@ -0,0 +1,184 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, cylinder } from '../src/geometry.js';+import { editMesh, validateTopology, meshFromGeometry, lintMesh, tagCounts, applyMeshEdits } from '../src/mesh.js';+import { normalizeMeshEdits, MESH_EDIT_OPERATIONS } from '../src/mesh-recipe.js';++const cube = () => meshFromGeometry(box(0, 1));++function run(mesh, edits) {+ const outcome = applyMeshEdits(mesh, edits);+ validateTopology(editMesh(outcome.mesh));+ return outcome;+}++function assertClosed(mesh) {+ const report = lintMesh(mesh);+ assert.deepEqual(report.problems, []);+ assert.equal(report.parts.closed, 1);+}++function volume(mesh) {+ let total = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ const corners = [];+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ const vertex = mesh.cornerVertices[corner] * 3;+ corners.push([mesh.positions[vertex], mesh.positions[vertex + 1], mesh.positions[vertex + 2]]);+ }+ for (let index = 1; index + 1 < corners.length; index++) {+ const [a, b, c] = [corners[0], corners[index], corners[index + 1]];+ total += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6;+ }+ }+ return total;+}++function sameBytes(first, second) {+ assert.deepEqual(Buffer.from(first.positions.buffer), Buffer.from(second.positions.buffer));+ assert.deepEqual(first.cornerVertices, second.cornerVertices);+ assert.deepEqual(first.faceOffsets, second.faceOffsets);+}++const openCube = () => run(cube(), [{ op: 'delete', select: { tag: 'top' } }]).mesh;++test('poke turns each selected face into a fan, keeps the surface closed and is deterministic', () => {+ const { mesh, results } = run(cube(), [{ op: 'poke', name: 'spike', offset: 0.25 }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [14, 24]);+ assert.equal(tagCounts(mesh)['spike.poke'], 24);+ assert.equal(tagCounts(mesh).top, 4);+ assert.equal(results[0].pokedFaces, 6);+ assertClosed(mesh);+ assert.ok(volume(mesh) > 1, 'a positive offset pushes the centres outward');+ sameBytes(mesh, run(cube(), [{ op: 'poke', name: 'spike', offset: 0.25 }]).mesh);+});++test('poke only touches the selection and relative scales the offset by the face size', () => {+ const { mesh } = run(cube(), [{ op: 'poke', select: { tag: 'top' }, offset: 1, relative: true }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [9, 9]);+ let highest = -Infinity;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) highest = Math.max(highest, mesh.positions[vertex * 3 + 1]);+ assert.ok(Math.abs(highest - (0.5 + Math.SQRT1_2)) < 1e-6, `apex height ${highest}`);+ assert.throws(() => run(cube(), [{ op: 'poke', select: { faces: [] } }]), /select/);+});++test('dual swaps faces and vertices and keeps the winding', () => {+ const { mesh, results } = run(cube(), [{ op: 'dual', name: 'octa' }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [6, 8]);+ assert.equal(tagCounts(mesh)['octa.dual'], 8);+ assert.deepEqual([results[0].dualVertices, results[0].dualFaces], [6, 8]);+ assertClosed(mesh);+ assert.ok(volume(mesh) > 0, 'faces still point outward');+ const back = run(mesh, [{ op: 'dual' }]).mesh;+ assert.deepEqual([back.vertexCount, back.faceCount], [8, 6]);+ assert.ok(volume(back) > 0);+ sameBytes(mesh, run(cube(), [{ op: 'dual', name: 'octa' }]).mesh);+});++test('dual refuses an open mesh and a reversed face', () => {+ assert.throws(() => run(openCube(), [{ op: 'dual' }]), /open boundary.*fill_holes/s);+ const flipped = run(cube(), [{ op: 'flip_normals', select: { tag: 'top' } }]).mesh;+ assert.throws(() => run(flipped, [{ op: 'dual' }]), /consistent winding/);+});++test('tris_to_quads joins triangulated quads back, keeping tags and a closed surface', () => {+ const triangles = run(cube(), [{ op: 'triangulate' }]).mesh;+ assert.equal(triangles.faceCount, 12);+ const { mesh, results } = run(triangles, [{ op: 'tris_to_quads', name: 'quad' }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);+ assert.equal(results[0].joinedPairs, 6);+ assert.equal(tagCounts(mesh)['quad.merged'], 6);+ for (const tag of ['top', 'bottom', 'left', 'right', 'front', 'back']) assert.equal(tagCounts(mesh)[tag], 1, tag);+ assertClosed(mesh);+ assert.ok(Math.abs(volume(mesh) - 1) < 1e-6);+ sameBytes(mesh, run(triangles, [{ op: 'tris_to_quads', name: 'quad' }]).mesh);+});++test('tris_to_quads respects the selection, the angle limit and refuses a mesh with nothing to join', () => {+ const triangles = run(cube(), [{ op: 'triangulate' }]).mesh;+ const top = run(triangles, [{ op: 'tris_to_quads', select: { tag: 'top' } }]).mesh;+ assert.equal(top.faceCount, 11);+ // Two triangles meeting at 90 degrees never form a flat quad at the default 40 degree limit.+ assert.throws(() => run(run(cube(), [{ op: 'triangulate' }]).mesh, [{ op: 'tris_to_quads', angle: 0, select: { faces: [0] } }]), /No two adjacent selected triangles/);+ assert.throws(() => run(cube(), [{ op: 'tris_to_quads' }]), /No two adjacent selected triangles/);+});++test('scale_elements scales connected faces about their own centre and keeps the topology', () => {+ const source = cube();+ const { mesh, results } = run(source, [{ op: 'scale_elements', select: { tag: 'top' }, scale: 0.5 }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);+ assert.deepEqual([results[0].movedVertices, results[0].islands], [4, 1]);+ assert.deepEqual(mesh.cornerVertices, source.cornerVertices);+ const topHeights = new Set();+ const topWidths = [];+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (mesh.positions[vertex * 3 + 1] > 0) {+ topHeights.add(mesh.positions[vertex * 3 + 1]);+ topWidths.push(Math.abs(mesh.positions[vertex * 3]));+ }+ }+ assert.deepEqual([...topHeights], [0.5]);+ assert.ok(topWidths.every(width => Math.abs(width - 0.25) < 1e-6));+ assertClosed(mesh);+ const two = run(source, [{ op: 'scale_elements', select: { or: [{ tag: 'left' }, { tag: 'right' }] }, scale: 2 }]);+ assert.equal(two.results[0].islands, 2);+});++test('symmetrize mirrors the kept half over the plane, cutting faces that cross it', () => {+ const sliced = run(cube(), [{ op: 'loop_cut', name: 'cut', edges: { along: [1, 0, 0] } }]).mesh;+ const lifted = run(sliced, [{ op: 'translate', select: { inside: { min: [0.01, -9, -9], max: [9, 9, 9] } }, offset: [0, 0.3, 0] }]).mesh;+ const { mesh, results } = run(lifted, [{ op: 'symmetrize', axis: 'x', keep: 'negative', name: 'sym' }]);+ assert.equal(results[0].removedFaces, 5);+ assert.equal(tagCounts(mesh)['sym.mirrored'], 5);+ assert.equal(tagCounts(mesh).left, 1);+ assert.equal(tagCounts(mesh).right, 1);+ assertClosed(mesh);+ const points = new Set();+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ points.add(`${mesh.positions[vertex * 3].toFixed(4)},${mesh.positions[vertex * 3 + 1].toFixed(4)},${mesh.positions[vertex * 3 + 2].toFixed(4)}`);+ }+ for (const key of points) {+ const [x, y, z] = key.split(',');+ assert.ok(points.has(`${(-Number(x)).toFixed(4).replace('-0.0000', '0.0000')},${y},${z}`) || x === '0.0000', `${key} has a mirror twin`);+ }+ sameBytes(mesh, run(lifted, [{ op: 'symmetrize', axis: 'x', keep: 'negative', name: 'sym' }]).mesh);+});++test('symmetrize bisects faces that straddle the plane and refuses a mesh without a kept side', () => {+ const skewed = run(cube(), [{ op: 'translate', select: { tag: 'top' }, offset: [0.2, 0.1, 0] }]).mesh;+ const { mesh } = run(skewed, [{ op: 'symmetrize', axis: 'x' }]);+ assertClosed(mesh);+ assert.ok(Math.abs(volume(mesh) - volume(run(skewed, [{ op: 'symmetrize', axis: 'x' }]).mesh)) < 1e-9);+ const away = run(cube(), [{ op: 'translate', select: { all: true }, offset: [5, 0, 0] }]).mesh;+ assert.throws(() => run(away, [{ op: 'symmetrize', axis: 'x', keep: 'negative' }]), /No face lies on the negative side/);+});++test('extrude_edges grows a surface from its boundary and tags the new quads', () => {+ const { mesh, results } = run(openCube(), [{ op: 'extrude_edges', name: 'lip', edges: { open: true }, offset: [0, 1, 0] }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [12, 9]);+ assert.equal(results[0].extrudedEdges, 4);+ assert.equal(tagCounts(mesh)['lip.side'], 4);+ assert.equal(tagCounts(mesh).front, 1);+ assert.equal(lintMesh(mesh).problems.filter(problem => problem.kind === 'boundary-edge').length > 0, true);+ const upward = run(openCube(), [{ op: 'extrude_edges', edges: { open: true }, offset: [0, 1, 0] }]).mesh;+ const round = meshFromGeometry(cylinder(8, 0, 1));+ assert.throws(() => run(round, [{ op: 'extrude_edges', edges: { open: true }, offset: [0, 1, 0] }]), /selects no edge/);+ sameBytes(mesh, run(openCube(), [{ op: 'extrude_edges', name: 'lip', edges: { open: true }, offset: [0, 1, 0] }]).mesh);+ assert.equal(upward.faceCount, 9);+});++test('the reshaping edits validate their fields', () => {+ assert.throws(() => normalizeMeshEdits([{ op: 'scale_elements', scale: 0 }]), /edits\[0\]\.scale/);+ assert.throws(() => normalizeMeshEdits([{ op: 'poke', relative: 'yes' }]), /edits\[0\]\.relative/);+ assert.throws(() => normalizeMeshEdits([{ op: 'symmetrize', keep: 'left' }]), /positive/);+ assert.throws(() => normalizeMeshEdits([{ op: 'dual', select: { all: true } }]), /dual takes: name/);+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_edges', offset: [0, 1, 0] }]), /edits\[0\]\.edges/);+ for (const name of ['poke', 'dual', 'tris_to_quads', 'symmetrize', 'scale_elements', 'extrude_edges']) {+ assert.ok(MESH_EDIT_OPERATIONS[name], name);+ }+});++test('a poke that would pass the face limit is refused before it allocates', () => {+ const big = meshFromGeometry(cylinder(64, 0, 1));+ assert.throws(() => applyMeshEdits(big, [{ op: 'poke' }], { maxFaces: 100 }), /edits\[0\]\.select.*within 100 faces/s);+});