Skip to content

armgit / kiln

Public Imported from GitHub
0

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

feat(organic): adapt contributed field and path helpers to current Kiln

Matt Kissinger2f321dae0973
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b9431047..40bf11cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,14 @@ Source releases and installable package publication are separate milestones.
Published versions and tags are recorded by the npm registry; changing this file
does not publish a package.
+## Unreleased
+
+- Adapt the non-rock organic helpers contributed by [FaberVi (Vincenzo Fabiano)](https://github.com/FaberVi)
+ in [#141](https://github.com/instruktlabs/kiln/pull/141): metaball surfaces, field
+ composition, sampled paths, tapered tubes, curls and smoothing. Maintainer
+ integration corrects sampling, recipes, input validation and unsafe count arithmetic while
+ retaining the original blend default. See the [provenance record](docs/reviews/2026-10-16-organic-adoption.md).
+
## 1.2.3 (2026-10-12)
- Allow concurrent renderer clients to await verified health through the shared
diff --git a/docs/geometry.md b/docs/geometry.md
index efe19105..412853c5 100644
--- a/docs/geometry.md
+++ b/docs/geometry.md
@@ -355,6 +355,36 @@ const blob = await implicitSurface(
);
```
+Higher-level organic helpers build on the same positive-inside convention:
+`metaballSurface` smooth-unions spheres; `taperedTube` and `catmullRomPath` author
+smooth limbs and tentacles; `smoothOrganic` subdivides then limits crease angles;
+`smoothUnion` and `sphereInside` compose custom fields inside `implicitSurface` callbacks.
+
+`taperedTube` takes one radius per sampled path point. Derive radii from the
+returned path length, not the original control-point count. `catmullRomPath`
+includes both endpoints on open curves and omits the repeated endpoint on closed
+curves, so its closed output can feed `taperedTube(..., { closed: true })` directly.
+Both `catmullRomPath` and `spiralPath` reject derived sample counts that exceed
+safe-integer precision before sampling.
+
+`metaballSurface` retains the experimental implicit-surface limits and has no UVs.
+Its default blend is `Math.max(0.35 * smallestRadius, 0.02)` in scene units; provide
+`blend` explicitly when scaling a shape. More spheres add work to every field
+sample; finer `edgeLength` increases mesh cost. Bounds must include the desired
+surface, including blended junctions.
+Metaballs use `implicitSurface`'s existing default grid and field-callback limits;
+explicit `maxCells` and `maxEvaluations` ceilings pass through unchanged.
+`maxEvaluations` counts field callbacks, not the individual spheres evaluated by
+each callback. More spheres therefore increase work within that ceiling. Use the
+host's process-bounded evaluator when execution deadlines matter.
+
+`spiralPath` is a rising, shrinking curl: it starts `radius` away from `center`
+along the projected `forward` direction, rises by `rise`, and ends at 42% of the
+initial radius after `turns` turns. `smoothOrganic` changes geometry through
+subdivision before computing crease normals. It can increase triangle count
+sharply and drops UVs by default; use `preserveUV: true` when retaining supported
+corner attributes and material boundaries matters.
+
The field is **positive inside**. Bounds and `edgeLength` are required. Smaller spacing can increase cost sharply and is necessary for thin features. The default limits are one million estimated grid cells and eight million actual callback evaluations; `maxCells` and `maxEvaluations` are explicit overrides. An evaluation counter cannot stop a callback that never returns: use the host's process-bounded evaluator for untrusted source.
Output is experimental, has no UVs, and records resolution and evaluation counts. A finite grid cannot guarantee preservation of every thin feature or exact CAD dimensions. See the [candidate measurements and adoption decisions](https://github.com/instruktlabs/kiln/blob/main/docs/experiments/geometry-frontier.md) for implicit surfaces, general beveling, normal-offset shells, and mesh-to-field remeshing.
diff --git a/docs/reviews/2026-10-16-organic-adoption.md b/docs/reviews/2026-10-16-organic-adoption.md
new file mode 100644
index 00000000..f51b5d88
--- /dev/null
+++ b/docs/reviews/2026-10-16-organic-adoption.md
@@ -0,0 +1,73 @@
+# Selected organic helper adoption: provenance and scope
+
+This records source provenance and the integration scope. It is not release or
+visual acceptance, and does not override the current engine contracts.
+
+## Original contribution
+
+- Contributor: FaberVi (Vincenzo Fabiano).
+- Original PR: https://github.com/instruktlabs/kiln/pull/141
+- Original code commit: `e738b29bda2cf7ce6ed7c89b316b7d20474235cf`.
+- Original author and committer: `Cursor Agent <[email protected]>`.
+- Original trailer: `Co-authored-by: Vincenzo Fabiano <[email protected]>`.
+- Reviewed PR head: `a664d787db4eacb646d54780d5f9e2c09af368a5`.
+- Original extraction base: `743965ac` (origin/main when the extraction worktree was created).
+- Combined candidate base: `86e369fe` (the local delivery-contract branch, which includes that main revision).
+
+An exact `git show --format=fuller --binary` record of the original code commit
+is retained in the local review evidence as `organic-adoption-origin.patch`.
+Its SHA-256 is `d6482ef5686c29ff58fd634d466b8bae53cf3c2b4a68c38e322d691518926c67`.
+The original immutable commit is the repository source of truth; the local
+evidence copy is not a package dependency.
+
+## Retained and adapted work
+
+| Original contribution | Integration treatment |
+| --- | --- |
+| `metaballSurface`, `sphereInside`, `smoothUnion` | Retained on existing implicit-surface infrastructure. Preserve original blend shape default; align documentation and reject invalid field inputs. |
+| `catmullRomPath`, `taperedTube` | Retained on existing sweep infrastructure. Correct sample counts and closed-path endpoint composition. |
+| `spiralPath` | Retain the small specialized curl helper; document its fixed shrink, start offset and positive rise; reject nonfinite direction vectors. |
+| `smoothOrganic` | Retain subdivision/normal convenience; state geometry cost and default UV/material-group effects. |
+| Sandbox/public wiring, Discovery, tests and recipes | Retain selected helper entries; correct executable radii recipes, contract facts and generated API snapshot. |
+
+`smoothUnionSpheres` is retained as the internal implementation shared by
+metaballs and SDF tests, without adding another package or sandbox API.
+
+## Deferred work and excluded dependencies
+
+`rockDisplace` and `rockBoulder`, including their aspect/sliver utilities, remain
+credited original work but are excluded from this integration. Displacement
+needs seam-preservation work; boulder proportions, retry/fallback behavior and
+solid-contract integration need separate agreement. Deferral is not rejection
+of the contributor or a claim that those helpers have no value.
+
+PR #140's universal topology blocker and facet detector are not dependencies.
+PR #142's runner, guards, warning filters, fixtures and benchmark infrastructure
+are not included. This subset does not depend on the later local delivery
+contract branch's `requireSolid` API. Existing rock-cluster examples cannot run
+unchanged without the deferred rock helper.
+
+## Maintainer corrections and verification boundary
+
+The maintainer integration adds focused regressions for open/closed sampling,
+closed-tube composition, executable catalog and maintained skill recipes,
+retention of the contributed default blend, and invalid field/direction inputs.
+Those tests were observed failing against the extracted implementation before
+the corresponding fixes. Geometry checks establish structural properties, not
+art quality, runtime suitability or owner acceptance.
+
+An intermediate maintainer pass added a fixed aggregate sphere-work ceiling and
+borrowed the parametric-sample cap for path output. Those restrictions were not
+part of the contributor's implementation and were removed after review: their
+thresholds were not calibrated for these helpers. Metaballs now pass existing
+implicit-surface defaults and explicit grid/callback ceilings through unchanged.
+Paths retain derived safe-integer validation without a new output-count policy.
+Regressions verify larger caller ceilings, tighter existing limits, valid paths
+above the removed threshold, and unsafe-count rejection before sampling.
+
+Keep the original author/coauthor identity when carrying original commits. If
+selected work is recorded in a replacement integration commit, retain the exact
+coauthor trailer above and reference PR #141 and the original commit. Maintainer
+corrections should be described as adaptations, not as original authorship of
+the contributed helpers. No commit, merge, push or release is implied by this
+provenance record.
diff --git a/skills/kiln-author-asset/references/geometry-recipes.md b/skills/kiln-author-asset/references/geometry-recipes.md
index 108ef7af..6a92c0be 100644
--- a/skills/kiln-author-asset/references/geometry-recipes.md
+++ b/skills/kiln-author-asset/references/geometry-recipes.md
@@ -473,6 +473,45 @@ const blob = await implicitSurface(([x,y,z]) => 1 - Math.hypot(x,y,z), {
Positive values are inside. Bounds/resolution are required; smaller cells cost more and thin features can disappear. Explicit grid/evaluation limits apply. Output has no UVs. Use this for a deliberate organic/cellular experiment, not an unsupported promise of general shelling, remeshing, or CAD accuracy.
+## Organic curves and blended volumes
+
+Prefer smooth paths and round profiles before adding detail:
+
+```js
+const path = catmullRomPath([[0,0,0],[0.2,0.4,0.1],[0.5,0.2,0]], 8);
+const radii = path.map((_, i) => 0.06 - 0.04 * i / (path.length - 1));
+const limb = taperedTube(path, radii, { radialSegments: 16, creaseAngle: 180 });
+const soft = smoothOrganic(limb, { iterations: 1, creaseAngle: 50 });
+```
+
+Use one radius per sampled station. Closed `catmullRomPath` output omits the
+repeated endpoint and can feed `taperedTube(path, radii, { closed: true })` directly.
+Path helpers reject derived sample counts that exceed safe-integer precision.
+Subdivision changes the shape and increases triangle count; inspect the result
+before adding iterations. `smoothOrganic` drops UVs by default; use `preserveUV: true` when retaining supported corner attributes and material boundaries matters.
+
+`metaballSurface` smooth-unions spheres for torsos, bells and heads without visible CSG seams:
+
+```js
+const torso = await metaballSurface(
+ [{ center: [0,0.4,0], radius: 0.3 }, { center: [0.2,0.45,0], radius: 0.22 }],
+ { bounds: { min: [-0.4,0,-0.35], max: [0.45,0.7,0.35] }, edgeLength: 0.06, blend: 0.08 },
+);
+```
+
+Compose custom fields with `sphereInside` and `smoothUnion` inside `implicitSurface` when metaballs are not enough.
+
+The default metaball blend is `max(0.35 * smallestRadius, 0.02)` in scene units;
+choose an explicit blend when scaling. Include blended junctions inside the
+sampling bounds. Finer cells cost more and do not guarantee thin-feature fidelity;
+the result remains experimental and has no UVs. For a rising tail curl,
+`spiralPath` starts one radius away from its center and shrinks to 42% of that
+radius over the requested turns. It does not produce a constant-radius helix.
+Metaballs use the existing implicit-surface grid and callback limits, including
+explicit `maxCells` and `maxEvaluations` overrides. The callback count does not
+include individual sphere evaluations, so additional spheres increase work.
+Use the host evaluator's process/time boundary for execution deadlines.
+
For textures, preserve valid primitive UVs. Use `copyGeometry` before independent
buffer edits, `remapUV` to scale/offset UVs, and `projectUV` for explicit planar,
diff --git a/src/__tests__/__snapshots__/prompt-api.test.ts.snap b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
index a67a6208..e6a939ed 100644
--- a/src/__tests__/__snapshots__/prompt-api.test.ts.snap
+++ b/src/__tests__/__snapshots__/prompt-api.test.ts.snap
@@ -227,6 +227,22 @@ await implicitSurface(sample: ([x,y,z]) => signedValue, { bounds: { min, max },
// boundary. Thin features and geometric accuracy require inspection.
// e.g. const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min:
// [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });
+await metaballSurface(spheres: { center: [x,y,z], radius }[], { bounds, edgeLength, blend?, maxCells?, maxEvaluations? })
+ // Experimental smooth union of spheres meshed through implicitSurface. Uses polynomial
+ // blending; output has no UVs.
+ // NOTE: Prefer this over hand-rolling smoothUnion fields for creatures, blobs and rounded
+ // junctions. Match edgeLength to feature size.
+ // e.g. const body = await metaballSurface([{ center: [0,0.4,0], radius: 0.35 }, { center:
+ // [0.2,0.55,0], radius: 0.22 }], { bounds: { min: [-0.6,-0.1,-0.5], max: [0.6,1,0.5] },
+ // edgeLength: 0.08 });
+smoothUnion(a: number, b: number, blend: number)
+ // Polynomial smooth maximum for positive-inside implicit fields. Compose inside
+ // implicitSurface callbacks.
+ // e.g. smoothUnion(sphereInside(p,[0,0,0],0.5), sphereInside(p,[0.3,0,0],0.4), 0.12)
+sphereInside(point: [x,y,z], center: [x,y,z], radius: number)
+ // Positive-inside sphere field sample for implicitSurface. Returns radius minus distance to
+ // center.
+ // e.g. sphereInside(p, [0,0.4,0], 0.25)
boxGeo(width: number, height: number, depth: number) // 6-face box. 12 tris regardless of size. Cheapest geometry.
// e.g. const geo = boxGeo(1, 0.5, 2);
sphereGeo(radius: number, widthSegments?: 8, heightSegments?: 6)
@@ -570,6 +586,9 @@ displace(geometry, offset: ([x,y,z], t) => [dx,dy,dz], opts?: { frame?: { origin
// Adds an authored displacement vector in the chosen local frame. Returns owned geometry;
// callback coordinates are local and t is normalized along the interval.
// e.g. const rippled = displace(surface, ([x,y,z]) => [0, 0.1*Math.sin(x*8), 0]);
+smoothOrganic(geometry, opts?: { iterations?: 1, creaseAngle?: 55, preserveUV?: false })
+ // Runs subdivide then creaseNormals with organic-friendly defaults.
+ // e.g. const soft = smoothOrganic(tube, { iterations: 1, creaseAngle: 50 });
bakeSurfaceAttributes(target: Object3D, opts?: { edge?: { thresholdDegrees?: 35, smoothing?: 1 } | false, cavity?: { rays?: 32, radius?, occluders? } | false })
// Bakes two float vertex attributes in [0, 1] on every visible mesh in target: _edge (convex
// rim weight, 1 on chamfers and rims, 0 on flat faces) and _cavity (exposure, 1 open, toward
@@ -615,6 +634,21 @@ loftProfiles(sections: { profile: [x,z][], frame?: { origin, rotation } }[], opt
// self-intersections.
// e.g. const hull = loftProfiles([{ profile: wide }, { profile: narrow, frame: { origin:
// [0,2,0] } }]);
+taperedTube(path: [x,y,z][], radii: number[], opts?: { radialSegments?: 20, creaseAngle?: 180, cap?: true, closed?: false, up?, twist?, sectionScale?: [side,depth][] })
+ // Circular sweep with one radius per path station. Default creaseAngle 180 shades round
+ // profiles smoothly; sample splines with catmullRomPath first.
+ // e.g. const path = catmullRomPath([[0,0.5,0],[0.3,0.7,0],[0.5,0.4,0]], 6); const radii =
+ // path.map((_, i) => 0.08 - 0.06 * i / (path.length - 1)); const tail = taperedTube(path,
+ // radii);
+catmullRomPath(controlPoints: [x,y,z][], samplesPerSpan?: 8, closed?: false)
+ // Samples a Catmull-Rom spline through waypoints. Open paths include both endpoints; closed
+ // paths omit the repeated endpoint for closed sweeps.
+ // e.g. const path = catmullRomPath([[0,0,0],[0.2,0.4,0.1],[0.5,0.2,0]], 10);
+spiralPath(opts: { center, radius, rise, turns, axis?, forward?, samples? })
+ // Rising spiral for curled appendages, shrinking to 42% of the start radius. Returns samples
+ // + 1 stations; starts radius away from center.
+ // e.g. const curl = spiralPath({ center: [0,0.05,0], radius: 0.03, rise: 0.12, turns: 1.75,
+ // forward: [0,0,1] });
curveToMesh(points: [x,y,z][], radius, tubularSegs?: 32, radialSegs?: 8, closed?: false)
// Sweeps a circular profile along a path. Equivalent to Blender's Curve to Mesh node with a
// circle profile. Use for pipes, cables, tubular frames.
diff --git a/src/__tests__/organic-contract.test.ts b/src/__tests__/organic-contract.test.ts
new file mode 100644
index 00000000..7c68b669
--- /dev/null
+++ b/src/__tests__/organic-contract.test.ts
@@ -0,0 +1,245 @@
+import { expect, spyOn, test } from 'bun:test';
+import * as THREE from 'three';
+import { readFileSync } from 'node:fs';
+import { geometryDiagnostics, type Point3 } from '../geometry';
+import { geometryPrimitives } from '../geometry-catalog';
+import {
+ catmullRomPath,
+ metaballSurface,
+ smoothOrganic,
+ spiralPath,
+ taperedTube,
+} from '../organic';
+
+test('spline rejects unsafe derived counts before invoking the curve sampler', () => {
+ const sample = spyOn(THREE.CatmullRomCurve3.prototype, 'getPoints').mockImplementation(() => {
+ throw new Error('SAMPLER_CALLED');
+ });
+ try {
+ for (const closed of [false, true])
+ expect(() =>
+ catmullRomPath(
+ [
+ [0, 0, 0],
+ [1, 0, 0],
+ [1, 1, 0],
+ ],
+ Number.MAX_SAFE_INTEGER,
+ closed,
+ ),
+ ).toThrow('safe integer');
+ expect(sample).not.toHaveBeenCalled();
+ } finally {
+ sample.mockRestore();
+ }
+});
+
+test('spiral rejects an unsafe derived count before evaluating its first station', () => {
+ const cosine = spyOn(Math, 'cos').mockImplementation(() => {
+ throw new Error('STATION_CALLED');
+ });
+ try {
+ expect(() =>
+ spiralPath({
+ center: [0, 0, 0],
+ radius: 1,
+ rise: 1,
+ turns: 1,
+ samples: Number.MAX_SAFE_INTEGER,
+ }),
+ ).toThrow('safe integer');
+ expect(cosine).not.toHaveBeenCalled();
+ } finally {
+ cosine.mockRestore();
+ }
+});
+
+test('closed spline validates the temporary repeated endpoint count before reading controls', () => {
+ let reads = 0;
+ const controls = new Proxy([] as Point3[], {
+ get(_target, key) {
+ if (key === 'length') return 6361;
+ reads++;
+ throw new Error('CONTROL_READ');
+ },
+ });
+ // The closed output count is exactly MAX_SAFE_INTEGER; getPoints temporarily
+ // creates one additional endpoint before it is removed.
+ expect(() => catmullRomPath(controls, 1_416_003_655_831, true)).toThrow('safe integer');
+ expect(reads).toBe(0);
+});
+
+test('spline supports valid output above the removed 262144-station cap', () => {
+ const path = catmullRomPath(
+ [
+ [0, 0, 0],
+ [1, 0, 0],
+ ],
+ 262_144,
+ );
+ expect(path).toHaveLength(262_145);
+ expect(path[0]).toEqual([0, 0, 0]);
+ expect(path[131_072]![0]).toBeCloseTo(0.5, 8);
+ expect(path.at(-1)).toEqual([1, 0, 0]);
+});
+
+test('spiral supports valid output above the removed 262144-station cap', () => {
+ const path = spiralPath({ center: [0, 0, 0], radius: 1, rise: 1, turns: 1, samples: 262_144 });
+ expect(path).toHaveLength(262_145);
+ expect(path[0]).toEqual([0, 0, 1]);
+ expect(path.at(-1)![1]).toBeCloseTo(1, 8);
+ expect(path.at(-1)![2]).toBeCloseTo(0.42, 8);
+});
+
+const budgetSpheres = [
+ { center: [0, 0, 0] as Point3, radius: 0.2 },
+ { center: [0.2, 0, 0] as Point3, radius: 0.2 },
+];
+const budgetOptions = {
+ bounds: { min: [-0.4, -0.4, -0.4] as Point3, max: [0.6, 0.4, 0.4] as Point3 },
+ edgeLength: 0.1,
+};
+
+test('metaball inherits the existing implicit grid and evaluation defaults', async () => {
+ const geometry = await metaballSurface(budgetSpheres, budgetOptions);
+ expect(geometry.userData.kilnImplicit.maxCells).toBe(1_000_000);
+ expect(geometry.userData.kilnImplicit.maxEvaluations).toBe(8_000_000);
+});
+
+test('metaball passes explicit larger grid and evaluation ceilings through unchanged', async () => {
+ const geometry = await metaballSurface(budgetSpheres, {
+ ...budgetOptions,
+ maxCells: 2_000_000,
+ maxEvaluations: 16_000_000,
+ });
+ expect(geometry.userData.kilnImplicit.maxCells).toBe(2_000_000);
+ expect(geometry.userData.kilnImplicit.maxEvaluations).toBe(16_000_000);
+ const tighter = await metaballSurface(budgetSpheres, {
+ ...budgetOptions,
+ maxEvaluations: 50_000,
+ });
+ expect(tighter.userData.kilnImplicit.maxEvaluations).toBe(50_000);
+ expect(geometry.getAttribute('position').array).toEqual(tighter.getAttribute('position').array);
+});
+
+test('metaball still enforces caller-selected implicit limits and input validation', async () => {
+ await expect(
+ metaballSurface(budgetSpheres, { ...budgetOptions, maxEvaluations: 1 }),
+ ).rejects.toThrow('maxEvaluations 1');
+ await expect(metaballSurface(budgetSpheres, { ...budgetOptions, maxCells: 1 })).rejects.toThrow(
+ 'exceeds maxCells 1',
+ );
+ for (const maxEvaluations of [0, Infinity, 1.5])
+ await expect(
+ metaballSurface(budgetSpheres, { ...budgetOptions, maxEvaluations }),
+ ).rejects.toThrow('positive safe integer');
+});
+
+test('open spline samples each span and includes both endpoints', () => {
+ const controls: Point3[] = [
+ [0, 0, 0],
+ [0, 1, 0],
+ [1, 1, 0],
+ ];
+ const path = catmullRomPath(controls, 8);
+ expect(path).toHaveLength(17);
+ expect(path[0]).toEqual(controls[0]);
+ expect(path.at(-1)).toEqual(controls.at(-1));
+});
+
+test('closed spline composes with closed tube without a duplicate endpoint', () => {
+ const path = catmullRomPath(
+ [
+ [0, 0, 0],
+ [1, 0, 0],
+ [1, 0, 1],
+ [0, 0, 1],
+ ],
+ 4,
+ true,
+ );
+ expect(path).toHaveLength(16);
+ expect(path.at(-1)).not.toEqual(path[0]);
+ const geometry = taperedTube(
+ path,
+ path.map(() => 0.08),
+ { closed: true },
+ );
+ const diagnostics = geometryDiagnostics(geometry);
+ expect(diagnostics.boundaryEdges).toBe(0);
+ expect(diagnostics.degenerateTriangles).toBe(0);
+});
+
+test('closed spline requires enough distinct stations for its sweep companion', () => {
+ expect(() =>
+ catmullRomPath(
+ [
+ [0, 0, 0],
+ [1, 0, 0],
+ ],
+ 4,
+ true,
+ ),
+ ).toThrow();
+});
+
+test('published catalog tube example executes', () => {
+ const example = geometryPrimitives.find((entry) => entry.name === 'taperedTube')!.example;
+ const geometry = new Function('catmullRomPath', 'taperedTube', `${example}\nreturn tail;`)(
+ catmullRomPath,
+ taperedTube,
+ );
+ expect(geometryDiagnostics(geometry).boundaryEdges).toBe(0);
+});
+
+test('maintained organic curve recipe executes', () => {
+ const text = readFileSync(
+ new URL('../../skills/kiln-author-asset/references/geometry-recipes.md', import.meta.url),
+ 'utf8',
+ );
+ const section = text.split('## Organic curves and blended volumes')[1]!;
+ const example = section.match(/```js\r?\n([\s\S]*?)```/)![1]!;
+ const geometry = new Function(
+ 'catmullRomPath',
+ 'taperedTube',
+ 'smoothOrganic',
+ `${example}\nreturn soft;`,
+ )(catmullRomPath, taperedTube, smoothOrganic);
+ expect(geometryDiagnostics(geometry).boundaryEdges).toBe(0);
+});
+
+test('metaball default blend remains the contributed shape default', async () => {
+ const spheres = [
+ { center: [0, 0, 0] as Point3, radius: 0.2 },
+ { center: [0.2, 0, 0] as Point3, radius: 0.2 },
+ ];
+ const options = {
+ bounds: { min: [-0.4, -0.4, -0.4] as Point3, max: [0.6, 0.4, 0.4] as Point3 },
+ edgeLength: 0.08,
+ };
+ const implicitDefault = await metaballSurface(spheres, options);
+ const explicitDefault = await metaballSurface(spheres, { ...options, blend: 0.07 });
+ expect(implicitDefault.getAttribute('position').array).toEqual(
+ explicitDefault.getAttribute('position').array,
+ );
+ expect(geometryDiagnostics(implicitDefault).boundaryEdges).toBe(0);
+});
+
+test('metaball rejects invalid blend even when only one sphere is supplied', async () => {
+ await expect(
+ metaballSurface([{ center: [0, 0, 0], radius: 0.2 }], {
+ bounds: { min: [-0.4, -0.4, -0.4], max: [0.4, 0.4, 0.4] },
+ edgeLength: 0.1,
+ blend: 0,
+ }),
+ ).rejects.toThrow();
+});
+
+test('spiral rejects nonfinite direction vectors before producing positions', () => {
+ expect(() =>
+ spiralPath({ center: [0, 0, 0], radius: 1, rise: 1, turns: 1, axis: [0, NaN, 0] }),
+ ).toThrow();
+ expect(() =>
+ spiralPath({ center: [0, 0, 0], radius: 1, rise: 1, turns: 1, forward: [Infinity, 0, 1] }),
+ ).toThrow();
+});
diff --git a/src/__tests__/organic.test.ts b/src/__tests__/organic.test.ts
new file mode 100644
index 00000000..2f360bf2
--- /dev/null
+++ b/src/__tests__/organic.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, test } from 'bun:test';
+
+import { geometryDiagnostics } from '../geometry';
+import { catmullRomPath, smoothOrganic, spiralPath, taperedTube } from '../organic';
+import { countTriangles, createPart, createRoot, gameMaterial } from '../primitives';
+
+describe('organic helpers', () => {
+ test('catmullRomPath returns more points than controls', () => {
+ const path = catmullRomPath(
+ [
+ [0, 0, 0],
+ [0, 1, 0],
+ [1, 1, 0],
+ [1, 0, 0],
+ ],
+ 4,
+ );
+ expect(path.length).toBeGreaterThan(4);
+ expect(path[0]).toEqual([0, 0, 0]);
+ });
+
+ test('taperedTube produces closed tube geometry with smooth shading default', () => {
+ const path = catmullRomPath(
+ [
+ [0, 0, 0],
+ [0, 0.5, 0],
+ [0.2, 1, 0],
+ ],
+ 6,
+ );
+ const radii = path.map((_, i, arr) => 0.06 * (1 - i / (arr.length - 1)) + 0.02);
+ const geo = taperedTube(path, radii);
+ const diag = geometryDiagnostics(geo);
+ expect(diag.triangles).toBeGreaterThan(100);
+ expect(diag.degenerateTriangles).toBe(0);
+ });
+
+ test('smoothOrganic increases triangle count', () => {
+ const base = taperedTube(
+ [
+ [0, 0, 0],
+ [0, 0.4, 0],
+ ],
+ [0.05, 0.03],
+ { radialSegments: 12 },
+ );
+ const smooth = smoothOrganic(base, { iterations: 1 });
+ expect(smooth.getAttribute('position')!.count).toBeGreaterThan(
+ base.getAttribute('position')!.count,
+ );
+ });
+
+ test('spiralPath and elliptical taperedTube build closed geometry', () => {
+ const spiral = spiralPath({
+ center: [0, 0, 0],
+ radius: 0.05,
+ rise: 0.12,
+ turns: 1.5,
+ samples: 16,
+ });
+ expect(spiral.length).toBeGreaterThan(10);
+ const path = [
+ ...spiral,
+ [0, 0.2, 0.05] as [number, number, number],
+ [0, 0.28, 0.04] as [number, number, number],
+ ];
+ const radii = path.map((_, i) => 0.02 * (1 - i / (path.length - 1)) + 0.008);
+ const scale = path.map(() => [0.4, 1.1] as [number, number]);
+ const geo = taperedTube(path, radii, { radialSegments: 14, sectionScale: scale });
+ expect(geometryDiagnostics(geo).degenerateTriangles).toBe(0);
+ });
+
+ test('organic creature root builds with QA-friendly triangle budget', async () => {
+ const root = createRoot('OrganicProbe');
+ const mat = gameMaterial(0x6a8f5a);
+ const bodyPath = catmullRomPath(
+ [
+ [0, 0.15, 0],
+ [0.25, 0.22, 0],
+ [0.45, 0.18, 0],
+ [0.55, 0.1, 0],
+ ],
+ 5,
+ );
+ const radii = bodyPath.map((_, i, a) => 0.12 - (i / (a.length - 1)) * 0.05);
+ createPart('Body', smoothOrganic(taperedTube(bodyPath, radii)), mat, { parent: root });
+ expect(countTriangles(root)).toBeGreaterThan(200);
+ });
+});
diff --git a/src/__tests__/sdf.test.ts b/src/__tests__/sdf.test.ts
new file mode 100644
index 00000000..fd2c86c4
--- /dev/null
+++ b/src/__tests__/sdf.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test';
+import { smoothUnion, smoothUnionSpheres, sphereInside } from '../sdf';
+
+describe('sdf helpers', () => {
+ test('public field helpers reject nonfinite inputs and invalid blend widths', () => {
+ expect(() => sphereInside([NaN, 0, 0], [0, 0, 0], 1)).toThrow();
+ expect(() => smoothUnion(Infinity, 0, 0.1)).toThrow();
+ expect(() => smoothUnion(0, NaN, 0.1)).toThrow();
+ expect(() => smoothUnionSpheres([0, 0, 0], [{ center: [0, 0, 0], radius: 1 }], 0)).toThrow();
+ });
+ test('sphereInside is positive at the center', () => {
+ expect(sphereInside([0, 0, 0], [0, 0, 0], 0.5)).toBe(0.5);
+ expect(sphereInside([0.5, 0, 0], [0, 0, 0], 0.5)).toBe(0);
+ });
+
+ test('smoothUnion blends between spheres', () => {
+ const p: [number, number, number] = [0, 0, 0];
+ const a = sphereInside(p, [-0.2, 0, 0], 0.4);
+ const b = sphereInside(p, [0.2, 0, 0], 0.4);
+ const blended = smoothUnion(a, b, 0.2);
+ expect(blended).toBeGreaterThan(Math.max(a, b) - 1e-6);
+ });
+
+ test('smoothUnionSpheres matches chained smoothUnion', () => {
+ const p: [number, number, number] = [0.1, 0.05, 0];
+ const spheres = [
+ { center: [0, 0, 0] as [number, number, number], radius: 0.35 },
+ { center: [0.25, 0.1, 0] as [number, number, number], radius: 0.25 },
+ ];
+ const chained = smoothUnion(
+ sphereInside(p, spheres[0]!.center, spheres[0]!.radius),
+ sphereInside(p, spheres[1]!.center, spheres[1]!.radius),
+ 0.15,
+ );
+ expect(smoothUnionSpheres(p, spheres, 0.15)).toBeCloseTo(chained, 6);
+ });
+});
diff --git a/src/discovery/helper-contracts.ts b/src/discovery/helper-contracts.ts
index 8ded5976..14d0eafc 100644
--- a/src/discovery/helper-contracts.ts
+++ b/src/discovery/helper-contracts.ts
@@ -708,7 +708,86 @@ define(
],
},
);
-
+define(
+ 'metaballSurface',
+ {
+ ...ownedGeometry,
+ execution: 'async',
+ axes: 'Sphere centers use XYZ; positive-inside smooth union.',
+ origin: 'Explicit sampling bounds min/max define the evaluated region.',
+ parameters: [
+ 'One or more { center, radius } spheres; blend defaults to max(0.35 times the smallest radius, 0.02 scene units).',
+ 'Same bounds/edgeLength limits as implicitSurface.',
+ 'Uses implicitSurface defaults of 1,000,000 estimated cells and 8,000,000 field callbacks; explicit maxCells/maxEvaluations ceilings pass through unchanged.',
+ ],
+ topology: ['Resolution-dependent manifold level set; review thin features.'],
+ preservation: ['No UVs; experimental metadata like implicitSurface.'],
+ cost: 'Implicit grid cost times sphere count; maxEvaluations counts field callbacks, not individual sphere evaluations. Use the host evaluator for process/time limits.',
+ },
+ {
+ references: ['src/organic.ts', 'src/implicit.ts'],
+ tags: ['metaball', 'blob', 'organic'],
+ aliases: ['smooth blob', 'blended spheres'],
+ intents: ['author a smooth organic solid from spheres'],
+ stability: 'experimental',
+ related: [{ name: 'implicitSurface', relation: 'alternative' }],
+ },
+);
+define(
+ 'smoothUnion',
+ {
+ units: 'Blend width uses asset-length units when composed into spatial fields.',
+ axes: 'Operands are scalar field samples, not mesh coordinates.',
+ parameters: ['Finite operands; positive finite blend width.'],
+ topology: [noMesh],
+ preservation: ['Pure scalar helper; no geometry output.'],
+ cost: 'O(1) per sample.',
+ },
+ {
+ references: ['src/sdf.ts'],
+ tags: ['sdf', 'implicit', 'blend'],
+ intents: ['smoothly join two positive-inside fields'],
+ related: [{ name: 'implicitSurface', relation: 'companion' }],
+ },
+);
+define(
+ 'sphereInside',
+ {
+ units: lengthUnits,
+ axes: 'Center and sample point use XYZ.',
+ parameters: ['Positive finite radius; finite center and sample point.'],
+ topology: [noMesh],
+ preservation: ['Scalar field sample only.'],
+ cost: 'O(1) per sample.',
+ },
+ {
+ references: ['src/sdf.ts'],
+ tags: ['sdf', 'sphere', 'field'],
+ intents: ['sphere distance field for implicitSurface'],
+ related: [{ name: 'smoothUnion', relation: 'companion' }],
+ },
+);
+define(
+ 'smoothOrganic',
+ {
+ ...ownedGeometry,
+ parameters: [
+ 'Optional iterations (default 1), creaseAngle (default 55), preserveUV flag.',
+ 'Subject to subdivide admission budgets.',
+ ],
+ preservation: [
+ 'Subdivision may drop legacy CSG provenance; creaseNormals invalidates tangents.',
+ 'Default position-only subdivision drops UVs and material groups; preserveUV: true retains supported corner attributes and material boundaries.',
+ ],
+ cost: 'Subdivide estimate applies before work begins.',
+ },
+ {
+ references: ['src/organic.ts', 'src/ops.ts', 'src/geometry.ts'],
+ tags: ['subdivide', 'normals', 'organic'],
+ intents: ['soften an authored mesh for creatures and plants'],
+ related: [{ name: 'subdivide', relation: 'companion' }],
+ },
+);
const nodeFacts: Facts = {
units: `${lengthUnits} explicit rotation triples use degrees unless stated otherwise.`,
axes: 'Three.js local XYZ; +Y is the normal up convention.',
@@ -2320,6 +2399,82 @@ define(
],
},
);
+define(
+ 'catmullRomPath',
+ {
+ units: lengthUnits,
+ axes: 'Control points and output use XYZ.',
+ parameters: [
+ 'At least two open or three closed control points; positive integer samplesPerSpan.',
+ 'Open output has (controlPoints.length - 1) * samplesPerSpan + 1 stations including endpoints. Closed output has controlPoints.length * samplesPerSpan stations without a repeated endpoint.',
+ 'Derived sample counts must be safe integers; unsafe products are rejected before sampling.',
+ ],
+ topology: [noMesh],
+ preservation: ['Returns a point array for downstream sweeps.'],
+ cost: 'Linear in control points × samplesPerSpan.',
+ },
+ {
+ references: ['src/organic.ts'],
+ tags: ['path', 'spline', 'curve'],
+ aliases: ['smooth path samples'],
+ intents: ['sample a smooth curve through waypoints'],
+ related: [
+ { name: 'taperedTube', relation: 'companion' },
+ { name: 'sweepProfile', relation: 'companion' },
+ ],
+ },
+);
+define(
+ 'spiralPath',
+ {
+ units: lengthUnits,
+ axes: 'Center, axis, forward and output use XYZ.',
+ origin:
+ 'Starts radius away from center in the projected forward direction; center is the spiral axis datum.',
+ parameters: [
+ 'Positive radius, rise, and turns; optional sample count (>= 4).',
+ 'Finite nonzero axis and forward; forward must not be parallel to axis.',
+ 'Returns samples + 1 stations, rising by rise while radius shrinks linearly to 42% of its initial value.',
+ 'The derived samples + 1 count must be a safe integer.',
+ ],
+ topology: [noMesh],
+ preservation: ['Returns spiral polyline samples for taperedTube or sweepProfile.'],
+ cost: 'Linear in samples.',
+ },
+ {
+ references: ['src/organic.ts'],
+ tags: ['path', 'spiral', 'curve'],
+ aliases: ['curl path', 'prehensile tail path'],
+ intents: ['sample a rising spiral for curled tails and tendrils'],
+ related: [
+ { name: 'catmullRomPath', relation: 'alternative' },
+ { name: 'taperedTube', relation: 'companion' },
+ ],
+ },
+);
+define(
+ 'taperedTube',
+ {
+ ...curveFacts,
+ parameters: [
+ 'Polyline path with one positive radius per station.',
+ 'Closed paths omit the repeated endpoint, matching closed catmullRomPath output.',
+ 'Optional per-station sectionScale [side, depth] for elliptical cross-sections.',
+ 'Default creaseAngle 180 for round profiles; radialSegments default 20.',
+ ],
+ preservation: ['UVs and normals like sweepProfile; smooth round shading by default.'],
+ },
+ {
+ references: ['src/organic.ts', 'src/sweep.ts'],
+ tags: ['tube', 'taper', 'organic'],
+ aliases: ['varying radius tube'],
+ intents: ['limb, tail, tentacle or branch with changing thickness'],
+ related: [
+ { name: 'pipeAlongPath', relation: 'alternative' },
+ { name: 'catmullRomPath', relation: 'prerequisite' },
+ ],
+ },
+);
define(
'lathe',
{
diff --git a/src/geometry-catalog.ts b/src/geometry-catalog.ts
index 4786fd55..ad22a6a0 100644
--- a/src/geometry-catalog.ts
+++ b/src/geometry-catalog.ts
@@ -212,4 +212,74 @@ export const geometryPrimitives: readonly HelperSpec[] = [
example:
'const blob = await implicitSurface(([x,y,z]) => 1-Math.hypot(x,y,z), { bounds: { min: [-1.2,-1.2,-1.2], max: [1.2,1.2,1.2] }, edgeLength: 0.15 });',
},
+ {
+ name: 'metaballSurface',
+ signature:
+ 'await metaballSurface(spheres: { center: [x,y,z], radius }[], { bounds, edgeLength, blend?, maxCells?, maxEvaluations? })',
+ returns: 'Promise<THREE.BufferGeometry>',
+ category: 'geometry',
+ description:
+ 'Experimental smooth union of spheres meshed through implicitSurface. Uses polynomial blending; output has no UVs.',
+ promptNotes:
+ 'Prefer this over hand-rolling smoothUnion fields for creatures, blobs and rounded junctions. Match edgeLength to feature size.',
+ example:
+ 'const body = await metaballSurface([{ center: [0,0.4,0], radius: 0.35 }, { center: [0.2,0.55,0], radius: 0.22 }], { bounds: { min: [-0.6,-0.1,-0.5], max: [0.6,1,0.5] }, edgeLength: 0.08 });',
+ },
+ {
+ name: 'taperedTube',
+ signature:
+ 'taperedTube(path: [x,y,z][], radii: number[], opts?: { radialSegments?: 20, creaseAngle?: 180, cap?: true, closed?: false, up?, twist?, sectionScale?: [side,depth][] })',
+ returns: 'THREE.BufferGeometry',
+ category: 'curves',
+ description:
+ 'Circular sweep with one radius per path station. Default creaseAngle 180 shades round profiles smoothly; sample splines with catmullRomPath first.',
+ example:
+ 'const path = catmullRomPath([[0,0.5,0],[0.3,0.7,0],[0.5,0.4,0]], 6); const radii = path.map((_, i) => 0.08 - 0.06 * i / (path.length - 1)); const tail = taperedTube(path, radii);',
+ },
+ {
+ name: 'catmullRomPath',
+ signature: 'catmullRomPath(controlPoints: [x,y,z][], samplesPerSpan?: 8, closed?: false)',
+ returns: '[x,y,z][]',
+ category: 'curves',
+ description:
+ 'Samples a Catmull-Rom spline through waypoints. Open paths include both endpoints; closed paths omit the repeated endpoint for closed sweeps.',
+ example: 'const path = catmullRomPath([[0,0,0],[0.2,0.4,0.1],[0.5,0.2,0]], 10);',
+ },
+ {
+ name: 'spiralPath',
+ signature: 'spiralPath(opts: { center, radius, rise, turns, axis?, forward?, samples? })',
+ returns: '[x,y,z][]',
+ category: 'curves',
+ description:
+ 'Rising spiral for curled appendages, shrinking to 42% of the start radius. Returns samples + 1 stations; starts radius away from center.',
+ example:
+ 'const curl = spiralPath({ center: [0,0.05,0], radius: 0.03, rise: 0.12, turns: 1.75, forward: [0,0,1] });',
+ },
+ {
+ name: 'smoothOrganic',
+ signature:
+ 'smoothOrganic(geometry, opts?: { iterations?: 1, creaseAngle?: 55, preserveUV?: false })',
+ returns: 'THREE.BufferGeometry',
+ category: 'mesh-ops',
+ description: 'Runs subdivide then creaseNormals with organic-friendly defaults.',
+ example: 'const soft = smoothOrganic(tube, { iterations: 1, creaseAngle: 50 });',
+ },
+ {
+ name: 'smoothUnion',
+ signature: 'smoothUnion(a: number, b: number, blend: number)',
+ returns: 'number',
+ category: 'geometry',
+ description:
+ 'Polynomial smooth maximum for positive-inside implicit fields. Compose inside implicitSurface callbacks.',
+ example: 'smoothUnion(sphereInside(p,[0,0,0],0.5), sphereInside(p,[0.3,0,0],0.4), 0.12)',
+ },
+ {
+ name: 'sphereInside',
+ signature: 'sphereInside(point: [x,y,z], center: [x,y,z], radius: number)',
+ returns: 'number',
+ category: 'geometry',
+ description:
+ 'Positive-inside sphere field sample for implicitSurface. Returns radius minus distance to center.',
+ example: 'sphereInside(p, [0,0.4,0], 0.25)',
+ },
];
diff --git a/src/organic.ts b/src/organic.ts
new file mode 100644
index 00000000..7519bf7d
--- /dev/null
+++ b/src/organic.ts
@@ -0,0 +1,215 @@
+/** Higher-level organic authoring helpers built on sweeps, SDFs and mesh ops. */
+import * as THREE from 'three';
+import type { Point3 } from './geometry';
+import { creaseNormals } from './geometry';
+import { implicitSurface, type ImplicitSurfaceOptions } from './implicit';
+import { circleProfile } from './profile';
+import { subdivide } from './ops';
+import { sweepProfile } from './sweep';
+import { smoothUnionSpheres } from './sdf';
+
+function assertSafePathCount(name: string, count: number): void {
+ if (!Number.isSafeInteger(count))
+ throw new Error(`${name} derived sample count must be a safe integer; reduce sample counts.`);
+}
+
+export interface MetaballSphere {
+ center: Point3;
+ radius: number;
+}
+
+export type MetaballSurfaceOptions = Omit<ImplicitSurfaceOptions, 'bounds'> & {
+ bounds: ImplicitSurfaceOptions['bounds'];
+ /** Shared smooth-union width. Default max(0.35 × smallest radius, 0.02 scene units). */
+ blend?: number;
+};
+
+/**
+ * Smooth union of spheres meshed through the experimental implicit pipeline.
+ * Spheres use the same positive-inside convention as `implicitSurface`.
+ * Uses the existing implicit-surface grid and field-callback limits unchanged.
+ */
+export async function metaballSurface(
+ spheres: readonly MetaballSphere[],
+ options: MetaballSurfaceOptions,
+): Promise<THREE.BufferGeometry> {
+ if (!spheres.length) throw new Error('metaballSurface needs at least one sphere');
+ let minRadius = Infinity;
+ for (const s of spheres) {
+ if (s.center.length !== 3 || !s.center.every(Number.isFinite))
+ throw new Error('metaballSurface sphere center must be three finite numbers');
+ if (!Number.isFinite(s.radius) || s.radius <= 0)
+ throw new Error('metaballSurface sphere radius must be positive and finite');
+ minRadius = Math.min(minRadius, s.radius);
+ }
+ const blend = options.blend ?? Math.max(minRadius * 0.35, 0.02);
+ if (!Number.isFinite(blend) || blend <= 0)
+ throw new Error('metaballSurface blend must be positive and finite');
+ const { bounds, ...rest } = options;
+ const field = (p: Point3) => smoothUnionSpheres(p, spheres, blend);
+ return implicitSurface(field, { bounds, ...rest });
+}
+
+/**
+ * Sample a Catmull-Rom spline through arbitrary control points. Use the samples
+ * as a `sweepProfile` or `taperedTube` path for smooth curvature. Open paths
+ * include both endpoints; closed paths omit the repeated endpoint.
+ * Derived sample counts must remain safe integers.
+ */
+export function catmullRomPath(
+ controlPoints: readonly Point3[],
+ samplesPerSpan = 8,
+ closed = false,
+): Point3[] {
+ if (controlPoints.length < (closed ? 3 : 2))
+ throw new Error('catmullRomPath needs at least two open or three closed control points');
+ if (!Number.isSafeInteger(samplesPerSpan) || samplesPerSpan < 1)
+ throw new Error('catmullRomPath samplesPerSpan must be a positive integer');
+ const spans = closed ? controlPoints.length : controlPoints.length - 1;
+ assertSafePathCount('catmullRomPath', spans * samplesPerSpan + 1);
+ if (controlPoints.some((p) => p.length !== 3 || !p.every(Number.isFinite)))
+ throw new Error('catmullRomPath control points must be finite [x,y,z] triples');
+ const vectors = controlPoints.map((p) => new THREE.Vector3(p[0], p[1], p[2]));
+ const curve = new THREE.CatmullRomCurve3(vectors, closed);
+ const points = curve.getPoints(spans * samplesPerSpan);
+ if (closed) points.pop();
+ return points.map((v) => [v.x, v.y, v.z] as Point3);
+}
+
+export interface TaperedTubeOptions {
+ radialSegments?: number;
+ /** Degree crease for profile sides; 180 shades a round profile smoothly. Default 180. */
+ creaseAngle?: number;
+ cap?: boolean | 'start' | 'end';
+ closed?: boolean;
+ up?: Point3;
+ twist?: number;
+ /**
+ * Per-station elliptical scale on the circular profile `[side, depth]`.
+ * Values multiply the profile axes before the station radius is applied.
+ */
+ sectionScale?: readonly (readonly [number, number])[];
+}
+
+export interface SpiralPathOptions {
+ center: Point3;
+ /** Max radius of the spiral in the horizontal plane. */
+ radius: number;
+ /** Vertical rise while spiraling. */
+ rise: number;
+ /** Full turns (e.g. 1.75). */
+ turns: number;
+ /** World up axis. Default `[0, 1, 0]`. */
+ axis?: Point3;
+ /** Horizontal direction at the start of the spiral (belly / curl opening). Default `[0, 0, 1]`. */
+ forward?: Point3;
+ samples?: number;
+}
+
+/**
+ * Circular tube with per-station radius along a polyline path. For smooth paths,
+ * sample a spline first with `catmullRomPath`.
+ */
+export function taperedTube(
+ path: readonly Point3[],
+ radii: readonly number[],
+ options: TaperedTubeOptions = {},
+): THREE.BufferGeometry {
+ const closed = options.closed ?? false;
+ const stations = path;
+ if (stations.length < (closed ? 3 : 2))
+ throw new Error('taperedTube needs at least two open or three closed path points');
+ if (radii.length !== stations.length)
+ throw new Error('taperedTube radii must have one entry per path point');
+ for (const r of radii) {
+ if (!Number.isFinite(r) || r <= 0)
+ throw new Error('taperedTube radii must be positive and finite');
+ }
+ const radialSegments = options.radialSegments ?? 20;
+ const profile = circleProfile(1, radialSegments).map(([x, y]) => [x, y] as [number, number]);
+ const scale = radii.map((r, i) => {
+ const [side, depth] = options.sectionScale?.[i] ?? [1, 1];
+ return [r * side, r * depth] as [number, number];
+ });
+ if (options.sectionScale && options.sectionScale.length !== stations.length)
+ throw new Error('taperedTube sectionScale needs one [side, depth] pair per path point');
+ const geo = sweepProfile(profile, [...stations], {
+ cap: options.cap ?? true,
+ closed,
+ up: options.up,
+ twist: options.twist ?? 0,
+ scale,
+ creaseAngle: options.creaseAngle ?? 180,
+ });
+ return geo;
+}
+
+/**
+ * Rising, shrinking spiral for prehensile tails. Starts `radius` from center in
+ * the projected forward direction; ends `rise` higher at 42% of the start radius.
+ * Returns samples + 1 stations over the requested number of turns.
+ * Derived sample counts must remain safe integers.
+ */
+export function spiralPath(options: SpiralPathOptions): Point3[] {
+ const {
+ center,
+ radius,
+ rise,
+ turns,
+ axis = [0, 1, 0],
+ forward = [0, 0, 1],
+ samples = 24,
+ } = options;
+ if (![radius, rise, turns].every((n) => Number.isFinite(n) && n > 0))
+ throw new Error('spiralPath radius, rise and turns must be positive and finite');
+ if (!Number.isSafeInteger(samples) || samples < 4)
+ throw new Error('spiralPath samples must be an integer >= 4');
+ assertSafePathCount('spiralPath', samples + 1);
+ if (center.length !== 3 || !center.every(Number.isFinite))
+ throw new Error('spiralPath center must be a finite [x,y,z] triple');
+ if (axis.length !== 3 || forward.length !== 3 || ![...axis, ...forward].every(Number.isFinite))
+ throw new Error('spiralPath axis and forward must be finite [x,y,z] triples');
+ const up = new THREE.Vector3(...axis);
+ const fwd = new THREE.Vector3(...forward);
+ if (up.lengthSq() < 1e-12 || fwd.lengthSq() < 1e-12)
+ throw new Error('spiralPath axis and forward must be nonzero');
+ up.normalize();
+ const horiz = fwd.clone().addScaledVector(up, -fwd.dot(up));
+ if (horiz.lengthSq() < 1e-12) throw new Error('spiralPath forward must not be parallel to axis');
+ horiz.normalize();
+ const right = new THREE.Vector3().crossVectors(up, horiz).normalize();
+ const out: Point3[] = [];
+ for (let i = 0; i <= samples; i++) {
+ const u = i / samples;
+ const theta = u * turns * Math.PI * 2;
+ const r = radius * (1 - u * 0.58);
+ const offset = horiz
+ .clone()
+ .multiplyScalar(r * Math.cos(theta))
+ .add(right.clone().multiplyScalar(r * Math.sin(theta)));
+ const lift = up.clone().multiplyScalar(u * rise);
+ out.push([
+ center[0] + offset.x + lift.x,
+ center[1] + offset.y + lift.y,
+ center[2] + offset.z + lift.z,
+ ]);
+ }
+ return out;
+}
+
+export interface SmoothOrganicOptions {
+ iterations?: number;
+ creaseAngle?: number;
+ preserveUV?: boolean;
+}
+
+/** Subdivide then angle-limit normals — common finish for organic sweeps and lofts. */
+export function smoothOrganic(
+ geometry: THREE.BufferGeometry,
+ options: SmoothOrganicOptions = {},
+): THREE.BufferGeometry {
+ const iterations = options.iterations ?? 1;
+ const preserveUV = options.preserveUV ?? false;
+ const subdivided = subdivide(geometry, iterations, preserveUV ? { preserveUV: true } : undefined);
+ return creaseNormals(subdivided, { angle: options.creaseAngle ?? 55 });
+}
diff --git a/src/primitives.ts b/src/primitives.ts
index cb582030..3e11de09 100644
--- a/src/primitives.ts
+++ b/src/primitives.ts
@@ -62,7 +62,11 @@ import * as geometry from './geometry';
import * as deform from './deform';
import * as sweep from './sweep';
import { implicitSurface } from './implicit';
+import { catmullRomPath, metaballSurface, smoothOrganic, spiralPath, taperedTube } from './organic';
+import { smoothUnion, sphereInside } from './sdf';
export * from './implicit';
+export * from './organic';
+export { smoothUnion, sphereInside } from './sdf';
export * from './sweep';
export * from './deform';
export * from './geometry';
@@ -2379,6 +2383,13 @@ export function buildSandboxGlobals(
bobbingAnimation: wrap('bobbingAnimation', bobbingAnimation),
idleBreathing: wrap('idleBreathing', idleBreathing),
implicitSurface: wrap('implicitSurface', implicitSurface),
+ metaballSurface: wrap('metaballSurface', metaballSurface),
+ catmullRomPath: wrap('catmullRomPath', catmullRomPath),
+ spiralPath: wrap('spiralPath', spiralPath),
+ taperedTube: wrap('taperedTube', taperedTube),
+ smoothOrganic: wrap('smoothOrganic', smoothOrganic),
+ smoothUnion: wrap('smoothUnion', smoothUnion),
+ sphereInside: wrap('sphereInside', sphereInside),
sweepProfile: wrap('sweepProfile', sweep.sweepProfile),
loftProfiles: wrap('loftProfiles', sweep.loftProfiles),
bend: wrap('bend', deform.bend),
diff --git a/src/sdf.ts b/src/sdf.ts
new file mode 100644
index 00000000..edb0f1ab
--- /dev/null
+++ b/src/sdf.ts
@@ -0,0 +1,43 @@
+/** Signed-distance helpers for positive-inside implicit fields (experimental). */
+import type { Point3 } from './geometry';
+
+/** Sphere SDF: positive inside when `radius - distance(center, p) > 0`. */
+export function sphereInside(point: Point3, center: Point3, radius: number): number {
+ if (point.length !== 3 || !point.every(Number.isFinite))
+ throw new Error('sphereInside point must be three finite numbers');
+ if (!Number.isFinite(radius) || radius <= 0)
+ throw new Error('sphereInside radius must be positive and finite');
+ if (center.length !== 3 || !center.every(Number.isFinite))
+ throw new Error('sphereInside center must be three finite numbers');
+ return radius - Math.hypot(point[0] - center[0], point[1] - center[1], point[2] - center[2]);
+}
+
+/**
+ * Polynomial smooth union (IQ smooth maximum). Both operands use the same
+ * positive-inside convention as `implicitSurface`.
+ */
+export function smoothUnion(a: number, b: number, blend: number): number {
+ if (!Number.isFinite(a) || !Number.isFinite(b))
+ throw new Error('smoothUnion operands must be finite');
+ if (!Number.isFinite(blend) || blend <= 0)
+ throw new Error('smoothUnion blend must be positive and finite');
+ const h = Math.max(blend - Math.abs(a - b), 0) / blend;
+ return Math.max(a, b) + (h * h * blend) / 4;
+}
+
+/** Smooth union of many sphere fields with a shared blend width. */
+export function smoothUnionSpheres(
+ point: Point3,
+ spheres: readonly { center: Point3; radius: number }[],
+ blend: number,
+): number {
+ if (!spheres.length) throw new Error('smoothUnionSpheres needs at least one sphere');
+ if (!Number.isFinite(blend) || blend <= 0)
+ throw new Error('smoothUnionSpheres blend must be positive and finite');
+ let value = sphereInside(point, spheres[0]!.center, spheres[0]!.radius);
+ for (let i = 1; i < spheres.length; i++) {
+ const s = spheres[i]!;
+ value = smoothUnion(value, sphereInside(point, s.center, s.radius), blend);
+ }
+ return value;
+}