Skip to content
Kiln1.9Get Kiln

Latest published package: Kiln 1.9.0. Earlier versions below identify feature requirements or historical results.

Kiln programs are JavaScript. The helpers cover common modeling operations; equations, loops, and custom THREE.BufferGeometry remain available when you need a different shape. Geometry functions belong in the saved program, so a later source edit can change one parameter and keep the rest.

Use meters for dimensions. The asset convention is +X forward, +Y up, +Z right. Helper rotation values use Euler XYZ degrees; direct Three.js rotations use radians.

Size and orient a gear

gearGeo builds a gear in the XZ plane, centered at the origin, with its axle and thickness along Y. To mount its axle along Z, use rotation: [90, 0, 0] on the part.

Radii are absolute dimensions, not proportions. Set all three when making a small gear: boreRadius < rootRadius < tipRadius. A zero bore makes a solid center. Changing only tipRadius can leave it smaller than the default root radius of 0.8 meters.

createPart('ElevationWheel', gearGeo({
  teeth: 28, rootRadius: 0.063, tipRadius: 0.075,
  boreRadius: 0.012, height: 0.024,
}), brass, { rotation: [90, 0, 0], parent: yoke });

The helper makes a stylized toothed shape; it does not calculate an involute tooth profile or prove that two gears mesh correctly.

Own geometry before changing it

Primitive calls with identical arguments can share a cached geometry. Copy before changing its vertices or applying a geometry transform:

const editable = copyGeometry(boxGeo(1, 1, 1));
editable.translate(0, 0.5, 0);
const red = copyMaterial(steel);
red.color.set(0xaa2222);

copyGeometry copies vertex buffers. copyMaterial copies material properties while retaining shared texture references. Pass the same geometry or material directly to multiple parts when sharing is intentional. The identity aliases cloneGeometry and cloneMaterial have been removed; migration guidance distinguishes sharing from copying. Direct .clone() is also available.

New shaping helpers return independent geometry. Use createInstance when sharing geometry and materials is intentional.

Transform existing texture coordinates

remapUV returns an independent geometry with uv = uv * scale + offset, in U/V order:

const tiled = remapUV(cylinderGeo(0.4, 0.4, 1), {
  scale: [4, 2], offset: [0, 0.25],
});

Defaults are scale: [1, 1] and offset: [0, 0]. The helper requires existing UV0 with two finite components per vertex; project or unwrap first when UVs are absent. Negative scale mirrors that texture axis. Interleaved and normalized UV attributes are read as logical values and written as Float32 coordinates. Nonfinite values or mapped Float32 overflow are rejected.

Topology, material groups and other attributes are preserved. Changing scale drops existing tangents and records UV_REMAP_TANGENTS_DROPPED; regenerate tangents when normal mapping needs them. Offsets preserve tangents. This transforms a mapping; it does not create an atlas or repair overlapping UV islands. The former panelRemapV helper is removed, and its old V default of 0.3 must be requested explicitly during migration.

Check an explicit material budget

materialBudgetAdvisory(root, { maxMaterials: 8 }) counts distinct material objects and reports whether that requested count was exceeded. Omit the budget to receive the count with maxMaterials: null, exceeded: null, and no warnings. The helper does not select a category budget, declare asset validity, or estimate draw calls. Use countMaterials(root) when only the count is needed, and the validation and render/QA tools for their specific findings.

Author a surface with an equation

const canopy = parametricSurface(
  (u, v) => [u, 0.4 * Math.sin(u * 2) + 0.15 * v * v, v],
  { u: [-2, 2], v: [-1, 1], uSegments: 48, vSegments: 24 },
);

u and v are finite parameter domains. Sampling defaults to 24 segments in each direction. The default orientation: 'uv' follows the cross product of the increasing U and V directions; use 'vu' to reverse it. UVs run from 0 to 1.

For a periodic surface, declare the matching seam explicitly:

const torus = parametricSurface(
  (u, v) => [
    (2 + 0.5 * Math.cos(v)) * Math.cos(u),
    0.5 * Math.sin(v),
    (2 + 0.5 * Math.cos(v)) * Math.sin(u),
  ],
  { u: [0, 2 * Math.PI], v: [0, 2 * Math.PI],
    uSegments: 48, vSegments: 24, periodicU: true, periodicV: true },
);

Periodic endpoint positions must coincide. Kiln retains distinct 0/1 UVs while matching seam positions and normals. Sampling does not add thickness, cap poles, remove self-intersections, or turn every equation into a solid. Avoid collapsed parameter rows unless you deliberately handle their degenerate triangles.

For hand-authored topology, meshGeo takes flat arrays:

const triangle = meshGeo({
  positions: [0, 0, 0, 1, 0, 0, 0, 1, 0],
  indices: [0, 1, 2],
  uvs: [0, 0, 1, 0, 0, 1],
});

Positions contain XYZ triples; each index triple is a counterclockwise triangle. Without indices, every three vertices form one triangle. Optional normals, uvs, and tangents must match the vertex count. Normals are computed when omitted and normalized when supplied. Tangents use unit XYZ plus handedness +1 or -1. Validation rejects nonfinite data and invalid indices. Raw Three.js can carry additional attributes, but check Kiln’s export diagnostics before assuming every Three.js feature survives GLB export.

Bend, twist, taper, and displace

const twisted = twist(column, { angle: 120 });
const narrower = taper(column, { endScale: [0.4, 0.7] });
const arched = bend(rib, { angle: 90 });
const corrugated = displace(sheet, ([x, y, z]) => [0, 0.06 * Math.sin(x * 18), 0]);

