3D engine that AI agents drive
Add bisect, knife, bridge, fill, grid fill, edge subdivision and dissolve edits
Nguyen Xuan An0778ac67962b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84e136cb..1dbb2fae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Add ten cutting and repair edits: `fill_holes`, `dissolve_faces`, `dissolve_edges`, `dissolve_verts`, `dissolve_limited`, `bisect_plane` (with `fill`, `clearInner`, `clearOuter`), `bridge_edge_loops` (with `segments`), `subdivide_edges`, `grid_fill` and `knife_project`. Each tags what it makes, and the edge rule `{ "open": true }` picks boundary edges. The lint message for an open boundary now suggests `fill_holes`. 18 new cases match Blender in counts, face sizes, area, volume and positions; the knife is compared only with a straight plane cut and differs where a face runs along the projection direction- Add `subdivide` as a mesh edit and stack node: Catmull-Clark subdivision to 4 levels with semi-sharp creases picked by an edge rule, sharp boundaries, kept corners, n-gon support, and tags, UVs and edge attributes carried through each level. The size is checked before it allocates. Counts, area and positions match Blender at levels 1 to 3; the `pebble` task joins the agent modeling suite- Remove `67js/addons/film` from the npm package. It held the 187-second trailer demo with its baked physics recording, 75 KB gzip of the archive. Nothing else in the package used it. To keep using it, copy `src/film.js`, `src/film-rig.js`, `src/film-character.js`, `src/film-physics-definition.js` and `src/film-physics-clip.json` from the repository, or read the trailer on the site at `/film.html`. The archive goes from 901,314 to 829,085 bytes- Remove three.js from modeling and the agent scene: `lathe`, `extrude` and `tube` no longer import it, and `scene:agent-scene` drops from 185,681 to 117,290 bytes gzip. `lathe` and `tube` output is identical to before, vertex for vertex. `extrude` walls, bevels, UVs, normals and bounds are identical, and volume matches within 1e-4. Extrusion caps use a new ear-clipping triangulation, so a cap can split along other diagonals, and a cap with collinear points can add or drop a seam vertex. A clockwise hole under a clockwise contour is now flipped to face outward, where it used to keep inward wallsdiff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex f307371c..aad187fe 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -15,7 +15,7 @@"entry:sculpt": 2500,"entry:surface": 74500,"entry:mesh-query": 87300,- "entry:mesh": 34900,+ "entry:mesh": 43800,"entry:shrinkwrap": 88600,"entry:surface-attachment": 11800,"entry:physics": 16500,@@ -28,11 +28,11 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 95300,- "entry:agent-asset": 102600,+ "entry:agent-scene": 104200,+ "entry:agent-asset": 111600,"entry:hdri": 3300,"scene:lit-box": 49800,"scene:gltf-box": 68900,- "scene:agent-scene": 119700+ "scene:agent-scene": 128300}}diff --git a/docs/mesh.md b/docs/mesh.mdindex 00536462..1128d954 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -248,6 +248,38 @@ each other in one edit are refused; cut them in separate edits. The result reporA typical sequence: `loop_cut` with `cuts: 2`, then `extrude_individual` or `extrude_face_region` with`alongNormals` on `<name>.band-1` to raise a belt around the middle.+### Cutting tools++These edits cut, join, fill and merge faces. Each tags the faces it makes with `<name>.<tag>`, and each result passes+`validateTopology`. Edge rules (the `edges` field) are those of bevel and loop cut, plus `{ "open": true }` for+boundary edges (those with one face) and `{ "open": { "inside": { "min": [x, y, z], "max": [x, y, z] } } }` for the+boundary edges whose midpoint is in a box, which picks one hole among several.++| Edit | Fields | Tags | What it does |+| --- | --- | --- | --- |+| `fill_holes` | `sides` | `fill` | Caps each closed boundary loop with one polygon; `sides` skips loops with more edges. |+| `dissolve_faces` | `select` | `merged` | Merges connected selected faces into one polygon each. |+| `dissolve_edges` | `edges` | `merged` | Merges the two faces beside each selected edge. Boundary edges are ignored. |+| `dissolve_verts` | `verts` | `merged` | Removes vertices: a vertex with two edges just leaves its faces, one with more merges the faces around it. |+| `dissolve_limited` | `edges` (default all), `angle` (default 5) | `merged` | Dissolves edges whose faces bend by at most `angle` degrees, then the straight vertices left behind. |+| `bisect_plane` | `point`, `normal`, `distance`, `clearInner`, `clearOuter`, `fill` | `inner`, `outer`, `cap` | Cuts at a plane. `clearInner` removes the side behind the normal, `clearOuter` the side in front. `fill` caps the cut; with both sides kept the halves separate into two closed shells. |+| `bridge_edge_loops` | `edges`, `segments`, `twistOffset` | `bridge` | Joins exactly two boundary loops with the same edge count by a strip of quads, `segments` deep. |+| `subdivide_edges` | `edges`, `cuts` | `split` | Splits each selected edge into `cuts` + 1 pieces. Quads with two opposite edges split become bands, with four split a grid, and any other face keeps one n-gon with the new points inserted. |+| `grid_fill` | `edges` | `fill` | Fills each closed boundary loop of an even number of edges (4 or more) with a grid of quads. |+| `knife_project` | `path`, `direction` | `cut` | Cuts along a polyline of object-space points projected along `direction`, through front and back faces. |++`dissolve_verts` rules: `{ "all": true }`, `{ "vertices": [indices] }`, `{ "valence": 2 }` (vertices with exactly that many+neighbours) or `{ "inside": { "min", "max" } }`. `dissolve_edges`, `dissolve_verts` and `dissolve_faces` refuse a merge+that would leave a face with a hole or pinch it. `bisect_plane` throws when the plane misses every face, and when a face+is crossed more than twice (a concave face); split it first. `bridge_edge_loops` aligns closed loops at the rotation with+the shortest total distance, then turns them by `twistOffset` vertices. A knife stretch that starts or ends inside a face+makes no cut, and a face that runs along `direction` is not split (its edge points are still inserted). The sizes of+`subdivide_edges` are checked before it allocates.++Open boundaries reported by lint (`boundary-edge`) are fixed with `fill_holes`. Names follow `bmesh.ops`+(`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`.+### 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 7325eb96..504dee74 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -44,7 +44,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 | 16 edits, including extrude, inset, bevel, loop cut, boolean and merge. There is no bisect, knife, bridge, fill or dissolve. | [Blender results](../tests/fixtures/blender/golden.json) | #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 > 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. There is no check for thin walls or intersections. | | #66 |diff --git a/scripts/blender-golden.py b/scripts/blender-golden.pyindex 652ad6ae..28c5f3ba 100644--- a/scripts/blender-golden.py+++ b/scripts/blender-golden.py@@ -11,6 +11,7 @@ from mathutils import VectorFIXTURE_DIRECTORY = Path(__file__).resolve().parent.parent / "tests" / "fixtures" / "blender"DEFAULT_MAX_ANGLE = 10+UNLIMITED_SIDES = 4096ANGLE_EPSILON = 1e-9CREASE_TO_SHARPNESS = 10@@ -50,7 +51,27 @@ def selected_faces(bm, rule):raise ValueError(f"Unsupported face rule: {rule}")+def selected_vertices(bm, rule):+ if "vertices" in rule:+ return [bm.verts[index] for index in rule["vertices"]]+ if "valence" in rule:+ return [vertex for vertex in bm.verts if len(vertex.link_edges) == rule["valence"]]+ if rule.get("all"):+ return list(bm.verts)+ raise ValueError(f"Unsupported vertex rule: {rule}")+++def edge_midpoint_inside(edge, box):+ if box is None:+ return True+ middle = (edge.verts[0].co + edge.verts[1].co) / 2+ return all(box["min"][axis] - 1e-6 <= middle[axis] <= box["max"][axis] + 1e-6 for axis in range(3))++def selected_edges(bm, rule):+ if "open" in rule:+ box = None if rule["open"] is True else rule["open"]["inside"]+ return [edge for edge in bm.edges if len(edge.link_faces) == 1 and edge_midpoint_inside(edge, box)]if rule.get("all"):return [edge for edge in bm.edges if len(edge.link_faces) == 2]if "along" in rule:@@ -166,6 +187,77 @@ def loop_cut(bm, edit):bmesh.ops.subdivide_edges(bm, edges=edges, cuts=cuts, use_grid_fill=True, edge_percents=edge_percents)+def fill_holes(bm, edit):+ boundary = [edge for edge in bm.edges if edge.is_boundary]+ bmesh.ops.holes_fill(bm, edges=boundary, sides=edit.get("sides", UNLIMITED_SIDES))+++def dissolve_faces(bm, edit):+ bmesh.ops.dissolve_faces(bm, faces=selected_faces(bm, edit["select"]), use_verts=False)+++def dissolve_edges(bm, edit):+ bmesh.ops.dissolve_edges(bm, edges=selected_edges(bm, edit["edges"]), use_verts=False, use_face_split=False)+++def dissolve_verts(bm, edit):+ bmesh.ops.dissolve_verts(bm, verts=selected_vertices(bm, edit["verts"]), use_face_split=False, use_boundary_tear=False)+++def dissolve_limited(bm, edit):+ bmesh.ops.dissolve_limit(+ bm,+ angle_limit=radians(edit.get("angle", 5)),+ use_dissolve_boundaries=False,+ verts=list(bm.verts),+ edges=list(bm.edges),+ )+++def bisect_plane(bm, edit):+ geometry = list(bm.verts) + list(bm.edges) + list(bm.faces)+ result = bmesh.ops.bisect_plane(+ bm,+ geom=geometry,+ dist=edit.get("distance", 1e-4),+ plane_co=edit["point"],+ plane_no=edit["normal"],+ clear_inner=edit.get("clearInner", False),+ clear_outer=edit.get("clearOuter", False),+ )+ if edit.get("fill"):+ cut = [element for element in result["geom_cut"] if isinstance(element, bmesh.types.BMEdge) and element.is_boundary]+ bmesh.ops.holes_fill(bm, edges=cut, sides=UNLIMITED_SIDES)+++def bridge_edge_loops(bm, edit):+ result = bmesh.ops.bridge_loops(+ bm,+ edges=selected_edges(bm, edit["edges"]),+ use_pairs=False,+ use_cyclic=False,+ use_merge=False,+ merge_factor=0.5,+ twist_offset=edit.get("twistOffset", 0),+ )+ segments = edit.get("segments", 1)+ if segments > 1:+ bmesh.ops.subdivide_edges(bm, edges=result["edges"], cuts=segments - 1, use_grid_fill=True)+++def subdivide_edges(bm, edit):+ bmesh.ops.subdivide_edges(bm, edges=selected_edges(bm, edit["edges"]), cuts=edit["cuts"], use_grid_fill=True)+++# Blender's knife project needs a viewport, so a straight cut is compared with the plane through the line that holds+# the projection direction. It agrees where the line spans the whole mesh.+def knife_project(bm, edit):+ start = Vector(edit["path"][0])+ end = Vector(edit["path"][1])+ normal = (end - start).cross(Vector(edit["direction"])).normalized()+ bisect_plane(bm, {"point": list(start), "normal": list(normal)})++BMESH_OPERATIONS = {"extrude_face_region": extrude_face_region,"extrude_individual": extrude_individual,@@ -173,6 +265,15 @@ BMESH_OPERATIONS = {"inset_individual": inset_individual,"bevel": bevel,"loop_cut": loop_cut,+ "fill_holes": fill_holes,+ "dissolve_faces": dissolve_faces,+ "dissolve_edges": dissolve_edges,+ "dissolve_verts": dissolve_verts,+ "dissolve_limited": dissolve_limited,+ "bisect_plane": bisect_plane,+ "bridge_edge_loops": bridge_edge_loops,+ "subdivide_edges": subdivide_edges,+ "knife_project": knife_project,}@@ -256,6 +357,28 @@ def run_bmesh_case(case, inputs):return bm+# bmesh.ops.grid_fill returns nothing in background mode, so the Fill > Grid Fill operator runs in edit mode instead.+def run_operator_case(case, inputs):+ mesh_object = new_object("Input", inputs[case["input"]])+ bpy.context.view_layer.objects.active = mesh_object+ mesh_object.select_set(True)+ bpy.ops.object.mode_set(mode="EDIT")+ bpy.ops.mesh.select_all(action="DESELECT")+ edit_bm = bmesh.from_edit_mesh(mesh_object.data)+ refresh(edit_bm)+ loop_edges = selected_edges(edit_bm, case["edit"]["edges"])+ for edge in loop_edges:+ edge.select_set(True)+ edit_bm.select_flush_mode()+ bmesh.update_edit_mesh(mesh_object.data)+ bpy.ops.mesh.fill_grid(span=len(loop_edges) // 4, offset=0, use_interp_simple=False)+ bpy.ops.object.mode_set(mode="OBJECT")+ bm = bmesh.new()+ bm.from_mesh(mesh_object.data)+ refresh(bm)+ return bm++def run_modifier_case(case, inputs):mesh_object = new_object("Input", inputs[case["input"]])MODIFIERS[case["edit"]["op"]](mesh_object, case["edit"], inputs)@@ -314,6 +437,8 @@ def main():remove_all_objects()operation = case["edit"]["op"]runner = run_bmesh_case if operation in BMESH_OPERATIONS else run_modifier_case+ if operation == "grid_fill":+ runner = run_operator_casebm = runner(case, fixture["inputs"])results[case["id"]] = measure(bm)bm.free()diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 8d9126f4..540218c0 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -136,6 +136,7 @@ function primitiveGeometries(identified) {}const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}. Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');const editName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).optional().describe('Prefix for the tags this edit creates. Defaults to <op>-<index>.');+const edgeRule = z.record(z.string(), z.unknown()).describe('Edge rule: {"all":true}, {"angle":30}, {"along":[x,y,z]}, {"between":[faceRule,faceRule]}, {"boundaryOf":faceRule} or {"open":true} for boundary edges (also {"open":{"inside":{"min":[x,y,z],"max":[x,y,z]}}}).');const meshEdit = z.discriminatedUnion('op', [z.strictObject({ op: z.literal('extrude_face_region'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each connected region\'s average normal (negative pushes in).'), direction: vector3.optional().describe('Move along this direction instead of the normal.'), alongNormals: z.boolean().optional().describe('Move each vertex along its own normal instead, keeping the region joined: use for rings and curved bands.') }),z.strictObject({ op: z.literal('extrude_individual'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each face\'s own normal.'), direction: vector3.optional() }),@@ -151,6 +152,28 @@ const meshEdit = z.discriminatedUnion('op', [cuts: z.number().int().min(1).max(16).optional().describe('New loops per ring, evenly spaced. Defaults to 1.'),factor: bounded(0, 1).optional().describe('Single cut only: position from the low side of each ring edge. Defaults to 0.5.'),}).describe('Loop cut across quads. Bands between cuts get <name>.band-0 (low side) to <name>.band-<cuts>.'),+ z.strictObject({ op: z.literal('fill_holes'), name: editName, sides: z.number().int().min(3).max(4096).optional().describe('Skip boundary loops with more edges than this.') }).describe('Cap each closed boundary loop with one polygon, tagged <name>.fill. Fixes the lint boundary-edge warning.'),+ z.strictObject({ op: z.literal('dissolve_faces'), name: editName, select: selectRule }).describe('Merge connected selected faces into one polygon each, tagged <name>.merged.'),+ z.strictObject({ op: z.literal('dissolve_edges'), name: editName, edges: edgeRule }).describe('Merge the two faces beside each selected edge, tagged <name>.merged.'),+ z.strictObject({ op: z.literal('dissolve_verts'), name: editName, verts: z.record(z.string(), z.unknown()).describe('Vertex rule: {"all":true}, {"vertices":[indices]}, {"valence":2} or {"inside":{"min":[x,y,z],"max":[x,y,z]}}.') }).describe('Remove vertices. Two-edge vertices leave their faces; others merge the faces around them.'),+ z.strictObject({ op: z.literal('dissolve_limited'), name: editName, edges: edgeRule.optional().describe('Defaults to all edges.'), angle: bounded(0, 180).optional().describe('Degrees of bend still counted as flat. Defaults to 5.') }).describe('Dissolve flat edges and the straight vertices left behind; undoes a loop cut.'),+ z.strictObject({+ op: z.literal('bisect_plane'), name: editName,+ point: vector3.describe('A point on the plane, in the mesh\'s local space.'), normal: vector3.describe('Plane normal. The inner side is behind it, the outer side in front.'),+ distance: bounded(0, 1000).optional().describe('Vertices this close to the plane count as on it. Defaults to 0.0001.'),+ clearInner: z.boolean().optional(), clearOuter: z.boolean().optional(),+ fill: z.boolean().optional().describe('Cap the cut, tagged <name>.cap. With both sides kept the halves become two closed shells.'),+ }).describe('Cut at a plane. Faces get <name>.inner or <name>.outer by side.'),+ z.strictObject({+ op: z.literal('bridge_edge_loops'), name: editName, edges: edgeRule.describe('Rule that selects exactly two boundary loops with the same edge count, usually {"open":true}.'),+ segments: z.number().int().min(1).max(64).optional().describe('Quads across the strip. Defaults to 1.'), twistOffset: z.number().int().min(-4096).max(4096).optional().describe('Rotate the second loop by this many vertices after the closest match.'),+ }).describe('Join two boundary loops with a strip of quads, tagged <name>.bridge.'),+ z.strictObject({ op: z.literal('subdivide_edges'), name: editName, edges: edgeRule, cuts: z.number().int().min(1).max(16).optional().describe('New points per edge. Defaults to 1.') }).describe('Split edges. Quads with opposite edges split become bands, with all four a grid; others keep an n-gon. New faces get <name>.split.'),+ z.strictObject({ op: z.literal('grid_fill'), name: editName, edges: edgeRule.describe('Rule that selects closed boundary loops of an even edge count, usually {"open":true}.') }).describe('Fill each closed boundary loop with a grid of quads, tagged <name>.fill.'),+ z.strictObject({+ 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('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/skills/build-67js-scene/references/mesh-modeling.md b/skills/build-67js-scene/references/mesh-modeling.mdindex c16dea9a..add1d7d4 100644--- a/skills/build-67js-scene/references/mesh-modeling.md+++ b/skills/build-67js-scene/references/mesh-modeling.md@@ -197,6 +197,35 @@ bounds and rescale the node.] }```+## Cutting and repairing++Use these when a part has a hole, needs an opening or has too many faces. Each names what it makes with `<name>.<tag>`.++```json+{+ "id": "halved-crate", "type": "mesh",+ "base": { "type": "box", "bevel": 0 },+ "edits": [+ { "op": "bisect_plane", "name": "half", "point": [0, 0.1, 0], "normal": [0, 1, 0], "clearOuter": true, "fill": true }+ ]+}+```++Other edits take the same shape, for example:++```text+{ "op": "fill_holes", "name": "lid" }+{ "op": "bridge_edge_loops", "name": "neck", "edges": { "open": true }, "segments": 3 }+{ "op": "dissolve_limited", "angle": 5 }+```++- `bisect_plane` keeps the side the normal points to when `clearInner`, the other when `clearOuter`; `fill` tags the cap `<name>.cap`.+- `fill_holes` caps every closed open boundary (`sides` limits their size); `grid_fill` fills an even loop with quads instead.+- `bridge_edge_loops` needs exactly two boundary loops of equal length. `{ "open": true }` picks all holes; add `"inside": { "min", "max" }` to pick one.+- `dissolve_edges`, `dissolve_faces`, `dissolve_verts` and `dissolve_limited` remove edges and vertices that only split a flat surface. `dissolve_limited` with a small angle undoes a loop cut.+- `subdivide_edges` splits chosen edges; with all four edges of a quad chosen it makes a grid.+- `knife_project` cuts along a polyline projected along `direction`, front and back. Start and end the line outside the mesh.+## Giving a part a surfaceA material `pattern` textures any part with no UVs, after any edits. `size` is metres per repeat, so it stays right on@@ -220,6 +249,9 @@ adding another pattern: a scene holds at most 16 different ones. `uv_unwrap` is| `must be closed for a boolean` | Fix the open or non-manifold edges it counts, or `merge_by_distance` first || `need the optional peer dependency manifold-3d` | Booleans are unavailable here; model the cut another way or ask for the peer || `rings cross` | Cut each direction in its own `loop_cut` edit |+| `selects N boundary loops; bridge needs exactly 2` | Narrow `edges` with `{ "open": { "inside": { "min", "max" } } }` |+| `needs the same number` (bridge) | Run `subdivide_edges` on the shorter loop first |+| lint `boundary-edge` | `fill_holes`, or `solidify` if the part must be closed || bevel `edges` lower than expected | An earlier inset or extrude left untagged rim faces at the edge; bevel earlier, or widen the rule || bevel `clamped: true` | A neighbouring face is narrower than the width; bevel before the narrow inset, or use a smaller width || `over the limit of N vertices` | Fewer segments, fewer array copies, fewer subdivide levels, or split the part |diff --git a/src/mesh-bevel.js b/src/mesh-bevel.jsindex e428e767..3b27559d 100644--- a/src/mesh-bevel.js+++ b/src/mesh-bevel.js@@ -19,6 +19,7 @@ import { MeshBuilder } from './mesh-stack.js';* { "boundaryOf": faceRule } edges between a matching face and a non-matching one* { "along": [x, y, z], "maxAngle": 10 } edges parallel to a direction (either way) within maxAngle degrees* { "all": true } every edge with two faces+ * { "open": true } every boundary edge (one face); { "open": { "inside": { min, max } } } limits it to a box* Returns a Uint8Array over MeshData edges.*/export function selectEdges(mesh, rule, table) {@@ -26,7 +27,8 @@ export function selectEdges(mesh, rule, table) {const keys = Object.keys(rule);const mask = new Uint8Array(mesh.edgeCount);const facesOf = edge => table.faces[edge];- if (keys.length !== 1 && rule.along === undefined) throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, all.');+ if (keys.length !== 1 && rule.along === undefined) throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, open, all.');+ if (rule.open !== undefined) return selectOpenEdges(mesh, rule, table);if (rule.all === true) {for (let edge = 0; edge < mesh.edgeCount; edge++) mask[edge] = facesOf(edge).length === 2 ? 1 : 0;return mask;@@ -85,7 +87,26 @@ export function selectEdges(mesh, rule, table) {}return mask;}- throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, all.');+ throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, open, all.');+}++// { "open": true } picks the boundary edges, those with one face; { "open": { "inside": { min, max } } } keeps the+// ones whose midpoint lies in the box, which picks one hole among several.+function selectOpenEdges(mesh, rule, table) {+ const mask = new Uint8Array(mesh.edgeCount);+ const box = rule.open === true ? null : rule.open?.inside;+ if (!box && rule.open !== true) throw new TypeError('Edge rule open is true or { "inside": { "min": [x, y, z], "max": [x, y, z] } }.');+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (table.faces[edge].length !== 1) continue;+ const first = mesh.edgeVertices[edge * 2] * 3;+ const second = mesh.edgeVertices[edge * 2 + 1] * 3;+ const inside = !box || [0, 1, 2].every(axis => {+ const middle = (mesh.positions[first + axis] + mesh.positions[second + axis]) / 2;+ return middle >= box.min[axis] - 1e-6 && middle <= box.max[axis] + 1e-6;+ });+ mask[edge] = inside ? 1 : 0;+ }+ return mask;}/** Faces of every MeshData edge. */diff --git a/src/mesh-bisect.js b/src/mesh-bisect.jsnew file mode 100644index 00000000..14bac489--- /dev/null+++ b/src/mesh-bisect.js@@ -0,0 +1,233 @@+import { facePolygons, buildPolygonMesh } from './mesh-polygons.js';++// Cutting a mesh with a plane (bisect_plane, after bmesh.ops.bisect_plane) or with a polyline projected along a+// direction (the knife). Both insert one shared point on every cut edge, so no T-junctions appear, and split each+// crossed face along the cut.++const subtract = (first, second) => [first[0] - second[0], first[1] - second[1], first[2] - second[2]];+const dot = (first, second) => first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+const cross = (first, second) => [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];+const lerp = (first, second, fraction) => first.map((value, axis) => value + (second[axis] - value) * fraction);+const unit = vector => {+ const size = Math.hypot(...vector);+ if (size === 0) throw new RangeError('A direction cannot be zero.');+ return vector.map(value => value / size);+};++function positionOf(mesh, extraPositions, vertex) {+ if (vertex >= mesh.vertexCount) return extraPositions[vertex - mesh.vertexCount];+ return [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+}++/** A polygon's outline from `first` to `last` along its vertex loop, inclusive and wrapping around. */+export function loopRange(items, first, last) {+ const range = [];+ for (let index = first; ; index = (index + 1) % items.length) {+ range.push(items[index]);+ if (index === last) return range;+ }+}++/** Split a polygon along a chain between its vertices at `first` and `last`; the chain's own points are `inner`. */+export function splitPolygon(polygon, first, last, inner, innerCorner) {+ const build = (from, to, chain, chainCorners) => ({+ ...polygon,+ vertices: [...loopRange(polygon.vertices, from, to), ...chain],+ sourceCorners: [...loopRange(polygon.sourceCorners, from, to), ...chainCorners],+ sourceEdges: [...loopRange(polygon.sourceEdges, from, to), ...chain.map(() => -1)],+ });+ return [+ build(first, last, [...inner].reverse(), inner.map(() => innerCorner)),+ build(last, first, inner, inner.map(() => innerCorner)),+ ];+}++// ----- bisect_plane -----++function planeSigns(mesh, point, normal, distance) {+ const signs = new Int8Array(mesh.vertexCount);+ const offsets = new Float64Array(mesh.vertexCount);+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const offset = dot(subtract(positionOf(mesh, [], vertex), point), normal);+ offsets[vertex] = offset;+ signs[vertex] = offset > distance ? 1 : offset < -distance ? -1 : 0;+ }+ return { signs, offsets };+}++/** One point per mesh edge whose ends lie on opposite sides of the plane. */+function crossingPoints(mesh, signs, offsets, extraPositions) {+ const points = new Map();+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ if (signs[first] * signs[second] !== -1) continue;+ const fraction = offsets[first] / (offsets[first] - offsets[second]);+ extraPositions.push(lerp(positionOf(mesh, [], first), positionOf(mesh, [], second), fraction));+ points.set(edge, { vertex: mesh.vertexCount + extraPositions.length - 1, from: first, fraction });+ }+ return points;+}++/** The polygon's outline with the crossing points inserted, plus each point's side (0 on the plane). */+function withCrossings(mesh, polygon, signs, points) {+ const outline = { ...polygon, vertices: [], sourceCorners: [], sourceEdges: [] };+ const sides = [];+ const count = polygon.vertices.length;+ for (let index = 0; index < count; index++) {+ const vertex = polygon.vertices[index];+ const corner = polygon.sourceCorners[index];+ const edge = polygon.sourceEdges[index];+ outline.vertices.push(vertex);+ outline.sourceCorners.push(corner);+ outline.sourceEdges.push(edge);+ sides.push(signs[vertex]);+ const crossing = points.get(edge);+ if (!crossing) continue;+ const nextCorner = polygon.sourceCorners[(index + 1) % count];+ const fraction = crossing.from === vertex ? crossing.fraction : 1 - crossing.fraction;+ outline.vertices.push(crossing.vertex);+ outline.sourceCorners.push({ from: corner, to: nextCorner, t: fraction });+ outline.sourceEdges.push(edge);+ sides.push(0);+ }+ return { outline, sides };+}++function sideOf(sides) {+ return sides.find(side => side !== 0) ?? 0;+}++/** Cut one polygon; returns [{ polygon, side }]. */+function bisectPolygon(mesh, polygon, signs, points, index) {+ const { outline, sides } = withCrossings(mesh, polygon, signs, points);+ if (!sides.includes(1) || !sides.includes(-1)) return { pieces: [{ polygon: outline, side: sideOf(sides) }], cut: false };+ const onPlane = sides.map((side, position) => (side === 0 ? position : -1)).filter(position => position >= 0);+ if (onPlane.length !== 2) {+ throw new RangeError(`Face ${index} crosses the plane ${onPlane.length} times. Split it into convex faces first.`);+ }+ const [first, last] = onPlane;+ const forward = loopRange(sides, first, last);+ const pieces = splitPolygon(outline, first, last, [], -1);+ return {+ pieces: [+ { polygon: pieces[0], side: sideOf(forward) },+ { polygon: pieces[1], side: -sideOf(forward) },+ ],+ cut: true,+ };+}++function cutHalfEdges(pieces, onPlane) {+ const halfEdges = [];+ for (const { polygon } of pieces) {+ polygon.vertices.forEach((vertex, position) => {+ const next = polygon.vertices[(position + 1) % polygon.vertices.length];+ if (onPlane(vertex) && onPlane(next)) halfEdges.push({ from: vertex, to: next, polygon, position });+ });+ }+ return halfEdges;+}++/** Cut half-edges of one side that no polygon of that side (or lying in the plane) runs back over. */+function openCutEdges(sidePieces, otherCoplanar, onPlane) {+ const halfEdges = cutHalfEdges(sidePieces, onPlane);+ const keys = new Set(cutHalfEdges([...sidePieces, ...otherCoplanar], onPlane).map(({ from, to }) => `${from}>${to}`));+ return halfEdges.filter(({ from, to }) => !keys.has(`${to}>${from}`));+}++function chainLoops(halfEdges) {+ const outgoing = new Map(halfEdges.map(halfEdge => [halfEdge.from, halfEdge]));+ const used = new Set();+ const loops = [];+ let open = 0;+ for (const start of halfEdges) {+ if (used.has(start)) continue;+ const loop = [];+ let current = start;+ while (current && !used.has(current)) {+ used.add(current);+ loop.push(current);+ current = outgoing.get(current.to);+ }+ if (current === start) loops.push(loop);+ else open++;+ }+ return { loops, open };+}++function capPolygon(loop, tag) {+ const reversed = [...loop].reverse();+ const corner = halfEdge => halfEdge.polygon.sourceCorners[halfEdge.position];+ return {+ vertices: reversed.map(halfEdge => halfEdge.to),+ sourceFace: loop[0].polygon.sourceFace,+ sourceCorners: reversed.map(corner),+ sourceEdges: reversed.map(() => -1),+ keepTags: false,+ tags: [tag],+ };+}++/**+ * Cut the mesh at a plane through `point` with the given `normal`. Points within `distance` of the plane count as on+ * it. `clearInner` removes the side the normal points away from, `clearOuter` the side it points to. `fill` caps the+ * cut with polygons tagged `<name>.cap`; when both sides stay, the halves separate into two closed shells so no edge+ * has four faces. Faces get `<name>.inner` or `<name>.outer` by side.+ */+export function bisectPlane(mesh, { point, normal, distance = 1e-4, clearInner = false, clearOuter = false, fill = false, name = 'bisect' }) {+ const planeNormal = unit(normal);+ const { signs, offsets } = planeSigns(mesh, point, planeNormal, distance);+ const extraPositions = [];+ const points = crossingPoints(mesh, signs, offsets, extraPositions);+ const pieces = [];+ let cutFaces = 0;+ facePolygons(mesh).forEach((polygon, index) => {+ const result = bisectPolygon(mesh, polygon, signs, points, index);+ if (result.cut) cutFaces++;+ pieces.push(...result.pieces);+ });+ if (cutFaces === 0) throw new RangeError('The plane does not cross any face. Check point and normal against the mesh bounds.');+ const onPlane = vertex => vertex >= mesh.vertexCount || signs[vertex] === 0;+ const inner = pieces.filter(piece => piece.side === -1);+ const outer = pieces.filter(piece => piece.side === 1);+ const coplanar = pieces.filter(piece => piece.side === 0);+ for (const { polygon, side } of pieces) {+ if (side === -1) polygon.tags = [...polygon.tags, `${name}.inner`];+ if (side === 1) polygon.tags = [...polygon.tags, `${name}.outer`];+ }+ const kept = pieces.filter(({ side }) => (side === -1 && !clearInner) || (side === 1 && !clearOuter) || side === 0);+ const polygons = kept.map(({ polygon }) => polygon);+ const capsOf = sidePieces => {+ const { loops, open } = chainLoops(openCutEdges(sidePieces, coplanar, onPlane));+ return { caps: loops.map(loop => capPolygon(loop, `${name}.cap`)), open };+ };+ let capped = 0;+ let unfilled = 0;+ if (fill) {+ const innerCaps = clearInner ? { caps: [], open: 0 } : capsOf(inner);+ const outerCaps = clearOuter ? { caps: [], open: 0 } : capsOf(outer);+ if (!clearInner && !clearOuter) {+ separateOuterShell(mesh, [...outer.map(({ polygon }) => polygon), ...outerCaps.caps], onPlane, extraPositions);+ }+ polygons.push(...innerCaps.caps, ...outerCaps.caps);+ capped = innerCaps.caps.length + outerCaps.caps.length;+ unfilled = innerCaps.open + outerCaps.open;+ }+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), cutFaces, capped, unfilled, newVertices: points.size };+}++// With both halves kept and capped, the outer half gets its own copies of the vertices on the plane.+function separateOuterShell(mesh, outerPolygons, onPlane, extraPositions) {+ const copies = new Map();+ const copyOf = vertex => {+ if (!copies.has(vertex)) {+ extraPositions.push(positionOf(mesh, extraPositions, vertex));+ copies.set(vertex, mesh.vertexCount + extraPositions.length - 1);+ }+ return copies.get(vertex);+ };+ for (const polygon of outerPolygons) {+ polygon.vertices = polygon.vertices.map(vertex => (onPlane(vertex) ? copyOf(vertex) : vertex));+ }+}diff --git a/src/mesh-bridge.js b/src/mesh-bridge.jsnew file mode 100644index 00000000..453c31d2--- /dev/null+++ b/src/mesh-bridge.js@@ -0,0 +1,173 @@+import { facePolygons, buildPolygonMesh, boundaryLoops, faceOfCorner } from './mesh-polygons.js';++// bridge_edge_loops and grid_fill. Both work on boundary loops: chains of edges that have one face.++const MAX_GRID_VERTICES = 65536;++function position(mesh, extraPositions, vertex) {+ if (vertex >= mesh.vertexCount) return extraPositions[vertex - mesh.vertexCount];+ return [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+}++const lerp = (first, second, fraction) => first.map((value, axis) => value + (second[axis] - value) * fraction);+const distanceSquared = (first, second) => first.reduce((sum, value, axis) => sum + (value - second[axis]) ** 2, 0);++function newVertex(mesh, extraPositions, point) {+ extraPositions.push(point);+ return mesh.vertexCount + extraPositions.length - 1;+}++function strip(vertices, sourceFace, tag) {+ return { vertices, sourceFace, sourceCorners: vertices.map(() => -1), sourceEdges: vertices.map(() => -1), keepTags: false, tags: [tag] };+}++/** The shift of the second loop against the first that puts matching vertices closest together. */+function bestShift(mesh, first, second) {+ let best = 0;+ let bestCost = Infinity;+ for (let shift = 0; shift < first.length; shift++) {+ let cost = 0;+ for (let index = 0; index < first.length; index++) {+ cost += distanceSquared(position(mesh, [], first[index]), position(mesh, [], second[(index + shift) % second.length]));+ }+ if (cost < bestCost - 1e-12) {+ best = shift;+ bestCost = cost;+ }+ }+ return best;+}++/**+ * Join two boundary loops with a strip of quads, `segments` quads deep. The loops must have the same number of edges.+ * Closed loops are matched at the rotation that puts vertices closest, then turned by `twist` vertices. The strip faces+ * wind opposite to the faces already on each loop, so the result is a closed surface where both loops were holes.+ * Strip faces get `<name>.bridge`.+ */+export function bridgeEdgeLoops(mesh, edgeMask, { segments = 1, twist = 0, name = 'bridge' } = {}) {+ const loops = boundaryLoops(mesh, edgeMask);+ if (loops.length !== 2) {+ throw new RangeError(`The edge rule selects ${loops.length} boundary loops; bridge needs exactly 2. Use { "open": true } for every hole, or { "open": { "inside": { "min": [x, y, z], "max": [x, y, z] } } } to pick some.`);+ }+ const [first, second] = loops;+ if (first.closed !== second.closed) throw new RangeError('One loop is closed and the other is an open chain; bridge needs two of the same kind.');+ if (first.vertices.length !== second.vertices.length) {+ throw new RangeError(`The loops have ${first.vertices.length} and ${second.vertices.length} edges; bridge needs the same number. Run subdivide_edges on the shorter one first.`);+ }+ const edgeCount = first.vertices.length;+ const closed = first.closed;+ if ((edgeCount + 1) * (segments + 1) > MAX_GRID_VERTICES) throw new RangeError('The bridge would make too many vertices. Lower segments.');+ const near = chainPoints(mesh, first);+ const farReversed = chainPoints(mesh, second).reverse();+ const shift = closed ? (bestShift(mesh, near, farReversed) + (twist % edgeCount) + edgeCount) % edgeCount : 0;+ const far = near.map((_, index) => farReversed[(index + shift) % farReversed.length]);+ const extraPositions = [];+ const rows = [near];+ for (let row = 1; row < segments; row++) {+ rows.push(near.map((vertex, index) => newVertex(+ mesh, extraPositions, lerp(position(mesh, extraPositions, vertex), position(mesh, extraPositions, far[index]), row / segments),+ )));+ }+ rows.push(far);+ const polygons = facePolygons(mesh);+ const sourceFace = faceOfCorner(mesh, first.corners[0]);+ for (let row = 0; row < segments; row++) {+ for (let index = 0; index < edgeCount; index++) {+ const next = (index + 1) % near.length;+ polygons.push(strip([rows[row][next], rows[row][index], rows[row + 1][index], rows[row + 1][next]], sourceFace, `${name}.bridge`));+ }+ }+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), loopEdges: edgeCount, strips: segments * edgeCount };+}++function faceNextCorner(mesh, corner) {+ const face = faceOfCorner(mesh, corner);+ return corner + 1 === mesh.faceOffsets[face + 1] ? mesh.faceOffsets[face] : corner + 1;+}++// A closed loop lists each vertex once; an open chain also needs the vertex its last edge ends on.+function chainPoints(mesh, loop) {+ if (loop.closed) return [...loop.vertices];+ const lastCorner = loop.corners[loop.corners.length - 1];+ return [...loop.vertices, mesh.cornerVertices[faceNextCorner(mesh, lastCorner)]];+}++// ----- grid_fill -----++function turnAngle(mesh, previous, vertex, next) {+ const before = position(mesh, [], vertex).map((value, axis) => value - position(mesh, [], previous)[axis]);+ const after = position(mesh, [], next).map((value, axis) => value - position(mesh, [], vertex)[axis]);+ const size = Math.hypot(...before) * Math.hypot(...after) || 1;+ const cosine = before.reduce((sum, value, axis) => sum + value * after[axis], 0) / size;+ return Math.acos(Math.max(-1, Math.min(1, cosine)));+}++/** The split of a loop of even length into sides a, b, a, b that puts the four corners on its sharpest turns. */+function chooseCorners(mesh, vertices) {+ const count = vertices.length;+ let best = null;+ for (let a = 1; a < count / 2; a++) {+ const b = count / 2 - a;+ for (let start = 0; start < count; start++) {+ const corners = [0, a, a + b, 2 * a + b].map(offset => (start + offset) % count);+ const score = corners.reduce((sum, corner) => sum + turnAngle(mesh, vertices[(corner + count - 1) % count], vertices[corner], vertices[(corner + 1) % count]), 0)+ - Math.abs(a - b) * 1e-6;+ if (!best || score > best.score + 1e-9) best = { score, a, b, start };+ }+ }+ return best;+}++function gridPolygons(mesh, loop, name, extraPositions) {+ const vertices = loop.vertices;+ const count = vertices.length;+ const { a, b, start } = chooseCorners(mesh, vertices);+ const at = offset => vertices[(start + offset) % count];+ const grid = Array.from({ length: a + 1 }, () => new Array(b + 1));+ for (let i = 0; i <= a; i++) {+ grid[i][0] = at(i);+ grid[i][b] = at(2 * a + b - i);+ }+ for (let j = 0; j <= b; j++) {+ grid[a][j] = at(a + j);+ grid[0][j] = at(count - j);+ }+ const corner = (i, j) => position(mesh, extraPositions, grid[i][j]);+ for (let i = 1; i < a; i++) {+ for (let j = 1; j < b; j++) {+ const u = i / a;+ const v = j / b;+ const point = [0, 1, 2].map(axis => (1 - v) * corner(i, 0)[axis] + v * corner(i, b)[axis]+ + (1 - u) * corner(0, j)[axis] + u * corner(a, j)[axis]+ - ((1 - u) * (1 - v) * corner(0, 0)[axis] + u * (1 - v) * corner(a, 0)[axis] + (1 - u) * v * corner(0, b)[axis] + u * v * corner(a, b)[axis]));+ grid[i][j] = newVertex(mesh, extraPositions, point);+ }+ }+ const sourceFace = faceOfCorner(mesh, loop.corners[0]);+ const faces = [];+ for (let i = 0; i < a; i++) {+ for (let j = 0; j < b; j++) {+ faces.push(strip([grid[i][j], grid[i][j + 1], grid[i + 1][j + 1], grid[i + 1][j]], sourceFace, `${name}.fill`));+ }+ }+ return faces;+}++/**+ * Fill each closed boundary loop of the selected edges with a grid of quads, which needs an even number of edges+ * (at least 4). The loop is cut into four sides at its sharpest corners, opposite sides holding the same number of+ * edges; inner points come from a Coons patch. Cells get `<name>.fill`.+ */+export function gridFill(mesh, edgeMask, { name = 'grid' } = {}) {+ const loops = boundaryLoops(mesh, edgeMask);+ if (loops.length === 0) throw new RangeError('The edge rule selects no boundary loop. Use { "open": true } to pick the holes.');+ const polygons = facePolygons(mesh);+ const extraPositions = [];+ for (const loop of loops) {+ const count = loop.vertices.length;+ if (!loop.closed) throw new RangeError('A selected boundary chain is open; grid_fill needs closed loops.');+ if (count < 4 || count % 2 !== 0) throw new RangeError(`A loop has ${count} edges; grid_fill needs an even number, at least 4. Subdivide one edge or use fill_holes.`);+ polygons.push(...gridPolygons(mesh, loop, name, extraPositions));+ }+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), loops: loops.length };+}diff --git a/src/mesh-cut-edits.js b/src/mesh-cut-edits.jsnew file mode 100644index 00000000..8f5f4a0e--- /dev/null+++ b/src/mesh-cut-edits.js@@ -0,0 +1,149 @@+import { selectEdges, edgeFaces } from './mesh-bevel.js';+import { selectFaces, countSelected } from './mesh-select.js';+import {+ fillHoles, dissolveFaces, dissolveEdges, dissolveVertices, dissolveLimited, selectVertices,+} from './mesh-dissolve.js';+import { bisectPlane } from './mesh-bisect.js';+import { bridgeEdgeLoops, gridFill } from './mesh-bridge.js';+import { subdivideEdges, edgeSplitSize } from './mesh-edgesplit.js';+import { knifeCut } from './mesh-knife.js';++// The cutting edits as recipe operations: validation of their fields and running them on MeshData. The geometry lives+// in the modules imported above; this file only connects it to the edit log.++export const CUT_OPERATIONS = Object.freeze([+ 'fill_holes', 'dissolve_faces', 'dissolve_edges', 'dissolve_verts', 'dissolve_limited',+ 'bisect_plane', 'bridge_edge_loops', 'subdivide_edges', 'grid_fill', 'knife_project',+]);++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 }';++function ruleObject(value, index, label, hint) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`Mesh edit ${index} (${label} must be ${hint})`);+ return value;+}++function integerInRange(value, index, label, minimum, maximum) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw new TypeError(`Mesh edit ${index} (${label} must be an integer from ${minimum} to ${maximum})`);+ }+ return value;+}++function booleanField(value, index, label) {+ if (value !== undefined && typeof value !== 'boolean') throw new TypeError(`Mesh edit ${index} (${label} must be boolean)`);+ return value ?? false;+}++/** Fill in `normalized` for a cutting edit, throwing a TypeError that names the edit when a field is wrong. */+export function normalizeCutEdit(edit, normalized, index, { finiteNumber, vector }) {+ switch (edit.op) {+ case 'fill_holes':+ if (edit.sides !== undefined) normalized.sides = integerInRange(edit.sides, index, 'sides', 3, 4096);+ break;+ case 'dissolve_faces':+ break;+ case 'dissolve_edges':+ case 'bridge_edge_loops':+ case 'subdivide_edges':+ case 'grid_fill':+ normalized.edges = ruleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);+ break;+ case 'dissolve_verts':+ normalized.verts = ruleObject(edit.verts, index, 'verts', 'a vertex rule: { "all": true }, { "vertices": [indices] }, { "valence": 2 } or { "inside": { "min": [x, y, z], "max": [x, y, z] } }');+ break;+ case 'dissolve_limited':+ normalized.edges = edit.edges === undefined ? { all: true } : ruleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);+ normalized.angle = edit.angle === undefined ? 5 : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });+ break;+ case 'bisect_plane':+ normalized.point = vector(edit.point, index, 'point');+ normalized.normal = vector(edit.normal, index, 'normal');+ if (normalized.normal.every(component => component === 0)) throw new TypeError(`Mesh edit ${index} (normal cannot be zero)`);+ normalized.distance = edit.distance === undefined ? 1e-4 : finiteNumber(edit.distance, index, 'distance', { minimum: 0, maximum: 1e3 });+ normalized.clearInner = booleanField(edit.clearInner, index, 'clearInner');+ normalized.clearOuter = booleanField(edit.clearOuter, index, 'clearOuter');+ normalized.fill = booleanField(edit.fill, index, 'fill');+ if (normalized.clearInner && normalized.clearOuter) throw new TypeError(`Mesh edit ${index} (clearInner and clearOuter together would remove everything)`);+ break;+ case 'bridge_edge_loops':+ break;+ case 'knife_project':+ if (!Array.isArray(edit.path) || edit.path.length < 2 || edit.path.length > MAX_PATH_POINTS) {+ throw new TypeError(`Mesh edit ${index} (path needs 2 to ${MAX_PATH_POINTS} points [x, y, z] in object space)`);+ }+ normalized.path = edit.path.map(point => vector(point, index, 'path point'));+ normalized.direction = vector(edit.direction, index, 'direction');+ if (normalized.direction.every(component => component === 0)) throw new TypeError(`Mesh edit ${index} (direction cannot be zero)`);+ break;+ }+ if (edit.op === 'bridge_edge_loops') {+ normalized.segments = edit.segments === undefined ? 1 : integerInRange(edit.segments, index, 'segments', 1, 64);+ normalized.twistOffset = edit.twistOffset === undefined ? 0 : integerInRange(edit.twistOffset, index, 'twistOffset', -4096, 4096);+ }+ if (edit.op === 'subdivide_edges') normalized.cuts = edit.cuts === undefined ? 1 : integerInRange(edit.cuts, index, 'cuts', 1, 16);+}++/** Refuse a subdivide_edges that would grow past the limits, before it allocates anything. */+export function checkCutBudget(mesh, edit, limits, index) {+ if (edit.op !== 'subdivide_edges') return;+ const mask = selectEdges(mesh, edit.edges, edgeFaces(mesh));+ const size = edgeSplitSize(mesh, mask, edit.cuts);+ if (size.vertices > limits.maxVertices || size.faces > limits.maxFaces) {+ throw new RangeError(`Mesh edit ${index} (subdivide_edges) would make up to ${size.vertices} vertices and ${size.faces} faces, over the limit of ${limits.maxVertices} vertices and ${limits.maxFaces} faces. Lower cuts or select fewer edges.`);+ }+}++function edgeMaskOf(mesh, rule) {+ return selectEdges(mesh, rule, edgeFaces(mesh));+}++/** Run a cutting edit. Returns { mesh, result } where result holds the counts to report. */+export function runCutEdit(mesh, edit) {+ switch (edit.op) {+ case 'fill_holes': {+ const outcome = fillHoles(mesh, { sides: edit.sides ?? Infinity, name: edit.name });+ return { mesh: outcome.mesh, result: { filled: outcome.filled, skipped: outcome.skipped } };+ }+ case 'dissolve_faces': {+ const mask = selectFaces(mesh, edit.select);+ if (countSelected(mask) === 0) throw new RangeError('The rule selects no faces. Check it with mesh_inspect tags and counts.');+ const outcome = dissolveFaces(mesh, mask, { name: edit.name });+ return { mesh: outcome.mesh, result: { merged: outcome.merged } };+ }+ case 'dissolve_edges': {+ const outcome = dissolveEdges(mesh, edgeMaskOf(mesh, edit.edges), { name: edit.name });+ return { mesh: outcome.mesh, result: { merged: outcome.merged, dissolvedEdges: outcome.dissolvedEdges } };+ }+ case 'dissolve_verts': {+ const outcome = dissolveVertices(mesh, selectVertices(mesh, edit.verts), { name: edit.name });+ return { mesh: outcome.mesh, result: { merged: outcome.merged, removedStraight: outcome.removedStraight } };+ }+ case 'dissolve_limited': {+ const outcome = dissolveLimited(mesh, edgeMaskOf(mesh, edit.edges), { angle: edit.angle, name: edit.name });+ return { mesh: outcome.mesh, result: { merged: outcome.merged, removedStraight: outcome.removedStraight } };+ }+ case 'bisect_plane': {+ const outcome = bisectPlane(mesh, edit);+ return { mesh: outcome.mesh, result: { cutFaces: outcome.cutFaces, capped: outcome.capped, unfilled: outcome.unfilled } };+ }+ case 'bridge_edge_loops': {+ const outcome = bridgeEdgeLoops(mesh, edgeMaskOf(mesh, edit.edges), { segments: edit.segments, twist: edit.twistOffset, name: edit.name });+ return { mesh: outcome.mesh, result: { loopEdges: outcome.loopEdges, strips: outcome.strips } };+ }+ case 'subdivide_edges': {+ const outcome = subdivideEdges(mesh, edgeMaskOf(mesh, edit.edges), { cuts: edit.cuts, name: edit.name });+ return { mesh: outcome.mesh, result: { splitEdges: outcome.splitEdges, splitFaces: outcome.splitFaces } };+ }+ case 'grid_fill': {+ const outcome = gridFill(mesh, edgeMaskOf(mesh, edit.edges), { name: edit.name });+ return { mesh: outcome.mesh, result: { loops: outcome.loops } };+ }+ case 'knife_project': {+ const outcome = knifeCut(mesh, edit);+ return { mesh: outcome.mesh, result: { cutFaces: outcome.cutFaces, newVertices: outcome.newVertices } };+ }+ }+ throw new TypeError(`Not a cutting edit: ${edit.op}`);+}diff --git a/src/mesh-dissolve.js b/src/mesh-dissolve.jsnew file mode 100644index 00000000..cb2a9ad2--- /dev/null+++ b/src/mesh-dissolve.js@@ -0,0 +1,251 @@+import { faceNormals } from './mesh-normals.js';+import {+ facePolygons, buildPolygonMesh, boundaryLoops, edgeFaces, vertexNeighbors, faceOfCorner,+} from './mesh-polygons.js';++// fill_holes and the dissolve family, after Blender's bmesh.ops holes_fill, dissolve_faces, dissolve_edges,+// dissolve_verts and dissolve_limit.++/**+ * Cap each closed boundary loop with one polygon wound to match the surface around it. `sides` skips loops with more+ * edges. The cap copies non-tag face data from a face beside the hole and gets the tag `<name>.fill`.+ */+export function fillHoles(mesh, { sides = Infinity, name = 'fill' } = {}) {+ const polygons = facePolygons(mesh);+ let filled = 0;+ let skipped = 0;+ for (const loop of boundaryLoops(mesh)) {+ if (!loop.closed || loop.vertices.length > sides) {+ skipped++;+ continue;+ }+ polygons.push({+ vertices: [...loop.vertices].reverse(),+ sourceFace: faceOfCorner(mesh, loop.corners[0]),+ sourceCorners: [...loop.corners].reverse(),+ sourceEdges: [...loop.corners].reverse().map(corner => mesh.cornerEdges[corner]),+ keepTags: false,+ tags: [`${name}.fill`],+ });+ filled++;+ }+ if (filled === 0) {+ throw new RangeError(skipped === 0+ ? 'The mesh has no open boundary to fill.'+ : `No boundary loop could be filled: ${skipped} skipped because they are open chains or have more than ${sides} sides.`);+ }+ return { mesh: buildPolygonMesh(mesh, polygons), filled, skipped };+}++function findGroup(parents, face) {+ let root = face;+ while (parents[root] !== root) root = parents[root];+ while (parents[face] !== root) {+ const next = parents[face];+ parents[face] = root;+ face = next;+ }+ return root;+}++/**+ * Merge the faces on both sides of every masked edge into polygons: faces joined through masked edges become one+ * polygon whose outline is their combined boundary. Vertices only the old faces used disappear. Throws when a group's+ * outline is not a single loop (the group would need a hole or touch itself).+ */+function mergeAcrossEdges(mesh, edgeMask, name) {+ const table = edgeFaces(mesh);+ const parents = Array.from({ length: mesh.faceCount }, (_, face) => face);+ const dissolved = new Uint8Array(mesh.edgeCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const faces = table.faces[edge];+ if (!edgeMask[edge] || faces.length !== 2) continue;+ dissolved[edge] = 1;+ parents[findGroup(parents, faces[0])] = findGroup(parents, faces[1]);+ }+ const members = new Map();+ for (let face = 0; face < mesh.faceCount; face++) {+ const root = findGroup(parents, face);+ if (!members.has(root)) members.set(root, []);+ members.get(root).push(face);+ }+ const original = facePolygons(mesh);+ const polygons = [];+ let merged = 0;+ for (const faces of members.values()) {+ if (faces.length === 1) {+ polygons.push(original[faces[0]]);+ continue;+ }+ polygons.push(groupOutline(mesh, faces, dissolved, name));+ merged++;+ }+ return { polygons, merged, dissolvedEdges: dissolved.reduce((sum, flag) => sum + flag, 0) };+}++function groupOutline(mesh, faces, dissolved, name) {+ const outgoing = new Map();+ let boundaryCount = 0;+ for (const face of faces) {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ if (dissolved[mesh.cornerEdges[corner]]) continue;+ const vertex = mesh.cornerVertices[corner];+ if (outgoing.has(vertex)) throw new RangeError(`Dissolving would pinch a face at vertex ${vertex}. Dissolve fewer edges.`);+ outgoing.set(vertex, corner);+ boundaryCount++;+ }+ }+ const lowestFace = Math.min(...faces);+ const polygon = { vertices: [], sourceFace: lowestFace, sourceCorners: [], sourceEdges: [], tags: [`${name}.merged`] };+ const start = outgoing.values().next().value;+ let corner = start;+ do {+ polygon.vertices.push(mesh.cornerVertices[corner]);+ polygon.sourceCorners.push(corner);+ polygon.sourceEdges.push(mesh.cornerEdges[corner]);+ const face = faceOfCorner(mesh, corner);+ const nextCorner = corner + 1 === mesh.faceOffsets[face + 1] ? mesh.faceOffsets[face] : corner + 1;+ corner = outgoing.get(mesh.cornerVertices[nextCorner]);+ } while (corner !== undefined && corner !== start);+ if (polygon.vertices.length !== boundaryCount) {+ throw new RangeError('Dissolving would leave a face with a hole or a split outline. Dissolve fewer edges.');+ }+ return polygon;+}++/** Merge connected selected faces into one polygon each. */+export function dissolveFaces(mesh, faceMask, { name = 'dissolve' } = {}) {+ const table = edgeFaces(mesh);+ const edgeMask = new Uint8Array(mesh.edgeCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const faces = table.faces[edge];+ edgeMask[edge] = faces.length === 2 && faceMask[faces[0]] && faceMask[faces[1]] ? 1 : 0;+ }+ const outcome = mergeAcrossEdges(mesh, edgeMask, name);+ if (outcome.merged === 0) throw new RangeError('The selection holds no two faces that share an edge, so nothing dissolves.');+ return { mesh: buildPolygonMesh(mesh, outcome.polygons), merged: outcome.merged };+}++/** Merge the two faces beside each selected edge. Boundary edges cannot dissolve and are ignored. */+export function dissolveEdges(mesh, edgeMask, { name = 'dissolve' } = {}) {+ const outcome = mergeAcrossEdges(mesh, edgeMask, name);+ if (outcome.merged === 0) throw new RangeError('The rule selects no edge with a face on each side, so nothing dissolves.');+ return { mesh: buildPolygonMesh(mesh, outcome.polygons), merged: outcome.merged, dissolvedEdges: outcome.dissolvedEdges };+}++function removeVertices(polygons, removable) {+ for (const polygon of polygons) {+ const keep = polygon.vertices.map(vertex => !removable.has(vertex));+ if (keep.every(Boolean)) continue;+ if (keep.filter(Boolean).length < 3) throw new RangeError('Removing the vertices would collapse a face below three corners.');+ for (const field of ['vertices', 'sourceCorners', 'sourceEdges']) {+ polygon[field] = polygon[field].filter((_, index) => keep[index]);+ }+ }+}++/**+ * Remove vertices. A vertex with two edges leaves its faces, which just lose a corner. A vertex with more edges merges+ * every face around it (the edges between them dissolve); one on the open boundary stays as a corner of that face.+ */+export function dissolveVertices(mesh, vertexMask, { name = 'dissolve' } = {}) {+ const neighbors = vertexNeighbors(facePolygons(mesh));+ const edgeMask = new Uint8Array(mesh.edgeCount);+ const straight = new Set();+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!vertexMask[vertex]) continue;+ if ((neighbors.get(vertex)?.size ?? 0) === 2) straight.add(vertex);+ }+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ if ((vertexMask[first] && !straight.has(first)) || (vertexMask[second] && !straight.has(second))) edgeMask[edge] = 1;+ }+ const outcome = mergeAcrossEdges(mesh, edgeMask, name);+ removeVertices(outcome.polygons, straight);+ const selected = vertexMask.reduce((sum, flag) => sum + flag, 0);+ if (selected === 0) throw new RangeError('The rule selects no vertices.');+ return { mesh: buildPolygonMesh(mesh, outcome.polygons), merged: outcome.merged, removedStraight: straight.size };+}++function edgeDirection(mesh, from, to) {+ const direction = [0, 1, 2].map(axis => mesh.positions[to * 3 + axis] - mesh.positions[from * 3 + axis]);+ const size = Math.hypot(...direction) || 1;+ return direction.map(value => value / size);+}++/**+ * Dissolve what is flat enough: edges whose two faces bend by at most `angle` degrees (among the edges the mask+ * allows), then vertices left with two edges that run straight within the same angle. Faces keep their tags.+ */+export function dissolveLimited(mesh, edgeMask, { angle = 5, name = 'dissolve' } = {}) {+ const table = edgeFaces(mesh);+ const { normals } = faceNormals(mesh);+ const limit = Math.cos(angle * Math.PI / 180) - 1e-9;+ const flat = new Uint8Array(mesh.edgeCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const faces = table.faces[edge];+ if (!edgeMask[edge] || faces.length !== 2) continue;+ const [first, second] = faces;+ const cosine = [0, 1, 2].reduce((sum, axis) => sum + normals[first * 3 + axis] * normals[second * 3 + axis], 0);+ if (cosine >= limit) flat[edge] = 1;+ }+ const outcome = mergeAcrossEdges(mesh, flat, name);+ const neighbors = vertexNeighbors(outcome.polygons);+ const straight = new Set();+ for (const [vertex, around] of neighbors) {+ if (around.size !== 2 || vertex >= mesh.vertexCount) continue;+ const [first, second] = [...around];+ const incoming = edgeDirection(mesh, first, vertex);+ const outgoing = edgeDirection(mesh, vertex, second);+ const cosine = incoming.reduce((sum, value, axis) => sum + value * outgoing[axis], 0);+ if (cosine >= limit) straight.add(vertex);+ }+ removeStraightWherePossible(outcome.polygons, straight);+ if (outcome.merged === 0 && straight.size === 0) throw new RangeError(`Nothing is within ${angle} degrees of flat among the selected edges.`);+ return { mesh: buildPolygonMesh(mesh, outcome.polygons), merged: outcome.merged, removedStraight: straight.size };+}++// A straight vertex stays when removing it would leave a triangle with two corners.+function removeStraightWherePossible(polygons, straight) {+ const blocked = new Set();+ for (const polygon of polygons) {+ const removing = polygon.vertices.filter(vertex => straight.has(vertex)).length;+ if (polygon.vertices.length - removing < 3) polygon.vertices.forEach(vertex => blocked.add(vertex));+ }+ for (const vertex of blocked) straight.delete(vertex);+ removeVertices(polygons, straight);+}++/** Vertex rules: { "all": true }, { "vertices": [indices] }, { "valence": n } or { "inside": { min, max } }. */+export function selectVertices(mesh, rule) {+ if (!rule || typeof rule !== 'object' || Array.isArray(rule) || Object.keys(rule).length !== 1) {+ throw new TypeError('Vertex rule takes exactly one of all, vertices, valence, inside.');+ }+ const mask = new Uint8Array(mesh.vertexCount);+ if (rule.all === true) return mask.fill(1);+ if (Array.isArray(rule.vertices)) {+ for (const vertex of rule.vertices) {+ if (!Number.isInteger(vertex) || vertex < 0 || vertex >= mesh.vertexCount) throw new RangeError(`Vertex ${vertex} does not exist.`);+ mask[vertex] = 1;+ }+ return mask;+ }+ if (Number.isInteger(rule.valence)) {+ const neighbors = vertexNeighbors(facePolygons(mesh));+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ mask[vertex] = (neighbors.get(vertex)?.size ?? 0) === rule.valence ? 1 : 0;+ }+ return mask;+ }+ if (rule.inside && Array.isArray(rule.inside.min) && Array.isArray(rule.inside.max)) {+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ mask[vertex] = [0, 1, 2].every(axis => {+ const value = mesh.positions[vertex * 3 + axis];+ return value >= rule.inside.min[axis] - 1e-6 && value <= rule.inside.max[axis] + 1e-6;+ }) ? 1 : 0;+ }+ return mask;+ }+ throw new TypeError('Vertex rule takes exactly one of all, vertices (indices), valence (integer), inside ({ min, max }).');+}diff --git a/src/mesh-edgesplit.js b/src/mesh-edgesplit.jsnew file mode 100644index 00000000..0057fde8--- /dev/null+++ b/src/mesh-edgesplit.js@@ -0,0 +1,152 @@+import { facePolygons, buildPolygonMesh } from './mesh-polygons.js';++// subdivide_edges, after bmesh.ops.subdivide_edges with grid fill: every selected edge is split into cuts + 1 equal+// pieces, and the faces beside it follow the split edges:+// a quad with two opposite edges split becomes bands (as loop_cut does)+// a quad with all four edges split becomes a grid of (cuts + 1) squared quads+// any other face keeps one n-gon with the new points inserted, so nothing is left cracked++function lerp(first, second, fraction) {+ return first.map((value, axis) => value + (second[axis] - value) * fraction);+}++export function edgeSplitSize(mesh, edgeMask, cuts) {+ let splitEdges = 0;+ for (let edge = 0; edge < mesh.edgeCount; edge++) splitEdges += edgeMask[edge] ? 1 : 0;+ const pieces = cuts + 1;+ return { vertices: mesh.vertexCount + splitEdges * cuts + mesh.faceCount * cuts * cuts, faces: mesh.faceCount * pieces * pieces };+}++export function subdivideEdges(mesh, edgeMask, { cuts = 1, name = 'subdivide' } = {}) {+ const extraPositions = [];+ const base = mesh.vertexCount;+ const vertexPoint = vertex => [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+ const addPoint = point => {+ extraPositions.push(point);+ return base + extraPositions.length - 1;+ };+ const edgePoints = new Map();+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (!edgeMask[edge]) continue;+ const start = vertexPoint(mesh.edgeVertices[edge * 2]);+ const end = vertexPoint(mesh.edgeVertices[edge * 2 + 1]);+ edgePoints.set(edge, Array.from({ length: cuts }, (_, index) => addPoint(lerp(start, end, (index + 1) / (cuts + 1)))));+ }+ const pointPosition = vertex => (vertex >= base ? extraPositions[vertex - base] : vertexPoint(vertex));+ const fractions = Array.from({ length: cuts }, (_, index) => (index + 1) / (cuts + 1));++ // The new points on a polygon's edge after its corner `index`, in the polygon's own direction.+ const pointsAfter = (polygon, index) => {+ const points = edgePoints.get(polygon.sourceEdges[index]);+ if (!points) return [];+ const forward = polygon.vertices[index] === mesh.edgeVertices[polygon.sourceEdges[index] * 2];+ return (forward ? points : [...points].reverse()).map((vertex, step) => ({ vertex, t: fractions[step] }));+ };++ const output = [];+ let splitFaces = 0;+ for (const polygon of facePolygons(mesh)) {+ const size = polygon.vertices.length;+ const splitSides = polygon.vertices.map((_, index) => pointsAfter(polygon, index).length > 0);+ if (!splitSides.some(Boolean)) {+ output.push(polygon);+ continue;+ }+ splitFaces++;+ const pieces = size === 4 ? splitQuad(polygon, splitSides, pointsAfter, pointPosition, addPoint, cuts) : null;+ output.push(...(pieces ?? insertPoints(polygon, pointsAfter)).map(piece => ({ ...piece, tags: [...polygon.tags, `${name}.split`] })));+ }+ return { mesh: buildPolygonMesh(mesh, output, extraPositions), splitEdges: edgePoints.size, splitFaces };+}++function insertPoints(polygon, pointsAfter) {+ const result = { ...polygon, vertices: [], sourceCorners: [], sourceEdges: [] };+ const size = polygon.vertices.length;+ polygon.vertices.forEach((vertex, index) => {+ result.vertices.push(vertex);+ result.sourceCorners.push(polygon.sourceCorners[index]);+ result.sourceEdges.push(polygon.sourceEdges[index]);+ for (const { vertex: point, t } of pointsAfter(polygon, index)) {+ result.vertices.push(point);+ result.sourceCorners.push({ from: polygon.sourceCorners[index], to: polygon.sourceCorners[(index + 1) % size], t });+ result.sourceEdges.push(polygon.sourceEdges[index]);+ }+ });+ return [result];+}++function rotated(polygon, shift) {+ const turn = items => items.map((_, index) => items[(index + shift) % items.length]);+ return { ...polygon, vertices: turn(polygon.vertices), sourceCorners: turn(polygon.sourceCorners), sourceEdges: turn(polygon.sourceEdges) };+}++function splitQuad(polygon, splitSides, pointsAfter, pointPosition, addPoint, cuts) {+ const count = splitSides.filter(Boolean).length;+ const oppositePair = count === 2 && splitSides[0] === splitSides[2];+ if (count !== 4 && !oppositePair) return null;+ // Rotate so a split pair is the first and third sides: a to b, and c to d.+ const quad = count === 4 || splitSides[0] ? polygon : rotated(polygon, 1);+ const [a, b, c, d] = quad.vertices;+ const [cornerA, cornerB, cornerC, cornerD] = quad.sourceCorners;+ const along = side => pointsAfter(quad, side);+ const bottom = [{ vertex: a, source: cornerA }, ...along(0).map(({ vertex, t }) => ({ vertex, source: { from: cornerA, to: cornerB, t } })), { vertex: b, source: cornerB }];+ const top = [{ vertex: d, source: cornerD }, ...along(2).reverse().map(({ vertex, t }) => ({ vertex, source: { from: cornerD, to: cornerC, t: 1 - t } })), { vertex: c, source: cornerC }];+ if (count === 2) return bandFaces(quad, bottom, top);+ return gridFaces(quad, bottom, top, along, pointPosition, addPoint, cuts);+}++function face(quad, vertices, sources) {+ return { ...quad, vertices, sourceCorners: sources, sourceEdges: vertices.map(() => -1) };+}++function bandFaces(quad, bottom, top) {+ const bands = [];+ for (let step = 0; step + 1 < bottom.length; step++) {+ bands.push(face(quad, [bottom[step].vertex, bottom[step + 1].vertex, top[step + 1].vertex, top[step].vertex], [bottom[step].source, bottom[step + 1].source, top[step + 1].source, top[step].source]));+ }+ return bands;+}++function gridFaces(quad, bottom, top, along, pointPosition, addPoint, cuts) {+ const [a, b, c, d] = quad.vertices;+ const [cornerA, cornerB, cornerC, cornerD] = quad.sourceCorners;+ const rows = cuts + 2;+ // Left side runs a to d, right side b to c; sides after corner b and d are walked against their own direction.+ const rightSide = [b, ...along(1).map(({ vertex }) => vertex), c];+ const leftSide = [a, ...along(3).reverse().map(({ vertex }) => vertex), d];+ const grid = Array.from({ length: rows }, () => new Array(rows));+ const sources = Array.from({ length: rows }, () => new Array(rows));+ for (let column = 0; column < rows; column++) {+ grid[column][0] = bottom[column].vertex;+ grid[column][rows - 1] = top[column].vertex;+ }+ for (let row = 0; row < rows; row++) {+ grid[0][row] = leftSide[row];+ grid[rows - 1][row] = rightSide[row];+ }+ const corners = [cornerA, cornerB, cornerC, cornerD];+ for (let column = 0; column < rows; column++) {+ for (let row = 0; row < rows; row++) {+ const s = column / (rows - 1);+ const t = row / (rows - 1);+ const weights = [(1 - s) * (1 - t), s * (1 - t), s * t, (1 - s) * t];+ sources[column][row] = { weights: corners.map((corner, index) => [corner, weights[index]]) };+ }+ }+ const [pa, pb, pc, pd] = [a, b, c, d].map(pointPosition);+ for (let column = 1; column < rows - 1; column++) {+ for (let row = 1; row < rows - 1; row++) {+ const s = column / (rows - 1);+ const t = row / (rows - 1);+ grid[column][row] = addPoint(lerp(lerp(pa, pb, s), lerp(pd, pc, s), t));+ }+ }+ const cells = [];+ for (let column = 0; column + 1 < rows; column++) {+ for (let row = 0; row + 1 < rows; row++) {+ const cell = [[column, row], [column + 1, row], [column + 1, row + 1], [column, row + 1]];+ cells.push(face(quad, cell.map(([x, y]) => grid[x][y]), cell.map(([x, y]) => sources[x][y])));+ }+ }+ return cells;+}diff --git a/src/mesh-knife.js b/src/mesh-knife.jsnew file mode 100644index 00000000..2669a581--- /dev/null+++ b/src/mesh-knife.js@@ -0,0 +1,184 @@+import { facePolygons, buildPolygonMesh } from './mesh-polygons.js';+import { splitPolygon } from './mesh-bisect.js';++// Knife: cut along a polyline in object space, projected onto the mesh along a direction, as if the line were a+// curtain that hangs along that direction. Every face the curtain crosses is split along it, front and back (the+// editor's "cut through"). A stretch of the line that starts or ends inside a face, without reaching its edge, makes no+// cut, because a face cannot hold a dangling edge.++const MAX_PATH_POINTS = 256;+const SNAP = 1e-6;++const dot = (first, second) => first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+const cross = (first, second) => [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];+const lerp = (first, second, fraction) => first.map((value, axis) => value + (second[axis] - value) * fraction);+const cross2 = (first, second) => first[0] * second[1] - first[1] * second[0];++function projectionBasis(direction) {+ const length = Math.hypot(...direction);+ if (length === 0) throw new RangeError('direction cannot be zero.');+ const along = direction.map(value => value / length);+ const weakest = along.map(Math.abs).indexOf(Math.min(...along.map(Math.abs)));+ const helper = [0, 0, 0];+ helper[weakest] = 1;+ const first = cross(along, helper);+ const firstLength = Math.hypot(...first);+ const sideways = first.map(value => value / firstLength);+ return { along, sideways, upwards: cross(along, sideways) };+}++function insidePolygon(point, polygon) {+ let inside = false;+ for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index++) {+ const [ax, ay] = polygon[index];+ const [bx, by] = polygon[previous];+ if ((ay > point[1]) !== (by > point[1]) && point[0] < ((bx - ax) * (point[1] - ay)) / (by - ay) + ax) inside = !inside;+ }+ return inside;+}++/** Where each mesh edge meets the projected line: { t, vertex, s, inserted } sorted by t from the edge's first vertex. */+function edgeCrossings(mesh, flat, vertexPoint, line, extraPositions) {+ const crossings = new Map();+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ const start = flat[first];+ const span = [flat[second][0] - start[0], flat[second][1] - start[1]];+ const found = [];+ for (let index = 0; index + 1 < line.points.length; index++) {+ const origin = line.points[index];+ const step = [line.points[index + 1][0] - origin[0], line.points[index + 1][1] - origin[1]];+ const denominator = cross2(span, step);+ if (Math.abs(denominator) < 1e-12) continue;+ const offset = [origin[0] - start[0], origin[1] - start[1]];+ const t = cross2(offset, step) / denominator;+ const u = cross2(offset, span) / denominator;+ if (t < -SNAP || t > 1 + SNAP || u < -SNAP || u > 1 + SNAP) continue;+ const clamped = Math.min(1, Math.max(0, t));+ const s = line.lengths[index] + Math.min(1, Math.max(0, u)) * (line.lengths[index + 1] - line.lengths[index]);+ if (found.some(other => Math.abs(other.t - clamped) < SNAP)) continue;+ if (clamped < SNAP) found.push({ t: 0, vertex: first, s, inserted: false });+ else if (clamped > 1 - SNAP) found.push({ t: 1, vertex: second, s, inserted: false });+ else {+ extraPositions.push(lerp(vertexPoint(first), vertexPoint(second), clamped));+ found.push({ t: clamped, vertex: mesh.vertexCount + extraPositions.length - 1, s, inserted: true });+ }+ }+ if (found.length) crossings.set(edge, found.sort((left, right) => left.t - right.t));+ }+ return crossings;+}++function outlineWithCrossings(mesh, polygon, crossings) {+ const outline = { ...polygon, vertices: [], sourceCorners: [], sourceEdges: [] };+ const size = polygon.vertices.length;+ const events = [];+ polygon.vertices.forEach((vertex, index) => {+ outline.vertices.push(vertex);+ outline.sourceCorners.push(polygon.sourceCorners[index]);+ outline.sourceEdges.push(polygon.sourceEdges[index]);+ const edge = polygon.sourceEdges[index];+ const found = crossings.get(edge);+ if (!found) return;+ const forward = vertex === mesh.edgeVertices[edge * 2];+ for (const crossing of forward ? found : [...found].reverse()) {+ events.push(crossing);+ if (!crossing.inserted) continue;+ outline.vertices.push(crossing.vertex);+ outline.sourceCorners.push({ from: polygon.sourceCorners[index], to: polygon.sourceCorners[(index + 1) % size], t: forward ? crossing.t : 1 - crossing.t });+ outline.sourceEdges.push(edge);+ }+ });+ return { outline, events };+}++function faceNormal(points) {+ const normal = [0, 0, 0];+ points.forEach((point, index) => {+ const next = points[(index + 1) % points.length];+ normal[0] += (point[1] - next[1]) * (point[2] + next[2]);+ normal[1] += (point[2] - next[2]) * (point[0] + next[0]);+ normal[2] += (point[0] - next[0]) * (point[1] + next[1]);+ });+ return normal;+}++function pointAt(line, s) {+ let index = 0;+ while (index + 2 < line.lengths.length && line.lengths[index + 1] < s) index++;+ const span = line.lengths[index + 1] - line.lengths[index] || 1;+ return lerp(line.points[index], line.points[index + 1], (s - line.lengths[index]) / span);+}++/** Lift a flat point back onto a face's plane along the projection direction. */+function liftOntoFace(flatPoint, basis, centre, normal) {+ const origin = basis.sideways.map((value, axis) => value * flatPoint[0] + basis.upwards[axis] * flatPoint[1]);+ const distance = dot(normal, centre.map((value, axis) => value - origin[axis])) / dot(normal, basis.along);+ return origin.map((value, axis) => value + basis.along[axis] * distance);+}++/**+ * Cut the mesh along `path`, a polyline of at least two object-space points, projected along `direction`. Faces split+ * by the cut get `<name>.cut`. Returns { mesh, cutFaces, newVertices }.+ */+export function knifeCut(mesh, { path, direction, name = 'knife' }) {+ if (!Array.isArray(path) || path.length < 2 || path.length > MAX_PATH_POINTS) throw new RangeError(`path needs 2 to ${MAX_PATH_POINTS} points.`);+ const basis = projectionBasis(direction);+ const vertexPoint = vertex => [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];+ const flatten = point => [dot(point, basis.sideways), dot(point, basis.upwards)];+ const flat = Array.from({ length: mesh.vertexCount }, (_, vertex) => flatten(vertexPoint(vertex)));+ const points = path.map(flatten);+ const lengths = [0];+ for (let index = 1; index < points.length; index++) {+ lengths.push(lengths[index - 1] + Math.hypot(points[index][0] - points[index - 1][0], points[index][1] - points[index - 1][1]));+ }+ const line = { points, lengths };+ const extraPositions = [];+ const crossings = edgeCrossings(mesh, flat, vertexPoint, line, extraPositions);+ const output = [];+ let cutFaces = 0;+ for (const polygon of facePolygons(mesh)) {+ const { outline, events } = outlineWithCrossings(mesh, polygon, crossings);+ const parts = splitFace(mesh, polygon, outline, events, { basis, line, flat, vertexPoint, extraPositions, name });+ if (parts.length > 1) cutFaces++;+ output.push(...parts);+ }+ if (cutFaces === 0) throw new RangeError('The line does not cross any face when projected along the direction. Check path and direction against the mesh bounds.');+ return { mesh: buildPolygonMesh(mesh, output, extraPositions), cutFaces, newVertices: extraPositions.length };+}++function splitFace(mesh, polygon, outline, events, context) {+ const { basis, line, flat, vertexPoint, extraPositions, name } = context;+ const corners3d = polygon.vertices.map(vertexPoint);+ const normal = faceNormal(corners3d);+ if (Math.abs(dot(normal, basis.along)) < 1e-9 * Math.hypot(...normal)) return [outline];+ const ordered = [];+ for (const event of [...events].sort((left, right) => left.s - right.s)) {+ const last = ordered[ordered.length - 1];+ if (last && last.vertex === event.vertex && Math.abs(last.s - event.s) < 1e-6) continue;+ ordered.push(event);+ }+ const flatOutline = polygon.vertices.map(vertex => flat[vertex]);+ const centre = corners3d[0];+ let parts = [outline];+ for (let index = 0; index + 1 < ordered.length; index++) {+ const from = ordered[index];+ const to = ordered[index + 1];+ if (from.vertex === to.vertex) continue;+ if (!insidePolygon(pointAt(line, (from.s + to.s) / 2), flatOutline)) continue;+ const inner = [];+ line.lengths.forEach((length, vertexIndex) => {+ if (length <= from.s + 1e-9 || length >= to.s - 1e-9) return;+ extraPositions.push(liftOntoFace(line.points[vertexIndex], basis, centre, normal));+ inner.push(mesh.vertexCount + extraPositions.length - 1);+ });+ parts = parts.flatMap(part => {+ const first = part.vertices.indexOf(from.vertex);+ const last = part.vertices.indexOf(to.vertex);+ if (first < 0 || last < 0) return [part];+ return splitPolygon(part, first, last, inner, part.sourceCorners[first]).map(piece => ({ ...piece, tags: [...polygon.tags, `${name}.cut`] }));+ });+ }+ return parts;+}diff --git a/src/mesh-lint.js b/src/mesh-lint.jsindex 7740b58c..0873c9e5 100644--- a/src/mesh-lint.js+++ b/src/mesh-lint.js@@ -11,7 +11,7 @@ const PROBLEMS = Object.freeze({'inverted-part': { severity: 'error', fix: 'Run flip_normals on the part; its normals point inward.' },'degenerate-face': { severity: 'error', fix: 'Run merge_by_distance or dissolve the zero-area faces.' },'loose-vertex': { severity: 'warning', fix: 'Delete loose vertices; they do not render and confuse bounds.' },- 'boundary-edge': { severity: 'warning', fix: 'Open surface. Fill the hole or add solidify if the part must be closed.' },+ 'boundary-edge': { severity: 'warning', fix: 'Open surface. Run fill_holes to cap each boundary loop, or add solidify if the part must be closed.' },});function addProblem(problems, kind, element) {diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 2a4bf4b8..35b28f99 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -21,6 +21,16 @@ export const MESH_EDIT_OPERATIONS = Object.freeze({loop_cut: { fields: ['name', 'edges', 'cuts', 'factor'], tags: ['band-<k>'] },uv_unwrap: { fields: ['seams', 'margin', 'maxDistortion'], tags: [] },subdivide: { fields: ['levels', 'crease', 'sharpness'], tags: [] },+ fill_holes: { fields: ['name', 'sides'], tags: ['fill'] },+ dissolve_faces: { fields: ['select', 'name'], tags: ['merged'] },+ dissolve_edges: { fields: ['edges', 'name'], tags: ['merged'] },+ dissolve_verts: { fields: ['verts', 'name'], tags: ['merged'] },+ dissolve_limited: { fields: ['edges', 'angle', 'name'], tags: ['merged'] },+ bisect_plane: { fields: ['name', 'point', 'normal', 'distance', 'clearInner', 'clearOuter', 'fill'], tags: ['inner', 'outer', 'cap'] },+ bridge_edge_loops: { fields: ['edges', 'name', 'segments', 'twistOffset'], tags: ['bridge'] },+ subdivide_edges: { fields: ['edges', 'name', 'cuts'], tags: ['split'] },+ grid_fill: { fields: ['edges', 'name'], tags: ['fill'] },+ knife_project: { fields: ['name', 'path', 'direction'], tags: ['cut'] },});export const STACK_OPERATIONS = Object.freeze(['mirror', 'array', 'solidify', 'bevel', 'uv_unwrap', 'subdivide']);diff --git a/src/mesh-polygons.js b/src/mesh-polygons.jsnew file mode 100644index 00000000..1544088b--- /dev/null+++ b/src/mesh-polygons.js@@ -0,0 +1,130 @@+import { MeshBuilder } from './mesh-stack.js';+import { edgeFaces } from './mesh-bevel.js';++// Shared pieces for the edits that rebuild a mesh from a list of polygons (fill, dissolve, bisect, bridge, knife).+//+// A polygon is { vertices, sourceFace, sourceCorners, sourceEdges, tags }. Vertex numbers below the mesh's vertex count+// are its own vertices; higher numbers index the `extraPositions` array, offset by that count.++/** One polygon per face, each keeping its source face, corners and edges so attributes carry over. */+export function facePolygons(mesh) {+ const polygons = [];+ for (let face = 0; face < mesh.faceCount; face++) {+ const polygon = { vertices: [], sourceFace: face, sourceCorners: [], sourceEdges: [], tags: [] };+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ polygon.vertices.push(mesh.cornerVertices[corner]);+ polygon.sourceCorners.push(corner);+ polygon.sourceEdges.push(mesh.cornerEdges[corner]);+ }+ polygons.push(polygon);+ }+ return polygons;+}++/** Build MeshData from polygons, dropping vertices that no polygon uses. */+export function buildPolygonMesh(mesh, polygons, extraPositions = []) {+ const used = new Set();+ for (const polygon of polygons) {+ for (const vertex of polygon.vertices) used.add(vertex);+ }+ const builder = new MeshBuilder(mesh);+ const remap = new Map();+ for (const vertex of [...used].sort((first, second) => first - second)) {+ const position = vertex < mesh.vertexCount+ ? [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]]+ : extraPositions[vertex - mesh.vertexCount];+ remap.set(vertex, builder.addVertex(...position));+ }+ for (const polygon of polygons) {+ builder.addFace(polygon.vertices.map(vertex => remap.get(vertex)), {+ sourceFace: polygon.sourceFace,+ sourceCorners: polygon.sourceCorners,+ sourceEdges: polygon.sourceEdges,+ keepTags: polygon.keepTags ?? true,+ tags: polygon.tags,+ });+ }+ return builder.build();+}++export function edgeFaceCounts(mesh) {+ const counts = new Uint32Array(mesh.edgeCount);+ for (const edge of mesh.cornerEdges) counts[edge]++;+ return counts;+}++/**+ * Boundary loops: chains of edges that have one face, each followed in the direction its own face runs. `vertices[i]`+ * to `vertices[i + 1]` is the half-edge of `corners[i]`. A chain that does not return to its start is `closed: false`.+ */+export function boundaryLoops(mesh, edgeMask = null) {+ const counts = edgeFaceCounts(mesh);+ const outgoing = new Map();+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const edge = mesh.cornerEdges[corner];+ if (counts[edge] !== 1 || (edgeMask && !edgeMask[edge])) continue;+ const vertex = mesh.cornerVertices[corner];+ if (!outgoing.has(vertex)) outgoing.set(vertex, []);+ outgoing.get(vertex).push(corner);+ }+ }+ const nextCornerOf = corner => {+ const face = faceOfCorner(mesh, corner);+ return corner + 1 === mesh.faceOffsets[face + 1] ? mesh.faceOffsets[face] : corner + 1;+ };+ const taken = new Set();+ const loops = [];+ for (const candidates of outgoing.values()) {+ for (const firstCorner of candidates) {+ if (taken.has(firstCorner)) continue;+ const loop = { vertices: [], corners: [], closed: false };+ let corner = firstCorner;+ while (corner !== undefined && !taken.has(corner)) {+ taken.add(corner);+ loop.vertices.push(mesh.cornerVertices[corner]);+ loop.corners.push(corner);+ const arrival = mesh.cornerVertices[nextCornerOf(corner)];+ if (arrival === loop.vertices[0]) {+ loop.closed = true;+ break;+ }+ corner = (outgoing.get(arrival) ?? []).find(other => !taken.has(other));+ }+ loops.push(loop);+ }+ }+ return loops;+}++export function faceOfCorner(mesh, corner) {+ let low = 0;+ let high = mesh.faceCount - 1;+ while (low < high) {+ const middle = (low + high + 1) >> 1;+ if (mesh.faceOffsets[middle] <= corner) low = middle;+ else high = middle - 1;+ }+ return low;+}++/** Distinct neighbouring vertices of each vertex, across a polygon list. */+export function vertexNeighbors(polygons) {+ const neighbors = new Map();+ const link = (first, second) => {+ if (!neighbors.has(first)) neighbors.set(first, new Set());+ neighbors.get(first).add(second);+ };+ for (const polygon of polygons) {+ polygon.vertices.forEach((vertex, index) => {+ const next = polygon.vertices[(index + 1) % polygon.vertices.length];+ link(vertex, next);+ link(next, vertex);+ });+ }+ return neighbors;+}++export { edgeFaces };diff --git a/src/mesh-recipe.js b/src/mesh-recipe.jsindex 4dbada35..f08aafb9 100644--- a/src/mesh-recipe.js+++ b/src/mesh-recipe.js@@ -9,6 +9,7 @@ import { createMeshData } from './mesh-data.js';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 { unwrapUv } from './mesh-uv.js';import { subdivideMesh, subdivisionSize, MAX_SUBDIVISION_LEVELS, MAX_CREASE_SHARPNESS } from './mesh-subdivide.js';import { MESH_EDIT_OPERATIONS, MAX_MESH_EDITS, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-operations.js';@@ -49,7 +50,7 @@ export function normalizeMeshEdits(edits) {}const normalized = { op: edit.op };if (definition.fields.includes('select')) {- if (edit.select === undefined && ['delete', 'tag'].includes(edit.op)) throw editError(index, `${edit.op} needs select`);+ if (edit.select === undefined && ['delete', 'tag', 'dissolve_faces'].includes(edit.op)) throw editError(index, `${edit.op} needs select`);normalized.select = edit.select ?? { all: true };}if (definition.fields.includes('name')) {@@ -181,6 +182,7 @@ export function normalizeMeshEdits(edits) {normalized.distance = finiteNumber(edit.distance ?? 1e-4, index, 'distance', { minimum: 0, maximum: 1e3 });break;}+ if (CUT_OPERATIONS.includes(edit.op)) normalizeCutEdit(edit, normalized, index, { finiteNumber, vector });return normalized;});}@@ -194,6 +196,7 @@ function checkSubdivideBudget(mesh, edit, limits, index) {}function checkArrayBudget(mesh, edit, limits, index) {+ checkCutBudget(mesh, edit, limits, index);if (edit.op === 'subdivide') {checkSubdivideBudget(mesh, edit, limits, index);return;@@ -289,6 +292,18 @@ function runEdit(current, edit, index, { resolveCutter }) {result.tags = tagSummary(outcome.mesh, edit.name);return { mesh: outcome.mesh, result };}+ if (CUT_OPERATIONS.includes(edit.op)) {+ let outcome;+ try {+ outcome = runCutEdit(current, edit);+ } catch (error) {+ throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);+ }+ Object.assign(result, outcome.result);+ const tags = tagSummary(outcome.mesh, edit.name);+ if (Object.keys(tags).length) result.tags = tags;+ return { mesh: outcome.mesh, result };+ }if (edit.op === 'subdivide') {let subdivided;try {diff --git a/src/mesh-stack.js b/src/mesh-stack.jsindex e4fac2b5..3d0490ea 100644--- a/src/mesh-stack.js+++ b/src/mesh-stack.js@@ -113,6 +113,20 @@ export class MeshBuilder {}}+/** A corner made from several source corners, each with a weight; integer attributes copy the heaviest one. */+function blendWeighted(data, attribute, corner, weights, blends) {+ const heaviest = weights.reduce((best, entry) => (entry[1] > best[1] ? entry : best));+ for (let component = 0; component < attribute.size; component++) {+ if (!blends) {+ data[corner * attribute.size + component] = attribute.data[heaviest[0] * attribute.size + component];+ continue;+ }+ let sum = 0;+ for (const [source, weight] of weights) sum += attribute.data[source * attribute.size + component] * weight;+ data[corner * attribute.size + component] = sum;+ }+}+function faceCorners(mesh, face) {const corners = [];for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) corners.push(corner);diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.jsonindex 1bce1bf3..e36abc68 100644--- a/tests/fixtures/blender/cases.json+++ b/tests/fixtures/blender/cases.json@@ -23,7 +23,12 @@"cylinder": {"vertices": [[1,0,-1],[0.70710678,0.70710678,-1],[0,1,-1],[-0.70710678,0.70710678,-1],[-1,0,-1],[-0.70710678,-0.70710678,-1],[0,-1,-1],[0.70710678,-0.70710678,-1],[1,0,1],[0.70710678,0.70710678,1],[0,1,1],[-0.70710678,0.70710678,1],[-1,0,1],[-0.70710678,-0.70710678,1],[0,-1,1],[0.70710678,-0.70710678,1]],"faces": [[0,1,9,8],[1,2,10,9],[2,3,11,10],[3,4,12,11],[4,5,13,12],[5,6,14,13],[6,7,15,14],[7,0,8,15],[8,9,10,11,12,13,14,15],[7,6,5,4,3,2,1,0]]- }+ },+ "cube-pair-open": {"vertices":[[-0.5,-0.5,-1.5],[0.5,-0.5,-1.5],[0.5,0.5,-1.5],[-0.5,0.5,-1.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.5],[-0.5,-0.5,1.5],[0.5,-0.5,1.5],[0.5,0.5,1.5],[-0.5,0.5,1.5]],"faces":[[0,3,2,1],[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7],[12,13,14,15],[8,9,13,12],[9,10,14,13],[10,11,15,14],[11,8,12,15]]},+ "cube-cut": {"vertices":[[-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.5,-0.5,0],[0.5,-0.5,0],[0.5,0.5,0],[-0.5,0.5,0]],"faces":[[0,3,2,1],[4,5,6,7],[0,1,9,8],[8,9,5,4],[1,2,10,9],[9,10,6,5],[2,3,11,10],[10,11,7,6],[3,0,8,11],[11,8,4,7]]},+ "grid-hole": {"vertices":[[0,0,0],[1,0,0],[2,0,0],[3,0,0],[4,0,0],[0,1,0],[1,1,0],[2,1,0],[3,1,0],[4,1,0],[0,2,0],[1,2,0],[3,2,0],[4,2,0],[0,3,0],[1,3,0],[2,3,0],[3,3,0],[4,3,0],[0,4,0],[1,4,0],[2,4,0],[3,4,0],[4,4,0]],"faces":[[0,1,6,5],[1,2,7,6],[2,3,8,7],[3,4,9,8],[5,6,11,10],[8,9,13,12],[10,11,15,14],[12,13,18,17],[14,15,20,19],[15,16,21,20],[16,17,22,21],[17,18,23,22]]},+ "square-midpoint": {"vertices":[[0,0,0],[2,0,0],[2,2,0],[0,2,0],[1,0,0]],"faces":[[0,4,1,2,3]]},+ "cylinder-open": {"vertices":[[1,0,-1],[0.70710678,0.70710678,-1],[0,1,-1],[-0.70710678,0.70710678,-1],[-1,0,-1],[-0.70710678,-0.70710678,-1],[0,-1,-1],[0.70710678,-0.70710678,-1],[1,0,1],[0.70710678,0.70710678,1],[0,1,1],[-0.70710678,0.70710678,1],[-1,0,1],[-0.70710678,-0.70710678,1],[0,-1,1],[0.70710678,-0.70710678,1]],"faces":[[0,1,9,8],[1,2,10,9],[2,3,11,10],[3,4,12,11],[4,5,13,12],[5,6,14,13],[6,7,15,14],[7,0,8,15],[7,6,5,4,3,2,1,0]]}},"cases": [{ "id": "extrude-region-cube-top", "input": "cube", "edit": { "op": "extrude_face_region", "select": { "normal": [0,0,1] }, "offset": 0.5 } },@@ -74,6 +79,25 @@{"id":"subdivide-cylinder-crease-rims","input":"cylinder","edit":{"op":"subdivide","levels":2,"crease":{"angle":60},"sharpness":10}},{"id":"subdivide-cube-crease-two-levels","input":"cube","edit":{"op":"subdivide","levels":3,"crease":{"all":true},"sharpness":2}},{"id":"subdivide-cube-crease-half","input":"cube","edit":{"op":"subdivide","levels":2,"crease":{"all":true},"sharpness":0.5}},- {"id":"subdivide-grid-crease-middle","input":"grid","edit":{"op":"subdivide","levels":2,"crease":{"along":[1,0,0]},"sharpness":10}}+ {"id":"subdivide-grid-crease-middle","input":"grid","edit":{"op":"subdivide","levels":2,"crease":{"along":[1,0,0]},"sharpness":10}},+ { "id": "fill-holes-cube-open", "input": "cube-open", "edit": {"op":"fill_holes"} },+ { "id": "fill-holes-cylinder-open", "input": "cylinder-open", "edit": {"op":"fill_holes"} },+ { "id": "dissolve-faces-grid-block", "input": "grid", "edit": {"op":"dissolve_faces","select":{"faces":[0,1,3,4]}} },+ { "id": "dissolve-edges-grid-pair", "input": "grid", "edit": {"op":"dissolve_edges","edges":{"between":[{"faces":[0]},{"faces":[1]}]}} },+ { "id": "dissolve-verts-grid-centre", "input": "grid", "edit": {"op":"dissolve_verts","verts":{"vertices":[5]}} },+ { "id": "dissolve-verts-square-midpoint", "input": "square-midpoint", "edit": {"op":"dissolve_verts","verts":{"vertices":[4]}} },+ { "id": "dissolve-limited-cube-cut", "input": "cube-cut", "edit": {"op":"dissolve_limited","angle":5} },+ { "id": "bisect-cube-clear-outer-fill", "input": "cube", "edit": {"op":"bisect_plane","point":[0,0.1,0],"normal":[0,1,0],"clearOuter":true,"fill":true} },+ { "id": "bisect-cube-both-sides", "input": "cube", "edit": {"op":"bisect_plane","point":[0,0.1,0],"normal":[0,1,0]} },+ { "id": "bisect-cube-diagonal-clear-inner", "input": "cube", "edit": {"op":"bisect_plane","point":[0,0,0],"normal":[1,1,0],"clearInner":true,"fill":true} },+ { "id": "bisect-cylinder-clear-inner-fill", "input": "cylinder", "edit": {"op":"bisect_plane","point":[0,0,0.25],"normal":[0,0,1],"clearInner":true,"fill":true} },+ { "id": "bridge-cube-pair", "input": "cube-pair-open", "edit": {"op":"bridge_edge_loops","edges":{"open":true}} },+ { "id": "bridge-cube-pair-segments", "input": "cube-pair-open", "edit": {"op":"bridge_edge_loops","edges":{"open":true},"segments":3} },+ { "id": "subdivide-edges-cube-all", "input": "cube", "edit": {"op":"subdivide_edges","edges":{"all":true},"cuts":1} },+ { "id": "subdivide-edges-cube-all-two-cuts", "input": "cube", "edit": {"op":"subdivide_edges","edges":{"all":true},"cuts":2} },+ { "id": "subdivide-edges-grid-along", "input": "grid", "edit": {"op":"subdivide_edges","edges":{"along":[1,0,0]},"cuts":2} },+ { "id": "grid-fill-grid-hole", "input": "grid-hole", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[0.9,0.9,-1],"max":[3.1,3.1,1]}}}} },+ { "id": "grid-fill-cylinder-open", "input": "cylinder-open", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[-2,-2,0.9],"max":[2,2,1.1]}}}} },+ { "id": "knife-project-cube-line", "input": "cube", "edit": {"op":"knife_project","path":[[-1,0,0],[1,0,0]],"direction":[0,0,-1]} }]}diff --git a/tests/fixtures/blender/differences.json b/tests/fixtures/blender/differences.jsonindex f70e9af1..7c790193 100644--- a/tests/fixtures/blender/differences.json+++ b/tests/fixtures/blender/differences.json@@ -41,5 +41,10 @@},"subdivide-cube-crease-half": {"volume": "The refined quads are bent, and the measure splits each quad from its first corner, so the volume depends on which corner a quad starts at. Counts, area and every vertex match Blender; the volume differs from Blender by under 1%."+ },+ "knife-project-cube-line": {+ "edgeCount": "Blender's check here is a plane through the line that holds the projection direction, which also cuts the two faces that run along that direction. 67.js cuts only faces the projection can see side-on to the line, so those two faces keep their edges and gain the cut points as corners.",+ "faceCount": "The two faces that run along the projection direction are not split by the knife, so 67.js has two faces fewer than the plane cut.",+ "faceSizes": "Those two faces stay whole with the cut points inserted, so they become hexagons where Blender has four quads."}}diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.jsonindex da917074..6bc6db1b 100644--- a/tests/fixtures/blender/golden.json+++ b/tests/fixtures/blender/golden.json@@ -20949,6 +20949,1941 @@0.0]]+ },+ "fill-holes-cube-open": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 1.0,+ "area": 6.0,+ "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+ ]+ ]+ },+ "fill-holes-cylinder-open": {+ "vertexCount": 16,+ "edgeCount": 24,+ "faceCount": 10,+ "faceSizes": {+ "4": 8,+ "8": 2+ },+ "volume": 5.656854,+ "area": 17.902724,+ "positions": [+ [+ -1.0,+ 0.0,+ -1.0+ ],+ [+ -1.0,+ 0.0,+ 1.0+ ],+ [+ -0.70711,+ -0.70711,+ -1.0+ ],+ [+ -0.70711,+ -0.70711,+ 1.0+ ],+ [+ -0.70711,+ 0.70711,+ -1.0+ ],+ [+ -0.70711,+ 0.70711,+ 1.0+ ],+ [+ 0.0,+ -1.0,+ -1.0+ ],+ [+ 0.0,+ -1.0,+ 1.0+ ],+ [+ 0.0,+ 1.0,+ -1.0+ ],+ [+ 0.0,+ 1.0,+ 1.0+ ],+ [+ 0.70711,+ -0.70711,+ -1.0+ ],+ [+ 0.70711,+ -0.70711,+ 1.0+ ],+ [+ 0.70711,+ 0.70711,+ -1.0+ ],+ [+ 0.70711,+ 0.70711,+ 1.0+ ],+ [+ 1.0,+ 0.0,+ -1.0+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ]+ ]+ },+ "dissolve-faces-grid-block": {+ "vertexCount": 15,+ "edgeCount": 20,+ "faceCount": 6,+ "faceSizes": {+ "4": 5,+ "8": 1+ },+ "volume": 0.0,+ "area": 9.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 1.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 0.0,+ 3.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.0,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 1.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 3.0,+ 0.0+ ],+ [+ 3.0,+ 0.0,+ 0.0+ ],+ [+ 3.0,+ 1.0,+ 0.0+ ],+ [+ 3.0,+ 2.0,+ 0.0+ ],+ [+ 3.0,+ 3.0,+ 0.0+ ]+ ]+ },+ "dissolve-edges-grid-pair": {+ "vertexCount": 16,+ "edgeCount": 23,+ "faceCount": 8,+ "faceSizes": {+ "4": 7,+ "6": 1+ },+ "volume": 0.0,+ "area": 9.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 1.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 0.0,+ 3.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 1.0,+ 0.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.0,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 1.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 3.0,+ 0.0+ ],+ [+ 3.0,+ 0.0,+ 0.0+ ],+ [+ 3.0,+ 1.0,+ 0.0+ ],+ [+ 3.0,+ 2.0,+ 0.0+ ],+ [+ 3.0,+ 3.0,+ 0.0+ ]+ ]+ },+ "dissolve-verts-grid-centre": {+ "vertexCount": 15,+ "edgeCount": 20,+ "faceCount": 6,+ "faceSizes": {+ "4": 5,+ "8": 1+ },+ "volume": 0.0,+ "area": 9.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 1.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 0.0,+ 3.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.0,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 1.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 3.0,+ 0.0+ ],+ [+ 3.0,+ 0.0,+ 0.0+ ],+ [+ 3.0,+ 1.0,+ 0.0+ ],+ [+ 3.0,+ 2.0,+ 0.0+ ],+ [+ 3.0,+ 3.0,+ 0.0+ ]+ ]+ },+ "dissolve-verts-square-midpoint": {+ "vertexCount": 4,+ "edgeCount": 4,+ "faceCount": 1,+ "faceSizes": {+ "4": 1+ },+ "volume": 0.0,+ "area": 4.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ]+ ]+ },+ "dissolve-limited-cube-cut": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 1.0,+ "area": 6.0,+ "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+ ]+ ]+ },+ "bisect-cube-clear-outer-fill": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 0.6,+ "area": 4.4,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.1,+ -0.5+ ],+ [+ -0.5,+ 0.1,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.1,+ -0.5+ ],+ [+ 0.5,+ 0.1,+ 0.5+ ]+ ]+ },+ "bisect-cube-both-sides": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 10,+ "faceSizes": {+ "4": 10+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.1,+ -0.5+ ],+ [+ -0.5,+ 0.1,+ 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.1,+ -0.5+ ],+ [+ 0.5,+ 0.1,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "bisect-cube-diagonal-clear-inner": {+ "vertexCount": 6,+ "edgeCount": 9,+ "faceCount": 5,+ "faceSizes": {+ "3": 2,+ "4": 3+ },+ "volume": 0.5,+ "area": 4.414214,+ "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+ ]+ ]+ },+ "bisect-cylinder-clear-inner-fill": {+ "vertexCount": 16,+ "edgeCount": 24,+ "faceCount": 10,+ "faceSizes": {+ "4": 8,+ "8": 2+ },+ "volume": 2.12132,+ "area": 10.249055,+ "positions": [+ [+ -1.0,+ 0.0,+ 0.25+ ],+ [+ -1.0,+ 0.0,+ 1.0+ ],+ [+ -0.70711,+ -0.70711,+ 0.25+ ],+ [+ -0.70711,+ -0.70711,+ 1.0+ ],+ [+ -0.70711,+ 0.70711,+ 0.25+ ],+ [+ -0.70711,+ 0.70711,+ 1.0+ ],+ [+ 0.0,+ -1.0,+ 0.25+ ],+ [+ 0.0,+ -1.0,+ 1.0+ ],+ [+ 0.0,+ 1.0,+ 0.25+ ],+ [+ 0.0,+ 1.0,+ 1.0+ ],+ [+ 0.70711,+ -0.70711,+ 0.25+ ],+ [+ 0.70711,+ -0.70711,+ 1.0+ ],+ [+ 0.70711,+ 0.70711,+ 0.25+ ],+ [+ 0.70711,+ 0.70711,+ 1.0+ ],+ [+ 1.0,+ 0.0,+ 0.25+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ]+ ]+ },+ "bridge-cube-pair": {+ "vertexCount": 16,+ "edgeCount": 28,+ "faceCount": 14,+ "faceSizes": {+ "4": 14+ },+ "volume": 3.0,+ "area": 14.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -1.5+ ],+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ -0.5,+ 1.5+ ],+ [+ -0.5,+ 0.5,+ -1.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ 1.5+ ],+ [+ 0.5,+ -0.5,+ -1.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ 1.5+ ],+ [+ 0.5,+ 0.5,+ -1.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ 1.5+ ]+ ]+ },+ "bridge-cube-pair-segments": {+ "vertexCount": 24,+ "edgeCount": 44,+ "faceCount": 22,+ "faceSizes": {+ "4": 22+ },+ "volume": 3.0,+ "area": 14.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -1.5+ ],+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ -0.16667+ ],+ [+ -0.5,+ -0.5,+ 0.16667+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ -0.5,+ 1.5+ ],+ [+ -0.5,+ 0.5,+ -1.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ -0.16667+ ],+ [+ -0.5,+ 0.5,+ 0.16667+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ 1.5+ ],+ [+ 0.5,+ -0.5,+ -1.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ -0.16667+ ],+ [+ 0.5,+ -0.5,+ 0.16667+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ 1.5+ ],+ [+ 0.5,+ 0.5,+ -1.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ -0.16667+ ],+ [+ 0.5,+ 0.5,+ 0.16667+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ 1.5+ ]+ ]+ },+ "subdivide-edges-cube-all": {+ "vertexCount": 26,+ "edgeCount": 48,+ "faceCount": 24,+ "faceSizes": {+ "4": 24+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.0+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.0,+ -0.5+ ],+ [+ -0.5,+ 0.0,+ 0.0+ ],+ [+ -0.5,+ 0.0,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.0+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.0,+ -0.5,+ -0.5+ ],+ [+ 0.0,+ -0.5,+ 0.0+ ],+ [+ 0.0,+ -0.5,+ 0.5+ ],+ [+ 0.0,+ 0.0,+ -0.5+ ],+ [+ 0.0,+ 0.0,+ 0.5+ ],+ [+ 0.0,+ 0.5,+ -0.5+ ],+ [+ 0.0,+ 0.5,+ 0.0+ ],+ [+ 0.0,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.0+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.0,+ -0.5+ ],+ [+ 0.5,+ 0.0,+ 0.0+ ],+ [+ 0.5,+ 0.0,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.0+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "subdivide-edges-cube-all-two-cuts": {+ "vertexCount": 56,+ "edgeCount": 108,+ "faceCount": 54,+ "faceSizes": {+ "4": 54+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ -0.16667+ ],+ [+ -0.5,+ -0.5,+ 0.16667+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ -0.16667,+ -0.5+ ],+ [+ -0.5,+ -0.16667,+ -0.16667+ ],+ [+ -0.5,+ -0.16667,+ 0.16667+ ],+ [+ -0.5,+ -0.16667,+ 0.5+ ],+ [+ -0.5,+ 0.16667,+ -0.5+ ],+ [+ -0.5,+ 0.16667,+ -0.16667+ ],+ [+ -0.5,+ 0.16667,+ 0.16667+ ],+ [+ -0.5,+ 0.16667,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ -0.16667+ ],+ [+ -0.5,+ 0.5,+ 0.16667+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ -0.16667,+ -0.5,+ -0.5+ ],+ [+ -0.16667,+ -0.5,+ -0.16667+ ],+ [+ -0.16667,+ -0.5,+ 0.16667+ ],+ [+ -0.16667,+ -0.5,+ 0.5+ ],+ [+ -0.16667,+ -0.16667,+ -0.5+ ],+ [+ -0.16667,+ -0.16667,+ 0.5+ ],+ [+ -0.16667,+ 0.16667,+ -0.5+ ],+ [+ -0.16667,+ 0.16667,+ 0.5+ ],+ [+ -0.16667,+ 0.5,+ -0.5+ ],+ [+ -0.16667,+ 0.5,+ -0.16667+ ],+ [+ -0.16667,+ 0.5,+ 0.16667+ ],+ [+ -0.16667,+ 0.5,+ 0.5+ ],+ [+ 0.16667,+ -0.5,+ -0.5+ ],+ [+ 0.16667,+ -0.5,+ -0.16667+ ],+ [+ 0.16667,+ -0.5,+ 0.16667+ ],+ [+ 0.16667,+ -0.5,+ 0.5+ ],+ [+ 0.16667,+ -0.16667,+ -0.5+ ],+ [+ 0.16667,+ -0.16667,+ 0.5+ ],+ [+ 0.16667,+ 0.16667,+ -0.5+ ],+ [+ 0.16667,+ 0.16667,+ 0.5+ ],+ [+ 0.16667,+ 0.5,+ -0.5+ ],+ [+ 0.16667,+ 0.5,+ -0.16667+ ],+ [+ 0.16667,+ 0.5,+ 0.16667+ ],+ [+ 0.16667,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ -0.16667+ ],+ [+ 0.5,+ -0.5,+ 0.16667+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ -0.16667,+ -0.5+ ],+ [+ 0.5,+ -0.16667,+ -0.16667+ ],+ [+ 0.5,+ -0.16667,+ 0.16667+ ],+ [+ 0.5,+ -0.16667,+ 0.5+ ],+ [+ 0.5,+ 0.16667,+ -0.5+ ],+ [+ 0.5,+ 0.16667,+ -0.16667+ ],+ [+ 0.5,+ 0.16667,+ 0.16667+ ],+ [+ 0.5,+ 0.16667,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ -0.16667+ ],+ [+ 0.5,+ 0.5,+ 0.16667+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "subdivide-edges-grid-along": {+ "vertexCount": 40,+ "edgeCount": 66,+ "faceCount": 27,+ "faceSizes": {+ "4": 27+ },+ "volume": 0.0,+ "area": 9.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 1.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 0.0,+ 3.0,+ 0.0+ ],+ [+ 0.33333,+ 0.0,+ 0.0+ ],+ [+ 0.33333,+ 1.0,+ 0.0+ ],+ [+ 0.33333,+ 2.0,+ 0.0+ ],+ [+ 0.33333,+ 3.0,+ 0.0+ ],+ [+ 0.66667,+ 0.0,+ 0.0+ ],+ [+ 0.66667,+ 1.0,+ 0.0+ ],+ [+ 0.66667,+ 2.0,+ 0.0+ ],+ [+ 0.66667,+ 3.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 1.0,+ 0.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.0,+ 3.0,+ 0.0+ ],+ [+ 1.33333,+ 0.0,+ 0.0+ ],+ [+ 1.33333,+ 1.0,+ 0.0+ ],+ [+ 1.33333,+ 2.0,+ 0.0+ ],+ [+ 1.33333,+ 3.0,+ 0.0+ ],+ [+ 1.66667,+ 0.0,+ 0.0+ ],+ [+ 1.66667,+ 1.0,+ 0.0+ ],+ [+ 1.66667,+ 2.0,+ 0.0+ ],+ [+ 1.66667,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 1.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 3.0,+ 0.0+ ],+ [+ 2.33333,+ 0.0,+ 0.0+ ],+ [+ 2.33333,+ 1.0,+ 0.0+ ],+ [+ 2.33333,+ 2.0,+ 0.0+ ],+ [+ 2.33333,+ 3.0,+ 0.0+ ],+ [+ 2.66667,+ 0.0,+ 0.0+ ],+ [+ 2.66667,+ 1.0,+ 0.0+ ],+ [+ 2.66667,+ 2.0,+ 0.0+ ],+ [+ 2.66667,+ 3.0,+ 0.0+ ],+ [+ 3.0,+ 0.0,+ 0.0+ ],+ [+ 3.0,+ 1.0,+ 0.0+ ],+ [+ 3.0,+ 2.0,+ 0.0+ ],+ [+ 3.0,+ 3.0,+ 0.0+ ]+ ]+ },+ "grid-fill-grid-hole": {+ "vertexCount": 25,+ "edgeCount": 40,+ "faceCount": 16,+ "faceSizes": {+ "4": 16+ },+ "volume": 0.0,+ "area": 16.0,+ "positions": [+ [+ 0.0,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ 1.0,+ 0.0+ ],+ [+ 0.0,+ 2.0,+ 0.0+ ],+ [+ 0.0,+ 3.0,+ 0.0+ ],+ [+ 0.0,+ 4.0,+ 0.0+ ],+ [+ 1.0,+ 0.0,+ 0.0+ ],+ [+ 1.0,+ 1.0,+ 0.0+ ],+ [+ 1.0,+ 2.0,+ 0.0+ ],+ [+ 1.0,+ 3.0,+ 0.0+ ],+ [+ 1.0,+ 4.0,+ 0.0+ ],+ [+ 2.0,+ 0.0,+ 0.0+ ],+ [+ 2.0,+ 1.0,+ 0.0+ ],+ [+ 2.0,+ 2.0,+ 0.0+ ],+ [+ 2.0,+ 3.0,+ 0.0+ ],+ [+ 2.0,+ 4.0,+ 0.0+ ],+ [+ 3.0,+ 0.0,+ 0.0+ ],+ [+ 3.0,+ 1.0,+ 0.0+ ],+ [+ 3.0,+ 2.0,+ 0.0+ ],+ [+ 3.0,+ 3.0,+ 0.0+ ],+ [+ 3.0,+ 4.0,+ 0.0+ ],+ [+ 4.0,+ 0.0,+ 0.0+ ],+ [+ 4.0,+ 1.0,+ 0.0+ ],+ [+ 4.0,+ 2.0,+ 0.0+ ],+ [+ 4.0,+ 3.0,+ 0.0+ ],+ [+ 4.0,+ 4.0,+ 0.0+ ]+ ]+ },+ "grid-fill-cylinder-open": {+ "vertexCount": 17,+ "edgeCount": 28,+ "faceCount": 13,+ "faceSizes": {+ "4": 12,+ "8": 1+ },+ "volume": 5.656854,+ "area": 17.902724,+ "positions": [+ [+ -1.0,+ 0.0,+ -1.0+ ],+ [+ -1.0,+ 0.0,+ 1.0+ ],+ [+ -0.70711,+ -0.70711,+ -1.0+ ],+ [+ -0.70711,+ -0.70711,+ 1.0+ ],+ [+ -0.70711,+ 0.70711,+ -1.0+ ],+ [+ -0.70711,+ 0.70711,+ 1.0+ ],+ [+ 0.0,+ -1.0,+ -1.0+ ],+ [+ 0.0,+ -1.0,+ 1.0+ ],+ [+ -0.0,+ 0.0,+ 1.0+ ],+ [+ 0.0,+ 1.0,+ -1.0+ ],+ [+ 0.0,+ 1.0,+ 1.0+ ],+ [+ 0.70711,+ -0.70711,+ -1.0+ ],+ [+ 0.70711,+ -0.70711,+ 1.0+ ],+ [+ 0.70711,+ 0.70711,+ -1.0+ ],+ [+ 0.70711,+ 0.70711,+ 1.0+ ],+ [+ 1.0,+ 0.0,+ -1.0+ ],+ [+ 1.0,+ 0.0,+ 1.0+ ]+ ]+ },+ "knife-project-cube-line": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 10,+ "faceSizes": {+ "4": 10+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.0,+ -0.5+ ],+ [+ -0.5,+ 0.0,+ 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.0,+ -0.5+ ],+ [+ 0.5,+ 0.0,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]}}}diff --git a/tests/mesh-cut-tools.test.js b/tests/mesh-cut-tools.test.jsnew file mode 100644index 00000000..36cfd005--- /dev/null+++ b/tests/mesh-cut-tools.test.js@@ -0,0 +1,131 @@+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, meshBounds } 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, parts = 1) {+ const report = lintMesh(mesh);+ assert.deepEqual(report.problems, []);+ assert.equal(report.parts.closed, parts);+}++const openCube = () => run(cube(), [{ op: 'delete', select: { tag: 'top' } }]).mesh;++test('fill_holes caps an open boundary and tags the cap', () => {+ const { mesh, results } = run(openCube(), [{ op: 'fill_holes', name: 'lid' }]);+ assertClosed(mesh);+ assert.equal(mesh.faceCount, 6);+ assert.equal(tagCounts(mesh)['lid.fill'], 1);+ assert.deepEqual([results[0].filled, results[0].skipped], [1, 0]);+});++test('fill_holes skips loops with more sides than allowed and refuses a closed mesh', () => {+ assert.throws(() => run(openCube(), [{ op: 'fill_holes', sides: 3 }]), /No boundary loop could be filled/);+ assert.throws(() => run(cube(), [{ op: 'fill_holes' }]), /no open boundary/);+});++test('the lint message for an open boundary points at fill_holes', () => {+ const report = lintMesh(openCube());+ assert.match(report.problems.find(problem => problem.kind === 'boundary-edge').fix, /fill_holes/);+});++const sliced = () => run(cube(), [{ op: 'loop_cut', name: 'cut', edges: { along: [0, 1, 0] } }]).mesh;++test('dissolve_edges, dissolve_verts and dissolve_limited undo a loop cut', () => {+ const merged = run(sliced(), [{ op: 'dissolve_edges', name: 'join', edges: { between: [{ tag: 'cut.band-0' }, { tag: 'cut.band-1' }] } }]);+ assert.deepEqual([merged.mesh.vertexCount, merged.mesh.faceCount], [12, 6]);+ assert.equal(tagCounts(merged.mesh)['join.merged'], 4);+ const straightened = run(merged.mesh, [{ op: 'dissolve_verts', verts: { valence: 2 } }]);+ assert.deepEqual([straightened.mesh.vertexCount, straightened.mesh.faceCount], [8, 6]);+ assertClosed(straightened.mesh);+ const limited = run(sliced(), [{ op: 'dissolve_limited', angle: 5 }]);+ assert.deepEqual([limited.mesh.vertexCount, limited.mesh.faceCount], [8, 6]);+ assertClosed(limited.mesh);+});++test('dissolve_faces merges a connected selection into one polygon', () => {+ const { mesh } = run(sliced(), [{ op: 'dissolve_faces', name: 'wall', select: { and: [{ tag: 'side' }, { normal: [1, 0, 0], maxAngle: 5 }] } }]);+ assert.equal(mesh.faceCount, 9);+ assertClosed(mesh);+ assert.throws(() => run(cube(), [{ op: 'dissolve_faces', select: { faces: [0] } }]), /nothing dissolves/);+});++test('bisect_plane cuts, clears one side and fills the cut', () => {+ const half = run(cube(), [{ op: 'bisect_plane', name: 'half', point: [0, 0.1, 0], normal: [0, 1, 0], clearOuter: true, fill: true }]);+ assertClosed(half.mesh);+ assert.equal(tagCounts(half.mesh)['half.cap'], 1);+ assert.ok(Math.abs(meshBounds(half.mesh).max[1] - 0.1) < 1e-6);+ assert.equal(half.results[0].capped, 1);+ const open = run(cube(), [{ op: 'bisect_plane', point: [0, 0, 0], normal: [0, 1, 0], clearInner: true }]);+ assert.equal(lintMesh(open.mesh).problems[0].kind, 'boundary-edge');+});++test('bisect_plane with fill and both sides kept makes two closed shells', () => {+ const { mesh } = run(cube(), [{ op: 'bisect_plane', name: 'split', point: [0, 0, 0], normal: [0, 1, 0], fill: true }]);+ assertClosed(mesh, 2);+ assert.equal(tagCounts(mesh)['split.cap'], 2);+ assert.throws(() => run(cube(), [{ op: 'bisect_plane', point: [0, 5, 0], normal: [0, 1, 0] }]), /does not cross/);+});++test('bridge_edge_loops joins two holes with a strip', () => {+ const tube = run(cube(), [{ op: 'delete', select: { or: [{ tag: 'top' }, { tag: 'bottom' }] } }]).mesh;+ const bridged = run(tube, [{ op: 'bridge_edge_loops', name: 'ring', edges: { open: true }, segments: 2 }]);+ assert.equal(bridged.mesh.faceCount, 4 + 8);+ assert.equal(tagCounts(bridged.mesh)['ring.bridge'], 8);+ assert.equal(lintMesh(bridged.mesh).problems.length, 0);+ assert.throws(() => run(openCube(), [{ op: 'bridge_edge_loops', edges: { open: true } }]), /exactly 2/);+});++test('subdivide_edges grids quads whose edges are all split', () => {+ const { mesh } = run(cube(), [{ op: 'subdivide_edges', name: 'fine', edges: { all: true }, cuts: 2 }]);+ assert.equal(mesh.faceCount, 6 * 9);+ assert.equal(mesh.vertexCount, 8 + 12 * 2 + 6 * 4);+ assertClosed(mesh);+ assert.equal(tagCounts(mesh)['fine.split'], 54);+});++test('subdivide_edges refuses to grow past the limits before allocating', () => {+ assert.throws(() => applyMeshEdits(cube(), [{ op: 'subdivide_edges', edges: { all: true }, cuts: 16 }], { maxFaces: 100 }), /over the limit/);+});++test('grid_fill fills an even loop with quads', () => {+ const round = meshFromGeometry(cylinder(8, 0, 1));+ const opened = run(round, [{ op: 'delete', select: { tag: 'top' } }]).mesh;+ const { mesh } = run(opened, [{ op: 'grid_fill', name: 'cap', edges: { open: true } }]);+ assert.equal(tagCounts(mesh)['cap.fill'], 4);+ assertClosed(mesh);+ assert.throws(() => run(round, [{ op: 'grid_fill', edges: { open: true } }]), /no boundary loop/);+});++test('knife_project cuts every face a projected line crosses', () => {+ const { mesh } = run(cube(), [{ op: 'knife_project', name: 'slit', path: [[-1, 0, 0], [1, 0, 0]], direction: [0, 0, -1] }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [12, 8]);+ assert.equal(tagCounts(mesh)['slit.cut'], 4);+ assertClosed(mesh);+ assert.throws(() => run(cube(), [{ op: 'knife_project', path: [[5, 5, 0], [6, 5, 0]], direction: [0, 0, -1] }]), /does not cross/);+});++test('knife_project follows a bend and adds points on the face', () => {+ const { mesh } = run(cube(), [{ op: 'knife_project', path: [[-1, -0.25, 0], [0, 0.25, 0], [1, -0.25, 0]], direction: [0, 0, -1] }]);+ assertClosed(mesh);+ assert.ok(mesh.faceCount > 6);+});++test('the cutting edits validate their fields', () => {+ assert.throws(() => normalizeMeshEdits([{ op: 'bridge_edge_loops' }]), /edges/);+ assert.throws(() => normalizeMeshEdits([{ op: 'bisect_plane', point: [0, 0, 0], normal: [0, 1, 0], clearInner: true, clearOuter: true }]), /everything/);+ assert.throws(() => normalizeMeshEdits([{ op: 'knife_project', path: [[0, 0, 0]], direction: [0, 0, 1] }]), /path/);+ assert.throws(() => normalizeMeshEdits([{ op: 'subdivide_edges', edges: { all: true }, cuts: 99 }]), /cuts/);+ for (const name of ['fill_holes', 'dissolve_faces', 'dissolve_edges', 'dissolve_verts', 'dissolve_limited', 'bisect_plane', 'bridge_edge_loops', 'subdivide_edges', 'grid_fill', 'knife_project']) {+ assert.ok(MESH_EDIT_OPERATIONS[name], name);+ }+});