Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

feat(primitives): bevel, chamfer, extrude, and revolve profile solids (#12)

Matthew Kissinger0984f5bf260c
diff --git a/package.json b/package.json
index cc10ea78..94318fe8 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"./views": "./src/views/index.ts",
"./validation": "./src/validation.ts",
"./primitives": "./src/primitives.ts",
+ "./profile": "./src/profile.ts",
"./architecture": "./src/architecture.ts",
"./character": "./src/character.ts",
"./vehicle": "./src/vehicle.ts",
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index 332859fd..dc875216 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -214,6 +214,38 @@ await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false })
await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false })
// Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading
// for sharp mechanical edges.
+await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })
+ // A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested —
+ // roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads
+ // too sharp: consoles, crates, appliances, handheld props, machined blocks.
+ // NOTE: Real objects almost never have perfectly sharp box edges, and a small radius is the
+ // single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for
+ // anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the
+ // smallest dimension); radius must be less than half the smallest dimension or the call
+ // throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async
+ // — build() must be async and the call must use await.
+await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })
+ // Sweeps a closed 2D outline into a watertight solid, with optional holes, corner
+ // rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box
+ // or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage,
+ // extruded trim.
+ // NOTE: The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two
+ // flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead.
+ // Holes are subtracted, so their winding order does not matter. A bevel larger than half the
+ // outline's narrowest feature throws rather than silently returning an empty solid. Output is
+ // manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it
+ // inside an async build().
+await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })
+ // Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding
+ // the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes,
+ // buttons, pills.
+ // NOTE: Use this instead of lathe/revolveGeo whenever the result must survive a boolean or
+ // needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed
+ // solid. Profile convention matches lathe: x is distance from the axis, y is position along
+ // it, and only the x >= 0 side is used. Async — await it inside an async build().
+circleProfile(radius: number, segments?: 24, center?: [number, number])
+ // Builds a closed circular outline for extrudeProfile / revolveProfile, so you never
+ // hand-write the trigonometry. Synchronous.
await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })
// Keeps only the volume where both operands overlap. Default flat shading.
await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })
@@ -616,6 +648,49 @@ await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { sm
// e.g. const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel); const teeth = [...];
// // 8 radially-arrayed box meshes const gear = await boolDiff('Gear', body, ...teeth); //
// hard-edged
+await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })
+ // A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested —
+ // roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads
+ // too sharp: consoles, crates, appliances, handheld props, machined blocks.
+ // NOTE: Real objects almost never have perfectly sharp box edges, and a small radius is the
+ // single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for
+ // anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the
+ // smallest dimension); radius must be less than half the smallest dimension or the call
+ // throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async
+ // — build() must be async and the call must use await.
+ // e.g. const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05); createPart('Console', geo,
+ // plastic, { position: [0, 0.3, 0], parent: root });
+await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })
+ // Sweeps a closed 2D outline into a watertight solid, with optional holes, corner
+ // rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box
+ // or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage,
+ // extruded trim.
+ // NOTE: The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two
+ // flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead.
+ // Holes are subtracted, so their winding order does not matter. A bevel larger than half the
+ // outline's narrowest feature throws rather than silently returning an empty solid. Output is
+ // manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it
+ // inside an async build().
+ // e.g. // L-bracket, inner AND outer corners filleted const outline = [[0, 0], [2, 0], [2,
+ // 0.4], [0.4, 0.4], [0.4, 2], [0, 2]]; const geo = await extrudeProfile(outline, { depth:
+ // 0.5, bevel: 0.06 }); createPart('Bracket', geo, steel, { parent: root });
+await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })
+ // Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding
+ // the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes,
+ // buttons, pills.
+ // NOTE: Use this instead of lathe/revolveGeo whenever the result must survive a boolean or
+ // needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed
+ // solid. Profile convention matches lathe: x is distance from the axis, y is position along
+ // it, and only the x >= 0 side is used. Async — await it inside an async build().
+ // e.g. // capsule tank with a rounded rim, then carve a port into it const profile = [[0,
+ // -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]]; const body = await revolveProfile(profile, {
+ // bevel: 0.08, segments: 32 }); const tank = await boolDiff('Tank', createPart('B', body,
+ // steel), portCutter);
+circleProfile(radius: number, segments?: 24, center?: [number, number])
+ // Builds a closed circular outline for extrudeProfile / revolveProfile, so you never
+ // hand-write the trigonometry. Synchronous.
+ // e.g. const washer = await extrudeProfile(circleProfile(1), { depth: 0.1, holes:
+ // [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])], });
await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })
// Keeps only the volume where both operands overlap. Default flat shading.
// e.g. const lens = await boolIntersect('Lens', boxMesh, sphereMesh);
diff --git a/src/__tests__/profile.test.ts b/src/__tests__/profile.test.ts
new file mode 100644
index 00000000..b808bda7
--- /dev/null
+++ b/src/__tests__/profile.test.ts
@@ -0,0 +1,440 @@
+/**
+ * Bevel / extrude / revolve — the profile-solid ops.
+ *
+ * These assert the two properties the whole approach was chosen for:
+ * **the bounding box does not move** when you bevel, and the result is a
+ * closed solid that survives a boolean. Minkowski-based rounding was rejected
+ * for cost and `smoothOut` for moving the bounding box, so both are pinned
+ * here rather than left as prose.
+ *
+ * Volume is computed from the returned BufferGeometry (signed-tetrahedron
+ * sum) rather than trusted from manifold, so these tests also fail if the
+ * geometry bridge ever hands back an unclosed or mis-wound mesh.
+ *
+ * All manifold-backed ops share one WASM init; keep them in one file so that
+ * cost is paid once.
+ */
+
+import { describe, it, expect } from 'bun:test';
+import * as THREE from 'three';
+import {
+ circleProfile,
+ extrudeProfile,
+ revolveProfile,
+ roundedBoxGeo,
+ type Profile2D,
+} from '../profile';
+import { boolDiff } from '../solids';
+import { createPart, createRoot, cylinderGeo, gameMaterial } from '../primitives';
+import { buildSandboxGlobals } from '../primitives';
+import { executeKilnCode, renderSceneToGLB } from '../render';
+
+/** Signed volume via the tetrahedron sum. Works indexed or non-indexed. */
+function meshVolume(geo: THREE.BufferGeometry): number {
+ const pos = geo.getAttribute('position') as THREE.BufferAttribute;
+ const idx = geo.getIndex();
+ const triCount = idx ? idx.count / 3 : pos.count / 3;
+ const a = new THREE.Vector3();
+ const b = new THREE.Vector3();
+ const c = new THREE.Vector3();
+ let total = 0;
+ for (let t = 0; t < triCount; t++) {
+ const i0 = idx ? (idx.getX(t * 3) as number) : t * 3;
+ const i1 = idx ? (idx.getX(t * 3 + 1) as number) : t * 3 + 1;
+ const i2 = idx ? (idx.getX(t * 3 + 2) as number) : t * 3 + 2;
+ a.fromBufferAttribute(pos, i0);
+ b.fromBufferAttribute(pos, i1);
+ c.fromBufferAttribute(pos, i2);
+ total += a.dot(b.clone().cross(c)) / 6;
+ }
+ return Math.abs(total);
+}
+
+function boxSize(geo: THREE.BufferGeometry): [number, number, number] {
+ geo.computeBoundingBox();
+ const bb = geo.boundingBox!;
+ return [bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z];
+}
+
+function triCount(geo: THREE.BufferGeometry): number {
+ const idx = geo.getIndex();
+ return Math.floor(idx ? idx.count / 3 : (geo.getAttribute('position')?.count ?? 0) / 3);
+}
+
+const UNIT_SQUARE: Profile2D = [
+ [-0.5, -0.5],
+ [0.5, -0.5],
+ [0.5, 0.5],
+ [-0.5, 0.5],
+];
+
+describe('roundedBoxGeo', () => {
+ it('rounds all twelve edges without growing the box', async () => {
+ const geo = await roundedBoxGeo(1, 1, 1, 0.1);
+ const [w, h, d] = boxSize(geo);
+ // The rejected alternatives fail exactly here: minkowskiSum grows the box
+ // by 2r, and smoothOut+refine took a unit box to 1.56 across.
+ expect(w).toBeCloseTo(1, 5);
+ expect(h).toBeCloseTo(1, 5);
+ expect(d).toBeCloseTo(1, 5);
+ // Rounding removes material, so volume sits just under the sharp box.
+ const vol = meshVolume(geo);
+ expect(vol).toBeLessThan(1);
+ expect(vol).toBeGreaterThan(0.97);
+ });
+
+ it('honours non-cubic dimensions in boxGeo argument order (w, h, d)', async () => {
+ const geo = await roundedBoxGeo(2, 0.5, 1.25, 0.05);
+ const [w, h, d] = boxSize(geo);
+ expect(w).toBeCloseTo(2, 5);
+ expect(h).toBeCloseTo(0.5, 5);
+ expect(d).toBeCloseTo(1.25, 5);
+ });
+
+ it('chamfer keeps the exact size and is far cheaper than round', async () => {
+ const chamfer = await roundedBoxGeo(1, 1, 1, 0.1, { style: 'chamfer' });
+ const round = await roundedBoxGeo(1, 1, 1, 0.1, { style: 'round' });
+ const [w, h, d] = boxSize(chamfer);
+ expect(w).toBeCloseTo(1, 5);
+ expect(h).toBeCloseTo(1, 5);
+ expect(d).toBeCloseTo(1, 5);
+ // A chamfer is one flat per edge; a fillet is an arc per edge.
+ expect(triCount(chamfer)).toBeLessThan(triCount(round));
+ // Flat cuts remove more material than arcs of the same nominal size.
+ expect(meshVolume(chamfer)).toBeLessThan(meshVolume(round));
+ });
+
+ it('segments trades triangles for smoothness without moving the box', async () => {
+ const coarse = await roundedBoxGeo(1, 1, 1, 0.1, { segments: 6 });
+ const fine = await roundedBoxGeo(1, 1, 1, 0.1, { segments: 24 });
+ expect(triCount(fine)).toBeGreaterThan(triCount(coarse));
+ expect(boxSize(fine)[0]).toBeCloseTo(1, 5);
+ expect(boxSize(coarse)[0]).toBeCloseTo(1, 5);
+ });
+
+ it('rejects a radius that leaves no box to round', async () => {
+ // 0.5 on a 1-unit side is exactly half — there is no flat left.
+ await expect(roundedBoxGeo(1, 1, 1, 0.5)).rejects.toThrow(
+ /less than half the smallest dimension/,
+ );
+ await expect(roundedBoxGeo(2, 2, 0.4, 0.3)).rejects.toThrow(
+ /less than half the smallest dimension/,
+ );
+ });
+
+ it('rejects non-positive dimensions instead of returning an empty mesh', async () => {
+ await expect(roundedBoxGeo(0, 1, 1, 0.1)).rejects.toThrow(/width must be a positive number/);
+ await expect(roundedBoxGeo(1, 1, 1, 0)).rejects.toThrow(/radius must be a positive number/);
+ await expect(roundedBoxGeo(1, -1, 1, 0.1)).rejects.toThrow(/height must be a positive number/);
+ });
+});
+
+describe('extrudeProfile', () => {
+ it('sweeps a square into a prism of exactly the right volume', async () => {
+ const geo = await extrudeProfile(UNIT_SQUARE, { depth: 2 });
+ expect(meshVolume(geo)).toBeCloseTo(2, 4);
+ const [w, h, d] = boxSize(geo);
+ // Default axis is 'y' to match cylinderGeo, so depth runs along Y.
+ expect(w).toBeCloseTo(1, 5);
+ expect(h).toBeCloseTo(2, 5);
+ expect(d).toBeCloseTo(1, 5);
+ });
+
+ it('REGRESSION: an untapered extrude is a full prism, not a half-volume wedge', async () => {
+ // manifold-3d 3.5.1 types `scaleTop` as `Vec2 | number` but misreads the
+ // scalar form as `[s, 0]`: extrude(1, 1, 0, 1) returns a 20-triangle wedge
+ // of volume 0.5 where a unit prism was asked for. normalizeTaper() exists
+ // solely to force the Vec2 form. If it is ever "simplified" into passing
+ // the scalar straight through, both of these drop to half volume.
+ const plain = await extrudeProfile(UNIT_SQUARE, { depth: 1 });
+ expect(meshVolume(plain)).toBeCloseTo(1, 4);
+
+ const explicitFullTaper = await extrudeProfile(UNIT_SQUARE, { depth: 1, taper: 1 });
+ expect(meshVolume(explicitFullTaper)).toBeCloseTo(1, 4);
+ });
+
+ it('bevelling does not move the bounding box', async () => {
+ const sharp = await extrudeProfile(UNIT_SQUARE, { depth: 1 });
+ const rounded = await extrudeProfile(UNIT_SQUARE, { depth: 1, bevel: 0.1 });
+ expect(boxSize(rounded)[0]).toBeCloseTo(boxSize(sharp)[0], 4);
+ expect(boxSize(rounded)[2]).toBeCloseTo(boxSize(sharp)[2], 4);
+ // The bevel only removes material from the vertical edges.
+ expect(meshVolume(rounded)).toBeLessThan(meshVolume(sharp));
+ expect(meshVolume(rounded)).toBeGreaterThan(meshVolume(sharp) * 0.95);
+ });
+
+ it('chamfer and round are different shapes at the same nominal bevel', async () => {
+ const round = await extrudeProfile(UNIT_SQUARE, { depth: 1, bevel: 0.1, bevelStyle: 'round' });
+ const chamfer = await extrudeProfile(UNIT_SQUARE, {
+ depth: 1,
+ bevel: 0.1,
+ bevelStyle: 'chamfer',
+ });
+ // 'Miter' would have been a no-op here — this is why the mapping is
+ // round->Round, chamfer->Square. A chamfer must actually remove material.
+ expect(meshVolume(chamfer)).toBeLessThan(1);
+ expect(meshVolume(round)).toBeLessThan(1);
+ expect(triCount(chamfer)).toBeLessThan(triCount(round));
+ });
+
+ it('rejects a bevel larger than the profile can absorb', async () => {
+ // A 0.15-wide profile cannot survive eroding by 0.1.
+ const thin: Profile2D = [
+ [-0.075, -1],
+ [0.075, -1],
+ [0.075, 1],
+ [-0.075, 1],
+ ];
+ await expect(extrudeProfile(thin, { depth: 1, bevel: 0.1 })).rejects.toThrow(
+ /too large for this profile/,
+ );
+ });
+
+ it('subtracts holes regardless of their winding order', async () => {
+ const outer = circleProfile(1, 48);
+ const hole = circleProfile(0.5, 48);
+ const solid = await extrudeProfile(outer, { depth: 0.2 });
+ const ccw = await extrudeProfile(outer, { depth: 0.2, holes: [hole] });
+ const cw = await extrudeProfile(outer, { depth: 0.2, holes: [[...hole].reverse()] });
+
+ const expectedRing = Math.PI * (1 - 0.25) * 0.2;
+ expect(meshVolume(ccw)).toBeCloseTo(expectedRing, 2);
+ // Reversed winding must give the same washer, not a filled disc. Under an
+ // EvenOdd fill rule it would silently fill in.
+ expect(meshVolume(cw)).toBeCloseTo(meshVolume(ccw), 4);
+ expect(meshVolume(ccw)).toBeLessThan(meshVolume(solid));
+ });
+
+ it('taper 0 makes a pyramid of one third the prism volume', async () => {
+ const pyramid = await extrudeProfile(UNIT_SQUARE, { depth: 1, taper: 0 });
+ expect(meshVolume(pyramid)).toBeCloseTo(1 / 3, 3);
+ });
+
+ it('taper accepts an anisotropic [x, y] pair', async () => {
+ const wedge = await extrudeProfile(UNIT_SQUARE, { depth: 1, taper: [1, 0] });
+ // Full width at top, zero depth: a triangular prism laid on its side.
+ expect(meshVolume(wedge)).toBeCloseTo(0.5, 3);
+ });
+
+ it('twist adds slices, and more slices converge on the true volume', async () => {
+ const straight = await extrudeProfile(UNIT_SQUARE, { depth: 2 });
+ const twisted = await extrudeProfile(UNIT_SQUARE, { depth: 2, twist: 90 });
+ expect(triCount(twisted)).toBeGreaterThan(triCount(straight));
+
+ // Every slice of a twisted prism is still a unit square, so the exact
+ // solid has the same volume as the straight one. The *mesh* overshoots:
+ // the lateral surface is ruled between two rotated squares, and that ruled
+ // patch bulges outside both. The overshoot is a discretisation artifact
+ // that shrinks as divisions rise — assert the convergence rather than
+ // pretending the coarse mesh is exact.
+ const exact = meshVolume(straight);
+ const coarse = await extrudeProfile(UNIT_SQUARE, { depth: 2, twist: 90, divisions: 4 });
+ const fine = await extrudeProfile(UNIT_SQUARE, { depth: 2, twist: 90, divisions: 64 });
+ const err = (g: THREE.BufferGeometry) => Math.abs(meshVolume(g) - exact);
+ expect(err(fine)).toBeLessThan(err(coarse));
+ expect(err(fine)).toBeLessThan(exact * 0.01);
+ // The default (16 divisions) should already be within a few percent.
+ expect(err(twisted)).toBeLessThan(exact * 0.05);
+ });
+
+ it('sweeps along the requested axis', async () => {
+ const along = async (axis: 'x' | 'y' | 'z') =>
+ boxSize(await extrudeProfile(UNIT_SQUARE, { depth: 3, axis }));
+ expect((await along('x'))[0]).toBeCloseTo(3, 5);
+ expect((await along('y'))[1]).toBeCloseTo(3, 5);
+ expect((await along('z'))[2]).toBeCloseTo(3, 5);
+ });
+
+ it('center:false starts the sweep at the origin', async () => {
+ const geo = await extrudeProfile(UNIT_SQUARE, { depth: 2, axis: 'z', center: false });
+ geo.computeBoundingBox();
+ expect(geo.boundingBox!.min.z).toBeCloseTo(0, 5);
+ expect(geo.boundingBox!.max.z).toBeCloseTo(2, 5);
+ });
+
+ it('rejects malformed profiles with a message that names the problem', async () => {
+ await expect(
+ extrudeProfile([
+ [0, 0],
+ [1, 1],
+ ]),
+ ).rejects.toThrow(/at least 3 points/);
+ await expect(
+ extrudeProfile([
+ [0, 0],
+ [1, 0],
+ [Number.NaN, 1],
+ ]),
+ ).rejects.toThrow(/point 2 is not a finite/);
+ await expect(extrudeProfile(UNIT_SQUARE, { depth: 0 })).rejects.toThrow(
+ /depth must be a positive number/,
+ );
+ await expect(extrudeProfile(UNIT_SQUARE, { bevel: -1 })).rejects.toThrow(/bevel must be >= 0/);
+ });
+});
+
+describe('revolveProfile', () => {
+ it('revolves a rectangle into a solid cylinder of the right volume', async () => {
+ const geo = await revolveProfile(
+ [
+ [0, -0.5],
+ [0.4, -0.5],
+ [0.4, 0.5],
+ [0, 0.5],
+ ],
+ { segments: 64 },
+ );
+ // Discretised circle undersells the true area slightly.
+ expect(meshVolume(geo)).toBeCloseTo(Math.PI * 0.16 * 1, 2);
+ const [w, h, d] = boxSize(geo);
+ expect(h).toBeCloseTo(1, 4); // default axis 'y', matching lathe
+ expect(w).toBeCloseTo(0.8, 2);
+ expect(d).toBeCloseTo(0.8, 2);
+ });
+
+ it('bevel rounds the rim without growing the silhouette', async () => {
+ const profile: Profile2D = [
+ [0, -0.5],
+ [0.4, -0.5],
+ [0.4, 0.5],
+ [0, 0.5],
+ ];
+ const sharp = await revolveProfile(profile, { segments: 64 });
+ const rounded = await revolveProfile(profile, { segments: 64, bevel: 0.08 });
+ expect(boxSize(rounded)[1]).toBeCloseTo(boxSize(sharp)[1], 3);
+ expect(meshVolume(rounded)).toBeLessThan(meshVolume(sharp));
+ });
+
+ it('a partial sweep produces less volume than a full revolution', async () => {
+ const profile: Profile2D = [
+ [0.2, 0],
+ [0.5, 0],
+ [0.5, 1],
+ [0.2, 1],
+ ];
+ const full = await revolveProfile(profile, { segments: 64 });
+ const half = await revolveProfile(profile, { segments: 64, angle: 180 });
+ expect(meshVolume(half)).toBeCloseTo(meshVolume(full) / 2, 2);
+ });
+
+ it('rejects an out-of-range sweep angle', async () => {
+ const p: Profile2D = [
+ [0, 0],
+ [1, 0],
+ [1, 1],
+ ];
+ await expect(revolveProfile(p, { angle: 0 })).rejects.toThrow(/angle must be in \(0, 360\]/);
+ await expect(revolveProfile(p, { angle: 540 })).rejects.toThrow(/angle must be in \(0, 360\]/);
+ });
+});
+
+describe('circleProfile', () => {
+ it('builds a closed outline of the requested radius and segment count', () => {
+ const pts = circleProfile(2, 16);
+ expect(pts).toHaveLength(16);
+ for (const [x, y] of pts) {
+ expect(Math.hypot(x, y)).toBeCloseTo(2, 6);
+ }
+ // Closed by construction — the last point must not duplicate the first.
+ expect(pts[0]).not.toEqual(pts[pts.length - 1]!);
+ });
+
+ it('offsets around an explicit center', () => {
+ const pts = circleProfile(1, 8, [5, -3]);
+ for (const [x, y] of pts) {
+ expect(Math.hypot(x - 5, y + 3)).toBeCloseTo(1, 6);
+ }
+ });
+
+ it('rejects degenerate inputs', () => {
+ expect(() => circleProfile(0)).toThrow(/radius must be a positive number/);
+ expect(() => circleProfile(1, 2)).toThrow(/segments must be an integer >= 3/);
+ });
+});
+
+describe('interop', () => {
+ it('an extruded profile survives a boolean and exports to GLB', async () => {
+ const root = createRoot('Washer');
+ const plate = await extrudeProfile(circleProfile(1, 48), { depth: 0.3, bevel: 0.05 });
+ const body = createPart('Plate', plate, gameMaterial(0x8899aa), { parent: root });
+ const drill = new THREE.Mesh(cylinderGeo(0.3, 0.3, 2, 24), gameMaterial(0x000000));
+ const pierced = await boolDiff('Pierced', body, drill);
+
+ expect(triCount(pierced.geometry)).toBeGreaterThan(0);
+ expect(meshVolume(pierced.geometry)).toBeLessThan(meshVolume(plate));
+
+ const out = createRoot('WasherOut');
+ out.add(pierced);
+ const { bytes } = await renderSceneToGLB(out);
+ expect(bytes.byteLength).toBeGreaterThan(1000);
+ });
+
+ it('agent-authored code can use every new op through executeKilnCode', async () => {
+ // The real authoring path. Importing the functions proves they work;
+ // this proves the *agent* can reach them — registration, the async
+ // build() contract, and interop with createPart/boolDiff all at once.
+ const code = `
+const meta = { name: 'Bracket', category: 'prop' };
+
+async function build() {
+ const root = createRoot('Bracket');
+ const steel = gameMaterial(0x9aa4b0, { metalness: 0.6, roughness: 0.4 });
+
+ const plate = await roundedBoxGeo(1.2, 0.15, 0.8, 0.04);
+ createPart('Plate', plate, steel, { position: [0, 0, 0], parent: root });
+
+ const rib = await extrudeProfile(
+ [[0, 0], [0.6, 0], [0.6, 0.12], [0.12, 0.12], [0.12, 0.6], [0, 0.6]],
+ { depth: 0.2, bevel: 0.02, axis: 'z' },
+ );
+ createPart('Rib', rib, steel, { position: [0, 0.1, 0], parent: root });
+
+ const boss = await revolveProfile(
+ [[0, 0], [0.12, 0], [0.12, 0.3], [0, 0.3]],
+ { segments: 24, bevel: 0.03 },
+ );
+ const bossPart = createPart('Boss', boss, steel, {});
+ const bore = createPart('Bore', cylinderGeo(0.05, 0.05, 1, 16), steel, {});
+ root.add(await boolDiff('Boss', bossPart, bore));
+
+ const washer = await extrudeProfile(circleProfile(0.3, 32), {
+ depth: 0.06,
+ holes: [circleProfile(0.12, 24)],
+ bevel: 0.015,
+ bevelStyle: 'chamfer',
+ });
+ createPart('Washer', washer, steel, { position: [0.5, 0.4, 0], parent: root });
+
+ return root;
+}
+`;
+ const { root } = await executeKilnCode(code);
+ expect(root.name).toBe('Bracket');
+ // createPart / boolDiff both prefix the mesh name with `Mesh_`.
+ const names = new Set<string>();
+ root.traverse((c) => names.add(c.name));
+ expect(names.has('Mesh_Plate')).toBe(true);
+ expect(names.has('Mesh_Rib')).toBe(true);
+ expect(names.has('Mesh_Boss')).toBe(true);
+ expect(names.has('Mesh_Washer')).toBe(true);
+
+ const { bytes, tris } = await renderSceneToGLB(root);
+ expect(bytes.byteLength).toBeGreaterThan(1000);
+ expect(tris).toBeGreaterThan(0);
+ });
+
+ it('the sandbox exposes all four ops as globals', () => {
+ const globals = buildSandboxGlobals();
+ for (const name of ['roundedBoxGeo', 'extrudeProfile', 'revolveProfile', 'circleProfile']) {
+ expect(typeof globals[name]).toBe('function');
+ }
+ });
+
+ it('usage tracking counts the new ops like any other primitive', async () => {
+ const usage: Record<string, number> = {};
+ const globals = buildSandboxGlobals(usage);
+ const rounded = globals['roundedBoxGeo'] as typeof roundedBoxGeo;
+ await rounded(1, 1, 1, 0.1);
+ expect(usage['roundedBoxGeo']).toBe(1);
+ });
+});
diff --git a/src/list-primitives.ts b/src/list-primitives.ts
index 469468aa..19d1e379 100644
--- a/src/list-primitives.ts
+++ b/src/list-primitives.ts
@@ -690,6 +690,55 @@ const PRIMITIVES: PrimitiveSpec[] = [
example:
"const body = new THREE.Mesh(cylinderGeo(1, 1, 0.3, 32), steel);\nconst teeth = [...]; // 8 radially-arrayed box meshes\nconst gear = await boolDiff('Gear', body, ...teeth); // hard-edged",
},
+ {
+ name: 'roundedBoxGeo',
+ signature:
+ "await roundedBoxGeo(width: number, height: number, depth: number, radius: number, opts?: { style?: 'round' | 'chamfer', segments?: 12, smooth?: boolean })",
+ returns: 'Promise<THREE.BufferGeometry>',
+ category: 'csg',
+ description:
+ 'A box with all twelve edges rounded (or chamfered) at the EXACT outer size requested — roundedBoxGeo(1, 1, 1, 0.1) measures 1x1x1, it does not grow. Use it anywhere boxGeo reads too sharp: consoles, crates, appliances, handheld props, machined blocks.',
+ promptNotes:
+ "Real objects almost never have perfectly sharp box edges, and a small radius is the single cheapest upgrade to how manufactured an asset looks. Prefer this over boxGeo for anything moulded, cast, or machined. Keep radius small relative to the box (5-10% of the smallest dimension); radius must be less than half the smallest dimension or the call throws. style: 'chamfer' reads as machined metal, 'round' as moulded plastic. This is async — build() must be async and the call must use await.",
+ example:
+ "const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);\ncreatePart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });",
+ },
+ {
+ name: 'extrudeProfile',
+ signature:
+ "await extrudeProfile(profile: [number, number][], opts?: { depth?: 1, holes?: [number, number][][], bevel?: 0, bevelStyle?: 'round' | 'chamfer', segments?: 12, twist?: 0, taper?: number | [number, number], divisions?: number, axis?: 'x' | 'y' | 'z', center?: true, smooth?: false })",
+ returns: 'Promise<THREE.BufferGeometry>',
+ category: 'csg',
+ description:
+ 'Sweeps a closed 2D outline into a watertight solid, with optional holes, corner rounding/chamfering, twist, and taper. The way to build any cross-section that is not a box or a cylinder: L-brackets, I-beams, gaskets, washers, star and gear plates, signage, extruded trim.',
+ promptNotes:
+ "The bevel rounds the edges PARALLEL to the sweep axis (the profile corners) — the two flat caps stay sharp. For a box rounded on all twelve edges use roundedBoxGeo instead. Holes are subtracted, so their winding order does not matter. A bevel larger than half the outline's narrowest feature throws rather than silently returning an empty solid. Output is manifold, so it feeds straight into boolUnion / boolDiff / boolIntersect. Async — await it inside an async build().",
+ example:
+ "// L-bracket, inner AND outer corners filleted\nconst outline = [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]];\nconst geo = await extrudeProfile(outline, { depth: 0.5, bevel: 0.06 });\ncreatePart('Bracket', geo, steel, { parent: root });",
+ },
+ {
+ name: 'revolveProfile',
+ signature:
+ "await revolveProfile(profile: [number, number][], opts?: { segments?: 24, angle?: 360, bevel?: 0, bevelStyle?: 'round' | 'chamfer', bevelSegments?: 12, axis?: 'x' | 'y' | 'z', smooth?: true })",
+ returns: 'Promise<THREE.BufferGeometry>',
+ category: 'csg',
+ description:
+ 'Revolves a closed 2D outline around an axis into a watertight SOLID, optionally rounding the profile corners first. Bottles, tanks, pressure vessels, wheels, turned wood, domes, buttons, pills.',
+ promptNotes:
+ 'Use this instead of lathe/revolveGeo whenever the result must survive a boolean or needs a rounded rim — lathe and revolveGeo build an open surface, this builds a closed solid. Profile convention matches lathe: x is distance from the axis, y is position along it, and only the x >= 0 side is used. Async — await it inside an async build().',
+ example:
+ "// capsule tank with a rounded rim, then carve a port into it\nconst profile = [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]];\nconst body = await revolveProfile(profile, { bevel: 0.08, segments: 32 });\nconst tank = await boolDiff('Tank', createPart('B', body, steel), portCutter);",
+ },
+ {
+ name: 'circleProfile',
+ signature: 'circleProfile(radius: number, segments?: 24, center?: [number, number])',
+ returns: '[number, number][]',
+ category: 'csg',
+ description:
+ 'Builds a closed circular outline for extrudeProfile / revolveProfile, so you never hand-write the trigonometry. Synchronous.',
+ example:
+ 'const washer = await extrudeProfile(circleProfile(1), {\n depth: 0.1,\n holes: [circleProfile(0.4), circleProfile(0.1, 16, [0.7, 0])],\n});',
+ },
{
name: 'boolIntersect',
signature:
diff --git a/src/primitives.ts b/src/primitives.ts
index d0a55a85..892796cc 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -20,6 +20,7 @@ import {
} from './architecture';
import * as gears from './gears';
import * as ops from './ops';
+import * as profile from './profile';
import * as solids from './solids';
import * as textures from './textures';
import { materialRecipe } from './material-recipe-runtime';
@@ -1645,6 +1646,13 @@ export function buildSandboxGlobals(usage?: Record<string, number>): Record<stri
boolDiff: wrap('boolDiff', solids.boolDiff),
boolIntersect: wrap('boolIntersect', solids.boolIntersect),
hull: wrap('hull', solids.hull),
+ // Bevel / extrude / revolve (async — same manifold WASM as the CSG ops).
+ // NOT wrapGeo: these return a Promise, and the geometry memo/kilnRanges
+ // stamp in wrapGeo operates on a BufferGeometry synchronously.
+ roundedBoxGeo: wrap('roundedBoxGeo', profile.roundedBoxGeo),
+ extrudeProfile: wrap('extrudeProfile', profile.extrudeProfile),
+ revolveProfile: wrap('revolveProfile', profile.revolveProfile),
+ circleProfile: wrap('circleProfile', profile.circleProfile),
// Array/mirror/subdivide/curve ops
arrayLinear: wrap('arrayLinear', ops.arrayLinear),
arrayRadial: wrap('arrayRadial', ops.arrayRadial),
diff --git a/src/profile.ts b/src/profile.ts
new file mode 100644
index 00000000..5ea890fd
--- /dev/null
+++ b/src/profile.ts
@@ -0,0 +1,482 @@
+/**
+ * Kiln profile solids — bevel, chamfer, extrude, revolve (manifold-3d backed)
+ *
+ * Three ops that close the two biggest gaps in the primitive set: nothing
+ * could round or chamfer an edge, and nothing could turn an arbitrary 2D
+ * outline into a solid. Both are answered by the same mechanism, so they live
+ * together.
+ *
+ * ## Why this implementation and not the obvious one
+ *
+ * The textbook general bevel is morphological: erode the solid by r, then
+ * dilate it by r (a Minkowski "open"). manifold-3d exposes `minkowskiSum` /
+ * `minkowskiDifference`, and it does produce a correct, size-preserving round
+ * on arbitrary meshes. It is unusable inside a generation loop — measured on
+ * this exact library version:
+ *
+ * | source | tris in | tris out | time |
+ * |-------------------|---------|----------|----------|
+ * | box | 12 | 236 | 61 ms |
+ * | plate with a hole | 208 | 23,760 | 10,161 ms |
+ * | sphere (seg 64) | 2,048 | 8,978 | 35,860 ms |
+ *
+ * Cost is superlinear in source complexity and it detonates the triangle
+ * budget. `smoothOut() + refine()` is fast but is not a bevel at all: it moves
+ * the bounding box (a unit box becomes 1.56 across) and inflates volume.
+ *
+ * What works is doing the rounding in **2D** and then sweeping: offset the
+ * cross-section with a `JoinType`, then `extrude` or `revolve`. Every case
+ * measured here lands between 0.3 ms and 9 ms, preserves the bounding box
+ * exactly, keeps holes, and composes with the boolean ops in `solids.ts`.
+ *
+ * The bevel sequence is erode(-r) -> dilate(+2r) -> erode(-r), which rounds
+ * **inner and outer** corners while leaving the outer dimensions untouched.
+ *
+ * ## What this deliberately does NOT do
+ *
+ * There is no general "bevel every edge of an arbitrary mesh" op. `extrudeProfile`
+ * rounds the edges **parallel to the sweep axis** (the profile's corners); the
+ * two caps stay sharp. For an all-12-edges rounded box use `roundedBoxGeo`.
+ * Re-rounding an arbitrary solid by projecting it back to 2D works only for
+ * genuinely prismatic shapes and silently destroys everything else, so it is
+ * not exposed.
+ *
+ * As with all manifold-backed ops, only positions survive: normals are
+ * regenerated and UVs are not carried.
+ */
+
+import type * as THREE from 'three';
+import type { CrossSection, JoinType, Manifold, Vec2 } from 'manifold-3d';
+import { getManifoldModule, manifoldToGeometry } from './solids';
+
+/** A closed 2D outline as `[x, y]` pairs — same convention as `lathe`. */
+export type Profile2D = Array<[number, number]>;
+
+/** `round` = fillet, `chamfer` = a single flat cut across the corner. */
+export type BevelStyle = 'round' | 'chamfer';
+
+/** Which world axis the sweep runs along. */
+export type SweepAxis = 'x' | 'y' | 'z';
+
+export interface ExtrudeProfileOptions {
+ /** Length of the sweep. Default 1. */
+ depth?: number;
+ /** Holes as additional closed outlines, subtracted from `profile`. */
+ holes?: Profile2D[];
+ /** Corner rounding radius. 0 (default) leaves corners sharp. */
+ bevel?: number;
+ /** `round` (default) or `chamfer`. */
+ bevelStyle?: BevelStyle;
+ /** Segments per 360 degrees of round corner. Default 12. */
+ segments?: number;
+ /** Total twist across the sweep, in degrees. Default 0. */
+ twist?: number;
+ /** Top scale: `0.5` shrinks both axes by half, `0` makes a pyramid/cone. */
+ taper?: number | [number, number];
+ /** Intermediate slices along the sweep. Auto-raised to 16 when twisting. */
+ divisions?: number;
+ /** Sweep axis. Default `y`, matching `cylinderGeo`. */
+ axis?: SweepAxis;
+ /** Center on the sweep axis. Default true, matching `boxGeo`. */
+ center?: boolean;
+ /** Averaged (smooth) normals instead of flat facets. Default false. */
+ smooth?: boolean;
+}
+
+export interface RevolveProfileOptions {
+ /** Radial segments. Default 24. */
+ segments?: number;
+ /** Sweep angle in degrees. Default 360. */
+ angle?: number;
+ /** Corner rounding radius applied to the profile before revolving. */
+ bevel?: number;
+ /** `round` (default) or `chamfer`. */
+ bevelStyle?: BevelStyle;
+ /** Segments per 360 degrees of round corner. Default 12. */
+ bevelSegments?: number;
+ /** Axis of revolution. Default `y`, matching `lathe`. */
+ axis?: SweepAxis;
+ /** Averaged (smooth) normals. Default true — revolved shapes are curved. */
+ smooth?: boolean;
+}
+
+export interface RoundedBoxOptions {
+ /** `round` (default) or `chamfer`. */
+ style?: BevelStyle;
+ /** Sphere segments for `round`. Default 12. Higher = smoother, more tris. */
+ segments?: number;
+ /** Averaged normals. Defaults to true for `round`, false for `chamfer`. */
+ smooth?: boolean;
+}
+
+const JOIN_FOR_STYLE: Record<BevelStyle, JoinType> = {
+ // Measured, not assumed: on a 2x2 square with bevel 0.1, `Round` yields a
+ // 5-point arc per corner, `Square` yields one 45-degree flat, and `Miter`
+ // leaves the corner *untouched* (area stays exactly 4.0). Miter is a
+ // corner-preserving join by definition and is never a bevel.
+ round: 'Round',
+ chamfer: 'Square',
+};
+
+function assertFiniteProfile(profile: Profile2D, label: string): void {
+ if (!Array.isArray(profile) || profile.length < 3) {
+ throw new Error(`${label}: need at least 3 points to form a closed outline.`);
+ }
+ for (let i = 0; i < profile.length; i++) {
+ const p = profile[i];
+ if (!Array.isArray(p) || p.length < 2 || !Number.isFinite(p[0]) || !Number.isFinite(p[1])) {
+ throw new Error(
+ `${label}: point ${i} is not a finite [x, y] pair (got ${JSON.stringify(p)}).`,
+ );
+ }
+ }
+}
+
+function assertPositive(value: number, label: string): void {
+ if (!Number.isFinite(value) || value <= 0) {
+ throw new Error(`${label} must be a positive number (got ${value}).`);
+ }
+}
+
+/** Rotate a Z-swept geometry onto the requested axis, in place. */
+function orientSweep(geo: THREE.BufferGeometry, axis: SweepAxis): THREE.BufferGeometry {
+ // manifold sweeps along +Z; Kiln's primitive set is Y-up.
+ if (axis === 'y') geo.rotateX(-Math.PI / 2);
+ else if (axis === 'x') geo.rotateY(Math.PI / 2);
+ else if (axis !== 'z') throw new Error(`axis must be 'x', 'y', or 'z' (got ${String(axis)}).`);
+ return geo;
+}
+
+/**
+ * Round or chamfer every corner of a cross-section without moving its outer
+ * dimensions: erode by r, dilate by 2r, erode by r.
+ *
+ * Throws when `bevel` is too large for the profile's narrowest feature — the
+ * first erosion empties the section, and manifold would otherwise hand back a
+ * silently empty solid.
+ */
+function bevelCrossSection(
+ cs: CrossSection,
+ bevel: number,
+ style: BevelStyle,
+ segments: number,
+ label: string,
+): CrossSection {
+ const join = JOIN_FOR_STYLE[style];
+ if (!join) {
+ throw new Error(`${label}: bevelStyle must be 'round' or 'chamfer' (got ${String(style)}).`);
+ }
+ const eroded = cs.offset(-bevel, join, 2, segments);
+ if (eroded.isEmpty()) {
+ eroded.delete();
+ throw new Error(
+ `${label}: bevel ${bevel} is too large for this profile — eroding by it leaves nothing. ` +
+ `Use a bevel smaller than half the narrowest part of the outline.`,
+ );
+ }
+ const dilated = eroded.offset(2 * bevel, join, 2, segments);
+ const out = dilated.offset(-bevel, join, 2, segments);
+ eroded.delete();
+ dilated.delete();
+ return out;
+}
+
+/**
+ * `scaleTop` MUST be a Vec2. manifold-3d 3.5.1 types it as `Vec2 | number`,
+ * but the scalar path is misread as `[s, 0]`: `extrude(1, 1, 0, 1)` returns a
+ * half-volume 20-triangle wedge where a unit prism was asked for, while
+ * `extrude(1, 1, 0, [1, 1])` returns the correct volume-1 prism. Passing a
+ * scalar silently produces wedges wherever a taper was intended.
+ */
+function normalizeTaper(taper: number | [number, number] | undefined): Vec2 {
+ if (taper === undefined) return [1, 1];
+ if (typeof taper === 'number') {
+ if (!Number.isFinite(taper) || taper < 0) {
+ throw new Error(`taper must be a finite number >= 0 (got ${taper}).`);
+ }
+ return [taper, taper];
+ }
+ if (
+ !Array.isArray(taper) ||
+ taper.length !== 2 ||
+ !taper.every((v) => Number.isFinite(v) && v >= 0)
+ ) {
+ throw new Error(
+ `taper must be a number or [x, y] pair of numbers >= 0 (got ${JSON.stringify(taper)}).`,
+ );
+ }
+ return [taper[0], taper[1]];
+}
+
+/**
+ * Sweep a closed 2D outline into a solid, optionally rounding or chamfering
+ * its corners, punching holes, twisting, and tapering.
+ *
+ * The bevel applies to the edges **parallel to the sweep axis**. The two caps
+ * stay sharp — for a box rounded on all twelve edges use `roundedBoxGeo`.
+ *
+ * Output is a watertight manifold solid, so it feeds straight into
+ * `boolUnion` / `boolDiff` / `boolIntersect`.
+ *
+ * @example
+ * // An L-bracket with filleted inner and outer corners.
+ * const geo = await extrudeProfile(
+ * [[0, 0], [2, 0], [2, 0.4], [0.4, 0.4], [0.4, 2], [0, 2]],
+ * { depth: 0.5, bevel: 0.06 },
+ * );
+ * createPart('Bracket', geo, steel, { parent: root });
+ *
+ * @example
+ * // A washer: round outline, round hole, chamfered edges.
+ * const ring = await extrudeProfile(circleProfile(1), {
+ * depth: 0.2,
+ * holes: [circleProfile(0.5)],
+ * bevel: 0.03,
+ * bevelStyle: 'chamfer',
+ * });
+ *
+ * @example
+ * // A twisted tapered spire.
+ * const spire = await extrudeProfile(
+ * [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]],
+ * { depth: 3, twist: 90, taper: 0.2 },
+ * );
+ */
+export async function extrudeProfile(
+ profile: Profile2D,
+ options: ExtrudeProfileOptions = {},
+): Promise<THREE.BufferGeometry> {
+ assertFiniteProfile(profile, 'extrudeProfile');
+ const {
+ depth = 1,
+ holes = [],
+ bevel = 0,
+ bevelStyle = 'round',
+ segments = 12,
+ twist = 0,
+ taper,
+ divisions,
+ axis = 'y',
+ center = true,
+ smooth = false,
+ } = options;
+ assertPositive(depth, 'extrudeProfile: depth');
+ if (bevel < 0) throw new Error(`extrudeProfile: bevel must be >= 0 (got ${bevel}).`);
+ for (let i = 0; i < holes.length; i++) {
+ assertFiniteProfile(holes[i] as Profile2D, `extrudeProfile: holes[${i}]`);
+ }
+
+ const mod = await getManifoldModule();
+ const { CrossSection: CS } = mod;
+
+ const disposable: CrossSection[] = [];
+ const track = <T extends CrossSection>(cs: T): T => {
+ disposable.push(cs);
+ return cs;
+ };
+
+ try {
+ let section: CrossSection = track(new CS([profile as Vec2[]], 'NonZero'));
+ if (holes.length > 0) {
+ // Subtract rather than relying on an EvenOdd fill rule: agent-written
+ // hole outlines have arbitrary winding, and a wrong winding under
+ // EvenOdd yields a filled disc instead of a hole with no error.
+ const holeSections = holes.map((h) => track(new CS([h as Vec2[]], 'NonZero')));
+ section = track(CS.difference(section, CS.union(holeSections)));
+ if (section.isEmpty()) {
+ throw new Error(
+ 'extrudeProfile: the holes consume the whole profile — nothing left to extrude.',
+ );
+ }
+ }
+ if (bevel > 0) {
+ section = track(bevelCrossSection(section, bevel, bevelStyle, segments, 'extrudeProfile'));
+ }
+
+ // Twist needs intermediate slices or it interpolates as a single shear.
+ const nDivisions = divisions ?? (twist !== 0 ? 16 : 1);
+ const solid = section.extrude(depth, nDivisions, twist, normalizeTaper(taper), center);
+ try {
+ return orientSweep(manifoldToGeometry(solid, { smooth }), axis);
+ } finally {
+ solid.delete();
+ }
+ } finally {
+ for (const cs of disposable) cs.delete();
+ }
+}
+
+/**
+ * Revolve a closed 2D outline around an axis into a **solid** (watertight,
+ * CSG-ready) shape, optionally rounding its corners first.
+ *
+ * This is the manifold-backed sibling of `lathe` / `revolveGeo`, which build
+ * an open Three.js `LatheGeometry` surface. Reach for those when you just want
+ * a surface; reach for this when the result has to survive a boolean, or when
+ * you want the rim rounded.
+ *
+ * The profile is in the same convention as `lathe`: `x` is distance from the
+ * axis, `y` is position along it. Only the `x >= 0` side is used.
+ *
+ * @example
+ * // A pill/capsule tank with a rounded rim, ready to be carved.
+ * const body = await revolveProfile(
+ * [[0, -0.5], [0.4, -0.5], [0.4, 0.5], [0, 0.5]],
+ * { bevel: 0.08, segments: 32 },
+ * );
+ * const carved = await boolDiff('Tank', createPart('B', body, mat), portCutter);
+ */
+export async function revolveProfile(
+ profile: Profile2D,
+ options: RevolveProfileOptions = {},
+): Promise<THREE.BufferGeometry> {
+ assertFiniteProfile(profile, 'revolveProfile');
+ const {
+ segments = 24,
+ angle = 360,
+ bevel = 0,
+ bevelStyle = 'round',
+ bevelSegments = 12,
+ axis = 'y',
+ smooth = true,
+ } = options;
+ if (bevel < 0) throw new Error(`revolveProfile: bevel must be >= 0 (got ${bevel}).`);
+ if (!Number.isFinite(angle) || angle <= 0 || angle > 360) {
+ throw new Error(`revolveProfile: angle must be in (0, 360] degrees (got ${angle}).`);
+ }
+
+ const mod = await getManifoldModule();
+ const { CrossSection: CS } = mod;
+
+ const disposable: CrossSection[] = [];
+ try {
+ let section: CrossSection = new CS([profile as Vec2[]], 'NonZero');
+ disposable.push(section);
+ if (bevel > 0) {
+ section = bevelCrossSection(section, bevel, bevelStyle, bevelSegments, 'revolveProfile');
+ disposable.push(section);
+ }
+ const solid = section.revolve(segments, angle);
+ try {
+ return orientSweep(manifoldToGeometry(solid, { smooth }), axis);
+ } finally {
+ solid.delete();
+ }
+ } finally {
+ for (const cs of disposable) cs.delete();
+ }
+}
+
+/**
+ * A box with all twelve edges rounded or chamfered, at the exact outer size
+ * you asked for — `roundedBoxGeo(1, 1, 1, 0.1)` is 1x1x1, not 1.2x1.2x1.2.
+ *
+ * `round` is built as the convex hull of eight inset spheres and `chamfer` as
+ * the hull of three interlocking boxes. Both are exact and cheap (a seg-12
+ * rounded box lands near 200 triangles in a couple of milliseconds).
+ *
+ * Argument order matches `boxGeo(width, height, depth)`.
+ *
+ * @example
+ * const geo = await roundedBoxGeo(1.2, 0.6, 0.8, 0.05);
+ * createPart('Console', geo, plastic, { position: [0, 0.3, 0], parent: root });
+ *
+ * @example
+ * // Chamfered instead of filleted — reads as machined metal.
+ * const block = await roundedBoxGeo(1, 1, 1, 0.08, { style: 'chamfer' });
+ */
+export async function roundedBoxGeo(
+ width: number,
+ height: number,
+ depth: number,
+ radius: number,
+ options: RoundedBoxOptions = {},
+): Promise<THREE.BufferGeometry> {
+ assertPositive(width, 'roundedBoxGeo: width');
+ assertPositive(height, 'roundedBoxGeo: height');
+ assertPositive(depth, 'roundedBoxGeo: depth');
+ assertPositive(radius, 'roundedBoxGeo: radius');
+ const { style = 'round', segments = 12, smooth } = options;
+
+ const smallest = Math.min(width, height, depth);
+ if (radius >= smallest / 2) {
+ throw new Error(
+ `roundedBoxGeo: radius ${radius} must be less than half the smallest dimension ` +
+ `(${smallest} / 2 = ${smallest / 2}). A larger radius has no box left to round.`,
+ );
+ }
+
+ const mod = await getManifoldModule();
+ const ManifoldCls = mod.Manifold;
+ const parts: Manifold[] = [];
+
+ try {
+ let solid: Manifold;
+ if (style === 'round') {
+ // Hull of eight spheres inset by the radius: exact outer size, every
+ // edge and corner filleted.
+ const corners: Manifold[] = [];
+ for (const sx of [-1, 1]) {
+ for (const sy of [-1, 1]) {
+ for (const sz of [-1, 1]) {
+ const s = ManifoldCls.sphere(radius, segments).translate([
+ (sx * (width - 2 * radius)) / 2,
+ (sy * (height - 2 * radius)) / 2,
+ (sz * (depth - 2 * radius)) / 2,
+ ]);
+ parts.push(s);
+ corners.push(s);
+ }
+ }
+ }
+ solid = ManifoldCls.hull(corners);
+ } else if (style === 'chamfer') {
+ // Hull of three interlocking boxes: each of the twelve edges becomes a
+ // 45-degree flat, each corner a triangle. No rounding, no extra segments.
+ const boxes = [
+ ManifoldCls.cube([width, height - 2 * radius, depth - 2 * radius], true),
+ ManifoldCls.cube([width - 2 * radius, height, depth - 2 * radius], true),
+ ManifoldCls.cube([width - 2 * radius, height - 2 * radius, depth], true),
+ ];
+ parts.push(...boxes);
+ solid = ManifoldCls.hull(boxes);
+ } else {
+ throw new Error(`roundedBoxGeo: style must be 'round' or 'chamfer' (got ${String(style)}).`);
+ }
+
+ try {
+ return manifoldToGeometry(solid, { smooth: smooth ?? style === 'round' });
+ } finally {
+ solid.delete();
+ }
+ } finally {
+ for (const p of parts) p.delete();
+ }
+}
+
+/**
+ * A closed circular outline, for feeding `extrudeProfile` / `revolveProfile`
+ * holes and outlines without hand-writing trigonometry.
+ *
+ * @example
+ * const washer = await extrudeProfile(circleProfile(1), {
+ * depth: 0.1,
+ * holes: [circleProfile(0.4)],
+ * });
+ */
+export function circleProfile(
+ radius: number,
+ segments = 24,
+ center: [number, number] = [0, 0],
+): Profile2D {
+ assertPositive(radius, 'circleProfile: radius');
+ if (!Number.isInteger(segments) || segments < 3) {
+ throw new Error(`circleProfile: segments must be an integer >= 3 (got ${segments}).`);
+ }
+ const out: Profile2D = [];
+ for (let i = 0; i < segments; i++) {
+ const t = (i / segments) * Math.PI * 2;
+ out.push([center[0] + Math.cos(t) * radius, center[1] + Math.sin(t) * radius]);
+ }
+ return out;
+}
diff --git a/src/prompt.ts b/src/prompt.ts
index 967101e9..869ebc14 100644
--- a/src/prompt.ts
+++ b/src/prompt.ts
@@ -95,7 +95,8 @@ const meta = { name: "AssetName", category: "prop", role: "prop" };
// "ground" | "building" | "wonder" | "poi" | "prop" | "fill" | "vehicle".
// build() may be sync OR async. Mark it async if you use any CSG op
-// (boolUnion / boolDiff / boolIntersect / hull) because those await WASM.
+// (boolUnion / boolDiff / boolIntersect / hull) or any bevel/sweep op
+// (roundedBoxGeo / extrudeProfile / revolveProfile) because those await WASM.
function build() { // simple, no CSG
const root = createRoot("AssetName");
return root;
@@ -707,6 +708,11 @@ The sandbox exposes ~70 primitive helpers as globals (no imports), grouped:
- Materials: gameMaterial, glassMaterial, lambertMaterial, basicMaterial, pbrMaterial
- Repetition: createInstance, arrayLinear, arrayRadial, mirror
- CSG (async build() required): boolUnion, boolDiff, boolIntersect, hull
+- Bevel & sweeps (async build() required): roundedBoxGeo (all 12 edges rounded
+ or chamfered, exact outer size — prefer over boxGeo for anything moulded,
+ cast, or machined), extrudeProfile (any 2D outline -> solid, with holes,
+ corner bevel, twist, taper), revolveProfile (solid lathe with a bevelled
+ rim), circleProfile (sync outline helper)
- Mesh ops & curves: subdivide, mergeVertices, curveToMesh, pipeAlongPath, lathe, revolveGeo
- UV + textures: autoUnwrap, boxUnwrap, cylinderUnwrap, planeUnwrap, panelRemapV, loadTexture
- Animation: rotationTrack/positionTrack/scaleTrack (keys are "rotation"/"position"/"scale",
diff --git a/src/solids.ts b/src/solids.ts
index b6cafdbf..753f5069 100644
--- a/src/solids.ts
+++ b/src/solids.ts
@@ -31,7 +31,11 @@ import type { ManifoldToplevel, Manifold, Mesh } from 'manifold-3d';
let _module: ManifoldToplevel | null = null;
let _initPromise: Promise<ManifoldToplevel> | null = null;
-async function getManifoldModule(): Promise<ManifoldToplevel> {
+/**
+ * @internal — shared with `profile.ts` so the extrude/revolve/bevel ops reuse
+ * this one WASM instance instead of initialising a second one.
+ */
+export async function getManifoldModule(): Promise<ManifoldToplevel> {
if (_module) return _module;
if (_initPromise) return _initPromise;
@@ -123,6 +127,24 @@ function manifoldToThree(
name: string,
opts: { smooth?: boolean } = {},
): THREE.Mesh {
+ const out = new THREE.Mesh(manifoldToGeometry(m, opts), material);
+ out.name = name;
+ return out;
+}
+
+/**
+ * Manifold -> BufferGeometry, with the same flat/smooth normal contract as
+ * `manifoldToThree`. Split out so `profile.ts` shares the bridge.
+ *
+ * As with every manifold-backed op, **only positions survive** — normals are
+ * regenerated here and UVs are not carried at all.
+ *
+ * @internal
+ */
+export function manifoldToGeometry(
+ m: Manifold,
+ opts: { smooth?: boolean } = {},
+): THREE.BufferGeometry {
const mesh = m.getMesh();
const numProp = mesh.numProp;
const verts = mesh.vertProperties;
@@ -142,18 +164,12 @@ function manifoldToThree(
if (opts.smooth) {
geo.computeVertexNormals();
- } else {
- // Flat: duplicate verts per triangle so each face gets its own normal.
- const flat = geo.toNonIndexed();
- flat.computeVertexNormals();
- const out = new THREE.Mesh(flat, material);
- out.name = name;
- return out;
+ return geo;
}
-
- const out = new THREE.Mesh(geo, material);
- out.name = name;
- return out;
+ // Flat: duplicate verts per triangle so each face gets its own normal.
+ const flat = geo.toNonIndexed();
+ flat.computeVertexNormals();
+ return flat;
}
/**