These operations work along local +Y. bend turns +Y toward +X; twist rotates around +Y. taper interpolates positive X/Z scale pairs from startScale (default [1,1]) to endScale. displace returns a vector to add, not an absolute replacement position.

A shared options shape controls the frame and affected region:

const shaped = twist(geometry, {
  angle: 75,
  frame: { origin: [0, 1, 0], rotation: [0, 0, 90] },
  interval: [-1, 1],
  falloff: t => Math.sin(Math.PI * t),
});

frame is a rigid origin and degree-based rotation. interval contains local Y distances; it defaults to the mesh’s local Y extent. Vertices outside an explicit interval remain unchanged. The optional falloff returns a weight from 0 to 1. Use a weight that reaches zero at the region boundary when a hard transition would tear or fold the surface. A zero-height mesh has normalized interval coordinate 0.

Deformation preserves vertex topology and UVs, recomputes normals and bounds, and invalidates old tangents. Apply creaseNormals afterward when you want controlled smooth/sharp boundaries. Enough segments must exist before shaping: bending a single quad does not create a curved surface.

A deterministic displacement can use an authored hash instead of ambient randomness:

function seededHeight(x, z, seed) {
  const value = Math.sin(x * 12.9898 + z * 78.233 + seed * 37.719) * 43758.5453;
  return (value - Math.floor(value)) * 2 - 1;
}
const rough = displace(surface, ([x, y, z]) => [0, 0.02 * seededHeight(x, z, 7), 0]);

Extrude a footprint in the intended direction

extrudeProfile maps a profile point (u,v) and depth coordinate d to these geometry-local coordinates:

Axis Output (X,Y,Z)
x (d,v,-u)
y (default) (u,d,-v)
z (u,v,d)

For a horizontal platform with a desired XZ footprint, pass [X,-Z] and axis: 'y'. Positive profile v projects toward negative Z. center: false starts extrusion at zero on the selected axis; the default centers its depth. Check asymmetric footprints against attached railings and supports in exported world coordinates. A correct width and a shared parent do not prove they face the same direction.

Compose open structures from editable parts

Discovery’s recipe:structural-bays-v1 supplies a six-storey facade example with independent bay placement, real apertures and replaceable recessed glazing. Change the center width without scaling outer detailing, or replace one opening’s infill under a transformed parent. Storey count is an editable parameter. The ground entry is intentionally open; later trim, doors or collision meshes need their own clearance review.

recipe:open-tiered-seating-v1 supplies separately editable solid seating sectors around an open arena. It reserves an entrance before generating geometry and puts placement on each sector root. Rows, rise, radius and angular coverage are editable; no house layout, roof or asset category is required. These are optional construction examples, not completed buildings, navigation certificates or finished materials.

Fill wall openings

wallWithOpening cuts each opening and, with fill, makes what fills it: frame, glazing, bars, sill (windows), lintel, shutters, and a leaf under a Joint_ hinge pivot. Every piece is placed from its opening and the wall, so moving or widening an opening moves its fills. Depths are metres inward from the outer face: outward: 1 (the default) puts it on the +X side of a wall along z and the +Z side of one along x, and -1 on the other side. Negative depths stand proud of the wall. Materials come by role in materials (frame, glazing, bars, sill, lintel, shutter, leaf, hardware); each falls back to frame, then the wall material, except glazing, which must be given. Parts are named <wall>_<Door|Window><n>_<Piece>; an opening’s name replaces the prefix and its names maps a piece to the exact part name an existing contract needs.

wallWithOpening('FrontWall', masonry, {
  length: 7.4, height: 3.2, thickness: 0.3,
  materials: { frame: trim, glazing: glass, sill: stone, shutter: olive },
  openings: [
    { kind: 'door', width: 1, height: 2.15,
      fill: { frame: true, leaf: { pivot: 'FrontDoor', handle: true } } },
    { kind: 'window', offset: 2, width: 1.1, height: 1.3, sill: 0.75,
      fill: { frame: true, glazing: true, bars: { vertical: [0.5], horizontal: [0.58] },
              sill: true, lintel: true, shutters: true } },
  ],
  parent: root,
});

Pieces in the opening (frame, glazing, bars, leaf) stay inside it; sill, lintel and shutters stand against the outer face. Fills meet the wall and each other face to face or with a gap, none passes through another, and glazing stands 1 mm clear of the frame, bars and reveal so a double-sided pane cannot z-fight. Every piece is a closed box with UV0. A fill that does not fit, such as a frame wider than its opening, shutters over a neighbouring opening or glazing without a material, throws before anything is built. room passes fill, name, names and materials to its walls, with each wall’s outer face outside the room.

Run a fence along a path

fenceRun(name, { path, post, rails, material }) puts a post at each path point and rails between neighbouring posts, so a fence bay, a pen or a sloping paddock run is one call. Each post sits in its own frame (post.groups, default <name>_Post<i>) at its point; the frames are snap anchors. A post’s local +X follows the run: it bisects a turn of up to 45 degrees, and at a sharper turn it bisects only what is left after the nearest right angle, so the corner posts of a square pen are square to both rails. Posts take a section (a size or [along, across]), height, chamfer, a weathering cap: { rise, inset } and pegs on their side faces at each rail height. Rails run at rails.heights above the post bases, follow the slope, and stop embed (default 2 cm) inside each post face, so no rail end shows and no rail face lies on a post face. rails.merge makes every rail one part with that name, and closed: true joins the last post to the first.

