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.

Round 4 follow-on + textured-aircraft cycle (substrate fixes kept, cycle abandoned)

Matt Kissinger17bec91b3a2d
diff --git a/__tests__/ops.test.ts b/__tests__/ops.test.ts
index 6c679acb..1010c8c7 100644
--- a/__tests__/ops.test.ts
+++ b/__tests__/ops.test.ts
@@ -7,8 +7,8 @@
import { describe, it, expect } from 'bun:test';
import * as THREE from 'three';
-import { boxGeo, sphereGeo } from '../primitives';
-import { mergeVertices, subdivide } from '../ops';
+import { boxGeo, sphereGeo, cylinderGeo } from '../primitives';
+import { mergeVertices, subdivide, revolveGeo, lathe, pipeAlongPath } from '../ops';
describe('mergeVertices', () => {
it('default (attribute-aware) preserves per-face normal splits', () => {
@@ -116,3 +116,157 @@ describe('subdivide auto-weld', () => {
}
});
});
+
+describe('revolveGeo', () => {
+ function bbox(geo: THREE.BufferGeometry): { x: number; y: number; z: number } {
+ geo.computeBoundingBox();
+ const size = new THREE.Vector3();
+ geo.boundingBox!.getSize(size);
+ return { x: size.x, y: size.y, z: size.z };
+ }
+
+ it('full revolution of a vertical line ≡ cylinder bbox', () => {
+ // Profile: a vertical line at radius=0.5, from y=0 to y=2.
+ // Note: lathe orients y from bottom to top. To match cylinderGeo (which
+ // is centered on origin), we offset the profile so it spans y=-1..+1.
+ const profile: Array<[number, number]> = [
+ [0.5, -1],
+ [0.5, 1],
+ ];
+ const cyl = cylinderGeo(0.5, 0.5, 2, 16);
+ const rev = revolveGeo(profile, { segments: 16 });
+ const a = bbox(cyl);
+ const b = bbox(rev);
+ expect(b.x).toBeCloseTo(a.x, 3);
+ expect(b.y).toBeCloseTo(a.y, 3);
+ expect(b.z).toBeCloseTo(a.z, 3);
+ });
+
+ it('full revolution matches lathe (back-compat sanity)', () => {
+ const profile: Array<[number, number]> = [
+ [0.1, 0],
+ [0.3, 0.5],
+ [0.2, 1],
+ [0.1, 1.2],
+ ];
+ const a = bbox(lathe(profile, 16));
+ const b = bbox(revolveGeo(profile, { segments: 16 }));
+ expect(b.x).toBeCloseTo(a.x, 5);
+ expect(b.y).toBeCloseTo(a.y, 5);
+ expect(b.z).toBeCloseTo(a.z, 5);
+ });
+
+ it('partial sweep covers the requested angular extent', () => {
+ // Quarter sweep (90°) of a vertical line at radius=1.
+ // LatheGeometry's phi=0 starts at +Z (not +X), so:
+ // quarter (0..π/2): sweeps +Z → +X → bbox.x≈1, bbox.z≈1
+ // half (0..π): sweeps +Z → -Z passing through +X → bbox.x≈1, bbox.z≈2
+ // full (0..2π): bbox.x≈2, bbox.z≈2
+ const profile: Array<[number, number]> = [
+ [1, 0],
+ [1, 1],
+ ];
+ const quarter = revolveGeo(profile, { angle: Math.PI / 2, segments: 16 });
+ const half = revolveGeo(profile, { angle: Math.PI, segments: 16 });
+ const full = revolveGeo(profile, { angle: Math.PI * 2, segments: 16 });
+ expect(bbox(full).x).toBeCloseTo(2, 1);
+ expect(bbox(full).z).toBeCloseTo(2, 1);
+ expect(bbox(half).x).toBeCloseTo(1, 1);
+ expect(bbox(half).z).toBeCloseTo(2, 1);
+ expect(bbox(quarter).x).toBeCloseTo(1, 1);
+ expect(bbox(quarter).z).toBeCloseTo(1, 1);
+ });
+
+ it('non-Y axis reorients the surface', () => {
+ // Same line profile, sweep around +X instead of +Y. The "height" should
+ // now lie along X, the radial direction in the YZ plane.
+ const profile: Array<[number, number]> = [
+ [0.5, -1],
+ [0.5, 1],
+ ];
+ const aroundX = revolveGeo(profile, { axis: [1, 0, 0], segments: 16 });
+ const b = bbox(aroundX);
+ expect(b.x).toBeCloseTo(2, 1); // along X = the lathe axis
+ expect(b.y).toBeCloseTo(1, 1); // diameter in YZ
+ expect(b.z).toBeCloseTo(1, 1);
+ });
+
+ it('rejects zero-length axis', () => {
+ expect(() =>
+ revolveGeo(
+ [
+ [1, 0],
+ [1, 1],
+ ],
+ { axis: [0, 0, 0] }
+ )
+ ).toThrow('axis must be a non-zero vector');
+ });
+});
+
+describe('pipeAlongPath', () => {
+ function bbox(geo: THREE.BufferGeometry): { x: number; y: number; z: number } {
+ geo.computeBoundingBox();
+ const size = new THREE.Vector3();
+ geo.boundingBox!.getSize(size);
+ return { x: size.x, y: size.y, z: size.z };
+ }
+
+ it('2-point pipe matches a beamBetween bbox along the same vector', () => {
+ // Path = [origin, +Y at 1]; radius 0.05.
+ // Bbox should span 1 along Y, ≈0.1 along X and Z (diameter).
+ const pipe = pipeAlongPath(
+ [
+ [0, 0, 0],
+ [0, 1, 0],
+ ],
+ 0.05
+ );
+ const b = bbox(pipe);
+ expect(b.y).toBeCloseTo(1, 1);
+ expect(b.x).toBeLessThan(0.2);
+ expect(b.z).toBeLessThan(0.2);
+ });
+
+ it('3-point right-angle path covers both legs', () => {
+ // L-shape in the XY plane: (0,0,0) → (1,0,0) → (1,1,0).
+ const pipe = pipeAlongPath(
+ [
+ [0, 0, 0],
+ [1, 0, 0],
+ [1, 1, 0],
+ ],
+ 0.05
+ );
+ const b = bbox(pipe);
+ expect(b.x).toBeGreaterThan(0.9);
+ expect(b.y).toBeGreaterThan(0.9);
+ });
+
+ it('bendRadius>0 changes the geometry vs unsmoothed path', () => {
+ const pts: Array<[number, number, number]> = [
+ [0, 0, 0],
+ [1, 0, 0],
+ [1, 1, 0],
+ ];
+ const sharp = pipeAlongPath(pts, 0.05);
+ const smooth = pipeAlongPath(pts, 0.05, { bendRadius: 0.2 });
+ // Both produce non-empty geometry; the bend variant has a different
+ // vertex count due to inserted waypoints / spline resampling.
+ const sharpVerts = (sharp.getAttribute('position') as THREE.BufferAttribute).count;
+ const smoothVerts = (smooth.getAttribute('position') as THREE.BufferAttribute).count;
+ expect(sharpVerts).toBeGreaterThan(0);
+ expect(smoothVerts).toBeGreaterThan(0);
+ // Bend radius adds interpolated waypoints — vertex counts may differ
+ // (the underlying TubeGeometry uses CatmullRom over the new path).
+ const sharpBb = bbox(sharp);
+ const smoothBb = bbox(smooth);
+ // Smoothed corner shouldn't bow OUTSIDE the original path's bbox.
+ expect(smoothBb.x).toBeLessThanOrEqual(sharpBb.x + 0.05);
+ expect(smoothBb.y).toBeLessThanOrEqual(sharpBb.y + 0.05);
+ });
+
+ it('rejects single-point input', () => {
+ expect(() => pipeAlongPath([[0, 0, 0]], 0.05)).toThrow('need at least 2 points');
+ });
+});
diff --git a/__tests__/primitives.test.ts b/__tests__/primitives.test.ts
index 390faf5a..e48ba2c5 100644
--- a/__tests__/primitives.test.ts
+++ b/__tests__/primitives.test.ts
@@ -32,9 +32,11 @@ import {
cylinderGeo,
cylinderXGeo,
cylinderZGeo,
+ cylinderOnAxis,
coneGeo,
coneXGeo,
coneZGeo,
+ taperConeGeo,
capsuleGeo,
capsuleXGeo,
capsuleZGeo,
@@ -252,6 +254,179 @@ describe('geometry primitives produce real Three.js geometries', () => {
expect(z.y).toBeLessThan(0.5);
});
+ test('cylinderOnAxis with Y normal matches cylinderGeo bbox at origin', () => {
+ const baseline = cylinderGeo(0.3, 0.3, 1.5, 16);
+ const onAxis = cylinderOnAxis([0, 0, 0], [0, 1, 0], 0.3, 1.5, { segments: 16 });
+ const a = geometrySize(baseline);
+ const b = geometrySize(onAxis);
+ expect(b.x).toBeCloseTo(a.x, 5);
+ expect(b.y).toBeCloseTo(a.y, 5);
+ expect(b.z).toBeCloseTo(a.z, 5);
+ });
+
+ test('cylinderOnAxis with X normal matches cylinderXGeo bbox', () => {
+ const ax = geometrySize(cylinderXGeo(0.2, 0.2, 1.2, 12));
+ const on = geometrySize(cylinderOnAxis([0, 0, 0], [1, 0, 0], 0.2, 1.2, { segments: 12 }));
+ expect(on.x).toBeCloseTo(ax.x, 5);
+ expect(on.y).toBeCloseTo(ax.y, 5);
+ expect(on.z).toBeCloseTo(ax.z, 5);
+ });
+
+ test('cylinderOnAxis with Z normal matches cylinderZGeo bbox', () => {
+ const az = geometrySize(cylinderZGeo(0.18, 0.18, 0.9, 10));
+ const on = geometrySize(cylinderOnAxis([0, 0, 0], [0, 0, 1], 0.18, 0.9, { segments: 10 }));
+ expect(on.x).toBeCloseTo(az.x, 5);
+ expect(on.y).toBeCloseTo(az.y, 5);
+ expect(on.z).toBeCloseTo(az.z, 5);
+ });
+
+ test('cylinderOnAxis with arbitrary normal lies along the requested vector', () => {
+ const center: [number, number, number] = [1, 2, -0.5];
+ const normal: [number, number, number] = [1, 1, 0];
+ const geo = cylinderOnAxis(center, normal, 0.05, 2);
+ geo.computeBoundingBox();
+ const center3 = new THREE.Vector3();
+ geo.boundingBox!.getCenter(center3);
+ expect(center3.x).toBeCloseTo(1, 5);
+ expect(center3.y).toBeCloseTo(2, 5);
+ expect(center3.z).toBeCloseTo(-0.5, 5);
+ // For normal=[1,1,0] (axis in XY plane at 45°), height=2, radius=0.05:
+ // bbox.x = bbox.y = cos(45°)·2 + sin(45°)·0.1 ≈ 1.485
+ // bbox.z = 2·radius = 0.1
+ const size = geometrySize(geo);
+ const expectedXY = Math.SQRT2 + 0.1 * Math.SQRT1_2;
+ expect(size.x).toBeCloseTo(expectedXY, 2);
+ expect(size.y).toBeCloseTo(expectedXY, 2);
+ expect(size.z).toBeLessThan(0.2);
+ });
+
+ test('cylinderOnAxis rejects zero-length normal', () => {
+ expect(() => cylinderOnAxis([0, 0, 0], [0, 0, 0], 0.1, 1)).toThrow(
+ 'normal must be a non-zero vector'
+ );
+ });
+
+ test('cylinderOnAxis radiusTop option produces a frustum', () => {
+ const frustum = cylinderOnAxis([0, 0, 0], [0, 1, 0], 0.5, 1, { radiusTop: 0.2 });
+ expect(frustum.parameters.radiusTop).toBeCloseTo(0.2);
+ expect(frustum.parameters.radiusBottom).toBeCloseTo(0.5);
+ });
+
+ test('taperConeGeo with radiusTop=0 matches coneGeo bbox', () => {
+ const a = geometrySize(coneGeo(0.5, 1.2, 12));
+ const b = geometrySize(taperConeGeo(0.5, 0, 1.2, 'y', 12));
+ expect(b.x).toBeCloseTo(a.x, 5);
+ expect(b.y).toBeCloseTo(a.y, 5);
+ expect(b.z).toBeCloseTo(a.z, 5);
+ });
+
+ test('taperConeGeo with equal radii matches cylinderGeo bbox', () => {
+ const a = geometrySize(cylinderGeo(0.3, 0.3, 1.0, 12));
+ const b = geometrySize(taperConeGeo(0.3, 0.3, 1.0, 'y', 12));
+ expect(b.x).toBeCloseTo(a.x, 5);
+ expect(b.y).toBeCloseTo(a.y, 5);
+ expect(b.z).toBeCloseTo(a.z, 5);
+ });
+
+ test('taperConeGeo emits a true frustum (top !== bottom !== 0)', () => {
+ const f = taperConeGeo(0.4, 0.15, 0.8);
+ expect(f.parameters.radiusTop).toBeCloseTo(0.15);
+ expect(f.parameters.radiusBottom).toBeCloseTo(0.4);
+ });
+
+ test('taperConeGeo axis="x" aligns height along +X', () => {
+ const size = geometrySize(taperConeGeo(0.2, 0.2, 1.6, 'x'));
+ expect(size.x).toBeCloseTo(1.6);
+ expect(size.y).toBeLessThan(0.5);
+ });
+
+ test('taperConeGeo axis="z" aligns height along +Z', () => {
+ const size = geometrySize(taperConeGeo(0.2, 0.2, 1.4, 'z'));
+ expect(size.z).toBeCloseTo(1.4);
+ expect(size.y).toBeLessThan(0.5);
+ });
+
+ // ---- Lazy mesh cache (Wave 2 B2) -----------------------------------------
+
+ test('sandbox geometry cache returns the same ref for identical args', () => {
+ const sandbox = buildSandboxGlobals();
+ const box1 = (sandbox.boxGeo as typeof boxGeo)(1, 2, 3);
+ const box2 = (sandbox.boxGeo as typeof boxGeo)(1, 2, 3);
+ expect(box1).toBe(box2);
+ });
+
+ test('sandbox geometry cache returns a new ref when args differ', () => {
+ const sandbox = buildSandboxGlobals();
+ const a = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const b = (sandbox.boxGeo as typeof boxGeo)(1, 1, 2);
+ expect(a).not.toBe(b);
+ });
+
+ test('sandbox geometry cache is per-execution — fresh sandbox = fresh cache', () => {
+ const s1 = buildSandboxGlobals();
+ const s2 = buildSandboxGlobals();
+ const a = (s1.boxGeo as typeof boxGeo)(1, 1, 1);
+ const b = (s2.boxGeo as typeof boxGeo)(1, 1, 1);
+ // Different sandbox -> different cached instance even with same args.
+ expect(a).not.toBe(b);
+ });
+
+ test('cache hits still tick the usage counter', () => {
+ const usage: Record<string, number> = {};
+ const sandbox = buildSandboxGlobals(usage);
+ (sandbox.boxGeo as typeof boxGeo)(1, 2, 3);
+ (sandbox.boxGeo as typeof boxGeo)(1, 2, 3);
+ (sandbox.boxGeo as typeof boxGeo)(1, 2, 3);
+ expect(usage.boxGeo).toBe(3);
+ });
+
+ test('cache spans different geometry families independently', () => {
+ const sandbox = buildSandboxGlobals();
+ const box = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const sphere = (sandbox.sphereGeo as typeof sphereGeo)(1);
+ const cyl = (sandbox.cylinderGeo as typeof cylinderGeo)(1, 1, 1);
+ // Each is independent; caching doesn't collide across primitive names.
+ expect(box).not.toBe(sphere);
+ expect(box).not.toBe(cyl);
+ expect(sphere).not.toBe(cyl);
+ });
+
+ // ---- Mesh-range / sub-shape mapping (Wave 3 B3) -------------------------
+
+ test('sandbox primitives stamp userData.kilnRanges with one entry covering all triangles', () => {
+ const sandbox = buildSandboxGlobals();
+ const geo = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const ranges = (geo.userData as Record<string, unknown>).kilnRanges as
+ | Array<{ name: string; start: number; count: number }>
+ | undefined;
+ expect(Array.isArray(ranges)).toBe(true);
+ expect(ranges).toHaveLength(1);
+ expect(ranges![0]!.name).toMatch(/^boxGeo#\d+$/);
+ expect(ranges![0]!.start).toBe(0);
+ // Box has 12 tris regardless of size.
+ expect(ranges![0]!.count).toBe(12);
+ });
+
+ test('kilnRanges name carries the primitive function name', () => {
+ const sandbox = buildSandboxGlobals();
+ const cyl = (sandbox.cylinderGeo as typeof cylinderGeo)(1, 1, 1, 8);
+ const ranges = (cyl.userData as Record<string, unknown>).kilnRanges as
+ | Array<{ name: string; start: number; count: number }>
+ | undefined;
+ expect(ranges![0]!.name).toMatch(/^cylinderGeo#\d+$/);
+ });
+
+ test('different primitive calls get distinct kilnRange call ids', () => {
+ const sandbox = buildSandboxGlobals();
+ const a = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const b = (sandbox.boxGeo as typeof boxGeo)(2, 2, 2);
+ const idA = ((a.userData as Record<string, unknown>).kilnRanges as Array<{ name: string }>)[0]!
+ .name;
+ const idB = ((b.userData as Record<string, unknown>).kilnRanges as Array<{ name: string }>)[0]!
+ .name;
+ expect(idA).not.toBe(idB);
+ });
+
test('coneGeo with default segments', () => {
const g = coneGeo(1, 2);
expect(g).toBeInstanceOf(THREE.ConeGeometry);
@@ -638,12 +813,15 @@ describe('buildSandboxGlobals', () => {
expect(usageB.createRoot).toBe(2);
});
- test('without a usage map, primitives are unwrapped (zero-overhead path)', () => {
+ test('without a usage map, geometry primitives still produce valid output', () => {
+ // Round 4: caching is now baseline — geometry primitives go through a
+ // per-sandbox memo wrapper even without usage instrumentation. The
+ // wrapper is observably equivalent to the raw primitive for first-call
+ // semantics (returns a real BufferGeometry of the right type).
const globals = buildSandboxGlobals() as Record<string, unknown>;
- // Identity check: the exposed function is the original primitive, not a
- // wrapper. Looking up by name against a second fresh globals keeps the
- // test independent of module structure.
- const raw = buildSandboxGlobals() as Record<string, unknown>;
- expect(globals.boxGeo).toBe(raw.boxGeo);
+ const fn = globals.boxGeo as (w: number, h: number, d: number) => THREE.BoxGeometry;
+ const geo = fn(1, 1, 1);
+ expect(geo).toBeInstanceOf(THREE.BoxGeometry);
+ expect(geo.getAttribute('position').count).toBeGreaterThan(0);
});
});
diff --git a/__tests__/sandbox-three-bridge.test.ts b/__tests__/sandbox-three-bridge.test.ts
new file mode 100644
index 00000000..fc79b96b
--- /dev/null
+++ b/__tests__/sandbox-three-bridge.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Regression test for the cross-module THREE bug — see
+ * `kiln-cross-module-three.md` memory entry.
+ *
+ * The kiln executor uses `new Function(...)` to run LLM-generated code,
+ * which under bun creates an isolated module realm. `new THREE.Mesh()`
+ * inside that sandbox produces objects whose constructor is NOT the same
+ * class object as `THREE.Mesh` imported by render.ts / inspect.ts /
+ * solids.ts / etc.
+ *
+ * Before this was fixed, every consumer using `instanceof THREE.Mesh`
+ * silently dropped sandbox meshes (treated them as not-meshes), producing
+ * GLBs with empty Mesh nodes and corrupted texture export.
+ *
+ * The fix: every cross-sandbox check uses Three.js's `.isMesh`,
+ * `.isObject3D`, `.isTexture`, `.isMeshStandardMaterial` etc. duck-typing
+ * flags, which are set on the prototype and survive across module realms.
+ *
+ * This test ensures the canonical "LLM emitted `new THREE.Mesh()` directly"
+ * code path produces a GLB with the mesh attached (not stripped). If the
+ * test fails, an `instanceof THREE.X` check regressed somewhere on the
+ * bridge path.
+ */
+import { test, expect } from 'bun:test';
+import { NodeIO } from '@gltf-transform/core';
+import { renderGLB } from '../render';
+
+test('sandbox new THREE.Mesh() survives the GLB bridge (cross-module realm)', async () => {
+ const code = `
+const meta = { name: 'sandbox-mesh-test', category: 'prop' };
+function build() {
+ const root = createRoot('Root');
+ // The LLM canonical pattern: \`new THREE.Mesh(geo, mat)\` directly,
+ // NOT via createPart. This goes through the cross-module realm.
+ const m = new THREE.Mesh(boxGeo(1, 1, 1), gameMaterial(0xff0000));
+ m.name = 'Mesh_DirectMesh';
+ root.add(m);
+ return root;
+}
+`;
+ const result = await renderGLB(code);
+ expect(result.warnings).toEqual([]);
+ expect(result.meta.tris).toBeGreaterThan(0);
+
+ // Confirm the mesh ACTUALLY made it into the GLB binary, not just the
+ // Three.js scene. Read back via NodeIO and verify a node named
+ // "Mesh_DirectMesh" has an attached mesh with non-zero tris.
+ const io = new NodeIO();
+ const doc = await io.readBinary(result.glb);
+ const directNode = doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getName() === 'Mesh_DirectMesh');
+ expect(directNode).toBeDefined();
+ const mesh = directNode!.getMesh();
+ expect(mesh).toBeDefined();
+ let tris = 0;
+ for (const p of mesh!.listPrimitives()) {
+ tris += (p.getIndices()?.getCount() ?? 0) / 3;
+ }
+ expect(tris).toBeGreaterThan(0);
+});
+
+test('sandbox new THREE.Mesh() with pbrMaterial+texture survives — texture serialised', async () => {
+ // Reproduces the textured-aircraft cycle issue: LLM does
+ // new THREE.Mesh(unwrappedGeo, pbrMaterial({ albedo: loadedTex }))
+ // and the resulting GLB needs to actually carry the texture.
+ // Build a tiny in-memory PNG via sharp to avoid coupling to disk paths.
+ const { default: sharp } = await import('sharp');
+ const pngBytes = await sharp({
+ create: { width: 16, height: 16, channels: 4, background: { r: 200, g: 80, b: 80, alpha: 1 } },
+ })
+ .png()
+ .toBuffer();
+ const tmpPath = `${process.cwd()}/.tmp-sandbox-three-bridge.png`;
+ const fs = await import('node:fs');
+ fs.writeFileSync(tmpPath, pngBytes);
+
+ try {
+ const code = `
+const meta = { name: 'sandbox-textured-mesh-test', category: 'prop' };
+async function build() {
+ const root = createRoot('Root');
+ const tex = await loadTexture(${JSON.stringify(tmpPath)});
+ const mat = pbrMaterial({ albedo: tex, roughness: 0.85, metalness: 0 });
+ const geo = cylinderUnwrap(boxGeo(1, 1, 1));
+ const m = new THREE.Mesh(geo, mat);
+ m.name = 'Mesh_TexturedDirect';
+ root.add(m);
+ return root;
+}
+`;
+ const result = await renderGLB(code);
+ expect(result.warnings).toEqual([]);
+
+ const io = new NodeIO();
+ const doc = await io.readBinary(result.glb);
+ const root = doc.getRoot();
+ // Texture carried through?
+ expect(root.listTextures().length).toBeGreaterThan(0);
+ // Material with base-color texture present?
+ const matWithTex = root.listMaterials().find((m) => m.getBaseColorTexture());
+ expect(matWithTex).toBeDefined();
+ } finally {
+ if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
+ }
+});
diff --git a/__tests__/solids.test.ts b/__tests__/solids.test.ts
index dff9c5f5..abdc4afa 100644
--- a/__tests__/solids.test.ts
+++ b/__tests__/solids.test.ts
@@ -142,4 +142,49 @@ describe('Wave 2A: CSG primitives (manifold-3d)', () => {
const wrapped = await hull('Cluster', ...parts, { smooth: false });
expect(wrapped.geometry.index).toBeNull();
});
+
+ // ---- B3 mesh-range tagging ---------------------------------------------
+
+ it('boolUnion stamps kilnRanges with one entry per operand, summing to total tris', async () => {
+ // Build operands through buildSandboxGlobals so they're auto-tagged.
+ const { buildSandboxGlobals } = await import('../primitives');
+ const sandbox = buildSandboxGlobals();
+ const aGeo = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const bGeo = (sandbox.boxGeo as typeof boxGeo)(1.2, 1.2, 1.2);
+ const a = new THREE.Mesh(aGeo, gameMaterial(0xff0000));
+ const b = new THREE.Mesh(bGeo, gameMaterial(0xff0000));
+ b.position.set(0.4, 0, 0);
+
+ const merged = await boolUnion('Merged', a, b);
+ const ranges = (merged.geometry.userData as Record<string, unknown>).kilnRanges as
+ | Array<{ name: string; start: number; count: number }>
+ | undefined;
+ expect(Array.isArray(ranges)).toBe(true);
+ expect(ranges).toHaveLength(2);
+
+ // Total tri count from output index (or non-indexed positions).
+ const idx = merged.geometry.getIndex();
+ const totalTris = idx
+ ? idx.count / 3
+ : (merged.geometry.getAttribute('position') as THREE.BufferAttribute).count / 3;
+ const sum = ranges!.reduce((s, r) => s + r.count, 0);
+ expect(sum).toBe(Math.floor(totalTris));
+
+ // Non-overlapping windows, monotonic starts.
+ expect(ranges![0]!.start).toBe(0);
+ expect(ranges![1]!.start).toBe(ranges![0]!.start + ranges![0]!.count);
+ });
+
+ it('GLB export round-trips without serialising kilnRanges (userData is dropped)', async () => {
+ const { buildSandboxGlobals } = await import('../primitives');
+ const sandbox = buildSandboxGlobals();
+ const geo = (sandbox.boxGeo as typeof boxGeo)(1, 1, 1);
+ const root = createRoot('Crate');
+ createPart('Body', geo, gameMaterial(0xc0a26b), { parent: root });
+
+ const { bytes } = await renderSceneToGLB(root);
+ expect(bytes.length).toBeGreaterThan(0);
+ // gltf-transform doesn't carry userData through the buffer; this is a
+ // smoke-test that the metadata doesn't blow up the writer.
+ });
});
diff --git a/index.ts b/index.ts
index 258297c2..5f8e6fba 100644
--- a/index.ts
+++ b/index.ts
@@ -76,11 +76,13 @@ export {
cylinderGeo,
cylinderXGeo,
cylinderZGeo,
+ cylinderOnAxis,
boxGeo,
sphereGeo,
coneGeo,
coneXGeo,
coneZGeo,
+ taperConeGeo,
torusGeo,
planeGeo,
wingGeo,
@@ -114,7 +116,9 @@ export {
subdivide,
mergeVertices,
curveToMesh,
+ pipeAlongPath,
lathe,
+ revolveGeo,
bezierCurve,
} from './ops';
export { autoUnwrap } from './uv';
diff --git a/inspect.ts b/inspect.ts
index a3c1cb79..42563b4f 100644
--- a/inspect.ts
+++ b/inspect.ts
@@ -138,7 +138,11 @@ function detectPrimitivesUsed(code: string): string[] {
// =============================================================================
function classifyNode(obj: THREE.Object3D): 'pivot' | 'mesh' | 'group' {
- if (obj instanceof THREE.Mesh) return 'mesh';
+ // Duck-typed `.isMesh` instead of `instanceof` — sandbox-created meshes
+ // (from `new Function(...)` in executeKilnCode) belong to a different
+ // module realm than this file's THREE import, so `instanceof` returns
+ // false. See `kiln-cross-module-three.md` memory + render.ts comment.
+ if ((obj as { isMesh?: boolean }).isMesh) return 'mesh';
if (obj.name.startsWith('Joint_')) return 'pivot';
return 'group';
}
@@ -159,8 +163,9 @@ function collectNamedParts(root: THREE.Object3D): InspectNamedPart[] {
function countTris(root: THREE.Object3D): number {
let count = 0;
root.traverse((child) => {
- if (!(child instanceof THREE.Mesh)) return;
- const geometry = child.geometry;
+ if (!(child as { isMesh?: boolean }).isMesh) return;
+ const meshChild = child as THREE.Mesh;
+ const geometry = meshChild.geometry;
if (!geometry) return;
if (geometry.index) {
count += geometry.index.count / 3;
@@ -175,11 +180,12 @@ function countTris(root: THREE.Object3D): number {
function countUniqueMaterials(root: THREE.Object3D): number {
const materials = new Set<THREE.Material>();
root.traverse((child) => {
- if (!(child instanceof THREE.Mesh)) return;
- if (Array.isArray(child.material)) {
- for (const m of child.material) materials.add(m);
- } else if (child.material) {
- materials.add(child.material);
+ if (!(child as { isMesh?: boolean }).isMesh) return;
+ const meshChild = child as THREE.Mesh;
+ if (Array.isArray(meshChild.material)) {
+ for (const m of meshChild.material) materials.add(m);
+ } else if (meshChild.material) {
+ materials.add(meshChild.material);
}
});
return materials.size;
diff --git a/list-primitives.ts b/list-primitives.ts
index c95014ef..8345d552 100644
--- a/list-primitives.ts
+++ b/list-primitives.ts
@@ -165,6 +165,17 @@ const PRIMITIVES: PrimitiveSpec[] = [
'Cylinder pre-rotated to run along +Z/-Z. Use for side-mounted weapons, rails, crossbars, and pipes.',
example: 'const geo = cylinderZGeo(0.08, 0.08, 0.9, 10);',
},
+ {
+ name: 'cylinderOnAxis',
+ signature:
+ 'cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom: number, height: number, opts?: { radiusTop?, segments? })',
+ returns: 'THREE.CylinderGeometry',
+ category: 'geometry',
+ description:
+ 'Frame-first cylinder: position + axis specified directly, no post-hoc rotation. Use when the cylinder needs to point along a non-cardinal direction (struts inside CSG operands, antennas off a tilted surface). For cardinal axes prefer the terser cylinderXGeo / cylinderYGeo / cylinderZGeo helpers.',
+ example:
+ "const strut = cylinderOnAxis([0.5, 0.7, 0], [1, 1, 0.3], 0.05, 0.9);",
+ },
{
name: 'capsuleGeo',
signature: 'capsuleGeo(radius: number, height: number, segments?: 6)',
@@ -233,6 +244,16 @@ const PRIMITIVES: PrimitiveSpec[] = [
'Cone pre-rotated so its point faces +Z. Use for side-facing projectiles and tips.',
example: 'const geo = coneZGeo(0.12, 0.35, 10);',
},
+ {
+ name: 'taperConeGeo',
+ signature:
+ "taperConeGeo(radiusBottom: number, radiusTop: number, height: number, axis?: 'x'|'y'|'z', segments?: 8)",
+ returns: 'THREE.CylinderGeometry',
+ category: 'geometry',
+ description:
+ 'Truncated cone (frustum) — exposes both bottom and top radius. radiusTop=0 matches coneGeo, radiusTop=radiusBottom matches cylinderGeo. Use for pylon caps, soda cans, lampshades, anything tapered that does not come to a point. axis selects orientation (default Y).',
+ example: 'const cap = taperConeGeo(0.3, 0.18, 0.4); // frustum',
+ },
{
name: 'torusGeo',
signature:
@@ -586,6 +607,17 @@ const PRIMITIVES: PrimitiveSpec[] = [
example:
"const pipe = curveToMesh([[0,0,0],[0,1,0],[1,1,0],[1,2,0]], 0.1);",
},
+ {
+ name: 'pipeAlongPath',
+ signature:
+ 'pipeAlongPath(points: [x,y,z][], radius: number, opts?: { bendRadius?: 0, closed?: false, tubularSegments?: 32, radialSegments?: 8 })',
+ returns: 'THREE.BufferGeometry',
+ category: 'curves',
+ description:
+ 'Path-driven swept circle with optional bend smoothing. Generalises beamBetween (point-to-point) and curveToMesh (raw spline) into one helper. bendRadius>0 inserts interpolated waypoints near interior corners so the spline reads as a rounded turn instead of pinching to the control point.',
+ example:
+ "const cable = pipeAlongPath([[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]], 0.02, { bendRadius: 0.1 });",
+ },
{
name: 'lathe',
signature: 'lathe(profile: [x,y][], segments?: 12)',
@@ -596,6 +628,17 @@ const PRIMITIVES: PrimitiveSpec[] = [
example:
"const vase = lathe([[0.1,0],[0.3,0.5],[0.2,1],[0.1,1.2]], 16);",
},
+ {
+ name: 'revolveGeo',
+ signature:
+ 'revolveGeo(profile: [x,y][], opts?: { angle?: 2π, axis?: [x,y,z]=[0,1,0], segments?: 12 })',
+ returns: 'THREE.BufferGeometry',
+ category: 'curves',
+ description:
+ 'Surface of revolution with explicit axis + sweep angle. Generalises lathe — use it when you need a partial sweep (half-dome, 90° wedge) or revolution around a non-Y axis. Profile convention is identical to lathe: x = radial distance, y = position along the axis.',
+ example:
+ "// Half-dome (180° sweep around +Y):\nconst quarter = [...Array(8)].map((_, i) => { const t = (i/7)*Math.PI/2; return [Math.cos(t), Math.sin(t)] as [number, number]; });\nconst dome = revolveGeo(quarter, { angle: Math.PI });",
+ },
{
name: 'bezierCurve',
signature: 'bezierCurve(controlPoints: [x,y,z][], samples?: 32)',
@@ -651,6 +694,16 @@ const PRIMITIVES: PrimitiveSpec[] = [
example:
"const sign = planeUnwrap(planeGeo(1, 0.6));\nconst mesh = new THREE.Mesh(sign, pbrMaterial({ albedo: kilnTextTex }));",
},
+ {
+ name: 'panelRemapV',
+ signature: 'panelRemapV(geo, vScale=0.30, vOffset=0, uScale=1, uOffset=0)',
+ returns: 'THREE.BufferGeometry',
+ category: 'uv',
+ description:
+ "Scales an existing UV attribute so a small mesh samples a sub-region of a SHARED texture. Replaces the broken texture.clone() pattern (Three.js Texture.clone() runs JSON.stringify on userData, mangling encoded PNG bytes — panelRemapV avoids that by remapping UVs on the geometry instead). Typical use: multi-zone albedo where v=0..0.30 is plain panel and v=0.30..1 has windows/markings — small parts call panelRemapV(unwrap(geo), 0.30) to sample only the clean strip.",
+ example:
+ "const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);\nconst cowl = new THREE.Mesh(cowlGeo, bodyMat); // SAME bodyMat as fuselage, no clone needed",
+ },
// ---------------------------------------------------------------------------
// Textures + PBR (Wave 3B)
diff --git a/ops.ts b/ops.ts
index 77344afa..a2094bdf 100644
--- a/ops.ts
+++ b/ops.ts
@@ -257,6 +257,139 @@ export function lathe(
return new THREE.LatheGeometry(points2d, segments);
}
+/**
+ * Surface of revolution with explicit axis + sweep angle. Generalises
+ * `lathe` (which is locked to a full revolution around +Y) for cases where
+ * you need a partial sweep (e.g. half a dome, a 90° wedge of a wheel) or
+ * a non-Y axis of revolution (e.g. a fan blade revolved around +X).
+ *
+ * The 2D `profile` is in the same convention as `lathe`: x = radial
+ * distance from the axis, y = position along the axis. Then:
+ * - `angle` controls the sweep (default `2π` = full revolution).
+ * - `axis` reorients the resulting Y-up surface to point along the
+ * supplied unit vector (defaults to `[0, 1, 0]` = no reorientation).
+ *
+ * Pattern adapted from chili3d's `revolve(profile, axis: Line, angle)` —
+ * the parameter shape is the same, but the implementation is mesh-only
+ * (Three.js LatheGeometry + a quaternion reorientation) rather than B-rep.
+ *
+ * @example
+ * // Half-dome: profile traces a quarter circle, sweep 180°.
+ * const dome = revolveGeo(
+ * [...Array(8)].map((_, i) => {
+ * const t = (i / 7) * Math.PI / 2;
+ * return [Math.cos(t), Math.sin(t)] as [number, number];
+ * }),
+ * { angle: Math.PI }
+ * );
+ */
+export function revolveGeo(
+ profile: Array<[number, number]>,
+ options: {
+ angle?: number;
+ axis?: [number, number, number];
+ segments?: number;
+ } = {}
+): THREE.BufferGeometry {
+ const { angle = Math.PI * 2, axis = [0, 1, 0], segments = 12 } = options;
+ const points2d = profile.map((p) => new THREE.Vector2(p[0], p[1]));
+ // LatheGeometry signature: (points, segments, phiStart, phiLength).
+ const geo = new THREE.LatheGeometry(points2d, segments, 0, angle);
+
+ const n = new THREE.Vector3(axis[0], axis[1], axis[2]);
+ if (n.lengthSq() < 1e-12) {
+ throw new Error(`revolveGeo: axis must be a non-zero vector (got [${axis.join(',')}]).`);
+ }
+ n.normalize();
+ if (n.x !== 0 || n.y !== 1 || n.z !== 0) {
+ const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), n);
+ geo.applyQuaternion(q);
+ }
+ return geo;
+}
+
+/**
+ * Path-driven swept circle. Generalises `beamBetween` (point-to-point) and
+ * `curveToMesh` (raw catmull-rom) into a single helper that accepts a path
+ * of waypoints plus an optional bend-radius for smoothing sharp corners.
+ *
+ * Compared to `curveToMesh`:
+ * - Same TubeGeometry/CatmullRomCurve3 backbone, so the visual result is
+ * identical for unsmoothed paths.
+ * - `bendRadius > 0` inserts interpolated waypoints near each interior
+ * turn so the spline reads as a rounded corner instead of a single
+ * control point yanking the curve.
+ * - `closed` loops the path end back to start.
+ *
+ * Pattern adapted from chili3d's PipeNode (`bendRadius` + path interpolation
+ * for sharp turns) — implementation is original Three.js mesh-side code.
+ *
+ * @example
+ * // Cable run along the gunwale of a boat:
+ * const cable = pipeAlongPath(
+ * [[0, 0.5, 0], [1, 0.5, 0], [1, 0.5, 2]],
+ * 0.02,
+ * { bendRadius: 0.1 }
+ * );
+ */
+export function pipeAlongPath(
+ points: Array<[number, number, number]>,
+ radius: number,
+ options: {
+ bendRadius?: number;
+ closed?: boolean;
+ tubularSegments?: number;
+ radialSegments?: number;
+ } = {}
+): THREE.BufferGeometry {
+ const {
+ bendRadius = 0,
+ closed = false,
+ tubularSegments = 32,
+ radialSegments = 8,
+ } = options;
+
+ if (points.length < 2) {
+ throw new Error(
+ `pipeAlongPath: need at least 2 points (got ${points.length}).`
+ );
+ }
+
+ let pathPoints = points;
+
+ // Bend smoothing: at each interior corner, replace the corner point with
+ // two points offset along the incoming/outgoing edges by `bendRadius`.
+ // The Catmull-Rom spline then curves smoothly between them instead of
+ // pinching tightly to the corner. Skipped for endpoints (or always for a
+ // closed path's first/last, since they're not corners).
+ if (bendRadius > 0 && points.length >= 3) {
+ const smoothed: Array<[number, number, number]> = [];
+ smoothed.push(points[0]!);
+ for (let i = 1; i < points.length - 1; i++) {
+ const prev = new THREE.Vector3(...points[i - 1]!);
+ const cur = new THREE.Vector3(...points[i]!);
+ const next = new THREE.Vector3(...points[i + 1]!);
+ const inDir = cur.clone().sub(prev);
+ const outDir = next.clone().sub(cur);
+ const inLen = inDir.length();
+ const outLen = outDir.length();
+ // Cap the offset so adjacent segments don't overlap.
+ const inOffset = Math.min(bendRadius, inLen / 2);
+ const outOffset = Math.min(bendRadius, outLen / 2);
+ const before = cur.clone().sub(inDir.clone().normalize().multiplyScalar(inOffset));
+ const after = cur.clone().add(outDir.clone().normalize().multiplyScalar(outOffset));
+ smoothed.push([before.x, before.y, before.z]);
+ smoothed.push([after.x, after.y, after.z]);
+ }
+ smoothed.push(points[points.length - 1]!);
+ pathPoints = smoothed;
+ }
+
+ const vectors = pathPoints.map((p) => new THREE.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE.CatmullRomCurve3(vectors, closed);
+ return new THREE.TubeGeometry(curve, tubularSegments, radius, radialSegments, closed);
+}
+
/**
* Quadratic or cubic Bézier curve sampled into a point list for curveToMesh.
* 3 points = quadratic, 4 points = cubic.
diff --git a/primitives.ts b/primitives.ts
index 5d9bc07e..bd3a9316 100644
--- a/primitives.ts
+++ b/primitives.ts
@@ -206,6 +206,74 @@ export const cylinderYGeo = cylinderGeo;
export const capsuleYGeo = capsuleGeo;
export const coneYGeo = coneGeo;
+/**
+ * Frame-first cylinder. Builds a Y-up cylinder of `height` at the origin,
+ * orients its axis to `normal`, and translates the center to `center`. Use
+ * this when the cylinder needs to point along a non-cardinal axis — struts
+ * inside CSG operands, antennas off a tilted surface, anything where the
+ * `*XGeo` / `*ZGeo` variants don't fit.
+ *
+ * `radiusTop === radiusBottom` for plain tubes; pass different values for a
+ * tapered/conical body without reaching for `coneGeo`.
+ *
+ * The returned geometry has its position pre-baked. You can pass it straight
+ * to `new THREE.Mesh(...)` without further rotation.
+ */
+export function cylinderOnAxis(
+ center: Vec3Tuple,
+ normal: Vec3Tuple,
+ radiusBottom: number,
+ height: number,
+ options: { radiusTop?: number; segments?: number } = {}
+): THREE.CylinderGeometry {
+ const radiusTop = options.radiusTop ?? radiusBottom;
+ const segments = options.segments ?? 8;
+ const geo = new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+
+ const n = new THREE.Vector3(normal[0], normal[1], normal[2]);
+ const len = n.length();
+ if (len < 1e-6) {
+ throw new Error(
+ `cylinderOnAxis: normal must be a non-zero vector (got [${normal.join(',')}]).`
+ );
+ }
+ n.divideScalar(len);
+
+ // Quaternion from Y to normal.
+ const q = new THREE.Quaternion().setFromUnitVectors(
+ new THREE.Vector3(0, 1, 0),
+ n
+ );
+ geo.applyQuaternion(q);
+ geo.translate(center[0], center[1], center[2]);
+ return geo;
+}
+
+/**
+ * Tapered cone helper that exposes the bottom + top radius. The default Y-up
+ * `coneGeo` is apex-only (top radius locked at 0); for truncated/frustum
+ * shapes — soda cans, pylon caps, lampshades — pass a non-zero
+ * `radiusTop`. When `radiusTop === 0` it matches `coneGeo` exactly; when
+ * `radiusTop === radiusBottom` it matches `cylinderGeo`.
+ *
+ * `axis` selects the orientation:
+ * - `'y'` (default) — apex/cap on +Y, matches `coneGeo`
+ * - `'x'` — pre-rotated along +X, matches the `coneXGeo` family
+ * - `'z'` — pre-rotated along +Z
+ */
+export function taperConeGeo(
+ radiusBottom: number,
+ radiusTop: number,
+ height: number,
+ axis: 'x' | 'y' | 'z' = 'y',
+ segments = 8
+): THREE.CylinderGeometry {
+ const geo = new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments);
+ if (axis === 'x') geo.rotateZ(-Math.PI / 2);
+ else if (axis === 'z') geo.rotateX(Math.PI / 2);
+ return geo;
+}
+
export function torusGeo(
radius: number,
tube: number,
@@ -409,8 +477,20 @@ export interface WingGeometryOptions {
* Trapezoid aircraft wing panel.
*
* Coordinate contract: +X forward, +Y up, +Z right. The root edge sits at
- * local Z=0 and the panel extends toward +Z. Positive sweep moves the tip aft
- * along -X. Positive dihedral raises the tip along +Y.
+ * local Z=0 and the panel extends toward +Z.
+ *
+ * **Parameter units (READ THIS — these are NOT angles):**
+ * - `sweep` is the **X-displacement of the tip leading edge in world units**
+ * (positive = tip moves aft along -X). NOT an angle in degrees/radians.
+ * - `dihedral` is the **Y-displacement of the tip in world units**
+ * (positive = tip rises). NOT an angle. For most aircraft you want a
+ * small value like 0.05–0.1 — a value of 1 with span=2 gives a 45°
+ * gull-wing, almost certainly wrong unless explicitly designing one.
+ * - `span` is wing length in world units (root to tip).
+ * - `rootChord` / `tipChord` / `thickness` are all world units.
+ *
+ * Quick reference: a real-aircraft-looking wing has dihedral roughly 2–7%
+ * of span (e.g. span=4, dihedral=0.1 to 0.25).
*/
export function wingGeo(options: WingGeometryOptions = {}): THREE.BufferGeometry {
const span = options.span ?? 1;
@@ -855,10 +935,13 @@ export function createInstance(
parent?: THREE.Object3D;
} = {}
): THREE.Object3D {
- const sourceMesh =
- source instanceof THREE.Mesh
- ? source
- : (source.children.find((c) => c instanceof THREE.Mesh) as THREE.Mesh | undefined);
+ // Duck-typed `.isMesh` — sandbox-created meshes belong to a different
+ // module realm than this file's THREE import. See render.ts comment.
+ const isMesh = (o: THREE.Object3D | undefined): o is THREE.Mesh =>
+ !!(o as { isMesh?: boolean })?.isMesh;
+ const sourceMesh = isMesh(source)
+ ? source
+ : (source.children.find(isMesh) as THREE.Mesh | undefined);
if (!sourceMesh) {
throw new Error(
@@ -889,8 +972,9 @@ export function createInstance(
export function countTriangles(root: THREE.Object3D): number {
let count = 0;
root.traverse((child) => {
- if (child instanceof THREE.Mesh) {
- const geometry = child.geometry;
+ if ((child as { isMesh?: boolean }).isMesh) {
+ const meshChild = child as THREE.Mesh;
+ const geometry = meshChild.geometry;
if (geometry.index) {
count += geometry.index.count / 3;
} else {
@@ -905,11 +989,12 @@ export function countTriangles(root: THREE.Object3D): number {
export function countMaterials(root: THREE.Object3D): number {
const materials = new Set<THREE.Material>();
root.traverse((child) => {
- if (child instanceof THREE.Mesh) {
- if (Array.isArray(child.material)) {
- child.material.forEach((m) => materials.add(m));
+ if ((child as { isMesh?: boolean }).isMesh) {
+ const meshChild = child as THREE.Mesh;
+ if (Array.isArray(meshChild.material)) {
+ meshChild.material.forEach((m) => materials.add(m));
} else {
- materials.add(child.material);
+ materials.add(meshChild.material);
}
}
});
@@ -1002,31 +1087,107 @@ export function buildSandboxGlobals(
return wrapped as F;
};
+ // -- Lazy mesh cache (per-sandbox, not a process global) ---------------
+ //
+ // Pattern adapted from chili3d's lazy-mesher: each parametric geometry is
+ // memoised on stringified args, so repeated calls inside a single build()
+ // return the same BufferGeometry reference. gltf-transform deduplicates
+ // on export but agents that don't reach for cloneGeometry/createInstance
+ // still get the win for free.
+ //
+ // Contract: callers must NOT mutate returned geometries. The existing
+ // primitive surface already follows this — every helper returns a fresh
+ // object today, and any caller that wants to mutate uses cloneGeometry
+ // first (already a no-op-by-design signal). With caching enabled, that
+ // signal becomes load-bearing: mutating a cached geometry corrupts every
+ // subsequent caller.
+ //
+ // Each cached geometry is also stamped with a `kilnRanges` entry on its
+ // userData (B3 — sub-shape mapping). The renderer ignores it (gltf-
+ // transform doesn't serialise userData), but downstream tooling — a
+ // future click-to-edit interaction in the gallery viewer — can map a
+ // clicked triangle back to the primitive call that produced it.
+ const geoCache = new Map<string, THREE.BufferGeometry>();
+ let _kilnCallSeq = 0;
+ const stampKilnRange = (name: string, geo: THREE.BufferGeometry) => {
+ const idx = geo.getIndex();
+ const triCount = idx
+ ? idx.count / 3
+ : (geo.getAttribute('position')?.count ?? 0) / 3;
+ const callId = ++_kilnCallSeq;
+ geo.userData = {
+ ...(geo.userData ?? {}),
+ kilnRanges: [
+ {
+ name: `${name}#${callId}`,
+ start: 0,
+ count: Math.floor(triCount),
+ },
+ ],
+ };
+ };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const cacheGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(
+ name: string,
+ fn: F
+ ): F => {
+ const memoFn = (...args: Parameters<F>): THREE.BufferGeometry => {
+ let key: string;
+ try {
+ key = `${name}::${JSON.stringify(args)}`;
+ } catch {
+ // Args weren't JSON-stringifiable (circular ref, BufferGeometry,
+ // etc.) — bypass the cache rather than throw, but still tag the
+ // result with kilnRanges so downstream inspection works.
+ const result = fn(...args);
+ stampKilnRange(name, result);
+ return result;
+ }
+ const hit = geoCache.get(key);
+ if (hit) return hit;
+ const result = fn(...args);
+ stampKilnRange(name, result);
+ geoCache.set(key, result);
+ return result;
+ };
+ return memoFn as F;
+ };
+ // Compose: usage tracking (outer) + memoisation (inner). A cache hit
+ // still ticks the usage counter so the telemetry reflects what the
+ // agent wrote, not what was recomputed.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const wrapGeo = <F extends (...args: any[]) => THREE.BufferGeometry>(
+ name: string,
+ fn: F
+ ): F => wrap(name, cacheGeo(name, fn));
+
return {
createRoot: wrap('createRoot', createRoot),
createPivot: wrap('createPivot', createPivot),
createPart: wrap('createPart', createPart),
- capsuleGeo: wrap('capsuleGeo', capsuleGeo),
- capsuleXGeo: wrap('capsuleXGeo', capsuleXGeo),
- capsuleYGeo: wrap('capsuleYGeo', capsuleYGeo),
- capsuleZGeo: wrap('capsuleZGeo', capsuleZGeo),
- cylinderGeo: wrap('cylinderGeo', cylinderGeo),
- cylinderXGeo: wrap('cylinderXGeo', cylinderXGeo),
- cylinderYGeo: wrap('cylinderYGeo', cylinderYGeo),
- cylinderZGeo: wrap('cylinderZGeo', cylinderZGeo),
- boxGeo: wrap('boxGeo', boxGeo),
- sphereGeo: wrap('sphereGeo', sphereGeo),
- coneGeo: wrap('coneGeo', coneGeo),
- coneXGeo: wrap('coneXGeo', coneXGeo),
- coneYGeo: wrap('coneYGeo', coneYGeo),
- coneZGeo: wrap('coneZGeo', coneZGeo),
- torusGeo: wrap('torusGeo', torusGeo),
- planeGeo: wrap('planeGeo', planeGeo),
- decalBox: wrap('decalBox', decalBox),
- foliageCardGeo: wrap('foliageCardGeo', foliageCardGeo),
- crossedQuadsGeo: wrap('crossedQuadsGeo', crossedQuadsGeo),
- octaGridPlane: wrap('octaGridPlane', octaGridPlane),
- wingGeo: wrap('wingGeo', wingGeo),
+ capsuleGeo: wrapGeo('capsuleGeo', capsuleGeo),
+ capsuleXGeo: wrapGeo('capsuleXGeo', capsuleXGeo),
+ capsuleYGeo: wrapGeo('capsuleYGeo', capsuleYGeo),
+ capsuleZGeo: wrapGeo('capsuleZGeo', capsuleZGeo),
+ cylinderGeo: wrapGeo('cylinderGeo', cylinderGeo),
+ cylinderXGeo: wrapGeo('cylinderXGeo', cylinderXGeo),
+ cylinderYGeo: wrapGeo('cylinderYGeo', cylinderYGeo),
+ cylinderZGeo: wrapGeo('cylinderZGeo', cylinderZGeo),
+ boxGeo: wrapGeo('boxGeo', boxGeo),
+ sphereGeo: wrapGeo('sphereGeo', sphereGeo),
+ coneGeo: wrapGeo('coneGeo', coneGeo),
+ coneXGeo: wrapGeo('coneXGeo', coneXGeo),
+ coneYGeo: wrapGeo('coneYGeo', coneYGeo),
+ coneZGeo: wrapGeo('coneZGeo', coneZGeo),
+ taperConeGeo: wrapGeo('taperConeGeo', taperConeGeo),
+ cylinderOnAxis: wrapGeo('cylinderOnAxis', cylinderOnAxis),
+ torusGeo: wrapGeo('torusGeo', torusGeo),
+ planeGeo: wrapGeo('planeGeo', planeGeo),
+ decalBox: wrapGeo('decalBox', decalBox),
+ foliageCardGeo: wrapGeo('foliageCardGeo', foliageCardGeo),
+ crossedQuadsGeo: wrapGeo('crossedQuadsGeo', crossedQuadsGeo),
+ octaGridPlane: wrapGeo('octaGridPlane', octaGridPlane),
+ wingGeo: wrapGeo('wingGeo', wingGeo),
createWingPair: wrap('createWingPair', createWingPair),
beamBetween: wrap('beamBetween', beamBetween),
createLadder: wrap('createLadder', createLadder),
@@ -1056,7 +1217,9 @@ export function buildSandboxGlobals(
subdivide: wrap('subdivide', ops.subdivide),
mergeVertices: wrap('mergeVertices', ops.mergeVertices),
curveToMesh: wrap('curveToMesh', ops.curveToMesh),
+ pipeAlongPath: wrap('pipeAlongPath', ops.pipeAlongPath),
lathe: wrap('lathe', ops.lathe),
+ revolveGeo: wrap('revolveGeo', ops.revolveGeo),
bezierCurve: wrap('bezierCurve', ops.bezierCurve),
// UV (async)
autoUnwrap: wrap('autoUnwrap', uv.autoUnwrap),
@@ -1064,9 +1227,10 @@ export function buildSandboxGlobals(
boxUnwrap: wrap('boxUnwrap', uvShapes.boxUnwrap),
cylinderUnwrap: wrap('cylinderUnwrap', uvShapes.cylinderUnwrap),
planeUnwrap: wrap('planeUnwrap', uvShapes.planeUnwrap),
+ panelRemapV: wrap('panelRemapV', uvShapes.panelRemapV),
// Parametric primitives
- gearGeo: wrap('gearGeo', gears.gearGeo),
- bladeGeo: wrap('bladeGeo', gears.bladeGeo),
+ gearGeo: wrapGeo('gearGeo', gears.gearGeo),
+ bladeGeo: wrapGeo('bladeGeo', gears.bladeGeo),
// Textures + PBR (loadTexture is async)
loadTexture: wrap('loadTexture', textures.loadTexture),
pbrMaterial: wrap('pbrMaterial', textures.pbrMaterial),
diff --git a/prompt.ts b/prompt.ts
index b167905b..1e866293 100644
--- a/prompt.ts
+++ b/prompt.ts
@@ -125,10 +125,12 @@ cylinderGeo(radiusTop, radiusBot, height, segments=8) // Y-axis (preferred)
cylinderXGeo(radiusTop, radiusBot, length, segments=8) // X-axis
cylinderYGeo(radiusTop, radiusBot, length, segments=8) // alias for cylinderGeo (Y-axis)
cylinderZGeo(radiusTop, radiusBot, length, segments=8) // Z-axis
+cylinderOnAxis(center: [x,y,z], normal: [x,y,z], radiusBottom, height, opts?: { radiusTop?, segments? }) // arbitrary axis — use only when not cardinal
coneGeo(radius, height, segments=8) // Y-axis, point +Y (preferred)
coneXGeo(radius, length, segments=8) // point +X
coneYGeo(radius, length, segments=8) // alias for coneGeo (point +Y)
coneZGeo(radius, length, segments=8) // point +Z
+taperConeGeo(radiusBottom, radiusTop, height, axis?='y', segments?=8) // truncated cone / frustum — use for soda cans, pylon caps, lampshades
capsuleGeo(radius, height, segments=6) // Y-axis (preferred)
capsuleXGeo(radius, length, segments=6) // X-axis
capsuleYGeo(radius, length, segments=6) // alias for capsuleGeo (Y-axis)
@@ -177,7 +179,9 @@ mergeVertices(geometry, tolerance=1e-4) // weld coincident verts; call before d
// Curves
curveToMesh(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)
+pipeAlongPath(points: [x,y,z][], radius, opts?: { bendRadius?, closed?, tubularSegments?, radialSegments? }) // path-driven swept circle with corner smoothing — use for cables, hoses, tubing, rigging
+lathe(profile: [x,y][], segments=12) // surface of revolution around Y axis (vase, wheel, bottle)
+revolveGeo(profile: [x,y][], opts?: { angle?=2π, axis?=[0,1,0], segments?=12 }) // partial sweep / non-Y axis (half-domes, 90° wedges, fan blades around +X)
bezierCurve(ctrlPts: [x,y,z][], samples=32) // returns [x,y,z][] — feed into curveToMesh
// UV + Textures (loadTexture is async; shape-aware unwraps are sync)
@@ -185,8 +189,11 @@ await autoUnwrap(geometry, { resolution?: 1024, padding?: 2 }) // xatlas atlas
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, posters
+panelRemapV(geo, vScale=0.30) // rescale UV.y so a SMALL part samples a sub-region of a SHARED texture (e.g. clean v=0..0.30 panel zone)
await loadTexture(path) // returns THREE.DataTexture with encoded bytes stashed for GLB export
pbrMaterial({ albedo?, normal?, roughness?, metalness?, emissive?, aoMap? }) // Any slot = color/scalar OR Texture
+// Do NOT clone a loaded texture (texture.clone() corrupts userData via JSON.stringify, breaking GLB export).
+// Use panelRemapV on the SMALL mesh's geometry instead, sharing the same Texture object across materials.
// Textured asset pipeline:
// 1. Build a geometry (boxGeo / CSG / subdivide / curveToMesh / etc)
@@ -233,6 +240,17 @@ For animations, track names must use "Joint_" prefix:
cylinders unless you have a specific reason.
- Use cylinderZGeo / capsuleZGeo / coneZGeo for side-facing rails, pods, floats,
and crossbars.
+- Use cylinderOnAxis(center, normal, radius, height) ONLY when the cylinder
+ needs to point along a non-cardinal direction (oblique struts, antennae off
+ a tilted face). For X/Y/Z-aligned parts the terser *XGeo / *YGeo / *ZGeo
+ helpers stay preferred.
+- Use taperConeGeo(rBottom, rTop, height) for truncated/frustum shapes (soda
+ cans, lampshades, pylon caps). coneGeo only does pointed cones.
+- Use pipeAlongPath(points, radius, { bendRadius }) for cables, hoses,
+ rigging, multi-segment piping. beamBetween is point-to-point only.
+- Use revolveGeo(profile, { angle, axis }) for partial sweeps (half-domes,
+ 90° wedges) or revolution around non-Y axes. lathe stays for full Y-axis
+ revolutions.
- Use beamBetween() for struts, braces, cables, skid supports, scaffolding, and
diagonal rails. Endpoints must touch the parts they connect to.
- Use createLadder() for ladders. A ladder must have two continuous rails and
diff --git a/render.ts b/render.ts
index 751fd30d..3bd51044 100644
--- a/render.ts
+++ b/render.ts
@@ -117,7 +117,12 @@ export async function executeKilnCode(code: string): Promise<ExecutedKilnCode> {
}
const root = await build();
- if (!(root instanceof THREE.Object3D)) {
+ // Duck-typed check — the kiln sandbox uses `new Function(...)`, which under
+ // bun creates an isolated module realm. `new THREE.X()` inside the sandbox
+ // produces objects whose constructor is a *different* class object from the
+ // THREE imported here, so `instanceof THREE.Object3D` returns false.
+ // Three.js sets `.isObject3D = true` on the prototype for exactly this case.
+ if (!(root as { isObject3D?: boolean })?.isObject3D) {
throw new Error('executeKilnCode: build() did not return a THREE.Object3D');
}
@@ -141,54 +146,65 @@ function bridgeMaterial(
const mat = doc.createMaterial(threeMat.name || undefined);
- if (threeMat instanceof THREE.MeshStandardMaterial) {
- mat.setBaseColorFactor([threeMat.color.r, threeMat.color.g, threeMat.color.b, threeMat.opacity]);
- mat.setRoughnessFactor(threeMat.roughness);
- mat.setMetallicFactor(threeMat.metalness);
- if (threeMat.emissive) {
- mat.setEmissiveFactor([threeMat.emissive.r, threeMat.emissive.g, threeMat.emissive.b]);
+ // Duck-typed material checks — see executeKilnCode for the rationale.
+ // Sandbox-created materials are different class instances of the same
+ // module, so `.isXMaterial` is the only reliable identity test.
+ const matFlags = threeMat as unknown as {
+ isMeshStandardMaterial?: boolean;
+ isMeshLambertMaterial?: boolean;
+ isMeshBasicMaterial?: boolean;
+ };
+ if (matFlags.isMeshStandardMaterial) {
+ const stdMat = threeMat as THREE.MeshStandardMaterial;
+ mat.setBaseColorFactor([stdMat.color.r, stdMat.color.g, stdMat.color.b, stdMat.opacity]);
+ mat.setRoughnessFactor(stdMat.roughness);
+ mat.setMetallicFactor(stdMat.metalness);
+ if (stdMat.emissive) {
+ mat.setEmissiveFactor([stdMat.emissive.r, stdMat.emissive.g, stdMat.emissive.b]);
}
- if (threeMat.transparent) {
+ if (stdMat.transparent) {
mat.setAlphaMode('BLEND');
}
- if (threeMat.side === THREE.DoubleSide) {
+ if (stdMat.side === THREE.DoubleSide) {
mat.setDoubleSided(true);
}
// PBR texture slots (Wave 3B)
- if (threeMat.map) {
- const t = bridgeTexture(doc, threeMat.map, textureCache);
+ if (stdMat.map) {
+ const t = bridgeTexture(doc, stdMat.map, textureCache);
if (t) mat.setBaseColorTexture(t);
}
- if (threeMat.normalMap) {
- const t = bridgeTexture(doc, threeMat.normalMap, textureCache);
+ if (stdMat.normalMap) {
+ const t = bridgeTexture(doc, stdMat.normalMap, textureCache);
if (t) mat.setNormalTexture(t);
}
// metallic + roughness live in one glTF texture (R=unused, G=rough, B=metal).
// If the agent used separate Three.js maps we emit the roughness one as
// the combined channel — the common case is a single combined map anyway.
- const mrSource = threeMat.roughnessMap ?? threeMat.metalnessMap;
+ const mrSource = stdMat.roughnessMap ?? stdMat.metalnessMap;
if (mrSource) {
const t = bridgeTexture(doc, mrSource, textureCache);
if (t) mat.setMetallicRoughnessTexture(t);
}
- if (threeMat.emissiveMap) {
- const t = bridgeTexture(doc, threeMat.emissiveMap, textureCache);
+ if (stdMat.emissiveMap) {
+ const t = bridgeTexture(doc, stdMat.emissiveMap, textureCache);
if (t) mat.setEmissiveTexture(t);
}
- if (threeMat.aoMap) {
- const t = bridgeTexture(doc, threeMat.aoMap, textureCache);
+ if (stdMat.aoMap) {
+ const t = bridgeTexture(doc, stdMat.aoMap, textureCache);
if (t) mat.setOcclusionTexture(t);
- mat.setOcclusionStrength(threeMat.aoMapIntensity ?? 1);
+ mat.setOcclusionStrength(stdMat.aoMapIntensity ?? 1);
}
- } else if (threeMat instanceof THREE.MeshLambertMaterial) {
- mat.setBaseColorFactor([threeMat.color.r, threeMat.color.g, threeMat.color.b, threeMat.opacity]);
+ } else if (matFlags.isMeshLambertMaterial) {
+ const lambMat = threeMat as THREE.MeshLambertMaterial;
+ mat.setBaseColorFactor([lambMat.color.r, lambMat.color.g, lambMat.color.b, lambMat.opacity]);
mat.setRoughnessFactor(1.0);
mat.setMetallicFactor(0.0);
- if (threeMat.emissive) {
- mat.setEmissiveFactor([threeMat.emissive.r, threeMat.emissive.g, threeMat.emissive.b]);
+ if (lambMat.emissive) {
+ mat.setEmissiveFactor([lambMat.emissive.r, lambMat.emissive.g, lambMat.emissive.b]);
}
- } else if (threeMat instanceof THREE.MeshBasicMaterial) {
- mat.setBaseColorFactor([threeMat.color.r, threeMat.color.g, threeMat.color.b, threeMat.opacity]);
+ } else if (matFlags.isMeshBasicMaterial) {
+ const basicMat = threeMat as THREE.MeshBasicMaterial;
+ mat.setBaseColorFactor([basicMat.color.r, basicMat.color.g, basicMat.color.b, basicMat.opacity]);
mat.setRoughnessFactor(1.0);
mat.setMetallicFactor(0.0);
}
@@ -304,18 +320,19 @@ function bridgeNode(
]);
gtNode.setScale([threeObj.scale.x, threeObj.scale.y, threeObj.scale.z]);
- if (threeObj instanceof THREE.Mesh) {
- const threeMat = threeObj.material as THREE.Material;
+ if ((threeObj as { isMesh?: boolean }).isMesh) {
+ const threeMesh = threeObj as THREE.Mesh;
+ const threeMat = threeMesh.material as THREE.Material;
const gtMat = bridgeMaterial(doc, threeMat, matCache, texCache);
// Key the mesh cache by (geometry ref, material ref) so createInstance
// (same geo + mat as source) produces a GLB-level mesh instance: a
// single Mesh referenced by multiple Nodes. Cuts duplicated accessors
// for wheels, bolts, fence posts, etc.
- const cacheKey = `${threeObj.geometry.uuid}__${threeMat.uuid}`;
+ const cacheKey = `${threeMesh.geometry.uuid}__${threeMat.uuid}`;
let gtMesh = meshCache.get(cacheKey);
if (!gtMesh) {
- gtMesh = bridgeGeometry(doc, buf, threeObj.geometry, gtMat, threeObj.name || 'mesh');
+ gtMesh = bridgeGeometry(doc, buf, threeMesh.geometry, gtMat, threeMesh.name || 'mesh');
meshCache.set(cacheKey, gtMesh);
}
gtNode.setMesh(gtMesh);
@@ -582,8 +599,9 @@ function collectMeshStats(root: THREE.Object3D): MeshStats[] {
root.updateMatrixWorld(true);
const out: MeshStats[] = [];
root.traverse((obj) => {
- if (!(obj instanceof THREE.Mesh)) return;
- const geo = obj.geometry;
+ if (!(obj as { isMesh?: boolean }).isMesh) return;
+ const meshObj = obj as THREE.Mesh;
+ const geo = meshObj.geometry;
if (!geo) return;
const idx = geo.getIndex();
@@ -601,7 +619,7 @@ function collectMeshStats(root: THREE.Object3D): MeshStats[] {
out.push({
name: obj.name || '(unnamed)',
triCount: Math.floor(tri),
- isPlaneGeo: geo instanceof THREE.PlaneGeometry,
+ isPlaneGeo: geo.type === 'PlaneGeometry',
center,
size,
box,
diff --git a/solids.ts b/solids.ts
index b396e75d..7a1b0696 100644
--- a/solids.ts
+++ b/solids.ts
@@ -62,12 +62,15 @@ function threeToManifold(src: THREE.Object3D, ManifoldCls: typeof Manifold, Mesh
let vertexOffset = 0;
src.traverse((child) => {
- if (!(child instanceof THREE.Mesh)) return;
- const geo = child.geometry as THREE.BufferGeometry;
+ // Duck-typed `.isMesh` — sandbox-created meshes belong to a different
+ // module realm than this file's THREE import. See render.ts comment.
+ if (!(child as { isMesh?: boolean }).isMesh) return;
+ const meshChild = child as THREE.Mesh;
+ const geo = meshChild.geometry as THREE.BufferGeometry;
const posAttr = geo.getAttribute('position') as THREE.BufferAttribute | undefined;
if (!posAttr) return;
- const matrix = child.matrixWorld;
+ const matrix = meshChild.matrixWorld;
for (let i = 0; i < posAttr.count; i++) {
tmpVec.fromBufferAttribute(posAttr, i).applyMatrix4(matrix);
@@ -162,7 +165,7 @@ function splitPartsAndOpts(
if (
last &&
typeof last === 'object' &&
- !(last instanceof THREE.Object3D) &&
+ !(last as { isObject3D?: boolean }).isObject3D &&
('smooth' in last)
) {
return {
@@ -174,14 +177,92 @@ function splitPartsAndOpts(
}
function materialOf(src: THREE.Object3D, fallback: THREE.Material): THREE.Material {
- if (src instanceof THREE.Mesh) return src.material as THREE.Material;
+ if ((src as { isMesh?: boolean }).isMesh) {
+ return (src as THREE.Mesh).material as THREE.Material;
+ }
let found: THREE.Material | null = null;
src.traverse((c) => {
- if (!found && c instanceof THREE.Mesh) found = c.material as THREE.Material;
+ if (!found && (c as { isMesh?: boolean }).isMesh) {
+ found = (c as THREE.Mesh).material as THREE.Material;
+ }
});
return found ?? fallback;
}
+interface KilnRange {
+ name: string;
+ start: number;
+ count: number;
+}
+
+/**
+ * Synthesise a `kilnRanges` array for a CSG output by walking each input's
+ * geometry.userData.kilnRanges (or falling back to mesh names + tri counts)
+ * and weight-partitioning the *output* triangle count among them. The
+ * partition is a coarse approximation — manifold-3d does not preserve per-
+ * triangle provenance, so we cannot map output tris back to input tris
+ * exactly. Sum invariant holds: `Σ count === outputTris`.
+ *
+ * The metadata is consumed by future click-to-inspect UI; the GLB exporter
+ * ignores it (gltf-transform doesn't serialise userData).
+ */
+function combineRangesFromCsgInputs(
+ parts: THREE.Object3D[],
+ outputTris: number
+): KilnRange[] {
+ const inputs: Array<{ name: string; weight: number }> = [];
+ for (const part of parts) {
+ part.traverse((child) => {
+ if (!(child as { isMesh?: boolean }).isMesh) return;
+ const meshChild = child as THREE.Mesh;
+ if (!meshChild.geometry) return;
+ const ranges = (meshChild.geometry.userData as Record<string, unknown>)['kilnRanges'] as
+ | KilnRange[]
+ | undefined;
+ if (ranges && ranges.length > 0) {
+ for (const r of ranges) inputs.push({ name: r.name, weight: r.count });
+ return;
+ }
+ // No prior ranges — fall back to mesh name + own tri count.
+ const idx = meshChild.geometry.getIndex();
+ const tris = idx
+ ? idx.count / 3
+ : (meshChild.geometry.getAttribute('position')?.count ?? 0) / 3;
+ inputs.push({ name: meshChild.name || 'csgInput', weight: Math.floor(tris) });
+ });
+ }
+
+ if (inputs.length === 0) {
+ return [{ name: 'csg', start: 0, count: outputTris }];
+ }
+ const totalWeight = inputs.reduce((s, i) => s + i.weight, 0) || 1;
+ const out: KilnRange[] = [];
+ let offset = 0;
+ for (let i = 0; i < inputs.length; i++) {
+ const isLast = i === inputs.length - 1;
+ const weight = inputs[i]!.weight;
+ const count = isLast
+ ? outputTris - offset
+ : Math.floor((weight / totalWeight) * outputTris);
+ out.push({ name: inputs[i]!.name, start: offset, count });
+ offset += count;
+ }
+ return out;
+}
+
+/** Stamp `kilnRanges` on the result mesh's geometry from its CSG inputs. */
+function tagCsgOutput(result: THREE.Mesh, parts: THREE.Object3D[]): void {
+ const idx = result.geometry.getIndex();
+ const tris = idx
+ ? idx.count / 3
+ : (result.geometry.getAttribute('position')?.count ?? 0) / 3;
+ const ranges = combineRangesFromCsgInputs(parts, Math.floor(tris));
+ result.geometry.userData = {
+ ...(result.geometry.userData ?? {}),
+ kilnRanges: ranges,
+ };
+}
+
// =============================================================================
// Public primitives
// =============================================================================
@@ -210,6 +291,7 @@ export async function boolUnion(
const result = mod.Manifold.union(manifolds);
const mat = materialOf(parts[0]!, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
+ tagCsgOutput(mesh, parts);
manifolds.forEach((m) => m.delete());
result.delete();
return mesh;
@@ -242,6 +324,7 @@ export async function boolDiff(
const result = bodyM.subtract(cutterUnion);
const mat = materialOf(body, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
+ tagCsgOutput(mesh, [body, ...cutters]);
bodyM.delete();
cutterM.forEach((m) => m.delete());
if (cutterM.length > 1) cutterUnion.delete();
@@ -267,6 +350,7 @@ export async function boolIntersect(
const result = aM.intersect(bM);
const mat = materialOf(a, new THREE.MeshStandardMaterial());
const mesh = manifoldToThree(result, mat, `Mesh_${name}`, opts);
+ tagCsgOutput(mesh, [a, b]);
aM.delete();
bM.delete();
result.delete();
@@ -295,6 +379,7 @@ export async function hull(
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}`, { smooth: opts.smooth ?? true });
+ tagCsgOutput(mesh, parts);
manifolds.forEach((m) => m.delete());
if (manifolds.length > 1) result.delete();
return mesh;
diff --git a/textures.ts b/textures.ts
index 8a03c637..9d87298c 100644
--- a/textures.ts
+++ b/textures.ts
@@ -142,36 +142,41 @@ export interface PbrMaterialOptions {
export function pbrMaterial(opts: PbrMaterialOptions = {}): THREE.MeshStandardMaterial {
const mat = new THREE.MeshStandardMaterial();
- if (opts.albedo instanceof THREE.Texture) {
+ // Duck-typed `.isTexture` — sandbox-created textures may belong to a
+ // different module realm. See render.ts cross-module-THREE comment.
+ const isTex = (v: unknown): v is THREE.Texture =>
+ !!(v as { isTexture?: boolean } | null)?.isTexture;
+
+ if (isTex(opts.albedo)) {
mat.map = opts.albedo;
mat.color = new THREE.Color(0xffffff);
} else if (opts.albedo !== undefined) {
- mat.color = new THREE.Color(opts.albedo);
+ mat.color = new THREE.Color(opts.albedo as number | string);
}
if (opts.normal) mat.normalMap = opts.normal;
- if (opts.roughness instanceof THREE.Texture) {
+ if (isTex(opts.roughness)) {
mat.roughnessMap = opts.roughness;
mat.roughness = 1;
} else if (opts.roughness !== undefined) {
- mat.roughness = opts.roughness;
+ mat.roughness = opts.roughness as number;
} else {
mat.roughness = 0.8;
}
- if (opts.metalness instanceof THREE.Texture) {
+ if (isTex(opts.metalness)) {
mat.metalnessMap = opts.metalness;
mat.metalness = 1;
} else if (opts.metalness !== undefined) {
- mat.metalness = opts.metalness;
+ mat.metalness = opts.metalness as number;
}
- if (opts.emissive instanceof THREE.Texture) {
+ if (isTex(opts.emissive)) {
mat.emissiveMap = opts.emissive;
mat.emissive = new THREE.Color(0xffffff);
} else if (opts.emissive !== undefined) {
- mat.emissive = new THREE.Color(opts.emissive);
+ mat.emissive = new THREE.Color(opts.emissive as number | string);
}
if (opts.emissiveIntensity !== undefined) {
mat.emissiveIntensity = opts.emissiveIntensity;
diff --git a/uv-shapes.ts b/uv-shapes.ts
index a3d3e750..30fc4576 100644
--- a/uv-shapes.ts
+++ b/uv-shapes.ts
@@ -77,6 +77,48 @@ export function planeUnwrap(geo: THREE.BufferGeometry): THREE.BufferGeometry {
return cloned;
}
+/**
+ * Remap an existing UV attribute to a sub-region of the texture, by scaling
+ * U by `uScale` and V by `vScale` (both default 1.0 = identity), with
+ * optional offsets `uOffset`/`vOffset`. Use this when you want a small mesh
+ * to sample a specific zone of a SHARED texture without cloning the texture
+ * itself — Three.js `Texture.clone()` runs `JSON.parse(JSON.stringify(...))`
+ * on userData, which mangles the encoded PNG `Uint8Array` (becomes a plain
+ * object) and breaks the GLB bridge.
+ *
+ * Typical use: a multi-zone albedo where the bottom 30% (v=0..0.30) is a
+ * clean panel-only region and the top 70% (v=0.30..1.0) carries
+ * windows/markings/decoration. The fuselage uses the full UV range; smaller
+ * parts (engine cowling, tail boom, fin) call `panelRemapV(geo, 0.30)` so
+ * their 0..1 UV.y collapses to 0..0.30, sampling only the clean strip.
+ *
+ * Operates on a CLONE of the input; input geometry is not mutated.
+ *
+ * @example
+ * // Engine cowling shares the body's bodyMat but only samples the clean
+ * // bottom strip — no doorway/window pixels show on the small part.
+ * const cowlGeo = panelRemapV(cylinderUnwrap(capsuleXGeo(0.45, 1.0)), 0.30);
+ * const cowl = new THREE.Mesh(cowlGeo, bodyMat);
+ */
+export function panelRemapV(
+ geo: THREE.BufferGeometry,
+ vScale = 0.30,
+ vOffset = 0,
+ uScale = 1,
+ uOffset = 0,
+): THREE.BufferGeometry {
+ const cloned = geo.clone();
+ const uvAttr = cloned.getAttribute('uv') as THREE.BufferAttribute | undefined;
+ if (!uvAttr) return cloned;
+ const arr = uvAttr.array as Float32Array;
+ for (let i = 0; i < arr.length; i += 2) {
+ arr[i] = (arr[i] ?? 0) * uScale + uOffset;
+ arr[i + 1] = (arr[i + 1] ?? 0) * vScale + vOffset;
+ }
+ uvAttr.needsUpdate = true;
+ return cloned;
+}
+
// =============================================================================
// Internal helpers
// =============================================================================