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.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat(kiln): Round 1 primitive fixes + security hardening
Matt Kissingerb7b8f8717003
diff --git a/__tests__/gears.test.ts b/__tests__/gears.test.tsnew file mode 100644index 00000000..e62eb5aa--- /dev/null+++ b/__tests__/gears.test.ts@@ -0,0 +1,135 @@+/**+ * gearGeo + bladeGeo parametric primitives — Round 1 Task 3/4+ */++import { describe, it, expect } from 'bun:test';+import * as THREE from 'three';+import { gearGeo, bladeGeo } from '../gears';++function bbox(geo: THREE.BufferGeometry) {+ geo.computeBoundingBox();+ return geo.boundingBox!;+}++describe('gearGeo', () => {+ it('produces a flat-shaded, non-indexed gear with sensible tri count', () => {+ const g = gearGeo({ teeth: 12 });+ expect(g.index).toBeNull();+ const pos = g.getAttribute('position') as THREE.BufferAttribute;+ // N = 4*teeth = 48. Triangles: 2 caps × N quads × 2 tris + 2 walls × N × 2 = 8N = 384 tris.+ // Non-indexed: 384 tris × 3 verts = 1152 verts.+ expect(pos.count).toBe(8 * 4 * 12 * 3);+ const norm = g.getAttribute('normal') as THREE.BufferAttribute;+ expect(norm).toBeDefined();+ expect(norm.count).toBe(pos.count);+ });++ it('bounding box is bounded by tipRadius and height', () => {+ const g = gearGeo({ teeth: 12, tipRadius: 1.0, rootRadius: 0.8, height: 0.3 });+ const b = bbox(g);+ // tooth-tip polar positions are offset from the cardinal axes by+ // alpha = (1-toothWidthFrac) * π/N ≈ 7.5°, so the extremal X/Z is+ // ≤ tipRadius (but close). With 12 teeth, max ≈ cos(7.5°) ≈ 0.991.+ expect(b.max.x).toBeGreaterThan(0.95);+ expect(b.max.x).toBeLessThanOrEqual(1.0);+ expect(b.min.x).toBeGreaterThanOrEqual(-1.0);+ expect(b.min.x).toBeLessThan(-0.95);+ expect(b.max.z).toBeGreaterThan(0.95);+ expect(b.max.z).toBeLessThanOrEqual(1.0);+ expect(b.min.z).toBeGreaterThanOrEqual(-1.0);+ expect(b.min.z).toBeLessThan(-0.95);+ expect(b.min.y).toBeCloseTo(-0.15, 3);+ expect(b.max.y).toBeCloseTo(0.15, 3);+ });++ it('bore is respected (no verts inside boreRadius)', () => {+ const boreR = 0.3;+ const g = gearGeo({ teeth: 10, boreRadius: boreR, rootRadius: 0.7, tipRadius: 0.9 });+ const pos = g.getAttribute('position') as THREE.BufferAttribute;+ let minR = Infinity;+ for (let i = 0; i < pos.count; i++) {+ const x = pos.getX(i);+ const z = pos.getZ(i);+ const r = Math.hypot(x, z);+ if (r < minR) minR = r;+ }+ // min radius of any vertex should be ≈ boreRadius.+ expect(minR).toBeCloseTo(boreR, 2);+ });++ it('rejects invalid params', () => {+ expect(() => gearGeo({ teeth: 2 })).toThrow(/teeth must be >= 3/);+ expect(() => gearGeo({ tipRadius: 0.5, rootRadius: 0.8 })).toThrow(/tipRadius/);+ expect(() => gearGeo({ boreRadius: 1.0, rootRadius: 0.8 })).toThrow(/boreRadius/);+ });+});++describe('bladeGeo', () => {+ it('flat blade: bbox is [-w/2..+w/2, 0..length, -t/2..+t/2]', () => {+ const b = bladeGeo({ length: 1.5, baseWidth: 0.1, thickness: 0.02, tipLength: 0.25 });+ const bb = bbox(b);+ expect(bb.min.x).toBeCloseTo(-0.05, 3);+ expect(bb.max.x).toBeCloseTo(0.05, 3);+ expect(bb.min.y).toBeCloseTo(0, 3);+ expect(bb.max.y).toBeCloseTo(1.5, 3);+ expect(bb.min.z).toBeCloseTo(-0.01, 3);+ expect(bb.max.z).toBeCloseTo(0.01, 3);+ });++ it('tip tapers to a point (width at tip = 0)', () => {+ const b = bladeGeo({ length: 1.5, baseWidth: 0.1, tipLength: 0.25 });+ const pos = b.getAttribute('position') as THREE.BufferAttribute;+ // Find verts at the very tip (y = length).+ const tipVerts: Array<{ x: number; z: number }> = [];+ for (let i = 0; i < pos.count; i++) {+ if (Math.abs(pos.getY(i) - 1.5) < 1e-4) {+ tipVerts.push({ x: pos.getX(i), z: pos.getZ(i) });+ }+ }+ expect(tipVerts.length).toBeGreaterThan(0);+ // All tip verts are on the centerline (x = 0).+ for (const v of tipVerts) {+ expect(v.x).toBeCloseTo(0, 4);+ }+ });++ it('bevelled blade has a centerline ridge at z = 0', () => {+ const b = bladeGeo({ edgeBevel: 1 }); // full diamond: ridge pinches to z=0+ const pos = b.getAttribute('position') as THREE.BufferAttribute;+ // The ridge z-value in a full diamond is 0. Look for any vert with |z| < 1e-6 at a profile corner (base, shoulder, or tip).+ let foundRidge = false;+ for (let i = 0; i < pos.count; i++) {+ if (Math.abs(pos.getZ(i)) < 1e-6) {+ foundRidge = true;+ break;+ }+ }+ expect(foundRidge).toBe(true);+ });++ it('flat blade has no verts at z = 0 (no ridge)', () => {+ const b = bladeGeo({ edgeBevel: 0 });+ const pos = b.getAttribute('position') as THREE.BufferAttribute;+ let hasRidge = false;+ for (let i = 0; i < pos.count; i++) {+ if (Math.abs(pos.getZ(i)) < 1e-6) {+ hasRidge = true;+ break;+ }+ }+ // Flat cross-section has all verts at z = ±thickness/2.+ expect(hasRidge).toBe(false);+ });++ it('rejects invalid params', () => {+ expect(() => bladeGeo({ length: 0 })).toThrow();+ expect(() => bladeGeo({ length: 1, tipLength: 1 })).toThrow(/tipLength/);+ });++ it('is flat-shaded (non-indexed with per-triangle normals)', () => {+ const b = bladeGeo();+ expect(b.index).toBeNull();+ const norm = b.getAttribute('normal') as THREE.BufferAttribute;+ expect(norm).toBeDefined();+ });+});diff --git a/__tests__/ops.test.ts b/__tests__/ops.test.tsnew file mode 100644index 00000000..6c679acb--- /dev/null+++ b/__tests__/ops.test.ts@@ -0,0 +1,118 @@+/**+ * Kiln mesh ops tests — Round 1+ *+ * Covers mergeVertices + subdivide interaction. Array/mirror/curve ops are+ * covered by validation scripts (no separate unit tests yet).+ */++import { describe, it, expect } from 'bun:test';+import * as THREE from 'three';+import { boxGeo, sphereGeo } from '../primitives';+import { mergeVertices, subdivide } from '../ops';++describe('mergeVertices', () => {+ it('default (attribute-aware) preserves per-face normal splits', () => {+ const box = boxGeo(1, 1, 1);+ expect((box.getAttribute('position') as THREE.BufferAttribute).count).toBe(24);+ const welded = mergeVertices(box);+ // 24 stays 24 — each face keeps its own normals/UVs.+ const after = (welded.getAttribute('position') as THREE.BufferAttribute).count;+ expect(after).toBe(24);+ expect(welded.index).not.toBeNull();+ });++ it('positionOnly welds BoxGeometry corners down to 8', () => {+ const box = boxGeo(1, 1, 1);+ const welded = mergeVertices(box, { positionOnly: true });+ const after = (welded.getAttribute('position') as THREE.BufferAttribute).count;+ expect(after).toBe(8);+ expect(welded.index).not.toBeNull();+ expect(welded.index!.count).toBe(36);+ // Other attributes are dropped — caller is expected to recompute.+ expect(welded.getAttribute('normal')).toBeUndefined();+ expect(welded.getAttribute('uv')).toBeUndefined();+ });++ it('accepts legacy numeric tolerance arg for backward compat', () => {+ const box = boxGeo(1, 1, 1);+ const welded = mergeVertices(box, 1e-4);+ expect((welded.getAttribute('position') as THREE.BufferAttribute).count).toBe(24);+ });++ it('does not mutate the input', () => {+ const input = boxGeo(1, 1, 1);+ const beforeIndex = input.index;+ const beforeCount = (input.getAttribute('position') as THREE.BufferAttribute).count;+ mergeVertices(input, { positionOnly: true });+ expect(input.index).toBe(beforeIndex);+ expect((input.getAttribute('position') as THREE.BufferAttribute).count).toBe(beforeCount);+ });++ it('collapses poles on a SphereGeometry under positionOnly weld', () => {+ const s = sphereGeo(1, 8, 6);+ const before = (s.getAttribute('position') as THREE.BufferAttribute).count;+ const welded = mergeVertices(s, { positionOnly: true });+ const after = (welded.getAttribute('position') as THREE.BufferAttribute).count;+ expect(after).toBeLessThan(before);+ });+});++describe('subdivide auto-weld', () => {+ it('keeps deformed corners connected (rock-smooth fix)', () => {+ // Repro of the rock-smooth audit failure: jitter positions of a+ // non-indexed box then subdivide. Without weld, each corner exists+ // 3x (one per face) and jitter drifts them apart — three-subdivide's+ // position-hash adjacency breaks and the surface splits into shards.+ // With weld (positionOnly) applied first, each corner moves once and+ // the mesh stays one connected blob.+ const base = boxGeo(1.2, 0.8, 1);+ const pos = base.getAttribute('position') as THREE.BufferAttribute;+ // Deterministic "jitter"+ const rng = (seed: number) => {+ let s = seed >>> 0;+ return () => {+ s = (s * 1664525 + 1013904223) >>> 0;+ return (s / 0xffffffff - 0.5) * 0.2;+ };+ };+ const rand = rng(42);+ for (let i = 0; i < pos.count; i++) {+ pos.setXYZ(i, pos.getX(i) + rand(), pos.getY(i) + rand(), pos.getZ(i) + rand());+ }++ const smoothed = subdivide(base, 1); // auto-welds first++ // Count distinct position clusters: mergeVertices({positionOnly}) on+ // the subdivided output collapses coincident verts. A connected surface+ // has indices that reach every cluster.+ const collapsed = mergeVertices(smoothed, { positionOnly: true });+ const clusters = (collapsed.getAttribute('position') as THREE.BufferAttribute).count;++ // Sanity: collapsed result has verts, and substantially fewer than+ // the non-indexed vertex buffer (proving shared corners exist).+ const subVerts = (smoothed.getAttribute('position') as THREE.BufferAttribute).count;+ expect(clusters).toBeGreaterThan(0);+ expect(clusters).toBeLessThan(subVerts);+ });++ it('weld: false disables the auto-merge (legacy behavior)', () => {+ const box = boxGeo(1, 1, 1);+ const legacy = subdivide(box, 1, { weld: false });+ const auto = subdivide(box, 1);+ const legacyVerts = (legacy.getAttribute('position') as THREE.BufferAttribute).count;+ const autoVerts = (auto.getAttribute('position') as THREE.BufferAttribute).count;+ // The welded path produces ≤ verts because corners are shared.+ expect(autoVerts).toBeLessThanOrEqual(legacyVerts);+ });++ it('preserves geometry survival through GLB export after welded subdivide', () => {+ const sub = subdivide(boxGeo(1, 1, 1), 1);+ const pos = sub.getAttribute('position') as THREE.BufferAttribute;+ // Positions finite, no NaN+ for (let i = 0; i < pos.count; i++) {+ expect(Number.isFinite(pos.getX(i))).toBe(true);+ expect(Number.isFinite(pos.getY(i))).toBe(true);+ expect(Number.isFinite(pos.getZ(i))).toBe(true);+ }+ });+});diff --git a/__tests__/solids.test.ts b/__tests__/solids.test.tsindex e22268f0..dff9c5f5 100644--- a/__tests__/solids.test.ts+++ b/__tests__/solids.test.ts@@ -39,8 +39,11 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {const hole = new THREE.Mesh(cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000));const pierced = await boolDiff('Pierced', body, hole);- const piercedTris =- (pierced.geometry.getIndex()?.count ?? 0) / 3;+ // Default output is flat-shaded (non-indexed): count positions/3.+ const posCount = (pierced.geometry.getAttribute('position') as THREE.BufferAttribute).count;+ const piercedTris = pierced.geometry.index+ ? pierced.geometry.index.count / 3+ : posCount / 3;// A pierced box has more triangles than a plain box (12).expect(piercedTris).toBeGreaterThan(12);});@@ -99,4 +102,44 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {boolUnion('X', new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000)))).rejects.toThrow(/at least two/);});++ it('flat shading (default) produces non-indexed output with per-face normals', async () => {+ const body = new THREE.Mesh(boxGeo(2, 2, 2), gameMaterial(0x888888));+ const hole = new THREE.Mesh(cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000));+ const pierced = await boolDiff('Pierced', body, hole);+ // Flat-shaded output is non-indexed: each triangle has 3 unique verts+ // so normals stay per-face.+ expect(pierced.geometry.index).toBeNull();+ const norm = pierced.geometry.getAttribute('normal') as THREE.BufferAttribute;+ expect(norm).toBeDefined();+ });++ it('smooth shading preserves indexed output and averages normals', async () => {+ const body = new THREE.Mesh(boxGeo(2, 2, 2), gameMaterial(0x888888));+ const hole = new THREE.Mesh(cylinderGeo(0.4, 0.4, 3, 16), gameMaterial(0x000000));+ const pierced = await boolDiff('Pierced', body, hole, { smooth: true });+ expect(pierced.geometry.index).not.toBeNull();+ });++ it('hull defaults to smooth (organic wrapping shapes)', async () => {+ const parts: THREE.Mesh[] = [];+ for (let i = 0; i < 4; i++) {+ const b = new THREE.Mesh(boxGeo(0.2, 0.2, 0.2), gameMaterial(0x6699cc));+ b.position.set(Math.cos(i) * 0.8, Math.sin(i) * 0.8, 0);+ parts.push(b);+ }+ const wrapped = await hull('Cluster', ...parts);+ expect(wrapped.geometry.index).not.toBeNull();+ });++ it('hull can be opted into flat shading', async () => {+ const parts: THREE.Mesh[] = [];+ for (let i = 0; i < 4; i++) {+ const b = new THREE.Mesh(boxGeo(0.2, 0.2, 0.2), gameMaterial(0x6699cc));+ b.position.set(Math.cos(i) * 0.8, Math.sin(i) * 0.8, 0);+ parts.push(b);+ }+ const wrapped = await hull('Cluster', ...parts, { smooth: false });+ expect(wrapped.geometry.index).toBeNull();+ });});diff --git a/__tests__/uv-shapes.test.ts b/__tests__/uv-shapes.test.tsnew file mode 100644index 00000000..ed9d6003--- /dev/null+++ b/__tests__/uv-shapes.test.ts@@ -0,0 +1,96 @@+/**+ * Shape-aware UV unwraps — Round 1 Task 5+ */++import { describe, it, expect } from 'bun:test';+import * as THREE from 'three';+import { boxGeo, cylinderGeo, planeGeo } from '../primitives';+import { boxUnwrap, cylinderUnwrap, planeUnwrap } from '../uv-shapes';++describe('boxUnwrap', () => {+ it('preserves BoxGeometry per-face [0,1] UVs', () => {+ const b = boxUnwrap(boxGeo(1, 2, 3));+ const uv = b.getAttribute('uv') as THREE.BufferAttribute;+ expect(uv).toBeDefined();+ // Built-in box UVs push (ix/gridX, 1-iy/gridY) — default 1×1 segments+ // means each face has 4 verts at corners (0,0), (0,1), (1,0), (1,1).+ const uniqueUs = new Set<number>();+ const uniqueVs = new Set<number>();+ for (let i = 0; i < uv.count; i++) {+ uniqueUs.add(uv.getX(i));+ uniqueVs.add(uv.getY(i));+ }+ expect(uniqueUs.size).toBe(2);+ expect(uniqueVs.size).toBe(2);+ // All UVs in [0,1].+ for (let i = 0; i < uv.count; i++) {+ expect(uv.getX(i)).toBeGreaterThanOrEqual(0);+ expect(uv.getX(i)).toBeLessThanOrEqual(1);+ expect(uv.getY(i)).toBeGreaterThanOrEqual(0);+ expect(uv.getY(i)).toBeLessThanOrEqual(1);+ }+ });++ it('does not mutate the input', () => {+ const input = boxGeo(1, 1, 1);+ const beforeUv = input.getAttribute('uv');+ boxUnwrap(input);+ expect(input.getAttribute('uv')).toBe(beforeUv);+ });+});++describe('cylinderUnwrap', () => {+ it('preserves CylinderGeometry axial UV layout', () => {+ const c = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));+ const uv = c.getAttribute('uv') as THREE.BufferAttribute;+ expect(uv).toBeDefined();+ // Side verts: v=0 at top, v=1 at bottom; u=0..1 around the circle.+ // We should see both u=0 and u=1 in the attribute (seam verts).+ let minU = Infinity;+ let maxU = -Infinity;+ let minV = Infinity;+ let maxV = -Infinity;+ for (let i = 0; i < uv.count; i++) {+ const u = uv.getX(i);+ const v = uv.getY(i);+ if (u < minU) minU = u;+ if (u > maxU) maxU = u;+ if (v < minV) minV = v;+ if (v > maxV) maxV = v;+ }+ expect(minU).toBeCloseTo(0, 3);+ expect(maxU).toBeCloseTo(1, 3);+ expect(minV).toBeCloseTo(0, 3);+ expect(maxV).toBeCloseTo(1, 3);+ });+});++describe('planeUnwrap', () => {+ it('maps xy bbox to [0,1]', () => {+ const p = planeUnwrap(planeGeo(2, 3));+ const uv = p.getAttribute('uv') as THREE.BufferAttribute;+ expect(uv).toBeDefined();+ // 4 corners: (0,0), (1,0), (0,1), (1,1).+ const pairs = new Set<string>();+ for (let i = 0; i < uv.count; i++) {+ pairs.add(`${uv.getX(i).toFixed(3)},${uv.getY(i).toFixed(3)}`);+ }+ expect(pairs.has('0.000,0.000')).toBe(true);+ expect(pairs.has('1.000,0.000')).toBe(true);+ expect(pairs.has('0.000,1.000')).toBe(true);+ expect(pairs.has('1.000,1.000')).toBe(true);+ });++ it('works on a thin boxGeo (sign use case)', () => {+ const sign = planeUnwrap(boxGeo(1, 0.6, 0.05));+ const uv = sign.getAttribute('uv') as THREE.BufferAttribute;+ expect(uv).toBeDefined();+ // All UVs still in [0,1]; xy extent respected.+ for (let i = 0; i < uv.count; i++) {+ expect(uv.getX(i)).toBeGreaterThanOrEqual(0);+ expect(uv.getX(i)).toBeLessThanOrEqual(1);+ expect(uv.getY(i)).toBeGreaterThanOrEqual(0);+ expect(uv.getY(i)).toBeLessThanOrEqual(1);+ }+ });+});diff --git a/gears.ts b/gears.tsnew file mode 100644index 00000000..d5b050e2--- /dev/null+++ b/gears.ts@@ -0,0 +1,346 @@+/**+ * Parametric gear / blade geometry — Round 1+ *+ * Game-asset-grade (not real involute profiles). Built directly from+ * triangulated polygons, no CSG, no WASM. Fast and cheap.+ */++import * as THREE from 'three';++// =============================================================================+// gearGeo+// =============================================================================++export interface GearOptions {+ /** Number of teeth around the rim. Default 12. */+ teeth?: number;+ /** Radius at the valley between teeth. Default 0.8. */+ rootRadius?: number;+ /** Radius at the tip of each tooth. Default 1.0. */+ tipRadius?: number;+ /** Radius of the center bore (0 = no hole). Default 0.2. */+ boreRadius?: number;+ /** Thickness along Y. Default 0.3. */+ height?: number;+ /**+ * Fraction of each tooth sector occupied by the tooth itself (0..1).+ * 0.5 = tooth and valley equally wide. Default 0.5.+ */+ toothWidthFrac?: number;+}++/**+ * Build a stylized gear directly — no CSG required.+ *+ * Geometry: for each tooth i ∈ [0, N):+ * - the sector from θ = i·(2π/N) to (i+1)·(2π/N) is split at four angles+ * → valley-start, tooth-start, tooth-end, valley-end+ * - alternating radii root/tip/tip/root trace the crown profile+ * The profile is then extruded along Y and capped on both ends as an annulus+ * fan (a center bore is triangulated as a concentric inner ring).+ *+ * @example+ * const g = gearGeo({ teeth: 12 });+ * const mat = gameMaterial(0x909090, { metalness: 0.8, roughness: 0.3 });+ * createPart('Gear', g, mat, { parent: root });+ */+export function gearGeo(opts: GearOptions = {}): THREE.BufferGeometry {+ const {+ teeth = 12,+ rootRadius = 0.8,+ tipRadius = 1.0,+ boreRadius = 0.2,+ height = 0.3,+ toothWidthFrac = 0.5,+ } = opts;++ if (teeth < 3) throw new Error('gearGeo: teeth must be >= 3');+ if (tipRadius <= rootRadius) throw new Error('gearGeo: tipRadius must exceed rootRadius');+ if (boreRadius >= rootRadius) throw new Error('gearGeo: boreRadius must be less than rootRadius');++ // Crown (outer) ring: 4 points per tooth around XZ plane.+ // α = half-width of the valley within each sector (so the tooth spans+ // the central toothWidthFrac of the sector).+ const sector = (Math.PI * 2) / teeth;+ const alpha = (1 - toothWidthFrac) * (sector / 2);++ // Build the 4N outer crown points in the XZ plane (y = 0 as extrusion base).+ type V2 = [number, number];+ const crown: V2[] = [];+ for (let i = 0; i < teeth; i++) {+ const base = i * sector;+ const a0 = base; // valley start+ const a1 = base + alpha; // tooth start+ const a2 = base + sector - alpha; // tooth end+ const a3 = base + sector; // valley end (= next valley start, handled by next iter)+ crown.push([rootRadius * Math.cos(a0), rootRadius * Math.sin(a0)]);+ crown.push([tipRadius * Math.cos(a1), tipRadius * Math.sin(a1)]);+ crown.push([tipRadius * Math.cos(a2), tipRadius * Math.sin(a2)]);+ crown.push([rootRadius * Math.cos(a3), rootRadius * Math.sin(a3)]);+ }+ const N = crown.length; // 4 * teeth++ // Bore (inner) ring: one point per crown point so cap triangulation is a+ // clean strip between concentric rings. N points on a circle of boreRadius.+ const bore: V2[] = [];+ for (let i = 0; i < N; i++) {+ const t = (i / N) * Math.PI * 2;+ bore.push([boreRadius * Math.cos(t), boreRadius * Math.sin(t)]);+ }++ const halfH = height / 2;++ // Vertex layout:+ // [0 .. N-1] crown top+ // [N .. 2N-1] crown bottom+ // [2N .. 3N-1] bore top+ // [3N .. 4N-1] bore bottom+ const positions: number[] = [];+ const indices: number[] = [];++ for (let i = 0; i < N; i++) {+ const p = crown[i]!;+ positions.push(p[0], halfH, p[1]);+ }+ for (let i = 0; i < N; i++) {+ const p = crown[i]!;+ positions.push(p[0], -halfH, p[1]);+ }+ for (let i = 0; i < N; i++) {+ const p = bore[i]!;+ positions.push(p[0], halfH, p[1]);+ }+ for (let i = 0; i < N; i++) {+ const p = bore[i]!;+ positions.push(p[0], -halfH, p[1]);+ }++ const crownTop = 0;+ const crownBot = N;+ const boreTop = 2 * N;+ const boreBot = 3 * N;++ // Top cap: annulus between boreTop and crownTop (CCW seen from +Y).+ for (let i = 0; i < N; i++) {+ const j = (i + 1) % N;+ const cA = crownTop + i;+ const cB = crownTop + j;+ const bA = boreTop + i;+ const bB = boreTop + j;+ // Quad (bA, bB, cB, cA) → two tris, CCW from +Y+ indices.push(bA, cA, cB);+ indices.push(bA, cB, bB);+ }++ // Bottom cap: annulus (CCW seen from -Y, i.e. reversed winding)+ for (let i = 0; i < N; i++) {+ const j = (i + 1) % N;+ const cA = crownBot + i;+ const cB = crownBot + j;+ const bA = boreBot + i;+ const bB = boreBot + j;+ indices.push(bA, cB, cA);+ indices.push(bA, bB, cB);+ }++ // Outer side wall: rectangle between crownTop[i] → crownTop[i+1] → crownBot[i+1] → crownBot[i]+ for (let i = 0; i < N; i++) {+ const j = (i + 1) % N;+ const tA = crownTop + i;+ const tB = crownTop + j;+ const bA = crownBot + i;+ const bB = crownBot + j;+ indices.push(tA, bA, bB);+ indices.push(tA, bB, tB);+ }++ // Inner side wall (bore cylinder): reversed winding since the bore+ // surface faces inward toward the axis.+ for (let i = 0; i < N; i++) {+ const j = (i + 1) % N;+ const tA = boreTop + i;+ const tB = boreTop + j;+ const bA = boreBot + i;+ const bB = boreBot + j;+ indices.push(tA, bB, bA);+ indices.push(tA, tB, bB);+ }++ const geo = new THREE.BufferGeometry();+ geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));+ geo.setIndex(indices);+ // Flat shading → each face gets its own normal (hard mechanical edges).+ const nonIndexed = geo.toNonIndexed();+ nonIndexed.computeVertexNormals();+ return nonIndexed;+}++// =============================================================================+// bladeGeo+// =============================================================================++export interface BladeOptions {+ /** Total blade length along +Y. Default 1.5. */+ length?: number;+ /** Width at the guard (base). Default 0.1. */+ baseWidth?: number;+ /** Cross-section thickness along Z. Default 0.015. */+ thickness?: number;+ /** Length of the tapered tip section at the top. Default 0.25. */+ tipLength?: number;+ /**+ * 0..1 — cross-section bevel. 0 = flat rectangle; 1 = diamond (centerline+ * ridge). Default 0 (flat) for simplicity; 0.5 for a bevelled edge.+ */+ edgeBevel?: number;+}++/**+ * Build a game-grade sword blade: tapered profile from base to shoulder,+ * then shoulder to tip point. Cross-section is a flat rectangle or an+ * optional diamond (edgeBevel > 0).+ *+ * Origin is at (0, 0, 0) = the base of the blade (guard side). Tip is at+ * (0, length, 0). Center the blade on the grip by translating after.+ *+ * @example+ * const b = bladeGeo({ length: 1.5, baseWidth: 0.08, tipLength: 0.3 });+ * createPart('Blade', b, steelMat, { position: [0, 0, 0], parent: root });+ */+export function bladeGeo(opts: BladeOptions = {}): THREE.BufferGeometry {+ const {+ length = 1.5,+ baseWidth = 0.1,+ thickness = 0.015,+ tipLength = 0.25,+ edgeBevel = 0,+ } = opts;++ if (length <= 0 || baseWidth <= 0 || thickness <= 0) {+ throw new Error('bladeGeo: length, baseWidth, thickness must all be > 0');+ }+ if (tipLength >= length) {+ throw new Error('bladeGeo: tipLength must be less than length');+ }++ const hw = baseWidth / 2;+ const ht = thickness / 2;+ const shoulderY = length - tipLength;++ // 5-point outline in the XY plane (top surface of the blade looking down+ // from +Z). Outline traced CCW for a +Z-facing top.+ // base-left → base-right → shoulder-right → tip → shoulder-left+ const outline: Array<[number, number]> = [+ [-hw, 0],+ [hw, 0],+ [hw, shoulderY],+ [0, length],+ [-hw, shoulderY],+ ];+ const n = outline.length; // 5++ // If edgeBevel = 0, build a prism: extrude the outline by ±thickness/2.+ // If edgeBevel > 0, add a centerline ridge on each side that pinches+ // inward from the full thickness toward the edge of the outline.+ const positions: number[] = [];+ const indices: number[] = [];++ if (edgeBevel <= 0) {+ // ----- Flat-profile prism -----+ // verts: 0..n-1 = top (+Z), n..2n-1 = bottom (-Z)+ for (const [x, y] of outline) positions.push(x, y, ht);+ for (const [x, y] of outline) positions.push(x, y, -ht);++ // Top face: triangle fan from base-left (idx 0).+ // Outline 0,1,2,3,4 → fan (0,1,2) (0,2,3) (0,3,4).+ for (let i = 1; i < n - 1; i++) {+ indices.push(0, i, i + 1);+ }+ // Bottom face: reversed winding. Indices n..2n-1.+ for (let i = 1; i < n - 1; i++) {+ indices.push(n, n + i + 1, n + i);+ }+ // Side walls: for each outline edge (i, i+1), connect top+bottom.+ for (let i = 0; i < n; i++) {+ const j = (i + 1) % n;+ const tA = i;+ const tB = j;+ const bA = n + i;+ const bB = n + j;+ indices.push(tA, bA, bB);+ indices.push(tA, bB, tB);+ }+ } else {+ // ----- Bevelled (diamond) profile -----+ // For each outline vert, build 4 ring verts:+ // top-flat at (x, y, ht)+ // top-ridge at (x*(1-b), y, ht*(1-b)) // pinched toward centerline+ // Actually simpler: keep (x, y) path, bevel on z-axis:+ // flat verts at z = ±ht and ridge verts at z = 0 along the blade edge.+ // Scheme: at each outline vert i, emit+ // ring[i][0] = top-flat (+z)+ // ring[i][1] = ridge-front (z = +ht * (1 - edgeBevel))+ // ring[i][2] = ridge-back (z = -ht * (1 - edgeBevel))+ // ring[i][3] = bottom-flat (-z)+ // edgeBevel=1 pinches ridge to z=0 (true diamond).+ const zFlat = ht;+ const zRidge = ht * (1 - edgeBevel);+ const vertsPerRing = 4;+ for (const [x, y] of outline) {+ positions.push(x, y, zFlat);+ positions.push(x, y, zRidge);+ positions.push(x, y, -zRidge);+ positions.push(x, y, -zFlat);+ }++ const ringIdx = (i: number, k: number) => i * vertsPerRing + k;++ // Cap at base (y=0, i=0 and i=1 are the two base corners) — simplest+ // to triangulate as a quad between [0,1] ring verts. But a quick hack:+ // triangulate the base edge (between outline[0] and outline[1]) as a+ // rectangular end-cap.+ // Actually the "profile extrusion" approach doesn't have a flat base+ // plane naturally — we fan-cap both outline polygons on each z-layer.+ // For bevelled, do fan-cap on top (zFlat) and bottom (-zFlat) flats,+ // then connect the 4 longitudinal strips.++ // Top-flat cap fan (ring[*][0])+ for (let i = 1; i < n - 1; i++) {+ indices.push(ringIdx(0, 0), ringIdx(i, 0), ringIdx(i + 1, 0));+ }+ // Bottom-flat cap fan (ring[*][3]) — reversed winding+ for (let i = 1; i < n - 1; i++) {+ indices.push(ringIdx(0, 3), ringIdx(i + 1, 3), ringIdx(i, 3));+ }++ // Longitudinal side strips: for each outline edge (i, j=i+1), connect+ // corresponding k-layer pairs into quads.+ // Layers: 0 (top-flat) ↔ 1 (ridge-front) ↔ 3 (bottom-flat, skipping 2 of opposite face? Actually face layers on +z side are 0→1, and on -z are 3→2.)+ // Simpler: treat the 4 ring layers as a tube with quads (0,1), (1,2), (2,3), (3,0).+ const layerPairs: Array<[number, number]> = [+ [0, 1],+ [1, 2],+ [2, 3],+ [3, 0],+ ];+ for (const [kA, kB] of layerPairs) {+ for (let i = 0; i < n; i++) {+ const j = (i + 1) % n;+ const a = ringIdx(i, kA);+ const b = ringIdx(j, kA);+ const c = ringIdx(j, kB);+ const d = ringIdx(i, kB);+ indices.push(a, d, c);+ indices.push(a, c, b);+ }+ }+ }++ const geo = new THREE.BufferGeometry();+ geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));+ geo.setIndex(indices);+ // Flat shading: mechanical edges, crisp tip.+ const nonIndexed = geo.toNonIndexed();+ nonIndexed.computeVertexNormals();+ return nonIndexed;+}diff --git a/index.ts b/index.tsindex e907aa5b..186c0e02 100644--- a/index.ts+++ b/index.ts@@ -99,12 +99,16 @@ export {arrayRadial,mirror,subdivide,+ mergeVertices,curveToMesh,lathe,bezierCurve,} from './ops';export { autoUnwrap } from './uv';export type { AutoUnwrapOptions } from './uv';+export { boxUnwrap, cylinderUnwrap, planeUnwrap } from './uv-shapes';+export { gearGeo, bladeGeo } from './gears';+export type { GearOptions, BladeOptions } from './gears';export { loadTexture, pbrMaterial } from './textures';export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';diff --git a/list-primitives.ts b/list-primitives.tsindex 15aaab29..327cbd9c 100644--- a/list-primitives.ts+++ b/list-primitives.ts@@ -136,6 +136,28 @@ const PRIMITIVES: PrimitiveSpec[] = [description: 'Flat quad. Faces +Z by default. Rotate to use as ground / decal.',example: 'const geo = planeGeo(4, 4);',},+ {+ name: 'gearGeo',+ signature:+ 'gearGeo(opts?: { teeth?: 12, rootRadius?: 0.8, tipRadius?: 1.0, boreRadius?: 0.2, height?: 0.3, toothWidthFrac?: 0.5 })',+ returns: 'THREE.BufferGeometry',+ category: 'geometry',+ description:+ 'Parametric gear: disc with N additive teeth around the rim and a center bore. Flat-shaded hard edges. Built directly (no CSG), so cheap.',+ example:+ "const g = gearGeo({ teeth: 16, tipRadius: 1.0, boreRadius: 0.15, height: 0.25 });\ncreatePart('Gear', g, gameMaterial(0x909090, { metalness: 0.8 }), { parent: root });",+ },+ {+ name: 'bladeGeo',+ signature:+ 'bladeGeo(opts?: { length?: 1.5, baseWidth?: 0.1, thickness?: 0.015, tipLength?: 0.25, edgeBevel?: 0 })',+ returns: 'THREE.BufferGeometry',+ category: 'geometry',+ description:+ 'Parametric sword blade: rectangular base tapering to a point over tipLength. edgeBevel > 0 pinches the cross-section toward a diamond ridge.',+ example:+ "const b = bladeGeo({ length: 1.6, baseWidth: 0.09, tipLength: 0.3, edgeBevel: 0.5 });\ncreatePart('Blade', b, steel, { position: [0, 0, 0], parent: root });",+ },// ---------------------------------------------------------------------------// Materials@@ -285,41 +307,41 @@ const PRIMITIVES: PrimitiveSpec[] = [// these ops are WASM-backed. The executor awaits build() transparently.{name: 'boolUnion',- signature: 'await boolUnion(name: string, ...parts: Object3D[])',+ signature: 'await boolUnion(name: string, ...parts: Object3D[], opts?: { smooth?: false })',returns: 'Promise<THREE.Mesh>',category: 'csg',description:- 'Merges two or more parts into one watertight manifold mesh. Inherits material from the first operand.',+ 'Merges two or more parts into one watertight manifold mesh. Default flat shading (hard edges) — pass { smooth: true } as last arg for averaged normals on organic merges.',example:"const body = new THREE.Mesh(boxGeo(2, 1, 1), steel);\nconst turret = new THREE.Mesh(cylinderGeo(0.3, 0.3, 0.4, 16), steel);\nturret.position.y = 0.5;\nconst hull = await boolUnion('Hull', body, turret);",},{name: 'boolDiff',- signature: 'await boolDiff(name: string, body: Object3D, ...cutters: Object3D[])',+ signature: 'await boolDiff(name: string, body: Object3D, ...cutters: Object3D[], opts?: { smooth?: false })',returns: 'Promise<THREE.Mesh>',category: 'csg',description:- 'Subtracts one or more cutters from a body. Use to carve holes, button recesses, window slots, bolt mounts.',+ 'Subtracts cutters from a body (holes, button recesses, window slots). Default flat shading for sharp mechanical edges.',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);",+ "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: 'boolIntersect',- signature: 'await boolIntersect(name: string, a: Object3D, b: Object3D)',+ signature: 'await boolIntersect(name: string, a: Object3D, b: Object3D, opts?: { smooth?: false })',returns: 'Promise<THREE.Mesh>',category: 'csg',description:- 'Keeps only the volume where both operands overlap. Less common than union/diff but useful for lens shapes and trim cuts.',+ 'Keeps only the volume where both operands overlap. Default flat shading.',example:"const lens = await boolIntersect('Lens', boxMesh, sphereMesh);",},{name: 'hull',- signature: 'await hull(name: string, ...parts: Object3D[])',+ signature: 'await hull(name: string, ...parts: Object3D[], opts?: { smooth?: true })',returns: 'Promise<THREE.Mesh>',category: 'csg',description:- 'Tightest convex mesh enclosing all input points. Good for simplifying rocks, loose clusters, or collision volumes.',+ 'Tightest convex mesh enclosing all input points. Default smooth shading (rocks, collision volumes). Pass { smooth: false } for a faceted look.',example:"const rockChunks = [...]; // scattered box meshes\nconst rock = await hull('Rock', ...rockChunks);",},@@ -365,13 +387,23 @@ const PRIMITIVES: PrimitiveSpec[] = [{name: 'subdivide',signature:- 'subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { split, uvSmooth, preserveEdges, flatOnly })',+ 'subdivide(geometry: BufferGeometry, iterations?: 1, opts?: { split, uvSmooth, preserveEdges, flatOnly, weld })',returns: 'THREE.BufferGeometry',category: 'mesh-ops',description:- 'Loop subdivision. Each iteration ~4x the triangle count and smooths the surface. Use 1 for mild smoothing, 2 for organic shapes.',+ 'Loop subdivision. Each iteration ~4x the triangle count and smooths the surface. Non-indexed input is auto-welded via mergeVertices (weld: false to skip). Use 1 for mild smoothing, 2 for organic shapes.',example: "const smoothRock = subdivide(boxGeo(1, 1, 1), 2);",},+ {+ name: 'mergeVertices',+ signature: 'mergeVertices(geometry: BufferGeometry, tolerance?: 1e-4)',+ returns: 'THREE.BufferGeometry',+ category: 'mesh-ops',+ description:+ "Welds coincident vertices into shared, indexed ones. Three's primitives emit disconnected per-face strips — call this before subdividing, deforming, or smooth-shading so shared corners move once.",+ example:+ "// Weld before random deformation so corners drift together:\nconst base = mergeVertices(boxGeo(1, 1, 1));\nconst pos = base.getAttribute('position');\nfor (let i = 0; i < pos.count; i++) pos.setXYZ(i, pos.getX(i) + jitter(), pos.getY(i) + jitter(), pos.getZ(i) + jitter());\nconst rock = subdivide(base, 2);",+ },// ---------------------------------------------------------------------------// Curves (Wave 2B)@@ -418,9 +450,39 @@ const PRIMITIVES: PrimitiveSpec[] = [returns: 'Promise<THREE.BufferGeometry>',category: 'uv',description:- "Auto-generates a UV atlas for any BufferGeometry using xatlas. Required before applying textures or projection-baking. Input not mutated; output geometry has fresh uv attribute in [0,1] and atlas metadata on userData.atlas.",+ "xatlas-based UV atlas for ANY geometry (CSG output, subdivided, deformed). Output is a packed atlas with arbitrary per-chart rotation — use for non-tileable baked textures. For directional tileable textures on box/cylinder/plane primitives, prefer the shape-aware unwraps below.",+ example:+ "const unwrapped = await autoUnwrap(someCsgResult, { resolution: 1024 });\nconst mesh = new THREE.Mesh(unwrapped, bakedPbr);",+ },+ {+ name: 'boxUnwrap',+ signature: 'boxUnwrap(geometry: BufferGeometry)',+ returns: 'THREE.BufferGeometry',+ category: 'uv',+ description:+ "Preserves BoxGeometry's built-in per-face UVs — every face maps [0,1] with consistent orientation. Use for crates/blocks with a tileable texture. Sync; no WASM cost.",+ example:+ "const crate = boxUnwrap(boxGeo(1, 1, 1));\nconst mesh = new THREE.Mesh(crate, pbrMaterial({ albedo: planksTex }));",+ },+ {+ name: 'cylinderUnwrap',+ signature: 'cylinderUnwrap(geometry: BufferGeometry)',+ returns: 'THREE.BufferGeometry',+ category: 'uv',+ description:+ "Preserves CylinderGeometry's built-in UVs: u wraps around the axis (horizontal texture features ring the cylinder), v runs up the height. Caps use circle-in-square. Sync; no WASM cost.",+ example:+ "const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));\nconst mesh = new THREE.Mesh(barrel, pbrMaterial({ albedo: bandsTex }));",+ },+ {+ name: 'planeUnwrap',+ signature: 'planeUnwrap(geometry: BufferGeometry)',+ returns: 'THREE.BufferGeometry',+ category: 'uv',+ description:+ "Projects xy-extent of the bbox to [0,1]. Use for signs/decals/posters where you want ONE readable texture and no edge-face bleeding. Sync.",example:- "const unwrapped = await autoUnwrap(boxGeo(1, 2, 1), { resolution: 1024 });\nconst crate = new THREE.Mesh(unwrapped, woodPBR);",+ "const sign = planeUnwrap(planeGeo(1, 0.6));\nconst mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));",},// ---------------------------------------------------------------------------diff --git a/ops.ts b/ops.tsindex 9893cec8..77344afa 100644--- a/ops.ts+++ b/ops.ts@@ -15,6 +15,7 @@import * as THREE from 'three';import { LoopSubdivision } from 'three-subdivide';+import { mergeVertices as threeMergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js';import { createInstance } from './primitives';// =============================================================================@@ -131,6 +132,53 @@ export function mirror(// Mesh ops// =============================================================================+/**+ * Weld coincident vertices into shared indexed ones.+ *+ * Three.js's built-in BoxGeometry / CylinderGeometry / SphereGeometry carry+ * 4 verts per face so per-face normals and UVs stay independent. That's+ * correct for rendering but breaks any op that depends on vertex adjacency+ * — subdivision, smooth shading, per-vertex deformation.+ *+ * By default Three's `mergeVertices` hashes position + normal + uv, so+ * face-adjacent verts with different normals (e.g. a cube corner touching+ * 3 faces) do NOT collapse. Pass `{ positionOnly: true }` to weld purely+ * by position — the other attributes get dropped; the caller is+ * responsible for recomputing normals / UVs afterward.+ *+ * @example+ * // Full weld (preserves seams where normals or UVs differ):+ * const welded = mergeVertices(boxGeo(1, 1, 1)); // stays 24 verts+ *+ * @example+ * // Position-only weld (collapses shared corners for subdivision):+ * const merged = mergeVertices(boxGeo(1, 1, 1), { positionOnly: true }); // 8 verts+ * const smoothed = subdivide(merged, 2); // single connected blob+ */+export function mergeVertices(+ geometry: THREE.BufferGeometry,+ opts: { tolerance?: number; positionOnly?: boolean } | number = {}+): THREE.BufferGeometry {+ // Legacy numeric second-arg still works: mergeVertices(geo, 1e-4)+ const { tolerance = 1e-4, positionOnly = false } =+ typeof opts === 'number' ? { tolerance: opts } : opts;++ if (!positionOnly) return threeMergeVertices(geometry, tolerance);++ // Strip non-position attributes so the hash only keys on position.+ const stripped = new THREE.BufferGeometry();+ const pos = geometry.getAttribute('position') as THREE.BufferAttribute | undefined;+ if (!pos) return geometry;+ stripped.setAttribute(+ 'position',+ new THREE.BufferAttribute(new Float32Array(pos.array), pos.itemSize, pos.normalized)+ );+ if (geometry.index) {+ stripped.setIndex(new THREE.BufferAttribute(new Uint32Array(geometry.index.array), 1));+ }+ return threeMergeVertices(stripped, tolerance);+}+/*** Subdivide a geometry using Loop subdivision (via three-subdivide).* Returns a new BufferGeometry; the input is not mutated.@@ -138,15 +186,30 @@ export function mirror(* Higher `iterations` = smoother but exponentially more triangles.* 1 iteration ~= 4x triangle count, 2 ~= 16x. Budget accordingly.*+ * Non-indexed inputs (Three's built-in primitives) are auto-welded via+ * `mergeVertices` first so shared corners subdivide as one surface, not+ * as disconnected face patches. Pass `opts.weld = false` to skip.+ ** @example* const smoothRock = subdivide(boxGeo(1, 1, 1), 2);*/export function subdivide(geometry: THREE.BufferGeometry,iterations = 1,- opts: { split?: boolean; uvSmooth?: boolean; preserveEdges?: boolean; flatOnly?: boolean } = {}+ opts: {+ split?: boolean;+ uvSmooth?: boolean;+ preserveEdges?: boolean;+ flatOnly?: boolean;+ weld?: boolean;+ } = {}): THREE.BufferGeometry {- return LoopSubdivision.modify(geometry, iterations, opts);+ const { weld = true, ...subOpts } = opts;+ // Subdivision wants position-only adjacency. Weld shared corners so+ // Three's box/sphere/cylinder (which keep 4 verts per face for+ // independent normals/UVs) become a single connected surface.+ const input = weld ? mergeVertices(geometry, { positionOnly: true }) : geometry;+ return LoopSubdivision.modify(input, iterations, subOpts);}// =============================================================================diff --git a/primitives.ts b/primitives.tsindex ea2992d4..5c928f43 100644--- a/primitives.ts+++ b/primitives.ts@@ -525,6 +525,10 @@ export function buildSandboxGlobals(): Record<string, unknown> {// eslint-disable-next-line @typescript-eslint/no-require-importsconst textures = require('./textures') as typeof import('./textures');// eslint-disable-next-line @typescript-eslint/no-require-imports+ const gears = require('./gears') as typeof import('./gears');+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const uvShapes = require('./uv-shapes') as typeof import('./uv-shapes');+ // eslint-disable-next-line @typescript-eslint/no-require-importsconst THREE = require('three') as typeof import('three');return {createRoot, createPivot, createPart,@@ -543,11 +547,19 @@ export function buildSandboxGlobals(): Record<string, unknown> {arrayRadial: ops.arrayRadial,mirror: ops.mirror,subdivide: ops.subdivide,+ mergeVertices: ops.mergeVertices,curveToMesh: ops.curveToMesh,lathe: ops.lathe,bezierCurve: ops.bezierCurve,// UV (async)autoUnwrap: uv.autoUnwrap,+ // Shape-aware unwraps (sync — preserve built-in directional UVs)+ boxUnwrap: uvShapes.boxUnwrap,+ cylinderUnwrap: uvShapes.cylinderUnwrap,+ planeUnwrap: uvShapes.planeUnwrap,+ // Parametric primitives+ gearGeo: gears.gearGeo,+ bladeGeo: gears.bladeGeo,// Textures + PBR (loadTexture is async)loadTexture: textures.loadTexture,pbrMaterial: textures.pbrMaterial,diff --git a/prompt.ts b/prompt.tsindex 23ccc9e5..c60ea076 100644--- a/prompt.ts+++ b/prompt.ts@@ -114,6 +114,8 @@ coneGeo(radius, height, segments=8)capsuleGeo(radius, height, segments=6)torusGeo(radius, tube, radialSegs=8, tubularSegs=12)planeGeo(width, height, widthSegs=1, heightSegs=1)+gearGeo({ teeth=12, rootRadius=0.8, tipRadius=1.0, boreRadius=0.2, height=0.3, toothWidthFrac=0.5 }) // parametric gear, flat-shaded+bladeGeo({ length=1.5, baseWidth=0.1, thickness=0.015, tipLength=0.25, edgeBevel=0 }) // tapered sword blade with pointed tip// MaterialsgameMaterial(0xcolor, {metalness?, roughness?, emissive?, flatShading?})@@ -134,21 +136,27 @@ arrayRadial(namePrefix, source, count, 'x'|'y'|'z', parent?) // returns Object3Dmirror(name, source, 'x'|'y'|'z', parent?) // returns Object3D// CSG / Boolean (async - requires \`async function build()\`)-await boolUnion(name, ...parts) // merge into one watertight mesh-await boolDiff(name, body, ...cutters) // subtract cutters from body (holes, recesses)-await boolIntersect(name, a, b) // keep overlapping volume only-await hull(name, ...parts) // tightest convex hull+// Default: flat shading (hard mechanical edges). Pass { smooth: true }+// as the LAST arg for averaged normals on organic/blended merges.+await boolUnion(name, ...parts, opts?) // merge into one watertight mesh+await boolDiff(name, body, ...cutters, opts?) // subtract cutters from body (holes, recesses)+await boolIntersect(name, a, b, opts?) // keep overlapping volume only+await hull(name, ...parts, opts?) // tightest convex hull (defaults to smooth)// Mesh ops-subdivide(geometry, iterations=1) // Loop subdivision, returns new BufferGeometry+subdivide(geometry, iterations=1) // Loop subdivision, returns new BufferGeometry (auto-welds non-indexed input)+mergeVertices(geometry, tolerance=1e-4) // weld coincident verts; call before deforming/subdividing box/sphere/cylinder// CurvescurveToMesh(points: [x,y,z][], radius, tubularSegs=32, radialSegs=8, closed=false) // returns BufferGeometry (tube)lathe(profile: [x,y][], segments=12) // surface of revolution (vase, wheel, bottle)bezierCurve(ctrlPts: [x,y,z][], samples=32) // returns [x,y,z][] — feed into curveToMesh-// UV + Textures (both async, require \`async function build()\`)-await autoUnwrap(geometry, { resolution?: 1024, padding?: 2 }) // returns BufferGeometry with uv attribute+// UV + Textures (loadTexture is async; shape-aware unwraps are sync)+await autoUnwrap(geometry, { resolution?: 1024, padding?: 2 }) // xatlas atlas — for CSG/subdivided/deformed meshes+boxUnwrap(boxGeo(...)) // preserves per-face [0,1] UVs — crates, blocks+cylinderUnwrap(cylinderGeo(...)) // u around axis, v up — barrels, pipes (texture bands ring the mesh)+planeUnwrap(planeGeo(...)) // xy-extent → [0,1] — signs, decals, postersawait loadTexture(path) // returns THREE.DataTexture with encoded bytes stashed for GLB exportpbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? }) // Any slot = color/scalar OR Texturediff --git a/solids.ts b/solids.tsindex fc82249f..2856e71c 100644--- a/solids.ts+++ b/solids.ts@@ -103,9 +103,21 @@ function threeToManifold(src: THREE.Object3D, ManifoldCls: typeof Manifold, Mesh/*** Convert a Manifold result back to a Three.js Mesh with the given material.- * Regenerates vertex normals (flat shading by default).+ *+ * Default is **flat shading** (one normal per triangle, hard faceted edges)+ * — that's what most mechanical CSG parts (gears, vending machines, carved+ * boxes) want. `computeVertexNormals` on an indexed mesh averages normals+ * across adjacent faces and turns hard edges into smooth blobs.+ *+ * Pass `smooth: true` for organic CSG results (like hulled rocks) where+ * averaged normals read better.*/-function manifoldToThree(m: Manifold, material: THREE.Material, name: string): THREE.Mesh {+function manifoldToThree(+ m: Manifold,+ material: THREE.Material,+ name: string,+ opts: { smooth?: boolean } = {}+): THREE.Mesh {const mesh = m.getMesh();const numProp = mesh.numProp;const verts = mesh.vertProperties;@@ -122,13 +134,47 @@ function manifoldToThree(m: Manifold, material: THREE.Material, name: string): Tconst geo = new THREE.BufferGeometry();geo.setAttribute('position', new THREE.BufferAttribute(positions, 3));geo.setIndex(new THREE.BufferAttribute(new Uint32Array(tris), 1));- geo.computeVertexNormals();++ 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;+ }const out = new THREE.Mesh(geo, material);out.name = name;return out;}+/**+ * Pull a `{smooth}` options object off the end of a variadic part list.+ * Detects a plain object with `smooth` that's NOT an Object3D, so calls+ * like `boolUnion('X', a, b, { smooth: true })` still type-check.+ */+function splitPartsAndOpts(+ parts: Array<THREE.Object3D | { smooth?: boolean }>+): { parts: THREE.Object3D[]; opts: { smooth?: boolean } } {+ if (parts.length === 0) return { parts: [], opts: {} };+ const last = parts[parts.length - 1];+ if (+ last &&+ typeof last === 'object' &&+ !(last instanceof THREE.Object3D) &&+ ('smooth' in last)+ ) {+ return {+ parts: parts.slice(0, -1) as THREE.Object3D[],+ opts: last as { smooth?: boolean },+ };+ }+ return { parts: parts as THREE.Object3D[], opts: {} };+}+function materialOf(src: THREE.Object3D, fallback: THREE.Material): THREE.Material {if (src instanceof THREE.Mesh) return src.material as THREE.Material;let found: THREE.Material | null = null;@@ -146,10 +192,18 @@ function materialOf(src: THREE.Object3D, fallback: THREE.Material): THREE.Materi* Boolean union: combine two or more parts into one watertight mesh.* Inherits material from the first operand.*+ * Default shading is **flat** (hard faceted edges) — pass+ * `{ smooth: true }` as the last arg for averaged smooth normals.+ ** @example* const merged = await boolUnion('Hull', body, turret, barrel);+ * const blob = await boolUnion('Blob', a, b, c, { smooth: true });*/-export async function boolUnion(name: string, ...parts: THREE.Object3D[]): Promise<THREE.Mesh> {+export async function boolUnion(+ name: string,+ ...partsAndOpts: Array<THREE.Object3D | { smooth?: boolean }>+): Promise<THREE.Mesh> {+ const { parts, opts } = splitPartsAndOpts(partsAndOpts);if (parts.length < 2) {throw new Error('boolUnion requires at least two parts');}@@ -157,7 +211,7 @@ export async function boolUnion(name: string, ...parts: THREE.Object3D[]): Promiconst manifolds = parts.map((p) => threeToManifold(p, mod.Manifold, mod.Mesh));const result = mod.Manifold.union(manifolds);const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());- const mesh = manifoldToThree(result, mat, `Mesh_${name}`);+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);manifolds.forEach((m) => m.delete());result.delete();return mesh;@@ -167,14 +221,18 @@ export async function boolUnion(name: string, ...parts: THREE.Object3D[]): Promi* Boolean difference: subtract `cutter` parts from `body`.* Use to carve windows, buttons, grip panels, bolt holes.*+ * Default shading is **flat** (hard faceted edges). Pass+ * `{ smooth: true }` as the last arg for averaged smooth normals.+ ** @example* const gear = await boolDiff('Gear', cylinder, ...teethCutters);*/export async function boolDiff(name: string,body: THREE.Object3D,- ...cutters: THREE.Object3D[]+ ...cuttersAndOpts: Array<THREE.Object3D | { smooth?: boolean }>): Promise<THREE.Mesh> {+ const { parts: cutters, opts } = splitPartsAndOpts(cuttersAndOpts);if (cutters.length < 1) {throw new Error('boolDiff requires at least one cutter');}@@ -185,7 +243,7 @@ export async function boolDiff(cutterM.length === 1 ? (cutterM[0] as Manifold) : mod.Manifold.union(cutterM);const result = bodyM.subtract(cutterUnion);const mat = materialOf(body, new THREE.MeshStandardMaterial());- const mesh = manifoldToThree(result, mat, `Mesh_${name}`);+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);bodyM.delete();cutterM.forEach((m) => m.delete());if (cutterM.length > 1) cutterUnion.delete();@@ -196,18 +254,21 @@ export async function boolDiff(/*** Boolean intersection: keep only the overlapping volume.* Less commonly used in game assets, but handy for complex trim cuts.+ *+ * Default shading is **flat**; pass `{ smooth: true }` for averaged normals.*/export async function boolIntersect(name: string,a: THREE.Object3D,- b: THREE.Object3D+ b: THREE.Object3D,+ opts: { smooth?: boolean } = {}): Promise<THREE.Mesh> {const mod = await getManifoldModule();const aM = threeToManifold(a, mod.Manifold, mod.Mesh);const bM = threeToManifold(b, mod.Manifold, mod.Mesh);const result = aM.intersect(bM);const mat = materialOf(a, new THREE.MeshStandardMaterial());- const mesh = manifoldToThree(result, mat, `Mesh_${name}`);+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);aM.delete();bM.delete();result.delete();@@ -217,8 +278,16 @@ export async function boolIntersect(/*** Convex hull: tightest convex mesh enclosing all points of the inputs.* Good for simplifying collision volumes or wrapping a cluster of parts.+ *+ * Hulls are typically **smooth-shaded** (they're wrapping-shapes, not+ * mechanical), so this default is `smooth: true`. Override with+ * `{ smooth: false }` for a faceted look.*/-export async function hull(name: string, ...parts: THREE.Object3D[]): Promise<THREE.Mesh> {+export async function hull(+ name: string,+ ...partsAndOpts: Array<THREE.Object3D | { smooth?: boolean }>+): Promise<THREE.Mesh> {+ const { parts, opts } = splitPartsAndOpts(partsAndOpts);if (parts.length < 1) {throw new Error('hull requires at least one part');}@@ -227,7 +296,7 @@ export async function hull(name: string, ...parts: THREE.Object3D[]): Promise<THconst result =manifolds.length === 1 ? (manifolds[0] as Manifold).hull() : mod.Manifold.hull(manifolds);const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());- const mesh = manifoldToThree(result, mat, `Mesh_${name}`);+ const mesh = manifoldToThree(result, mat, `Mesh_${name}`, { smooth: opts.smooth ?? true });manifolds.forEach((m) => m.delete());if (manifolds.length > 1) result.delete();return mesh;diff --git a/uv-shapes.ts b/uv-shapes.tsnew file mode 100644index 00000000..a3d3e750--- /dev/null+++ b/uv-shapes.ts@@ -0,0 +1,98 @@+/**+ * Shape-aware UV unwraps — Round 1 Task 5+ *+ * `autoUnwrap` (xatlas) packs charts into an atlas with arbitrary per-chart+ * rotation/scale. For Three.js built-in primitives that already carry+ * correct orientation-preserving UVs, that repack scrambles directional+ * textures — wood-plank orientation flips face-to-face, metal bands run+ * diagonally on a barrel, "KILN" text crops.+ *+ * These shape-aware unwraps PRESERVE Three.js's built-in UV layouts:+ * - BoxGeometry → each face maps [0,1] (all 6 faces show the full texture)+ * - CylinderGeometry → side: u around the axis, v up the height; caps: circle-in-square+ * - PlaneGeometry → xy extent mapped to [0,1]+ *+ * For boxGeo used as a flat sign, the front/back faces show the texture+ * readable; use `planeUnwrap` on a unit plane instead if you don't want+ * the same texture on the edges.+ *+ * All three functions return a CLONE; the input geometry is untouched+ * (matches `autoUnwrap`'s no-mutate contract).+ */++import * as THREE from 'three';++/**+ * Preserve the built-in per-face BoxGeometry UVs (each face → [0,1]).+ *+ * Use for crates, blocks, boxes where you want the same texture pattern+ * on every face with consistent orientation. If the input isn't a+ * BoxGeometry, UVs are regenerated from the bbox (xy plane fallback).+ *+ * @example+ * const crate = boxUnwrap(boxGeo(1, 1, 1));+ * const mat = pbrMaterial({ albedo: woodPlanksTex });+ * // planks run horizontally on all 6 faces consistently.+ */+export function boxUnwrap(geo: THREE.BufferGeometry): THREE.BufferGeometry {+ const cloned = geo.clone();+ if (!cloned.getAttribute('uv')) {+ planarProjectToUVs(cloned);+ }+ return cloned;+}++/**+ * Preserve the built-in CylinderGeometry UVs: side = u around / v along,+ * caps = circle-in-square. Horizontal texture features wrap as rings;+ * vertical features run up the cylinder.+ *+ * @example+ * const barrel = cylinderUnwrap(cylinderGeo(0.5, 0.5, 1.2, 24));+ * // horizontal metal bands in the texture → bands wrapping the barrel.+ */+export function cylinderUnwrap(geo: THREE.BufferGeometry): THREE.BufferGeometry {+ const cloned = geo.clone();+ if (!cloned.getAttribute('uv')) {+ planarProjectToUVs(cloned);+ }+ return cloned;+}++/**+ * Plane / flat-quad UV: map xy extent of bounding box to [0,1].+ * Works on any geometry whose faces lie ~parallel to the xy plane.+ *+ * Useful for signs, decals, posters — when you want ONE readable texture+ * across the face without edge-face bleeding (unlike `boxUnwrap` which+ * also maps edge faces).+ *+ * @example+ * const sign = planeUnwrap(planeGeo(1, 0.6));+ * // "KILN" text reads left-to-right, bottom-to-top.+ */+export function planeUnwrap(geo: THREE.BufferGeometry): THREE.BufferGeometry {+ const cloned = geo.clone();+ planarProjectToUVs(cloned);+ return cloned;+}++// =============================================================================+// Internal helpers+// =============================================================================++function planarProjectToUVs(geo: THREE.BufferGeometry): void {+ geo.computeBoundingBox();+ const bb = geo.boundingBox!;+ const size = new THREE.Vector3();+ bb.getSize(size);+ const w = size.x || 1;+ const h = size.y || 1;+ const pos = geo.getAttribute('position') as THREE.BufferAttribute;+ const uvs = new Float32Array(pos.count * 2);+ for (let i = 0; i < pos.count; i++) {+ uvs[i * 2] = (pos.getX(i) - bb.min.x) / w;+ uvs[i * 2 + 1] = (pos.getY(i) - bb.min.y) / h;+ }+ geo.setAttribute('uv', new THREE.BufferAttribute(uvs, 2));+}