const run = fenceRun('Fence', {
  path: [[-1, 0, 0], [1, 0, 0], [1, 0, 2]],
  post: { section: 0.15, height: 1.1, chamfer: 0.018, cap: { rise: 0.06, inset: 0.035 },
          pegs: { radius: 0.013, length: 0.01, offsets: [-0.045, 0.045] } },
  rails: { heights: [0.42, 0.86], section: [0.06, 0.12], merge: 'Rails' },
  material: wood, parent: root,
});

Every member is a closed, outward solid with UVs in metres and the grain along it; uv.seed moves where each member’s grain starts. The call returns { root, posts, parts }: the post frames and the meshes. A run that does not fit throws before anything is built: posts too close for a rail, a rail outside the post shaft or showing its end on a steep slope or sharp turn, a rail meeting a post across its edge, two rails crossing outside a sharp corner post, or pegs where a rail enters a post’s side.

Merge an assembly by material

wallWithOpening, room and fenceRun take merge: 'byMaterial'. The helper builds its pieces as it would without the option, then replaces them with one part per material: the same triangles in the same places, so triangle count and bounds do not change. A part is named for the role of its first piece: a wall or a fence’s posts take the call’s name, the rest <name>_<Role> (a fence’s rails <name>_Rails). Frames that are not meshes stay where they were, so a room’s wall frames and a fence’s post frames still serve as anchors, and the pieces under a Joint_ pivot merge only with each other, under the pivot, so a door leaf still swings; they are named for their opening, such as <wall>_Door1_Leaf. Geometry is concatenated, not unioned: two pieces that share an edge make that edge non-manifold, so requireSolid fails a merged part where its pieces touch. Without merge, output is unchanged.

Compose moving assemblies

Discovery’s recipe:joined-frame-v1 derives brace endpoints from the same post dimensions, so resizing the frame moves both interfaces together. Check each brace against both intended supports and measure required gaps separately. A connected-component report or bounding-box snap can miss a detached endpoint; zero surface distance can also mean intersection. This recipe uses existing helpers and imposes no asset category or structural-strength claim.

createWheelAssembly accepts side: 'left' | 'right' | 'center'. Side identifies the wheel relative to its host; it neither positions it automatically nor chooses single- or double-sided fork support. Centerline wheels need no fabricated mate.

Discovery offers recipe:steerable-wheel-v1 and recipe:branched-articulation-v1 for moving assemblies. The wheel example parents its fork and axle beneath steering, separately from spin, and derives clearance from the wheel dimensions. Its contact marker describes the rest pose; inspect actual tire vertices over motion rather than treating that marker as rolling contact. The branched gripper preserves explicit joint offsets and nonzero rest rotations without a humanoid preset. Its rotation tracks are absolute local orientations; time zero matches the rest frame. Neither example certifies physics, collision-free motion or host attachment. Replicate animated assemblies together with their clips and use the returned remapped targets.

Sweep a profile or loft sections

const profile = [[-0.12, -0.2], [0.12, -0.2], [0.12, 0.2], [-0.12, 0.2]];
const rail = sweepProfile(profile, [[0, 0, 0], [0, 1, 0], [0.5, 2, 0]], {
  twist: 20,
  scale: [[1, 1], [0.9, 0.9], [0.7, 0.7]],
});

Profiles use local [x,z] coordinates. Sweep paths are polyline stations, not automatically smoothed splines. Sample a curve first for smooth curvature. The initial up vector defines profile +Z after projection perpendicular to the path. If omitted, Kiln chooses a stable cardinal direction. Subsequent frames use parallel transport instead of repeatedly projecting a global up vector.

Profile validity and path-station tolerances scale with their respective extents, so changing units does not introduce a fixed minimum size. up is a direction; its nonzero magnitude does not affect the frame. Very small features relative to the overall profile or path may still fall below those tolerances. Output geometry uses Float32 positions: use object placement for distant origins when baking the translation into vertices would erase detail. These checks do not prove a solid is free of self-intersections.

twist is the total degree rotation along the path. scale can be one positive number or one positive [x,z] pair per station. Caps default to true. For closed: true, omit the repeated endpoint; total twist must be a multiple of 360 degrees. Closed frames receive a seam correction and retain a wrapped UV seam.

For profiles that change shape rather than just scale:

const body = loftProfiles([
  { profile: [[-1,-1],[1,-1],[1,1],[-1,1]] },
  { profile: [[-.5,-1],[.8,-.6],[.6,.5],[-.5,.7]],
    frame: { origin: [0.4, 2, 0], rotation: [0, 15, 0] } },
]);

Each loft section lies in its frame’s local XZ plane. Initial section travel relative to the first plane determines face winding, so sections may progress in either direction. All profiles need the same vertex count and meaningful index-to-index correspondence. Outline winding is normalized while retaining the first vertex. These helpers accept one simple outline without holes. Supplying holes in sweep/loft options or a loft section fails explicitly, including from JavaScript. Use extrudeProfile for a holed cross-section with optional twist and taper. Independently varying inner and outer contours need explicit geometry or solid subtraction; there is no automatic contour correspondence. cap: false leaves end boundaries open; it does not create inner walls or thickness.

These helpers reject self-crossing 2D outlines, duplicate path stations, and near-reversals. Tight turns get a warning. Closed boundaries do not prove the resulting 3D surface is free of self-intersections. Review nearby path segments, large profiles, and crossed loft sections. Kiln does not claim a general CAD-solid guarantee for sweeps or lofts.

Choose each loft’s starting vertex deliberately: a cyclic shift can cross connecting edges while leaving all topology counts green. extrudeProfile adds no side-wall rings unless divisions asks for them (default 0, or 16 when it twists). Holed extrudeProfile supports twist/taper, but twist accuracy depends on divisions, and its output needs UV projection or unwrapping before directional textures. See the bounded construction comparison for measured alternatives and limits.

