# API by Concept

Every public API function belongs to one of 16 fundamental concepts. This document groups them by concept rather than by module, making it easy to see the full set of operations for each idea.

## Concepts

- **[C1: Primitive Construction](#c1-primitive-construction)** — Create geometry from parameters — no input geometry required. *(76 functions)*
- **[C2: Boolean Combination](#c2-boolean-combination)** — Combine same-dimension geometry using CSG set operations. *(6 functions)*
- **[C3: Rigid Transform](#c3-rigid-transform)** — Reposition or reorient geometry without changing its shape. *(3 functions)*
- **[C4: Dimensional Promotion](#c4-dimensional-promotion)** — Convert a 2D profile into a 3D solid (extrude, revolve, loft, sweep). *(52 functions)*
- **[C5: Topology Query](#c5-topology-query)** — Select or inspect named faces and edges on a shape. *(3 functions)*
- **[C6: Edge Feature](#c6-edge-feature)** — Modify edges of a solid — fillets, chamfers, draft, offset. *(7 functions)*
- **[C7: Pattern Replication](#c7-pattern-replication)** — Duplicate geometry in regular arrangements (linear, circular, mirror). *(6 functions)*
- **[C8: Constraint Solving](#c8-constraint-solving)** — Define geometry by relationships and let a solver find positions. *(17 functions)*
- **[C9: Spatial Placement](#c9-spatial-placement)** — Position geometry relative to other geometry using semantic anchors. *(6 functions)*
- **[C10: Assembly & Kinematics](#c10-assembly-kinematics)** — Compose parts with joints for kinematic simulation. *(3 functions)*
- **[C11: Parameterization & UI](#c11-parameterization-ui)** — Declare user-facing controls that drive model geometry. *(7 functions)*
- **[C12: Dimensional Demotion](#c12-dimensional-demotion)** — Extract 2D geometry from a 3D solid (section, projection). *(3 functions)*
- **[C13: Export & Output](#c13-export-output)** — Convert geometry to external formats (STL, 3MF, SVG, DXF, G-code, PDF). *(5 functions)*
- **[C14: Visual & Debugging](#c14-visual-debugging)** — Control viewport appearance and debugging aids. *(36 functions)*
- **[C15: Import & Composition](#c15-import-composition)** — Bring external geometry or other ForgeCAD modules into the current script. *(1 functions)*
- **[C16: Part Library](#c16-part-library)** — Pre-built parametric parts accessible via `lib.*`. *(4 functions)*

---

## C1: Primitive Construction

Create geometry from parameters — no input geometry required.

#### `sdf.sphere()` — Create an SDF sphere centered at the origin.

```ts
sdf.sphere(radius: number): SdfShape
```

#### `sdf.box()` — Create an SDF box centered at the origin with given full dimensions (not half-extents).

```ts
sdf.box(x: number, y: number, z: number): SdfShape
```

#### `sdf.cylinder()` — Create an SDF cylinder centered at the origin, axis along Z.

```ts
sdf.cylinder(height: number, radius: number): SdfShape
```

#### `sdf.torus()` — Create an SDF torus centered at the origin, lying in the XY plane.

```ts
sdf.torus(majorRadius: number, minorRadius: number): SdfShape
```

#### `sdf.capsule()` — Create an SDF capsule centered at the origin, axis along Z.

```ts
sdf.capsule(height: number, radius: number): SdfShape
```

#### `sdf.cone()` — Create an SDF cone with base at z=0 and tip at z=height.

```ts
sdf.cone(height: number, radius: number): SdfShape
```

#### `sdf.smoothUnion()` — Smooth union — blends shapes together with a smooth transition radius.

```ts
sdf.smoothUnion(a: SdfShape, b: SdfShape, options: { radius: number; }): SdfShape
```

#### `sdf.smoothDifference()` — Smooth difference — smoothly subtracts b from a.

```ts
sdf.smoothDifference(a: SdfShape, b: SdfShape, options: { radius: number; }): SdfShape
```

#### `sdf.smoothIntersection()` — Smooth intersection — smoothly intersects a and b.

```ts
sdf.smoothIntersection(a: SdfShape, b: SdfShape, options: { radius: number; }): SdfShape
```

#### `sdf.morph()` — Morph between two SDF shapes. t=0 → a, t=1 → b.

```ts
sdf.morph(a: SdfShape, b: SdfShape, t: number): SdfShape
```

#### `sdf.blend()` — Spatially blend between two SDF patterns. The blend function receives (x, y, z) and returns 0..1: 0 = fully pattern `a`, 1 = fully pattern `b`.

```ts
sdf.blend(a: SdfShape, b: SdfShape, fn: (x: number, y: number, z: number) => number, options?: BlendOptions): SdfShape
```

**`BlendOptions`**
- `constants?: Record<string, number>` — Optional named constants accessible in the blend function.

#### `sdf.gyroid()` — Gyroid TPMS lattice — the most common lattice for additive manufacturing.

```ts
sdf.gyroid(options: TpmsOptions): SdfShape
```

**`TpmsOptions`**
- `thickness?: number` — Dimensionless field threshold kept for compatibility. Prefer `wallThickness` for approximate millimeter units.
- `wallThickness?: number` — Approximate physical wall thickness in millimeters.
- `tpmsThicknessMode?: TpmsThicknessMode` — Override TPMS thickness interpretation. Defaults to metric when `wallThickness` is used, field-threshold when `thickness` is used.
- Also: `cellSize: number`

#### `sdf.schwarzP()` — Schwarz-P TPMS lattice — isotropic pore structure.

```ts
sdf.schwarzP(options: TpmsOptions): SdfShape
```

#### `sdf.diamond()` — Diamond TPMS lattice — stiffest TPMS structure.

```ts
sdf.diamond(options: TpmsOptions): SdfShape
```

#### `sdf.lidinoid()` — Lidinoid TPMS lattice — visually distinct from gyroid, popular in research and art.

```ts
sdf.lidinoid(options: TpmsOptions): SdfShape
```

#### `sdf.tpmsBlock()` — TPMS block preset clipped to an explicit design space.

```ts
sdf.tpmsBlock(options: TpmsBlockOptions): SdfShape
```


`TpmsBlockOptions`: `{ type?: "gyroid" | "schwarzP" | "diamond" | "lidinoid", size: Vec3 }`

#### `sdf.withinBox()` — Clip an SDF shape to a box-shaped design space.

```ts
sdf.withinBox(shape: SdfShape, options: { size: Vec3; }): SdfShape
```

#### `sdf.noise()` — 3D Simplex noise field — produces organic, natural-looking displacements.

```ts
sdf.noise(options?: NoiseOptions): SdfShape
```

**`NoiseOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `scale?` | `number` | Spatial frequency — smaller = larger features. Default: 0.1 |
| `amplitude?` | `number` | Peak displacement amplitude. Default: 1 |
| `octaves?` | `number` | fBm octaves (1 = plain simplex, higher = more detail). Default: 1 |
| `seed?` | `number` | Seed for deterministic variation. Default: 0 |

#### `sdf.voronoi()` — 3D Voronoi pattern — organic cellular structures like bone, coral, or soap bubbles.

```ts
sdf.voronoi(options?: VoronoiOptions): SdfShape
```

**`VoronoiOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `cellSize?` | `number` | Size of each Voronoi cell in world units. Default: 10 |
| `wallThickness?` | `number` | Wall thickness between cells. Default: 1 |
| `seed?` | `number` | Seed for deterministic variation. Default: 0 |
| `suppressionThreshold?` | `number` | Projection weight for membrane suppression (0..1). Controls how much of the surface-normal distance component is removed from Voronoi cell distances. 0 = no projection (classic 3D voronoi with membranes). 1 = full tangent-plane projection (pure 2D pattern on surface). Default: 0.85. Only active when voronoi is intersected with another shape. |

#### `sdf.honeycomb()` — Honeycomb (hexagonal) lattice pattern. Intersect with your shape to apply.

```ts
sdf.honeycomb(options?: HoneycombOptions): SdfShape
```

**`HoneycombOptions`**
- `cellSize?: number` — Size of each hex cell. Default: 8
- `wallThickness?: number` — Wall thickness. Default: 1

#### `sdf.waves()` — Sinusoidal wave ridges — parallel ridges along an axis.

```ts
sdf.waves(options?: WavesOptions): SdfShape
```

**`WavesOptions`**
- `wavelength?: number` — Distance between wave peaks. Default: 10
- `amplitude?: number` — Height of waves. Default: 1
- `axis?: "x" | "y" | "z"` — Axis along which waves propagate: 'x', 'y', or 'z'. Default: 'x'

#### `sdf.knurl()` — Knurl pattern — crossed helical grooves for grips and handles.

```ts
sdf.knurl(options?: KnurlOptions): SdfShape
```

**`KnurlOptions`**
- `pitch?: number` — Distance between knurl ridges. Default: 3
- `depth?: number` — Depth of knurl grooves. Default: 0.5
- `angle?: number` — Helix angle in degrees. Default: 30

#### `sdf.perforated()` — Perforated plate pattern — regular array of cylindrical holes.

```ts
sdf.perforated(options?: PerforatedOptions): SdfShape
```

**`PerforatedOptions`**
- `radius?: number` — Hole radius. Default: 3
- `spacing?: number` — Center-to-center spacing. Default: 8

#### `sdf.scales()` — Fish/dragon scale pattern — overlapping circular scales in hex-packed rows.

```ts
sdf.scales(options?: ScalesOptions): SdfShape
```

**`ScalesOptions`**
- `size?: number` — Scale diameter. Default: 5
- `depth?: number` — How much scales protrude. Default: 0.8

#### `sdf.brick()` — Brick/stone wall pattern — running bond with mortar grooves.

```ts
sdf.brick(options?: BrickOptions): SdfShape
```

**`BrickOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `width?` | `number` | Brick width. Default: 10 |
| `height?` | `number` | Brick height. Default: 5 |
| `depth?` | `number` | Mortar groove depth. Default: 0.5 |
| `mortar?` | `number` | Mortar gap width. Default: 1 |

#### `sdf.weave()` — Grid lattice pattern — two families of infinite slabs crossing at 90°.

```ts
sdf.weave(options?: WeaveOptions): SdfShape
```

**`WeaveOptions`**
- `spacing?: number` — Thread center-to-center spacing (for intersection patterns). Default: 5
- `threadRadius?: number` — Thread half-width. Default: 1

#### `sdf.basketWeave()` — Basket weave surface pattern — threads with over-under crossings in UV space. Returns a SurfacePattern for use with `.surfaceDisplace()`.

```ts
sdf.basketWeave(options?: BasketWeaveOptions): SurfacePattern
```

**`BasketWeaveOptions`**
- `spacing?: number` — Spacing between threads in mm (both directions). Default: 3
- `threadWidth?: number` — Thread width in mm. Default: 1.5
- `depth?: number` — Thread protrusion depth in mm. Default: 0.8

#### `sdf.pattern2d()` — Create typed, composable 2D surface patterns for `.surfaceDisplace()`.

```ts
sdf.pattern2d(): Pattern2DBuilder
```

#### `sdf.twist()` — Twist an SDF shape around the Z axis.

```ts
sdf.twist(shape: SdfShape, degreesPerUnit: number): SdfShape
```

#### `sdf.bend()` — Bend an SDF shape around the Z axis.

```ts
sdf.bend(shape: SdfShape, radius: number): SdfShape
```

#### `sdf.repeat()` — Repeat an SDF shape in space.

```ts
sdf.repeat(shape: SdfShape, spacing: Vec3, count?: Vec3): SdfShape
```

#### `sdf.circularArray()` — Arrange an SDF shape in a circular array around the Z axis with O(1) folded-domain evaluation.

```ts
sdf.circularArray(shape: SdfShape, count: number, offset?: number): SdfShape
```

#### `sdf.SurfacePattern()` — A 2D surface pattern — a heightmap function for use with `.surfaceDisplace()`.

```ts
sdf.SurfacePattern: typeof SurfacePattern
```

#### `sdf.fromFunction()` — Create a custom SDF from one expression; shader-safe expressions raymarch directly.

```ts
sdf.fromFunction(fn: SdfFunctionSource, options: SdfFunctionOptions): SdfShape
```

**`SdfFunctionOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `bounds` | `SdfBounds \| [ Vec3, Vec3 ]` | Finite design bounds for this opaque custom field. |
| `constants?` | `SdfFunctionConstants` | Named finite constants referenced from the expression body. |
| `maxStep?` | `number` | Conservative maximum raymarch step for native preview. |
| `lipschitz?` | `number` | Optional divisor for non-distance fields. Values above 1 slow preview marching. |

`SdfBounds`: `{ min: Vec3, max: Vec3 }`

#### `sdf.Sculpt()` — Sculpt-like facade: friendly liquid-modeling verbs backed by the same SDF kernel.

```ts
sdf.Sculpt: { sphere: (radius: number) => SdfShape; box: (x: number, y: number, z: number, options?: SculptBoxOptions) => SdfShape; cylinder: (height: number, radius: number) => SdfShape; disk: (radius: number, thickness?: number) => SdfShape; circle: (radius: number, thickness?: number) => SdfShape; capsule: (height: number, radius: number) => SdfShape; torus: (majorRadius: number, minorRadius: number) => SdfShape; cone: (height: number, radius: number) => SdfShape; tube: (points: SculptPointList, options?: SculptTubeOptions) => SdfShape; curve: (points: SculptPointList, options?: SculptTubeOptions) => SdfShape; path: (points: SculptPointList, options?: SculptTubeOptions) => SdfShape; blend: (first?: SculptBlendInput | SculptBlendOptions, optionsOrShape?: SculptBlendInput | SculptBlendOptions, ...rest: (SculptBlendInput | SculptBlendOptions)[]) => SdfShape; union: (first?: SculptBlendInput, ...rest: SculptBlendInput[]) => SdfShape; carve: (base: SdfShape, cutters: SculptBlendInput, options?: SculptBlendOptions) => SdfShape; keep: (first?: SculptBlendInput | SculptBlendOptions, optionsOrShape?: SculptBlendInput | SculptBlendOptions, ...rest: (SculptBlendInput | SculptBlendOptions)[]) => SdfShape; polish: (shape: SdfShape, input?: SculptPolishInput) => SdfShape; material: (input?: SculptPolishInput) => ShapeMaterialProps & { color?: string; }; look: (preset?: SculptLookPreset) => SceneOptions; knownMaterials: typeof knownSculptMaterialPresets; }
```

**`SculptBoxOptions`**
- `radius?: number` — Rounded-box radius. Omit for a sharp SDF box.

**`SculptTubeOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `radius?` | `number` | Tube radius in model units. Used as the default when points do not carry their own radius. Default: 3. |
| `blend?` | `number` | Smooth blend radius between tube segments and joints. Default: smallest point radius. |
| `curve?` | `boolean \| "linear" \| "catmull-rom"` | Smooth the control polyline into a Catmull-Rom curve before sweeping. Default: false for tube/path, true for curve. |
| `segments?` | `number` | Curve samples per control-point interval when curve smoothing is enabled. Default: 8, capped at 8 for realtime preview. |
| `tension?` | `number` | Catmull-Rom tangent scale when curve smoothing is enabled. Default: 0.5. |
| `polish?` | `SculptPolishInput` | Material/color preset applied to the final tube. |

**`SculptBlendOptions`**
- `radius?: number` — Smooth blend radius in model units. Default: 4.

**`ShapeMaterialProps`**

| Option | Type | Description |
|--------|------|-------------|
| `metalness?` | `number` | Metalness factor (0 = dielectric, 1 = metal). Default: 0.05 |
| `roughness?` | `number` | Roughness factor (0 = mirror, 1 = fully diffuse). Default: 0.35 |
| `emissive?` | `string` | Emissive glow color (hex string, e.g. "#ff6b35"). |
| `emissiveIntensity?` | `number` | Emissive intensity multiplier. Default: 1 |
| `opacity?` | `number` | Opacity (0 = fully transparent, 1 = fully opaque). Default: 1 |
| `wireframe?` | `boolean` | Render as wireframe. Default: false |
| `clearcoat?` | `number` | Clearcoat intensity (0–1). Default: 0.1 |
| `clearcoatRoughness?` | `number` | Clearcoat roughness (0–1). Default: 0.4 |
| `transmission?` | `number` | Glass/translucency transmission factor (0–1). Renderer support depends on target. |
| `ior?` | `number` | Index of refraction for transmissive materials. Typical glass is ~1.45. |
| `thickness?` | `number` | Approximate transmissive volume thickness in model units. |
| `specularIntensity?` | `number` | Specular highlight intensity (0–1). |
| `specularColor?` | `string` | Specular highlight tint. |
| `reflectivity?` | `number` | Reflection strength for supported renderers (0–1). |

**`SceneOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `capture?` | `SceneCaptureConfig` | Default capture parameters for `forgecad capture` — CLI flags override these. |
| `background?`, `camera?`, `views?`, `journeys?`, `lights?`, `environment?`, `fog?`, `postProcessing?`, `ground?` | | — |

`SceneBackgroundGradient`: `{ top: string, bottom: string }`

**`SceneCameraConfig`**: `position?: [ number, number, number ]`, `target?: [ number, number, number ]`, `up?: [ number, number, number ]`, `fov?: number`, `type?: "perspective" | "orthographic"`

**`SceneJourneyConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `title?` | `string` | Viewer-facing journey title. Defaults to the journey id. |
| `startsAt?` | `string` | Optional starting step id. Defaults to the first step. |
| `behavior?` | `"opt-in" \| "auto"` | Whether the viewer should offer or auto-open the journey. First slice supports opt-in. |
| `steps` | `SceneJourneyStepConfig[]` | Ordered journey spine. Branches can be added later without changing this core contract. |
| `valid?` | `boolean` | True unless any journey or step diagnostic has level "error". |

**`SceneJourneyStepConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `id` | `string` | Stable step id used by viewer links and Next/Back state. |
| `title?` | `string` | Viewer-facing title. Defaults to the step id. |
| `focus?` | `string` | Object name or slash-separated tree path to focus. |
| `caption?` | `string` | Short optional viewer caption. |
| `camera?` | `SceneViewCameraConfig` | Optional explicit camera for this step. When omitted, the viewer fits `focus`. |
| `resolvedFocusId?` | `string \| null` | Resolved object id after script execution, when `focus` matched exactly one object. |
| `resolvedFocusPath?` | `string \| null` | Resolved object tree path or name after script execution. |

**`SceneLightConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `target?` | `[ number, number, number ]` | Target for directional/spot lights |
| `groundColor?` | `string` | Ground color for hemisphere lights |
| `skyColor?` | `string` | Sky color alias for hemisphere lights (same as color) |
| `angle?` | `number` | Spot light cone angle in radians |
| `penumbra?` | `number` | Spot light penumbra (0–1) |
| `decay?` | `number` | Point/spot light decay |
| `distance?` | `number` | Point/spot light distance (0 = infinite) |
| `castShadow?` | `boolean` | Whether this light casts shadows |
| `type`, `color?`, `intensity?`, `position?` | | — |

**`SceneEnvironmentConfig`**
- `preset?: "studio" | "sunset" | "dawn" | "warehouse" | "forest" | "apartment" | "lobby" | "city" | "park" | "night" | "none"` — Built-in preset name or 'none' to disable
- `intensity?: number` — Environment map intensity
- `background?: boolean` — Use environment map as scene background

**`SceneFogConfig`**
- `near?: number` — Linear fog near distance
- `far?: number` — Linear fog far distance
- `density?: number` — Exponential fog density (if set, uses FogExp2 instead of linear Fog)
- Also: `color?: string`

`ScenePostProcessingConfig`: `{ bloom?: SceneBloomConfig, vignette?: SceneVignetteConfig, grain?: SceneGrainConfig, toneMappingExposure?: number }`

`SceneBloomConfig`: `{ intensity?: number, threshold?: number, radius?: number }`

`SceneVignetteConfig`: `{ darkness?: number, offset?: number }`

`SceneGrainConfig`: `{ intensity?: number }`

**`SceneGroundConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `visible?` | `boolean` | Show a ground plane |
| `color?` | `string` | Ground color |
| `offset?` | `number` | Offset below the model's bounding box minimum Z. Default 0 (flush with model bottom). |
| `receiveShadow?` | `boolean` | Receive shadows on the ground |

**`SceneCaptureConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `framesPerTurn?` | `number` | Frames for one full orbit rotation (default: 72) |
| `holdFrames?` | `number` | Frozen frames before motion starts (default: 6) |
| `pitchDeg?` | `number` | Orbit pitch angle in degrees (default: auto from camera) |
| `fps?` | `number` | Output frame rate (default: 24) |
| `size?` | `number` | Output frame size in pixels (default: 960) |
| `background?` | `string` | Canvas background color for capture (default: '#252526') |

#### `Sculpt.sphere()` — Create a liquid SDF sphere centered at the origin.

```ts
Sculpt.sphere(radius: number): SdfShape
```

#### `Sculpt.box()` — Create a liquid SDF box; pass `{ radius }` for a rounded box.

```ts
Sculpt.box(x: number, y: number, z: number, options?: SculptBoxOptions): SdfShape
```

#### `Sculpt.cylinder()` — Create a liquid SDF cylinder centered at the origin, axis along Z.

```ts
Sculpt.cylinder(height: number, radius: number): SdfShape
```

#### `Sculpt.disk()` — Create a thin circular disk centered at the origin, axis along Z. Useful as a circular cutter or insert.

```ts
Sculpt.disk(radius: number, thickness?: number): SdfShape
```

#### `Sculpt.circle()` — Alias for `Sculpt.disk()`.

```ts
Sculpt.circle(radius: number, thickness?: number): SdfShape
```

#### `Sculpt.capsule()` — Create a liquid SDF capsule centered at the origin, axis along Z.

```ts
Sculpt.capsule(height: number, radius: number): SdfShape
```

#### `Sculpt.torus()` — Create a liquid SDF torus lying in the XY plane.

```ts
Sculpt.torus(majorRadius: number, minorRadius: number): SdfShape
```

#### `Sculpt.cone()` — Create a liquid SDF cone.

```ts
Sculpt.cone(height: number, radius: number): SdfShape
```

#### `Sculpt.tube()` — Create a smooth tube through a list of 3D points.

```ts
Sculpt.tube(points: SculptPointList, options?: SculptTubeOptions): SdfShape
```

#### `Sculpt.curve()` — Create a smooth variable-thickness sweep through 3D control points.

```ts
Sculpt.curve(points: SculptPointList, options?: SculptTubeOptions): SdfShape
```

#### `Sculpt.path()` — Alias for `Sculpt.tube()`; points may use [x, y, z, radius] for variable thickness.

```ts
Sculpt.path(points: SculptPointList, options?: SculptTubeOptions): SdfShape
```

#### `Sculpt.blend()` — Smoothly blend one or more SDF shapes into a continuous body.

```ts
Sculpt.blend(first?: SculptBlendArg, optionsOrShape?: SculptBlendArg, ...rest: SculptBlendArg[]): SdfShape
```

#### `Sculpt.union()` — Sharply union one or more SDF shapes.

```ts
Sculpt.union(first?: SculptBlendInput, ...rest: SculptBlendInput[]): SdfShape
```

#### `Sculpt.carve()` — Smoothly subtract one or more cutter shapes from a base shape.

```ts
Sculpt.carve(base: SdfShape, cutters: SculptBlendInput, options?: SculptBlendOptions): SdfShape
```

#### `Sculpt.keep()` — Smoothly intersect one or more SDF shapes.

```ts
Sculpt.keep(first?: SculptBlendArg, optionsOrShape?: SculptBlendArg, ...rest: SculptBlendArg[]): SdfShape
```

#### `Sculpt.polish()` — Apply a Sculpt material preset or direct material properties.

```ts
Sculpt.polish(shape: SdfShape, input?: SculptPolishInput): SdfShape
```

#### `Sculpt.material()` — Resolve a Sculpt material preset to ForgeCAD material properties.

```ts
Sculpt.material(input?: SculptPolishInput): ShapeMaterialProps & { color?: string; }
```

#### `Sculpt.look()` — Return a polished scene preset tuned for liquid SDF preview.

```ts
Sculpt.look(preset?: SculptLookPreset): SceneOptions
```

#### `Sculpt.knownMaterials()` — List the built-in Sculpt material preset names.

```ts
Sculpt.knownMaterials(): SculptMaterialPreset[]
```

#### `toShape()` — Materialize one SDF leaf or all SDF leaves in a renderable tree.

Raw `SdfShape` values become mesh-backed `Shape`s. Plain objects and arrays preserve their renderable children as a `ShapeGroup` when more than one leaf is found. Non-renderable metadata is ignored for materialization and remains available to callers through normal `require()` return values.

```ts
toShape(value: unknown, options?: SdfToShapeOptions): ToShapeTreeResult
```

**`SdfToShapeOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `edgeLength?` | `number` | Target mesh edge length. Smaller = finer mesh. Overrides quality-derived resolution. |
| `bounds?` | `{ min: Vec3; max: Vec3; }` | Override auto-computed bounds. Strongly recommended for infinite/repeated fields. |
| `quality?` | `SdfMeshingQuality` | Coarse quality preset. Default: 'preview'. |
| `tolerance?` | `number` | Preferred absolute surface tolerance in millimeters. |
| `minFeatureSize?` | `number` | Smallest feature that should survive meshing, in millimeters. |
| `simplify?` | `boolean \| "safe"` | Simplification control. `false` disables, `true` and `'safe'` use topology-validated simplification. |
| `maxTriangles?` | `number` | Optional post-extraction triangle budget. |
| `maxGridPoints?` | `number` | Optional pre-extraction grid-point budget. Default is browser-safe. |
| `minEdgeLength?` | `number` | Lower clamp for resolved edge length. Default: 0.15mm. |
| `diagnostics?` | `boolean` | Log resolved meshing settings and backend extraction timings. |

#### `combine()` — Collapse a tree of SDF leaves into one continuous SDF field.

This intentionally discards per-leaf color/material identity because the result is one scalar field. Use plain object returns for multi-material SDF preview, and use `combine(...)` only when you want one implicit body.

```ts
combine(value: unknown, options?: CombineOptions): SdfShape
```

`CombineOptions`: `{ op?: "union" | "intersection" }`

#### `circle2d()` — Create a 2D circle centered at the origin.

Omit `segments` for a smooth (auto-tessellated) circle. Pass an integer to get a regular polygon approximation — e.g. `6` for a hexagon, `8` for an octagon.

```ts
circle2d(25).extrude(10);          // smooth cylinder
circle2d(25, 6).extrude(10);       // hexagonal prism
```

```ts
circle2d(radius: number, segments?: number): Sketch
```

#### `ellipse()` — Create a 2D ellipse centered at the origin.

```ts
ellipse(30, 15).extrude(5);
ellipse(30, 15, 32).extrude(5); // lower-resolution approximation
```

```ts
ellipse(rx: number, ry: number, segments?: number): Sketch
```

#### `loadFont()` — Pre-load and cache a font for use with `text2d()`.

Fonts are cached by their source string (or `cacheKey` for `ArrayBuffer` sources), so repeated calls with the same path are free. Pre-loading is useful when you call `text2d()` many times with the same font — it avoids repeated disk reads.

Built-in font names that work everywhere (browser + CLI):

- `'sans-serif'` or `'inter'` — bundled Inter Regular

```ts
const font = loadFont('/path/to/Arial Bold.ttf');
text2d('Title', { size: 12, font }).extrude(1.5);
text2d('Subtitle', { size: 8, font }).extrude(1);
```

```ts
loadFont(source: string | ArrayBuffer, cacheKey?: string): opentype.Font
```

#### `ngon()` — Create a regular polygon inscribed in a circle of the given radius.

`radius` is the center-to-vertex (circumradius) distance. Use `sides` of `3` for a triangle, `6` for a hexagon, etc. The first vertex is at the top (−90° from +X).

```ts
ngon(6, 20).extrude(10); // hexagonal prism, circumradius 20
```

```ts
ngon(sides: number, radius: number): Sketch
```

#### `path()` — Create a new `PathBuilder` for tracing a 2D outline point by point.

`PathBuilder` is a fluent API for constructing 2D profiles using a mix of line segments, arcs, bezier curves, and splines. Always start with `.moveTo(x, y)` to set the starting point. Call `.close()` to get a filled `Sketch`, or `.stroke(width)` to thicken an open polyline into a solid profile.

Edge labels can be assigned with `.label('name')` after any segment — they propagate through extrusion, revolve, loft, and sweep into named faces on the resulting `Shape`.

```ts
// Closed triangle
const triangle = path().moveTo(0, 0).lineH(50).lineV(30).close();

// L-shaped bracket as a stroke
const bracket = path().moveTo(0, 0).lineH(50).lineV(-70).lineAngled(20, 235).stroke(4);

// Labeled edges for downstream face references
const slot = path()
  .moveTo(0, 0)
  .lineTo(30, 0).label('bottom')
  .lineTo(30, 10)
  .lineTo(0, 10).label('top')
  .close();
```

```ts
path(): PathBuilder
```

#### `polygon()` — Create a 2D polygon from an array of `[x, y]` points or `Point2D` objects.

Winding order is normalized automatically — clockwise (CW) input is silently reversed to CCW before being passed to the geometry kernel.

```ts
polygon([[0, 0], [50, 0], [25, 40]]).extrude(5); // triangle
```

```ts
polygon(points: ([ number, number ] | Point2D)[]): Sketch
```

#### `polygonVertices()` — Compute the vertex positions of a regular polygon.

Default orientation places the first vertex at the top (90 degrees), matching the convention used by `ngon()`.

Eliminates manual Math.sqrt(3) for triangles, pentagon vertex math, etc:

```js
// Before — manual equilateral triangle
const v1 = [center.x - r/2, center.y + r * Math.sqrt(3)/2];
const v2 = [center.x - r/2, center.y - r * Math.sqrt(3)/2];
const v3 = [center.x + r, center.y];

// After — declarative
const [v1, v2, v3] = polygonVertices(3, r);
```

```ts
polygonVertices(sides: number, radius: number, options?: PolygonVerticesOptions): LayoutPoint[]
```

**`PolygonVerticesOptions`**
- `startDeg?: number` — Angle of the first vertex in degrees (default: 90 = top).
- `centerX?: number` — Center X coordinate (default: 0).
- `centerY?: number` — Center Y coordinate (default: 0).

`LayoutPoint`: `{ x: number, y: number }`

#### `rect()` — Create a 2D rectangle centered at the origin.

```ts
rect(40, 20).extrude(5);
```

```ts
rect(width: number, height: number): Sketch
```

#### `arcSlot()` — Create an arc-shaped slot (banana / annular sector) centered at the origin.

The slot is symmetric about the +X axis. The two ends are closed with semicircular caps. `pitchRadius` is the distance from the origin to the centerline of the slot, and `thickness` is the radial width of the slot.

```ts
arcSlot(135, 74, 40).extrude(5); // pitch R135, 74° sweep, 40mm wide
```

```ts
arcSlot(pitchRadius: number, sweepDeg: number, thickness: number): Sketch
```

#### `roundedRect()` — Create a 2D rectangle with rounded corners, centered at the origin.

The corner radius is automatically clamped to `min(width/2, height/2)` so it can never exceed the shape dimensions.

```ts
roundedRect(60, 30, 5).extrude(3);
```

```ts
roundedRect(width: number, height: number, radius: number): Sketch
```

#### `slot()` — Create a slot (oblong / stadium shape) — a rectangle with semicircular ends, centered at the origin.

```ts
slot(40, 10).extrude(3); // 40mm long, 10mm wide slot
```

```ts
slot(length: number, width: number): Sketch
```

#### `spline2d()` — Build a smooth Catmull-Rom spline sketch from 2D control points.

A closed spline (default) returns a filled profile. An open spline requires a strokeWidth option to produce a solid sketch. Use tension (0..1, default 0.5) to control curve tightness.

```ts
spline2d(points: Vec2[], options?: Spline2DOptions): Sketch
```

**`Spline2DOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `closed?` | `boolean` | Closed loop (default true). |
| `tension?` | `number` | Catmull-Rom tension in [0, 1]. 0 = very round, 1 = linear-ish. Default 0.5. |
| `samplesPerSegment?` | `number` | Samples per segment (minimum 3). Default 16. |
| `strokeWidth?` | `number` | For open splines, provide stroke width to return a solid Sketch. If omitted for open splines, an error is thrown. |
| `join?` | `"Round" \| "Square"` | Stroke join for open splines. Default 'Round'. |

#### `star()` — Create a star shape with alternating outer and inner radii.

```ts
star(5, 30, 12).extrude(4); // five-pointed star
```

```ts
star(points: number, outerR: number, innerR: number): Sketch
```

#### `stroke()` — Create a stroked polyline sketch from an array of 2D points.

```ts
stroke(points: [ number, number ][], width: number, join?: "Round" | "Square"): Sketch
```

#### `text2d()` — Build a filled 2D Sketch from a text string.

The Sketch origin is at the left end of the text baseline by default. Use `align` and `baseline` options to adjust placement. Text is rendered using the bundled Inter font by default, or any TTF/OTF/WOFF font you provide.

`text2d()` creates real geometry. For temporary viewport annotations, prefer `Viewport.label()` so the text stays off the geometry and OCCT compile paths. Do not use either form of text to make unclear production geometry readable; model the physical artifact clearly instead.

Alignment reference table:

| `align`    | `baseline`   | Origin                              |
|------------|--------------|-------------------------------------|
| `'left'`   | `'baseline'` | Bottom-left of first char (default) |
| `'center'` | `'center'`   | Dead center of text block           |
| `'right'`  | `'top'`      | Top-right corner                    |

```ts
// Extruded nameplate
text2d('FORGE CAD', { size: 8 }).extrude(1.2);

// Centered label on the XY plane
text2d('V 2.0', { size: 6, align: 'center', baseline: 'center' });

// Engraved text cut into the top face of a box
const label = text2d('REV A', { size: 5, align: 'center', baseline: 'center' });
plate.subtract(label.onFace(plate, 'top', { protrude: -0.5 }).extrude(1));

// Custom TTF font
text2d('Hello', { size: 10, font: '/path/to/Arial.ttf' }).extrude(1);

// Pre-loaded font for reuse
const font = loadFont('/path/to/Arial Bold.ttf');
text2d('Title', { size: 12, font }).extrude(1.5);
```

```ts
text2d(content: string, options?: TextOptions): Sketch
```

**`TextOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `size?` | `number` | Cap height of the text in model units. All other dimensions (stroke weight, spacing) scale proportionally. |
| `letterSpacing?` | `number` | Extra space between characters in model units. Negative values tighten the tracking. |
| `align?` | `"left" \| "center" \| "right"` | Horizontal alignment relative to x = 0. - `'left'` — left edge at x = 0 (default) - `'center'` — centred on x = 0 - `'right'` — right edge at x = 0 |
| `baseline?` | `"baseline" \| "center" \| "top"` | Vertical alignment relative to y = 0. - `'baseline'` — y = 0 is the text baseline (bottom of capital letters) - `'center'` — y = 0 is the vertical midpoint of the cap height - `'top'` — y = 0 is the top of capital letters |
| `font?` | `string \| opentype.Font` | Font to use for text rendering. - `'sans-serif'` or `'inter'` — bundled Inter font (works everywhere, including browser) - **file path** — path to a TTF, OTF, or WOFF font file (CLI/Node only) - **Font object** — a previously loaded opentype.js Font (from `loadFont()`) - **omitted** — uses the bundled Inter font (same as `'sans-serif'`) |
| `flattenTolerance?` | `number` | Bezier flattening tolerance in model units. Smaller = more polygon segments = smoother curves. |

#### `textWidth()` — Measure the rendered advance width of a string without creating any geometry.

Uses the same font metrics as `text2d()`. Useful for computing layout dimensions before building the actual sketch — e.g. sizing a plate to fit a label.

```ts
const w = textWidth('SERIAL: 001', { size: 6 });
const plate = box(w + 10, 12, 2);
```

```ts
textWidth(content: string, options?: Pick<TextOptions, "size" | "letterSpacing" | "font">): number
```

#### `box()` — Create a rectangular box. Centered on XY, base at Z=0.

Extents:

- X: `[-width/2, width/2]`
- Y: `[-depth/2, depth/2]`
- Z: `[0, height]`

For named faces, build from a labeled sketch: `rect(width, depth).labelEdges('s', 'e', 'n', 'w').extrude(height, { labels: { start: 'bottom', end: 'top' } })`.

```ts
box(width: number, depth: number, height: number): Shape
```

#### `cylinder()` — Create a cylinder or cone with named faces and edges. Centered on XY, base at Z=0.

Extents:

- X/Y: centered at the origin
- Z: `[0, height]`

`radiusTop` defaults to `radius`. Set `radiusTop` smaller to taper the side, or `0` for a pointy cone. Use `segments` to create regular prisms (for example `6` for a hexagonal prism).

Named faces: `top`, `bottom`, `side` Named edges: `top-rim`, `bottom-rim`

```ts
cylinder(height: number, radius: number, radiusTop?: number, segments?: number): Shape
```

#### `sphere()` — Create a sphere centered at the origin.

Extents:

- X: `[-radius, radius]`
- Y: `[-radius, radius]`
- Z: `[-radius, radius]`

Use `segments` for lower-poly approximations.

```ts
sphere(radius: number, segments?: number): Shape
```

#### `torus()` — Create a torus (donut shape) lying in the XY plane. Centered on all axes.

Extents:

- X: `[-(majorRadius + minorRadius), +(majorRadius + minorRadius)]`
- Y: `[-(majorRadius + minorRadius), +(majorRadius + minorRadius)]`
- Z: `[-minorRadius, minorRadius]`

The origin is the center of the ring.

```ts
torus(majorRadius: number, minorRadius: number, segments?: number): Shape
```

---

## C2: Boolean Combination

Combine same-dimension geometry using CSG set operations.

#### `difference2d()` — Subtract one or more 2D sketches from a base sketch.

The first sketch is the base; all subsequent sketches are subtracted from it. Accepts individual sketches or arrays: `difference2d(base, c1, c2)` or `difference2d([base, c1, c2])`. Uses Manifold's batch operation — faster than chaining `.subtract()` one by one.

```ts
const donut = difference2d(circle2d(50), circle2d(30));
```

```ts
difference2d(...inputs: SketchOperandInput[]): Sketch
```

#### `intersection2d()` — Keep only the area where all input sketches overlap (intersection boolean).

Accepts individual sketches or arrays: `intersection2d(a, b)` or `intersection2d([a, b, c])`. Uses Manifold's batch operation — faster than chaining `.intersect()` one by one.

```ts
const lens = intersection2d(circle2d(30).translate(-10, 0), circle2d(30).translate(10, 0));
```

```ts
intersection2d(...inputs: SketchOperandInput[]): Sketch
```

#### `union2d()` — Combine 2D sketches into a single profile using an additive boolean union.

Accepts individual sketches or arrays: `union2d(a, b, c)` or `union2d([a, b, c])`. Uses Manifold's batch operation — faster than chaining `.add()` one by one when combining many sketches.

```ts
const cross = union2d(rect(60, 10), rect(10, 60));
```

```ts
union2d(...inputs: SketchOperandInput[]): Sketch
```

#### `union()` — Combine shapes into a single solid (additive boolean).

Accepts individual shapes, or an array of shapes. `union()` returns one solid, so only the first operand's color is preserved in the result. Use `group()` when you want separate child colors or identities.

```ts
union(...inputs: ShapeOperandInput[]): Shape
```

#### `difference()` — Subtract shapes from a base shape (subtractive boolean).

The first shape is the base; all subsequent shapes are subtracted from it. Accepts individual shapes, or an array of shapes.

```ts
difference(...inputs: ShapeOperandInput[]): Shape
```

#### `intersection()` — Keep only the overlapping volume of the input shapes (intersection boolean).

Requires at least two shapes. Accepts individual shapes, or an array.

```ts
intersection(...inputs: ShapeOperandInput[]): Shape
```

---

## C3: Rigid Transform

Reposition or reorient geometry without changing its shape.

#### `degrees()` — Identity function that returns degrees unchanged.

Use for clarity when the unit of an angle value would otherwise be ambiguous — e.g. `param("Angle", degrees(45))`.

```ts
degrees(deg: number): number
```

#### `radians()` — Convert radians to degrees.

ForgeCAD's public API uses degrees throughout. Use this when you have a radian value (e.g. from `Math.atan2`) that you want to express in degrees.

```ts
radians(rad: number): number
```

#### `composeChain()` — Compose transforms in chain order. Equivalent to Transform.identity().mul(a).mul(b).mul(c)...

```ts
composeChain(...steps: TransformInput[]): Transform
```

---

## C4: Dimensional Promotion

Convert a 2D profile into a 3D solid (extrude, revolve, loft, sweep).

#### `Curve.Blend()` — Create an exact G1 blend curve between two directed endpoints.

The returned curve is a cubic non-rational `NurbsCurve3D`: ForgeCAD converts the endpoint positions and tangents into Bezier control points, so the curve can feed `sweep` and exact surface boundaries through the existing `nurbs` IR rather than a sampled polyline.

```js
const rail = Curve.Blend(
  { point: [0, 0, 0], tangent: [1, 0, 0], weight: 0.8 },
  { point: [40, 20, 8], tangent: [0, 1, 0], weight: 0.8 },
);
const tube = sweep(circle2d(2), rail);
```

```ts
Curve.Blend(start: CurveBlendEndpoint, end: CurveBlendEndpoint): NurbsCurve3D
```

**`CurveBlendEndpoint`**
- `point: Vec3` — Endpoint position.
- `tangent: Vec3` — Tangent direction at this endpoint. Magnitude is ignored.
- `weight?: number` — Tangent reach relative to the endpoint chord length. Default 1.

#### `Curve.BlendG2()` — Create an exact G2 blend curve between two directed endpoints.

This is the curvature-aware companion to `Curve.Blend()`. It returns a degree-5 non-rational `NurbsCurve3D` that matches endpoint position, tangent direction, and optional curvature/second-derivative vectors.

```js
const rail = Curve.BlendG2(
  { point: [0, 0, 0], tangent: [1, 0, 0], curvature: [0, 0.02, 0] },
  { point: [50, 20, 0], tangent: [0, 1, 0], curvature: [-0.02, 0, 0] },
);
```

```ts
Curve.BlendG2(start: CurveBlendG2Endpoint, end: CurveBlendG2Endpoint): NurbsCurve3D
```


**`CurveBlendG2Endpoint`** extends CurveBlendEndpoint
- `curvature?: Vec3` — Optional endpoint curvature/second-derivative vector. Default is zero.

#### `Curve.Arc()` — Create an exact circular 3D arc from start, end, and start tangent.

The returned curve is a rational quadratic `NurbsCurve3D`, split into stable spans when needed, so it can feed `sweep` without sampling the authoring intent away.

```js
const rail = Curve.Arc({
  start: [40, 0, 0],
  end: [0, 40, 0],
  tangent: [0, 1, 0],
});
const tube = sweep(circle2d(2), rail);
```

```ts
Curve.Arc(options: CurveArcOptions): NurbsCurve3D
```

**`CurveArcOptions`**
- `start: Vec3` — Arc start point.
- `end: Vec3` — Arc end point.
- `tangent: Vec3` — Tangent direction at the start point. Magnitude is ignored.

#### `Curve.Line()` — Create an exact straight 3D NURBS line segment.

```js
const rail = Curve.Line([0, 0, 0], [80, 0, 15]);
const rib = sweep(circle2d(2), rail);
```

```ts
Curve.Line(start: Vec3, end: Vec3): NurbsCurve3D
```

#### `Curve.Polyline()` — Create a polyline path as cloned 3D points.

Polylines are exact as route/path input to `sweep`. Use `Curve.Route` when the centerline needs bend and endpoint-frame metadata.

```ts
Curve.Polyline(points: Vec3[]): Vec3[]
```

#### `Curve.Spline()` — Create a smooth Catmull-Rom spline path.

This is a smooth sampled curve object. Use `Curve.Nurbs` when the path must preserve exact control-point and knot data.

```ts
Curve.Spline(points: Vec3[], options?: Spline3DOptions): Curve3D
```

**`Spline3DOptions`**
- `closed?: boolean` — Closed loop (default false).
- `tension?: number` — Catmull-Rom tension in [0, 1]. 0 = very round, 1 = linear-ish. Default 0.5.

#### `Curve.Nurbs()` — Create an exact NURBS 3D curve from control points, weights, knots, and degree.

```js
const rail = Curve.Nurbs([[0, 0, 0], [30, 4, 12], [60, -4, 12], [90, 0, 0]]);
const tube = sweep(circle2d(2), rail);
```

```ts
Curve.Nurbs(points: Vec3[], options?: NurbsCurve3DOptions): NurbsCurve3D
```

**`NurbsCurve3DOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `degree?` | `number` | Polynomial degree (default 3 = cubic). Must be ≥ 1. |
| `weights?` | `number[]` | Rational weights, one per control point (default: all 1.0 = non-rational). |
| `knots?` | `number[]` | Knot vector (default: uniform clamped). Must have length = controlPoints.length + degree + 1. |
| `closed?` | `boolean` | Whether the curve is closed/periodic (default false). |

#### `Curve.Fit()` — Fit a non-rational NURBS curve that interpolates every input point.

This is global B-spline interpolation, not approximate curve reduction: ForgeCAD computes chord-length parameters, averaged clamped knots, solves the control points, then verifies the interpolation residual against `tolerance`.

```js
const rail = Curve.Fit(
  [[0, 0, 0], [20, 8, 12], [50, -4, 18], [80, 0, 0]],
  { degree: 3, tolerance: 0.001 },
);
const tube = sweep(circle2d(2), rail);
```

```ts
Curve.Fit(points: Vec3[], options?: CurveFitOptions): NurbsCurve3D
```

**`CurveFitOptions`**
- `degree?: number` — Polynomial degree. Default is cubic, reduced automatically for short point lists.
- `tolerance?: number` — Maximum allowed interpolation residual in model units. Default 1e-7.

#### `Curve.Trim()` — Extract an exact curve segment from normalized parameter `start` to `end`.

`NurbsCurve3D` inputs are trimmed with exact knot insertion/subdomain extraction. Polyline point arrays are trimmed by arclength over their exact line segments. Sampled `Curve3D` splines are rejected until ForgeCAD has a tolerance-controlled rebuild path.

```ts
Curve.Trim<T extends CurveTrimInput>(curve: T, start: number, end: number): CurveTrimOutput<T>
```

#### `Curve.Reverse()` — Reverse an exact curve without changing its geometry.

`NurbsCurve3D` inputs reverse control points, weights, and knots. Polyline point arrays are cloned and reversed. Sampled `Curve3D` splines are rejected until ForgeCAD has a tolerance-controlled rebuild path.

```ts
Curve.Reverse<T extends CurveTrimInput>(curve: T): CurveTrimOutput<T>
```

#### `Curve.Route()` — Build analytic 3D line/arc routes for sweeps.

`Curve.Route.fromPolyline()` is the canonical route API. It returns a `Route3D` value object, preserving exact route segments, named port frames, and the lowerable `route3d` sweep compile plan.

```js
const route = Curve.Route.fromPolyline(
  [[0, 0, 0], [0, 0, 50], [40, 0, 50]],
  { cornerRadius: 12, startPort: 'inlet', endPort: 'outlet' },
);
const tube = sweep(circle2d(4), route);
```

```ts
Curve.Route: typeof Route3D
```

#### `Curve.Helix()` — Build helical paths and swept coils.

`Curve.Helix` is the canonical namespace for helical paths and coils. It uses the same sweep-based lowering as other curve paths.

```js
const guide = Curve.Helix.path({ radius: 20, pitch: 6, turns: 4 });
const spring = Curve.Helix.coil({ radius: 20, pitch: 6, turns: 4, wireRadius: 1 });
```

```ts
Curve.Helix: { path(options: HelixOptions): CurveHelixPath; coil: CurveHelixCoil; }
```

**`HelixOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `radius` | `number` | Radius from the central Z axis to the helix centerline. |
| `pitch?` | `number` | Axial distance per full turn. Provide any two of `pitch`, `turns`, and `height`. |
| `turns?` | `number` | Number of full rotations around the axis. Provide any two of `pitch`, `turns`, and `height`. |
| `height?` | `number` | Total height along +Z. Provide any two of `pitch`, `turns`, and `height`. |
| `startAngle?` | `number` | Start angle in degrees. Default 0 starts on +X. |
| `clockwise?` | `boolean` | Reverse winding direction when viewed from +Z. |
| `samplesPerTurn?` | `number` | Point samples per turn for the metadata path. Default 32. |


`CurveHelixPath`: `{ radius: number, pitch: number, turns: number, height: number, startAngle: number, clockwise: boolean }`

#### `Loft.station()` — Create a loft station from a 2D profile and an axis position.

```ts
Loft.station(profile: Sketch, position: number): LoftStation
```

`LoftStation`: `{ profile: Sketch, position: number }`

#### `Loft.leftRail()` — Create a guide rail that constrains the section-local negative-X side.

```ts
Loft.leftRail(path: LoftGuideRailPath): LoftGuideRail
```

`LoftGuideRail`: `{ side: LoftGuideRailSide, path: LoftGuideRailPath }`

#### `Loft.rightRail()` — Create a guide rail that constrains the section-local positive-X side.

```ts
Loft.rightRail(path: LoftGuideRailPath): LoftGuideRail
```

#### `Loft.frontRail()` — Create a guide rail that constrains the section-local positive-Y side.

```ts
Loft.frontRail(path: LoftGuideRailPath): LoftGuideRail
```

#### `Loft.backRail()` — Create a guide rail that constrains the section-local negative-Y side.

```ts
Loft.backRail(path: LoftGuideRailPath): LoftGuideRail
```

#### `Loft.centerRail()` — Create a guide rail that moves section centers along the loft.

```ts
Loft.centerRail(path: LoftGuideRailPath): LoftGuideRail
```

#### `Loft.pathOnXz()` — Place a 2D guide path onto the XZ plane.

The path's first coordinate becomes X and its second coordinate becomes Z. Use this for left/right silhouette rails authored with `path()` or `constrainedSketch()`.

```ts
Loft.pathOnXz(path: LoftPath2D, y?: number): Vec3[]
```

#### `Loft.pathOnYz()` — Place a 2D guide path onto the YZ plane.

The path's first coordinate becomes Y and its second coordinate becomes Z. Use this for front/back crown rails authored with `path()` or `constrainedSketch()`.

```ts
Loft.pathOnYz(path: LoftPath2D, x?: number): Vec3[]
```

#### `Loft.pathOnXy()` — Place a 2D guide path onto the XY plane.

The path's first coordinate becomes X and its second coordinate becomes Y. Use this when lofting along X or Y and a rail lives in a horizontal sketch plane.

```ts
Loft.pathOnXy(path: LoftPath2D, z?: number): Vec3[]
```

#### `Loft.withGuideRails()` — Loft through profile stations while forcing generated sections to follow guide rails.

Stations define the cross-section family. Guide rails define the side or center paths the loft must pass through. With opposite side rails, the section is scaled to touch both rails. With one side rail, the section keeps its interpolated size unless a center rail is also present.

```ts
Loft.withGuideRails(stations: LoftStation[], rails: LoftGuideRail[], options?: LoftWithGuideRailsOptions): Shape
```

**`LoftOptions`**
- `edgeLength?: number` — Marching-grid edge length for level-set meshing. Smaller = finer.
- `boundsPadding?: number` — Optional extra bounds padding.

**`LoftWithGuideRailsOptions`** extends LoftOptions
- `axis?: LoftAxis` — Primary station axis. Default Z.
- `samples?: number` — Number of generated loft stations including ends. Default scales with station count.
- `railSamples?: number` — Number of points sampled from curve-backed rails before axis interpolation. Default 64.

#### `Analysis.EdgeContinuity()`

```ts
Analysis.EdgeContinuity(shape: Shape, options?: EdgeContinuityThresholds): EdgeContinuityReport
```

**`EdgeContinuityThresholds`**: `continuity?: SurfaceContinuity`, `samples?: number`, `positionTolerance?: number`, `tangentToleranceDeg?: number`, `curvatureTolerance?: number`

**`EdgeContinuityReport`**: `requested: SurfaceContinuity`, `passed: boolean`, `sampledEdges: number`, `edges: EdgeContinuityEdgeReport[]`, `worst: { continuity: SurfaceContinuity; maxPositionalGap: number; maxTangentAngleDeg: number; maxCurvatureGap: number; }`

**`EdgeContinuityEdgeReport`**: `edgeIndex: number`, `continuity: SurfaceContinuity`, `maxPositionalGap: number`, `maxTangentAngleDeg: number`, `maxCurvatureGap: number`

#### `Analysis.SurfaceContinuity()`

```ts
Analysis.SurfaceContinuity(shape: Shape, options?: EdgeContinuityThresholds): EdgeContinuityReport
```

#### `Analysis.CurvatureComb()`

```ts
Analysis.CurvatureComb(input: NurbsCurve3D | EdgeRef, options?: { samples?: number; }): CurvatureSample[]
```

**`EdgeRef`**

| Option | Type | Description |
|--------|------|-------------|
| `start` | `[ number, number, number ]` | Start point |
| `end` | `[ number, number, number ]` | End point |
| `query?` | `EdgeQueryRef` | Compiler-owned edge query when available. |
| `curve?` | `EdgeCurve` | Exact or parametric curve family when the backend/source can identify one. |
| `faceName?` | `string` | Owning face name when the edge is associated with one face in a larger topology. |
| `name` | | — |

`CurvatureSample`: `{ t: number, curvature: number, point: Vec3 }`

#### `Analysis.SurfaceHealth()`

```ts
Analysis.SurfaceHealth(shape: Shape, options?: { tinyEdgeThreshold?: number; sliverThreshold?: number; }): SurfaceHealthReport
```

**`SurfaceHealthReport`**: `tinyEdges: Array<{ index: number; length: number; }>`, `sliverFaces: Array<{ index: number; area: number; sliverScore: number; }>`, `valid: boolean`

#### `Analysis.BRepValidity()` — Validate B-rep/shell/solid structure and return closedness, manifoldness, orientation, and issue diagnostics.

```ts
Analysis.BRepValidity(shape: Shape, options?: BRepValidityOptions): BRepValidityReport
```

`BRepValidityOptions`: `{ tolerance?: number, requireClosed?: boolean, requireManifold?: boolean, requireSolid?: boolean, minVolume?: number }`

**`BRepValidityReport`**: `ok: boolean`, `valid: boolean`, `closed: boolean`, `manifold: boolean`, `solid: boolean`, `oriented: boolean`, `volume: number`, `edgeCount: number`, `faceCount: number`, `openEdges: number`, `nonManifoldEdges: number`, `degenerateFaces: number`, `errors: BRepValidityIssue[]`

**`BRepValidityIssue`**: `kind: BRepValidityIssueKind`, `message: string`, `index?: number`, `faceCount?: number`, `length?: number`, `volume?: number`, `area?: number`

#### `Blend.Edge()`

```ts
Blend.Edge(options: BlendEdgeOptions): Shape
```

`BlendEdgeOptions`: `{ shape?: Shape, edges: EdgeRef[], radius: number, continuity?: SurfaceContinuity, segments?: number }`

#### `Blend.Surface()`

```ts
Blend.Surface(options: BlendSurfaceOptions): Shape
```

`SurfaceCommonOptions`: `{ resolution?: number, approximate?: boolean }`

**`SurfaceFillInput`** extends SurfaceCommonOptions: `boundaries: Array<{ name: string; curve: ExactCurveInput; }>`, `match?: Record<string, SurfaceMatchConstraintInput>`, `style?: SurfaceFillStyle`

`SurfaceMatchConstraintInput`: `{ target: EdgeRef, continuity?: SurfaceContinuity }`

#### `Surface.Plane()` — Create a finite analytic plane sheet that can be trimmed, sewn, thickened, or used as a low-level face.

```ts
Surface.Plane(options: SurfacePlaneOptions): Shape
```

**`SurfaceAnalyticCommonOptions`**
- `resolution?: number` — Tessellation/sample hint for non-OCCT previews and diagnostics.
- `trim?: SurfaceTrimOptions` — Optional normalized UV trims in this surface's bounded parameter domain.

**`SurfaceTrimOptions`**
- `outer: SurfaceTrimLoopInput` — Outer trim loop in normalized post-domain UV space.
- `holes?: SurfaceTrimLoopInput[]` — Optional hole loops in normalized post-domain UV space.

**`SurfacePlaneOptions`** extends SurfaceAnalyticCommonOptions

| Option | Type | Description |
|--------|------|-------------|
| `origin?` | `Vec3` | Center of the finite plane patch. Defaults to the origin. |
| `normal?` | `Vec3` | Plane normal. Defaults to +Z. |
| `xAxis?` | `Vec3` | Plane-local +U direction. Defaults to a stable perpendicular axis. |
| `width` | `number` | Physical width along the +U axis. |
| `height` | `number` | Physical height along the +V axis. |

#### `Surface.Cylinder()` — Create a finite analytic cylindrical sheet, optionally bounded by start/end angles.

```ts
Surface.Cylinder(options: SurfaceCylinderOptions): Shape
```


**`SurfaceCylinderOptions`** extends SurfaceAnalyticCommonOptions

| Option | Type | Description |
|--------|------|-------------|
| `origin?` | `Vec3` | Center of the cylinder base. Defaults to the origin. |
| `axis?` | `Vec3` | Cylinder axis from base toward top. Defaults to +Z. |
| `xAxis?` | `Vec3` | Direction for angle 0 around the axis. Defaults to a stable perpendicular axis. |
| `radius`, `height`, `startDeg?`, `endDeg?` | | — |

#### `Surface.Cone()` — Create a finite analytic conical or frustum sheet, optionally bounded by start/end angles.

```ts
Surface.Cone(options: SurfaceConeOptions): Shape
```


**`SurfaceConeOptions`** extends SurfaceAnalyticCommonOptions

| Option | Type | Description |
|--------|------|-------------|
| `origin?` | `Vec3` | Center of the cone/frustum base. Defaults to the origin. |
| `axis?` | `Vec3` | Cone axis from base toward top. Defaults to +Z. |
| `xAxis?` | `Vec3` | Direction for angle 0 around the axis. Defaults to a stable perpendicular axis. |
| `radiusBottom`, `radiusTop`, `height`, `startDeg?`, `endDeg?` | | — |

#### `Surface.Sphere()` — Create a finite analytic spherical sheet bounded by longitude and latitude ranges.

```ts
Surface.Sphere(options: SurfaceSphereOptions): Shape
```


**`SurfaceSphereOptions`** extends SurfaceAnalyticCommonOptions

| Option | Type | Description |
|--------|------|-------------|
| `axis?` | `Vec3` | Polar axis. Defaults to +Z. |
| `xAxis?` | `Vec3` | Direction for longitude 0 around the axis. Defaults to a stable perpendicular axis. |
| `center?`, `radius`, `startDeg?`, `endDeg?`, `minLatitudeDeg?`, `maxLatitudeDeg?` | | — |

#### `Surface.Torus()` — Create a finite analytic torus sheet bounded by major and tube angle ranges.

```ts
Surface.Torus(options: SurfaceTorusOptions): Shape
```


**`SurfaceTorusOptions`** extends SurfaceAnalyticCommonOptions

| Option | Type | Description |
|--------|------|-------------|
| `axis?` | `Vec3` | Axis through the torus hole. Defaults to +Z. |
| `xAxis?` | `Vec3` | Direction for major angle 0 around the axis. Defaults to a stable perpendicular axis. |
| `center?`, `majorRadius`, `minorRadius`, `startDeg?`, `endDeg?`, `tubeStartDeg?`, `tubeEndDeg?` | | — |

#### `Surface.Nurbs()`

```ts
Surface.Nurbs(controlGrid: Vec3[][], options?: NurbsSurfaceOptions): Shape
```

**`NurbsSurfaceOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `degreeU?` | `number` | Degree in U direction (default 3). |
| `degreeV?` | `number` | Degree in V direction (default 3). |
| `weights?` | `number[][]` | Weights grid — same dimensions as controlGrid (default: all 1.0). |
| `knotsU?` | `number[]` | Knot vector in U direction (default: uniform clamped). |
| `knotsV?` | `number[]` | Knot vector in V direction (default: uniform clamped). |
| `thickness?` | `number` | Sheet thickness — if > 0, thickens the surface into a solid (default 0 = surface only). |
| `resolution?` | `number` | Tessellation resolution — points per direction (default 32). |
| `domain?` | `SurfaceDomainOptions` | Optional rectangular parameter domain in normalized [0, 1] U/V space. |
| `trim?` | `SurfaceTrimOptions` | Optional polygonal or NURBS-curve UV trim loops. Truck and OCCT support open trimmed surfaces; Manifold supports sampled thickened trimmed solids. |
| `tessellation?` | `SurfaceTessellationOptions` | Optional Truck kernel tessellation controls for render mesh generation. |
| `approximate?` | `boolean` | Explicit opt-in for sampled approximation paths on non-exact backends. |

**`SurfaceDomainOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `uMin?` | `number` | Lower U parameter bound in normalized surface space (default 0). |
| `uMax?` | `number` | Upper U parameter bound in normalized surface space (default 1). |
| `vMin?` | `number` | Lower V parameter bound in normalized surface space (default 0). |
| `vMax?` | `number` | Upper V parameter bound in normalized surface space (default 1). |

**`SurfaceTessellationOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `mode?` | `"uniform" \| "adaptive"` | `uniform` uses resolution directly; `adaptive` lets the Truck kernel refine open sheets from chord error. |
| `tolerance?` | `number` | Target chord-error tolerance in model units for adaptive Truck tessellation. |
| `minResolution?` | `number` | Minimum adaptive samples per direction. |
| `maxResolution?` | `number` | Maximum adaptive samples per direction. Defaults to `resolution` when omitted. |

#### `Surface.Ruled()`

```ts
Surface.Ruled(curveA: ExactCurveInput, curveB: ExactCurveInput, options?: SurfaceCommonOptions): Shape
```

#### `Surface.Patch()`

```ts
Surface.Patch(curves: { bottom: ExactCurveInput; top: ExactCurveInput; left: ExactCurveInput; right: ExactCurveInput; }, options?: SurfacePatchOptions): Shape
```

**`SurfacePatchOptions`**
- `resolution?: number` — Number of samples along each direction. Default 24.
- `thickness?: number` — Thickness of the generated solid. Default 0 for an open exact sheet.
- `approximate?: boolean` — Allow explicit approximation for non-exact curve inputs such as Curve3D samples.

#### `Surface.Boundary()`

```ts
Surface.Boundary(input: SurfaceBoundaryInput): Shape
```


**`SurfaceBoundaryInput`** extends SurfaceCommonOptions: `u: [ ExactCurveInput, ExactCurveInput ]`, `v: [ ExactCurveInput, ExactCurveInput ]`, `match?: Partial<Record<"u0" | "u1" | "v0" | "v1", SurfaceMatchConstraintInput>>`, `style?: SurfaceFillStyle`

#### `Surface.Fill()`

```ts
Surface.Fill(input: SurfaceFillInput): Shape
```

#### `Surface.Sew()`

```ts
Surface.Sew(shapes: Shape[], options?: { tolerance?: number; }): Shape
```

#### `Surface.Solid()` — Sew surface faces or consume an existing sewn shell and make a solid B-rep.

```ts
Surface.Solid(input: Shape | Shape[], options?: SurfaceSolidOptions): Shape
```

`SurfaceSolidOptions`: `{ tolerance?: number, validate?: boolean }`

#### `Surface.Extend()`

```ts
Surface.Extend(shape: Shape, options: SurfaceExtendOptions): Shape
```

`SurfaceExtendOptions`: `{ edge: "u0" | "u1" | "v0" | "v1", length: number, continuity?: SurfaceContinuity }`

#### `Surface.Trim()`

```ts
Surface.Trim(shape: Shape, tool: Shape | SurfacePlaneOp): Shape
```

`SurfacePlaneOp`: `{ normal: Vec3, offset?: number }`

#### `Surface.Split()`

```ts
Surface.Split(shape: Shape, tool: Shape | SurfacePlaneOp): [ Shape, Shape ]
```

#### `Surface.Match()`

```ts
Surface.Match(shape: Shape, options: { edge: "u0" | "u1" | "v0" | "v1"; target: EdgeRef; continuity?: SurfaceContinuity; }): Shape
```

#### `Surface.MatchEdge()`

```ts
Surface.MatchEdge(shape: Shape, options: { edge: "u0" | "u1" | "v0" | "v1"; target: EdgeRef; continuity?: SurfaceContinuity; }): Shape
```

#### `nurbsSurface()` — Create a NURBS surface from a grid of control points.

The control grid is indexed as `controlGrid[u][v]` — each row is a curve in the V direction, and columns trace curves in the U direction.

With default options, creates a bicubic non-rational B-spline surface with uniform clamped knots.

```js
// Simple 4×4 control grid — a gently curved surface
const grid = [
  [[0,0,0], [10,0,2], [20,0,2], [30,0,0]],
  [[0,10,1], [10,10,5], [20,10,5], [30,10,1]],
  [[0,20,1], [10,20,5], [20,20,5], [30,20,1]],
  [[0,30,0], [10,30,2], [20,30,2], [30,30,0]],
];
const surface = nurbsSurface(grid, { thickness: 2 });
```

```ts
nurbsSurface(controlGrid: Vec3[][], options?: NurbsSurfaceOptions): Shape
```

#### `loft()` — Loft between multiple sketches along Z stations.

Profiles can differ in topology and vertex count: interpolation is done on signed-distance fields and meshed with level-set extraction. Heights must be strictly increasing. Compatible loft stacks can also stay on the maintained export-backend path.

Performance note: loft is significantly heavier than primitive/extrude/revolve. If the part is axis-symmetric (bottles, vases, knobs), prefer revolve().

```ts
loft(profiles: Sketch[], heights: number[], options?: LoftOptions): Shape
```

#### `surfacePatch()` — Create a smooth surface patch from 4 boundary curves (Coons patch).

The four curves form the boundary of a quadrilateral patch:

- bottom: u=0..1 at v=0 (from corner00 to corner10)
- top: u=0..1 at v=1 (from corner01 to corner11)
- left: v=0..1 at u=0 (from corner00 to corner01)
- right: v=0..1 at u=1 (from corner10 to corner11)

The interior is filled using bilinear Coons patch interpolation: P(u,v) = Lc(u,v) + Ld(u,v) - B(u,v)

The result is a thin solid created by offsetting the surface mesh along its normals by the specified thickness.

Note: curves should meet at corners. Small gaps are tolerated.

```ts
surfacePatch(curves: { ... }, options?: SurfacePatchOptions): Shape
```

#### `sweep()`

```ts
sweep(profile: Sketch, path: SweepPathInput, options?: SweepOptions): Shape
```

**`SweepOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `samples?` | `number` | Number of samples when path is a Curve3D. Default 48. |
| `edgeLength?` | `number` | Marching-grid edge length for level-set meshing. Smaller = finer. |
| `boundsPadding?` | `number` | Optional extra bounds padding. |
| `up?` | `Vec3` | Preferred "up" vector for local profile frame. Auto fallback is used near parallel segments. |

#### `variableSweep()` — Sweep a variable cross-section along a 3D spine curve.

Unlike sweep(), which uses a single constant profile, variableSweep() interpolates between multiple profiles at different stations along the spine. This enables organic shapes like tapering tubes, bone-like structures, and sculptural forms.

Each section specifies a t parameter (0 = start, 1 = end of spine) and a 2D profile sketch. The SDF-based level-set mesher smoothly blends between profiles at intermediate positions.

Performance note: like sweep(), this uses level-set meshing internally.

```ts
variableSweep(spine: SweepPathInput, sections: VariableSweepSection[], options?: VariableSweepOptions): Shape
```

**`VariableSweepSection`**
- `t: number` — Parameter along the spine (0 = start, 1 = end).
- `profile: Sketch` — Cross-section profile at this station.

**`VariableSweepOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `samples?` | `number` | Number of samples when spine is a Curve3D. Default 48. |
| `edgeLength?` | `number` | Marching-grid edge length for level-set meshing. Smaller = finer. |
| `boundsPadding?` | `number` | Optional extra bounds padding. |
| `up?` | `Vec3` | Preferred "up" vector for local profile frame. Auto fallback is used near parallel segments. |

---

## C5: Topology Query

Select or inspect named faces and edges on a shape.

#### `coalesceEdges()` — Merge collinear edge segments into longer logical edges.

Tessellation often splits one geometric edge into multiple short segments. `coalesceEdges` groups adjacent collinear segments and merges each group into a single `EdgeSegment` spanning the full extent. This is usually needed before passing edges to `fillet()` or `chamfer()` on non-primitive shapes.

The `tolerance` controls the maximum perpendicular distance from collinearity before two segments are considered non-collinear. Default: `0.01`.

```ts
const topEdges = selectEdges(part, { atZ: 20 });
for (const edge of coalesceEdges(topEdges)) {
  result = fillet(result, 2, edge);
}
```

```ts
coalesceEdges(segments: EdgeSegment[], tolerance?: number): EdgeSegment[]
```

**`EdgeSegment`**

| Option | Type | Description |
|--------|------|-------------|
| `index` | `number` | Stable index within the extraction (deterministic for a given mesh). |
| `direction` | `Vec3` | Normalized direction from start → end. |
| `dihedralAngle` | `number` | Dihedral angle in degrees (0 = coplanar, 180 = knife edge). |
| `convex` | `boolean` | true = outside corner (convex), false = inside corner (concave). |
| `normalA` | `Vec3` | Normal of first adjacent face. |
| `normalB` | `Vec3` | Normal of second adjacent face (same as normalA for boundary edges). |
| `boundary` | `boolean` | true if this is a boundary (unmatched) edge — unusual for closed solids. |
| `start`, `end`, `midpoint`, `length` | | — |

#### `selectEdge()` — Select the single best-matching edge from a shape.

When `near` is specified, returns the edge whose midpoint is closest to that point. Otherwise returns the first matching edge in mesh order. Throws if no edges match the query — useful as a guard when you expect exactly one result.

```ts
// Chamfer one specific edge near a known point
const bottomEdge = selectEdge(part, { near: [25, 0, 0], atZ: 0 });
result = chamfer(result, 1.5, bottomEdge);
```

```ts
selectEdge(shape: Shape, query?: EdgeQuery): EdgeSegment
```

**`EdgeQuery`**

| Option | Type | Description |
|--------|------|-------------|
| `near?` | `Vec3` | Sort by proximity to this point (closest first). When used with `selectEdge`, picks the closest match. |
| `parallel?` | `Vec3` | Filter: edge direction approximately parallel to this vector. |
| `perpendicular?` | `Vec3` | Filter: edge direction approximately perpendicular to this vector. |
| `convex?` | `boolean` | Filter: only convex (outside corner) edges. |
| `concave?` | `boolean` | Filter: only concave (inside corner) edges. |
| `minAngle?` | `number` | Filter: minimum dihedral angle in degrees. |
| `maxAngle?` | `number` | Filter: maximum dihedral angle in degrees. |
| `minLength?` | `number` | Filter: minimum edge length. |
| `maxLength?` | `number` | Filter: maximum edge length. |
| `within?` | `BoundingRegion` | Filter: edge midpoint must be within this bounding region. |
| `atZ?` | `number` | Shorthand: edge midpoint Z is approximately this value within `tolerance`. |
| `tolerance?` | `number` | Position tolerance for approximate matches. Used by `atZ` and `near`. Default: `1.0`. |
| `angleTolerance?` | `number` | Angular tolerance in degrees for `parallel`/`perpendicular` filters. Default: `10`. |

`BoundingRegion`: `{ xMin?: number, xMax?: number, yMin?: number, yMax?: number, zMin?: number, zMax?: number }`

#### `selectEdges()` — Select all edges from a shape that match the given query.

Uses the active kernel's native topology query when available (Truck), otherwise extracts sharp edges from the mesh (dihedral angle > 1°), applies all filters in the query, and returns the matching `EdgeSegment[]`. When `near` is specified the results are sorted closest-first.

Works on any shape — primitives, booleans, shells, and imported meshes. Use this when tracked topology is unavailable (e.g. after a difference or on imported geometry). For simpler cases, pass an `EdgeQuery` directly to `fillet()` or `chamfer()` instead of calling `selectEdges` separately.

```ts
// Fillet all top edges of a box
const topEdges = selectEdges(part, { atZ: 20, perpendicular: [0, 0, 1] });
let result = part;
for (const edge of coalesceEdges(topEdges)) {
  result = fillet(result, 2, edge);
}
```

```ts
selectEdges(shape: Shape, query?: EdgeQuery): EdgeSegment[]
```

---

## C6: Edge Feature

Modify edges of a solid — fillets, chamfers, draft, offset.

#### `chamfer()` — Apply experimental chamfers (beveled edges) to one or more edges of a shape.

**Experimental**: chamfers are still backend-sensitive. The Manifold backend is known to produce incorrect results for some edge-finish cases, and the OCCT backend can be very slow, especially with broad edge selections. Prefer targeted edge selectors and inspect the result before treating it as production-ready geometry.

Produces a 45° bevel at the specified `size` (distance from edge). Edge selections compile into backend operations; unsupported selections fail as explicit kernel gaps instead of using TypeScript geometry fallbacks.

The `edges` parameter accepts the same options as `fillet()`: inline `EdgeQuery`, pre-selected `EdgeSegment`/`EdgeSegment[]`, or `undefined` (all sharp edges).

```ts
// Chamfer all edges
chamfer(myShape, 1)

// Chamfer only vertical edges
chamfer(myShape, 2, { parallel: [0, 0, 1] })
```

```ts
chamfer(shape: Shape, size: number, edges?: EdgeSelector): Shape
```

#### `draft()` — Apply a draft angle (taper) to vertical faces for mold extraction.

Adds a taper angle to the vertical faces of a solid so that it can be extracted from a mold. The neutral plane is the Z position where the draft angle is zero — faces above and below are tapered symmetrically. Typical values for injection molding are 1–5°.

Truck supports vertical-prism solids with Z-axis pull directions. OCCT uses its native draft operation when available. Manifold throws.

```ts
// Add 3° draft to a box for injection molding
draft(myBox, 3)

// Draft with custom pull direction and neutral plane
draft(myShape, 2, [0, 0, 1], 10)
```

```ts
draft(shape: Shape, angleDeg: number, pullDirection?: [ number, number, number ], neutralPlaneOffset?: number): Shape
```

#### `fillet()` — Apply experimental fillets (rounded edges) to one or more edges of a shape.

**Experimental**: fillets are still backend-sensitive. The Manifold backend is known to produce incorrect results for some edge-finish cases, and the OCCT backend can be very slow, especially with broad edge selections. Prefer targeted edge selectors and inspect the result before treating it as production-ready geometry.

Edge selections compile into backend operations; unsupported selections fail as explicit kernel gaps instead of using TypeScript geometry fallbacks.

The `edges` parameter is flexible:

- Omit to fillet **all** sharp edges
- Pass an `EdgeQuery` for an inline filter (most common)
- Pass an `EdgeSegment` or `EdgeSegment[]` from `selectEdges()` for pre-selected edges

Throws if no edges match the selection, or if `radius` is not a positive finite number.

```ts
// Fillet all edges
fillet(myShape, 2)

// Fillet only top convex edges
fillet(myShape, 1.5, { atZ: 20, convex: true })

// Fillet vertical edges selected beforehand
const edges = selectEdges(myShape, { parallel: [0, 0, 1] })
fillet(myShape, 3, edges)
```

```ts
fillet(shape: Shape, radius: number, edges?: EdgeSelector, segments?: number): Shape
```

#### `offsetSolid()` — Uniformly offset all surfaces of a solid inward or outward.

Unlike `shell()`, which hollows a solid by removing one face, `offsetSolid()` produces a new solid whose every surface is shifted by `thickness`. Positive values grow the shape outward; negative values shrink it inward.

Requires the OCCT backend. Throws on Manifold.

```ts
// Grow a box outward by 1mm on all sides
offsetSolid(myBox, 1)

// Shrink a shape inward by 0.5mm
offsetSolid(myShape, -0.5)
```

```ts
offsetSolid(shape: Shape, thickness: number): Shape
```

#### `chamferTrackedEdge()` — Bevel a tracked vertical solid edge with a 45° chamfer.

Compiler-owned chamfer for tracked vertical edges. Requires a compile-plan-covered target. This is not a general 2D sketch-corner tool; supported subset and quadrant semantics are the same as `filletTrackedEdge()` - see that function for details.

```ts
const base = Rectangle2D.fromDimensions(0, 0, 50, 50).extrude(20);
const chamfered = chamferTrackedEdge(base, base.edge('vert-br'), 3, [-1, -1]);
```

```ts
chamferTrackedEdge(shape: Shape, edge: EdgeRef, size: number, quadrant?: [ number, number ]): Shape
```

**`EdgeRef`**

| Option | Type | Description |
|--------|------|-------------|
| `start` | `[ number, number, number ]` | Start point |
| `end` | `[ number, number, number ]` | End point |
| `query?` | `EdgeQueryRef` | Compiler-owned edge query when available. |
| `curve?` | `EdgeCurve` | Exact or parametric curve family when the backend/source can identify one. |
| `faceName?` | `string` | Owning face name when the edge is associated with one face in a larger topology. |
| `name` | | — |

#### `filletTrackedEdge()` — Round a tracked vertical solid edge with a circular fillet.

Compiler-owned fillet for a narrow tracked-edge subset on solids.

This is **not** a general 2D sketch-corner fillet. It currently works only on tracked vertical edges from `box()` or `Rectangle2D` extrusions (plus rigid transforms and supported preserved descendants of those). Generic sketch extrudes, including `rect(...).extrude(...)`, are outside the supported subset right now.

**Supported edges:**

- Tracked vertical edges from `box()` or `Rectangle2D.extrude()`
- Rigid transforms between tracked source and target
- Untouched sibling tracked vertical edges after earlier `filletTrackedEdge`/`chamferTrackedEdge`

**Not supported:** edges after shell, hole, cut, trim, difference, intersection, generic sketch extrudes, or tapered extrudes.

Canonical quadrants: `vert-bl → [1,-1]`, `vert-br → [-1,-1]`, `vert-tr → [-1,1]`, `vert-tl → [1,1]`

```ts
const base = Rectangle2D.fromDimensions(0, 0, 50, 50).extrude(20);
const filleted = filletTrackedEdge(base, base.edge('vert-br'), 5, [-1, -1]);
```

```ts
filletTrackedEdge(shape: Shape, edge: EdgeRef, radius: number, quadrant?: [ number, number ], segments?: number): Shape
```

#### `filletCorners()` — Create a polygon from points with specific corners rounded to arc fillets.

Each corner spec identifies a vertex by its index in the `points` array and the desired fillet `radius`. Both convex and concave corners are supported.

Constraints:

- Collinear corners cannot be filleted (throws an error)
- Two neighboring fillets whose tangent lengths overlap the same edge will throw
- Radius must be positive and small enough to fit within the adjacent edge lengths

Use `offset(-r).offset(+r)` instead if you want to round **all** convex corners uniformly. Use `filletCorners` when you need selective or mixed sharp/rounded profiles.

```ts
const roof = filletCorners(roofPoints, [
  { index: 3, radius: 19 },
  { index: 4, radius: 19 },
  { index: 5, radius: 19 },
]);
```

```ts
filletCorners(points: PointInput[], corners: FilletCornerSpec[]): Sketch
```

`FilletCornerSpec`: `{ index: number, radius: number, segments?: number }`

---

## C7: Pattern Replication

Duplicate geometry in regular arrangements (linear, circular, mirror).

#### `circularLayout()` — Compute evenly-spaced positions around a circle.

Eliminates the most common trig pattern in CAD scripts:

```js
// Before — manual trig
for (let i = 0; i < 12; i++) {
  const angle = i * 30 * Math.PI / 180;
  markers.push(marker.translate(r * Math.cos(angle), r * Math.sin(angle), 0));
}

// After — declarative
for (const {x, y} of circularLayout(12, r)) {
  markers.push(marker.translate(x, y, 0));
}
```

```ts
circularLayout(count: number, radius: number, options?: CircularLayoutOptions): LayoutPoint[]
```

**`CircularLayoutOptions`**
- `startDeg?: number` — Angle of the first element in degrees (default: 0 = +X axis).
- `centerX?: number` — Center X coordinate (default: 0).
- `centerY?: number` — Center Y coordinate (default: 0).

`LayoutPoint`: `{ x: number, y: number }`

#### `circularPattern()` — Repeat a shape in a circular pattern around an axis and union the copies.

Distributes `count` copies evenly around the rotation axis (360° / count per step). All copies are unioned into a single `Shape`. Distinct compiler ownership is assigned to each copy — post-merge face identity via owner-scoped canonical queries still works for pattern descendants.

Two calling conventions:

- **Simple** (Z axis): `circularPattern(shape, 6)` or `circularPattern(shape, 6, centerX, centerY)`
- **Advanced** (arbitrary axis): `circularPattern(shape, 6, { axis, origin })`

```ts
// 8 holes evenly spaced around origin
circularPattern(cylinder(12, 4).translate(30, 0, -1), 8)

// Circular pattern around X axis
circularPattern(myFeature, 4, { axis: [1, 0, 0], origin: [0, 0, 50] })
```

```ts
circularPattern(shape: Shape, count: number, centerXOrOpts?: number | CircularPatternOptions, centerY?: number): Shape
```

**`CircularPatternOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `centerX?` | `number` | Center X of the rotation (default: 0). Used when the rotation axis is Z. |
| `centerY?` | `number` | Center Y of the rotation (default: 0). Used when the rotation axis is Z. |
| `axis?` | `[ number, number, number ]` | Rotation axis direction (default: [0, 0, 1] = Z axis). |
| `origin?` | `[ number, number, number ]` | Pivot point for the rotation (default: [0, 0, 0]). Overrides centerX/centerY when set. |

#### `circularPattern2d()` — Repeat a 2D sketch in a circular pattern around a center point and union the copies.

```ts
circularPattern2d(sketch: Sketch, count: number, centerXOrOpts?: number | { centerX?: number; centerY?: number; startDeg?: number; }, centerY?: number): Sketch
```

#### `linearPattern()` — Repeat a shape in a linear pattern along a direction vector and union the copies.

Creates `count` copies of `shape`, each offset by `(dx*i, dy*i, dz*i)` from the original. All copies are unioned into a single `Shape`. Distinct compiler ownership is assigned to each copy so face identity via owner-scoped canonical queries still works post-merge.

```ts
// 5 cylinders, 20mm apart along X
linearPattern(cylinder(10, 3), 5, 20, 0)
```

```ts
linearPattern(shape: Shape, count: number, dx: number, dy: number, dz?: number): Shape
```

#### `linearPattern2d()` — Repeat a 2D sketch in a linear pattern and union the copies.

```ts
linearPattern2d(sketch: Sketch, count: number, dx: number, dy?: number): Sketch
```

#### `mirrorCopy()` — Mirror a shape across a plane and union the mirror with the original.

The mirror plane passes through the origin and is defined by its normal vector. The mirrored copy is unioned with the original to produce a single symmetric Shape.

```ts
// Mirror across the YZ plane (X=0)
mirrorCopy(box(50, 30, 10), [1, 0, 0])
```

```ts
mirrorCopy(shape: Shape, normal: [ number, number, number ]): Shape
```

---

## C8: Constraint Solving

Define geometry by relationships and let a solver find positions.

#### `Constraint.makeParallel()` — Constrain two lines to be parallel.

```ts
Constraint.makeParallel(builder: ConstrainedSketchBuilder, a: LineArg, b: LineArg): ConstrainedSketchBuilder
```

#### `Constraint.enforceAngle()` — Constrain the signed angle from line `a` to line `b`.

```ts
Constraint.enforceAngle(builder: ConstrainedSketchBuilder, a: LineArg, b: LineArg, angleDeg: number): ConstrainedSketchBuilder
```

#### `Constraint.horizontal()` — Constrain a line to be horizontal.

```ts
Constraint.horizontal(builder: ConstrainedSketchBuilder, line: LineArg): ConstrainedSketchBuilder
```

#### `Constraint.vertical()` — Constrain a line to be vertical.

```ts
Constraint.vertical(builder: ConstrainedSketchBuilder, line: LineArg): ConstrainedSketchBuilder
```

#### `Constraint.equalLength()` — Constrain two lines to have equal length.

```ts
Constraint.equalLength(builder: ConstrainedSketchBuilder, a: LineArg, b: LineArg): ConstrainedSketchBuilder
```

#### `Constraint.distance()` — Constrain the distance between two points.

```ts
Constraint.distance(builder: ConstrainedSketchBuilder, a: PointArg, b: PointArg, value: number): ConstrainedSketchBuilder
```

#### `Constraint.fix()` — Fix a point at a specific coordinate.

```ts
Constraint.fix(builder: ConstrainedSketchBuilder, pt: PointArg, x: number, y: number): ConstrainedSketchBuilder
```

#### `Constraint.coincident()` — Constrain two points to occupy the same location.

```ts
Constraint.coincident(builder: ConstrainedSketchBuilder, a: PointArg, b: PointArg): ConstrainedSketchBuilder
```

#### `Constraint.perpendicular()` — Constrain two lines to be perpendicular.

```ts
Constraint.perpendicular(builder: ConstrainedSketchBuilder, a: LineArg, b: LineArg): ConstrainedSketchBuilder
```

#### `Constraint.length()` — Constrain the length of a line.

```ts
Constraint.length(builder: ConstrainedSketchBuilder, line: LineArg, value: number): ConstrainedSketchBuilder
```

#### `addPolygon()` — Add a general polygon concept to the builder.

Creates n vertices and n sides (CCW: `sides[i]` from `vertices[i]` → `vertices[(i+1) % n]`). Applies a `ccw` constraint to enforce winding. All dimensional constraints (lengths, angles, position) are left to the caller.

Use `sk.addPolygon()` as the shorthand builder method.

```ts
const sk = constrainedSketch();
const tri = sk.addPolygon({ points: [[0,0],[100,0],[50,80]] });
sk.fix(tri.vertex(0), 0, 0);
sk.length(tri.side(0), 100);
return sk.solve().extrude(5);
```

```ts
addPolygon(sk: ConstrainedSketchBuilder, options: PolygonOptions): ConstrainedPolygon
```

**`PolygonOptions`**
- `points: ReadonlyArray<readonly [ number, number ]>` — Initial vertex coordinates. Minimum 3 points.
- `addLoop?: boolean` — Whether to register a closed loop for sketch generation. Default: true.
- `blockRotation?: boolean` — Prevent 180° rotation (ensures first edge maintains its initial direction). Default: false.

**`ConstrainedPolygon`**
- `vertices: PointId[]` — CCW-ordered PointIds.
- `sides: LineId[]` — CCW-ordered LineIds. `sides[i]` runs from `vertices[i]` → `vertices[(i+1) % n]`.
- `shape: ShapeId` — ShapeId for `shapeWidth`, `shapeHeight`, `shapeArea`, `shapeCentroidX/Y`.

#### `addRect()` — Add an axis-aligned rectangle concept to the builder.

Creates 4 vertices (CCW: bl→br→tr→tl), 4 sides, 4 structural constraints (`horizontal`/`vertical` on each side), CCW winding, a center point, a loop, and a shape. Returns a `ConstrainedRect` handle with 4 DOF (x, y, width, height).

Use `sk.rect()` as the shorthand builder method.

```ts
const sk = constrainedSketch();
const r = sk.rect({ x: 0, y: 0, width: 100, height: 50 });
sk.fix(r.bottomLeft, 0, 0);
sk.length(r.bottom, 120);  // override initial width
return sk.solve().extrude(10);
```

```ts
addRect(sk: ConstrainedSketchBuilder, options?: RectOptions): ConstrainedRect
```

**`RectOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `x?` | `number` | Bottom-left x coordinate. Default: 0. |
| `y?` | `number` | Bottom-left y coordinate. Default: 0. |
| `width?` | `number` | Width (along x). Default: 10. |
| `height?` | `number` | Height (along y). Default: 10. |
| `blockRotation?` | `boolean` | Prevent 180° rotation (ensures bottom edge points rightward). Default: false. |

**`ConstrainedRect`**

| Option | Type | Description |
|--------|------|-------------|
| `bottom` | `LineId` | bottom-left → bottom-right |
| `right` | `LineId` | bottom-right → top-right |
| `top` | `LineId` | top-right → top-left |
| `left` | `LineId` | top-left → bottom-left |
| `center` | `PointId` | Center point constrained to the geometric center via `midpoint` on the diagonal. Can be used in further constraints: `sk.fix(rect.center, 0, 0)`, `sk.coincident(rect.center, other)`. |
| `shape` | `ShapeId` | ShapeId for `shapeWidth`, `shapeHeight`, `shapeArea`, `shapeCentroidX/Y`. |
| `vertices` | `[ PointId, PointId, PointId, PointId ]` | CCW-ordered vertex array: [bottomLeft, bottomRight, topRight, topLeft]. |
| `sides` | `[ LineId, LineId, LineId, LineId ]` | CCW-ordered side array: [bottom, right, top, left]. |
| `bottomLeft`, `bottomRight`, `topRight`, `topLeft` | | — |

#### `addRegularPolygon()` — Add a regular n-gon concept to the builder.

Vertices are placed at `(cx + r·cos(startAngle + i·2π/n), cy + r·sin(...))`. Equal-radius and equal-side constraints enforce regularity (4 DOF: center x/y, radius, rotation). The center point is tracked by the solver and exposed via the returned handle.

Use `sk.regularPolygon()` as the shorthand builder method.

```ts
const sk = constrainedSketch();
const hex = sk.regularPolygon({ sides: 6, radius: 25 });
sk.fix(hex.center, 0, 0);
sk.length(hex.side(0), 30);  // all sides change (equal constraint)
return sk.solve().extrude(5);
```

```ts
addRegularPolygon(sk: ConstrainedSketchBuilder, options: RegularPolygonOptions): ConstrainedRegularPolygon
```

**`RegularPolygonOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `sides` | `number` | Number of sides (minimum 3). |
| `radius?` | `number` | Circumradius — distance from center to vertex. Default: 10. |
| `cx?` | `number` | Center x coordinate. Default: 0. |
| `cy?` | `number` | Center y coordinate. Default: 0. |
| `startAngle?` | `number` | Angle (in degrees) of vertex[0] measured from the +X axis (CCW positive). Default: 0 (rightmost vertex). |
| `blockRotation?` | `boolean` | Prevent 180° rotation (ensures first edge maintains its initial direction). Default: false. |


**`ConstrainedRegularPolygon`** extends ConstrainedPolygon
- `center: PointId` — Center point. Use `sk.fix(poly.center, x, y)` to pin location, or `sk.coincident(poly.center, other)` to align with other geometry.

#### `circle()` — Create an analytic 2D circle for measurement, construction, and extrusion.

```ts
const c = circle(0, 0, 25);
c.diameter; c.circumference; c.area;
c.pointAtAngle(90);  // Point2D at top (90° CCW from +X)

// Extrude to cylinder with named faces
const cyl = c.extrude(30);
cyl.face('top');   // FaceRef (planar)
cyl.face('side');  // FaceRef (curved)

Circle2D.fromDiameter(point(0, 0), 50);
```

```ts
circle(cx: number, cy: number, radius: number): Circle2D
```

#### `constrainedSketch()` — Create a parametric 2D sketch driven by geometric constraints and a nonlinear solver.

**Workflow**

1. Create a builder with `constrainedSketch()`.
2. Add geometry — points, lines, circles, arcs — using the builder methods.
3. Add constraints (`horizontal`, `length`, `fix`, etc.) to drive the geometry.
4. Call `.solve()` to run the solver and get a `ConstraintSketch` (which extends `Sketch`).

```ts
const sk = constrainedSketch();
const p1 = sk.point(0, 0);
const p2 = sk.point(50, 0);
const l1 = sk.line(p1, p2);
sk.fix(p1, 0, 0);
sk.horizontal(l1);
sk.length(l1, 50);
return sk.solve().extrude(10);
```

**Solver status**

```ts
const result = sk.solve();
result.constraintMeta.status;   // 'fully' | 'under' | 'over' | 'over-redundant'
result.constraintMeta.dof;      // 0 = fully constrained
result.constraintMeta.maxError; // residual — should be < 1e-6
result.inspect();               // human-readable summary
result.withUpdatedConstraint('cst-5', 120); // update a dimension without rebuilding
```

```ts
constrainedSketch(options?: ConstrainedSketchOptions): ConstrainedSketchBuilder
```

**`ConstrainedSketchOptions`**
- `strict?: boolean` — When true, adding a constraint that cannot be satisfied throws instead of silently discarding it.

#### `line()` — Create an analytic 2D line segment between two points.

```ts
const l = line(0, 0, 50, 0);
l.length; l.midpoint; l.angle; l.direction;
l.parallel(10);          // parallel line offset 10 (positive = left)
l.intersect(l2);         // Point2D — treats lines as infinite
l.intersectSegment(l2);  // Point2D or null — segments only

Line2D.fromPointAndAngle(point(0, 0), 45, 100);
Line2D.fromPointAndDirection(point(0, 0), [1, 1], 50);
```

```ts
line(x1: number, y1: number, x2: number, y2: number): Line2D
```

#### `point()` — Create an analytic 2D point for measurement and construction geometry.

```ts
const p = point(10, 20);
p.distanceTo(point(30, 40));  // Euclidean distance
p.midpointTo(point(30, 40)); // midpoint
p.translate(5, 5);           // new shifted point
p.toTuple();                 // [10, 20]
```

```ts
point(x: number, y: number): Point2D
```

---

## C9: Spatial Placement

Position geometry relative to other geometry using semantic anchors.


#### `Points.distance()` — Euclidean distance between two 3D points.

```ts
Points.distance(a: Vec3, b: Vec3): number
```

#### `Points.midpoint()` — Center point between two 3D points.

```ts
Points.midpoint(a: Vec3, b: Vec3): Vec3
```

#### `Points.lerp()` — Linearly interpolate between two 3D points. t=0 returns a, t=1 returns b.

```ts
Points.lerp(a: Vec3, b: Vec3, t: number): Vec3
```

#### `Points.direction()` — Unit direction vector from a to b. Throws if a and b are the same point.

```ts
Points.direction(a: Vec3, b: Vec3): Vec3
```

#### `Points.offset()` — Move a point along a direction vector by a given amount.

```ts
Points.offset(point: Vec3, dir: Vec3, amount: number): Vec3
```

#### `Points.polar()` — Compute a 2D point at distance and angle (degrees) from an optional origin.

```ts
Points.polar(length: number, angleDeg: number, from?: [ number, number ]): [ number, number ]
```

---

## C10: Assembly & Kinematics

Compose parts with joints for kinematic simulation.

#### `assembly()` — Create an assembly container with named parts, connectors, and kinematic links.

**Use this from iteration 1 for any model with moving parts.** Do not build one static pose and retrofit motion later.

Links are named kinematic markers in the assembly. `edgeBetweenLinks()` records structural distances or visual relationships. `addAngleBetweenLinks()` records measured, limited, or controlled angles. These APIs solve point positions, not rigid-body frames.

`addPart(..., { mate })` attaches a part connector origin to a solved link point by translation only. It is right for markers and point-following geometry. Use `connect()` / `match()` for physical articulated parts that need full connector frame alignment and deterministic rest orientation.

Return an `Assembly` directly to expose its connector joints and driven link controls in the editor. Moving those controls re-runs the assembly solve with the new state, so closed-loop link/edge mechanisms move through the real kinematic solver instead of a viewport-only forward-kinematics approximation.

If no link in a connected kinematic component is fixed, ForgeCAD chooses a deterministic gauge link for solving and reports a floating-component warning.

The legacy joint-chain APIs still exist for compatibility and exporter plumbing. New work should choose between point-link kinematics and connector-frame joints based on whether the part needs orientation.

For multi-file assemblies, a file that returns an `Assembly` is importable via `require()` and yields an `ImportedAssembly`. Use `mergeInto()` to flatten a sub-assembly into a parent assembly.

**Point-link example**

This snippet mates a marker to the solved `tip` point. It does not orient a bar along `ground -> tip`.

```ts
const marker = box(8, 8, 4).withConnectors({
  center: connector({ origin: [0, 0, 0], axis: [0, 0, 1] }),
});

const mech = assembly("Linkage")
  .link("ground", { at: [0, 0, 0], fixed: true })
  .link("worldX", { at: [10, 0, 0], fixed: true })
  .link("tip", { at: [40, 0, 0] })
  .edgeBetweenLinks("ground", "tip", { name: "bar" })
  .addAngleBetweenLinks("worldX", "ground", "tip", {
    name: "theta",
    control: { min: 0, max: 120, default: 30 },
  })
  .addPart("Tip marker", marker, { mate: { connector: "center", toLink: "tip" } });

return mech;
```

```ts
assembly(name?: string): Assembly
```

#### `bomToCsv()` — Convert an array of BOM rows into a CSV string.

Produces a CSV with columns: `part`, `qty`, `material`, `process`, `tolerance`, `notes`. String values are quoted and internal double-quotes are escaped. Prefer calling `solvedAssembly.bomCsv()` directly — this function is exposed for custom BOM processing.

```ts
bomToCsv(rows: BomRow[]): string
```

**`BomRow`**: `part: string`, `qty: number`, `material?: string`, `process?: string`, `tolerance?: string`, `notes?: string`, `metadata?: PartMetadata`

**`PartMetadata`**

| Option | Type | Description |
|--------|------|-------------|
| `tags?` | `string \| readonly string[]` | Viewport organization tags applied to scene objects produced from this part. |
| `material?`, `process?`, `tolerance?`, `qty?`, `notes?`, `densityKgM3?`, `massKg?` | | — |

<!-- forgecad-skill:exclude-start symbol="jointsView" reason="Compatibility-only viewport FK API. Prefer returning `Assembly` directly so controls move through the solver-backed link/edge kinematics model." -->
#### `jointsView()` — Register legacy viewport-only mechanism controls that animate returned objects without re-running the script.

> **Not included in ForgeCAD AI skill context yet.** This API remains visible in human docs, but is intentionally omitted from shipped agent skills until it is ready for agent-first use. Compatibility-only viewport FK API. Prefer returning `Assembly` directly so controls move through the solver-backed link/edge kinematics model.

Defines joints (revolute or prismatic), optional gear/rack couplings, and named animations. The viewport resolves transforms through the joint chain at display time — the script geometry is computed only once at rest pose.

For `Assembly` mechanisms, prefer returning the `Assembly` directly. Returned assemblies expose solver-backed controls automatically, so link/edge closed loops move through the real assembly solver instead of this viewport-only FK layer.

**Critical:** Solve the assembly at **rest pose** (all animated joints = 0). The viewport applies `jointsView` transforms on top of the returned scene. If geometry is already solved at non-zero angles, animation will double-rotate everything.

```js
// BAD — double rotation
const solved = mech.solve({ shoulder: 45, elbow: 30 });
jointsView({ joints: [{ name: 'shoulder', ... }] });
return solved;

// GOOD — rest pose, jointsView controls all posing
const solved = mech.solve({ shoulder: 0, elbow: 0 });
jointsView({
  joints: [
    { name: 'shoulder', child: 'Upper Arm', default: 45, ... },
    { name: 'elbow', child: 'Forearm', parent: 'Upper Arm', default: 30, ... },
  ],
});
return solved;
```

**Pivot coordinates** are world-space positions of each joint origin at rest pose. For `addRevolute('shoulder', 'Base', 'Link', { frame: Transform.identity().translate(0, 0, 20) })` where "Base" is at world origin, the pivot is `[0, 0, 20]`.

**Fixed attachments** that must follow a parent during animation need a zero-angle revolute joint in the chain:

```js
{ name: 'EE_Follow', child: 'End Effector', parent: 'Last Link',
  type: 'revolute', axis: [0, 0, 1], pivot: [linkLength, 0, 0],
  min: 0, max: 0, default: 0 }
```

Animation values are interpolated linearly between keyframes. ForgeCAD does **not** auto-wrap revolute values across `-180/180`. Keep keyframe values continuous — a `-180 -> 171` jump spins the part the long way around. Use `-180 -> -189` instead. Author high-speed multi-turn joints as accumulating angles (`0, 360, 720, ...`) with `continuous: true`.

**Mirrored revolute axes:** `default` values and animation keyframes are physical joint values, signed by the joint axis. In a bilateral mechanism, mirrored hinge axes such as `[1, 0, 0]` and `[-1, 0, 0]` need opposite physical values for the same mirrored pose. Negate the mirrored revolute track and mirror physical limits as `[min, max] -> [-max, -min]`. Prismatic tracks do not have this handedness flip.

**Tick-based keyframes:** Omit `at` from all keyframes to auto-distribute by tick weight:

```js
keyframes: [
  { ticks: 3, values: { Shoulder: 20 } },  // slow segment (3x weight)
  { ticks: 1, values: { Shoulder: -10 } }, // fast segment (1x weight)
  { values: { Shoulder: 20 } },            // last keyframe; ticks ignored
]
// positions: 0, 0.75, 1.0
```

Mixing explicit `at` and omitted `at` in the same animation is not allowed.

```js
jointsView({
  joints: [{
    name: 'Shoulder', child: 'Upper Arm', parent: 'Base',
    type: 'revolute', axis: [0, -1, 0], pivot: [0, 0, 46],
    min: -30, max: 110, default: 15,
  }],
  animations: [{
    name: 'Walk Cycle', duration: 1.6, loop: true,
    keyframes: [
      { values: { Shoulder: 20 } },
      { values: { Shoulder: -10 } },
      { values: { Shoulder: 20 } },
    ],
  }],
});
```

```ts
jointsView(options?: JointsViewOptions): void
```

**`JointsViewOptions`**: `enabled?: boolean`, `joints?: JointViewInput[]`, `couplings?: JointViewCouplingInput[]`, `animations?: JointViewAnimationInput[]`, `defaultAnimation?: string`

**`JointViewInput`**: `name: string`, `child: string`, `parent?: string`, `type?: JointViewType`, `axis?: JointViewAxis`, `pivot?: [ number, number, number ]`, `min?: number`, `max?: number`, `default?: number`, `unit?: string`, `hidden?: boolean`

`JointViewCouplingInput`: `{ joint: string, terms: JointViewCouplingTermInput[], offset?: number }`

`JointViewCouplingTermInput`: `{ joint: string, ratio?: number }`

`JointViewAnimationInput`: `{ name: string, duration?: number, loop?: boolean, continuous?: boolean, keyframes: JointViewAnimationKeyframeInput[] }`

**`JointViewAnimationKeyframeInput`**
- `at?: number` — Timeline position [0, 1]. If omitted from ALL keyframes, positions are auto-computed from tick weights.
- `ticks?: number` — Relative weight of the segment from this keyframe to the next (default 1). Only used in tick-based mode (when `at` is omitted). Last keyframe's ticks value is ignored.
- Also: `values: Record<string, number>`
<!-- forgecad-skill:exclude-end -->

---

## C11: Parameterization & UI

Declare user-facing controls that drive model geometry.

#### `Param.number()` — Declare a numeric parameter that renders as a slider in the UI.

Each call registers a slider control. When the user moves the slider the entire script re-executes with the new value. Parameter values are also overridable from `require()` imports or the CLI `--param` flag — the `name` string is the key used in both cases.

Default range rules when options are omitted:

- `min` defaults to `0`
- `max` defaults to `defaultValue * 4`
- `step` is auto-calculated: `1` for integer params, `0.1` for ranges ≤ 100, `1` for larger ranges

The `unit` option is cosmetic only — no conversion is performed. Use `integer: true` for counts, sides, quantities (rounds to whole numbers; step defaults to `1`).

```ts
const width = Param.number("Width", 50);
const angle = Param.number("Angle", 45, { min: 0, max: 180, unit: "°" });
const sides = Param.number("Sides", 6, { min: 3, max: 12, integer: true });
```

**Parameter overrides** — key must match `name` exactly:

```ts
// Via require()
const bracket = require("./bracket.forge.js", { Width: 80 });

// Via CLI
// forgecad run model.forge.js --param "Wall Thickness=3"
```

Also available as the shorthand alias `param()`.

```ts
Param.number(name: string, defaultValue: number, opts?: { min?: number; max?: number; step?: number; unit?: string; integer?: boolean; reverse?: boolean; }): number
```

#### `Param.string()` — Declare a string parameter that renders as a text input in the UI.

String parameters let users type free-form text — labels, names, inscriptions, file paths, etc. The `name` string is the override key.

```ts
const label = Param.string("Label", "Hello World");
const name  = Param.string("Name", "Part-001", { maxLength: 20 });
```

Override via import:

```ts
const tag = require("./tag.forge.js", { Label: "Custom Text" });
```

Only available as `Param.string()` — no standalone alias.

```ts
Param.string(name: string, defaultValue: string, opts?: { maxLength?: number; }): string
```

#### `Param.bool()` — Declare a boolean parameter that renders as a checkbox in the UI.

Internally stored as `0`/`1`. When overriding from CLI or `require()`, pass `1` for true and `0` for false. The `name` string is the override key.

```ts
const showHoles = Param.bool("Show Holes", true);
if (showHoles) return difference(plate, cylinder(10, 5).translate(50, 30, 0));
return plate;
```

Override via import:

```ts
const pan = require("./pan.forge.js", { "Show Lid": 0 });
```

Also available as the shorthand alias `boolParam()`.

```ts
Param.bool(name: string, defaultValue: boolean): boolean
```

#### `Param.choice()` — Declare a choice parameter that renders as a dropdown in the UI.

`defaultValue` must exactly match one entry in `choices`. Returns the selected string label. Prefer `Param.choice` over `Param.number` when a slider would hide intent — named choices like `"wok"` are self-describing.

Overrides may be passed as the choice label string (preferred) or as a numeric index. The `name` string is the override key.

```ts
const panStyle = Param.choice("Pan Style", "frying-pan", ["frying-pan", "saute-pan", "wok"]);
if (panStyle === "wok") return buildWok();
```

Override via import:

```ts
const pan = require("./pan.forge.js", { "Pan Style": "wok" });
```

Override via CLI:

```bash
forgecad run model.forge.js --param "Pan Style=wok"
```

Also available as the shorthand alias `choiceParam()`.

```ts
Param.choice(name: string, defaultValue: string, choices: string[]): string
```

#### `Param.list()` — Declare a list parameter — an array of struct items with per-field UI controls.

Each item in the list is a struct whose fields each render as their own control (slider, checkbox, or dropdown). The user can add/remove rows up to `minItems`/`maxItems` bounds.

Field types:

- Boolean fields (`boolean: true` in field defs) return as `boolean`
- Choice fields (`choices: [...]` in field defs) return as `string`
- All other fields return as `number`

```ts
Param.list<T extends Record<string, number | boolean | string>>(name: string, defaultItems: T[], opts: { ... }): T[]
```

`ListParamFieldDef`: `{ min?: number, max?: number, step?: number, unit?: string, integer?: boolean, boolean?: boolean, choices?: string[] }`

#### `dim()` — Add a dimension annotation between two points.

Dimension annotations are purely visual callouts rendered in the viewport and report export. They do not affect geometry or constrain the model.

Point arguments accept 2D tuples `[x, y]`, 3D tuples `[x, y, z]`, or `Point2D` objects (Z is treated as 0 for 2D inputs).

**Ownership Rules (Report Pages)**

- `currentComponent: true` — deterministic ownership by the calling import instance. Use when authoring reusable imported parts.
- `component: "Part Name"` — route dimension to another named returned object.
- Multiple owners: dimension is shared and appears on the assembly overview page.
- No ownership set: report export infers ownership via endpoint-in-bbox.

```ts
dim([-w / 2, 0, 0], [w / 2, 0, 0], { label: "Width" });
dim([0, 0, -h / 2], [0, 0, h / 2], { label: "Height", offset: 14 });
dim([0, 0, 0], [100, 0, 0], { component: "Base", color: "#00AAFF" });
```

`component` (string or string[] — report ownership), `currentComponent` (boolean)

```ts
dim(from: PointArg, to: PointArg, opts?: DimOpts): void
```

`DimOpts`: `{ offset?: number, label?: string, color?: string, component?: string | string[], currentComponent?: boolean }`

#### `dimLine()` — Add a dimension annotation along a `Line2D`.

Convenience wrapper around { points from a constrained-sketch `Line2D` entity. All `opts` are forwarded unchanged.

```ts
const a = point(0, 0);
const b = point(100, 0);
dimLine(line(a, b), { label: "Span", offset: -8 });
```

```ts
dimLine(l: Line2D, opts?: DimOpts): void
```

---

## C12: Dimensional Demotion

Extract 2D geometry from a 3D solid (section, projection).

#### `faceProfile()` — Extract the boundary profile of a named face as a 2D sketch.

The result is returned in the face's local 2D coordinate system, making it convenient for offsets, pocket profiles, or follow-up sketch operations driven by an existing face.

```ts
faceProfile(shape: Shape, face: FaceSelector): Sketch
```

#### `intersectWithPlane()` — Cross-section: slice a 3D shape with a plane and return the intersection as a 2D Sketch.

```ts
intersectWithPlane(shape: Shape, plane: PlaneSpec): Sketch
```

#### `projectToPlane()` — Orthographically project a 3D shape onto a plane and return the silhouette as a 2D Sketch.

```ts
projectToPlane(shape: Shape, plane: PlaneSpec): Sketch
```

---

## C13: Export & Output

Convert geometry to external formats (STL, 3MF, SVG, DXF, G-code, PDF).

#### `bom()` — Register a Bill of Materials entry for report export.

BOM entries are accumulated during script execution and exported alongside the model in report views. Rows are grouped by normalized `description + unit`. Pass an explicit `key` to force multiple descriptions to collapse into a single line item.

- `quantity` must be a finite number `>= 0`. A quantity of `0` is silently ignored (useful for conditional scripting with `param()`-driven counts).
- `unit` defaults to `"pieces"` when omitted or empty.
- The assembly `solved.bom()` / `solved.bomCsv()` API is separate and covers per-part assembly metadata; this function is for free-form purchased-item annotation.
- `bom()` is injected into every `.forge.js` script. Call it directly; do not write `const { bom } = require(...)`, because top-level declarations named `bom` collide with the built-in runtime name.

```ts
const tubeLen = param("Tube Length", 1200, { min: 300, max: 4000, unit: "mm" });
const boltCount = param("Bolt Count", 16, { min: 0, max: 200, integer: true });

bom(tubeLen, "iron tube 30 x 20", { unit: "mm" });
bom(boltCount, "M4 bolt, 16 mm length");
bom(4, "rubber foot", { key: "foot-rubber" }); // explicit aggregation key

// Structured metadata for richer reports:
bom(tubeLen, "rectangular steel tube", {
  unit: "mm",
  material: "steel",
  section: [30, 20],
  wall: 3,
});
```

```ts
bom(quantity: number, description: string, opts?: BomOpts): void
```

**`BomOpts`**

| Option | Type | Description |
|--------|------|-------------|
| `unit?` | `string` | Quantity unit label, e.g. "mm", "pieces", "kg". Default: "pieces" |
| `key?` | `string` | Optional explicit grouping key used during report aggregation. |
| `material?` | `string` | Material name, e.g. "steel", "birch plywood", "nylon" |
| `dimensions?` | `number[]` | Overall dimensions `[width, height]` or `[width, height, thickness]` in the entry's unit |
| `section?` | `number[]` | Cross-section dimensions `[w, h]` for tubes and profiles |
| `wall?` | `number` | Wall thickness for hollow sections (mm) |
| `diameter?` | `number` | Diameter for round stock, bolts, dowels (mm) |
| `length?` | `number` | Length for fasteners (mm) |
| `process?` | `string` | Manufacturing process, e.g. "laser cut", "CNC", "welded" |
| `notes?` | `string` | Free-form notes |
| `grain?` | `string` | Wood grain direction, e.g. "long", "cross" |

#### `robotExport()` — Declare that this script should export the assembly as a SDF/URDF robot package.

Call `robotExport()` alongside your assembly definition. The CLI commands `forgecad export sdf` and `forgecad export urdf` pick up the declaration and produce a robot package with:

- Mesh-based inertia tensors (full 6-component, not bounding-box approximations)
- Separate collision meshes (convex hull by default — ~50–80% smaller)
- Joint limits, effort/velocity/damping/friction metadata from assembly joints

**Collision mesh modes** (set per-link via `links["PartName"].collision`):

| Mode | Description | Default |
|------|-------------|---------|
| `'convex'` | Convex hull (separate `_collision.stl`) | Yes |
| `'box'` | AABB primitive — fastest physics | |
| `'visual'` | Same mesh as visual — exact but slow | |
| `'none'` | No collision geometry | |

**Unit conventions:**

- Revolute `velocity` is in degrees/second in Forge; exporters convert to rad/s.
- Prismatic distances are in mm in Forge; exported in meters.
- `massKg` is preferred; `densityKgM3` is used when mass is unknown.
- Compatibility coupling metadata, when present, maps only the primary term (largest ratio) to `<mimic>` — SDF/URDF support single-leader mimic only. Dropped terms emit a warning.

```ts
const rover = assembly("Scout")
  .addPart("Chassis", box(300, 220, 50).translate(0, 0, -25))
  .addPart("Left Wheel", cylinder(30, 60, undefined, 48).translate(0, 0, -15))
  .addRevolute("leftWheel", "Chassis", "Left Wheel", {
    axis: [0, 1, 0],
    frame: Transform.identity().translate(90, 140, 60),
    effort: 20, velocity: 1080,
  });

robotExport({
  assembly: rover,
  modelName: "Scout",
  links: {
    Chassis: { massKg: 10 },
    "Left Wheel": { massKg: 0.8 },
  },
  plugins: {
    diffDrive: {
      leftJoints: ["leftWheel"], rightJoints: ["rightWheel"],
      wheelSeparationMm: 280, wheelRadiusMm: 60,
    },
  },
  world: { generateDemoWorld: true },
});
```

**CLI usage**

```bash
forgecad export sdf model.forge.js   # SDF package (Gazebo/Ignition)
forgecad export urdf model.forge.js  # URDF package (ROS/PyBullet/MuJoCo)
```

```ts
robotExport(options: RobotExportOptions): CollectedRobotExport
```

**`RobotExportOptions`**: `assembly: Assembly`, `modelName?: string`, `state?: JointState`, `static?: boolean`, `selfCollide?: boolean`, `allowAutoDisable?: boolean`, `links?: Record<string, RobotLinkExportOptions>`, `joints?: Record<string, RobotJointExportOptions>`, `plugins?: { diffDrive?: RobotDiffDrivePluginOptions; jointStatePublisher?: RobotJointStatePublisherOptions; }`, `world?: RobotWorldOptions`

`RobotLinkExportOptions`: `{ massKg?: number, densityKgM3?: number, collision?: "visual" | "convex" | "box" | "none" }`

`RobotJointExportOptions`: `{ effort?: number, velocity?: number, damping?: number, friction?: number }`

**`RobotDiffDrivePluginOptions`**: `leftJoints: string[]`, `rightJoints: string[]`, `wheelSeparationMm: number`, `wheelRadiusMm: number`, `topic?: string`, `odomTopic?: string`, `tfTopic?: string`, `frameId?: string`, `odomFrameId?: string`, `maxLinearVelocity?: number`, `maxAngularVelocity?: number`, `linearAcceleration?: number`, `angularAcceleration?: number`

`RobotJointStatePublisherOptions`: `{ enabled?: boolean, joints?: string[], topic?: string, updateRate?: number }`

`RobotWorldOptions`: `{ name?: string, generateDemoWorld?: boolean, spawnPose?: RobotPose6, keyboardTeleop?: RobotWorldKeyboardTeleopOptions }`

`RobotWorldKeyboardTeleopOptions`: `{ enabled?: boolean, linearStep?: number, angularStep?: number }`

**`CollectedRobotExport`**: `modelName: string`, `assembly: AssemblyDefinition`, `state: JointState`, `static: boolean`, `selfCollide: boolean`, `allowAutoDisable: boolean`, `links: Record<string, RobotLinkExportOptions>`, `joints: Record<string, RobotJointExportOptions>`, `plugins: { diffDrive?: RobotDiffDrivePluginOptions; jointStatePublisher?: RobotJointStatePublisherOptions; }`, `world: RobotWorldOptions | null`

**`AssemblyDefinition`**: `name: string`, `parts: AssemblyPartDef[]`, `joints: AssemblyJointDef[]`, `jointCouplings: AssemblyJointCouplingDef[]`, `kinematics: AssemblyKinematicGraphDef`

`AssemblyPartDef`: `{ name: string, part: AssemblyPart, base: Transform, metadata?: PartMetadata, mates: AssemblyPartMateInput[] }`

**`PartMetadata`**

| Option | Type | Description |
|--------|------|-------------|
| `tags?` | `string \| readonly string[]` | Viewport organization tags applied to scene objects produced from this part. |
| `material?`, `process?`, `tolerance?`, `qty?`, `notes?`, `densityKgM3?`, `massKg?` | | — |

**`AssemblyPartMateInput`**
- `connector: string` — Name of a connector declared on the part (via `withConnectors()`).
- `toLink: string` — Name of the link this connector's origin is pinned to.
- `aimLink?: string` — Optional second link to orient toward. When set, the part is rotated so the connector's **axis** aims from `toLink` toward `aimLink`, posing an oriented bone instead of only translating it. For full pose without relying on a connector axis, declare a second mate (two connectors → two links).

**`AssemblyJointDef`**: `name: string`, `type: JointType`, `parent: string`, `child: string`, `frame: Transform`, `axis: Vec3`, `min?: number`, `max?: number`, `defaultValue: number`, `unit?: string`, `effort?: number`, `velocity?: number`, `damping?: number`, `friction?: number`, `connectorRefs?: JointConnectorRefs`

`JointConnectorRefs`: `{ parent: string, child: string, parentAlign?: PortAlign, childAlign?: PortAlign }`

`AssemblyJointCouplingDef`: `{ joint: string, terms: JointCouplingTermRecord[], offset: number }`

`JointCouplingTermRecord`: `{ joint: string, ratio: number }`

`AssemblyKinematicGraphDef`: `{ links: AssemblyLinkDef[], edges: AssemblyEdgeBetweenLinksDef[], angles: AssemblyAngleBetweenLinksDef[] }`

`AssemblyLinkDef`: `{ name: string, at: Vec3, fixed: boolean, metadata?: Record<string, unknown> }`

**`AssemblyEdgeBetweenLinksDef`**: `name: string`, `a: string`, `b: string`, `length: number | null`, `min?: number`, `max?: number`, `visualOnly: boolean`, `control?: AssemblyKinematicControlOptions`, `metadata?: Record<string, unknown>`

`AssemblyKinematicControlOptions`: `{ min?: number, max?: number, default?: number, unit?: string }`

**`AssemblyAngleBetweenLinksDef`**: `name: string`, `a: string`, `b: string`, `c: string`, `target?: number`, `min?: number`, `max?: number`, `control?: AssemblyKinematicControlOptions`, `metadata?: Record<string, unknown>`

#### `sheetMetal()` — Create a parametric sheet metal part with flanges, bend allowances, and flat-pattern unfolding.

`sheetMetal()` keeps one semantic model and derives both a folded 3D solid and an accurate flat pattern from it. The K-factor bend allowance is applied during unfolding. This is a strict v1 subset — it does not infer sheet metal from arbitrary solids.

**Recommended authoring order:**

1. Define the base panel + thickness + bend parameters.
2. Chain `.flange()` calls for each edge. Validate with `.folded()` and `.flatPattern()` before adding cutouts.
3. Add panel cutouts, then flange cutouts one region at a time.
4. Validate after each new cutout region.

**v1 limitations:** one base panel, up to four 90° edge flanges, constant thickness, explicit K-factor, rectangular corner reliefs, planar cutouts only. No hems, jogs, lofted bends, non-90° flanges, or bend-region cutouts.

```ts
const cover = sheetMetal({
  panel: { width: 180, height: 110 },
  thickness: 1.5,
  bendRadius: 2,
  bendAllowance: { kFactor: 0.42 },
  cornerRelief: { size: 4 },
})
  .flange('top',    { length: 18 })
  .flange('right',  { length: 18 })
  .flange('bottom', { length: 18 })
  .flange('left',   { length: 18 })
  .cutout('panel', rect(72, 36), { selfAnchor: 'center' })
  .cutout('flange-right', roundedRect(26, 10, 5), { selfAnchor: 'center' });

const folded = cover.folded();
const flat   = cover.flatPattern();
```

```ts
sheetMetal(options: SheetMetalOptions): SheetMetalPart
```

**`SheetMetalOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `panel` | `{ width: number; height: number; }` | Base panel dimensions. This is the flat blank before flanges are applied. |
| `thickness` | `number` | Sheet thickness in mm. Applied uniformly across the panel and all flanges. |
| `bendRadius` | `number` | Inside bend radius in mm. Must be ≥ 0. Typically 0.5–2× the sheet thickness. |
| `bendAllowance` | `{ kFactor: number; }` | Bend allowance model used when computing the flat-pattern developed length. Currently only K-factor is supported. The K-factor (0–1) describes how far the neutral axis sits from the inner bend surface. Typical values: - Soft materials / large radius: 0.50 - General sheet steel: 0.42–0.44 - Hard materials / tight radius: 0.30–0.38 |
| `cornerRelief?` | `{ kind?: "rect"; size: number; }` | Corner relief cut at each bend intersection. Prevents material overlap when two flanges meet at a corner. Defaults to a rectangular relief sized to `bendRadius + thickness` if omitted. |

#### `sketchToDxf()` — Export a 2D sketch as a DXF string (R12/AC1009 — maximally compatible).

For regular sketches, each polygon loop becomes a closed `LWPOLYLINE`. For constrained sketches, exports raw `LINE`, `CIRCLE`, and `ARC` entities from the constraint edge geometry, which preserves internal/shared edges that `toPolygons()` would merge away.

The R12 format is chosen for maximum compatibility with CAM tools, laser-cutter software, and older CAD readers.

```ts
const s = rect(100, 60);
const dxf = sketchToDxf(s, { layer: 'cut' });
```

```ts
sketchToDxf(sketch: Sketch, options?: SketchDxfOptions): string
```

**`SketchDxfOptions`**
- `layer?: string` — DXF layer name. Default: "0"
- `colorIndex?: number` — DXF color index (1–255, AutoCAD ACI). Default: 7 (white/black)

#### `sketchToSvg()` — Export a 2D sketch as an SVG string.

For regular sketches, exports filled polygon regions. For constrained sketches, exports raw edge geometry (LINE, ARC, CIRCLE) which preserves internal/shared edges that `toPolygons()` would merge away.

The SVG uses the sketch's native coordinate system (Y-up) with a CSS transform that flips Y so the output renders correctly in SVG's Y-down space. Coordinates are in sketch units (typically mm).

```ts
const s = rect(100, 60);
const svg = sketchToSvg(s, { stroke: '#333', strokeWidth: 0.8 });
```

```ts
sketchToSvg(sketch: Sketch, options?: SketchSvgOptions): string
```

**`SketchSvgOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `stroke?` | `string` | Stroke color. Default: "black" |
| `strokeWidth?` | `number` | Stroke width in sketch units. Default: 0.5 |
| `fill?` | `string` | Fill color. Default: "none" |
| `padding?` | `number` | Padding around the sketch bounding box in sketch units. Default: 2 |
| `pixelsPerUnit?` | `number` | If set, scale so 1 sketch-unit = this many px. Otherwise auto-fit. |

---

## C14: Visual & Debugging

Control viewport appearance and debugging aids.

#### `Viewport.label()` — Add a render-only viewport label at a world-space point.

`Viewport.label()` is for temporary review, debug, tutorial, or explicitly requested presentation overlays. It does not create sketches, meshes, B-rep topology, exported text, or face labels, so it stays off the OCCT path. Default production models should be understandable from physical geometry, materials, part boundaries, and named objects, not viewport annotations.

Use `text2d()` only when the letters should become manufactured geometry, such as raised lettering, engraved serial numbers, or exported nameplates.

Labels are collected during script execution and rendered by the viewport as lightweight overlay annotations. They are ignored by exports and do not appear in `objects`.

```js
Viewport.label('Bearing bore', [0, 0, 18], {
  color: '#f8fafc',
  background: '#0f172acc',
  offset: [0, 0, 8],
  anchor: 'bottom',
});

return box(40, 30, 12);
```

```ts
Viewport.label(text: string, at: [ number, number, number ], options?: RenderLabelOptions): void
```

**`RenderLabelOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `color?` | `string` | Text color as any CSS color string. |
| `background?` | `string` | Background color as any CSS color string. Use `'transparent'` for no pill background. |
| `size?` | `number` | Font size in CSS pixels. Defaults to 12. |
| `offset?` | `[ number, number, number ]` | Additional world-space offset from `at`. |
| `anchor?` | `RenderLabelAnchor` | Which point of the label box is anchored to `at`. Defaults to `'center'`. |
| `alwaysOnTop?` | `boolean` | When false, the label is hidden when occluded by scene geometry. Defaults to true. |

#### `verify.that()` — Custom predicate check.

```ts
verify.that(label: string, check: () => boolean, message?: string): void
```

#### `verify.equal()` — Check that two numbers are approximately equal (within tolerance).

```ts
verify.equal(label: string, actual: number, expected: number, tolerance?: number, message?: string): void
```

#### `verify.notEqual()` — Check that two numbers are NOT equal (differ by more than tolerance).

```ts
verify.notEqual(label: string, actual: number, unexpected: number, tolerance?: number, message?: string): void
```

#### `verify.greaterThan()` — Check that actual > min.

```ts
verify.greaterThan(label: string, actual: number, min: number, message?: string): void
```

#### `verify.lessThan()` — Check that actual < max.

```ts
verify.lessThan(label: string, actual: number, max: number, message?: string): void
```

#### `verify.inRange()` — Check that min <= actual <= max.

```ts
verify.inRange(label: string, actual: number, min: number, max: number, message?: string): void
```

#### `verify.centersCoincide()` — Check that the bounding-box centers of two shapes coincide within tolerance (mm).

```ts
verify.centersCoincide(label: string, a: ShapeLike, b: ShapeLike, tolerance?: number): void
```

`ShapeLike`: `{ min: number[], max: number[] }`

#### `verify.connectorDistance()` — Check the distance between two named connectors on a shape or group.

Use this when connectors + `matchTo()` define a static assembly interface. It proves the mate at runtime, unlike a plain source-level connector declaration. The common case is `expected = 0`, meaning the two connector origins should coincide after placement.

```ts
verify.connectorDistance("leg is seated", bench, "Rail.leg_0", "Leg0.head", 0, 0.01);
```

```ts
verify.connectorDistance(label: string, target: ConnectorDistanceLike, connectorA: string, connectorB: string, expected?: number, tolerance?: number): void
```

#### `verify.physicalComponentCount()` — Declare the expected physical connectivity component count for the returned visible model.

Use this for generated mechanical models that should have a clear component graph: one connected fixture, a purchased part plus a removable cartridge, a root assembly plus named intentional ghosts, and so on. `forgecad inspect mechanical-integrity` resolves the returned visible objects with the same physical-connectivity analysis used in the quality gate and fails if the actual component count differs.

This catches the common generated-CAD failure where a script returns a visually plausible artifact but the handle, screw, washer, cover, or terminal block is actually a separate island.

```ts
verify.physicalComponentCount("vise is one connected installed assembly", 1);
```

```ts
verify.physicalComponentCount(label: string, expected: number): void
```

#### `verify.intentionalOverlap()` — Declare that two visible objects intentionally overlap because the overlap is real manufacturing intent.

Use this only for overlaps that a mechanical reviewer would accept as actual matter sharing volume: welded/fused regions, overmolded inserts, potted electronics, cast-in hardware, or deliberately bonded laminations. This is not a shortcut for screws without holes, shafts without bores, covers without pockets, or parts placed with collision as a positioning hack.

`forgecad inspect mechanical-integrity --collisions` only honors this declaration when both shapes are returned as visible objects and the exact collision report finds that same object pair. Unused or non-visible declarations fail the quality gate so annotations cannot hide unrelated collisions.

```ts
verify.intentionalOverlap("rubber grip is overmolded on handle", rubberGrip, handleCore, "overmolded insert");
```

```ts
verify.intentionalOverlap(label: string, a: ShapeLike, b: ShapeLike, reason: string): void
```

#### `verify.notColliding()` — Check that two shapes do not share positive volume.

Face-to-face contact is allowed; use `verify.minClearance()` when an actual running gap is required.

```ts
verify.notColliding(label: string, a: ShapeLike, b: ShapeLike, searchLength?: number): void
```

#### `verify.minClearance()` — Check that a minimum clearance gap exists between two shapes.

```ts
verify.minClearance(label: string, a: ShapeLike, b: ShapeLike, minGap: number, searchLength?: number): void
```

#### `verify.clearanceBetween()` — Check that the clearance gap between two shapes is inside an allowed range.

Use this for seated and retained interfaces where a part must be close enough to be mechanically accountable, but must not collide beyond the allowed minimum. It catches both failure modes that make generated CAD look fake: parts floating away from their receiver, and parts intersecting their receiver because the pocket, bore, or running clearance was not modeled.

For contact, use a narrow range such as `[-0.01, 0.05]` to tolerate tiny numerical noise. For a running fit, use the intended clearance band.

Manifold-backed shapes use exact min-gap distance. Other backends use a mesh-derived min-gap check and say so in the verification message; keep `forgecad inspect mechanical-integrity --collisions` in the acceptance gate for positive-volume interference.

```ts
verify.clearanceBetween("cover is seated on gasket", cover, gasket, -0.01, 0.05);
verify.clearanceBetween("carriage runs inside rail", carriage, rail, 0.2, 0.5);
```

```ts
verify.clearanceBetween(label: string, a: ShapeLike, b: ShapeLike, minGap: number, maxGap: number, searchLength?: number): void
```

#### `verify.parallel()` — Check that two face normals are parallel (within toleranceDeg degrees).

```ts
verify.parallel(label: string, faceA: FaceRefLike, faceB: FaceRefLike, toleranceDeg?: number): void
```

`FaceRefLike`: `{ normal: [ number, number, number ], center: [ number, number, number ] }`

#### `verify.perpendicular()` — Check that two face normals are perpendicular (within toleranceDeg degrees).

```ts
verify.perpendicular(label: string, faceA: FaceRefLike, faceB: FaceRefLike, toleranceDeg?: number): void
```

#### `verify.coplanar()` — Check that a face is coplanar with (same plane as) another face, meaning they are parallel AND their centers lie on the same plane.

```ts
verify.coplanar(label: string, faceA: FaceRefLike, faceB: FaceRefLike, toleranceDeg?: number, toleranceMm?: number): void
```

#### `verify.faceAt()` — Check that a face center lies at a specific position (within toleranceMm).

```ts
verify.faceAt(label: string, face: FaceRefLike, expectedPos: [ number, number, number ], toleranceMm?: number): void
```

#### `verify.sameDirection()` — Check that two face normals point in the same direction (not antiparallel). Stricter than parallel — both |angle| AND sign must match.

```ts
verify.sameDirection(label: string, faceA: FaceRefLike, faceB: FaceRefLike, toleranceDeg?: number): void
```

#### `verify.isEmpty()` — Check that a shape is empty.

```ts
verify.isEmpty(label: string, shape: ShapeLike, message?: string): void
```

#### `verify.notEmpty()` — Check that a shape is NOT empty.

```ts
verify.notEmpty(label: string, shape: ShapeLike, message?: string): void
```

#### `verify.volumeApprox()` — Check that a shape's volume is approximately equal to expected (mm³).

```ts
verify.volumeApprox(label: string, shape: ShapeLike, expected: number, tolerance?: number): void
```

#### `verify.areaApprox()` — Check that a shape's surface area is approximately equal to expected (mm²).

```ts
verify.areaApprox(label: string, shape: ShapeLike, expected: number, tolerance?: number): void
```

#### `verify.boundingBoxSize()` — Check that a shape's bounding box has approximately the given size.

```ts
verify.boundingBoxSize(label: string, shape: ShapeLike, expectedSize: [ number, number, number ], tolerance?: number): void
```

#### `verify.edgeContinuity()` — Check that every sampled seam on a shape meets a requested continuity threshold.

```ts
verify.edgeContinuity(label: string, shape: ShapeLike, options?: EdgeContinuityThresholds): void
```

**`EdgeContinuityThresholds`**: `continuity?: SurfaceContinuity`, `samples?: number`, `positionTolerance?: number`, `tangentToleranceDeg?: number`, `curvatureTolerance?: number`

#### `verify.noTinyEdges()` — Check that a shape has no tiny edges below the requested threshold.

```ts
verify.noTinyEdges(label: string, shape: ShapeLike, threshold?: number): void
```

#### `verify.noSliverFaces()` — Check that a shape has no sliver faces below the requested score threshold.

```ts
verify.noSliverFaces(label: string, shape: ShapeLike, threshold?: number): void
```

#### `verify.noSelfIntersection()` — Best-effort exact-shape validity guard for self-intersections or broken B-Rep topology.

```ts
verify.noSelfIntersection(label: string, shape: ShapeLike): void
```

#### `explodeView()` — Configure how the viewport explode slider offsets returned objects.

Offsets are resolved from the returned object tree, not a flat list. In `radial` mode each node follows its parent branch direction, then fans locally from the immediate parent center — nested assemblies peel apart level by level. In fixed-axis or fixed-vector modes, the branch follows that axis/vector but nested descendants fan out perpendicular by default.

Multiple calls merge — later values override earlier ones on a per-key basis. `byName` and `byPath` maps are merged entry-by-entry.

For programmatic explode applied before returning (without the slider), use `lib.explode()` instead.

```js
explodeView({
  amountScale: 1.2,
  stages: [0.35, 0.8],
  mode: 'radial',
  byPath: { 'Drive/Shaft': { direction: [1, 0, 0], stage: 1.6 } },
});
```

```ts
explodeView(options?: ExplodeViewOptions): void
```

**`ExplodeViewOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `enabled?` | `boolean` | Set false to disable viewport explode offsets for this script output. |
| `amountScale?` | `number` | Scales the UI explode amount. Default: 1 |
| `stages?` | `number[]` | Per-depth stage multipliers (depth 1 = first level). If depth exceeds this array, the last value is reused. Default when omitted: reciprocal depth (1, 1/2, 1/3, ...) |
| `mode?` | `ExplodeViewDirection` | Global direction mode fallback. Default: 'radial' |
| `axisLock?` | `ExplodeAxis` | Global axis lock fallback. |
| `byName?` | `Record<string, ExplodeViewDirective>` | Per-object overrides by final object name. |
| `byPath?` | `Record<string, ExplodeViewDirective>` | Per-tree-path overrides using slash-separated object tree segments. |

**`ExplodeDirective`**
- `stage?: number` — Multiplier applied to `amount` for this node
- `direction?: ExplodeDirection` — Direction mode for this node
- `axisLock?: ExplodeAxis` — Optional axis lock after direction is resolved

#### `cutPlane()` — Define a named section plane for inspecting internal geometry.

Registers a cut plane that appears as a toggle in the viewport View Panel. When enabled, geometry on the positive side of the plane (the side the normal points toward) is clipped away, revealing the internal cross-section. The newly exposed section faces render with a hatched overlay; pre-existing coplanar boundary faces are left unhatched.

Planes are registered once per script run. The viewport toggle state (on/off) persists across parameter changes without re-running the script. The `exclude` option only works correctly when the excluded object names are stable across parameter changes.

Accepts two overloads: `cutPlane(name, normal, offset?, options?)` or `cutPlane(name, normal, options?)` where options may include `offset`.

```js
const cutZ = param('Cut Height', 10, { min: -50, max: 50, unit: 'mm' });
cutPlane('Inspection', [0, 0, 1], cutZ, { exclude: ['Probe', 'Fasteners'] });
```

Overloads:

- `cutPlane(name: string, normal: [ number, number, number ], offset?: number, options?: CutPlaneOptions): void`
- `cutPlane(name: string, normal: [ number, number, number ], options?: CutPlaneOptions): void`

**`CutPlaneOptions`**
- `offset?: number` — Optional offset along the plane normal (primarily for object-form overload).
- `exclude?: CutPlaneExcludeInput` — Object names to keep uncut for this plane.

#### `compareWith()` — Declare a reference model for comparison inspection.

`compareWith()` lets a model carry its own comparison target for inspection workflows. `forgecad inspect compare overlay model.forge.js` uses this reference to render the same Difference Only comparison overlay as the live viewport. Amber marks candidate mismatch evidence, cyan marks reference mismatch evidence, and faint model context keeps the overlay readable. When the CLI can resolve the referenced file, the manifest also includes the same geometric score produced by `forgecad compare 3d`.

The path is resolved relative to the file that calls `compareWith()`. It may point to another `.forge.js` file or an imported CAD asset such as `.stl`, `.obj`, `.3mf`, `.step`, or `.stp`.

```js
compareWith('./reference.3mf', { align: 'center', toleranceMm: 0.25, samples: 3000 });
return rebuiltBearing;
```

```ts
compareWith(path: string, options?: CompareWithOptions): void
```

**`CompareWithOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `align?` | `CompareAlignMode` | Candidate alignment before scoring. Defaults to no automatic alignment. |
| `toleranceMm?` | `number` | Distance tolerance in model units for coverage scoring. Defaults to the comparison scorer's auto tolerance. |
| `samples?` | `number` | Surface samples per direction for numeric scoring. Defaults to the comparison scorer's standard sample count. |
| `label?` | `string` | Human label for the reference model in inspection manifests. |

#### `mock()` — Register a mock (context) object for visualization and inspection.

Mock objects appear in the viewport and inspection analysis when you run a file directly, but are excluded when the file is imported via `require()`. This lets you model the surrounding context — walls, bolts, mating parts — without polluting the module's exports.

The shape is returned unchanged, so you can reference it for alignment, dimensioning, and `verify` checks.

Mock objects participate in focused inspection commands such as `forgecad inspect fit interference` and `forgecad inspect physical gaps`. Their names appear with a `(mock)` suffix in reports.

In the viewport, mock objects render at reduced opacity so they are visually distinct from real geometry.

```ts
// bracket.forge.js
const wall = mock(box(100, 200, 10).translate(0, 0, -5), "wall");
const bolt = mock(cylinder(3, 15).translate(10, 15, 0), "bolt");

const bracket = box(20, 30, 5);
verify.notColliding("bracket vs wall", bracket, wall);

return bracket;
// When imported: only bracket is exported
// When run directly: bracket + wall + bolt all visible
```

```ts
mock<T extends Shape>(shape: T, name?: string): T
```

#### `scene()` — Configure the scene environment for the current script execution.

Controls camera position, named render views, optional model journeys, lighting rig, background color or gradient, atmospheric fog, environment maps, post-processing effects, and capture parameters for the `forgecad capture` command. Multiple calls merge — later values override earlier ones on a per-key basis, so you can split configuration across multiple `scene()` calls.

When `lights` is specified, **all** default lights are removed. You must include your own ambient light or the scene will be fully dark.

Setting `camera.position` overrides auto-framing — the viewport will no longer auto-fit the geometry on script reload.

Named render views let scripts check in repeatable cameras next to the model code. The canonical shape is `{ camera: { position, target } }`, and a direct camera shorthand `{ position, target }` is also accepted. Use the canonical shape when you may add view metadata later. Use it from the CLI with `--view hero` on `forgecad render 3d`, `forgecad render hq`, or `forgecad capture`.

Model journeys let scripts check in a compact guided path through named objects. Each journey has ordered `steps`; each step can name a `focus` target by object name/tree path, provide a caption, and optionally provide an explicit camera. In the viewer, journeys are opt-in: they appear as a small Explore control and do not move the camera until the user starts them. Use `forgecad run model.forge.js --journeys` or `--journeys-json` to inspect resolved targets.

Post-processing effects (`bloom`, `vignette`, `grain`) work in the browser viewport only. The CLI applies camera, lights, background, fog, and `toneMappingExposure` but skips shader effects.

All numeric values accept `param()` expressions.

```js
scene({
  background: { top: '#000814', bottom: '#001d3d' },
  camera: { position: [160, -120, 100], target: [0, 0, 50], fov: 52 },
  views: {
    hero: {
      camera: { position: [180, -140, 90], target: [0, 0, 25], up: [0, 0, 1], fov: 38 },
    },
    side: { position: [240, 0, 70], target: [0, 0, 25], fov: 34 },
  },
  journeys: {
    grandTour: {
      title: 'Grand Tour',
      startsAt: 'overview',
      steps: [
        { id: 'overview', focus: 'Solar System', caption: 'Start with the whole model.' },
        { id: 'earth', focus: 'Earth', caption: 'Fit and inspect Earth.' },
      ],
    },
  },
  lights: [
    { type: 'ambient', color: '#001233', intensity: 0.08 },
    { type: 'point', position: [120, -80, 130], color: '#00f5d4', intensity: 4, distance: 400, decay: 1 },
    { type: 'point', position: [-100, 60, 20], color: '#f72585', intensity: 3, distance: 350 },
    { type: 'directional', position: [50, -30, 200], color: '#ffd60a', intensity: 1.2 },
    { type: 'hemisphere', skyColor: '#003566', groundColor: '#000814', intensity: 0.2 },
  ],
  fog: { color: '#000814', near: 100, far: 450 },
  postProcessing: {
    bloom: { intensity: param('bloom', 1.5, 0, 4), threshold: 0.5, radius: 0.7 },
    vignette: { darkness: 0.8, offset: 0.25 },
    grain: { intensity: 0.08 },
    toneMappingExposure: param('exposure', 1.5, 0.5, 4),
  },
});
```

```ts
scene(options: SceneOptions): void
```

**`SceneOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `capture?` | `SceneCaptureConfig` | Default capture parameters for `forgecad capture` — CLI flags override these. |
| `background?`, `camera?`, `views?`, `journeys?`, `lights?`, `environment?`, `fog?`, `postProcessing?`, `ground?` | | — |

`SceneBackgroundGradient`: `{ top: string, bottom: string }`

**`SceneCameraConfig`**: `position?: [ number, number, number ]`, `target?: [ number, number, number ]`, `up?: [ number, number, number ]`, `fov?: number`, `type?: "perspective" | "orthographic"`

**`SceneJourneyConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `title?` | `string` | Viewer-facing journey title. Defaults to the journey id. |
| `startsAt?` | `string` | Optional starting step id. Defaults to the first step. |
| `behavior?` | `"opt-in" \| "auto"` | Whether the viewer should offer or auto-open the journey. First slice supports opt-in. |
| `steps` | `SceneJourneyStepConfig[]` | Ordered journey spine. Branches can be added later without changing this core contract. |
| `valid?` | `boolean` | True unless any journey or step diagnostic has level "error". |

**`SceneJourneyStepConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `id` | `string` | Stable step id used by viewer links and Next/Back state. |
| `title?` | `string` | Viewer-facing title. Defaults to the step id. |
| `focus?` | `string` | Object name or slash-separated tree path to focus. |
| `caption?` | `string` | Short optional viewer caption. |
| `camera?` | `SceneViewCameraConfig` | Optional explicit camera for this step. When omitted, the viewer fits `focus`. |
| `resolvedFocusId?` | `string \| null` | Resolved object id after script execution, when `focus` matched exactly one object. |
| `resolvedFocusPath?` | `string \| null` | Resolved object tree path or name after script execution. |

**`SceneLightConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `target?` | `[ number, number, number ]` | Target for directional/spot lights |
| `groundColor?` | `string` | Ground color for hemisphere lights |
| `skyColor?` | `string` | Sky color alias for hemisphere lights (same as color) |
| `angle?` | `number` | Spot light cone angle in radians |
| `penumbra?` | `number` | Spot light penumbra (0–1) |
| `decay?` | `number` | Point/spot light decay |
| `distance?` | `number` | Point/spot light distance (0 = infinite) |
| `castShadow?` | `boolean` | Whether this light casts shadows |
| `type`, `color?`, `intensity?`, `position?` | | — |

**`SceneEnvironmentConfig`**
- `preset?: "studio" | "sunset" | "dawn" | "warehouse" | "forest" | "apartment" | "lobby" | "city" | "park" | "night" | "none"` — Built-in preset name or 'none' to disable
- `intensity?: number` — Environment map intensity
- `background?: boolean` — Use environment map as scene background

**`SceneFogConfig`**
- `near?: number` — Linear fog near distance
- `far?: number` — Linear fog far distance
- `density?: number` — Exponential fog density (if set, uses FogExp2 instead of linear Fog)
- Also: `color?: string`

`ScenePostProcessingConfig`: `{ bloom?: SceneBloomConfig, vignette?: SceneVignetteConfig, grain?: SceneGrainConfig, toneMappingExposure?: number }`

`SceneBloomConfig`: `{ intensity?: number, threshold?: number, radius?: number }`

`SceneVignetteConfig`: `{ darkness?: number, offset?: number }`

`SceneGrainConfig`: `{ intensity?: number }`

**`SceneGroundConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `visible?` | `boolean` | Show a ground plane |
| `color?` | `string` | Ground color |
| `offset?` | `number` | Offset below the model's bounding box minimum Z. Default 0 (flush with model bottom). |
| `receiveShadow?` | `boolean` | Receive shadows on the ground |

**`SceneCaptureConfig`**

| Option | Type | Description |
|--------|------|-------------|
| `framesPerTurn?` | `number` | Frames for one full orbit rotation (default: 72) |
| `holdFrames?` | `number` | Frozen frames before motion starts (default: 6) |
| `pitchDeg?` | `number` | Orbit pitch angle in degrees (default: auto from camera) |
| `fps?` | `number` | Output frame rate (default: 24) |
| `size?` | `number` | Output frame size in pixels (default: 960) |
| `background?` | `string` | Canvas background color for capture (default: '#252526') |

#### `showLabels()` — Highlight all user-labeled faces on a shape for visual debugging.

Shows each user-authored label name in the viewport for visual debugging. Returns the shape unchanged for chaining: `return showLabels(myShape)`.

```ts
showLabels(shape: Shape): Shape
```

#### `viewConfig()` — Configure viewport helper visuals for the current script execution.

Controls renderer-only overlays that appear in the viewport but are not part of the geometry. Currently supports the joint overlay that renders axis arrows and arc indicators when joint controls are active. Multiple calls merge — later values override earlier ones per key.

This does **not** trigger a geometry recompute; it only affects the visual helpers drawn on top of the 3D scene.

```js
viewConfig({
  jointOverlay: {
    axisColor: '#13dfff',
    arcColor: '#ff7a1a',
    axisLineRadiusScale: 0.03,
    arcLineRadiusScale: 0.022,
  },
});
```

```ts
viewConfig(options?: ViewConfigOptions): void
```

#### `spec()` — Create a named, reusable bundle of verification checks.

A spec groups related `verify.*` calls under a collapsible header in the Checks panel. This makes large check suites scannable. Specs can be applied to multiple shapes and can check relationships between parts.

Specs can be defined in separate `.forge.js` files and imported via `require()` to share them across models.

`spec.check()` returns a `SpecResult` — you can inspect it programmatically or ignore the return value and let the Checks panel show results.

```ts
const printable = spec("Fits printer bed", (shape) => {
  verify.notEmpty("Has geometry", shape);
  const bb = shape.boundingBox();
  verify.lessThan("Width  < 220mm", bb.max[0] - bb.min[0], 220);
  verify.lessThan("Depth  < 220mm", bb.max[1] - bb.min[1], 220);
  verify.lessThan("Height < 250mm", bb.max[2] - bb.min[2], 250);
});

// Reuse on multiple shapes
printable.check(bracket);
printable.check(standoff);

// Check relationships between parts
const fitSpec = spec("Assembly fit", (partA, partB) => {
  verify.notColliding("No interference", partA, partB, 10);
});
fitSpec.check(bracket, standoff);
```

**Spec-first workflow:** Write specs before building geometry. Checks go from red to green as you build — effectively TDD for CAD.

```ts
spec(name: string, checkFn: (...args: any[]) => void): Spec
```

**`Spec`**
- `name: string` — The display name of this spec

---

## C15: Import & Composition

Bring external geometry or other ForgeCAD modules into the current script.

#### `group()` — Group multiple shapes/sketches for joint transforms without merging into a single mesh.

Unlike union(), child colors and individual identities are preserved. Children can be plain shapes, named descriptors ({ name, shape/sketch/group }), or nested groups. The returned ShapeGroup supports all Shape transforms (translate, rotate, etc.).

Named descriptors can include `tags` for viewport organization. Tags do not affect geometry; they let the command palette hide, show only, or focus all objects with the same tag.

**Local coordinate pattern:** Build child parts at the origin (local coordinates), then group and translate once to place the whole assembly. This eliminates the error-prone pattern of manually adding parent offsets to every sub-part.

```js
const body = roundedBox(100, 20, 32, 4);
const panel = box(98, 2, 18).translate(0, -12, 4);
const louver = box(88, 2, 6).translate(0, -14, -11);
const indoorUnit = group(
  { name: 'Body', shape: body },
  { name: 'Panel', tags: 'cover', shape: panel },
  { name: 'Louver', tags: ['cover', 'moving'], shape: louver },
).translate(0, -18, 70);
```

```ts
group(...items: GroupInput[]): ShapeGroup
```

---

## C16: Part Library

Pre-built parametric parts accessible via `lib.*`.

#### `Wood.board()` — Create a wood board with metadata for manufacturing.

The board is a box(width, height, thickness) centered on XY, base at Z=0. Width along X, height along Y, thickness along Z (0 to thickness).

```ts
Wood.readonly board: (width: number, height: number, thickness: number, opts?: WoodBoardOptions) => WoodBoard
```

**`WoodBoardOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `species?` | `string` | Wood species, e.g. "birch", "oak", "plywood". Default: "wood" |
| `material?` | `string` | Material description for BOM, e.g. "birch plywood". Default: species value |
| `grain?` | `string` | Grain direction: "long" (along width) or "cross" (along height). Default: "long" |
| `color?` | `string` | Color hex string for visualization. Default: "#d2b48c" (tan/wood) |
| `autoBom?` | `boolean` | If false, skip automatic BOM registration. Default: true |

#### `Wood.dado()` — Cut a dado (channel) across the face of a host board for a guest board to sit in.

Returns a new host board with the dado cut applied.

```ts
Wood.dado(host: WoodBoard, guest: WoodBoard, opts: DadoOptions): WoodBoard
```

**`DadoOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `fromBottom?` | `number` | Distance from the bottom edge of the host to the bottom of the channel (mm). |
| `fromTop?` | `number` | Distance from the top edge of the host to the top of the channel (mm). Alternative to fromBottom. |
| `depth?` | `number` | Channel depth into the board thickness (mm). Default: 1/3 of host thickness. |
| `fit?` | `"friction" \| "snug" \| "slip"` | Fit tolerance. Default: 'snug'. |
| `stopped?` | `number` | If set, the dado stops this far from the front edge (mm), creating a stopped dado. |

#### `Wood.rabbet()` — Cut a rabbet (L-shaped step) along an edge of a board.

Returns a new board with the rabbet cut applied.

```ts
Wood.rabbet(board: WoodBoard, opts: RabbetOptions): WoodBoard
```

**`RabbetOptions`**
- `edge: "top" | "bottom" | "left" | "right" | "back"` — Which edge to cut the rabbet on.
- `width: number` — How far into the board face the rabbet extends (mm).
- `depth: number` — How deep the step is cut into the thickness (mm).

#### `Wood.mortiseAndTenon()` — Cut a mortise in one board and shape a tenon on another.

Returns new boards with the mortise pocket and tenon cuts applied.

```ts
Wood.mortiseAndTenon(mortiseBoard: WoodBoard, tenonBoard: WoodBoard, opts?: MortiseAndTenonOptions): MortiseAndTenonResult
```

**`MortiseAndTenonOptions`**

| Option | Type | Description |
|--------|------|-------------|
| `style?` | `"blind" \| "through"` | 'blind' (default): mortise doesn't go through. 'through': mortise goes all the way. |
| `position?` | `{ fromTop?: number; fromBottom?: number; }` | Position of the mortise center along the mortise board height. |
| `tenonThickness?` | `number` | Tenon thickness (mm). Default: 1/3 of tenon board thickness. |
| `tenonWidth?` | `number` | Tenon width (mm). Default: 60% of tenon board height. |
| `tenonLength?` | `number` | Tenon length (mm). Default: 2/3 of mortise board thickness for blind, full for through. |
| `cornerRadius?` | `number` | Corner radius for mortise (mm). Default: 0 (square corners, hand tools). |
| `fit?` | `"friction" \| "snug" \| "slip" \| "knockdown"` | Fit tolerance. Default: 'snug'. |

`MortiseAndTenonResult`: `{ mortiseBoard: WoodBoard, tenonBoard: WoodBoard }`

---