Lofts and profile sweeps reject corresponding profile edges that collapse between stations. Match section start vertices and order deliberately; use intermediate sections or path stations to resolve an intended twist. This linear-time local check does not detect every crossed panel or global self-intersection.

Lofts and profile sweeps divide warped four-corner side panels into four triangles around their bilinear midpoint. This avoids choosing a diagonal that changes the surface differently on mirrored sides. Planar panels retain two triangles. The midpoint also interpolates UVs; it adds one vertex and two triangles per warped panel. This is piecewise-linear sampling, not a smooth surface or a remedy for crossed correspondence. Add meaningful profile/path stations when more shape detail is needed.

Preserve seams and control shading

const smooth = subdivide(texturedGeometry, 1, { preserveUV: true });
const shaded = creaseNormals(smooth, { angle: 45 });
const report = geometryDiagnostics(shaded);
  • subdivide(..., { preserveUV: true }) keeps per-corner UV charts while smoothing positions. The default position-only weld reports UV loss with SUBDIVIDE_UV_DROPPED; losses of other attributes, groups and morphs are also explicit.
  • mergeVertices normally keeps separate vertices where normals or UVs differ. { positionOnly: true } explicitly drops other attributes to weld geometric topology.
  • creaseNormals preserves UV corners, averages neighboring face normals within the degree threshold, and invalidates tangents. Its position tolerance defaults to 1e-8 times the bounding-box diagonal, with no world-unit floor. An explicit positive tolerance overrides that distance.
  • Export writes unit normals. A non-unit normal, such as a hand-edited normal or the last ring of a raw THREE.LatheGeometry before three r187, is scaled to unit length in the written file with one NORMALS_NORMALISED note naming the part and count; your geometry is not changed and shading is identical. A zero-length normal has no direction, so export fails naming the part and vertex; build revolved profiles with lathe or revolveGeo, or recompute with creaseNormals.
  • geometryDiagnostics reports boundary edges, non-manifold edges, inconsistent edge orientation, degenerate triangles, invalid indices, and nonfinite vertices. Default seam tolerance is 1e-6 times the finite-position bounding-box diagonal. A supplied positive tolerance remains an absolute geometry-local distance. The result exposes tolerance, toleranceMode, and positionScale. Open boundaries are expected for sheets; the counts do not certify a valid solid or detect general self-intersections.
  • collapsedByToleranceTriangles reports faces whose vertices merge in that diagnostic grid. Those faces are excluded from edge counts so their remaining edges are not counted twice. This is separate from the area-based degenerateTriangles count. A nonzero value means topology detail was lost at the chosen tolerance; inspect at a finer deliberate tolerance before interpreting the edge counts. The helper does not weld, remove or repair geometry.

Both operations quantize positions relative to the bounds minimum. This is grid matching, not an exact radius weld. Explicit tolerances finer than the extent can resolve with safe integer quantization are rejected. Zero-extent geometry uses exact position matching; collapsed triangles remain degenerate. Invalid-position triangles are excluded from diagnostic edge/area counts and their nonfinite vertices remain reported. Relative defaults can merge fine features within a large combined mesh; choose an intentional absolute tolerance when inspecting such geometry.

Periodic surface endpoints must agree within 1e-6 of the sampled bounding-box diagonal. Translation or tiny world units cannot turn a proportionally open seam into an accepted periodic one. Float32 geometry cannot retain arbitrarily small detail at a distant origin: author in local coordinates and position the parent.

Keep Boolean materials and UVs when useful

const carved = await boolDiff('Housing', body, cutter, { preserveAttributes: true });

preserveAttributes: true carries UV0 through Manifold interpolation and returns material groups. Exposed subtraction surfaces inherit their cutter’s material and UVs. Missing UVs on an operand receive zero coordinates and an explicit warning. Normals are regenerated according to smooth; tangents are invalidated. This is useful for existing tileable mappings; it does not create a new unified atlas.

smooth: true averages normals across sharp rims as well as curved walls. For angle-controlled boundaries, assign carved.geometry = creaseNormals(carved.geometry, { angle: 60 }) and inspect the result. This changes shading, not surface positions; it cannot fix gaps, an uneven silhouette or self-intersections. Compare normals before changing a cutter to address what may only be a lighting artifact.

The preservation option is limited to UV0 and materials. Vertex colors, secondary UV channels, tangents, skin/custom attributes and inactive morph targets are removed with explicit diagnostics. Source geometry/attribute diagnostics survive the operation and appear in export warnings. Rebuild required shading data after CSG; normal-mapped export regenerates tangents from the final normals and UVs. Arbitrary source metadata, animation and morph correspondences are not retained.

Operands must be static triangle meshes. Instanced meshes, skinned meshes and active morph poses are rejected: bake the intended instances or pose into static meshes first. Reading only their base geometry would silently change the solid.

Legacy calls retain their original first-material/no-UV behavior. Use autoUnwrap after a Boolean when you want a fresh atlas. Profile solids also generate their own surfaces without UVs.

CSG metadata now records actual output runs and source face IDs, including the backside flag for subtraction, rather than allocating guessed triangle ranges. Nested preserving operations retain source names and material groups. A hull creates new faces, so it reports unknown provenance and retains only the first material with no UVs even when preservation was requested.

CSG uses one translated, uniformly normalized computation frame for every operand. The returned unparented mesh preserves world placement in its position, anchored at the first contributing mesh’s world origin. Its geometry has world-aligned axes and local coordinates relative to that origin. Keep the returned mesh transform; use new THREE.Box3().setFromObject(result) for world bounds. Detaching only result.geometry loses that placement. Before parenting under a transformed node, use world-preserving attachment or explicitly convert to that parent’s frame.

This avoids converting large world coordinates to Float32 before the Boolean. It cannot recover detail already lost in input buffers/transforms or promise arbitrarily tiny features within a vast combined operand extent.

Solid conversion checks the actual Float32 triangle positions before normals are generated. Manifold first rebuilds the topology from those consumer coordinates. Any remaining exactly zero-area seam faces are removed with their triangle metadata, followed by a final topology rebuild and validation. Both stages retain source IDs, UVs and material runs. Successful cleanup reports SOLID_FLOAT32_CANONICALIZED; unresolved collapse is an explicit error. Boolean output restores asset units before materialization, keeping the large world origin in the node transform. This can change rounding-level positions and normals from older builds. It is not a general self-intersection or mesh-repair tool.

Choose the path or revolution contract

curveToMesh constructs an open-ended Catmull-Rom tube with generated UVs. pipeAlongPath shares that construction and optionally inserts corner waypoints; its bendRadius is not an exact circular fillet. closed joins the path into a loop; it does not cap two open endpoints. For a selected profile along explicit polyline stations, use sweepProfile, whose end caps default to enabled and whose transported frames, scale and degree-based twist have a separate contract. cap also takes 'start' or 'end' on an open path. creaseAngle (degrees, default 60) splits vertices where side panels meet more sharply, so triangle, square and pentagon profiles keep hard edges while hexagons and finer profiles stay smooth; 180 smooths everything. bezierCurve returns sampled points; feeding them into a tube interpolates them again rather than retaining an exact parametric Bézier curve.

lathe is the full-Y surface shorthand for revolveGeo; both now share one implementation. revolveGeo takes radians and an arbitrary axis vector. Before axis reorientation its sweep starts at +Z and proceeds toward +X. These surface operations generate UVs and do not implicitly cap an open meridian. revolveProfile instead constructs a solid from a closed section, takes degrees, and has explicit X/Y/Z axis selection. Around Y it starts at +X and proceeds toward -Z; its new surfaces have no inherited UVs. Converting angle units alone therefore does not make partial surface and solid revolutions interchangeable.

These distinctions are preserved rather than hidden behind a mode-dependent return contract. The bounded comparison records the shared implementations and unchanged geometry/export checks.

Experiment with implicit fields

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 },
);

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 for implicit surfaces, general beveling, normal-offset shells, and mesh-to-field remeshing.

Computational bounds

parametricSurface checks (uSegments + 1) * (vSegments + 1) before calling the sampler and rejects values above 262,144. Domains and their extents must be finite. A callback that never returns still requires the evaluator’s process/time boundary.

subdivide accepts integer iterations from 0 to 10, then bounds worst-case triangle growth before cloning or welding. The estimate includes the optional presplit stage (up to four faces per input triangle, enabled by default), followed by 4 ** iterations. It rejects above 1,000,000 estimated triangles or 128 MiB of output attributes, including morph channels. This is a conservative admission bound, not a measurement of peak memory. It never silently reduces iterations.

arrayLinear and arrayRadial require integer counts from 1 to 10,000, including the existing source; their return value contains count - 1 new meshes. Count 1 returns no copies. Frames, offsets/centers, and all resulting positions must be finite, with rejection before attaching any copies. Resources remain shared and these helpers do not batch draw calls.

repeatAlongCurve(source, points, { count, ... }) places count copies along a sampled curve, evenly spaced by arc length between start and end (fractions of its length). Each copy’s local +X follows the tangent of the segment it sits on (the outgoing segment at a sample point) and local +Y points toward up, default [0,1,0], made perpendicular to the tangent. scale and twist are constant or interpolated from attachment to tip; opposite: true adds a copy twisted a further 180 degrees at each position. With the default merge: true it returns one BufferGeometry: every source attribute is copied per copy, UVs unchanged, positions, normals and tangents transformed, material groups and morph targets not copied, and along: true adds a float _along attribute from 0 on the first copy to 1 on the last, which both GLB converters export as _ALONG. A merge larger than 262,144 vertices fails before allocating. With merge: false it returns shared-geometry mesh nodes, like arrayLinear, and does not move the source.

These are per-operation compute limits for every asset. Choose a coarser sampling/subdivision or deliberately split large work; no asset category selects a different budget.

Basic shape factories now reject invalid dimensions and segment counts before construction. Dimensions must be finite and representable in Float32. Box, sphere, cone, plane, torus and positive shape radii require positive dimensions. A cylinder may have one zero end radius for a tip; both cannot be zero. Capsule middle length may be zero, making its total length twice the radius. Capsules drop the zero-area triangles three.js builds at the poles (and the empty straight section at zero length), as spheres do, keeping every vertex and UV: capsuleGeo(0.5, 1) has 48 triangles, 8 per radial segment (6 at zero length). A zero-thickness sheet uses planeGeo; a zero-size box is an error. decalBox retains its documented 0.002 minimum depth and accepts a nonnegative requested depth.

Basic shape segments are integers up to 4,096, with minima of 3 for circular segments, 2 for sphere height segments, and 1 for plane segments. Sphere, torus and plane grids also cap (firstSegments + 1) * (secondSegments + 1) at 262,144 before allocation. Kiln reports the offending argument; it does not round, reduce detail or change the requested shape. These checks do not replace the evaluator boundary for raw Three.js or authored custom geometry.

Require a closed solid

geometryDiagnostics(geometry).solid reports closed (no boundary edges), manifold (no edge shared by three or more faces), orientation (outward or inward from the sign of the signed volume, mixed on any winding conflict or a zero volume) and signedVolume in cubic geometry units. To make the build depend on it, mark the part:

const hull = createPart('Hull', await extrudeProfile(outline, { depth: 2 }), steel, { parent: root });
requireSolid(hull); // or requireSolid(group) for every visible mesh under it

A marked mesh that is open, non-manifold or not outward fails the build with REQUIRE_SOLID, naming the part and the failing facts. The check measures; it repairs nothing, and it does not detect general self-intersection. The print export (kiln export --format stl|3mf) applies the same measurement to every visible mesh, marked or not.

The solid primitives are closed solids by contract: boxGeo, sphereGeo, the cylinder*, cone* and capsule* families, cylinderOnAxis, taperConeGeo, torusGeo, decalBox and wingGeo each return a closed, manifold, outward mesh for every input they accept, so requireSolid passes on them. “Closed” is measured after welding vertices that share a position, as geometryDiagnostics does; the glTF primitive itself may stay split at UV seams, and at hard edges: each flat face of boxGeo, decalBox and wingGeo has its own vertices, so its vertex normals are its face normal in any renderer, with or without flatShading. Scene builders (createLadder, wallWithOpening, room, createStairs, createWingPair, beamBetween) make the same promise for each mesh they create, not for the assembly, whose parts overlap by design. Their parts still share no faces, so a textured build reports no FLUSH_FACES pair: an ascending createStairs riser stops under its tread (a step rise at or below treadThickness gets no riser), and room runs its front and back walls past the corners (width + wallThickness) and fits the left and right walls between them (depth - wallThickness), so no corner overlaps or leaves a notch; side-wall openings must fit the shorter walls. planeGeo, foliageCardGeo, crossedQuadsGeo and octaGridPlane are open, one-sided surfaces and requireSolid fails them. scripts/audit-primitives.test.ts measures the contract, and the measured table is in the primitives audit. torusGeo rejects tube >= radius, which would cross the ring axis and intersect itself while still reading as closed and outward.

Bake edge and cavity attributes

bakeSurfaceAttributes(target, { edge?, cavity? }) writes two float vertex attributes on each visible mesh under target, exported as glTF _EDGE and _CAVITY: edge is 1 on chamfers, bevels and rims and 0 on flat faces (for paint wear); cavity is 1 fully exposed and toward 0 in recesses (an ambient-occlusion input). Call it after every occluding part is attached. Each mesh gets its own geometry copy, because cavity depends on placement. The bake is deterministic and bounded by GEOMETRY_ALLOCATION_LIMITS; see the delivery contract for the formulas.

Carry vertex colours and author masks

Export keeps these vertex attributes; anything else is reported as EXPORT_ATTRIBUTE_UNSUPPORTED (or rejected under geometryPolicy: 'strict'):

three.js attribute glTF attribute legacy (default) three
position, normal, uv, tangent POSITION, NORMAL, TEXCOORD_0, TANGENT yes yes
color (3 or 4 components) COLOR_0 yes yes
_edge, _cavity (baked) _EDGE, _CAVITY yes yes
lowercase _name, 1 to 4 float components _NAME yes yes
uv1 TEXCOORD_1 yes yes
uv2, uv3 TEXCOORD_2, TEXCOORD_3 no yes
skinIndex, skinWeight JOINTS_0, WEIGHTS_0 no yes

A texture with channel = 1 (for example a baked aoMap) samples uv1 (TEXCOORD_1); export refuses it when the mesh has no uv1, and reports channels a converter does not write.

An author attribute name is an underscore, a lowercase letter, then lowercase letters, digits or single underscores (at most 64 characters), such as _wet or _flow_dir. It is written as 32-bit floats under the uppercase name, and three.js GLTFLoader reads it back under the lowercase one. Use it for a per-vertex mask such as a wet line or wear instead of cutting triangles along the boundary. runtime --target three keeps author attributes as unquantized 32-bit floats and lists them in the sidecar customAttributes. Mixed-case names such as _Wet would not round-trip and stay unsupported.

glTF multiplies base colour by COLOR_0, and loaders enable vertex colours when it is present, whether or not the authoring material set vertexColors. Remove a color attribute that is not meant to tint the surface.

Know what export welds

Export welds only exactly equal vertices. With the default indexPolicy: 'indexed', each primitive built without an index buffer gets one, and two corners merge only when every attribute (position, normal, UVs, colour, tangent, author attributes and morph data) is bitwise identical. Material optimization welds by the same rule. There is no distance tolerance, so corners a rounding error apart stay separate vertices: seams survive, and the file keeps every distinct corner you built.

To weld on purpose, call mergeVertices before returning the geometry, or round coordinates you know should coincide so their corners become equal; both can shrink a baked or generated mesh noticeably. indexPolicy: 'asBuilt' on render calls (local hosts: KILN_INDEX_POLICY=asBuilt) keeps helper buffers as built and requires optimization off. The receipt’s indexBuffers reports vertex, morph and index payload bytes before and after this pass, not GLB file size.

Find faces that will flicker

Two faces that lie on one plane, face the same way and overlap cannot be ordered by a depth buffer. The pixels they share switch between the two as the camera moves: z-fighting. It is a property of the geometry. A GLB cannot carry polygon offset or a depth bias, which are renderer state, so the flicker follows the file into every engine.

Every build measures its static meshes for this and adds one FLUSH_FACES line to warnings when it finds any:

FLUSH_FACES: 3 pairs of parts have faces on one plane that will flicker (z-fighting) in any
renderer. Worst: Mesh_Board and Mesh_Plaque, on one plane, sharing 0.08 m² near [0, 0.3,
0.02], normal (0, 0, 1). Also: Mesh_Board and Mesh_Label (0.02 m²); Mesh_Floor and Mesh_Mat
(0.01 m²). For each pair, move the smaller face at least 2 mm along the shared normal, remove the
covered face, or cut the opening it sits in.

A pair is reported when all of these hold:

Test Rule
Facing Normals within one degree. Faces that face each other, such as a crate on a floor, are contact and are not reported, unless one of them is drawn on both sides.
Plane Every corner of each triangle is within 0.5 mm of the other’s plane, or a thousandth of the asset’s size when that is smaller.
Area The overlap, summed over the two parts, is at least a ten-thousandth of the asset’s size squared: a patch a hundredth of the asset across. Faces that meet along an edge share none.
Place The shared area is not buried. Undersides on the asset’s lowest plane are where it stands. Faces that lie against a face pointing the other way, such as two undersides on one deck, are in contact with it. Neither is reported.
Look The two parts differ in something a renderer draws. Two parts with one plain material (no texture, no vertex colours, the same values) put the same colour on a pixel whichever wins, so they are not reported.

The warning is advisory: the build succeeds and QA verdicts do not change. It is a measurement of every triangle, in world space, so it does not depend on a camera, and it is not a visibility test: a flush pair behind other parts is still reported. It does not measure instanced, skinned or morphing meshes, hidden parts, or a mesh drawn from part of its buffer, and it does not compare two levels of one defineLod chain. On a very large asset it can stop at its budget, and then the line says so.

To fix a pair, change the geometry: move the overlay 2 mm or more along the normal, delete the face that is covered, or cut the opening the overlay sits in so only one face is left on that plane. Offsets much under 2 mm still fight at a distance, because depth precision falls with range.

Derive a lower-detail tier

defineLod declares tiers you build; it never generates one. To derive a lower tier from a part, call simplifyGeometry on that part’s geometry and place the result in the tier:

const rock = sphereGeo(1, 32, 16);
const far = await simplifyGeometry(rock, { ratio: 0.25 }); // or { targetTriangles: 240 }
createPart('RockNear', rock, stone, { parent: nearTier });
createPart('RockFar', far, stone, { parent: farTier });
defineLod([nearTier, farTier], { screenCoverage: [0.05, 0.002] });

It is async, uses the pinned meshoptimizer simplifier and returns new geometry; the input is unchanged. Surviving vertices keep their exact attribute values. Each material group is simplified on its own with its boundary vertices locked, vertices are welded only where every attribute matches so UV and normal seams hold, and open borders stay locked unless lockBorder: false. maxError (a fraction of the mesh extent, default 1, no practical limit) can stop it short of the target. userData.kilnSimplify records trianglesBefore, trianglesAfter, the achieved ratio and the simplifier’s error and errorAbsolute; a result more than 5% above the target adds a SIMPLIFY_TARGET_NOT_REACHED build note. It never runs implicitly or to meet a budget. Flat-shaded or heavily seamed meshes simplify less; inspect the lower tier through its levelsOfDetail path.

Declare a triangle budget

defineBudget({ triangles: { LOD0: 4000, LOD1: 900 }, draws: 3 }) records the asset’s budget. Receipts measure the written GLB: tier n is level min(n, last) of every MSFT_lod chain plus everything outside the chains, and draws count LOD0 as stored, before batching: each child of a repeatInstances group is a draw. The LOD0 tier also reports instancedDraws, the count after the three runtime target batches those groups, for information only. Do not merge repeated parts by hand to meet a draws cap that the batched export would meet; raise the cap or note the difference instead. The result is budget: { status, tiers } in render results, kiln_render and CLI receipts. It is advisory; kiln render --strict-budget exits 1 when a tier fails.

Material limits are declared the same way: defineBudget({ images: 6 }), decodedBytes, or materialTier: 'web.portable.v1/hero' for a reference tier’s figures. They report in budget.materials. Without one, materialAdvice notes compare the textures with the web.portable.v1/standard reference tier; they are optional optimization advice, not a budget, so keep textures that carry the look.

Joint discovery and resource counts

describeAssembly(root).joints finds validated articulated joints, wheel-spin pivots, and steering pivots by metadata, even after renaming. Entries contain the node, snapshot nodeId, kinds, semantic roles and a detached articulated descriptor when present. Match nodeId against the description’s frames for wheel axes. Duplicate names remain separate entries. This uses the common assembly node support described by Discovery; it is not skeleton validation or inference of undeclared custom roles. getJointNames(root) remains the narrower Joint_ prefix query.

countTriangles(root) counts placed source triangles, including the active count of an InstancedMesh and two triangles per sprite. It does not account for visibility, culling, draw ranges or material groups. countMaterials counts material identities; sharing a material does not merge meshes into a draw call.

The final render’s instanceability.metrics distinguishes meshNodes (mesh-bearing node placements), meshInstances (including GPU-instanced copies), uniqueMaterials, triangles and drawCalls. These counts span all document scenes. drawCalls is a single-pass estimate per referenced primitive, with GPU instancing counted as a batch; it is not a measured renderer frame and excludes shadow/depth passes, culling and destination batching. uniqueGeometries counts distinct referenced glTF primitives, not GPU buffer allocations. Final GLB metrics account for the exported representation, which may differ from the source after optimization. The instanceability grade is informational, not a QA verdict: its summary names the metric that set the grade, and a transparent material lowers only an A or B grade to C.

When drawn materials share alpha mode and cutoff, sidedness, texture bindings and samplers, extensions and extras, and differ only in factors such as base colour or roughness, the report adds optional advice. The summary ends with “Optional advice, not a requirement”, each reason names the members, differing factors, parts using them and what a merge needs, and instanceability.advice holds the groups with the projected material count and grade. The advice never changes the grade or a QA disposition. Merging differing base colours needs a shared texture, an atlas region or vertex colours (COLOR_0); the host’s KILN_BAKE_OPTIMIZE=palette builds a palette texture for flat-colour materials. Byte-identical materials are already merged by deduplication.

Specialized factories also check finite dimensions and bounded counts. Cards accept pivots outside their panel when the resulting coordinates remain finite. Wings accept a zero tip chord; stairs accept signed rise/run for descending or reversed flights. Blade bevels produce one closed cross-section, with partial bevels and a full diamond at edgeBevel: 1. See the specialized-domain evidence for limits and changed bevel topology.

Generate UVs in an explicit frame

Keep valid built-in UVs by sharing the geometry or using copyGeometry. Use remapUV to transform existing U/V values and autoUnwrap for an xatlas chart atlas. projectUV replaces UV0 with a named planar, box or cylindrical projection:

const mapped = projectUV(rawGeometry, {
  projection: 'cylindrical',
  frame: { origin: [0, 0, 0], rotation: [0, 0, -90] },
  seamDegrees: 180,
});

Frames use geometry-local coordinates and Euler XYZ degrees. Planar maps frame XY; box chooses a plane per triangle; cylindrical wraps frame Y. Partial arcs use angularRange: [startDegrees, sweepDegrees] instead of seamDegrees. The range must cover side vertices; sweep is positive and at most 360 degrees. Cap triangles parallel to frame XZ use planar UVs by default; caps: 'side' opts into side mapping. Full-wrap seam triangles may use U above 1, requiring repeat texture sampling. Triangles spanning more than half a revolution fail with a subdivision hint.

By default, planar/box coordinates and cylindrical height normalize each geometry’s extents to 0..1, so texel density changes with part size. Pass metersPerUnit to map one UV unit to a fixed length instead, measured from the frame origin:

const wall = projectUV(wallGeometry, { projection: 'box', metersPerUnit: 0.5 });

Parts of any size then tile at the same density, and wall pieces that share a frame continue the same brick courses. A full cylindrical wrap rounds its circumference at the largest radius to a whole number of tiles, so the seam meets itself; on a cone the narrower rings are compressed accordingly. A partial angularRange uses the exact arc length at the largest radius.

Output is owned and non-indexed to separate triangle-corner UVs. Positions, normals, matching attributes, material groups, draw range and triangle order are preserved; tangents are removed with a diagnostic. Zero projection extent maps to 0.5. Where the projection is continuous (one planar face, cylindrical sides), weld the result with mergeVertices: it rejoins corners that share position, normal and UV and keeps box faces and the cylindrical seam split. Per-triangle UVs left unwelded multiply vertex count and file size. Inputs must be finite triangle geometry with matching per-vertex attributes; morph targets require a separate contract. Limits are two million source samples and output corners plus 128 MiB of expanded attributes. This projection does not pack an atlas, remove geometric defects, or guarantee a stretch-free texture.

Roof surface coverage

createRoofSurfaceLayout places explicit boxes in a returned roof-face frame for either ridge axis. Panels fit evenly with 2% width gaps. Shingles stagger alternate rows, clip partial tiles at both edges, retain 4% gaps within the clipped cells, overlap rows by up to 8%, and shorten the final row at the eave. Seams and corrugations clip edge strips within the face. These are visual box approximations, not folded sheet-metal or interlocking construction guarantees.

The returned cost reports meshes and triangles (12 per box), not draw calls or hardware instancing. A request may generate at most 10000 boxes; excessive growth, invalid dimensions and singular transforms fail before attaching anything to the parent. The default parent is the face’s roof root, so later roof transforms carry the detail with it. An explicit different parent captures the face placement at construction time and must support lossless TRS rebasing; local shear is rejected with guidance to use the roof root. This avoids a silently distorted export.

Deformation shading and scale

Deformation keeps authored normals when positions are unchanged. When positions change, it rebuilds area-weighted normals using the original smooth/hard seam classes: coincident UV copies with matching authored normals stay smooth, while cap and other authored hard creases remain distinct. Matching is bounded by a relative 1e-7 position grid and 1e-6 normal-component grid; it is not exact topology certification. UVs and material groups remain unchanged. Removed tangents produce DEFORM_TANGENTS_DROPPED; regenerate them for normal maps.

A nonzero interval always has normalized progress, even for tiny geometry. Endpoint roundoff is capped at one millionth of interval length, and outside positions stay unchanged. Abrupt interval boundaries can still create a discontinuity: use a suitable falloff/segmentation and inspect the result. Deform before creating morph targets; their separate mapping is not supported. Deformation accepts at most two million vertices / three million corners and preserves input buffers.

Subdivision normalizes its working coordinates before welding and the upstream adjacency grid, then restores source units. This avoids changing topology merely because the same shape is authored in millimeters or meters. The upstream grid still has finite relative resolution, so extremely close features need inspection. Default position-only welding removes corner attributes and material groups; preserveUV: true retains supported corner/group/morph data. Loss diagnostics stay with the output. Subdivide before skin binding: averaging discrete joint indices would produce invalid skinning and is explicitly rejected.

The subdivision preservation path supports continuous vertex attributes with one to four components, including RGBA alpha; normalized storage is decoded to owned Float32 values before interpolation. Supported morph attributes have three components. Temporary scalar channels used for four-component interpolation are removed before returning the geometry; no internal attributes enter the export.

Read this page in the repository