# BaroCSS CAD — SDK & Developer Context > Pure-TypeScript B-rep CAD kernel, editable document model, React JSX/SDK components (``, ``), WebGPU renderer, and review SDK. --- # @barocss/cad The CAD kernel. It is a boundary-representation (B-rep) modeller with NURBS curves and surfaces, written in TypeScript, with no WebAssembly and no external geometry library. The studio, the document model and the agent's tools all run on it. - **Exact surfaces.** Planes, cylinders, cones, tori and B-spline surfaces stay exact through Booleans, fillets and offsets. - STEP is written from them. - Mass properties are integrated over them. The few curved bodies the quadrature can't integrate fall back to the tessellation, and their result says so (`method: 'tessellated'`), with an error bound. - **Stable names.** A part is a list of features. Faces are named by the feature and role that made them, such as `p.top` or `h.side0`. Those names are kept through every later feature, and through parameter edits that keep the topology. - **Correct or refused.** An operation gives a valid body, or a `CadPartError` saying why it can't. It doesn't return an approximate body. See [B-rep, robustness and refusals](/packages/cad/robustness). - **Meshes too.** Imported STL, OBJ and tessellated STEP bodies are faceted B-reps, with their own Booleans, holes and splits. ## Status and install Use `@barocss/cad` from the repository workspace. - **From the repository.** Use it from a checkout, as a workspace package. - **TypeScript sources.** Its entry point is the TypeScript source itself (`./src/index.ts`). Use it with a bundler or a TypeScript-aware runtime; there is no build step to run first. - **Two entry points.** - `@barocss/cad` is the core: the part document, its evaluation, and everything else the kernel does. - `@barocss/cad/api` is the [object facade](/packages/api) over it, for writing parts in code. ```js import { part } from '@barocss/cad/api'; // the object facade import { evaluateCadPart, CadPartError, checkOutput, reevaluate, massPropertiesOf } from '@barocss/cad'; // the core: the part document and its evaluation ``` ## A part in code A part is a JSON document: its units, its parameters, and its features in order. The facade's `part()` writes one, verb by verb, and `.doc` is the document. `evaluateCadPart` evaluates a document and returns a snapshot. Its `outputs` are the bodies no later feature consumes. ```js // A 60 × 40 × 8 plate with a Ø8 hole through it. const plate = part('plate') .box({ w: 60, d: 40, h: 8 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 30, y: 20 }); const doc = plate.doc; // the part document: its features in order assert.deepEqual(doc.features.map(f => [f.id, f.kind]), [['sketch1', 'sketch'], ['extrude1', 'extrude'], ['hole1', 'hole']]); const snapshot = evaluateCadPart(doc); // what the facade evaluates const [body] = snapshot.outputs; // the parts no later feature consumes ``` The facade gives the results as plain data, in millimetres and grams. Each output of the snapshot also checks itself: ```js const mass = plate.mass({ density: 2.7 }); // aluminium: mm³, g, mm, g·mm² assert.ok(Math.abs(mass.volume - (60 * 40 * 8 - Math.PI * 16 * 8)) < 1e-6); assert.ok(Math.abs(mass.mass - mass.volume * 2.7e-3) < 1e-9); assert.equal(checkOutput(body).valid, true); // strict B-rep validity, on the core's output assert.match(plate.step(), /^ISO-10303-21;/); const stl = plate.stl(); // binary STL of the display tessellation assert.equal(stl.length, 84 + 50 * new DataView(stl.buffer, stl.byteOffset).getUint32(80, true)); ``` These samples run in `apps/library-docs` (`pnpm test:samples`), against the package's sources. ## Where next - [Modeling API](/packages/cad/modeling): the part document, evaluating, outputs and tessellation. - [B-rep, robustness and refusals](/packages/cad/robustness): what the kernel guarantees, and what it refuses. - [Exchange formats](/packages/cad/formats): STEP, IGES, STL and DXF. - [@barocss/cad-model](/packages/cad-model/): the studio's document model on top of the kernel. --- # Modeling API ## The part document A part is a `barocss-cad-part` document: ```json { "format": "barocss-cad-part", "version": 1, "units": "mm", "parameters": { "t": 8 }, "features": [ { "id": "s", "kind": "sketch", "profile": "rectangle", "min": [0, 0], "max": [60, 40] }, { "id": "p", "kind": "extrude", "sketch": "s", "height": { "parameter": "t" } } ] } ``` - **Features in order.** Each feature has an `id` and a `kind`, and names the features it builds on by their ids: `sketch`, `target`, `tool`. - **Dimensions.** A dimension is a number, or `{ "parameter": "name" }` bound to one of the document's parameters. - **Units.** Lengths are millimetres. Public and document angles are degrees. Z is up. - **The reference.** The full set of kinds and their fields is the `CadPartFeature` type, which the package exports. Sketch profile points use local XY coordinates. Without `plane`, these are part XY at Z = 0. With `plane`, local X follows `xAxis`, local Y follows `normal × xAxis`, and local Z follows `normal`, from `origin`. An `extrude` runs from local Z = `from` (default 0) to `from + height`; these are offsets along the sketch normal. A negative `height` extrudes in the opposite direction. Zero height is refused. The kinds, by family: | Family | Kinds | |---|---| | Sketches and solids from them | `sketch` (rectangle, circle, polygon and loop profiles of lines and arcs, with holes, on a plane), `extrude`, `revolve`, `sweep`, `sweep-curve`, `loft` | | Booleans | `union`, `difference`, `intersect` | | Holes and finishing | `hole`, `thread`, `fillet`, `chamfer`, `draft`, `shell`, `thicken`, `split`, `split-face` | | Copies and moves | `linear-pattern`, `circular-pattern`, `mirror`, `translate`, `rotate`, `scale` | | Meshes and imports | `mesh`, `decimate`, `sew`, `separate`, `import` (a STEP file) | | Smooth shapes | `subd` (a subdivision cage, as exact B-spline faces) | | Sheet metal | `sheet-base`, `sheet-flange`, `sheet-path-flange`, `sheet-bead`, `sheet-perforate`, `sheet-contour`, `sheet-corner-relief` | | Frames and weldments | `frame`, `frame-member`, `gusset`, `end-cap`, `weld-bead` | | Machine elements | `spur-gear`, `spur-rack`, `internal-gear`, `bevel-gear`, `worm`, `worm-wheel`, `shaft`, `key`, `keyway`, `pin`, `retaining-ring`, `bearing`, `oring`, `oring-gland`, `pulley`, `sprocket`, `belt`, `spring`, `cam`, `coupling`, `connector-body`, `connector-opening` | ### Names - **Faces.** A face is named `.`, for example `p.top`, `p.side0` or `h.side0`. - **Splits and copies.** When a later feature splits a face, its pieces are `#k`. Copies are `@k` (patterns) and `@m` (kept mirrors). - **Edges.** An edge is named by its two faces: `p.side0|p.top`. - **References.** A feature's `id` means all of its parts, and `id/k` means part `k`, one side of a split. Fillets and chamfers pick edges by these names, so a selection survives parameter edits that keep the topology. ### Boolean algorithms `union`, `difference` and `intersect` select solid material from a target and a tool. Their implementation depends on the input representation: height-wise 2D arrangements, rational polyhedral operations, trimmed-surface intersections, or a mixed mesh path. See [Boolean operations](/packages/cad/robustness#boolean-operations) for a tested example, the algorithm stages, tolerances and refusal conditions. ## Evaluating ```ts evaluateCadPart(document, previous?, options?): CadPartSnapshot loadCadPart(text): CadPartSnapshot // JSON text, at most 4 MiB emptyCadPart(): CadPartDocument ``` A snapshot holds: - `outputs`: the parts no later feature consumes, in feature order. `outputOf(snapshot, id)` gets one by id. - `features`: each feature's id, kind and dependencies. - `recomputation`: the features computed in this evaluation, and those reused unchanged. Snapshots and outputs are plain data. Import these functions from `@barocss/cad`: - `reevaluate(snapshot, { parameters: edits })`: evaluates new parameter values and reuses unchanged features. - `reevaluate(snapshot, { document })`: evaluates another document and reuses unchanged features. - `saveCadPart(snapshot)`: returns the document as text. ```js const thicker = reevaluate(first, { parameters: { t: 10 } }); assert.ok(Math.abs(massPropertiesOf(thicker.outputs[0], 2.7).volume - 60 * 40 * 10) < 1e-6); assert.deepEqual(thicker.recomputation.evaluated, ['p']); // only the extrude ran again ``` ## Outputs Each output is one body, or several with `bodyCount`, as a B-rep (`brep`). - **Representation.** It is one of: - `upright`: a Z-prismatic solid, with closed-form mass; - `planar`; - `curved`; - `faceted`: a mesh body. - **Mass properties.** `massPropertiesOf(output, density)` takes density in g/cm³ and returns: - `volume` in mm³, `mass` in g and `centroid` in mm; - `inertia` in g·mm², about the centroid; - `method`: `closed-form`, `planar-exact`, `quadrature` or `tessellated`. A tessellated result carries `volumeBound`, its estimated volume error in mm³. - **Validity.** `checkOutput(output)` gives the strict validity report: `valid`, the first `issues`, the counts and topology, and the largest gaps. - **Surface area.** `surfaceAreaOf(output)` is in mm², over the exact surfaces. - **STEP.** `exportStep(output, { name })` writes the exact B-rep as STEP AP214. - **STL.** `exportStl(output, { segmentsPerQuarter })` writes the display tessellation as binary STL. - **Sheet metal.** `flatPatternOf(output, { fixedFace, kFactor })` returns a sheet-metal flat pattern. - **Reports.** Gears, racks and other generated parts carry a report of their own, such as `gear`. ### Moment of inertia about an axis Import `momentOfInertiaAboutAxis` and the `MassInertiaAxis` type from `@barocss/cad`. The function takes mass properties and an axis, and returns a number in g·mm². Supply a full 3 × 3 inertia tensor about the centre of mass in g·mm², positive finite mass in g and the centroid in mm. The axis requires a `point` in mm and a finite, nonzero `direction`. Use dense arrays of finite numbers: three components per vector and three rows of three for the tensor. Use the same XYZ frame for the axis and mass properties. The function normalizes the direction, so its magnitude does not change the axis. With unit direction `u` and offset `d = centroid − point`, the result is `uᵀ I_COM u + mass × |d × u|²`. The second term shifts the moment from the parallel axis through the centre of mass to the requested line. Invalid input arrays, non-finite arithmetic or a negative central inertia projection give `SOLID_MASS`. This query uses the supplied mass properties; it provides no frame or SI conversion, B-rep evaluation, motion simulation or physical validation. ### A numerical unit check For a 10 × 10 × 10 mm cube at density 2.7 g/cm³: - Volume is 1000 mm³. - Mass is 1000 × 2.7 / 1000 = 2.7 g. - The centroid is [5, 5, 5] mm. - Each diagonal centroidal inertia is 2.7 × (10² + 10²) / 12 = 45 g·mm². Off-diagonal terms are zero. The kernel already returns these units. Do not convert its mass or inertia a second time. ```js const snapshot = evaluateCadPart(cube); const body = outputOf(snapshot, 'p'); const result = massPropertiesOf(body, 2.7); // density g/cm³ near(result.volume, 1000); // mm³ near(result.mass, 2.7); // g result.centroid.forEach(value => near(value, 5)); // mm result.inertia.forEach((row, i) => row.forEach((value, j) => near(value, i === j ? 45 : 0))); // g·mm² ``` ## Tessellation The display mesh, and the STL written from it, is a tessellation of the exact surfaces. `segmentsPerQuarter` sets how finely curves are divided. Measurements and STEP never use the tessellation, except for a `tessellated` mass result. --- # B-rep, robustness and refusals ## Booleans, fillets and offsets on exact surfaces Each solid output is a B-rep: surfaces, boundary curves and the topology that joins them. Native faces retain their surfaces; mesh inputs retain faceted faces. The Boolean algorithm depends on that representation. - **Booleans.** `union`, `difference` and `intersect` use a prismatic, polyhedral, analytic or mixed mesh path, as described below. - **Fillets and chamfers** roll a ball along the named edges, or cut them back, on the exact faces either side. - **Offsets.** `shell`, `thicken` and `draft` offset or tilt faces on their surfaces. In a kernel part document, `draft` accepts `pull: 'x'`, `'y'`, `'z'`, `'-x'`, `'-y'` or `'-z'` for a signed world coordinate axis. Omitting `pull` selects +Z. A positive `angle` leans into the material; a negative angle leans out. `neutral` is the plane's coordinate in mm on the selected world X, Y or Z axis, not a distance from the picked face. If omitted, it uses the body's minimum coordinate for a positive pull or maximum coordinate for a negative pull. Do not negate an explicit `neutral` value just because the pull axis is negative. Arbitrary pull vectors remain unsupported. These axis choices do not establish general curved-face support or manufacturing validation. For the standalone `kind: 'draft'` feature, `angle` must be finite and satisfy `0 < |angle| < 45` degrees; otherwise it gives `INPUT`. The neutral plane must be at or below the entire selected face for a positive pull, or at or above it for a negative pull, within the existing 1e-6 mm plane tolerance. The face must extend a positive distance from that plane along the pull direction; violations of these placement or height conditions give `SELECTION`. ### Mesh conversion values `brepFromTriangles` creates its own planar faces. It fixes properties on the returned B-rep, face and surface records, plus the face list and knot arrays. Record properties such as `edges`, `vertices`, `controlPoints` and `weights` cannot be rebound. The remaining nested data, including coordinate and weight arrays, is not frozen by this step. The input positions and indices are not frozen. Create a deep copy before changing its face, degree or knot structure, for example with `structuredClone(brep)`. A shallow copy can still share the fixed records and knot arrays. Copies and transforms are checked independently. Existing numeric caches treat a B-rep as a value; use a new value after editing coordinates too. The fixed structure lets the kernel exclude this mesh conversion from one specific boundary check without reading every face again. It does not certify its geometry, mass or general surface bindings. Caller-created B-reps and faceted patches retain their existing ownership. A separate exact lower-bound check rejects a supported extruded piecewise-linear graph when a straight incident edge is proved farther from the surface than its declared tolerance. Other surface families keep their existing checks. ### A draft calculated from its dimensions Calculated geometry; the diagram is not an API render. Start with a rectangle from `[0, 0]` to `[20, 20]` mm and extrude it 10 mm along +Z. The box occupies `0 ≤ x ≤ 20`, `0 ≤ y ≤ 20`, `0 ≤ z ≤ 10`. Its initial volume is 4000 mm³. The sketch has ID `s`, its extrusion has ID `e`, and the draft has its own ID `d`. The draft's `target: 'e'` selects the extrusion to modify; `faces: ['e.side0']` selects one of its faces. This is a kernel part-document input, not a new Studio control. ```json { "format": "barocss-cad-part", "version": 1, "units": "mm", "parameters": {}, "features": [ { "id": "s", "kind": "sketch", "profile": "rectangle", "min": [0, 0], "max": [20, 20] }, { "id": "e", "kind": "extrude", "sketch": "s", "height": 10 }, { "id": "d", "kind": "draft", "target": "e", "faces": ["e.side0"], "angle": 10, "pull": "z", "neutral": 0 } ] } ``` The extrusion consumes sketch `s`; the draft consumes extrusion `e`. The final solid output is `d`, not a second independent copy of `e`. The first rectangle edge runs from `[0, 0]` to `[20, 0]`, so `e.side0` is the face at y = 0 with outward normal −Y. The positive draft removes material: the upper edge moves toward +Y, into the box. X coordinates do not change. ![Calculated Y–Z section, not an API result](/diagrams/cad/draft-section.svg) For the ideal neutral plane z = 0, the drafted face is `y = z tan(10°)`. At z = 10 mm, its inward movement is `10 tan(10°) ≈ 1.763270 mm`. The remaining top width along Y is about 18.236730 mm. The removed triangular prism has volume `½ × 10 × 1.763269807 × 20 ≈ 176.326981 mm³`. The nominal remaining volume is about 3823.673019 mm³. These are calculated values, not values returned by an API call. The implementation shifts the cutting plane slightly below the specified neutral plane to avoid line-only contact. Here `R = √(20² + 20² + 10²) + 2 = 32 mm` and `lift = 10⁻⁶ R = 0.000032 mm`. Its cutting plane therefore follows `y = (z + 0.000032) tan(10°)`, not exactly the ideal hinge line. The source plane predicts about 0.000005642 mm inward movement at z = 0 and 1.763275450 mm at z = 10. Integrating this shifted plane gives about 3823.671891 mm³ before Boolean and numerical effects. Both volumes are analytical calculations. An evaluated kernel result also includes Boolean and numerical effects. The selected face must be planar, parallel to the pull direction and have no holes. This example changes only one face. It does not claim support for adjacent selected draft faces, arbitrary pull vectors or negative pull axes. ## Guided conic lofts A `loft` document feature can use one `guide` with `kind: 'quadratic-bezier'` and exactly three world-space `controlPoints`, in mm. Each section must be a full circle or an inline ellipse. Use exactly two explicit frames with identical `xAxis` and `yAxis`, and positive separation along their common normal. Put `guide` on the `loft` feature beside `id`, `kind` and `sections`. Each section needs its own `frame` with `origin`, `xAxis` and `yAxis`. The axes must be perpendicular unit vectors. For a circle, use `sketch` to reference an existing circle sketch. For an inline ellipse, use `profile` with `kind: 'ellipse'`, `center` and two positive `radii`. Use either `sketch` or `profile` in each section, never both. These sections do not use `z`. The guide object accepts only `kind` and `controlPoints`. Each control point must contain exactly three finite numbers. The guide starts and ends at the sections' positive local X seams. Both endpoints must match exactly. Its middle control point must lie exactly on the plane halfway between the section planes. The kernel does not snap or project these points. The guide adds a quadratic transverse displacement to each intermediate section. The section stays circular or elliptical, with radii that vary linearly between the caps. The side surfaces retain exact rational conic curves and quadratic control points along the guide. Mass properties use section integrals, not the display mesh. For example, unit circles at Z = 0 and Z = 3 can use guide controls `[[1, 0, 0], [3, 0, 1.5], [1, 0, 3]]`. At the middle section, the circle centre is `[1, 0, 1.5]`. The guide's middle control point is not a point that the curve passes through. This option rejects polygon or mixed profiles, legacy `z` sections, differing frame axes, `smooth: true`, more than two sections, and multiple or general rails. All controls and generated surface controls must remain within the existing modeling coordinate range. ### Candidate: three-section conic lofts A source candidate extends the unguided conic loft to three sections. It is not yet integrated into the product or verified by execution. The two-section guided contract above is unchanged. Each section is a full circle or inline ellipse on an explicit frame. All three frames must have identical `xAxis` and `yAxis`, with positive separation between each adjacent pair of planes. The candidate joins each adjacent pair with ruled sides. Both spans share the middle section's boundary; only the first and last sections have caps, forming one solid rather than two separately capped bodies. The three-section path rejects a guide, `smooth: true`, polygon or mixed profiles, and legacy `z` sections. It does not provide a general multi-section or smooth loft. In particular, adding a third section does not extend the quadratic guide to three sections. ## Boolean operations Let A be the target body and B the tool body. The operation selects the solid material to keep: | Document feature | Object API method | Material kept | |---|---|---| | `union` | `union(tool)` | Material in A or B, counting the overlap once | | `difference` | `subtract(tool)` | Material in A that is outside B; reversing A and B changes the result | | `intersect` | `intersect(tool)` | Material common to A and B | ### From numbers to a solid result Start with a box whose X, Y and Z coordinates each run from 0 to 10 mm. Its six plane boundaries enclose 1000 mm³. The tool is another box, or a cylinder defined by its XY centre, radius and height. Move B along X and choose an operation. The solid view shows the inputs; the XY view shows the material selected by the operation. For the cylinder at its initial centre (8, 5) with radius 3, the wall meets the box's X = 10 plane where `(10 − 8)² + (y − 5)² = 9`: at Y = 5 ± √5, or about 2.764 and 7.236 mm. These crossing points split the boundaries. The inside/outside rule then selects regions, and their 10 mm height turns the selected area into volume. ### Build the result in 3D, one stage at a time Choose a fixed 3D example and an operation below. Start at **Input solids**, then follow the five pictures to the final shape. Drag the large view to rotate it. The same camera direction is used for every picture, so you can compare the cuts. These fixed cases have separate dimensions from the moving section example above. ### A checked code example For two 10 × 10 × 10 mm cubes offset 5 mm along X, the overlap is 5 × 10 × 10 = 500 mm³. The union is 1000 + 1000 − 500 = 1500 mm³; the difference and intersection are each 500 mm³. This example runs with the site's samples and checks the three resulting bodies' validity: ```js import { part as cadPart } from '@barocss/cad/api'; ``` The helper below is an independent volume oracle for these boxes. Their planar display triangles have integer coordinates. Summing signed tetrahedra with integer arithmetic checks the volumes without a floating-point equality test on the mass result. It is not a general volume method for curved bodies or non-integer meshes. ```js // Independent volume check for this integer-coordinate, planar example only. // Each oriented triangle contributes det(a, b, c) / 6, the signed volume to the origin. function integerMeshVolume(p) { let six = 0n; for (const mesh of p.meshes()) { const P = []; for (const x of mesh.positions) { assert.ok(Number.isSafeInteger(x)); P.push(BigInt(x)); } for (let t = 0; t < mesh.indices.length; t += 3) { const a = 3 * mesh.indices[t], b = 3 * mesh.indices[t + 1], c = 3 * mesh.indices[t + 2]; six += P[a] * (P[b + 1] * P[c + 2] - P[b + 2] * P[c + 1]) - P[a + 1] * (P[b] * P[c + 2] - P[b + 2] * P[c]) + P[a + 2] * (P[b] * P[c + 1] - P[b + 1] * P[c]); } } assert.equal(six % 6n, 0n); return Number((six < 0n ? -six : six) / 6n); } ``` ```js const target = cadPart('overlap').box({ w: 10, d: 10, h: 10 }); const tool = p => p.box({ w: 10, d: 10, h: 10, x: 5 }); const joined = target.union(tool); const cut = target.subtract(tool); // the document's difference const common = target.intersect(tool); assert.equal(integerMeshVolume(joined), 1500); assert.equal(integerMeshVolume(cut), 500); assert.equal(integerMeshVolume(common), 500); assert.equal(integerMeshVolume(target), 1000); // the input is unchanged ``` The callback adds the tool to the target's document. Each operation returns a new part. See [Several bodies](/packages/api#several-bodies) for tools by body name and the callback rules. An intersection of disjoint solids is empty. Empty operands keep the set rules: union with empty keeps the other operand, subtracting empty keeps A, and intersection with empty is empty. An empty target minus B stays empty. ## How the kernel chooses the algorithm The part evaluator chooses from the current representations, rather than from the feature's name alone. A rotated or imported body can therefore take a different path from an upright extrusion. | Inputs | Path | |---|---| | Both represented as Z-prismatic solids | Split into height intervals; run a 2D Boolean on each pair of sections | | Both have planar faces with straight edges | Try the exact rational polyhedral Boolean | | Other native B-reps | Intersect surface pairs, split their face domains, classify and stitch the retained pieces | | A mesh target with a native tool | Cut out the mesh region near the tool, process it with the native tool and rejoin the far mesh | The mixed path also handles union and intersection with the mesh on the tool side, by swapping operands. Subtraction keeps operand order. A native target minus a mesh tool, or two mesh operands, instead expands facet faces into planar triangles before the remaining dispatch. This expansion is limited to 16,000 triangles per expanded operand in a normal evaluation; a preview can set a lower limit. Larger cases are refused. ### 1. Z-prismatic solids: Boolean sections, then rebuild the boundary A prismatic solid is a stack of height intervals. Each interval has a constant XY section made of lines and circular arcs, including holes. 1. Collect every bottom and top height from both operands and sort the distinct levels. 2. For each interval between adjacent levels, read A's and B's sections. Run the requested 2D Boolean on them. 3. In the 2D arrangement, split curves at their crossings and merge coincident pieces. Order the directed edges around each vertex, trace regions and propagate winding counts from the outside region. Select regions by the operation. 4. Merge adjacent height intervals with equal sections. Build walls from their boundary curves, and horizontal caps where the section changes. Join shared edges into shells and assign cavity shells to their containing solids. Circular boundaries stay circular. Their intersections can be irrational numbers, so the 2D arrangement uses binary64 arithmetic and the scale-dependent numeric tolerance. This reduction avoids a general 3D surface-intersection search; it does not make every coordinate calculation rational or error-free. Step by step, with figures: [Booleans of upright extrusions](/how/prismatic). ### 2. Planar polyhedra: split, classify and stitch with rational arithmetic This path works on planar faces bounded by straight edges, including non-convex faces, holes and cavities. 1. For each pair of faces that meet, compute the intersection of their planes. Clip that line to both faces to obtain cut segments. Coplanar faces cut each other along their boundary edges. 2. Split each face by its cut segments using a planar arrangement. 3. Classify an interior point of each face piece against the other solid. Ray-crossing parity decides inside or outside; a degenerate ray is retried. Coincident pieces are also classified by their orientation. 4. Keep the pieces selected by the operation. Reverse retained tool-side pieces for subtraction, so cavity walls face the right way. Split T-junctions, join matching edges and form shells. Negative-volume shells become cavities of the smallest containing shell. Coordinates enter as their exact binary64 values, converted to integer fractions with `BigInt`. The polyhedral path uses exact rational predicates and intersections for those values. Results return to stored numeric coordinates; this does not recover precision already lost before the operation. Step by step, with figures: [Exact arithmetic for planar solids](/how/exact-boolean). A nominally planar face rotated in floating-point arithmetic can have corners that are no longer exactly coplanar. Only the `NOT_PLANAR_WITHIN_FLOAT` failure retries the pair through the analytic path. Other polyhedral failures are passed through. ### 3. Curved B-reps: intersect the surfaces and trim their face domains The analytic path retains each face's surface and changes the boundary that trims it. It first rejects face pairs whose bounding boxes do not meet, then computes cuts for the remaining pairs. - Plane/plane and supported plane/cylinder or cylinder/cylinder pairs use their geometric intersection formulas. Their curves can be lines, circles, ellipses or parametrised branches. - General surface pairs use a surface-intersection search. Coarse patch triangles supply candidate starting points. Each point is refined onto both surfaces. A predictor follows the intersection tangent, the cross product of the two surface normals; a Newton corrector returns the point to both surfaces. Tracing continues in both directions until it reaches a domain boundary or closes a loop. - Each cut is mapped into both faces' 2D parameter domains. A plane uses a local plane frame; a cylinder uses angle scaled by radius and axial height; a general surface uses scaled U/V coordinates. The curve arrangement splits each trimmed domain into pieces. - The pieces are classified against the other solid and selected as below. Matching boundary pieces are joined into shells. The code handles coincident surfaces separately, so their boundaries are not kept twice. | Operation | Pieces away from coincident boundaries | |---|---| | Union | Keep each operand's pieces outside the other | | Intersection | Keep each operand's pieces inside the other | | Difference A − B | Keep A's outside pieces and B's inside pieces; reverse B's pieces | For a same-oriented coincident patch, union and intersection retain one copy. Difference removes that shared patch; an oppositely oriented contact on A is handled separately. Tangencies need additional classification and manifold checks. The surface remains a native surface, but a general intersection edge can be a fitted cubic Bézier chain. The path uses binary64 calculations, Newton iteration and numeric tolerances; it is not an exact-arithmetic solution for every NURBS pair. A tighter requested edge fit is checked and can refuse the result; it does not relax topology tolerances. Step by step, with figures: [Booleans of curved solids](/how/boolean). ### 4. Mesh with a native tool: process the nearby mesh For a mesh target with a native tool, the mixed algorithm limits the expensive face operation to the affected region: 1. Split the mesh against a padded box around the tool. Keep the far triangles aside and cap the nearby region for the Boolean. 2. Convert the nearby triangles to planar faces and run the analytic Boolean with the native tool. A normal evaluation admits at most 16,000 nearby mesh triangles; the total mesh can be larger. Open or self-intersecting meshes are refused. 3. Tessellate the nearby result, remove temporary caps and join it to the far mesh. Intersection discards the far mesh. 4. Repair boundary T-junctions and rebuild the facet body. Restore native tool surfaces on the faces that came from them; the rim against the mesh remains a polyline with recorded chord-deviation tolerances. This path preserves the mesh representation of the input. It does not turn a scanned surface into an exact smooth surface. The nearby-triangle limit and the facet-expansion limit above apply to different stages. Step by step, with figures: [Meshes, native tools and the BVH](/how/mesh-boolean). ### More complex shapes: what changes The five 3D examples show three sources of complexity: - **Different height ranges.** Two offset boxes do not use one shared section for the whole height. In the first 3D example the levels are 0, 2, 10 and 12 mm. Only the middle interval contains both solids. Its overlap is 5 × 7 × 8 = 280 mm³. Rebuilding the boundary must also close the steps at Z = 2 and Z = 10. - **Several loops and bodies.** The plate example uses `A − (B₁ ∪ B₂)`. Its cap is one outer rectangle with two inner circles. The hole walls must connect the two caps with reversed cutter-side orientation. The plate remains one body; its intersection with the two cutters has two bodies. A single feature result can therefore contain several bodies. - **A section that changes continuously.** Tilting a circular cutter makes elliptical cuts on the plate caps. For the 30° cutter shown above, each ellipse has semiaxes 2 / cos 30° ≈ 2.309 mm and 2 mm. Its centre is at X = (Z − 4) tan 30°: about −2.309 mm on the bottom and +2.309 mm on the top. One constant XY section is insufficient. The **crossing cylinders** example goes further. Their wall equations are `x² + y² = 16` and `y² + z² = 6.25`. Subtracting them gives `x² − z² = 9.75`. Points on their common curve must satisfy both original equations. The curve runs through space on two curved faces. Each cylinder needs its own angle/height coordinates to split its face domain. The final model retains cylindrical surfaces bounded by these spatial curves; the viewer displays triangles. For a general pair of smooth B-spline or NURBS faces, a single circle or ellipse formula may not exist. The kernel uses candidate patches, refinement and tracing as described in [Curved B-reps](#_3-curved-b-reps-intersect-the-surfaces-and-trim-their-face-domains). A surface intersection point must lie on both surfaces: `Sₐ(u,v) = Sᵦ(s,t)`. Tracing uses both parameter pairs. The cross product of their surface normals gives a tangent direction when those normals are not parallel. Tangencies, small loops, seams and a curve leaving a trimmed domain need separate handling. Unsupported cases can refuse. For scanned or faceted shapes, use the [mixed mesh path](#_4-mesh-with-a-native-tool-process-the-nearby-mesh). A dense scan has many candidate triangles; clipping the nearby region limits the work. A mesh cutter still has planar facets. Adding display triangles does not recover an exact cylinder or smooth surface from that mesh. Boolean order also matters. `A − (B ∪ C)` cuts both tools from A. `(A − B) ∪ C` adds C after the first cut. An empty result, a disconnected result, a cavity and an invalid self-touching boundary are different outcomes. A successful picture for one fixed case does not establish support for all inputs of that surface family. ### Result names, contact and tolerances Retained faces keep their source names. Split pieces receive `#k` suffixes, and edges are named from their two faces. These names let later operations refer to the result, subject to the reference checks described under [Names](/packages/cad/modeling#names). Separate lumps that meet only at an edge or point can remain separate bodies in one output. A single boundary that touches itself and cannot form a manifold solid is refused. A tolerance used to compare points is different from a recorded edge-fit error; neither is a licence to accept an unsupported topology. Display tessellation density controls the display and STL. It does not select the native Boolean algorithm. The mesh path has its own sampling and tolerance work because a mesh is already part of its input. ### Implementation map These are the current source paths under `packages/barocss-cad/src/`: | Source | Responsibility | |---|---| | `part/part-model.ts` | Dispatch, empty operands, planar retry and mixed mesh operand order | | `features/prismatic-solid.ts` | Height intervals and B-rep reconstruction | | `brep/curved-arrangement.ts` | Line, arc and parametric-curve arrangements in 2D | | `brep/polyhedral-boolean.ts` | Rational planar intersections, classification and shell assembly | | `brep/analytic-boolean.ts` | Surface cuts, face-domain splitting, classification and stitching | | `intersect/surface-intersection.ts` | Predictor/corrector intersection tracing | | `mesh/facet-boolean.ts` | Nearby mesh/native processing and reconstruction | ## Candidate: small-cap conical chamfer A source candidate adds a chamfer to the complete outer rim where the smaller planar cap meets the conical wall of one solid frustum. It is not integrated into the product, and its execution checks have not been completed. Select a named edge on that closed circular rim. If the rim is represented by joined edge pieces, selecting one piece applies the finish around the complete circle; it does not request a partial chamfer. The distance is in mm, measured from the original corner along each adjoining face in the axial section. It must be finite and positive. Both contact points must stay strictly inside their faces, with clearance from the other cap and the rotation axis. A distance equal to a support limit is refused; reaching the axis is not allowed. This candidate excludes partial revolutions, the larger bottom rim, concave corners, hollow bodies and bodies that are not one closed solid frustum. Here “top” means the smaller cap relative to the frustum's axis, not world Z. The direct finishing operation reports an unsupported scope as `GEOMETRY` with `CONE_TOP_CHAMFER_SCOPE` in its message, and an inadmissible distance as `INPUT` with `CONE_TOP_CHAMFER_SIZE` in its message. These message tags do not replace the error's `code`. Other conical edges remain outside this candidate's supported scope. ## Strict validity and typed refusals `checkOutput(output)` runs the strict check on an output. It checks: - the topology: closed shells, each edge used twice; - that edges lie on their surfaces; - that loops don't cross; - that there are no slivers; - that tolerances stay under their cap. The report gives `valid`, the first issues, the counts, each body's topology (shells and genus) and the largest gaps. An operation the kernel can't complete correctly throws a `CadPartError` instead. It has: - **`code`**: the specific code its message starts with in brackets, such as `RADIUS_EXCEEDS_FACE`, or, when it has none, its category; - **`details.category`**: one of `FORMAT`, `INPUT`, `PARAMETER`, `REFERENCE`, `SELECTION`, `CAPABILITY` or `GEOMETRY`; - **`feature`**: the id of the feature it comes from; - **a message** saying what went wrong, and what would work. ```js const tooLarge = refusal(part([...block('a', [0, 0], [10, 10]), { id: 'f', kind: 'fillet', target: 'a', edges: ['a.side0|a.top'], radius: 50 }])); assert.equal(tooLarge.code, 'RADIUS_EXCEEDS_FACE'); // the specific code its message carries assert.equal(tooLarge.details.category, 'PARAMETER'); // and the kind of refusal it is assert.equal(tooLarge.feature, 'f'); assert.match(tooLarge.message, /\[RADIUS_EXCEEDS_FACE\] edge a\.side0\|a\.top: fillet 50 mm is too large for walls of 10 and 10 mm/); const missing = refusal(part([...block('a', [0, 0], [10, 10]), { id: 'f', kind: 'fillet', target: 'a', edges: ['a.side9|a.top'], radius: 1 }])); assert.equal(missing.code, 'SELECTION'); // no specific code: the category assert.equal(missing.details.category, 'SELECTION'); assert.match(missing.message, /no edge named a\.side9\|a\.top; edges: a\.bottom\|a\.side0, /); // and the edges there are ``` An unsupported native operation is refused instead of silently replacing the body with a display mesh. Supported curve fitting and mesh operations keep their own numeric tolerances, as described above. ## Touching lumps as separate bodies When a Boolean leaves pieces that touch only along an edge or at a point, they stay separate bodies of one output. They aren't welded into a body whose edge is shared by four faces, and they aren't refused. ```js const snapshot = evaluateCadPart(part([...block('a', [0, 0], [10, 10]), ...block('b', [10, 10], [20, 20]), { id: 'u', kind: 'union', target: 'a', tool: 'b' }])); const [joined] = snapshot.outputs; assert.equal(joined.bodyCount, 2); // not welded along the shared edge assert.equal(checkOutput(joined).valid, true); ``` The studio carries this through: such a body exports as one STL file per piece, or as separate 3MF objects. ## How it is checked - **Conformance.** `conformance/` holds over 400 cases in folders named by the roadmap step that added them. A case that a later step superseded is kept as the record, but not run. - Each case is a part document and what any correct implementation must produce: volume, centroid, area, bodies, topology, face names, a watertight tessellation, a STEP round trip, sheet-metal and frame reports, or the error it is refused with. - Each case says where its expected values come from: closed form, an independent tool, or this kernel. - `test/conformance.test.mjs` checks every case. - **The robustness runner** (`pnpm rb`) puts every conformance case and the seed corpus (`robustness/corpus/`) through the kernel. Each case runs in a worker under a time limit. The runner prints pass rates by stage and category, marks known failures as TODO, and fails on any failure that is new. - **Properties** (`pnpm rb:props`): generated inputs checked against stated properties, with the smallest counterexample when one fails. - **The fuzz** (`pnpm rb:fuzz`): - It runs seeded random CSG trees, each checked against an independent ray-casting oracle: valid, watertight, and with its volume and centroid within the oracle's bounds. - Each case is OK, KNOWN or REFUSED (counted by code). Anything else is a finding: WRONG, INVALID, CRASH or TIMEOUT. - A finding is shrunk to its smallest tree and can be saved as a replayable case. These need the built package (`pnpm build:library`). [How it is verified](/reference/verification) covers the studio's checks too. --- # Exchange formats ## File contents and reports from code These functions work on caller-supplied data. They do not open files, download results or save a document. Keep the report with the result; a report object is not the file content. | Function | Result and units | Failure boundary | |---|---|---| | `exportIGES(model, ids)` | `{ iges, report }`: `iges` is file text; the report declares mm, scale 1 and non-solid geometry | Requires a version-0 millimetre model with 1–16 objects and 1–16 distinct selected IDs; invalid model or selection is refused | | `importIGES(text, options)` | `{ request, source, model, metadata, entities, report }`: native model/source data and import provenance, not a B-rep solid | Unsupported input throws `IGESImportError` with a diagnostic `code`; it is not a successful report with missing geometry | | `writeDxf(drawing, options)` | `{ text, bytes, report }`: `bytes` is `Uint8Array` in Windows-1252; extents and chord distances use the drawing's units | Throws a typed refusal; use `isDxfWriteError(error)` to identify its code | The bounded IGES importer requires `sourceId`, `modelName`, `idPrefix`, `maximumEntities: 16` and `maximumRecords: 8192`. It accepts its supported millimetre profile without unit conversion. Its returned `source` is native model source, not the original IGES file text; `request.iges` retains that input text. For DXF, write the returned `bytes` when you need the writer's file encoding. Encoding `text` as UTF-8 can produce different bytes for non-ASCII characters. In R12, `report.r12` records conversions and whether units were omitted; the chord tolerance uses drawing units, not a fixed millimetre value. ```ts import { writeDxf, isDxfWriteError, type DxfDocument } from '@barocss/cad'; // The caller supplies drawing data and handles file I/O. export function prepareDxf(drawing: DxfDocument) { try { const result = writeDxf(drawing, { version: 'AC1015' }); return { bytes: result.bytes, report: result.report }; } catch (error: unknown) { if (isDxfWriteError(error)) return { error: error.code }; throw error; } } ``` ## STEP - **Writing.** An output's `exportStep(options)`, or `exportStep(brep | breps, options)`, writes the exact B-rep as STEP AP214: planes, B-spline surfaces and curves. Its options: - `name`: the product's name. - `timestamp`: the header's time; the default is now. - `description`: the header's `FILE_DESCRIPTION` entries. The default is `'BaroCSS CAD part'`; the studio adds its source revision. - `validationProperties`: CAx-IF geometric validation properties (volume, area, centroid and bounding box), written by default so a reader can check what it imported. - `meshes`, for mesh bodies: - `tessellated`: AP242 triangulated faces, compact; - `planar`: the triangles as planar faces, readable by any STEP reader, but large; - `auto` (the default): planar up to 5,000 triangles a body, tessellated above. Planar faces past 250,000 triangles a body are refused. - **Reading.** `importStep(text)`, or the `import` feature in a part, reads B-rep solids: - **surfaces:** planes, cylinders, cones, spheres and tori as exact rational patches, B-spline surfaces as they are, and surfaces of linear extrusion and of revolution; - **offset surfaces:** one level of `OFFSET_SURFACE` over direct `PLANE`, `CYLINDRICAL_SURFACE`, `SPHERICAL_SURFACE`, `CONICAL_SURFACE` (including exact-zero identity and nonzero cone offsets away from apex collapse/crossing), `TOROIDAL_SURFACE` (away from collapse and spindle pinch), and `B_SPLINE_SURFACE*` bases. Analytic offsets certify boundary curves explicitly; NURBS offsets check curvature fold bounds and disclose fitted deviation in `importStepWithReport(...).offsetApproximations`; - **curves and periodic bounds:** lines, circles and ellipses as rational arcs, B-spline curves (including exact domain splits and `TRIMMED_CURVE` bounds), `VERTEX_LOOP` pole/apex bounds on singular carriers, seam-crossing holes, and once-round swept/revolution/periodic carriers. A face that goes once round its axis is cut into seamless halves. Other offset bases, nested offsets, binary64 cone-offset underflows, pinched/collapsed offsets, non-singular `VERTEX_LOOP` pinholes and separated boundary curves are explicitly refused by name (`GEOMETRY` for proved boundary separation, `CAPABILITY` / `INPUT` otherwise). `stepMeshes(text)` reads a file of AP242 tessellated meshes only. - **Multi-level STEP assemblies.** STEP import and export preserve multi-level assembly definitions, shared part instances, and rigid placement transforms across round-trips rather than flattening every occurrence into unlinked bodies. - **Zero-RegExp Part 21 parsing.** STEP real/point formatting and Part 21 token parsing run on a dedicated scanner with zero RegExp backtracking overhead for large assemblies. ```js const [body] = evaluateCadPart(plate).outputs; const step = exportStep(body, { name: 'plate' }); // exact B-rep, AP214 const back = evaluateCadPart({ format: 'barocss-cad-part', version: 1, units: 'mm', parameters: {}, features: [{ id: 'i', kind: 'import', step }] }); // a STEP file as a feature const [read] = back.outputs; assert.ok(Math.abs(massPropertiesOf(read, 2.7).volume - massPropertiesOf(body, 2.7).volume) < 1e-6); assert.equal(checkOutput(read).valid, true); ``` With `each: true`, the `import` feature makes each solid in the file its own part (`id/k`), in file order. ## IGES `exportIGES` writes curves and surfaces as rational B-spline entities (126 and 128). `importIGES` reads the same profile: untransformed rational B-spline curves and surfaces in IGES 5.3. It gives typed diagnostics for anything else. In the studio, IGES is for curves and surfaces you edit directly, not solids. Native IGES exchange is verified end-to-end across `@barocss/cad`, `@barocss/cad-model`, and `@barocss/viewer` with strict bounds validation and refusal diagnostics. See [Files and exports](/studio/files). ## STL - **Writing.** An output's `exportStl({ segmentsPerQuarter })` writes its display tessellation as binary STL, in millimetres. `encodeBinaryStl(positions, indices)` writes any triangle mesh. - **Reading.** `readStl(bytes)` reads binary or ASCII STL triangles, and `readObj` reads OBJ. The `mesh` feature takes triangles as a faceted body. STL carries triangles only: no units, colours, names or exact curves. - **Unit scaling and malformed refusal.** Binary and ASCII STL readers support explicit unit scaling (`mm`, `cm`, `m`, `in`) and refuse truncated buffers, non-finite coordinates, or malformed headers with typed diagnostics instead of silently dropping triangles. - **Approximation disclosure.** Exporting a curved B-rep to STL approximates exact analytic/NURBS faces as triangles; Studio surfaces triangle count and chordal approximation metadata alongside the export. Omitting `segmentsPerQuarter` from `exportStl` uses 16. This dimensionless tessellation setting is not a millimetre tolerance or a guarantee of geometric error. It does not change the on-screen mesh; see [STL export choices](/studio/files#exports) for the studio controls. ## DXF `writeDxf(document, { version })` writes a 2D drawing: - **The input** is a plain document of layers, line types, text styles, blocks and entities. - **The versions** are DXF 2000 (`AC1015`, the default) and R12 (`AC1009`). - **Same document, same file.** The output has no time stamps, so the same document always gives the same bytes. - **R12's limits.** R12 has no ellipses, splines, hatches or multi-line text: - polylines and text are rewritten exactly; - ellipses and splines become polylines only within a chord tolerance you give; - anything else is refused, typed. The report counts every such change, so nothing is approximated silently. The document may also supply `dimensionStyle` with all three fields: a finite positive `textHeight` in the drawing's units, `textPlacement` (`above` or `center`) and `textOrientation` (`aligned` or `horizontal`). Both versions write these dimension-style defaults. Omitting the object preserves the existing defaults and bytes. Invalid values throw a typed DXF write error. The fields do not rebuild anonymous dimension display blocks or guarantee an external editor's regenerated layout. ```js const sheet = { units: 'mm', entities: [ { type: 'line', a: [0, 0], b: [60, 0] }, { type: 'line', a: [60, 0], b: [60, 40] }, { type: 'line', a: [60, 40], b: [0, 40] }, { type: 'line', a: [0, 40], b: [0, 0] }, { type: 'circle', center: [30, 20], radius: 4 }, ] }; const a = writeDxf(sheet), b = writeDxf(sheet); // DXF 2000 (AC1015) by default assert.equal(a.text, b.text); // no time stamps: the same document, the same file assert.deepEqual(a.report.modelSpace, { LINE: 4, CIRCLE: 1 }); const r12 = writeDxf(sheet, { version: 'AC1009' }); // R12 assert.match(r12.text, /AC1009/); ``` Sheet metal's flat pattern has its own DXF writer, `flatPatternDxf`. Reading a DXF sketch is the document model's job: see [@barocss/cad-model](/packages/cad-model/). --- # @barocss/cad-projection Headless, deterministic CPU hidden-line CAD geometry projection with exact SVG vector export and CPU-rendered PNG output — with **zero browser, GPU, DOM, canvas, React, or Studio dependencies**. `@barocss/cad-projection` builds on `@barocss/cad`'s exact B-rep hidden-line removal (`projectBrepHiddenLines`) and adds mixed-scene adaptation (B-rep solids, NURBS curves, UV-trimmed surfaces, triangle meshes, Direct sources), exact 2D fill visibility clipping, compact SVG export, and pure-CPU PNG rasterization for CI visual checks and multimodal AI verification (`query.render`). ## Quick start ```js import { evaluateCadPart } from '@barocss/cad'; import { part } from '@barocss/cad/api'; import { projectGeometry, projectGeometryFourViews, renderSvg, renderPng, } from '@barocss/cad-projection'; ``` ```js const bracket = part('Bracket') .box({ w: 80, d: 40, h: 10 }) .hole(p => p.faces().facing('+z').first(), { d: 8, x: 20, y: 20 }); const snapshot = evaluateCadPart(bracket.doc); const brep = snapshot.outputs[0].brep; const items = [{ id: 'bracket', kind: 'brep', brep }]; const doc = projectGeometry(items, { camera: { position: [240, -320, 220], target: [40, 20, 5], up: [0, 0, 1] }, fills: [{ item: 'bracket', color: '#dbeafe' }], }); const svg = renderSvg(doc, { compactFills: true, hiddenLines: true }); const png = await renderPng(doc, { hiddenLines: true, width: 320, height: 240 }); const fourView = projectGeometryFourViews(items); ``` This sample runs directly in CI via `pnpm --filter @barocss/library-docs test:samples`. ## Entry points | Subpath | Purpose | | --- | --- | | `@barocss/cad-projection` | Scene & B-rep projection (`projectGeometry`, `projectGeometryFourViews`, `projectBreps`, `projectDirectGeometry`, `projectModel`) + `renderSvg` / `renderPng` | | `@barocss/cad-projection/compression` | Zero-dependency `crc32`, `compress`, and `deflateZlib` utilities | | `@barocss/cad-projection/inspect` | Diagnostic inspection helpers for projected curves, visibility intervals, and coverage receipts | ## Supported input coverage | Input kind | Item descriptor | Routing & notes | | --- | --- | --- | | Solid / sheet / facet B-rep | `{ id, kind: 'brep', brep }` | Exact kernel HLR (`projectBrepHiddenLines`) | | Free NURBS curve | `{ id, kind: 'curve', curve, interval? }` | Analytic lines & circles preserved; general curves adaptively sampled | | UV-trimmed NURBS surface | `{ id, kind: 'surface', surface, trims? }` | Exact UV slab arrangement decomposition | | Triangle mesh / soup | `{ id, kind: 'mesh', positions, indices, open? }` | Native facet adapter with non-manifold triangle-sheet fallback | | Direct / compiled model | `projectDirectGeometry` / `projectModel` | Atomic validation (`ProjectionSourceError`) without Studio imports | ## Rendering options & boundaries - **`renderSvg(doc, options?)`**: Preserves exact lines and affine elliptical arcs (`transform="matrix(...)"`), optional `hiddenLines`, `faceGuideStyle` (`'illustration' | 'continuous'`), and `compactFills` (directed-edge cancellation). Also powers semantic SVG hit metadata in [`@barocss/cad-react/sdk`](/packages/cad-react/sdk) ``. - **`renderPng(doc, options?)`**: Deterministic RGB PNG (`Promise`) rasterized on CPU using standard `CompressionStream`. - **Camera & pixel limits**: Cameras are strictly orthographic (`position - target` sets view direction, auto-fitted to bounds), supporting standard orthographic, isometric, dimetric, trimetric, and magnified detail views. Image dimensions must be positive integers up to `8192` per side and `32,000,000` total pixels. - **Scope separation**: ISO/ASME title blocks, baseline/ordinate dimensions, GD&T callouts, and vector PDF/DXF sheet export live in [`@barocss/cad-model`](/packages/cad-model/); interactive WebGPU 3D rendering lives in [`@barocss/gpu`](/packages/gpu/). --- # @barocss/cad-interop `@barocss/cad-interop` bridges exact `@barocss/cad` B-Rep geometry and native face/curve packets into third-party WebGL/WebGPU scene graphs (**Three.js**, **Babylon.js**, **Pixi3D**) and binary **glTF / GLB** preview assets. Use `@barocss/cad-interop` when your application already renders with Three.js, Babylon.js, or Pixi3D and wants to embed BaroCSS CAD's pure-TypeScript B-Rep modeling engine without replacing your existing 3D engine. ## Core Capabilities | Entry Point | Target Engine / Format | What It Provides | | :--- | :--- | :--- | | `@barocss/cad-interop` | Engine-agnostic packets & GLB | `copyCadPreviewPacket`, `prepareCadPreviewMesh`, `prepareOwnNativeFaceMesh`, `encodeCadPreviewGlb`, `encodeOwnNativeFaceMeshGlb` | | `@barocss/cad-interop/three` | **Three.js** (`three`) | Direct BufferGeometry & scene adapters (`/three-document`, `/three-assembly`, `/three-boolean-mesh`, `/three-uniform-curve`, `/qualified-body-boundary-mesh-three`) | | `@barocss/cad-interop/babylon` | **Babylon.js** (`@babylonjs/core`) | Babylon mesh & assembly adapters (`/babylon-document`, `/babylon-assembly`, `/babylon-boolean-mesh`, `/babylon-uniform-curve`, `/qualified-body-boundary-mesh-babylon`) | | `@barocss/cad-interop/pixi3d` | **Pixi3D** (`pixi3d`) | Pixi3D mesh & document adapters (`/pixi3d-document`, `/pixi3d-assembly`, `/pixi3d-boolean-mesh`, `/qualified-body-boundary-mesh-pixi3d`) | | `@barocss/cad-interop/document-glb` | **glTF 2.0 Binary (`.glb`)** | Document, boolean mesh (`/boolean-mesh-glb`), and boolean extrusion (`/boolean-extrusion-glb`) GLB encoders | | `@barocss/cad-interop/native` | **Native CAD loaders** | Qualified body, native uniform curve (`/native-uniform-curve`), assembly (`/assembly`), and model-set (`/model-set`) loaders | All engine peer dependencies (`three`, `@babylonjs/core`, `pixi.js`, `pixi3d`) are optional — install only the renderer your app uses. ## Engine-Agnostic Packet & GLB Export The root entry point prepares detached, bounds-verified preview meshes and encodes binary `.glb` buffers directly from pure TypeScript: ```ts import { prepareCadPreviewMesh, encodeCadPreviewGlb, type CadPreviewPacket, } from '@barocss/cad-interop'; export function buildPreviewGlb(packet: CadPreviewPacket): Uint8Array { // Validates & normalizes positions, normals, indices, and metadata const prepared = prepareCadPreviewMesh(packet); // Encodes a self-contained binary glTF 2.0 (.glb) buffer in memory return encodeCadPreviewGlb(prepared); } ``` ## Cross-Format Interchange Reporting When exporting across formats (STEP, IGES, STL, 3MF, GLB), `@barocss/cad-interop` and Studio attach structured interchange reports (`interchange-report`) declaring the exact export target, output units, body count, and any representation loss (such as analytic B-Rep surfaces approximated into triangle meshes for STL/GLB) so downstream recipients never receive silent format degradation. ## Choosing Between `@barocss/cad-interop` and `@barocss/cad-react/sdk` - **Already using Three.js, Babylon.js, or Pixi3D?** Use `@barocss/cad-interop` adapters to mount exact BaroCSS B-Rep solids, curves, and assemblies into your existing camera, lighting, and shader pipeline. - **Building a CAD viewer or product configurator in React from scratch?** Use [`@barocss/cad-react/sdk`](/packages/cad-react/sdk) (`` + ``) powered by BaroCSS's native WebGPU renderer and exact 2D HLR projection. - **Need manufacturing exchange formats (STEP, IGES, DXF, STL)?** Those live directly in [`@barocss/cad` Exchange formats](/packages/cad/formats). ## Related Pages - [Exchange formats (STEP, IGES, STL, DXF)](/packages/cad/formats) - [React CAD SDK (`@barocss/cad-react/sdk`)](/packages/cad-react/sdk) - [WebGPU Renderer (`@barocss/gpu`)](/packages/gpu/) - [Viewer SDK (`@barocss/viewer`)](/packages/viewer/) --- # @barocss/cad-worker `@barocss/cad-worker` moves heavy B-Rep evaluation, mass properties, 2D proposal callouts, robotics workspace sweeps, and parallel generative variants off the browser main thread using standard Web Workers and zero-copy transferable buffers. Because the underlying `@barocss/cad` kernel is pure TypeScript with zero WebAssembly, the same worker modules run identically in browser Web Workers, Vite/esbuild apps, or synchronous in-process test ports. ## Subpath Entry Points | Entry Point | Purpose | | :--- | :--- | | `@barocss/cad-worker` | Main barrel exporting `EngineClient`, `Lanes`, ports, analysis router, robot tasks, and `VariantWorkerPool` | | `@barocss/cad-worker/client` | `EngineClient` RPC wrapper over a Web Worker with typed replies (`MassReply`, `VolumeReply`, `FootprintReply`, `RobotSweepReply`, `ProposalOverlay`) | | `@barocss/cad-worker/worker` | Ready-to-bundle `engine.worker.ts` entry point | | `@barocss/cad-worker/analysis` | `createAnalysisWorkerRouter` for modular auxiliary analysis workers (`faces`, `print`, `clearance`, `cam`) | | `@barocss/cad-worker/port` | `createDefaultEnginePort`, `createWorkerEnginePort`, and `createSyncEnginePort` (`CadEnginePort` abstraction) | | `@barocss/cad-worker/lanes` | `Lanes` request-lane coordinator (latest-wins cancellation for live slider dragging vs queued exports) | | `@barocss/cad-worker/variantPool` | `VariantWorkerPool`, `evaluateVariants`, `buildParametricVariantCandidates`, `computeSafeParameterBounds`, and `projectVariantThumbnail` | | `@barocss/cad-worker/robotTasks` | `collectRobotPartMeshes`, `runRobotSweep`, and `runRobotWorkspace` | | `@barocss/cad-worker/proposalDrawingCallouts` | `proposalDrawingCallouts` for computing 2D drawing annotation diffs on AI proposals | | `@barocss/cad-worker/stepMetadata` | `stepMetadata` / `receiveStepMetadata` for STEP provenance inspection | | `@barocss/cad-worker/mouldView` | `mouldView` parting-line and draft loop computation | ## Choosing an Engine Port (`CadEnginePort`) Use `@barocss/cad-worker/port` when your UI or SDK wants automatic Web Worker acceleration in browsers while falling back seamlessly to synchronous execution in Node.js or unit tests: ```ts import { createDefaultEnginePort, createSyncEnginePort, createWorkerEnginePort, } from '@barocss/cad-worker/port'; // Browser: spawns a Web Worker when available; Node/SSR: falls back to synchronous evaluation. const port = createDefaultEnginePort(); // Explicit synchronous port for deterministic CI tests or CLI tooling: const syncPort = createSyncEnginePort(); ``` ### Request Lanes (`Lanes`) Interactive CAD sliders fire dozens of updates per second. `Lanes` separates high-frequency interactive preview requests from authoritative operations: - **Latest-wins lanes** supersede stale in-flight slider evaluations so the UI never queues behind obsolete drag frames. - **Authoritative lanes** preserve ordering for saves, exports, and proposal acceptance. ## Parallel Generative Variants (`VariantWorkerPool`) The [Generative Variant Explorer](/agent/variants) uses `@barocss/cad-worker/variantPool` to evaluate multiple parameter and topology candidates in parallel without blocking viewport orbiting: ```ts import { buildParametricVariantCandidates, evaluateVariants, applyCandidateToDoc, type VariantCandidateInput, } from '@barocss/cad-worker/variantPool'; // 1. Derive safe bounded parameter candidates around the active document const candidates: VariantCandidateInput[] = buildParametricVariantCandidates(doc, { preset: 'lightweight', count: 4, }); // 2. Evaluate all candidates in parallel (B-Rep mass, bounds, DFM, checkSpec, 2D thumbnails) const batch = await evaluateVariants(doc, candidates); // 3. Promote the winning candidate into an editable document revision const winner = batch.results.find(r => r.ok && r.specs?.hardFailing === 0); if (winner) { const nextDoc = applyCandidateToDoc(doc, winner.candidate); } ``` Each `VariantCandidateResult` carries: - `VariantBaselineMetrics` deltas (mass, volume, bounding box) - `VariantSpecSummary` (`checkSpec` pass/fail counts) - `VariantDfmSummary` & `VariantPhysicsSummary` - `VariantThumbnail` lightweight 2D projection segments for side-by-side card previews ## Auxiliary Analysis Router (`createAnalysisWorkerRouter`) Heavy inspection tasks — print slice previews, clearance checks, face queries, and CAM toolpaths — run on isolated auxiliary workers routed through `createAnalysisWorkerRouter`: ```ts import { createAnalysisWorkerRouter } from '@barocss/cad-worker/analysis'; const router = createAnalysisWorkerRouter({ print: () => import('./printLane'), clearance: () => import('./clearanceLane'), cam: () => import('./camLane'), }); ``` ## Related Pages - [Generative Variant Explorer & Self-Verification](/agent/variants) - [`@barocss/cad` Core Kernel](/packages/cad/) - [React CAD SDK (`@barocss/cad-react/sdk`)](/packages/cad-react/sdk) - [Embedding & Self-Hosting Guide](/guide/embedding) --- # Object API > **Quick jump:** [Start with CAD Model API](#start-with-the-cad-model-api) · [Interactive 3D API Results](#see-actual-api-results) · [CAD Kernel Part](#parts) · [Studio / Model Part](#studio-parts) · [Parameters & Configs](#parameters-configurations-and-suppression) · [Assemblies](#assemblies) · [Manufacturing](#manufacturing-inputs-and-outputs) · [Scenes](#scenes) · [Errors](#errors) ## Start with the CAD model API For ordinary modeling, start with `@barocss/cad-model/api`. It builds the model document used for editing, materials, assemblies and drawings. The same API works in code without the Studio editor. This sample makes a bracket, then reads its mass, STEP and meshes: ```js import { part, assembly, Location, param, BarocssError } from '@barocss/cad-model/api'; ``` ```js // 3. The facade: the same command names, the same value names (no unit suffix), the selectors in place of // the names. const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass('al6061'); // or mass({ density: 2.7 }); native results also report method and an optional volumeBasis const step = bracket.step(); // STEP AP214 text const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` The kernel examples later on this page show its lower-level document and results. They are useful when working with the kernel directly; they are not the default entry point for the complete model document. Each of the three packages has an object facade over its own data-and-functions core: | Package | Entry | Over | For | |---|---|---|---| | @barocss/cad | `@barocss/cad/api` | The kernel's `CadPartDocument` and `evaluateCadPart` | Using the kernel on its own. It replaced the older `createCadModel()`, retired in R7.3d. | | @barocss/cad-model | `@barocss/cad-model/api` | The CAD model document, its evaluation, mass, STEP and assemblies | Materials by id, assemblies, variants and frames, in code or in Studio | | @barocss/gpu | `@barocss/gpu/api` | The `Viewer` and its geometry and material data | Putting parts on screen | Both Part APIs build and evaluate a model. Choose the document and workflow you need: | | CAD kernel part | CAD model part | |---|---|---| | Import | `@barocss/cad/api` | `@barocss/cad-model/api` | | Document returned by `.doc` | `CadPartDocument`, format `barocss-cad-part`, with `features` | `StudioDoc`, format `barocss-cad-model`, with `nodes` and `outputs` | | Use it when | You need the CAD kernel and its feature document in code. | You need the CAD model document, materials, configurations or drawing and manufacturing outputs. | | Shared modeling | Box, hole, fillet, Boolean operations, mass, meshes and STEP | These modeling and result methods use the CAD model document | | Additional operations | Supply a density for mass; export STL from this part API. | Set a material id; save configurations; generate drawings and manufacturing outputs. The model part also provides gear, spring and fastener commands. | The modeling calls can look the same, but the two `.doc` values have different formats: ```js import { part as kernelPart } from '@barocss/cad/api'; import { part as modelPart } from '@barocss/cad-model/api'; const kernel = kernelPart('plate').box({ w: 80, d: 40, h: 10 }); const model = modelPart('plate').box({ w: 80, d: 40, h: 10 }); console.log(kernel.doc.format); // 'barocss-cad-part' console.log(model.doc.format); // 'barocss-cad-model' ``` Each facade is an API for code. CAD Model's document type is named `StudioDoc` in the source. It is a data model that code can use independently; Studio is an editor that also uses that model and its core. The CAD model part facade writes commands into the document. Calling the facade does not control an open Studio screen. The agent works through its JSON tools. ## The shared rules - **Immutable objects.** Modeling methods return a new object and leave the original unchanged. Result methods such as `mass()` and `meshes()` return result data. - **One plain-JSON accessor.** - The two parts and the assembly have `.doc`, the document a person or the agent could have written by hand. - gpu's scene has `.data`. - Typed arrays appear only in mesh data. - **Modeling methods** write changes to a new document and use the core to evaluate it. Query and result methods read the document or return data; they do not add a feature. - **Modeling units.** Lengths are in millimetres, angles in degrees and density in g/cm³. Mass results use millimetres and grams. The confirmed R7 [robot contract](/studio/robots#robot-unit-boundaries) extends these units to public replies and stored joint settings. It uses N·mm for turning effort, mm/s² for gravity and seconds for time. Robot samples check angular metadata, B1 inertia/gravity and the CLI's shared B2 duty/report adapters. Further field changes and final combined checks are pending. Native robot files retain their format-specific SI units. - **Results are plain data.** Mass results contain `volume` in mm³, `mass` in g, `centroid` in mm and `inertia` in g·mm² about the centre of mass. A numeric `density` is in g/cm³. Density must be positive and finite; both facades refuse other numeric densities with `BarocssError`, code `DENSITY`, from `facade`. Native producers also report optional `method` provenance: `closed-form`, `planar-exact`, `quadrature` or `tessellated`. `planar-exact` describes the represented planar or facet boundary; it does not recover a smooth source from a mesh. `quadrature` describes numerical integration over the represented surfaces. These method names are not accuracy certificates. Legacy or custom Model bodies without producer metadata omit `method`; the facade does not infer it from the body's family or a missing estimate. A reported tessellated result can include `volumeBasis: { method: 'tessellated', bound }`. Despite its existing field name, `bound` is an estimate of volume error in mm³, derived from the mesh refinement change, rather than a certified error bound. `null` means no estimate was supplied; zero remains a reported zero estimate. Other native methods omit this basis. Density changes mass and inertia, while the method and volume estimate remain unchanged. The returned basis is detached from the producer's record. - **The agent's words.** The modelling verbs are the agent's v2 command names, and their options are that command's value names, with no unit in the name: `box({ w, d, h })`, `hole(face, { d, x, y })`, `fillet(edges, { radius })`. Where no command names a value, the option is named for it: `mass({ density })`. Two verbs are named for their studio palette entry instead: `box`, which has no v2 command, and `subtract`, whose command is `difference`. - **One part, two documents.** Both packages' parts are one implementation (cad's `Part`). Each verb is checked once, and a backend writes it into its own document: cad's as kernel features, cad-model's through the studio's own command, as the agent's `run_command` does. - **The same selectors.** `edges()` and `faces()`, with typed filters and no string selectors: - the kernel fills them from the B-rep, and cad-model from its display mesh; - both hand back the persistent names a feature stores. - **One error shape.** `BarocssError { code, message, where, details }`, where the message starts with `[CODE]`: - the facade's own codes cover only how it was called, with `where: 'facade'`; - a core refusal is passed through with its code and words, with `where: 'evaluate'` or `'export'`. - **Z-up, as given.** Meshes from either part go into a gpu scene unconverted: the Viewer is Z-up already. - **The oracle.** Each package's tests check every method two ways: its `.doc` equals the hand-written document, and its results equal the core's on that document, byte for byte. cad-model's `.doc` also equals what the agent's tools write for the same calls. ## See actual API results These three saved cases follow the public `@barocss/cad/api`: an 80 × 40 × 10 mm box, a through hole, then four rounded vertical edges. Each operation returns a new part. The earlier parts stay unchanged. The coordinates are Z-up, in mm. Mass uses a density of 2.7 g/cm³. The 3D view draws the actual Float32 tessellated mesh returned by the public API; the JPEGs show those saved meshes. Display triangles approximate curved surfaces and do not guarantee the kernel's geometric tolerance. This is a documentation view of fixed API results. Choose a case to read its executed code, inputs and returned mass properties. **Source bundle provenance** records the source and generation conditions. Missing result data is shown as `NOT_RUN`, not a successful API run. ### 01 · Box Create the box with `box({ w: 80, d: 40, h: 10 })`. ![Public API result: an 80 by 40 by 10 mm box, Z up](/shots/api-results/box.jpg)

{{ resultSummary('box') }}

### 02 · Through hole From the box, select the +Z face and make a diameter 8 mm through hole at face coordinates `(20, 20)`. ![Public API result: the box after a diameter 8 mm through hole at 20, 20](/shots/api-results/holed.jpg)

{{ resultSummary('holed') }}

### 03 · Rounded vertical edges From the holed part, select its four vertical edges and apply a 2 mm fillet radius. ![Public API result: the holed box after rounding four vertical edges with radius 2 mm](/shots/api-results/rounded.jpg)

{{ resultSummary('rounded') }}

## CAD kernel part {#parts} ```js import { part, sketch, Plane, Location, param, withParameters, BarocssError } from '@barocss/cad/api'; ``` A CAD kernel part is an immutable object over a `CadPartDocument`. Use it to work with the CAD kernel in code: ```js const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass({ density: 2.7 }); // a density: the kernel keeps no material library const step = bracket.step(); // STEP AP214 text const stl = bracket.stl(); // binary STL const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` The document it builds is the one you would write by hand. Feature ids are assigned in order: `sketch1`, `extrude1`, `hole1`… The hole keeps the face it went into by name, `face: 'extrude1.top'`, as the studio writes it. ```js // The CadPartDocument it builds: string ids the facade assigns in feature order, each feature naming its target, and // the hole the face it went into. const doc = { format: 'barocss-cad-part', version: 1, units: 'mm', parameters: {}, features: [ { id: 'sketch1', kind: 'sketch', profile: 'rectangle', min: [0, 0], max: [80, 40] }, { id: 'extrude1', kind: 'extrude', sketch: 'sketch1', height: 10 }, { id: 'hole1', kind: 'hole', target: 'extrude1', center: [20, 20], radius: 4, face: 'extrude1.top' }, { id: 'fillet1', kind: 'fillet', target: 'hole1', edges: ['extrude1.side0|extrude1.side1', 'extrude1.side0|extrude1.side3', 'extrude1.side1|extrude1.side2', 'extrude1.side2|extrude1.side3'], radius: 2 }, ] }; assert.equal(JSON.stringify(bracket.doc), JSON.stringify(doc)); // byte for byte ``` `part(name, doc)` continues a saved document, or another part's `.doc`: it is evaluated once, and the verbs add to it. ### Verbs Each verb makes a body of its own, or acts on the part's body. | Verb | v2 command | What it does | |---|---|---| | `box({ w, d, h, x?, y?, z? })` | (palette: Box) | A block, its least corner at (x, y, z) | | `cylinder({ r, h, x?, y?, z? })` | `cylinder` | A round bar standing on z about (x, y) | | `extrude(sketch, { h, draft? })` | `extrude` | A finished sketch pulled along its plane's normal | | `revolve(sketch, { axis?, deg? })` | `revolve` | A finished sketch turned about its plane's Y axis (or X), a full turn by default | | `hole(face, { d, x, y, type?, depth? })` | `hole` | A hole into the one flat face the selector picks, at (x, y) on that face's plane; through unless `'blind'` with a `depth` | | `fillet(edges, { radius, endRadius? })` | `fillet` | Rounds the selected edges with a constant radius or assigns two endpoint radii to one supported edge | | `chamfer(edges, { distance })` | `chamfer` | Cuts them back at 45° | | `shell(open?, { t })` | `shell` | Hollows the body to walls t thick, leaving the faces the selector picks open; with no selector, a closed hollow | | `union(tool)`, `subtract(tool)`, `intersect(tool)` | `union`, `difference`, `intersect` | Combines the body with a tool body | | `linearPattern({ axis, spacing, count })` | `linear-pattern` | Copies in a row, joined into one body | | `circularPattern({ axis?, count, span?, px?, py? })` | `circular-pattern` | Copies round an axis, joined into one body | | `mirror({ plane, at? })` | `mirror` | Joins the body with its image across the plane `'yz'`, `'xz'` or `'xy'`, through `at` on its axis (0 unless given) | | `scale({ factor, pivot? })` | `scale` | Scales the body by the factor, about the pivot (the origin unless given) | | `split({ axis, at })`, `split({ normal, at })` | `split` | Cuts the body in two by a plane, each side a body of its own | | `moved(location)` | `rotate`, then `move` | Turns the body about X, then Y, then Z through the origin, then moves it | - **Each verb evaluates its result.** A feature the core refuses is refused at its verb, with the core's code, and the part is unchanged. - **Patterns.** About X or Y the copies are quarter turns, 2 to 4 of them; anything else is refused, typed. - **No `rotate` verb.** The studio's rotate command turns about the body's centre by default, and the kernel's about the origin. `moved()` always turns about the origin. - **Mirror and scale** work about the origin unless given `at` or `pivot`. A mirror plane off the origin is written as the studio writes it: a move, the mirror, and a move back. ```js const block = () => part().box({ w: 10, d: 20, h: 5 }); const both = block().mirror({ plane: 'yz' }); // joined with its image across x = 0: 20 × 20 × 5 const big = block().scale({ factor: 2 }); // about the origin: 20 × 40 × 10 const halves = block().split({ axis: 'x', at: 4 }); // cut across x = 4, each side a body ``` ### Fillet with two endpoint radii Both TypeScript backends accept `endRadius` on one named straight open edge or a supported convex 90° circular rim. The circular rim joins a planar cap to a coaxial cylinder and ends at two outward radial planes. The radius starts at the selected edge's `a` endpoint and ends at `b`. Use at least 0.1 mm at each end. An equal numeric pair uses the constant-radius operation. ```ts import { part, sketch } from '@barocss/cad/api'; const sector = sketch().moveTo([0, 0]).lineTo([8, 0]).arcTo([0, 8], { center: [0, 0] }).close(); const rounded = part('Quarter rim').extrude(sector, { h: 10 }).fillet( body => body.edges().curved().where(edge => edge.a[2] === 10 && edge.b[2] === 10), { radius: 0.6, endRadius: 1.2 }, ); ``` Import `part` from `@barocss/cad-model/api` to make a Studio document. Encode it with `encodeStudioFile(rounded.doc)` from `@barocss/cad-model/engine/container` to open it as a `.bcad` file. Use Studio History to edit the end radius. ### Sketches, planes and locations `sketch(plane?)` starts a sketch on a `Plane`, XY by default. It gives `.rectangle({ w, d, x?, y? })`, `.circle({ r, x?, y? })`, `.polygon(points)`, or a chain `.moveTo(p).lineTo(p).arcTo(p, { center, direction? })` ended by `.close()`. - **Planes.** `Plane.XY`, `Plane.XZ` (its normal −Y, so its Y is world Z), `Plane.YZ`, `.offset(distance)`, and `Plane.of({ origin, normal, xAxis })`, which refuses vectors that aren't unit length and square to each other. - **Locations.** `Location.of({ position, rotation })` and `Location.at(position)`: the documents' pose, turned about X, then Y, then Z, through the origin, then moved. - **Plain data.** A sketch, a plane and a location are immutable, and each has `.data`, the shape the documents carry. - **Stable side names.** Every side of a facade sketch is tagged (`e1`, `e2` …), as the studio's sketcher tags the sketches it draws. So its walls keep their names when a vertex is added to the sketch later. ```js // A 20 × 30 section on XZ, turned a full turn about Z: a Ø40 × 30 drum. Hollowed to 2 mm walls, its top left open. const cup = part('cup') .revolve(sketch(Plane.XZ).polygon([[0, 0], [20, 0], [20, 30], [0, 30]])) .shell(body => body.faces().facing('+z'), { t: 2 }); const { volume } = cup.mass({ density: 1 }); assert.ok(Math.abs(volume - Math.PI * (20 ** 2 * 30 - 18 ** 2 * 28)) < 1e-6 * volume); // A tab from a loop of lines and an arc, on XY lifted 5, pulled 6 with a 3° draft. const tab = part('tab').extrude(sketch(Plane.XY.offset(5)) .moveTo([0, 0]).lineTo([30, 0]).arcTo([30, 20], { center: [30, 10] }).lineTo([0, 20]).close(), { h: 6, draft: 3 }); assert.deepEqual(tab.doc.features.map(f => f.kind), ['sketch', 'extrude']); ``` ### Several bodies - **`bodies()`** lists the part's bodies in the core's order: the kernel's output ids (`extrude1`, `fillet1` …), or the studio's keys (`b1`, `b3` …). - **`body(name)`** returns the same part with its verbs, `select()` and `mass()` acting on that body. `.doc` doesn't change: the choice is the facade's view, never written. It follows its body through a verb that replaces it. - **With several bodies and none chosen,** a verb refuses with `BODY_AMBIGUOUS`. `step()` writes every body, and `meshes()` gives every body. - **A Boolean's tool** is a body of the part by name, or a callback that adds it. The callback builds in the part's own document, so the tool's features take the next ids. It must add exactly one body. Its verbs after the first act on the body it made, so a callback can pattern or round its tool before the Boolean. ```js const two = part('pegged') .box({ w: 30, d: 30, h: 10 }) .cylinder({ r: 5, h: 30, x: 15, y: 15 }); // a peg standing through the block assert.deepEqual(two.bodies(), ['extrude1', 'extrude2']); assert.throws(() => two.mass({ density: 1 }), e => e.code === 'BODY_AMBIGUOUS'); const joined = two.body('extrude1').union('extrude2'); // the block, joined with the peg by name assert.deepEqual(joined.bodies(), ['union1']); // A tool added by a callback, in the part's own document: a Ø8 bore cut through a plate. const bored = part('plate').box({ w: 60, d: 40, h: 8 }) .subtract(p => p.cylinder({ r: 4, h: 20, x: 30, y: 20, z: -6 })); ``` #### Split a body and inspect each result Start with a 10 × 20 × 5 mm box at the origin. The plane `x = 4` cuts it into two bodies: ```text x = 0 x = 4 x = 10 |-----------|--------------------| 4 mm 6 mm split1/0 split1/1 ``` ```js import { part } from '@barocss/cad/api'; const divided = part('block') .box({ w: 10, d: 20, h: 5 }) .split({ axis: 'x', at: 4 }); const names = divided.bodies(); // For this document: ['split1/0', 'split1/1'] const results = names.map(name => ({ name, mass: divided.body(name).mass({ density: 1 }), })); ``` For this box, the expected volumes from its dimensions are 400 mm³ and 600 mm³. At 1 g/cm³, the expected masses are 0.4 g and 0.6 g. These are calculated expectations, not a new captured API run. The sample test above checks the two volumes. Names use the split feature id and a side index; call `bodies()` to get the names for your own part. `body(name)` selects one result without changing the document. With two bodies and no selection, `mass()` and other single-body operations refuse with `BODY_AMBIGUOUS`. `meshes()` still returns all bodies, each with a `key`, so use the key to associate a display mesh with a body. You can also set an oblique plane with `split({ normal: [1, 1, 0], at: 10 })`: it is the plane `x + y = 10`. In general, the plane is `normal · [x, y, z] = at`; changing the scale of the normal changes that equation unless `at` is scaled by the same factor. The normal must be finite and have length greater than `1e-9`. A split plane that does not cross the target body is refused. ```js // A 20 mm cube with three 40 × 40 × 2 fins: the callback adds one fin and patterns it, and the patterned tool is joined. const finned = part('finned').box({ w: 20, d: 20, h: 20, x: -10, y: -10 }) .union(p => p.box({ w: 40, d: 40, h: 2, x: -20, y: -20, z: 4 }).linearPattern({ axis: 'z', spacing: 6, count: 3 })); const expected = 20 ** 3 + 3 * (40 * 40 - 20 * 20) * 2; ``` Two separate parts aren't combined: merging two documents would renumber one's ids, and so its names. ```js const ring = part('ring') .box({ w: 10, d: 10, h: 5, x: 20 }) .circularPattern({ count: 6 }) // six round Z, joined into one body .linearPattern({ axis: 'z', spacing: 10, count: 2 }) // two tiers .moved(Location.of({ position: [0, 0, 5], rotation: [90, 0, 0] })); // turned about X, then lifted assert.deepEqual(ring.doc.features.map(f => f.kind), ['sketch', 'extrude', 'circular-pattern', 'linear-pattern', 'rotate', 'translate']); ``` ### Results - `.mass({ density })` gives the chosen body's mass properties. The kernel keeps no material library, so it takes a density; cad-model's part also takes a material id. - `.step(name?)` writes every body as one STEP AP214 file and returns its text. - `.stepReport(name?)` uses the same name, all-body selection and export rules, and returns `{ text, source, omitted? }` when the backend supports reports. On the CAD model backend, `source` is the source document revision string. It does not identify a native or mesh representation. `omitted` contains the existing exporter's applicable loss messages, such as feature history, parameters, flattened assemblies, names, appearance, drawings, datums, infill or missing bounding-box validation. An absent list does not certify a loss-free interchange. The returned object and its optional list are detached data. Band sheets still cause the same typed export refusal; reporting does not enable a partial band-sheet export. The kernel CAD backend and external backends without this optional capability refuse with `UNAVAILABLE`; they do not invent a report from the legacy text. Other backends define their own source provenance string. - `.stl()` writes the body as binary STL. It's on the kernel part only. - `.meshes()` gives each body's display mesh as `{ key, positions, normals, indices, lines }`. `lines` are the display edges as segment pairs: the edges a selector offers, with seams and smooth joins left out. ```js const [mesh] = part().box({ w: 10, d: 20, h: 30 }).meshes(); assert.equal(mesh.lines.length, 12 * 2 * 3); // the box's 12 edges, each a segment of two points ``` ### Selectors - **Edges:** `along(axis)`, `straight()`, `curved()`, `on(face)`, `where(test)`, `sortBy(axis)`, `first(n)`, `last(n)`, `count`, `list()` and `names()`. - **Faces:** `facing('+z')`, `planar()` and `curved()`, the same filters and sorts, and `edges()`. - **What they offer:** the edges a person could pick in the studio, and nothing else. A cylinder's seam and the joint between a hole's two half-cylinders are left out, since there is no corner there to round. - **Names, not indices.** A selector resolves to the edges' persistent names, such as `n1.side0|n1.side1`, when the verb runs. Editing an earlier feature keeps the names, so the feature follows the same edges, or is refused, typed, when they are gone. It is never given other edges. ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }); const top = plate.select().faces().facing('+z'); assert.deepEqual(top.names(), ['n1.top']); assert.equal(top.edges().count, 4); // the top face's four edges assert.equal(plate.select().edges().along('z').count, 4); // the four vertical edges ``` ## CAD model part {#studio-parts} ```js import { part, assembly, Location, param, BarocssError } from '@barocss/cad-model/api'; ``` `@barocss/cad-model/api`'s `part()` builds a CAD model part over a `StudioDoc`. It shares the modeling interface with the CAD kernel part and adds document, material, drawing and manufacturing features. The same bracket can be written three ways as a CAD model document. The sample checks that all three ways give the same document, byte for byte. 1. **The document**, as the studio's commands write it. Besides the shape, it keeps: - the box's values (`made`), so picking it in the studio edits them again; - the face the hole went into (`face`); - each filleted edge's geometry where it was picked (`sigs`), so the fillet can find its edges again after an edit. ```js // 1. The document, as the studio's commands write it: the box's values remembered (`made`), the face the hole went // into, and each filleted edge's geometry where it was picked (`sigs`). const EDGES = ['n1.side0|n1.side1', 'n1.side0|n1.side3', 'n1.side1|n1.side2', 'n1.side2|n1.side3']; const raw = { format: 'barocss-cad-model', schema: 3, units: 'mm', parameters: {}, nodes: [ { kind: 'sketch', profile: 'rectangle', min: [0, 0], max: [80, 40], id: 'n0' }, { kind: 'extrude', sketch: 0, height: 10, id: 'n1', made: { command: 'box', values: { w: 80, d: 40, h: 10, x: 0, y: 0, z: 0 } } }, { kind: 'hole', parent: { node: 1, side: 'solid' }, radius: 4, center: [20, 20], face: 'n1.top', id: 'n2' }, { kind: 'fillet', parent: { node: 2, side: 'solid' }, edges: EDGES, radius: 2, id: 'n3', sigs: { 'n1.side0|n1.side1': { k: 'line', p: [80, 0, 5], d: [0, 0, 1], s: 10 }, 'n1.side0|n1.side3': { k: 'line', p: [0, 0, 5], d: [0, 0, 1], s: 10 }, 'n1.side1|n1.side2': { k: 'line', p: [80, 40, 5], d: [0, 0, 1], s: 10 }, 'n1.side2|n1.side3': { k: 'line', p: [0, 40, 5], d: [0, 0, 1], s: 10 }, } }, ], outputs: { b3: { node: 3, side: 'solid' } }, nextId: 4 }; ``` 2. **The agent's commands.** `run_command`, the features tool's `command`, with the faces and edges by persistent name. Written this way, each name has to be read from the result before it. ```js // 2. The agent's v2 commands (the features tool's `command`, run_command): the faces and edges by persistent name. const commands = [ { command: 'box', values: { w: 80, d: 40, h: 10, x: 0, y: 0, z: 0 } }, { command: 'hole', faces: ['n1.top'], values: { type: 'through', d: 8, x: 20, y: 20 } }, { command: 'fillet', edges: EDGES, values: { radius: 2 } }, ]; ``` 3. **The facade.** For this bracket, it uses the same command names and value names, with selectors in place of names. These calls run the studio's commands, as `run_command` does. ```js // 3. The facade: the same command names, the same value names (no unit suffix), the selectors in place of // the names. const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass('al6061'); // or mass({ density: 2.7 }); native results also report method and an optional volumeBasis const step = bracket.step(); // STEP AP214 text const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` - **Immutability.** ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }); const holed = plate.hole(body => body.faces().facing('+z'), { d: 6, x: 30, y: 20 }); assert.equal(plate.doc.nodes.length, 2); // the sketch and its extrude, still assert.equal(holed.doc.nodes.length, 3); const copy = holed.doc; copy.nodes.length = 0; assert.equal(holed.doc.nodes.length, 3); // changing the copy changes nothing ``` - **Materials.** `.mass()` takes a material id from the library, such as `al6061`, or `{ density }`. `.material(id)` sets the chosen body's material, or every body's, as the agent's `set_material` writes it. `.mass()` with no argument then weighs the body in it, and `.meshes()` carries the id for a scene to look up. ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }).material('al6061'); // as set_material writes it assert.equal(JSON.stringify(plate.mass()), JSON.stringify(plate.mass('al6061'))); // weighed in its own material assert.equal(plate.meshes()[0].material, 'al6061'); // for a scene to look up ``` ### Text from a font file `StudioPart.text(font, text, options)` creates a new independent output. `size` is the em height in mm and `h` is a positive extrusion height. `tolerance` is the explicit outline chord bound (default 0.01 mm). Optional `tracking` adds mm between scalars; optional `plane` supplies `origin`, `normal` and `xAxis`. Size, height and tracking can use the existing `Dim` parameter binding. Separate glyph components can remain several physical bodies in one output. ```js import { readFile } from 'node:fs/promises'; import { fontFromBytes, part } from '@barocss/cad-model/api'; const bytes = new Uint8Array(await readFile('./font.ttf')); const font = await fontFromBytes(bytes, { filename: 'font.ttf' }); const label = part('label').text(font, 'A', { size: 10, h: 2, tolerance: 0.002, tracking: 0.2, }); const doc = label.doc; ``` Supply an admitted static TrueType original. Optional `source` and `license` metadata are preserved as supplied; they are not inferred. The recipe keeps the original string, source and dimensions, while the blob store keeps the original bytes for the existing `.bcad` container path. There is no OS font lookup or fallback substitution. This call does not join existing bodies. Shaping, kerning, bidi, normalization and text wrap are not implemented. The separate bounded modifier below embosses or engraves a supported top face. See [Text from font outlines](/how/text) for input limits and refusals. ### Text relief on a top face `StudioPart.textRelief(selector, font, text, options)` modifies the selected body. The selector must return one exact unmerged +Z top face, for example `b => b.faces().facing('+z')`. The native target must be one closed line-only upright slab with one physical solid. Every filled text component must fit within both its actual material and that selected face's trim, with clearance for flatness and native policy. Overlap/contact between components, unsupported source representations and ambiguous face names are refused. ```js // Reuse the imported font source from the example above. const plate = part('label plate').box({ w: 40, d: 30, h: 10 }); const raised = plate.textRelief(b => b.faces().facing('+z'), font, 'A', { size: 10, depth: 2, at: [5, 5], mode: 'emboss', tolerance: 0.002, }); const pocket = plate.textRelief(b => b.faces().facing('+z'), font, 'A', { size: 10, depth: 2, at: [5, 5], mode: 'engrave', tolerance: 0.002, }); ``` Required options are `size`, positive `depth`, world-XY baseline `at:[x,y]`, and `mode:'emboss'|'engrave'`. Optional `tolerance` defaults to 0.01 mm and `tracking` to zero. Size, depth, both baseline coordinates and tracking accept existing `Dim` bindings. There is no plane option. Engrave must leave a bottom web above the existing native linear tolerance; emboss needs a represented positive raised height and seat. The result is one physical solid. The original font/string/recipe remains editable and uses the existing `.bcad` asset path. The selected Korean `가한` Model fixtures pass at size 10, at `[5,5]`, depth 2 and the default tolerance 0.01. The tighter Myeongjo engrave fixture at 0.002 explicitly refuses the unchanged work budget and keeps its requested tolerance. The API does not increase tolerance to force success. The source `plate` is unchanged. See [Text relief](/how/text#emboss-or-engrave-a-top-face) for limits and refusals. ### The studio's own commands The CAD model part provides these Studio commands as methods. For these calls, it writes what the agent's `run_command` writes. The kernel part has no `gear()`, `gearMesh()`, `spring()` or `fastener()` method. The CAD kernel also provides lower-level gear and spring functions through `@barocss/cad`; those functions have their own inputs and outputs. | Verb | v2 command | What it does | |---|---|---| | `gear({ m, teeth, b, shift?, helix?, hand?, bore?, x?, y?, z? })` | `gear` | An involute spur or helical gear, a body of its own | | `gearMesh({ teeth, dir, bore?, shift? })` | `gear-mesh` | A gear meshing with the chosen one, `dir` degrees from +X | | `spring({ type, d, D, n, p, ends, hand, … })` | `spring` | A coil spring of round wire, by the command's values | | `fastener({ kind, size, length?, joint?, grip?, x?, y?, z?, model? })` | `fastener` | A bolt, screw, nut or washer, from the document's fastener-size rows | ```js // A module-1.5 spur gear of 20 teeth, 10 wide, with a Ø20 bore; then a 40-tooth gear meshing with it along +X. const pair = part('pair') .gear({ m: 1.5, teeth: 20, b: 10, bore: 20 }) .gearMesh({ teeth: 40, dir: 0, bore: 16 }); const [pinion, wheel] = pair.bodies(); const centre = pair.body(wheel).mass({ density: 1 }).centroid; assert.ok(Math.abs(centre[0] - 1.5 * (20 + 40) / 2) < 1e-6); // the centre distance, m (z1 + z2) / 2 = 45 const spring = part('spring').spring({ type: 'compression', d: 2.5, D: 18, n: 5, p: 6, ends: 'closed-ground', hand: 'right' }); ``` - **Rows come from a person's file.** `loadRows(kind, { name, text })` loads a rows file as the studio's Library does, with a receipt naming the file. The facade never writes rows itself, and nothing is built in, so `fastener` is refused until fastener sizes are loaded. The same file always loads the same bytes. The sample uses the rows cad-model ships under `samples/rows/`. ```js // The fastener sizes cad-model ships as a sample; your own file loads the same way. None is built in. const sizes = { name: 'fastener-sizes.json', text: readFileSync(resolve(import.meta.dirname, '../../../packages/barocss-cad-model/samples/rows/fastener-sizes.json'), 'utf8') }; assert.throws(() => part('bolt').fastener({ kind: 'hex-bolt', size: 'M8', length: '60' }), e => e instanceof BarocssError && e.code === 'FASTENER_SIZE_ROW'); // no rows loaded: refused const bolt = part('bolt') .loadRows('fastener-sizes', sizes) // its receipt names the file, as the studio's Library writes it .fastener({ kind: 'hex-bolt', size: 'M8', length: '60' }); assert.equal(bolt.bodies().length, 1); ``` The CAD model part also has `loft()` for a solid through closed sections. See [Solid lofts with a copied guide](/packages/cad-model/#solid-lofts-with-a-copied-guide) for its inputs, limits and example. ## Parameters, configurations and suppression A parameter is a named value in the document's `parameters`, and a dimension follows it as the documents' own reference, `{ parameter: 'W' }`. `param('W')` writes one. Both parts write the document a person would make: the kernel part writes the reference into its feature, and the CAD model part binds it as the studio's feature editor does. ```js // An 80 × 40 × 10 plate, its width W and its corners' radius R parameters. const plate = part('plate').parameter('W', 80).parameter('R', 2) .box({ w: param('W'), d: 40, h: 10 }) .fillet(body => body.edges().along('z'), { radius: param('R') }); assert.deepEqual(plate.doc.parameters, { W: 80, R: 2 }); assert.deepEqual(plate.doc.features[0].max, [{ parameter: 'W' }, 40]); // the document's own reference const narrow = plate.withParameters({ W: 60 }); // a new part; the plate is unchanged assert.deepEqual(withParameters(plate.doc, { W: 60 }).parameters, { W: 60, R: 2 }); // the same, on a plain document // A 60-wide plate with its four corners rounded 2. const expected = 60 * 40 * 10 - 4 * (2 ** 2 - Math.PI * 2 ** 2 / 4) * 10; assert.ok(Math.abs(narrow.mass({ density: 1 }).volume - expected) < 1e-6 * expected); ``` - **`parameter(name, value)`** adds or sets a parameter. A name is a letter, then letters, digits and `_`, up to 32. `parameters()` lists them. - **`withParameters({ name: value })`** returns a new part at the new values. A document with features is re-evaluated before the method returns; its features keep the faces and edges they stored. The separate `withParameters(doc, edits)` function updates a plain document without evaluating it. - **Which options can follow a parameter.** Only one that lands as it is in one place in the document, the same rule as the studio's feature editor: - `box`: `w` and `d` while `x` and `y` are 0, and `h`; - `cylinder`: `x`, `y` and `h` (not `r`: the studio's editor edits the diameter); - `extrude`: `h`; `hole`: `x` and `y` (not `d`: the hole is stored by its radius); - `fillet`: `radius`; `chamfer`: `distance`; `shell`: `t`; `linearPattern`: `spacing`; `split`: `at`; - in the CAD model part also `revolve`'s `deg`, `linearPattern`'s `count` and `scale`'s `factor`, which a kernel document holds as plain numbers. Any other option given a parameter is refused with `PARAMETER_UNBINDABLE`, naming the ones that bind. A number is never written in its place. Sketch sizes and a `Location` take numbers only. ```js const p = plate(); assert.deepEqual(p.parameters(), { W: 80, R: 2 }); assert.deepEqual(p.doc.nodes[0].max, [{ parameter: 'W' }, 40]); // the sketch's far corner follows W assert.deepEqual(p.doc.nodes[2].radius, { parameter: 'R' }); // the fillet's radius follows R const narrow = p.withParameters({ W: 60, R: 3 }); assert.ok(near(volume(narrow), plateVolume(60, 3))); // the shape built with the new numbers assert.deepEqual(narrow.doc.nodes[2].edges, p.doc.nodes[2].edges); // the same named edges ``` - **Configurations** are the CAD model part's saved sets of parameter values. `configuration(name)` saves the current values, as the Parameters panel's Save; `withConfiguration(name)` applies them, as its Apply; `configurations()` lists them. ```js const p = plate().configuration('wide') // the current values, as the panel's Save .withParameters({ W: 60 }).configuration('narrow'); assert.deepEqual(p.configurations(), { wide: { W: 80, R: 2 }, narrow: { W: 60, R: 2 } }); const wide = p.withConfiguration('wide'); // its values applied, as the panel's Apply assert.deepEqual(wide.parameters(), { W: 80, R: 2 }); ``` - **Features and suppression.** `features()` lists each feature's `{ id, kind, label }`, the last one being the feature the last verb added. `suppressed(id)` switches a feature off and `suppressed(id, false)` back on, as the History panel's toggle does. A sketch, a split or a separate can't be switched off. It's the CAD model part's: the kernel document has no suppression yet, so the kernel part refuses it with `UNAVAILABLE`. ```js const p = plate(); assert.deepEqual(p.features().map(f => [f.id, f.kind]), [['n0', 'sketch'], ['n1', 'extrude'], ['n2', 'fillet']]); const sharp = p.suppressed('n2'); // as the History panel's toggle writes it assert.ok(near(volume(sharp), 80 * 40 * 10)); // the unrounded plate assert.equal(JSON.stringify(sharp.suppressed('n2', false).doc), JSON.stringify(p.doc)); // back, byte for byte ``` - **No expressions.** Neither document can store one, such as `W / 2`, so a dimension follows one parameter as it is. ## Assemblies `assembly(name, base?)` is an immutable assembly over the CAD model document. The base part is fixed at the origin. Placed parts are instances, each with its own document, and mates relate their faces. A supplied base and each `addPart` argument must be a `StudioPart` instance from the same loaded `@barocss/cad-model/api` package. Create it with that package's `part()` function. A kernel part or a plain document is not accepted; the facade refuses it with `VALUE`. The base argument can be omitted. ```js // A 60 × 40 × 8 plate with a Ø10 bore at (20, 20), and a Ø10 pin 30 long. const plate = part('plate').box({ w: 60, d: 40, h: 8 }).hole(b => b.faces().facing('+z'), { d: 10, x: 20, y: 20 }); const pin = part('pin').cylinder({ r: 5, h: 30 }); const fixture = assembly('fixture', plate) // the base part, fixed at the origin .addPart('pin', pin, { at: Location.at([100, 0, 0]) }) // placed off to the side .addMate('concentric', { part: 'base', face: b => b.faces().curved() }, { part: 'pin', face: b => b.faces().curved() }) .addMate('distance', { part: 'base', face: b => b.faces().facing('-z') }, { part: 'pin', face: b => b.faces().facing('-z') }, { distance: 0, flip: true }) // the bottoms flush .inputs({ depth: { type: 'number', unit: 'mm', default: 0, min: -10, max: 10, bindings: [{ to: 'mate', mate: 'm2', field: 'distance' }] } }) // an input driving the second mate .variants({ low: { depth: -5 } }) .frames({ tip: { link: 'pin', at: Location.at([0, 0, 30]), kind: 'tool' } }); assert.deepEqual(fixture.placements()[0].position, [20, 20, 0]); // solved: in the bore assert.deepEqual(fixture.variant({ depth: -5 }).placements()[0].position, [20, 20, 5]); assert.deepEqual(fixture.framePoses()[0].position, [20, 20, 30]); // the tip, on the pin's top assert.deepEqual(fixture.meshes().map(m => m.key), ['base/b2', 'p1/b2']); // each part where it stands ``` - **The verbs carry the agent's assembly action names.** Each writes what that action writes, and the assembly is solved again after it: - `addPart(name, part, { at?, grounded? })` is `add_part`, with the part's document as it is; - `place(name, { at?, grounded? })` is `place_part`; - `addMate(kind, a, b, { distance?, angle?, flip? })` is `add_mate`. Each end is `{ part, face, body? }`: the part is `'base'` or a placed part by its name, and the face is a selector picking one face, or a face name; - `inputs({ name: input | null })` and `variants({ name: values | null }, active?)` are `set_inputs` and `set_variants`. Bindings name parts and mates by id: `parts()` lists the parts' ids, and mates are `m1`, `m2` … in order; - `frames({ name: { link, at?, kind? } | null })` is `set_frames`. The link is a part by name, and `at` is a Location in that part's own coordinates. - `lock(name, to?)` fixes a placed part to another part, the base by default, at its current placement. For a face-selector callback, supply `body` with that part's body key when it has several bodies. With no `body`, only a single-body part is selected automatically. An unavailable or ambiguous body gives `NO_BODY` or `BODY_AMBIGUOUS`; a callback selecting zero or several faces gives `SELECTION_ONE`. A string face name does not use this callback body-selection step. Distance mates require a finite distance in mm. Angle mates require a finite angle from 0° to 180°, inclusive. Missing or non-finite facade values give `VALUE`; an out-of-range angle is refused with `MATE_FACES`. `addMate` normally moves the second end's part. If it is fixed and the first is free, the ends swap. Two fixed ends give `MATE_BOTH_FIXED`; ends on the same part give `MATE_SAME_PART`. `place` re-solves the mates, and `grounded: true` on a part already moved by a mate gives `PART_MATED`. - **Its results are plain data:** - `parts()`; - `placements()`: each placed part's id, name, `position` (mm), `rotation` (degrees) and grounding; - `problems()`: the mates left unmet; - `variant(values)`: an assembly with those input values, the master unchanged; - `framePoses()`: each frame's world pose, as `position` and `rotation`; - `meshes()`: `base/` and `/`, each part where it stands; - `part(name)`: a placed part as a CAD model part, in its own coordinates. - **`robot()`** gives the assembly's joints, kinematics, motion checks and robot exports. See [Robots](/studio/robots) for the supported joints and motion limits. - **Not yet in the facade:** editing a placed part in place; deleting or editing parts and mates; library parts; an assembly's STEP. ## Manufacturing inputs and outputs The CAD model part can set its manufacturing inputs and produce the same outputs as the agent's tools. These methods call the studio core. They keep its typed refusals. | Method | What it writes or returns | |---|---| | `process(id, { pull? })` | The part's process and, for a casting, its pull direction | | `casting(options)` | The pattern inputs, including machined faces, gate and shrinkage | | `drawingSettings(options)` | The drawing settings | | `autoDimension()` | Dimensions added by the drawing core | | `bought()` | The part's bodies marked as bought | | `named(name)` | The chosen body's display name | | `drawing()` | The sheet, its issues, and SVG, DXF and PDF files | | `await manufacturability(options?)` | The process report, as `check_printability` returns it | | `await camPackage(options?)` | The 2.5D CAM preview reply from `output_cam_package`, not for production | An assembly also has `drawingSettings(options)` and `drawing()`. Its `await bom()` returns the `output_bom` reply; `await purchaseCsv(withMade?)` returns the `output_purchase_csv` reply. The purchase list leaves out made parts unless `withMade` is true. A report can contain failed rules. Receiving it does not mean the part passed its checks. A CAM package needs stock rows from a person's file; without them it refuses with `STOCK_NONE_LOADED`. No stock table is built in. ### Product example: single-cylinder engine The repository's `examples/products/engine-1cyl/` uses the studio facade to build a single-cylinder four-stroke engine. Its merged milestone 3 includes manufacturing inputs, dimensioned drawings, reports, the BOM and the purchase list. The saved assembly is `engine.bcad`. `build.ts` constructs it; `check.ts` checks a saved document, regardless of how it was built. `engine.test.mjs` checks the saved build and includes a negative case with the piston's bore mate removed. The example's checks cover parts, assembly constraints, the slider-crank cycle, timing, sweep, masses, balance and outputs. Its unit tests omit the sweep; the full runner includes it. These are scripted checks. They do not establish live-agent or manufacturing acceptance. The example still has limits: - **Missing rows (PG-2).** The spark-plug thread and main bearings need rows from a source the owner supplies. The plain plug hole and bearing stand-ins do not establish a catalogue fit. - **Evaluation cost (PG-3).** The engine head and valve spring still need profiling. - **Example workarounds.** Although the core now supports cam mates, locked-gear coupling, running-fit contact and closed-loop motions, this saved example still builds gears into their shafts, parks its followers and uses its own cycle and sweep checks. Those newer core features do not by themselves verify a rebuilt engine. - **CAM waits (PG-9).** No stock list ships with the example. The output check accepts `STOCK_NONE_LOADED` as a named wait, so a passing check can still have no CAM package. - **Base-body names (PG-10).** The BOM still lists the base part's bodies by key, even when their display names are set. See [Shop rows](/studio/rows), [Manufacturing](/studio/manufacturing) and [BOM and quotes](/studio/bom) for the inputs these outputs need. ## Errors ```js const block = part().box({ w: 10, d: 10, h: 10 }); assert.throws(() => part().mass({ density: 2.7 }), e => e instanceof BarocssError && e.code === 'NO_BODY'); assert.throws(() => block.mass({ density: -1 }), e => e instanceof BarocssError && e.code === 'DENSITY'); assert.throws(() => part().box({ w: -1, d: 10, h: 10 }), e => e instanceof BarocssError && e.code === 'VALUE'); // A hole goes into one face: two picked is refused before the kernel. assert.throws(() => block.hole(body => body.faces().planar(), { d: 2, x: 5, y: 5 }), e => e instanceof BarocssError && e.code === 'SELECTION_ONE'); // A fillet too large for its walls: the kernel's refusal, with the feature it came from. assert.throws(() => block.fillet(body => body.edges().along('z'), { radius: 50 }).mass({ density: 2.7 }), e => e instanceof BarocssError && e.code === 'RADIUS_EXCEEDS_FACE' && e.where === 'evaluate' && e.details?.feature === 'fillet1' && e.message.startsWith('[RADIUS_EXCEEDS_FACE] ')); ``` - **The facade's own codes,** checked before the core: - the part: `NO_BODY`, `BODY_AMBIGUOUS`, `BODY_UNKNOWN`, `SELECTION_EMPTY`, `SELECTION_ONE` (a hole's selector picked more than one face, or a tool callback added more than one body), `FACE_NOT_FLAT`, `VALUE` (a value out of its range or type), `DENSITY`, `PARAMETER_NAME`, `PARAMETER_UNKNOWN`, `PARAMETER_UNBINDABLE` and `FEATURE_UNKNOWN`; - the CAD model part: `SELECTION_UNKNOWN` (a name not on the part), `UNAVAILABLE` (the studio's command can't run here), `MATERIAL_UNKNOWN`, `MASS_UNKNOWN` and `CONFIGURATION_UNKNOWN`; - the assembly: `NAME_TAKEN` and `PART_UNKNOWN`. - **The core's refusals pass through** with their own code and words. A kernel refusal keeps the feature it came from in `details.feature`; a studio one keeps the core's own words in `details.friendly`. A fillet too large for its walls is refused as `RADIUS_EXCEEDS_FACE` by both parts. ```js assert.throws(() => part().hole(body => body.faces().facing('+z'), { d: 4, x: 0, y: 0 }), e => e instanceof BarocssError && e.code === 'NO_BODY' && e.where === 'facade' && e.message.startsWith('[NO_BODY] ')); assert.throws(() => part().box({ w: 10, d: 10, h: 10 }).mass('unobtainium'), e => e instanceof BarocssError && e.code === 'MATERIAL_UNKNOWN'); // A fillet too large for its walls: the kernel's own code, with the core's words. assert.throws(() => part().box({ w: 10, d: 10, h: 10 }).fillet(body => body.edges().along('z'), { radius: 50 }).mass('al6061'), e => e instanceof BarocssError && e.code === 'RADIUS_EXCEEDS_FACE' && e.where === 'evaluate' && !!e.details?.friendly); ``` ## Scenes ```js import { scene, LINE_MATERIAL, BarocssError } from '@barocss/gpu/api'; import { part } from '@barocss/cad/api'; import { part as studioPart } from '@barocss/cad-model/api'; ``` A scene is an immutable description of meshes, each with its material, lights, a background and a camera view: ```js const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }); const view = scene() .add(bracket.meshes(), { color: '#c8ccd2', roughness: 0.5 }) .light({ kind: 'directional', direction: [-0.4, 0.6, -1] }) .background('#ffffff'); const data = view.data; assert.equal(data.frame, 'z-up'); // CAD coordinates as given, no conversion assert.equal(data.meshes.length, 1); assert.ok(data.meshes[0].positions instanceof Float32Array); // typed arrays only in the meshes (Float32, the common shape) assert.deepEqual(data.lights, [{ kind: 'directional', direction: [-0.4, 0.6, -1] }]); // show(viewer, view) clears the viewer, sets its lights and background, adds each mesh and fits the view. ``` - **Building it.** - `scene()` makes an empty scene. - `.add(meshes, material?, { lines? })` takes one mesh, or a part's `.meshes()`. The material is a Material, or the id of one the scene registered; without one, each mesh takes the scene material its body names. `lines: true` (or a Material) also adds each mesh's display lines as line geometry, keyed `/lines`, thin and dark by default (`LINE_MATERIAL`). - `.material(id, look)` registers a Material under an id: a part's material id, such as `al6061`, or one of your own. No look is built in for a material id. - `.light(light)` takes a directional, point or spot light, in the Viewer's own terms. - `.background(value)` takes a colour, a gradient or `'transparent'`. - `.camera(view, { projection?, fovY? })` takes `'iso'`, `'front'`, `'back'`, `'right'`, `'left'`, `'top'`, `'bottom'`, or `{ direction, up? }`: the direction from the scene to the eye. The top and bottom views keep +Y up, the others +Z. - **`.data`** is the plain description, with `frame: 'z-up'`. Material ids stay ids in it, and the looks are under `materials`. - **`show(viewer, scene)`** presents it through the Viewer's public methods only. It: - clears the viewer; - sets the lights and background, when the scene has them; - adds each mesh under its key, with its material resolved; - when the scene has a camera view, sets the camera's projection, field of view and up, and puts the eye along the view's direction; - fits the view. The Viewer stays the one stateful object. ```js const plate = studioPart('plate').box({ w: 60, d: 40, h: 8 }).material('al6061'); const view = scene() .material('al6061', { color: '#b8bcc2', metallic: 1, roughness: 0.35 }) // a look for the part's material id .add(plate.meshes(), undefined, { lines: true }) // each mesh in the look its body names, and its lines .camera('iso', { projection: 'orthographic' }); const { meshes, materials, camera } = view.data; assert.deepEqual(meshes.map(m => [m.key, m.topology ?? 'triangles', m.material]), [['b1', 'triangles', 'al6061'], ['b1/lines', 'lines', LINE_MATERIAL]]); assert.deepEqual(Object.keys(materials), ['al6061']); // the ids stay in the data; show() resolves them assert.deepEqual(camera.up, [0, 0, 1]); ``` - **Its errors.** `MESH_INVALID`, `LIGHT_INVALID`, `MATERIAL_UNKNOWN`, `MATERIAL_INVALID` and `CAMERA_INVALID`, in gpu's own `BarocssError` of the same shape: gpu imports neither cad package. ```js const empty = scene(), lit = empty.light({ kind: 'directional', direction: [0, 0, -1] }); assert.equal(empty.data.lights, undefined); // the first scene is unchanged assert.equal(lit.data.lights.length, 1); assert.throws(() => scene().add({ positions: new Float64Array([0, 0]) }), e => e instanceof BarocssError && e.code === 'MESH_INVALID'); ``` `show()` needs a browser with WebGPU, so this site's samples stop at `.data`. gpu's own tests check `show()` two ways: - against a stand-in viewer, for the calls it makes, in order; - in Chrome's WebGPU, on a hardware adapter and on SwiftShader. A plate with a bore is drawn from the top, orthographic: its top in al6061's registered look, the background through the bore, and a display line on the bore's rim. ## Not in the facades yet - **Expressions** in dimensions, and feature names of your own: the stable ids (`n3`, `fillet1`) serve. - **Suppression in the kernel part,** until the kernel document carries it. - **More of the assembly,** as listed under [Assemblies](#assemblies). --- # @barocss/cad-model For joint timing, pose sampling and the boundary with dynamics, see [Robot motion](/guide/robot-motion). The studio's model layer, on top of [the kernel](/packages/cad/). It holds: - the document and its evaluation; - the modelling commands; - the analyses and manufacturability checks; - drawings, BOMs, robots and libraries; - the agent's tools. It has no UI: no React, no DOM and no browser storage. An app, such as the studio, supplies those. ## Importing by path Prefer the curated domain entrypoints for new code: - `@barocss/cad-model/api` - `@barocss/cad-model/doc` - `@barocss/cad-model/engine` - `@barocss/cad-model/sketch` - `@barocss/cad-model/assembly` - `@barocss/cad-model/drawing` - `@barocss/cad-model/chat` - `@barocss/cad-model/versions` - `@barocss/cad-model/app` - `@barocss/cad-model/mfg` - `@barocss/cad-model/robot` Legacy per-file subpaths remain temporarily available during migration; the package's own root entry exports nothing. ```js import { part } from '@barocss/cad-model/api'; // the object facade import { evaluateDoc, exportStudioStep } from '@barocss/cad-model/engine/evaluate'; // the core, module by module import { encodeStudioFile, readStudioFile } from '@barocss/cad-model/engine/container'; import { revisionOf } from '@barocss/cad-model/util/revision'; ``` - **Version.** It is `0.0.0` and unreleased. Its API can change between versions: there is no compatibility promise yet. - **TypeScript sources.** Its modules are the TypeScript sources themselves, as with the kernel. - **Data files.** JSON data is imported by path too, such as `@barocss/cad-model/library/builtin/materials.json`, and the shipped sample rows are under `@barocss/cad-model/samples/rows/`. The `engine/font/trueType` reader takes a copied, bounded static TTF input and returns metrics and unhinted quadratic contours. `engine/font/source` stores original bytes with supplied filename/source/license metadata; `engine/font/profiles` converts admitted glyphs to component profiles at an explicit chord tolerance. The `kind: 'text'` recipe and `part().text()` build an independent native solid that stays editable after Save/Open. One authored output can hold several physical bodies. No top-level font registry or new document/container version is added. Studio supplies font upload and the Text HUD; the original test fonts are not runtime defaults. The separate `text-relief` modifier and `part().textRelief()` share the source/profile path for bounded +Z cap emboss or engrave; they retain one physical target solid and require actual material/selected-face containment. Shaping, kerning, bidi, normalization, general/curved face relief and text wrap remain unsupported. See [Text from font outlines](/how/text) and the [Text API example](/packages/api#text-from-a-font-file). | Module | What it holds | |---|---| | `api/` | The object facade over the data-and-functions core, imported as `@barocss/cad-model/api`. `part()` makes an immutable studio part and `assembly()` an immutable assembly, each method returning a new one, with typed edge and face selectors, `.doc`, plain results and one error class, `BarocssError`. See [Object API](/packages/api) | | `doc/` | Pure document data types (`StudioDoc`, `ModelNode`, domain, drawing, report and workflow types), node graph helpers, ids, labels, materials and validation | | `schema/` | Single-source Zod runtime schemas for document primitives, feature nodes and agent tool inputs, with JSON Schema export | | `history/` | Command-pattern undo/redo stack (`CommandStack`) for deterministic document mutations | | `engine/` | The studio document compat barrel (`doc`), its evaluation into bodies and meshes, ids, mesh blobs, the `.bcad` container, shop rows and their sources, flattening an assembly | | `engine/schema/` | The types of the brief, questions, references, drafts, requirements and proposals; their functions are in `chat/` | | `sketch/` | Sketch profiles, constraints, trim, offset, corners, splines, reading a DXF and its underlay | | `app/` | The modelling commands as data: shapes, edits, holes, fasteners and threads, sheet metal, mass, measure, materials | | `assembly/` | Placed parts and mates: solving, shared definitions and revisions, drag, exploded views | | `subd/` | Editing a SubD cage | | `frames/` | Frames and weldments: sections, skeletons and 3D sketches, welds, nesting into stock lengths | | `chat/` | The agent's tool layer: the handlers, the 13 tools (`toolset`, `groups`), the contract, the script language, and the brief's, questions' and proposals' functions | | `drawing/` | The 2D drawing: views, sections, dimensions, tolerances, tables, issues | | `print/` | The manufacturability report, 3D printing's rules and preparation, and 3MF | | `mould/` | Injection moulding: draft, undercuts, walls, the parting line, the quote package | | `machining/` | CNC milling and turning: holes, pockets, access and setups, stock, a 2.5D preview (not for production) | | `casting/` | Die and sand casting: the report and the pattern, from your casting rules | | `robot/` | The mates as a robot: joints, kinematics, inertia, dynamics, actuator sizing, URDF, MJCF, SDF and USD | | `library/` | Materials, process profiles, and standard and team part libraries, as data | | `standards/` | Values derived from standards, with their sources and licences | | `versions/` | Named versions of a document and its branches: making, listing and restoring versions, compare (what changed, feature by feature) and a three-way merge with typed conflicts | | `team/` | Export sources, several agents on one part, baselines, freshness, change requests, bundles | | `analysis/` | The analyses the agent asks for (mass properties, interference and clearance, sections, wall thickness, draft), and alignment against a reference part | | `bom/` | The bill of materials | | `io/` | Output formats: the drawing's SVG, PDF and DXF, and a zip writer with no dependencies | | `util/` | Small shared helpers: unit factors, guards, ids, rounding, SHA-256 digests, the document revision | ## Drawing text layout `tableSize` and `tableLayout` in `@barocss/cad-model/drawing/table` accept an optional final `textHeight` argument, in sheet millimetres. Pass the same height to both helpers so the reserved size matches the drawn table. `tableLayout` keeps its existing third `corner` argument; `textHeight` is fourth. `symbolMarks` and `weldSymbols` in `@barocss/cad-model/drawing/welds` also accept an optional final `textHeight`. Weld label placement measures the resulting text at that height. All four helpers default to 2.5 mm, and reject a non-finite or non-positive height with `RangeError`. `buildSheet` supplies 3 mm for these ordinary labels under its ASME preset. See [Drawing standard](/studio/drawings#drawing-standard) for the preset's scope and limits. ## Reading saved render settings Import `readRender` and `validateRenderShadowLights` from `@barocss/cad-model/engine/render`. `readRender(value)` returns `RenderSettings` with the reader's existing defaults and clamps. For a supplied `lights` array, it reads only the first 12 input entries, before skipping unknown light kinds. It then applies the shadow-field checks. Invalid shadow fields or caster counts throw `VALUE`. `validateRenderShadowLights(lights)` returns `void` without changing the supplied lights. It checks point/spot shadow fields and eligible caster counts. It does not validate GPU position, direction or range inputs. Invalid shadow fields or caster counts throw `VALUE`. See [Saved render light fields](/reference/document#saved-render-light-fields) for the stored fields, eligibility limits and radius rules. ## Transforming one body A studio part inherits `moved(location)` from the shared Part API. It returns a new part with transform features; it does not set an absolute assembly placement. Keep the returned part. Calling `moved` on that returned part applies the transform again to its current geometry, while the original part stays unchanged. Use `part.bodies()` to obtain current body keys. With several bodies, first choose `part.body(key)`; `moved` acts on that body, not every body in the document. A missing body gives `NO_BODY`, no choice among several gives `BODY_AMBIGUOUS`, and an unknown key passed to `body(key)` gives `BODY_UNKNOWN`. ```ts import { Location, type StudioPart } from '@barocss/cad-model/api'; function turnAndMove(part: StudioPart, bodyKey: string): StudioPart { return part.body(bodyKey).moved(Location.of({ rotation: [0, 0, 90], position: [30, 0, 0], })); } ``` `Location` rotations use degrees about the document origin, in X, then Y, then Z order. Translation follows in world XYZ millimetres. It does not rotate about the body's centre or use its bounding box as a pivot. For the location above, an illustrative point on the body follows this calculation: | Step | Point in mm | |---|---| | Input | `[10, 0, 0]` | | Rotate +90° about Z | `[0, 10, 0]` | | Translate by `[30, 0, 0]` | `[30, 10, 0]` | | Apply the same location again | `[20, 30, 0]` | ![A body point is rotated about the origin before translation; repeating moved applies another transform](/diagrams/part-transform-order.svg) [Open the diagram at full size](/diagrams/part-transform-order.svg). The diagram is a coordinate calculation, not an API render or a construction check. For placement of an assembly instance, use [the assembly API](/packages/api#assemblies); for other body transforms, see [Object API](/packages/api#parts). ## Writing a root body's STL Import `evaluateDoc` and `stlFor` from `@barocss/cad-model/engine/evaluate`. `stlFor` takes a `StudioDoc`, a root body's key from that document's evaluated bodies, and optional `segmentsPerQuarter` settings. This helper selects only the first evaluated root body: ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { evaluateDoc, stlFor } from '@barocss/cad-model/engine/evaluate'; function firstRootStl(doc: StudioDoc, revision: number): Uint8Array | null { const r = evaluateDoc(doc, revision); if (!r.ok || r.bodies.length === 0) return null; return stlFor(doc, r.bodies[0].key, { segmentsPerQuarter: 16 }); } ``` Supply `revision` as the caller's numeric evaluation tag; it is not the saved source-record revision. A successful evaluation can still produce `null` from `stlFor`, so check the helper's result before writing a file. A missing root body, a non-finite `segmentsPerQuarter`, or an unavailable tessellation returns `null`. The helper throws a `BarocssError` with code `STL_FLOAT32_COLLAPSE` if a valid triangle becomes degenerate in Float32, or `STL_FLOAT32_RANGE` if a coordinate cannot be written as a finite Float32. Surface these errors before writing files. The studio's [display-mesh fallback](/studio/files#exports) is a separate UI policy. ### STL and its source record To keep an STL with its source information, create both from the same document and pass the STL's exact filename to `sourceRecord`. The following helper returns two named files in memory; it does not write or download them. It returns `null` when evaluation fails, there is no root body, or tessellation is unavailable. It propagates the Float32 errors from `stlFor`. ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { evaluateDoc, stlFor } from '@barocss/cad-model/engine/evaluate'; import { sourceRecord, sourceBytes, sourceName } from '@barocss/cad-model/team/source'; type MemoryFile = { name: string; bytes: Uint8Array }; function firstRootStlFiles( doc: StudioDoc, revision: number, stlName = 'part.stl', ): [MemoryFile, MemoryFile] | null { const result = evaluateDoc(doc, revision); if (!result.ok || result.bodies.length === 0) return null; const bytes = stlFor(doc, result.bodies[0].key, { segmentsPerQuarter: 16 }); if (bytes === null) return null; const source = sourceRecord(doc, [stlName]); return [ { name: stlName, bytes }, { name: sourceName(stlName), bytes: sourceBytes(source) }, ]; } ``` The caller's numeric `revision` tags the evaluation. The source record's string `revision` instead identifies the document's canonical revision content. Its `digest` is the SHA-256 of that input content, not a checksum of the STL bytes or a certificate of geometric accuracy. `sourceName('part.stl')` gives `part.source.json`. Keep the returned pair together; after changing the document, produce a new pair rather than reusing the old record. ![STL bytes and their separate source-record JSON from the same document](/diagrams/stl-source-pair.svg) ### Reading a source record `sourceRecord(doc, files, options)` from `@barocss/cad-model/team/source` returns these fields: | Field | Meaning | |---|---| | `format` | The literal `barocss-source`. | | `version` | Record version `1`. | | `revision` | The 16-character hexadecimal revision from `revisionOf(doc)`, for detecting stale input. It covers the revision fields, not every saved document field. | | `digest` | SHA-256 of the UTF-8 canonical content used for that revision. It is not a checksum of the exported files. | | `files` | A copy of the supplied file-name list. It contains names, not file contents or checksums. | | `handSet` | Robot base-link and joint settings, included only with `{ robot: true }`. It is omitted by default. | `sourceBytes(record)` encodes the record as JSON bytes. `sourceName(name)` replaces the last extension with `.source.json`, or appends that suffix when there is no matching extension. It only derives a name; it does not validate a file name or make it safe for a destination path. When reading the JSON, treat `revision` and `digest` as identifiers for the recorded input content. Reading the record does not verify the named export files, authenticate the author, or establish physical accuracy. For robot exports, read `handSet` when present; its omission does not mean the robot used zero limits or ratings. Keep the record with the files it names and keep the editable `.bcad` document separately. The record is not a saved document and cannot reconstruct the model from its revision or digest. ## Bounded cylindrical wrap The Model facade selects the usual merged cylinder wall. The operation uses its original +Y half, first native quarter, and stores that individual native face and its signature. ```ts import { part } from '@barocss/cad-model/api'; const wrapped = part('Wrapped cylinder') .cylinder({ r: 10, h: 30 }) .cylindricalWrap(body => body.faces().curved(), { u0: 0.1, u1: 0.4, v0: 0.2, v1: 0.7, height: 10, }); const doc = wrapped.doc; ``` This supports one rectangle on an original upright cylinder at any XY center. Original UV must satisfy `0 < u0 < u1 < 0.5` and `0 < v0 < v1 < 1`; height can be any positive value within the modeling range. Mass comes from the evaluated closed reference. Literal stored-coefficient closure/mass and native-SI accuracy are not certified. Downstream features can consume the resulting solid. Reopening the recipe rebuilds its provider; a copied output cannot supply mass authority. See the [Studio flow and remaining limits](/studio/features#cylindrical-wrap). ## Solid lofts with a copied guide `part(...).loft(sections, options)` builds a solid from closed sketches. It returns a new part with the new body selected. Use that returned part or its `.doc`. The separate `directOps.loft()` operation below adds a surface to direct geometry. Supply sections in the intended order. Each section takes a `sketch` and exactly one of `z` or `frame`. A legacy `z` is a finite height in mm. Use one sketch plane and strictly increasing `z` values for that form. An explicit frame gives a world-mm `origin` and perpendicular unit `xAxis` and `yAxis` vectors. The single quadratic or cubic Bézier guide uses explicit frames. Its control points are in world mm. ```ts import { part, sketch, Plane } from '@barocss/cad-model/api'; const frame = (z: number) => ({ origin: [0, 0, z] as [number, number, number], xAxis: [1, 0, 0] as [number, number, number], yAxis: [0, 1, 0] as [number, number, number], }); const model = part('Cubic guided loft').loft([ { sketch: sketch(Plane.XY).circle({ r: 1 }), frame: frame(0) }, { sketch: sketch(Plane.XY.offset(3)).circle({ r: 4 }), frame: frame(3) }, ], { guide: { kind: 'cubic-bezier', controlPoints: [[1, 0, 0], [4, 0, 1], [2, 0, 2], [4, 0, 3]], }, }); const doc = model.doc; ``` The circles have radii of 1 and 4 mm on parallel caps 3 mm apart. The guide starts at `[1, 0, 0]` and ends at `[4, 0, 3]`, exactly at the caps' +X seams. Its inner controls lie on the planes at one-third and two-thirds of the cap separation: here, z = 1 and 2 mm. A `quadratic-bezier` guide takes exactly three finite control points, with its middle control on the exact cap midplane. A `cubic-bezier` guide takes exactly four, with its inner controls on the exact one-third and two-thirds planes. Both require exact seam endpoints. This is one bounded seam guide for two sections on parallel frames with identical axes. The Kernel checks the supported conic or homothetic mixed line/arc profiles and the existing coordinate limits. A refused loft leaves the previous part and inputs unchanged. To use the existing height-based path without a guide, omit the API `guide` option and supply `z` sections. Do not pass `null` or the string `'None'` as an API guide. In Studio, Shift-click two finished section sketches in the intended order, open **Loft**, then choose an available curve from **Guide (copied)**. Use that list: picking the curve separately in the viewport clears the sketch selection. A guided loft keeps the picked section order and their frames. **None**, the default, uses the existing section heights and height sorting. An imported guide must be one world-mm quadratic or cubic Bézier span, with exactly three or four controls, clamped end knots, no internal knots, and finite positive equal weights. Trimmed objects, unbaked transforms, and nonconstant rational weights are refused. Frames and guide controls are copied snapshots. A separately imported source curve does not become a live reference. Later changes to that curve or the caller's arrays do not update the stored loft. This construction does not certify manufacturing suitability. A polynomial `guide: { kind: 'nurbs', degree, knots, controlPoints }` uses the separate 2–8 ruled-height-section path. It supports degree 1–5 and up to 64 controls under the original monotone-height and section-vertex rules. A common non-XY sketch plane is supported. Raw explicit frames also admit two to eight ruled line/arc sections with identical certified rigid axes, positive ordered separation and exact world/local reconstruction of origins and guide controls. Circle and mixed arc profiles retain their original correspondence rules; inline ellipse objects, different axes and failed reconstruction witnesses are refused. The adapter builds and places the loft once, preserving the mass method and existing native SI `transformed` refusal. Studio can reopen the recipe and edit the source profile through existing Width/Depth fields. The source is copied without a new schema. See the [tested polynomial example and actual Studio preview](/how/loft-sweep#one-polynomial-guide-on-height-sections). ### Two guides between rectangular sections Pass `guides` with two quadratic Bézier curves and two axis-aligned rectangular sections on a common XY sketch plane. Use `z` for the section heights. The sections can have different sizes. Their depth-to-width ratio changes linearly with height. Express the guide controls in world mm. Use the minimum-Y corners from minimum X to maximum X. Both guides go from the lower section to the upper section. Put both middle controls at the halfway height. Keep the second middle control to the right of the first. ```ts import { part, sketch } from '@barocss/cad-model/api'; const rectangle = sketch().rectangle({ w: 10, d: 6, x: 0, y: 0 }); const model = part('Two-guide loft').loft([ { sketch: rectangle, z: 0 }, { sketch: rectangle, z: 12 }, ], { guides: [ { kind: 'quadratic-bezier', controlPoints: [[0, 0, 0], [2, 0, 6], [0, 0, 12]] }, { kind: 'quadratic-bezier', controlPoints: [[10, 0, 0], [14, 0, 6], [10, 0, 12]] }, ], }); const doc = model.doc; ``` Studio History can edit the middle X and Y of each copied guide. Use either `guide` or `guides` in one Loft. Use ruled sections with `guides`. ## Direct sweep and loft surfaces `directOps` from `@barocss/cad-model/engine/direct` works on direct curves. Its sweep and loft add a surface and return a new `DirectGeometry`; use the returned value. These operations differ from the [solid features made from sketches](/studio/features#from-a-sketch). - `directOps.sweep(direct, profileId, railId)` uses the first curve as the profile and the second as the rail. In authored XYZ coordinates, in mm, its surface follows `P(u) + R(v) - R(vMin)`. The profile translates without turning to follow the rail. This is not the feature Sweep that keeps a sketch square to its path. - `directOps.loft(direct, curveIds)` passes through 2–15 curves in the supplied order. It aligns degrees and interior knots, but the parameter-domain endpoints must already match within `1e-12`. This tolerance is in parameter values, not mm. A mismatch gives `DIRECT_RANGE`; trim or rebuild the curves to one parameter range. A curve count outside 2–15 gives `DIRECT_LOFT`. ```ts import { directOps, type DirectGeometry } from '@barocss/cad-model/engine/direct'; export function sweptSurface(direct: DirectGeometry, profileId: string, railId: string): DirectGeometry { return directOps.sweep(direct, profileId, railId); } export function loftedSurface(direct: DirectGeometry, orderedCurveIds: string[]): DirectGeometry { return directOps.loft(direct, orderedCurveIds); } ``` Supply IDs from the current direct geometry. Neither helper above commits a Studio document. ![A straight profile keeps its X direction as a curved rail translates it through three world-coordinate positions](/diagrams/direct-sweep-surface.svg) [Open the direct sweep diagram at full size](/diagrams/direct-sweep-surface.svg). The diagram is a calculated coordinate example, not an API render. For `P(u) = [10u, 0, 0]` and `R(v) = [0, 20v, 20v²]`, with `u` and `v` from 0 to 1, the rail starts at `[0, 0, 0]` mm. At `v = 0.5`, the profile runs from `[0, 10, 5]` to `[10, 10, 5]` mm; at `v = 1`, it runs from `[0, 20, 20]` to `[10, 20, 20]` mm. Its direction stays along X. This calculation does not establish that arbitrary input curves will pass the construction checks. ## Route bundles in code Import the route-bundle helpers from `@barocss/cad-model/engine/routeBundle`. A bundle ties one interior control pole on each of two curves to one translation in world millimetres. It does not join the curves or move each whole curve. The input must contain exactly two distinct direct curves. Each curve must be an open, clamped cubic with positive weights. Each member selects an existing interior pole by its numeric string `handleKey` and names an existing active `sweep-curve` feature and its earlier circular sketch profile. The profile must have a finite positive radius; associated or placed profiles, extra regions, and holes are outside this contract. Each copied sweep path must already match its direct curve. Members must use distinct curves, source geometries, profiles, and sweeps. A document can contain one bundle; nested bundle metadata is not supported. | Helper | Result and meaning | | --- | --- | | `createRouteBundle(doc, input)` | Returns a copied `StudioDoc` candidate with schema `4`, one tie, two members, and markers on the two sweeps. It uses existing inputs; it does not create the curves, profiles, or sweeps. | | `moveRouteBundle(frozenStart, bundleId, totalDeltaMM, expectedDocumentIdentity)` | Returns a candidate measured from the unchanged drag-start document. Both selected poles and the tie anchor receive the same total delta. Endpoints and all other poles remain fixed. The copied sweep paths are updated to match. | | `detachRouteBundle(doc, bundleId, expectedDocumentIdentity)` | Removes the bundle and its sweep markers, and returns a schema `3` candidate. It keeps the current curve coordinates and copied sweep paths. | | `assertRouteBundleDocument(input)` | Returns `void` if the route-bundle admission checks accept the input. It does not evaluate the whole model. | | `routeBundleDocumentIdentity(doc)` | Returns the full canonical document identity used by these helpers. Use this exact string, not `revisionOf(doc)` or a revision label. | `createRouteBundle` receives `expectedDocumentIdentity` in its input object. Move and detach receive it as their last argument. A stale identity or an invalid bundle input is refused with `BAD_REFERENCE`. The stored source binding and copied path must still match the current direct curve. The following helpers take IDs and selections from the caller's existing document. They return candidates only. Evaluate the whole candidate and commit it only after that evaluation succeeds. For a drag, also check that the accepted document still has `baseIdentity` before commit; discard the candidate if the document has changed. ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { assertRouteBundleDocument, createRouteBundle, detachRouteBundle, moveRouteBundle, routeBundleDocumentIdentity, type CreateRouteBundleInput, } from '@barocss/cad-model/engine/routeBundle'; type DeltaMM = [number, number, number]; type NewBundle = Omit; export function createRouteCandidate( accepted: StudioDoc, input: NewBundle, ): StudioDoc { assertRouteBundleDocument(accepted); return createRouteBundle(accepted, { ...input, expectedDocumentIdentity: routeBundleDocumentIdentity(accepted), }); } // Call once at drag start, after the bundle candidate has been accepted. export function beginRouteDrag(accepted: StudioDoc, bundleId: string) { const frozenStart = structuredClone(accepted); const baseIdentity = routeBundleDocumentIdentity(frozenStart); return { baseIdentity, candidateFromTotal(totalDeltaMM: DeltaMM): StudioDoc { return moveRouteBundle( frozenStart, bundleId, totalDeltaMM, baseIdentity, ); }, }; } export function detachRouteCandidate( accepted: StudioDoc, bundleId: string, ): StudioDoc { return detachRouteBundle( accepted, bundleId, routeBundleDocumentIdentity(accepted), ); } ``` For every drag update, call the same `candidateFromTotal` function with displacement from the drag start. Do not add frame deltas or use the previous candidate as a new start. The tie stores each selected pole's offset from its anchor; it does not force both poles onto the anchor. These helpers do not certify clearance, bend radius, sweep validity, or manufacturing suitability. See [the control-point diagram and Studio steps](/studio/features#route-bundles) and [the saved fields](/reference/document#route-bundle-fields). ### When a route edit is refused Route helper admission failures use `BAD_REFERENCE` with a `Route bundle:` message. They reject an invalid binding or candidate; they are not results from evaluating the complete model. | What failed | What to change | |---|---| | The accepted document identity changed, or a captured curve/source binding is stale. | Discard the old candidate. Start from the current accepted document and select the current curve and copied sweep again. Do not replace only the stored revision or canonical string to bypass the check. | | A copied sweep path does not match its current direct curve, or its sweep/profile ID is missing or ambiguous. | Restore a consistent document, make a matching copied sweep from the current curve, and select its current independent circular profile. An old copied path is not a fallback. | | The selected point is an endpoint, or the source is not an open clamped cubic with finite coordinates, valid knots and positive matching weights. | Choose an existing interior control point on a supported millimetre curve. Correct the source geometry before creating the binding. | | Members repeat an ID, curve, sweep, profile, or the same source/geometry pair through different object names. | Choose two distinct curve sources, each with its own sweep and profile. Renaming an alias does not make it a second source. | | Bundle data has the wrong schema, is nested in a placed/pending part, or has missing or orphan member markers. | Keep bundle data in one valid schema-4 base document with two matching members and markers. Detach a valid bundle before placing its document as a part; changing the schema number alone does not repair the bindings. | | Binding admission succeeds, but complete candidate evaluation fails. | Keep the accepted document and inspect the evaluation error. Correct the model or reduce the proposed edit, then evaluate the whole candidate again before committing. This failure is not necessarily a route admission `BAD_REFERENCE`. | The helpers return private candidates. The caller owns complete evaluation and commit; the Studio keeps the accepted document when a route preview or final check fails. These checks do not establish collision clearance, general constraint solvability or manufacturing suitability. ## Assembly and robot motions Use the `api/` facade's `assembly(...).robot()` to read an assembly as a robot. `robot.path(...)` takes at least two waypoints; `robot.motion(name)` reads a saved path. Joint inputs use degrees for turns and mm for slides. Velocity and acceleration limits use deg/s and deg/s², or mm/s and mm/s². ### Checking assembly clearance Call `clearance()` on an existing assembly to read its current clearance map. The method is asynchronous: ```js const result = await myAssembly.clearance({ near: 2 }); // mm console.log(result.map); console.log(result.files.find(file => file.path === 'clearance.json')); ``` Omit `near` to use 1 mm. A supplied value must be finite, greater than 0 and at most 10,000 mm; otherwise the call rejects with `OUTPUT_INPUT`. Evaluation failures also reject the call. It includes the base and visible placed parts; hidden placed parts are excluded. | Result | Meaning | |---|---| | `revision` | The document revision used for this output. | | `shopRows` | The resolved shop-row provenance for the assembly. | | `map` | The clearance map: its own `revision`, `near`, `pairs`, `pending` count and `timing`. The map revision identifies the pair poses; it is separate from the document revision. | | `files` | One `clearance.json` file with map fields, document revision and shop-row provenance. Its entry includes UTF-8 `text`, byte count and SHA-256 digest. The file's `revision` is the document revision: it replaces the map revision. Keep `result.map.revision` separately if you need the map revision. | The map measures the least gap on display meshes. It first selects candidates using bounding boxes expanded by the near distance. A candidate can have state `clear` when its measured gap is greater than `near`, so do not assume that every returned pair is within the band. Each pair identifies its bodies as `a` and `b` and includes `minGap` in mm, closest points in the respective body-local frames, face names and a pose key. `near` means the measured gap is positive and within the requested distance. `contact` means the mesh gap is zero, but it does not yet distinguish touching from a volume overlap. When exact solids are available, `overlap.pending` is `true` until a separate exact overlap check fills it; awaiting `clearance()` does not run that fill. If an exact solid is unavailable, `overlap.refused` explains why the distinction was not made. A `designed` pair identifies a declared seat or fit; it is not an approval of the assembly. Inspect both the pair states and pending or refused overlap fields. An empty pending count alone does not establish that an assembly has no interference. ### Reading pose and path results `poseAt(t)` returns joint inputs, not link placements. Pass that record to `robot.pose(...)` to obtain the pose. A pose reply has no overall `ok` flag; inspect the fields needed by your caller: | Result | Read it as | |---|---| | `robot.pose(values).values` | The resolved joint values, including followers, in degrees or mm. | | `links`, optional `frames` | Named link/frame positions in mm and rotations in degrees, in the assembly coordinates. | | `out_of_limits` | Joint keys outside their stored limits. A direct pose preview keeps those values rather than clamping them; a returned pose alone is not a readiness check. | | `path.check()` | An array with one sweep reply for each adjacent waypoint pair, in waypoint order, for supported open-chain paths. Read each reply's `clear`, optional `contact`, and `minClearance`. A reply whose sample budget ran out carries `exhausted` (with `clear: false` and no `contact`): that segment is not certified, neither clear nor in contact. | Given a robot and waypoints from the caller's current joint keys: ```ts import type { Robot } from '@barocss/cad-model/api/robot'; function sampleMotion( robot: Robot, waypoints: Record[], limits: Record, seconds: number, ) { const path = robot.path(waypoints, { limits }); const values = path.poseAt(seconds); return robot.pose(values); } ``` Supply positive velocity and acceleration limits for each moving joint, or a `default` entry. Use deg/s and deg/s² for turns, or mm/s and mm/s² for slides. Path timing does not read those rates from the document's joint settings. `poseAt` can refuse invalid paths; inspect `path.problems()` before playback. The two coordinates returned by these APIs have different meanings: `poseAt` takes time in seconds, while a sweep's `contact.s` and `minClearance.fraction` locate a dimensionless fraction of that waypoint segment. `contact.values` uses degrees/mm; `minClearance.value` is in mm. They do not give elapsed contact time. `minClearance` can be `null`, and `contact` is absent when no contact is returned. Do not treat missing data as zero. ![Robot path inputs become a pose reply; separate per-segment checks use a fraction rather than time](/diagrams/robot-motion-result-flow.svg) [Open the motion result diagram at full size](/diagrams/robot-motion-result-flow.svg). For supported looped paths, supply driving-joint values only. `duration()` returns seconds. `poseAt(t)` returns the driving values at time `t` in seconds; pass them to `robot.pose(...)` to obtain solved passive-joint values and link placements. `problems()` returns `[]` for a supported, closable path or reports a typed refusal. Extra passive-joint waypoint inputs give `LOOP_PASSIVE`; finite passive loop-joint bounds remain unsupported. Timing and loop closure do not certify collision clearance. `RobotPath.check()` still refuses looped paths with `LOOP_OPEN`: its sweep and continuous collision checks do not follow the closed motion. See [Robots in code](/studio/robots#in-code) for the motion contract and [Moving it](/studio/robots#moving-it) for the agent's supported loop checks and playback limits. `robot.inertia()` returns `{ links }`. Each link's `mass` and counted `bodies[].mass` use g; `centroid` uses mm. `inertia` is a nested 3×3 matrix about the centre of mass, expressed in the link frame, in g·mm². The centroid uses that same link frame. `principal.moments` uses g·mm²; `frame.origin` uses mm in the part's coordinates. Check each link's `bodies` and `issues` before using its totals. A body is excluded with `NO_VOLUME` when `volume` is `null`, or centroid or inertia data is absent. If no bodies are counted or their total mass is not positive, `NO_BODY` accompanies an empty `bodies` list and zero mass and inertia. Other issues identify assumed materials or failed inertia checks; a returned total alone does not establish a usable model. `robot.gravity(values, g)` returns joint-keyed `torques` and `generalized`; read `units[key]` for N·mm on turns or N on slides. Its returned `gravity` is a magnitude in mm/s², not the input vector. See [Robot unit boundaries](/studio/robots#robot-unit-boundaries) for the full public unit contract. ### Static gravity experiment `robot.gravityExperiment({ values, gravity })` captures one prescribed static pose and its gravity holding-torque report. Supply exactly one joint angle in degrees and an explicit finite three-component gravity vector in mm/s²; there is no gravity default. The profile admits exactly one connected open revolute or continuous joint, with no loops or couplings. Nested part occurrences in the moving part are outside this profile. Every moving body needs an explicit known material and positive finite mass. The moving link must have resolved inertia with finite components and no reported issues. The report's torque uses N·mm. It uses the existing Model link-inertia and gravity calculation. In this report, `inputs.gravity` is the supplied document world XYZ vector in mm/s², while `result.gravity` is its scalar magnitude in mm/s². The returned object's `report` getter gives a deep copy. Use `matches(doc, options)` to compare the complete captured document and explicit inputs with the current ones. If their canonical contents differ, `matches` returns false and the report is stale. This check does not rerun the calculation or certify integrity. The profile reports static holding torque, not free motion, contact, actuator suitability or physical validation. It does not change the Studio document schema. Studio's STATIC GRAVITY panel requires explicit joint, angle and world XYZ gravity inputs. Calculation leaves the viewport pose unchanged. Results stay local to the panel. Changed document or input contents mark them stale; a refused calculation can keep the previous result visible. This control calculates holding torque at a prescribed static pose; it does not simulate free motion. Call `record()` to keep an independent JSON record of the past calculation. Its envelope has format `barocss-gravity-experiment-record` and schema `1`. `toJSON()` returns an object; serialize it with `JSON.stringify()` and restore the text with `GravityExperimentRecord.parse()`. Studio document Save and Open are separate from this record JSON. With the supported `robot` and explicit `options` described above: ```js import { GravityExperimentRecord } from '@barocss/cad-model/api/experimentRecord'; const record = robot.gravityExperiment(options).record(); const data = record.toJSON(); const text = JSON.stringify(data); const restored = GravityExperimentRecord.parse(text); const preview = restored.preview; // Typed display fields, including torque in N·mm. const pastReport = restored.report; // unknown; the full past report. const inputsMatch = restored.matches(robot.doc, options); ``` `preview` and `report` return copies. Parsing rejects unsupported format, schema, calculation profile or units, non-finite JSON numbers, and invalid required structure or inconsistent bindings. It does not validate the complete inertia schema. A record describes a past calculation: parsing does not recalculate it, prove authenticity, or check compatibility with the current producer code or material catalogue. Consistent finite changes to numerical results can pass these checks. `matches(doc, options)` compares the full canonical document and explicit inputs; if either canonical content differs, it returns false and the record is stale. A matching record does not establish a new result. When present, a counted body's optional `materialSnapshot` retains `bodyMaterialId`, `inputMaterialId`, `resolvedMaterialId` and `fallback` (`none`, `unset` or `unknown-id`) from the calculation. `densityGPerCm3` is the density used, in g/cm³; it can differ from the declared `catalogueDensityGPerCm3` (number or null). The catalogue 0.7.0 version, source ID/text/page and estimate fields describe the declared row; they do not certify the used density, authenticity or measured properties. `inertiaSource` distinguishes `mmgs-density-scaled` from an actually applied `callback-override`. The mass density does not establish the source of the callback's inertia tensor. Older schema 1 records can omit these fields: no current catalogue values are filled in. The full `report` remains `unknown`. Each read of the separate `record.materialPreview` getter returns a detached typed copy of recorded material fields with link and body IDs. It returns `null` when `inertia.links` is absent. Missing per-body `materialSnapshot` or `inertiaSource` becomes `null`; empty bodies stay empty. For otherwise accepted records, material-field shape errors raise `VALUE` on getter access; `parse` keeps its existing finite-JSON checks. The existing `preview`, unknown `report`, `matches` and schema `1` remain unchanged. The getter does not fill missing fields from the current catalogue or certify authenticity, measured properties or current compatibility. Reading or displaying these historical fields does not recalculate the result or turn it into a new measurement. In Studio's STATIC GRAVITY panel, use the Download button to export the displayed record as independent JSON. Use `Open gravity record` to load it as a historical record, not a recalculated result, even when document and inputs match. Opening a valid record fills the joint, angle and world XYZ gravity fields. Choose `Calculate holding torque` to calculate again. An invalid file reports an error and preserves the previous record and input fields. These controls do not save or open a Studio document. Expand **Recorded material inputs** to read the recorded metadata. Missing metadata is marked **Not recorded**; invalid material metadata makes only this section unavailable. This does not change the existing Historical/Match/Stale status or the record operations. Use **Pin this record** to keep the displayed record for comparison, **Replace pinned record** to replace it explicitly, and **Unpin record** to clear it. Expand **Compare records** to inspect the pinned and current entries. Each entry checks the current document at that record's own saved inputs; the panel's Match/Stale status instead compares the current form inputs too. A finite recorded torque difference (current − pinned), in N·mm, appears only when joint, occurrence, coordinate frame, axis origin and axis direction match exactly. Historical records remain **not recalculated** even when document and inputs match. A difference does not establish cause, accuracy, measured validation or producer compatibility. The pin is local to the mounted panel and is cleared when that panel is removed. It is separate from document Save and record Download/Open. ### Experiment setup | Artifact | Save | Open | |---|---|---| | Studio document | Document Save keeps the model document. | Document Open restores it separately from experiment setups and records. | | Experiment setup | **Save setup** downloads the current form inputs and their document binding as JSON. | **Open setup** previews settings without changing the form, results or pinned record. | | Past result record | The existing record Download keeps a past calculation. | **Open gravity record** restores that historical record; it does not calculate again. | Under **Experiment setup**, the steps remain separate: - **Use inputs** copies the loaded setup inputs into the form without calculating. - **Run saved setup** uses the loaded inputs even when the form differs. After a document match and a successful calculation, it replaces the current result and updates the form to those inputs. A failed run keeps the previous form and result. - **Bind setup to current design** makes new loaded settings bound to the current document, keeping their inputs. It does not change the form, download a file or calculate. - **Save setup** always uses the form. To download rebound settings with the loaded inputs, first choose **Use inputs**, then **Save setup**. An invalid setup file keeps the previous loaded setup, form and result. Loaded settings are local to the panel and are lost when it is removed. Past record objects and the pinned record remain unchanged. In code, `create` and `parse` do not calculate. `toJSON()` and `options` return independent copies. For caller-supplied Studio documents and the explicit options described above: ```js import { GravityExperimentDefinition } from '@barocss/cad-model/api/experimentDefinition'; const definition = GravityExperimentDefinition.create(doc, options); const text = JSON.stringify(definition.toJSON()); const opened = GravityExperimentDefinition.parse(text); const copiedInputs = opened.options; if (opened.matches(currentDoc)) { const freshResult = opened.run(currentDoc); // Explicit calculation; it can still refuse. const newRecord = freshResult.record(); } const rebound = opened.rebind(changedDoc); // New settings, no calculation; opened is unchanged. ``` `matches(doc)` compares the full canonical document using the saved inputs; it does not establish execution readiness. `run(doc)` uses the caller's current document and refuses a mismatch with `VALUE` before calculation. It does not execute the stored document text. `rebind(doc)` keeps the inputs in a new definition. Only explicit `run` attempts a new result under the existing static-gravity limits; past records are unchanged. Setup input `units` has exactly two keys: `angle: 'degree'` and `gravity: 'mm/s²'`. The result report has six: `angle: 'degree'`, `length: 'mm'`, `mass: 'g'`, `inertia: 'g·mm²'`, `gravity: 'mm/s²'` and `torque: 'N·mm'`. Keep result units and calculated fields out of a setup. The existing result-record schema `1` and parser are unchanged. ### Input contracts Constructors, getters and operations follow the input rules below. These rules do not extend the supported motion contract above. - Direct `RobotPath` construction copies nested waypoints and limits; its getters return copies. - `Robot`, `RobotPath` and `Assembly` constructors also copy their input document. Changing that input later does not change the stored snapshot. `Robot.doc` and `Assembly.doc` return copies, as do the path's motion getters. Copying cost has not been measured. Inputs that cannot be cloned may fail at construction rather than later use. - Open-chain `duration()` checks the path on its robot's tree before timing it, as `poseAt()` does. Typed refusals use the first finding's code and message, with the findings in `details.problems`. - `robot.withMotion(name, path)` checks the destination robot's tree, including paths from another robot. It permits zero- or one-waypoint and untimed recording drafts; saving does not make them ready to play. For loops, it checks closure at each saved waypoint separately. This does not certify the intervening path, continuation through earlier seams, finite passive-joint bounds or sweep/CCD. - Motion waypoints must be records of finite numeric joint values. Malformed paths and path options give `VALUE`; malformed limits or explicitly supplied non-finite `velocity`, `acceleration` or `jerk` give `LIMITS_BAD`. Missing recording limits remain absent; this does not remove the draft allowance above or certify a whole path. - A studio part's `meshes()` returns copies of positions, normals, indices and lines. Editing those typed arrays does not change the core's cached mesh data. Passing them to a GPU Scene still shares those returned arrays with that Scene, as described in the [Scene input contract](/packages/gpu/#scene-geometry-input-candidate). - A process `pull` must have exactly three finite coordinates and match one of the existing six unit directions: positive or negative X, Y or Z. Other vectors give `VALUE`; this does not add arbitrary pull directions. - Material lookup for an unknown body gives `NO_BODY`. Locking an unknown child or target gives `NO_PART`; an unknown target is not treated as the base part. - Library-part options must be a non-null object, not an array, with a non-empty `face` string. `point` and an optional `xDirection` each require exactly three finite numbers. Malformed inputs give `VALUE`. ## The studio document The document is a `barocss-cad-model` file in millimetres. Ordinary documents use schema 3; an explicit route bundle uses schema 4: - **The model.** Its `nodes` are the features in order, with its parameters and outputs. - **Everything else on the part:** - placed parts and mates; - the drawing; - shop rows with their sources; - the process settings; - the brief and requirements; - proposals and history. [The .bcad document](/reference/document) lists the fields. The model converts to the kernel's part document to evaluate. In code, the [object facade](/packages/api) writes the document as the studio's own commands do, and the core evaluates it: ```js // A 40 × 20 × 5 plate, then a Ø6 hole through it. const plate = part('plate') .box({ w: 40, d: 20, h: 5 }) .hole(body => body.faces().facing('+z'), { d: 6, x: 10, y: 10 }); const doc = plate.doc; // the studio document, as the studio's own commands write it const result = evaluateDoc(doc, 1); // the core: the bodies, their display meshes and masses assert.ok(result.ok); const [body] = result.bodies; assert.ok(Math.abs(body.volume - (40 * 20 * 5 - Math.PI * 9 * 5)) < 1e-6); assert.equal(plate.mass('al6061').volume, body.volume); const step = exportStudioStep(doc, { name: 'plate' }); // the exact solids, naming the revision they came from assert.equal(step.source, revisionOf(doc)); ``` ## Evaluation and its caches `evaluateDoc(doc, revision)` evaluates a document into bodies. Each body has: - its key (`b`, from the feature that made it); - its display mesh, with its faces and edges; - its volume, mass and centroid; - its surface area; - its notes. The last evaluation is kept, and the next one reuses every kernel feature whose definition is unchanged, so editing one value re-runs only what depends on it. In the studio this runs in a worker, and a newer request makes an older reply stale (see [Revisions and sources](/guide/concepts#revisions-and-sources)). ```js const bytes = encodeStudioFile(doc); // plain JSON, or the BCADPACK container when it holds mesh data const back = await readStudioFile(bytes); assert.ok('doc' in back); assert.equal(revisionOf(back.doc), revisionOf(doc)); ``` ## Data rules - **Sources.** Every catalogue or standard value names its source: a public page with its address and the date read, a value derived by a stated rule, or an estimate marked as one. - **Your lists.** Lists a shop owns, such as stock, fastener sizes or casting rules, are yours to load. None is built in (see [Shop rows](/studio/rows)). - **No copied standards.** No standard's text or tables are copied. ## The agent's tools `chat/` is the tool layer the chat, `cad-mcp` and `cad-cli` serve: - `chat/toolset`: the 13 tools and the system prompt; - `chat/groups`: each action and its handler; - `chat/tools`: the dispatcher, with its autonomy and approval gates. See [Tools](/agent/tools). --- # CAD React `@barocss/cad-react` is a private workspace package. It describes CAD geometry with ordinary React components, lowers the committed geometry to the existing [CAD Model](/packages/cad-model/) document, and can connect an injected engine to the existing [Viewer](/packages/viewer/). The current package is TypeScript source in this repository. It is not a published npm package, a portable engine client, a distribution build or a standalone Worker. The host application supplies the engine, Worker setup and mass integration. Add it to a workspace consumer with `workspace:*`. ## What you can compose | Operation | Components | Result | |---|---|---| | Closed planar profile | `Rectangle`, `Circle`, `Polygon`, `Loop`, `Profile` | Profile input for Extrude or Revolve | | Solid extrusion | `Extrude` | Existing native extrusion of one profile | | Solid revolution | `Revolve` | Existing sketch-axis revolution of one closed profile | | Solid union | `Union` | Join at least two realized solids | | Ordered subtraction | `Difference`, `Target`, `Tools` | Subtract tools from one target | | Rigid placement | `Translate`, `Rotate` | Existing Model body-transform nodes | | Reuse | `Definitions`, typed object refs | Share a declared profile or solid within one Part | | Model lifecycle | `Part`, `ModelHost` | Commit declarations and coordinate an injected engine | | Display | `ExistingViewerHost` | Send engine display meshes to the existing Viewer | Read the [component catalog](/packages/cad-react/components), [references and compiler](/packages/cad-react/references), [engine and Viewer integration](/packages/cad-react/engine-viewer), [examples](/packages/cad-react/examples) and [support boundaries](/packages/cad-react/limits). ## A Part is a model root ```tsx import { Part, Extrude, Rectangle, type ModelLifecycle, } from '@barocss/cad-react'; export function Plate({ lifecycle }: { lifecycle: ModelLifecycle }) { return ; } ``` This declaration produces a model. It does not create an engine or a visible canvas by itself. Pass an appropriate lifecycle, such as a connected `ModelHost`, and provide the [display integration](/packages/cad-react/engine-viewer). React runs normal function components and hooks. Committed hidden DOM markers record membership and sibling order. The compiler does not call your component functions manually and does not infer their output from `React.Children` alone. Native feature IDs are automatic; no manual Sketch IDs or native body references are required. For the complete existing ModelNode inventory and the missing adapter backlog, read the [CAD Model support map](/packages/cad-react/support-map). Existing backend operations are broader than this first React subset; this page does not claim full CAD React coverage. ## Public entry points | Entry point | Runtime exports | |---|---| | `@barocss/cad-react` | `Part`, `Rectangle`, `Circle`, `Polygon`, `Loop`, `LineSegment`, `ArcSegment`, `Profile`, `Outer`, `Voids`, `Extrude`, `Revolve`, `Union`, `Difference`, `Target`, `Tools`, `Definitions`, `Translate`, `Rotate`, `CompositionCompiler`, `IrError` | | `@barocss/cad-react/engine` | `ModelHost` | | `@barocss/cad-react/viewer` | `ExistingViewerHost` | All public type exports are listed with their contracts on the component, references and engine pages. The package also exposes `@barocss/cad-react/sdk` (``, ``) used by BaroCSS Review and embedded CAD experiences. Examples use standard React hooks (`useRef`, `useState`, `useEffect`). --- # Components and props Import these components from `@barocss/cad-react`. Coordinates and lengths are in millimetres. Profiles are local XY geometry; extrusion and transforms lower to the existing Model operations. A React wrapper may return a compatible realized output: validation concerns the committed geometry, not the raw JSX child count. ## Detailed component pages Each supported React element has its own props, complete example, logical/native role, validation and measured-scope page. | Root and profiles | Solid operations | Operand slots and reuse | Placement | |---|---|---|---| | [Part](/packages/cad-react/components/part) | [Extrude](/packages/cad-react/components/extrude) | [Target](/packages/cad-react/components/target) | [Translate](/packages/cad-react/components/translate) | | [Rectangle](/packages/cad-react/components/rectangle) | [Union](/packages/cad-react/components/union) | [Tools](/packages/cad-react/components/tools) | [Rotate](/packages/cad-react/components/rotate) | | [Circle](/packages/cad-react/components/circle) | [Difference](/packages/cad-react/components/difference) | [Definitions](/packages/cad-react/components/definitions) | | | [Polygon](/packages/cad-react/components/polygon) | [Revolve](/packages/cad-react/components/revolve) | | | ## Part | Prop | Contract | |---|---| | `lifecycle` | Required `ModelLifecycle` object | | `admission` | Required literal `"synchronous"`; caller promises the supported synchronous composition boundary | | `units` | Optional `"mm"`, default `"mm"` | | `children` | Required React children producing exactly one solid output outside Definitions | `ModelLifecycle` has `dirty():void`, `invalid(error:unknown):void`, `complete(model:Compiled):void` and `detached():void`. A connected `ModelHost` implements this interface. Each Part is a separate model root; nested Parts are not geometry operands. `Part` is not a canvas and does not create a Worker. ## Profiles | Component | Props | Output | |---|---|---| | `Rectangle` | `min:[x,y]`, `max:[x,y]`, optional `ref:ProfileRef` | Closed profile with strictly positive X/Y extents | | `Circle` | `center:[x,y]`, positive finite `radius`, optional `ref:ProfileRef` | Closed circular profile | | `Polygon` | `points:readonly [x,y][]` with 3..1024 dense finite pairs, optional `ref:ProfileRef` | Closed ordered profile | Supply dense finite coordinate tuples. These components are profile producers, not standalone solid bodies. They do not expose a native face, a selected region, an arbitrary wire or a sketch-constraint editor. ## Polygon [Polygon](/packages/cad-react/components/polygon) accepts a readonly array of 3..1024 ordered dense finite coordinate pairs and optional `ProfileRef`. It produces one closed profile through existing polygon sketch storage. `PolygonProps` is exported. Native validity and refusal remain authoritative; no points are repaired, removed or resampled. ## Extrude | Prop | Contract | |---|---| | `distance` | Required finite nonzero length; positive and negative values lower to the existing native height | | `from` | Optional finite start coordinate along the local extrusion direction; omitted by default | | `children` | Exactly one realized profile, exclusive with `profile` | | `profile` | `ProfileRef`, exclusive with `children` | | `ref` | Optional `SolidRef` for the resulting solid | `ExtrudeProps` is the public prop type. The input is profile geometry. An internal Sketch node is a document-storage detail, not a public `sketch={...}` prop. Native face/region extrusion available elsewhere in Studio is not automatically a source capability here. ## Revolve Revolve accepts one closed profile child or typed `profile` reference, required sketch `axis="x"|"y"`, required finite angle in `(0,360]` degrees and optional finite two-coordinate origin. It returns a solid reference. The adapter lowers the existing Model node; it adds no native math. Declaration/types/lint checks and the selected rectangle90/180/360/Reset 90 actual flow pass; broader profile/axis/origin combinations remain unqualified. Read the [Revolve contract](/packages/cad-react/components/revolve). ## Union and Difference | Component | Props | Contract | |---|---|---| | `Union` | `children`, optional `ref:SolidRef` | At least two realized solid operands; combines them in declared order | | `Difference` | `children`, optional `ref:SolidRef` | Exactly one `Target` and one `Tools` group | | `Target` | One solid child **or** `solid:SolidRef` | The solid to cut; `TargetProps` is exported | | `Tools` | `children` | One or more realized solid tools, subtracted in declared order | ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function HoledPlate() { return ; } ``` This is existing CAD Boolean evaluation, with the backend's native geometry/refusal limits. The JSX layer does not implement a new Boolean kernel or certify every operand arrangement. ## Translate and Rotate | Component | Required props | Optional props | |---|---|---| | `Translate` | `offset:[x,y,z]`, one solid input | `ref:SolidRef` | | `Rotate` | `axis:"x"|"y"|"z"`, `angle` in degrees, one solid input | `pivot:[x,y,z]`, `ref:SolidRef` | A solid input is exactly one realized solid child or `solid:SolidRef`. `SolidInput`, `TranslateProps` and `RotateProps` are exported. Offset and explicit pivot require three finite coordinates, including all three indexed array elements. Sparse arrays refuse. Angle must be finite with absolute value at most 3600; zero is allowed. An omitted pivot remains omitted and uses the existing backend origin default. ```tsx import { Translate, Rotate, Extrude, Rectangle } from '@barocss/cad-react'; export function PositionedPlate() { return ; } ``` The inner Rotate lowers before the outer Translate. No matrix or trigonometry is computed by the React layer. Accepted axes/angles are API input rules; they do not expand the finite [runtime evidence](/packages/cad-react/limits). ## Definitions, refs and standard React behavior `Definitions` takes `children` declaring profiles or solids for typed reuse. Its definitions do not add independent Part outputs. See [references](/packages/cad-react/references) for `ProfileHandle`, `SolidHandle`, `ProfileRef` and `SolidRef`. Normal function components, props, hooks, Fragments and keyed arrays can compose these components within synchronous admission. React keys and mounted identities preserve supported feature identity; remounting creates new identity. No component has a public native-ID prop. Internal Suspense/Offscreen/async behavior is outside admission, including when a wrapper hides it. ## Profile composition `Loop`, `LineSegment`, `ArcSegment`, `Profile`, `Outer`, and `Voids` compose multi-segment closed profiles with optional inner cutouts. | Component | Input and role | | --- | --- | | [Loop](/packages/cad-react/components/loop) | Ordered 1..1024 exact segment descriptors; optional profile ref | | [LineSegment](/packages/cad-react/components/line-segment) | Finite start pair inside Loop; no native ID or ref | | [ArcSegment](/packages/cad-react/components/arc-segment) | Finite start/center and explicit ccw/cw direction inside Loop | | [Profile](/packages/cad-react/components/profile) | Exactly one Outer, optional one Voids; optional profile ref | | [Outer](/packages/cad-react/components/outer) | Exactly one single-loop child or profile reference | | [Voids](/packages/cad-react/components/voids) | 1..64 single-loop children or dense profile references | `Profile` and `Loop` produce typed profile data; `Outer`/`Voids` and `LineSegment`/`ArcSegment` are structural descriptors rather than independent native features. Composite `Profile` emits one consumed sketch cleanly, `Circle` converts via exact loops, and `Extrude` admits explicit voids within native bounds. ## Hole [Hole](/packages/cad-react/components/hole) cuts an existing solid with numeric center/radius and optional axis, side and flat-bottom depth. Supply one solid child or `SolidRef`. Omitted depth requests a through hole. Native geometry and refusal remain authoritative. This component does not expose face selection, pointed drilling, threads or patterns. ## Declarative JSX DSL features (`@barocss/cad-react/dsl`) In addition to the synchronous host components above, `@barocss/cad-react/dsl` exposes a pure-functional JSX modeling DSL compiled by `compileCadElement` / `evaluateCadElement`, including parametric `param('name')` references and six advanced solid modeling components: | Component | Purpose | Key Props | | --- | --- | --- | | `Draft` | Taper selected faces about a neutral plane | `angle`, `pull` (`CadDraftPull`), `neutral`, `selector` (`CadFaceSelector`) or `select` callback | | `Mirror` | Mirror a solid across a plane (`'xy' \| 'xz' \| 'yz'`) | `plane` (`CadMirrorPlane`), `at`, optional `keep` | | `Split` | Conserved planar split along an axis or oblique normal | `axis` or `normal: [x, y, z]`, `at` | | `Loft` & `LoftSection` | Blend two or more planar or framed profile sections | `smooth`, child `` or `` | | `Sweep` | Sweep a `Circle` or `Profile` along a stepped path or NURBS rail | `path` (`straight` / `bend` segments) or `curve` (`CadSweepCurvePath`), `mode` | | `Rib` | Add a stiffening rib solid between bounding coordinates on a parent solid | `min: [x, y, z]`, `max: [x, y, z]` | ```tsx import { Part, Box, Draft, Mirror, Split, Loft, LoftSection, Sweep, Rib, Rectangle, Circle, param, evaluateCadElement, } from '@barocss/cad-react/dsl'; const bracket = ( ); const snapshot = evaluateCadElement(bracket); ``` --- # Part The model root and declaration lifecycle. Part is a logical React element, not a native feature node or a visible canvas. Import `Part` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `lifecycle` | Required ModelLifecycle | dirty, invalid, complete and detached callbacks; a connected ModelHost implements them. | | `admission` | Required "synchronous" | Explicit caller contract for supported synchronous composition. | | `units` | Optional "mm"; default "mm" | All source lengths are millimetres. | | `children` | Required ReactNode | Exactly one realized solid output outside any Definitions groups. | ## Example ```tsx import { Part, Extrude, Rectangle, type ModelLifecycle } from '@barocss/cad-react'; export function PlateModel({ lifecycle }: { lifecycle: ModelLifecycle }) { return ; } ``` The example includes its Part context and accepts a real lifecycle from its caller. It creates no Worker or canvas. ## Composition and validation React executes wrappers and hooks. Part records committed descendants and sends lifecycle changes; it neither calls component functions manually nor constructs a Worker. Supply the separate engine/Viewer integration to evaluate and display the model. Two solids outside Definitions refuse; combine them through Union or Difference. A profile alone is not a solid output. Nested Parts, portals and unsupported async boundaries are not model operands. A wrapper-hidden Suspense boundary is still outside synchronous admission. ## References and identity Mounted features use automatic IDs. Invalid declarations retain the compiler's last accepted document while the lifecycle retires freshness; previous visible geometry is not current success. Part does not reconnect source identity after reload. ## Measured boundary Original App/Bracket widths80→100→80 and the selected transformed W80 flow exercise this root with the real injected engine/Viewer. This does not cover arbitrary React scheduling or geometry. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Rectangle A closed axis-aligned profile in the local XY plane. The compiler lowers it to a native sketch-storage record when a consumer needs it; the logical component is a profile producer, not a solid. Import `Rectangle` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `min` | Required readonly [x,y] | Finite local XY millimetres. | | `max` | Required readonly [x,y] | Both coordinates must exceed the corresponding min coordinate. | | `ref` | Optional ProfileRef | Object token for reuse within this Part; no evaluated geometry is returned. | ## Example ```tsx import { Rectangle, Extrude } from '@barocss/cad-react'; export function RectangularPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Place Rectangle under Extrude, or declare it in Definitions and pass its ProfileRef to an extrusion. Coordinates are local geometry, not pixel positions or a native face selection. Zero or reversed extents refuse. Supply dense finite two-coordinate tuples. A Rectangle cannot be a Union/Target/transform solid input and cannot be the sole solid output of Part. Rectangle has no arbitrary-polygon, rounded-corner or sketch-constraint prop. Use the separate Polygon producer for an ordered closed outline; its native geometry limits and evidence scope remain separate. ## References and identity Its optional ref has kind rectangle. Standard mounted identity and React keys support ID retention; there is no public id or sketch-ID prop. ## Measured boundary Floor, wall and window-tool rectangles are exercised by the measured Bracket examples. The positive-extents/API contract is broader than those selected measured sizes. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Circle A closed circular profile in local XY. It lowers to existing sketch storage for extrusion, not to a solid hole feature by itself. Import `Circle` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `center` | Required readonly [x,y] | Finite local XY millimetres. | | `radius` | Required positive finite number | Radius in millimetres, not diameter. | | `ref` | Optional ProfileRef | Object token whose handle kind is circle. | ## Example ```tsx import { Circle, Extrude } from '@barocss/cad-react'; export function CircularTool() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Circle produces a profile. Extrude turns it into a solid; place that solid in Tools to cut a target. Circle alone does not subtract material and does not infer a hole direction or depth. Nonfinite or nonpositive radius refuses. Supply a dense finite center tuple. A circle profile cannot be supplied where a solid ref or solid child is required. Native circular-face queries and selected planar regions are separate unsupported source capabilities. ## References and identity A ProfileRef may be forwarded through ordinary components or Definitions. Pass the object token, not ref.current; the handle contains kind metadata, not synchronous native geometry. ## Measured boundary The four radius3 floor-hole tools in the original and transformed Bracket flows are measured. This is not a certificate for every radius, placement or Boolean arrangement. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Polygon `Polygon` declares one closed planar profile from an ordered list of points. It lowers to the existing Model polygon sketch storage. It adds no Boolean, tolerance, triangulation or geometry-repair algorithm. ## Props | Prop | Contract | |---|---| | `points` | Required readonly array of 3 to 1024 dense finite `[x,y]` coordinate pairs | | `ref` | Optional `ProfileRef`, for reuse within the same Part | Coordinates are in mm on the current local XY plane. Points are copied in declared order. The final edge returns to the first point. Do not repeat the first point to ask the adapter to close or repair a loop. No point is removed, snapped or resampled. Native geometry validation can refuse degenerate, crossing, contacting or otherwise unsupported outlines after declaration validation succeeds. `PolygonProps` is exported. Polygon produces a profile, not a solid, face selection, wire, mesh or sketch-constraint scope. There is no public native-ID prop. Holes, regions, arbitrary planes and constraints remain separate source capabilities. ## Direct child ```tsx import {Polygon,Extrude} from '@barocss/cad-react'; export function PolygonPlate({width}:{width:number}) { return ; } ``` Place this component inside an existing Part and supply the existing engine/Viewer integration. Changing width changes the declared polygon and requests the existing native recalculation. This component adds no visible explanatory UI. ## Forward reference through an ordinary component ```tsx import * as React from 'react'; import {Polygon,Extrude,Definitions,type ProfileRef,type ProfileHandle} from '@barocss/cad-react'; function Outline({ref,width}:{ref?:ProfileRef;width:number}) { return ; } export function SharedPolygon({width}:{width:number}) { const outline=React.useRef(null); return <> ; } ``` The ref is optional. Pass the object token, not `.current`. Normal React props, state, wrappers and stable keys provide reuse and identity. A Polygon profile can also feed the existing Revolve child/ref contract. That type compatibility does not qualify every revolved outline. ## Validation and current evidence Counts outside 3..1024, missing array elements, inherited array elements, missing coordinates, nonfinite values and malformed coordinate pairs refuse. A rejected declaration retains the prior immutable compiled document and retires its freshness. A mounted feature keeps its IDs on supported updates; remounting creates a new identity. The current PolygonApp measures the pentagon shown above at widths 60 and 80 mm and an extrusion height of 8 mm. Public Width changes, blank-input refusal, valid recovery and Reset pass with the existing Worker and Viewer. The exact returned width-60 document opens through public Studio Open and Frame all. These selected convex plates have independent native volume, centroid, boundary and topology evidence. A separate settled-error observation confirms the visible coordinate error and retained previous frame without an extra native request. The package has 57 controlled tests, package/API-example types and lint passing. The native 3 to 1024 point budget is not a certificate for every outline, concave polygon or Polygon-based Revolve. See the support boundaries for the separate declaration and physical results. --- # Loop D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output children:1..1024realized LineSegment/ArcSegment descriptors; optional ref:ProfileRef. One closed localXY profile. Segment end is the next segment start; the last ends at the first start. A one-arc full circle is expressible. Geometry closure/radius/self-contact/native validity remain engine authority. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,LineSegment,Extrude} from '@barocss/cad-react'; export function LoopedPlate(){return ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # LineSegment D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output start:required dense finite readonly[x,y] pair. No ref, end or native ID prop. A descriptor inside Loop. It does not create a native sketch, profile, solid or persistent native edge by itself. The next segment start defines its end. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,LineSegment} from '@barocss/cad-react'; export function Boundary(){return ;} ``` Place this segment inside Loop; consume that Loop through Extrude, or as an Outer/Voids input inside Profile consumed by Extrude. Mount the complete solid recipe under Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # ArcSegment D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output start and center:required dense finite readonly[x,y] pairs; direction:required ccw|cw. No angle, ref or native ID prop. An exact native arc descriptor inside Loop. No tessellation or inferred tangent/radius is computed by React. A single arc returns to its own start as a full circle; native validity remains separate. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,ArcSegment} from '@barocss/cad-react'; export function CircularVoid(){return ;} ``` Place this segment inside Loop; consume that Loop through Extrude, or as an Outer/Voids input inside Profile consumed by Extrude. Mount the complete solid recipe under Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Profile D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output children:exactly one Outer and at most one Voids; optional ref:ProfileRef. Closed profile data with explicit void loops. It emits only its own native sketch when an operation consumes it; descriptor sources are not emitted merely to assemble this profile. No Regions, arbitrary plane, raw Model, face or constraint prop. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Profile,Outer,Voids,Rectangle,Circle,Extrude} from '@barocss/cad-react'; export function BoredPlate({radius}:{radius:number}){return ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Outer D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output exactly one realized single-loop profile child OR profile:ProfileRef; never both. Structural Profile slot. Rectangle/Circle/Polygon/Loop or a Profile without holes can supply it. A nested profile with holes refuses instead of losing its holes. No native node/ID/ref of its own. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import * as React from 'react'; import {Profile,Outer,Rectangle,Definitions,Extrude,type ProfileHandle} from '@barocss/cad-react'; export function ReusedOuter(){const outline=React.useRef(null);return <> ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Voids D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output 1..64realized single-loop profile children OR profiles:readonly ProfileRef[]; never both. Reference list must be dense. Structural Profile slot that uses existing exact Model loopOf conversion. A Circle becomes one full CCW arc; it is not sampled. Omit Voids entirely for no holes; an empty live Voids refuses. No inferred containment, Regions, native IDs or own ref. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import * as React from 'react'; import {Profile,Outer,Voids,Rectangle,Circle,Definitions,Extrude,type ProfileHandle} from '@barocss/cad-react'; export function ReusedVoid(){const bore=React.useRef(null);return <> ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Extrude Turns one supported closed profile into a solid using the existing Model extrusion. Sketch lowering is internal storage; there is no public sketch prop. Import `Extrude` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `distance` | Required finite nonzero number | Signed extrusion height in millimetres; no default. | | `from` | Optional finite number | Local starting coordinate; omission preserves the existing backend default at the local origin. | | `children` | Exactly one realized profile | Exclusive with profile. | | `profile` | ProfileRef | Exclusive with children. | | `ref` | Optional SolidRef | Reuse the resulting solid within this Part. | ## Example ```tsx import { Extrude, Rectangle } from '@barocss/cad-react'; export function Floor() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Extrude accepts Rectangle/Circle/Polygon output and, in the D509 implementation, Loop/Profile output, including a compatible output returned by a synchronous wrapper or resolved ProfileRef. ExtrudeProps names the public exclusive-input type. The result can feed Union, Difference or a rigid transform. Zero/nonfinite distance or nonfinite from refuses. Both child and profile, multiple profiles, a solid token as profile, and arbitrary face/region descriptors refuse. Surface/face extrusion supported elsewhere in Studio is not automatically admitted here. ## References and identity The result is a solid handle of kind extrude. Feature IDs and the profile sketch linkage are automatic; source props do not expose native node indices. ## Measured boundary The Polygon producer uses the same profile child/ref contract. D504 qualifies the selected convex pentagon at widths 60 and 80 mm and an extrusion height of 8 mm, with current native, Worker, Viewer and returned-document Studio evidence. Other outlines remain outside that physical proof. Numeric declaration checks do not replace native outline validity. The measured Bracket uses floor6, wall56 and declared overcut tools, with original widths80/100 and selected W80 transforms. Positive/negative distance input support is not a runtime certificate for all heights/directions. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Revolve Revolve turns one closed profile into a solid through the existing CAD Model revolve node. Provide a profile, a sketch axis and an angle. The result is a solid that other operations can use. The selected rectangle example below has current browser, native geometry and Studio Open evidence. Import `Revolve` from `@barocss/cad-react`. The package is private, version `0.0.0`; it is not a published portable install. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `axis` | Required `x` or `y` | Axis in the existing sketch plane convention. | | `angle` | Required finite number greater than 0 and at most 360 | Degrees. There is no adapter default. | | `origin` | Optional readonly `[x,y]` | Explicit finite sketch coordinates in mm; omission stays omitted. Existing backend supplies `[0,0]`. | | `children` | One realized profile | Exclusive with `profile`. | | `profile` | Typed ProfileRef | Exclusive with children; scoped to the same Part. | | `ref` | Optional SolidRef | Resulting solid handle has kind `revolve`. | ## Example ```tsx import { Rectangle, Revolve } from '@barocss/cad-react'; export function RevolvedSection({ angle = 90 }: { angle?: number }) { return ; } ``` Place this composition as the single output inside a Part with a connected lifecycle. It lowers to an automatically identified sketch and revolve node. The React component and profile references are logical declarations, not public native sketch IDs. ## Composition and validation Rectangle, Circle and Polygon are the prior closed profile adapters. The D509 implementation adds Loop/Profile sources; holed Revolve remains subject to its separate native limits and is not physically qualified by the selected Extrude case. Use one child or one profile reference. Definitions can hold a referenced profile; Boolean operations and Translate/Rotate can consume the resulting solid. Declaration tests for those combinations do not qualify every combination as a native physical case. Angles that are zero, negative, nonfinite or greater than 360° are refused. Invalid axes, sparse/nonfinite explicit origins, missing/wrong-kind references, mixed child/ref and wrong cardinality refuse. Staged native IDs commit only on accepted compilation. Compiler refusal retains its prior accepted source; ModelHost invalidation clears its current desired document. A stale visible shape does not establish current acceptance. Polygon can feed this profile contract, but no Polygon Revolve physical certificate is claimed by D504. There is no public sketch ID, arbitrary vector axis, direction, selected face, open wire or native-face provider prop. Existing backend geometry restrictions still apply. ## Runtime boundary The actual checks use only the rectangle shown above, the y axis and the omitted origin. They measure 90°, 180° and 360°, then use Reset to return to 90°. Source review confirms the existing convention sweeps this positive-X rectangle toward positive Z. Partial states have radial end caps and genus 0; the full 360° state has no radial end caps and genus 1. Current native B-reps satisfy those distinct partial/full topology contracts. Output mass and independent B-rep mass agree with the polar integral: volumes of 2250π, 4500π and 9000π mm³; centroids `[k,35,k]`, `[0,35,k]`, `[0,35,0]`, with `k=280/(9π)` mm. Native relative volume and absolute centroid/boundary/normal budgets remain 1e-9. The browser uses working Angle and Reset controls, public group collapse/reopen and a 1200 ms idle sample. Those panel actions preserve the exact document and current geometry ownership. Reset returns the exact original document and rendered frame. Public Studio Open and Frame all consume that returned 90° document with fresh root Worker values. Three native captures plus two exact 90° subproof reuses bind five fresh consumers; they are not five native captures. The standalone code block is the measured geometry recipe, but the physical proof also depends on the current connected host and source pins. The x axis, Circle, explicit origin and downstream combinations remain outside actual physical qualification until separately measured. D463 is historical Studio evidence; it is not current React native proof. No new kernel algorithm, tolerance, face/UV, asynchronous admission or general SDK guarantee follows. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Union Joins realized solid operands in declared order through existing Model union nodes. The React group may lower to more than one native node. Import `Union` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required; at least two realized solids | Compatible synchronous wrappers are allowed. | | `ref` | Optional SolidRef | The combined solid handle has kind union. | ## Example ```tsx import { Union, Extrude, Rectangle } from '@barocss/cad-react'; export function BracketTarget() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Union folds its operands through the existing backend in source order. Use it to make the single target for a Difference or the single Part output. It does not join unrelated React nodes or execute user component functions. Fewer than two realized solids refuses. Profile inputs are incompatible. There is no solid prop on Union; reuse refs through components that accept a solid input. Backend Boolean refusals and native tolerances remain authoritative. ## References and identity Stable React keys retain supported mounted operand IDs across reorder; the current order still determines native parent refs. A remounted key creates new identity. ## Measured boundary The floor/wall union is part of the independently measured Bracket. That selected Boolean arrangement is not general union robustness or geometric-equivalence proof. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Difference Subtracts an ordered list of solid tools from one solid target. Difference is logical composition and can lower to multiple existing native difference nodes. Import `Difference` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Exactly one Target and one Tools group | No other direct realized slots are accepted. | | `ref` | Optional SolidRef | The final cut solid handle has kind difference. | ## Example ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function HoledPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation One Target establishes the initial solid. Each tool is subtracted from the running result in declared order. An overcut tool outside the target does not count as removed target material. Missing/duplicate slots, empty Tools or incompatible operands refuse. Difference does not accept a target or tools prop in place of its logical child groups. It adds no new Boolean algorithm, tolerance policy or mesh fallback. ## References and identity The outer Difference may expose one SolidRef. Target and Tools are operand slots, not native body handles or independent Part outputs. IDs/parent links are generated by the compiler. ## Measured boundary The original and transformed Bracket measure four floor cuts and the wall window. The standalone example above is a complete typechecked usage pattern, not an additional independent physical qualification. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Target Selects the single solid operand for its parent Difference. Target is a logical slot and creates no native feature node of its own. Import `Target` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | One realized solid child | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children; forward refs are supported after commit. | ## Example ```tsx import * as React from 'react'; import { Definitions, Difference, Target, Tools, Extrude, Rectangle, Circle, type SolidHandle } from '@barocss/cad-react'; export function ReusedTarget() { const plate = React.useRef(null); return <> ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Use Target directly inside Difference. It accepts a compatible solid from an ordinary wrapper or one typed SolidRef. TargetProps is the public exclusive-input type. Both child and solid, zero/multiple solids, a ProfileRef or missing/cyclic reference refuse. Target has no own output ref or native-ID prop. It is not a valid standalone Part solid. ## References and identity A referenced solid belongs to the same Part and must have one binding owner. Pass the object ref, not its current handle; lookup resolves the committed graph. ## Measured boundary Measured Bracket targets use ordinary child composition; controlled compiler/ReactDOM/type tests cover typed reference resolution. These are distinct proof channels. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Tools Groups the ordered solid cutters for Difference. Tools is a logical slot, not a native feature or a union of its children. Import `Tools` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required; one or more realized solids | Each tool is subtracted in the current declared order. | ## Example ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function TwoHolePlate() { return {[10,70].map(x => )} ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Tools belongs directly under Difference beside exactly one Target. Keyed arrays and compatible synchronous wrappers can produce its cutters. The cutter order is preserved rather than silently merged. An empty group refuses. Profiles must first be extruded to solids. Tools has no ref, solid, geometry-query or implicit-depth prop and cannot be the standalone Part output. More than one Tools slot is invalid. ## References and identity React keys provide mounted cutter identity during supported reorder/update. Tool source identity is separate from physical intersection success; native IDs are generated without author-supplied values. ## Measured boundary The actual Bracket cuts four radius3 floor holes followed by its window. The two-tool sample is a complete API pattern grounded in those source/tests, not an additional measured geometry domain. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Definitions Declares reusable profiles and solids without adding independent Part outputs. It is a logical registry group, not a native modeling operation. Import `Definitions` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required ReactNode | Supported profile or solid declarations with optional typed object refs. | ## Example ```tsx import * as React from 'react'; import { Definitions, Circle, Extrude, type ProfileHandle } from '@barocss/cad-react'; export function SharedProfile() { const profile = React.useRef(null); return <> ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Place Definitions alongside the single Part output. A consumer may appear earlier in JSX: the compiler resolves references in the committed graph. Use ProfileRef for an extrusion source and SolidRef for a target or transform source. Rectangle, Circle and Polygon, plus Loop and Profile, can declare profile tokens in this group. A synchronous ordinary component can pass its optional ref to Polygon. D504 controlled tests cover Polygon forward references through ordinary React components. This reference support does not qualify every native outline. Definitions alone is not a Part solid output. Missing, duplicate, cross-Part, wrong-kind and cyclic references refuse. Callback refs and ref.current are not dependency tokens. Definitions has no own ref or native-ID prop. ## References and identity React.useRef creates the supported object token; no useGeometryRef hook is exported. Handles expose kind metadata only. Reuse does not create persistent source-code links after saved-document reload. ## Measured boundary Controlled compiler and real ReactDOM tests cover forward refs, scoped lookup, typed kinds and invalid retention. No separate unmeasured native face/region producer is added by this registry. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Translate Places one solid with the existing Model body-translation node. It adds the authored XYZ offset to the parent solid in model coordinates; no frontend transform math is introduced. Import `Translate` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `offset` | Required readonly [x,y,z] | Three explicit finite millimetre coordinates; sparse arrays refuse. | | `children` | One realized solid | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children. | | `ref` | Optional SolidRef | Resulting handle kind translate. | ## Example ```tsx import { Translate, Extrude, Rectangle } from '@barocss/cad-react'; export function MovedPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation TranslateProps uses SolidInput. A nested child is lowered first, then its resulting solid becomes the translation parent. Wrap Rotate in Translate to rotate first and then apply the world offset, as the TransformApp recipe does. Missing coordinates, nonfinite/sparse offset, incompatible profile input, both child and solid or wrong cardinality refuse. Zero coordinates are valid; offset is not a destination bounding-box or unit-conversion command. ## References and identity Mounted transforms preserve supported IDs when offset changes; invalid declarations do not consume committed IDs. The optional ref remains scoped to this Part, with no geometry or matrix exposed on its handle. ## Measured boundary Actual W80 Bracket states use dx30/50,y40,z5 after Z90/180 origin rotation. Global translation plus automatic framing can produce identical pixels; current world Doc/centroid/bounds and owners establish the change, not forced framebuffer differences. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Rotate Rotates one solid with the existing Model body-rotation node. The component declares parameters; native backend code performs the transformation. Import `Rotate` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `axis` | Required x/y/z | Existing axis vocabulary. | | `angle` | Required finite number; abs≤3600 | Degrees; zero is valid. | | `pivot` | Optional readonly [x,y,z] | Explicit finite mm coordinates; omission stays omitted and uses the existing backend origin default. | | `children` | One realized solid | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children. | | `ref` | Optional SolidRef | Resulting handle kind rotate. | ## Example ```tsx import { Rotate, Translate, Extrude, Rectangle } from '@barocss/cad-react'; export function PlacedPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation RotateProps uses SolidInput. The inner Rotate above lowers before the outer Translate. Provide an explicit pivot when that placement matters; an omitted pivot is not silently written into the authored document. Invalid axis, nonfinite/out-of-limit angle, sparse/nonfinite explicit pivot, incompatible profile input, mixed child/ref or wrong cardinality refuse. There is no quaternion/matrix, camera, arbitrary-axis vector or selected-face rotation prop. ## References and identity Mounted transform identity and refs follow the same Part-scoped rules as other solids. Compiler validation retains prior accepted source on refusal; it does not make that old visible shape current. ## Measured boundary API axes/±3600 input acceptance is broader than independent actual proof. D497 measures only W80 Bracket, Z90°/180°, explicit origin pivot and selected dx30/50 translations. No arbitrary-angle or non-origin-pivot accuracy certificate follows. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Hole Cuts one solid with the existing native Hole operation. Import Hole and HoleProps from @barocss/cad-react. This is a private workspace API. | Prop | Contract | |---|---| | center | Required dense finite coordinate pair in mm. Axis z uses XY; x uses YZ; y uses ZX. | | radius | Required positive finite mm. | | axis | Optional x, y or z. Omission keeps the native z default. | | side | Optional min or max along the axis. Omission keeps native max. | | depth | Optional positive finite mm. Omit for through; supplied depth uses the existing flat-bottom cut. | | children / solid | Exactly one realized solid child or SolidRef, exclusive. | | ref | Optional SolidRef for the resulting Hole. | ```tsx import { Hole, Extrude, Rectangle } from '@barocss/cad-react'; export function BlindPlate({depth = 6}: {depth?: number}) { return ; } ``` Place this output inside Part with a connected lifecycle. A solid ref can replace the child, including a forward ref declared inside Definitions. Mounted identity follows the existing scoped solid rules. The compiler checks numeric inputs, input kind, cardinality and reference ownership. Native code decides whether the cut fits its stock. It receives omitted fields unchanged. Invalid declarations retain the preceding accepted document and frame while retiring freshness; valid recovery submits current geometry again. A flat-bottom Hole differs from the native blind-drill-hole operation with a drill point. No face selection, thread, pattern, countersink, drill angle or manual native ID is exposed here. A solid output can contain native pieces; this component adds no universal connected-solid guarantee. The desktop verification changes the blind depth and radius in React, checks the current native body and Viewer frame, then edits and reopens the returned Hole in Studio. The through and alternate-axis props have focused compiler coverage. This desktop verification uses one upper-face blind Hole. --- # References, identity and compiler results Native IDs are generated automatically. Use a typed object ref when another branch must consume declared geometry. A handle describes a supported kind; it does not contain synchronous evaluated CAD geometry. ## Share a profile ```tsx import * as React from 'react'; import { Definitions, Circle, Extrude, type ProfileHandle } from '@barocss/cad-react'; export function SharedProfile() { const profile = React.useRef(null); return <> ; } ``` Place this component inside a Part. Pass the ref object itself, not `profile.current`. The example declares the producer after its consumer: lookup resolves the committed model, so this is a supported forward reference. Do not read a handle during render to obtain geometry. ## Share a solid ```tsx import * as React from 'react'; import { Definitions, Extrude, Rectangle, Rotate, Translate, type SolidHandle } from '@barocss/cad-react'; export function SharedSolid() { const source = React.useRef(null); return <> ; } ``` A profile token cannot be used as a solid operand, and a solid token cannot be an extrusion profile. References are scoped to one Part. Missing, wrong-kind, duplicate or cyclic bindings refuse. Callback refs are not graph dependency tokens. Passing both a child and a source ref is invalid. | Public type | Meaning | |---|---| | `ProfileHandle` | Readonly kind `rectangle`, `circle` or `polygon` | | `SolidHandle` | Readonly kind `extrude`, `revolve`, `union`, `difference`, `translate` or `rotate` | | `ProfileRef` | React object ref containing `ProfileHandle|null` | | `SolidRef` | React object ref containing `SolidHandle|null` | | `ModelLifecycle` | Declaration dirty/invalid/complete/detached callbacks | | `ExtrudeProps`, `RevolveProps` | Exclusive one-profile child or ProfileRef input; their numeric operation parameters differ | | `TargetProps` | Exclusive one-solid child or SolidRef input | | `TranslateProps`, `RotateProps`, `SolidInput` | Existing body-transform and exclusive solid-input contracts | Extrude and Revolve share the child-or-profile-reference rule. Their exported prop types express that union directly; there is no public `ProfileInput` type export. Revolve outputs a SolidRef and can take part in Definitions, Boolean and rigid-transform declarations. Controlled composition checks do not qualify every combined shape as a new native case. ## Identity and invalid declarations Mounted feature identity and ordinary React keys retain native IDs through supported prop updates and reorders. Removal/remount creates a new identity. A ref object or an automatic native ID does not reconnect source code to a saved document after page reload. The compiler stages IDs until a declaration succeeds. An invalid declaration retains the prior accepted compiler result. That does not make prior displayed geometry current: dirty/invalid/detached lifecycle changes retire freshness in the host. Applications must distinguish previous visible geometry from a ready current result. ## CompositionCompiler and IrError `CompositionCompiler` is a public lower-level utility for inert realized descriptors. It does not execute React functions, native geometry or rendering. Most React hosts should use Part rather than manually construct descriptors. ```ts import { CompositionCompiler } from '@barocss/cad-react'; const result = new CompositionCompiler().compile({ kind: 'part', units: 'mm', children: [{ kind: 'extrude', distance: 6, children: [{ kind: 'rectangle', min: [0,0], max: [80,60], }], }], }); if (result.ok) { const document = result.value.doc; void document; // A compiled model document, not an evaluated B-rep. } else { console.error(result.error.code, result.error.message); } ``` | Public type | Fields | |---|---| | `Compiled` | `revision`, `doc`, `fingerprint`, `sourceIds` provenance | | `CompileResult` | Success `{ok:true,changed,value}` or failure `{ok:false,error,previous}` | | `ErrorCode` | The finite compiler refusal-code union below | Treat compiled results as immutable. Logical compiler outputs may be normalized by the existing Model reader; do not assume a compiler output key is already the accepted engine body key. `IrError` extends Error and exposes `code`. Current compiler codes are `CARDINALITY`, `TYPE`, `CYCLE`, `MISSING_REFERENCE`, `DUPLICATE_BINDING`, `DUPLICATE_ALIAS`, `DUPLICATE_KEY`, `INVALID_PARAMETER`, `EXCLUSIVE_INPUT` and `UNSUPPORTED_CAPABILITY`. These are declaration errors, not a replacement for the CAD engine's native refusal and tolerance contracts. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # React CAD SDK (`@barocss/cad-react/sdk`) While the root `@barocss/cad-react` entry provides declarative JSX geometry authoring (``, ``, ``), **`@barocss/cad-react/sdk`** ships ready-to-mount React components and hooks for building CAD viewers, configurators, and 2D drawing inspectors — the exact SDK powering [BaroCSS Review](/studio/review). ## Public exports | Export | Kind | Purpose | | --- | --- | --- | | `CadViewport` | Component | Embeddable WebGPU/WebGL2 3D CAD viewport bound to evaluated display meshes or snapshots | | `CadDrawing` | Component | Interactive 2D HLR engineering drawing SVG view with semantic edge/face/item hit callbacks | | `useCadDocument` | Hook | Manages reactive `.bcad` / part document state, parameter overrides, and worker evaluation | | `useCadSelection` | Hook | Tracks typed 3D/2D entity selection (`surface`, `curve`, `edge`, `item`) across views | | `renderCadDrawingSvg` | Function | Headless SVG rendering helper over `@barocss/cad-projection` with semantic `data-*` attributes | | `extractDrawingHit` | Function | Maps pointer events on a `CadDrawing` SVG element to typed `CadDrawingHit` payloads | | `snapshotToDisplayMeshes` | Function | Converts an evaluated kernel/model snapshot into `CadViewport` display mesh packets | ## Interactive 3D + 2D cross-highlighting Combine `CadViewport` and `CadDrawing` with `useCadSelection` to build split 3D/2D review surfaces: ```tsx import { useState } from 'react'; import { CadViewport, CadDrawing, useCadSelection, type CadDrawingHit, type ProjectionItem, } from '@barocss/cad-react/sdk'; export function PartReviewCard({ items }: { items: readonly ProjectionItem[] }) { const selection = useCadSelection(); const [lastHit, setLastHit] = useState(null); return (
{ setLastHit(hit); if (hit?.itemId) selection.select({ kind: 'item', id: hit.itemId }); }} /> {lastHit &&
{JSON.stringify(lastHit)}
}
); } ``` ## Semantic 2D SVG hit callbacks `CadDrawing` wraps [`@barocss/cad-projection`](/packages/cad-projection/) and annotates projected paths with semantic metadata (`CadDrawingEdgeHit`, `CadDrawingFaceHit`, `CadDrawingItemHit`). Clicking a hidden line, silhouette edge, or filled face invokes `onHit` with the originating B-rep item and edge classification so inspectors and 3D viewports stay synchronized without DOM coordinate heuristics. ## Headless JSX DSL (`@barocss/cad-react/dsl`) For server-side or worker-side declarative part generation without a DOM, import the headless compiler from `@barocss/cad-react/dsl`. For standard component props and compiler rules, see [Components and props](/packages/cad-react/components). --- # Engine and Viewer integration The package does not create a Worker or ship an engine client. Supply an existing implementation of `EnginePort`, a provenance-aware mass merger and a Viewer sink. Give one ModelHost exclusive evaluation use of its injected engine. `EngineClient` in the Studio source and the repository's `connectHost` example helper are application integration examples, not exports from `@barocss/cad-react`. A private Studio import is not a portable public client. ## Connect an existing engine This is an application helper built from current public exports. The caller provides engine/massPolicy and later disposes the returned host. Pass that host as Part's lifecycle. ```ts import { ModelHost, type EnginePort, type MassPolicy } from '@barocss/cad-react/engine'; import { ExistingViewerHost } from '@barocss/cad-react/viewer'; export async function connectCADView( canvas: HTMLCanvasElement, engine: EnginePort, massPolicy: MassPolicy, ): Promise { const sink = await ExistingViewerHost.create(canvas); let host: ModelHost|undefined; try { host = new ModelHost({ engine, ownership: 'borrowed', massPolicy, sink, ownsSink: true }); host.connect(); return host; } catch (error) { try { if (host) host.dispose(); else sink.dispose(); } catch { /* Retain connection error. */ } throw error; } } ``` Construct/connect after React commit, such as in an owning effect, and clean up when the application unmounts. Guard an asynchronous Viewer creation against an already-retired mount; the repository App examples show this pattern. ModelHost's constructor is inert: `connect()` installs subscriptions. Keep the engine, massPolicy and lifecycle identities stable for the intended lifetime. A Worker failure after a successful frame also makes `ModelHost.read()` report `failed`, with readable title, hint and detail. It does not restart the borrowed engine or resubmit automatically. In the repository `App` and `ProfileApp` examples, the engine owner can provide an optional `onRestart` callback that calls its existing client's `restart()` and returns whether it succeeded. The private Retry button uses that explicit callback, then rerenders the current declaration with the same Part, host, parameter values and feature IDs. A refused or thrown restart keeps the failure visible. Reset changes only the example's parameter. A Viewer startup failure has no connected host and does not offer Worker Retry; recreating that Viewer remains the caller's responsibility. ## Required ports and ownership Import these public types from `@barocss/cad-react/engine`: | Type | Required contract | |---|---| | `EnginePort` | `evaluate(doc,revision)`, `restart()`, `dispose()`, `onFailure(listener)`, `onMasses(listener)` | | `MassPatch` | `ref`, `fields`, and original `nativeMass` provenance envelope | | `MassPolicy` | `merge(bodies,patches)` using the existing provenance-aware native-mass policy | | `Owner` | Readonly `hostEpoch`, `declaration`, `evaluationRevision`, `fingerprint` | | `ExistingViewerSink` | Async `show(bodies,owner,stillCurrent)`, `snapshot()`, `dispose()` | | `ModelHostOptions` | `engine`, `ownership`, `massPolicy`, `sink`, `ownsSink` | `EnginePort.evaluate` returns a Promise of the existing CAD Model evaluation result or null. Failure/mass subscription methods return unsubscribe functions. `restart` returns a boolean. The host application owns the engine's Worker URL, protocol, CSP and caches; this package does not duplicate them. Do not merge mass patches only because numeric refs happen to match. Inject the existing native provenance checks. This is part of the port contract, not an optional performance optimization. `ownership:'borrowed'` leaves the engine with its caller. `ownership:'owned'` transfers its disposal policy to the host. `ownsSink` separately controls sink disposal. Host disposal removes subscriptions; applications must dispose their borrowed resources at their own boundary. ## ModelHost and readiness `ModelHost` implements the public `ModelLifecycle` interface. Part supplies `dirty`, `invalid`, `complete` and `detached` events; ordinary application components should not manufacture those events to inject a document. `connect()`, `read()` and `dispose()` serve integration and observation. `read()` reports status, pending declaration state, current accepted document/JSON, fingerprint, native/rendered owners, current native body diagnostics and the sink snapshot. Status is `pending`, `ready`, `failed` or `disposed`. A ready state requires current native and completed presentation ownership. A previous mesh may remain visible while the latest declaration is pending or invalid. Its visibility is not current acceptance. Each `read()` detaches the host-owned current document (including nested values), submitted request array and records, native centroid/bounds arrays, and the adapter's outer state. Mutating these returned copies does not change the host or a later observation. A held observation does not acquire later submitted requests. Volume, centroid, bounds and other numeric values keep their existing units and meaning. Owner tokens retain the same identity across reads. Tokens issued by `EngineAdapter` are frozen; a caller-provided Owner passed to `ExistingViewerHost.show()` is neither copied nor frozen by the sink. The adapter's `error: unknown` payload and a custom sink's `snapshot(): unknown` result are extension-owned values: their original identities and extension contracts remain in effect, and they are not deep-cloned. These boundaries allow callbacks and other non-cloneable extension data. The complete observation is not an immutable deep snapshot. Readiness separates declaration, evaluation revision, native mass readiness and display completion. Equivalent valid checkpoints may reuse a current request/result; invalid/failure recovery requires current ownership again. The existing Model reader normalizes accepted output keys. Diagnostic volume/centroid and mesh bounds do not replace independent native physical validation. ## ExistingViewerHost Import `ExistingViewerHost` from `@barocss/cad-react/viewer`. `create(canvas)` creates the existing Viewer sink and attaches the Viewer's pointer/keyboard controls. `show` sends render-only body meshes with right-handed Z-up/mm source metadata to the public Viewer facade, then observes frame completion under the supplied owner. `snapshot()` reports Viewer/camera/display-mesh metadata, mounted/frame owners and pixel diagnostics. `dispose()` releases its controls and Viewer. The sink detaches its own pixel-diagnostic record (`bytes`, `nonBackgroundPixels`, `sha256`) on each observation; this does not copy render meshes or raw image buffers. Viewer-provided camera and display metadata keep the existing Viewer facade's contract. Meshes have approximate-display authority. They are not native Face/UV geometry, pick provenance or physical B-rep authority. Frame-owner/pixel observations show a displayed current result; they are not an accuracy oracle. Global translation plus automatic framing may leave pixels identical while the document and world-space bounds change. The existing [Viewer documentation](/packages/viewer/) covers its separate public review/file/control features. Those APIs are not new CAD React exports, and saving a Viewer review does not save or reconnect JSX source. --- # Examples These examples use current public package exports. The repository examples provide the complete injected-engine application: `packages/barocss-cad-react/examples/App.tsx`, `Bracket.tsx`, `TransformApp.tsx`, `TransformedBracket.tsx` and the application helper `connect-host.ts`. The latter is not a package export. No public engine client or standalone Worker is implied. ## A bracket with ordered cutting tools ```tsx import { Difference, Target, Tools, Union, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function Bracket({ width }: { width: number }) { const holes = [ { key: 'front-left', at: [10,10] as const }, { key: 'front-right', at: [width-10,10] as const }, { key: 'rear-left', at: [10,44] as const }, { key: 'rear-right', at: [width-10,44] as const }, ]; return {holes.map(hole => )} ; } ``` The two target extrusions make the floor and wall. Four keyed tools cut floor holes. The last tool cuts a wall window. Extrusion overcut outside the target is not extra removed material. Place Bracket under Part with a connected lifecycle to evaluate/display it. This follows the current Bracket source. The original measured package flow changes width80→100→80 through its public input, using the real existing Worker and Viewer. That finite proof is not a width-range certificate or a promise that all Boolean compositions succeed. ## Rotate first, then translate ```tsx import { Translate, Rotate } from '@barocss/cad-react'; import { Bracket } from './Bracket'; export function TransformedBracket({ dx, angle }: { dx: number; angle: number }) { return ; } ``` `./Bracket` is the preceding example saved as `Bracket.tsx`, not a package export. Nested ordering matters: the W80 bracket is rotated around the origin before its world translation. The measured transform states are A(dx30,90°), B(dx50,90°), C(dx50,180°), then returned A. The public Translation X and Rotation Z inputs belong to the desktop TransformApp example. For the90° state, a source point[x,y,z] becomes[dx−y,40+x,5+z]. For180°, it becomes[dx−x,40−y,5+z]. Those are exact cardinal expectation rules used for these states, not a frontend transform implementation. The backend performs the native transformations. ## State updates through normal React ```tsx import * as React from 'react'; import { Part, type ModelLifecycle } from '@barocss/cad-react'; import { TransformedBracket } from './TransformedBracket'; export function PlacementControls({ lifecycle }: { lifecycle: ModelLifecycle }) { const [dx, setDx] = React.useState(30); const [angle, setAngle] = React.useState(90); return <> ; } ``` This code changes model props through ordinary React state. It needs the separately connected engine/Viewer integration; it does not create a canvas or a Worker. Blank/nonfinite input is an invalid declaration, not authorization to treat old visible geometry as fresh. Use the lifecycle/readiness state when presenting current results. ## Current desktop controls The repository App, TransformApp and RevolveApp share a right inspector with compact numeric fields, collapsible groups, actual host status and Reset. Folding controls leaves Part mounted. Status polling is owned by a separate inspector child and stops on unmount; the measured idle interval changes no document, request, checkpoint or owner. The Width example measures 80→100→Reset80. Transform measures A(30,90°)→B(50,90°)→C(50,180°)→ResetA. Reset restores the actual initial props. Source/request counts are observed, not assumed from the number of control edits. Canvas buffer 1000×700 and displayed 10:7 aspect are retained. See [validation limits](/packages/cad-react/limits) for current native/consumer evidence and finite scope. Global translation followed by automatic framing may leave pixels identical. The proof checks world document, centroid/bounds and fresh owners instead of forcing a pixel difference. Exact return document/frame is a finite observation, not general raster precision. ## Polygon inspector `examples/PolygonApp.tsx` uses the same existing engine/Viewer lifecycle and InspectorGroup/NumericField controls. Its Width prop drives a pentagonal plate; Reset restores 60 mm. The selected sequence uses 60 mm, 80 mm, blank-input refusal, valid 80 mm recovery and Reset to 60 mm. Current Worker/Viewer ownership, public collapse/reopen, idle behavior and the returned-document Studio Open pass. Separate settled-error UI proof retains the previous frame without an extra request. This adds no explanatory overlay or new renderer. ## Revolved section inspector `examples/RevolveApp.tsx` connects the same existing engine/Viewer lifecycle to `RevolvedSection`. The [complete Revolve recipe](/packages/cad-react/components/revolve) uses rectangle `[10,20]..[20,50]`, axis y and omitted origin. The actual Angle field measures 90°→180°→360°→public Reset 90°. Working collapse/reopen and 1200 ms idle leave the geometry and owners stable. The returned document opens through public Studio Open and Frame all. No arbitrary-axis, Circle or explicit-origin physical certificate follows from these selected states. See [current evidence](/packages/cad-react/limits#current-evidence); final saved-data review passes 41014 saved checks plus five post-write 64-hex document checks. ## Composite profile composition `examples/ProfileApp.tsx` demonstrates `SegmentedProfiledPlate` combining `Profile`, `Outer`, `Voids`, `Loop`, `LineSegment`, and `ArcSegment` in a single declarative `Part`. `Loop` and `Profile` produce closed-profile data with exact circle conversion and no orphan sketch emission, while remaining composable with `Extrude.profile` and typed refs. --- # CAD Model to React support map CAD React is the first adapter subset, not a complete React facade over CAD Model. The D509 implementation has nineteen logical elements: six operation adapters (Extrude, Revolve, Union, Difference, Translate, Rotate), five profile producers (Rectangle, Circle, Polygon, Loop, Profile), two segment descriptors (LineSegment, ArcSegment) and six structural elements (Part, Target, Tools, Definitions, Outer, Voids). The prior thirteen remain. Current76controls/types/lint/semanticmutants and selected native/Viewer proof pass; Studio Open/F and current Worker binding pass and freshdocs proof is NOT_RUN. This count is not a CAD-completeness percentage. All three packages currently identify as `0.0.0`. This map reads `packages/barocss-cad-model/src/engine/doc.ts` (`ModelNode = ModelNodeBase & NodeExtras`), current React `src/index.ts`/`components.tsx`/`compiler.ts`, and the existing public tests. The exact Model source SHA256 is `b35d4dedc69cb4921489084cd1c52e6fe0770b03916fd5000553b6728fdbe799`. A source AST inventory finds 75 distinct top-level ModelNode kind strings. That is a schema inventory, not 75 independently runtime-qualified capabilities. It excludes nested path/parameter tags from the count. ## Read the status correctly - ADAPTER: a named current React element lowers to the existing operation. It does not extend backend support or independently qualify all parameters. - PARTIAL: only a bounded part of a Model node's input vocabulary is exposed. - UNEXPOSED: the Model declaration exists, but no current public React component lowers it. This does not mean the CAD backend feature is absent. - GATED: a relevant existing owner HOLD still applies. Unexposed features are not all automatically held, and this document does not authorize an implementation or release a HOLD. `Part`, `Target`, `Tools` and `Definitions` are logical structure, not extra native feature kinds. Rectangle/Circle/Polygon are profiles lowered into sketch storage; there is no public Sketch-only prop or `` component. Conversely, a normal user function returning geometry is React composition, not an additional shipped element. ## Complete current ModelNode-kind inventory Every top-level kind appears exactly once below. Source locations refer to the current `packages/barocss-cad-model/src/engine/doc.ts`; they identify declarations, not validation receipts. | Model family | Existing Model kinds | React bridge | Boundary / missing contract | Declaration lines | |---|---|---|---|---| | Profile storage | `sketch` | PARTIAL | Rectangle/Circle/Polygon and Loop/Profile expose bounded closed-profile data and explicit holes. Band, regions, constraints, plane/face association and other SketchNode fields remain unexported. | `doc.ts:358` | | Current operation adapters | `extrude`, `revolve`, `union`, `difference`, `translate`, `rotate` | ADAPTER | Current Extrude/Revolve/Union/Difference/Translate/Rotate lower these existing nodes. Revolve adds selected rectangle/y-axis/omitted-origin 90/180/360 actual evidence; broader parameters remain outside physical qualification. Native limits and finite evidence remain separate. | `doc.ts:383, 385, 400, 402, 386, 388` | | Other profile solids | `sweep`, `sweep-curve`, `loft` | UNEXPOSED | No current component export. A bridge needs explicit profile/path/section/source/refusal contracts; existing backend is not missing. | `doc.ts:410, 412, 415` | | Other Boolean/body operations | `intersect`, `mirror`, `scale`, `split`, `separate` | UNEXPOSED | No current component export. Preserve existing output cardinality and body/reference identity before adding a bridge. | `doc.ts:401, 389, 391, 408, 652` | | Body patterns | `linear-pattern`, `circular-pattern` | UNEXPOSED | No current array/pattern component. Counts, placement, skipped occurrences and identity need a defined adapter contract. | `doc.ts:392, 399` | | Feature patterns | `linear-feature-pattern`, `fill-feature-pattern`, `curve-feature-pattern`, `rectangular-feature-pattern` | UNEXPOSED | Reference/selection-driven feature patterns require their own producer and ownership contract; existing typed refusal boundaries stay. | `doc.ts:394, 395, 396, 397` | | Finishing and holes | `thread`, `shell`, `chamfer`, `draft`, `full-round`, `face-fillet`, `face-thread`, `split-face`, `fillet`, `hole` | UNEXPOSED | No React selection-based finishing component. Edge/face source authority, rematch/refusal and current native support must be addressed; no fake handle/query is available. | `doc.ts:430, 432, 434, 639, 641, 643, 645, 647, 649, 660` | | Profile/detail text operations | `rib`, `rectangular-relief`, `text`, `text-relief`, `cylindrical-wrap` | UNEXPOSED | No current component or portable font/face-selection adapter. Backend/model declarations do not automatically expose these inputs. | `doc.ts:404, 406, 83, 85, 216` | | Imported/mesh data | `import`, `mesh`, `decimate` | UNEXPOSED | No source-file/mesh/import component. File/blob ownership, IO, provenance and display-vs-native authority remain separate. | `doc.ts:418, 424, 658` | | Sheet metal | `sheet-base`, `sheet-contour`, `sheet-corner-relief`, `sheet-flange` | UNEXPOSED | No current sheet component. Manufacturing and independently held workflows are not activated by a JSX adapter. | `doc.ts:441, 442, 448, 449` | | Frames and skeletons | `skeleton`, `frame`, `frame-member` | UNEXPOSED | No current structural graph component. These existing Model records are not ordinary React wrapper functions. | `doc.ts:463, 468, 469` | | Advanced surfaces | `band-surface`, `thicken`, `subd`, `sew` | UNEXPOSED / GATED | No current component. In particular #2258 public-thicken/fitter and #2266 widening remain held; this inventory releases neither gate. | `doc.ts:477, 478, 635, 637` | | Library and generated mechanical parts | `library`, `rack`, `internal-gear`, `bevel-gear`, `worm-wheel`, `spring`, `cam`, `sprocket`, `pulley`, `belt`, `coupling`, `shaft`, `oring-gland`, `oring`, `connector-opening`, `connector-body`, `gusset`, `end-cap`, `bearing`, `key`, `keyway`, `retaining-ring`, `pin`, `worm`, `gear` | UNEXPOSED | No current catalog/generator component. Existing generator versions, estimates, assembly/engineering claims and owner gates retain their own boundaries. | `doc.ts:501, 510, 516, 529, 546, 556, 566, 575, 576, 577, 578, 584, 603, 604, 611, 612, 619, 620, 621, 622, 623, 624, 625, 626, 627` | The sketch kind has rectangle/circle/polygon/loop/band variants; current baseline JSX exposes Rectangle/Circle numeric inputs and ordered Polygon points; D509 implements exact Loop segments and Profile outer/void composition. D504 Polygon has current tests and selected width-60/80 pentagon native/Worker/Viewer and returned-document Studio evidence. Other outlines remain outside that finite physical proof. The React package also does not expose general Model parameters (`Dim`), NodeExtras suppression/held/rematch fields or a source-code restoration system. Assemblies, mates, BOM, drawings, versions and robot settings are additional document APIs outside this ModelNode table; their existence is not a React API. ## Proposed bridge backlog, not new exports The existing D445 order remains C1 everyday parts, C2 ordinary robustness, C3 handoff, C4 static assemblies, then later/gated breadth. A reproduced C1/C2 blocker can change the order. The following is source-grounded selection guidance, not a promise to implement all candidates now. | Order | Candidate existing capability | Why it is useful / required adapter work | |---|---|---| | Delivered subset | Revolve | The existing-node adapter has declaration/types/lint checks and a current real React rectangle90/180/360/Reset 90 workflow plus returned-document Studio Open. This does not qualify arbitrary profiles, axes, origins or downstream combinations. | | 2 | Ordinary finishing: Hole, Chamfer, Shell, Fillet | C1/C2 daily tasks already exist (`doc.ts:660/434/432/649`). Define Hole parent/center/depth inputs and, where required, Chamfer/Fillet edge and Shell open-face selection sources with reference ownership. Current handles contain kind only; no new native Face/UV/query API is implied. | | 3 | Ordinary Sweep and Loft | Existing copied path/section workflows (`doc.ts:410/415`, `part/part-profile-solid.ts`). Define typed path/section frames, ordering, copied-source semantics and refusal before JSX surface. Curve sweep and broad surface/general-guide variants are separate. | | 4 | Body patterns, then feature patterns | C2 repetition requires stable occurrences, count/skip/placement/history and source refs. Body patterns (`doc.ts:392/399`) are a smaller boundary than selection-driven feature patterns (`394–397`). Do not treat an ordinary `.map()` of JSX as already implementing a native pattern feature. | | 5 | Other ordinary body/Boolean adapters | Intersect, Mirror and Scale already exist (`doc.ts:401/389/391`). Define exact solid inputs, output cardinality and retained native parameters rather than inventing new JSX math or implicit geometry equivalence. | The unexposed candidates describe possible bridges, not current exports. Revolve is now an export with the narrower qualification status stated above. Select the next bridge through the CAD roadmap and source audit after the present item; ordinary implementation is already authorized. Existing HOLD releases and gated downloads retain their specific owner requirements. There is no authority here to create dozens of placeholder components or call source inspection a runtime PASS. ## Holds and proof limits #2258 public-thicken/fitter, #2266 widening, manufacturing P2/PG11, new Physics/Motion, schema widening, browser CI, downloads and release retain their recorded gates. Existing accepted workflows and research history stay intact. The owner-authorized React example inspector does not lift the separate Studio UI redesign hold. Current React physical evidence includes the original Bracket widths 80/100, the selected W80 cardinal transforms and the selected rectangle Revolve 90/180/360, each with its recorded returned-document Studio Open boundary. It does not qualify all ModelNode kinds, angles, faces, profiles or generator families. Read [current support limits](/packages/cad-react/limits), the [component catalog](/packages/cad-react/components), the broader [CAD Model](/packages/cad-model/) API and [CAD modeling](/packages/cad/modeling) documentation for their separate contracts. --- # Support and validation boundaries The package is private workspace source, version `0.0.0`. Current code accepts more parameter combinations than have independent actual geometry evidence. Keep declaration support, controlled tests, real Worker/Viewer behavior and native physical accuracy separate. ## React admission Use `admission="synchronous"` for ordinary synchronous components, props, hooks, Fragments and keyed arrays. Current controlled tests cover normal registration, references, reorder, invalid retention, lifecycle cleanup and StrictMode replay. The compiler never calls a user function to guess its geometry. Portaled geometry and directly supplied unsupported async builtins refuse. A wrapper can hide an internal Suspense boundary whose fallback happens to leave a valid smaller model. The ordinary DOM registry cannot universally detect that hidden intent. Internal Suspense, Offscreen and async transitions remain unsupported, even when hidden by a wrapper. Resolve async inputs outside the complete Part before mounting it. There is no general whole-intent atomicity guarantee or custom reconciler. ## Geometry and references Supported sources include Rectangle/Circle/Polygon and D509 Loop/Profile data, profile-based Extrude/Revolve, Union/Difference and existing Model Translate/Rotate nodes. Outer/Voids and segment descriptors supply explicit composition. Typed refs and Definitions reuse outputs within one Part. Profiles and solids have different kinds. Child and ref input are exclusive. IDs track supported mounted identities and keys, not persistent source-code identity after reload. No native face/UV producer, arbitrary region/open-wire source, face query, sketch-constraint graph, surface extrusion, general topology picking or source-to-saved-document reconnection is exposed by this API. The backend may have capabilities that this package does not expose. The React layer adds no Boolean, transform, B-rep, numerical-tolerance or renderer algorithm. ## API inputs versus measured states | Capability | Current source contract | Independent actual scope | |---|---|---| | Bracket props | Ordinary component prop updates | Original width80→100→80 example | | Rotate | Existing x/y/z axis, finite angle with absolute value≤3600; optional finite pivot | W80 bracket, Z90°/Z180°, explicit origin pivot | | Translate | Three finite coordinates, explicit indexed checks | dx30/50 with y40,z5, after that rotation | | Revolve | Closed profile child/ref; required sketch x/y axis, finite angle in `(0,360]`, optional finite2D origin | Rectangle `[10,20]..[20,50]`, y axis, omitted origin,90°/180°/360° and public Reset90° | | Polygon | One closed ordered profile; 3..1024 dense finite coordinate pairs; optional ProfileRef; native outline validity remains authoritative | Selected convex pentagon widths 60/80, height 8; public invalid recovery, Reset and returned-document Studio Open pass | | Source restore | Supported mounted identity/key reuse | Exact original/returned finite example Doc/frame | | Studio handoff | Existing document reader/normalization | Public Open of the exact returned actual document | No general arbitrary-angle, arbitrary-width, arbitrary-component, full parameter-domain or inertia-accuracy certificate follows. Native sampling is finite. Worker mesh bounds/frame pixels are consumer observations, not a replacement for original native B-rep geometry. Polygon adds no repair or tolerance rules. The native length, area, simplicity and contact limits still decide whether a declared outline can produce a solid. A valid points array does not certify a valid native outline. D504 measures only a convex pentagonal plate at widths 60 and 80 mm, with omitted plane/from and an extrusion distance of 8 mm. That selected native/Worker/Viewer/Studio proof passes; broader outlines remain outside it. ## Current evidence The D495 checkpoint records24 unique controlled tests, package/API types, lint and final Model types PASS. Three actual browser states, one public Studio Open and two new native captures/two physical-oracle runs plus two exact 80 subproof reuses bind four current consumers. Original test fixture/type and Studio preflight failures remain in its record. The D497 transform checkpoint has 34 controlled tests, package/API types and lint PASS. Actual A/B/C/returned-A and public Studio Open pass at the selected profile. Three native captures and three independent physical-oracle runs plus two exact-A subproof reuses bind five current consumers. The retained budgets are absolute volume1e-6mm³, density1 mass1e-9g, centroid/bounds1e-8mm and carriers1e-7mm. No numerical budget is weakened for the React path. High final saved-data review passes 7959 hash/cardinal-arithmetic checks, separate from the 34 product tests. Maximum world-volume error is 4.37e-11 mm³ and centroid error is 7.11e-14 mm; the retained limits are unchanged. The first pre-inspector transform run recorded ready revisions1,2,3,5: two return-control edits retired an intermediate declaration. The current inspector uses a public Reset that batches initial values. Its selected Transform ready revisions/requests are1,2,3,4; Width records1,2,3. These observations do not promise one Worker request per prop change or qualify every intermediate state. The new inspector has seven fresh ready UI consumers across the two examples. Public collapse/reopen,1200 ms idle, functional Reset, current owners, real Ready status, right280px panel,10:7 canvas aspect and no document overflow pass. The seven current whole documents bind seven saved native physical subproofs at unchanged eligible producer source; this UI-only step runs zero new native captures or physical oracles. The saved UI audit passes 20132 hash/ownership/arithmetic checks, separate from product test counts. Its first binder stopped on descriptive statusTimer wording; saved-only correction preserves that FAIL without browser/native replay. Global translation with automatic fit yields identical A/B pixels in this measurement. A fresh visible frame, matching owners and correct world geometry are required. Some retained Studio palette occlusion remains outside a full fit/raster-precision claim. Mesh display authority is approximate; native Face/UV authority is not added. The D499 Revolve checkpoint has 44 unique controlled tests, package/API types and lint PASS. The original test run passed 43 and stopped one test on duplicate sibling keys in its two-profile fixture. Assigning only the second fixture key uniquely preserves validation order and its intended cardinality expectation; that named test then passes. The prior 43 passes are reused, not rerun as 44 new executions. Four selected GUI states and public Studio Open pass. Collapse/reopen and 1200 ms idle preserve document/checkpoints/requests/owners/frame. Three current native captures plus two exact 90° subproof reuses bind five fresh consumers. Native output mass and independent B-rep mass, trimmed physical bounds and the partial/full closure contracts are checked at relative volume 1e-9 and absolute centroid/boundary/normal 1e-9. The full 360° state is a genus 1 annular tube with no radial end caps;90°/180° are genus 0 partial solids. This is not general x-axis/Circle/nonzero-origin/angle or downstream-operation qualification. Final independent saved-data audit passes 41014 saved checks plus five post-write 64-hex document checks, separate from 44 product tests. ## Packaging and operations There is no npm publication, portable engine implementation, standalone packaged Worker or distribution output at this checkpoint. The package manifest declares the existing React19.2.3 peer environment. The consumer owns engine construction, exclusive evaluation use, mass provenance, Worker URL/CSP/cache setup and borrowed-resource cleanup. Internal application helpers and Studio imports are not public package exports. No mobile validation, PDF/export convenience, standards/manufacturing acceptance, full-kernel/baseline suite, browser CI, deployment or release is claimed here. A documentation category is not publication of the package or site. Existing project HOLDs and physical proof boundaries remain in force. ## Polygon checkpoint The package has 57 controlled tests, package/API-example types and lint PASS. The current positive sequence is width 60 → 80 → blank-input refusal → valid 80 recovery → Reset 60, with four Ready GUI observations. The exact returned document opens through public Studio Open and Frame all. Two native captures and three exact-document subproof reuses bind five positive consumers, including that Studio observation. These are not five native captures. The selected convex pentagon is `[[0,0],[width,0],[width,50],[10,50],[0,40]]`, extruded by 8 mm. At widths 60 and 80, independent areas are 2950 and 3950 mm², volumes 23600 and 31600 mm³, and centroid Z is 4 mm. Each native result has seven faces, fifteen edges, ten vertices, genus 0 and thirty observed pcurves. Separate output mass and actual B-rep integration satisfy unchanged relative-volume and absolute centroid/boundary/pcurve/D1/normal budgets of 1e-9. Maximum relative volume error is 2.303e-16 and centroid error is 1.422e-14 mm. This is finite native evidence, not an inertia, arbitrary-outline, concave-polygon, Polygon-Revolve or all-75-kinds certificate. The immediate invalid-input capture retained the previous frame but sampled the inspector before it settled from Ready. A separate public UI observation waits for Error, retains the visible finite-coordinate alert and previous frame, and submits no extra native request. Its two Ready states are antecedents only: it adds zero physical captures, oracles, reuses or consumer bindings. Its first self-pin/private-tmp alias preflight stopped before any browser or output; a corrected expected-hash config preserved the code and original evidence. The primary integrated flow passed on its first execution. D504 qualified24 actual Markdown examples against its then-current API. D509 preserves those24 fence bodies and adds6, for30 actual fences across26pages. All30 actual fences are inputs to a separate fresh whole-program docs check, seven navigation tests, site check/build and26desktop-route preview; results are recorded in their canonical receipts. The current19 logical elements are6operations,5profile producers,2segment descriptors and6structural elements. The75-kind table is source inventory, not completion. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. D509 selected physical scope: The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. --- # @barocss/physics Physics advances an admitted numerical model from initial state and applied loads. The caller supplies the clock and displays each accepted state. The rigid world uses spheres, boxes and capsules. It does not use the exact CAD Surface as its collision shape. The common World supports [continuous primitive rotation](./profiles-and-lifecycle#isolated-noncubic-rotor) within its input and numerical limits. Dynamic noncubic boxes use their COM inertia, not constant world angular velocity. Contact, CCD and joint limits remain separate. A CAD proxy conversion does not certify its physical accuracy. This guide describes the workspace package. Local implementation and numerical evidence do not establish active CAD adoption, publication, hardware validation or manufacturing acceptance. Existing HOLD and historical NO_GO decisions remain in force. See [Physics verification](/reference/physics-verification). For CAD, GPU and Viewer host ownership, see [host integration](./host-integration). ## Current contact verification The current contact coherence implementation passes the original two-cube and three-cube512-step numerical campaigns in Source and actual compiled World, with unchanged tolerances. Its extended three-cube campaign still fails at866: lateral error1.0037318971762749e-10m exceeds1e-10m. The library is not complete. New-provider full desktop HiDPI remains unrun; the gallery and earlier Viewer results below belong to their recorded providers. See the [roadmap evidence](/physics-evidence/api-roadmap.txt). All first failures and Studio/manufacturing/equipment HOLDs remain. No deployment. ## Run the local sample gallery The repository gallery has six independently checked finite examples: projectile, elastic box, sphere sliding/rolling, one sphere CCD event, principal anisotropic spin before contact, and two-cube floor support. Select a case, then use Step or Run. Reset restores the authored initial model. Worker owns the sole World; Viewer receives accepted poses. The desktop HiDPI tests compare complete Native states and commands as well as actual GPU pixel changes. With workspace dependencies present and Physics already built, run from the repository root: ```sh node examples/physics-sample-gallery-2276/dev.mjs ``` If `packages/barocss-physics/dist/index.js` is absent, first run `pnpm --filter @barocss/physics build:library`. The preview uses that compiled package only; it does not install dependencies or build Physics automatically. Open the loopback address printed by the server. Numerical qualification uses a separate authenticated verification entry, not saved answers as animation. This is a local library and Viewer host. The three-cube long horizon remains NO_GO. It does not qualify arbitrary CAD contact, mechanisms, physical fluid/cloth coupling, Studio or real equipment. Existing HOLDs remain. ## Choose the owning API | Need | Owning entry or API | Scope | | --- | --- | --- | | Rigid forward dynamics | `createPhysicsWorld` from `@barocss/physics` | Fixed-step primitive bodies, contacts, bounded joints and queries. Choose an admitted profile. | | One planar pendulum | Independent `examples/physics-planar-pendulum-reference/pendulum.ts` | Local one-coordinate ODE, separate from the rigid world and its joint solver. | | Static-box capsule sweep | `createUprightCapsuleQuery` from the root | Geometric query; no dynamic body or hidden clock. | | Upright capsule movement | `createUprightCapsuleController` from the root | Fixed upright capsule and immutable bounded box scene. No general character dynamics. | | CAD proxy admission and display mapping | `admitCadSurfaceProxy`, `assertCadProxyCurrent`, `cadProxyPose` from `@barocss/physics/cad-proxy` | Source-bound control-net sphere or box approximation. | | Accepted command-log replay | `createPhysicsRecorder`, `restorePhysicsRecording` from `@barocss/physics/replay` | Attach at step0; bounded indexed recording; no arbitrary state loading. | | Visual water | Root `createPhysicsWorld(model, options)` | Fixed 256-particle basin; visual settings, no calibrated fluid material. | | Visual sheet | Root `createPhysicsWorld(model, options)` | Fixed 289-vertex pinned sheet and static sphere. | | CAD obstacle in visual water | `admitCadFluidStaticData` data adapter, then root World | One static axis-aligned CAD box proxy in version 1 water. | ## Fixed cloth and fluid model data These visual profiles use the same World clock, guard and state contract. P5a private kernels passed their bounded two-step source/native gates. P5b public source and actual native runtime checks also pass for the named fixtures and horizons in [verification](/reference/physics-verification#p5-common-world-visual-profiles). Strict source/native consumers and the selected four-profile source example pass. Native host compilation keeps the missing rendering SDKs external; their implementation and product execution remain unverified. Site checks have separate receipts. [Download the inert model asset](/physics/model-data.mjs). It contains explicit public PhysicsModel data, not another World factory. Copy it into your application and import it locally. The repository sample uses that same asset. ```js import assert from 'node:assert/strict'; import { createPhysicsWorld } from '@barocss/physics'; import { createPhysicsRecorder } from '@barocss/physics/replay'; import { copyPhysicsModelPreset } from '../docs/public/physics/model-data.mjs'; ``` ```js function acceptVisualStep(profile) { const input=copyPhysicsModelPreset(profile),original=structuredClone(input.model); const world=createPhysicsWorld(input.model,input.options); try { const before=world.getState(); assert.throws(()=>createPhysicsRecorder(world),error=>error.code===(profile.startsWith('cloth')?'WORLD_LIMIT':'INVALID_SNAPSHOT')); assert.deepEqual(world.getState(),before); const submitted=input.model.cloths[0]?.initialPositionsM ?? input.model.fluids[0].initialPositionsM; submitted[0][0]=999; assert.deepEqual(world.getModel(),original); const state=world.step([]),domain=state.cloths[0]??state.fluids[0]; return {stepIndex:state.stepIndex,timeSeconds:state.timeSeconds,positionsM:domain.positionsM}; } finally { world.dispose(); } } ``` Cloth topology, pins, physical vertex masses and ordered constraints remain in `getModel().cloths[0]`. Copied positions/velocities and diagnostics are in `getState().cloths[0]`; fluid data uses the corresponding `fluids[0]` entry. Do not pass time to step. Host reset means dispose and recreate a root World. Only empty commands are supported for these fixed visual profiles. Profiles are `cloth-pinned-sphere-visual-v1`, `fluid-basin-visual-v1`, `fluid-basin-xsph-visual-v1`, and `fluid-static-box-visual-v1`, all with `domain-fixed` broad phase and1/120s. The fluid smoothing radius is the original computed binary64 value `0.09000000000000001`, not literal `0.09`. These are visual settings, without calibrated fabric, viscosity, pressure or P6 coupling. Domain recording is explicitly refused. Cloth exceeds the unchanged128KiB model cap (`WORLD_LIMIT`); fluid profiles use `INVALID_SNAPSHOT` until actual wire/budget/restore closure is qualified. The failed attach changes no owner or accepted state. Preserve1MiB/512frames/4096commands; no JSON wire fallback. For CAD-derived static data, keep its admitted proxy and call the existing current-source check before each World step. SourceBinding alone cannot prove current source. No CAD Studio/Viewer UI or release action is implied here. Robot FK, IK, timed paths and prescribed-motion loads belong to [CAD Model](/packages/cad-model/). Read the [robot motion guide](/guide/robot-motion) and [Studio robot documentation](/studio/robots). A sampled robot path gives joint values over time. It does not predict free motion from force. Motion is a capability here; there is no new installable Motion package. Viewer applies display poses. ## Import and advance a free body Workspace imports resolve TypeScript source. Use the documentation sample runner or a TypeScript-capable bundler. Plain Node cannot resolve the source's internal `.js` imports to `.ts`. The package's `publishConfig` selects compiled `dist` entries for a release. A source sample does not verify that compiled package graph or a published package. ```js import { createPhysicsWorld, PhysicsError } from '@barocss/physics'; import { admitCadSurfaceProxy, cadProxyPose } from '@barocss/physics/cad-proxy'; ``` Use SI values at the Physics boundary. This fixture has a 2 kg sphere, an initial +X speed of 1 m/s, and no other body. Its radius is 0.1 m. Keep conversion code outside the step loop. ```js const dt = 1 / 120; const worldOptions = { profile: 'rigid-discrete-v1', fixedStepSeconds: dt, broadPhase: 'direct' }; const freeBody = () => ({ id: 'part:ball', kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 2, 0], orientationXYZW: [0, 0, 0, 1], velocityMps: [1, 0, 0], angularVelocityRadps: [0, 0, 0] }, }); const freeModel = (gravityMps2 = [0, -9.81, 0]) => ({ format: 'barocss-physics-model', version: 1, revision: 'docsFlight1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2, bodies: [freeBody()], colliders: [{ id: 'collider:ball', bodyId: 'part:ball', geometry: { kind: 'sphere', radiusM: 0.1 }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 } }], joints: [], cloths: [], fluids: [], sourceBindings: [], }); ``` Pass `createPhysicsWorld(model, options)` a complete model and an explicit profile. The model separates rigid bodies, colliders and source bindings. Each body has an `initial` transform and motion. Each collider has its own geometry, local transform, material and filter. The options declare the fixed step and broad phase. `getModel()` returns a copy of the admitted input; `getState()` returns the accepted state and its identity. `step(commands?)` advances that configured step and takes no time argument. The world uses a configured fixed step. The sample compares 12 free-flight steps with the discrete semi-implicit Euler solution. Its position oracle includes the integrator's time-discretization term; it is not the continuous expression `p = p0 + v0*t + g*t²/2`. ```js const world = createPhysicsWorld(freeModel(), worldOptions); try { const n = 12; for (let i = 0; i < n; i++) world.step(); const state = world.getState(); // Semi-implicit Euler: v_n = v_0 + n*g*dt; // p_n = p_0 + n*v_0*dt + g*dt²*n*(n+1)/2. vectorNear(state.bodies[0].velocityMps, [1, -9.81 * n * dt, 0]); vectorNear(state.bodies[0].positionM, [n * dt, 2 - 9.81 * dt ** 2 * n * (n + 1) / 2, 0]); near(state.timeSeconds, n * dt); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` The sample helper `vectorNear` compares each finite component with absolute tolerance `1e-12` unless a tolerance is supplied. It uses `node:assert/strict`. The source is in `apps/library-docs/samples/physics-docs.test.mjs` and runs with the site's `test:samples` command. A separate sample test compares the same physical time, 0.1 s, with the continuous ballistic solution at steps 1/120 and 1/240 s. Its position-error gate is 0.0041 m and its refinement-ratio gate is 1.99–2.01; velocity is checked within 1e-12 m/s. This distinguishes integrator agreement from physical-time accuracy. These examples supply no contact, browser or hardware result. ## Apply a force or an impulse `step(commands)` validates the commands before it advances a candidate. A `force` acts for this one step, so its velocity change is `forceN * dt / massKg`. An `impulse` changes velocity once by `impulseNs / massKg`. Supply a force on each step when you need a sustained load. ```js const world = createPhysicsWorld(freeModel([0, 0, 0]), worldOptions); try { const first = world.step([ { kind: 'impulse', bodyId: 'part:ball', impulseNs: [2, 0, 0] }, { kind: 'force', bodyId: 'part:ball', forceN: [0, 24, 0] }, ]); // Mass is 2 kg: J/m = 1 m/s; F*dt/m = 0.1 m/s. vectorNear(first.bodies[0].velocityMps, [2, 0.1, 0]); vectorNear(first.bodies[0].positionM, [2 * dt, 2 + 0.1 * dt, 0]); const second = world.step(); vectorNear(second.bodies[0].velocityMps, [2, 0.1, 0]); vectorNear(second.bodies[0].positionM, [4 * dt, 2 + 0.2 * dt, 0]); } finally { world.dispose(); } ``` The command order in the input array does not select the integration order. Physics applies linear impulse, then gravity and force, then position, followed by collision and joint response. Torque and angular impulse use world-frame vectors and the body's orientation-transformed inverse inertia. `kinematicTarget` supplies an absolute metre position for one kinematic-body step. A kinematic body holds its position and reports zero velocity when the next step has no target. ## Reduced planar pendulum The independent example reference `createPlanarPendulum` solves one angle about a fixed +Z pivot at the origin, with gravity along −Y. It admits no contact geometry, motor, damping or joint network. It uses velocity Verlet and explicit COM or pivot inertia. Read the [unit and frame contract](./units-and-frames). ```js // Independent reduced ODE reference, outside the public Physics package. import { createPlanarPendulum } from '../../../examples/physics-planar-pendulum-reference/pendulum.ts'; ``` ```js // Imported from examples/physics-planar-pendulum-reference/pendulum.ts, not the package root. const pendulum = createPlanarPendulum({ massKg: 1, comDistanceM: 0.5, inertia: { about: 'com', kgM2: 0.02 }, gravityMps2: 9.81, initialAngleRad: 0, initialAngularVelocityRadps: 0, fixedStepSeconds: dt, maxSteps: 2, }); const state = pendulum.step(dt); near(state.angleRad, 0); near(state.energyJ, 0); vectorNear(state.comPositionM, [0, -0.5, 0]); assert.throws(() => pendulum.step(dt / 2), hasCode('INVALID_STEP')); assert.deepEqual(pendulum.getState(), state); pendulum.dispose(); assert.throws(() => pendulum.getState(), hasCode('DISPOSED')); ``` This sample checks the zero-angle equilibrium and an expected refusal. The separate foundation experiment records period, matched-time state, convergence and energy-envelope checks; see [Physics verification](/reference/physics-verification). The pendulum interface has `getState()`, `step(dt)` and `dispose()`. Create a new instance for a new initial state. The reference is outside the public package root. It does not establish adoption by the active CAD checkout. The CAD-bound workflow that authors a hinge, applies loads and displays free motion remains a separate product gate. It does not activate the original eight-box or two-hinge experiments. ## Select a bounded profile before creating a world The `rigid-discrete-v1` profile admits 1–32 bodies and uses one contact point per pair. The opt-in `rigid-persistent-box-v1` profile admits at most four bodies. `rigid-large-v1` admits up to 64 bodies with required AABB broad phase and excludes joints, CCD and persistent boxes. These capacities are admission bounds. They are not interchangeable stack-stability guarantees. Use [profiles and lifecycle](./profiles-and-lifecycle) for the exact combinations, step limits, typed refusals, copied state and replay rules. Use [units and frames](./units-and-frames) before connecting a CAD or Robot host. Contact impulses and joint projection reactions are numerical solver outputs. They are not calibrated mechanical loads. Source owners for this guide are `packages/barocss-physics/package.json` and `src/{index,types,world,limits,cad-proxy,replay}.ts` in that package. The [verification page](/reference/physics-verification) keeps numerical evidence, geometry-only receipts, failed trajectories and product acceptance separate. ## Common World transition The current rigid root uses the [model/state/command/failure contract](/physics-evidence/p0-contract.txt): `createPhysicsWorld(model, options)`, copied `getModel()` and `getState()`, `step(commands?)`, tagged `query(input)` and `dispose()`. State includes model, configuration and provider digests. It identifies bodies and colliders separately. The old root config and root reduced-pendulum factory are removed. There is no compatibility engine. Cloth and fluid now use the common World. The removed `/cloth`, `/fluid` and `/fluid-cad` factories have no compatibility path. Each admitted visual model contains one domain and its fixed static colliders. Dynamic mixtures and force exchange with a moving rigid body remain unsupported. The replay service attaches to the common World through `createPhysicsRecorder(world)` at step0 and owns advancing commands while attached. Recorder disposal detaches it; the caller also disposes the World. CAD admission emits a body, collider and source binding; it never steps a world. The [roadmap](/physics-evidence/api-roadmap.txt) and [migration contract](/physics-evidence/p0-migration.txt) separate these later transitions from this rigid root change. This API change does not establish coupling or a new numerical, Viewer, hardware or product acceptance result. ## P1b local evidence status The rigid model/options cutover has selected source 8 / emitted 8 public checks,21 focused probes in each graph and a native local published-map runtime/declaration receipt (`examples/physics-world-p1b-2276/evidence/native-04`). These are checks of named providers, not a new numerical qualification. Five foundation entries pass 21 tests; documentation samples pass 174/174 and source mapping passes (`mapping-02`). Documentation build, site and scoped link checks pass. README examples compile and execute (`native-05`). Current host callsites bundle with the absent Viewer SDK explicitly external; full Viewer/DOM execution remains NOT_RUN. Independent reduced-ODE receipts remain reference results. P2_DONE_LOCALSELECTED has public source05/emitted05 checks11/11 each, test-only preparation-fault checks12/12 each, and native published-map/runtime/type checks. These historical receipts apply to their named providers; whole-engine acceptance remains NO_GO. At that checkpoint, final recording callers passed3 per graph and docs samples174/174. Current P5 results are separate in [verification](/reference/physics-verification#p5-common-world-visual-profiles). Existing HOLD and NO_GO decisions stay in force. ## Physics Lab on desktop The local Physics Lab uses the public World and recorder with the existing WebGPU Viewer. From the repository root, run: ```sh node examples/physics-lab/server.mjs ``` Open `http://127.0.0.1:52889`. Select box, sphere or capsule, change mass and initial spin, apply world torque or a one-time angular impulse, then save, restore and continue. The existing512-frame recording limit remains visible. The fixed0.1s comparison uses six shared times at60/120/240Hz against saved independent directed reference data. Live torque work is marked approximate; it is not the independent comparison result. Desktop browser checks cover actual controls, Viewer pose agreement, GPU pixels and failure retention. This sample does not resume Studio or qualify contact/stack/device behavior. --- # Physics units and frames Declare the unit system and coordinate frame before you connect a Robot, a CAD proxy and a Physics world. Convert each value once at its boundary. Do not convert Physics output again before you use it as input to the next Physics step. This page describes the current unreleased branch. See the [package overview](./) and [robot motion guide](/guide/robot-motion) for API ownership. The existing [Robot unit boundaries](/studio/robots#robot-unit-boundaries) remain the Robot facade contract. ## Conversion and frame contract | Quantity or boundary | Source convention | Physics or destination convention | Required conversion or declaration | | --- | --- | --- | --- | | Public Robot turn input/output | Degrees | Internal joint calculations use radians | `rad = deg * Math.PI / 180`. The facade owns this conversion; do not preconvert facade turn inputs. | | Public Robot slide input/output | mm | Internal Robot joint calculations also use mm | No conversion inside the Robot facade. Convert mm to m when passing length to Physics. | | Timed Robot joint limits | Joint units per second, squared second or cubed second | Public turn limits use degrees; internal turn math uses radians. Slide limits use mm. | Match the API layer and each joint's unit. A playback speed is a display setting. | | CAD/Viewer length and Robot MMGS length | mm | Physics length in m | Multiply by `1e-3`; return Physics display positions to mm with `1e3`. Thus 100 mm is 0.1 m. | | Robot facade MMGS mass | g | kg | Multiply by `1e-3`. | | Robot facade MMGS inertia | g·mm² | kg·m² | Multiply by `1e-9`. State the inertia origin and axis as well. | | Robot reported moment | N·mm | N·m | Multiply by `1e-3`. Force in N needs no scale change. | | Physics time, angles and loads | s, rad, N, N·m | Same SI units in Physics state and commands | Linear impulse is N·s; angular impulse is N·m·s. Do not treat either as a force or torque. | | World frame | Host declares right-handed XYZ and CAD orientation | Physics body positions and velocities use that declared world frame | There is no universal CAD up axis. These Physics examples use −Y gravity; Robot statics default to −Z. Rotate vectors explicitly when connecting these frames. | | Body rotation | Local-to-world quaternion | `[x, y, z, w]`, right-handed | The input and state field is `orientationXYZW`; identity is `[0,0,0,1]`. Rigid admission requires norm within `1e-6` of one and normalizes it. `cadProxyPose` requires norm within `1e-9`. | | Body axes and angular input | Shape dimensions and joint anchors are body-local | Torque and angular velocity are world-frame vectors | A capsule's segment uses its local Y axis. `axisWorld` is a world hinge axis. | | Contact convention | Pair IDs sorted as A, B | `normalAtoB` points from A to B; `pointM` is world metres | Positive normal impulse acts along the normal on B and against it on A. `tangentImpulseOnBNs` is the accumulated world-vector impulse on B, opposite on A. | | Independent pendulum reference inertia | `inertia: {about:'com'|'pivot', kgM2}` | Moment about the +Z axis through the named origin | For COM input, Physics adds `massKg * comDistanceM²` once. For pivot input, include this term yourself. | | CAD proxy display | Source points and `sourceCenterMM` in mm; body centre in m | Viewer translation in mm and unchanged XYZW orientation | `translation = 1000 * bodyPositionM - R * sourceCenterMM`. Rotate around the source centre, then place that centre at the body position. | For continuous primitive rotation, angular impulse acts instantaneously at step start. Torque is constant in world coordinates during that step, then expires. The independent reference checks `Lend=Lbefore+J+tau*dt` and integrated torque work, not final momentum alone. The old full-kick/free G1d PASS remains a historical discrete-map result; the current World integrates continuous torque. The rigid world's sphere inertia is `2*m*r²/5`; a dynamic sphere can declare `inertia:{kind:'sphere-isotropic',about:'com',frame:'body-local',kgM2}` to supply that scalar. Other admitted primitive bodies use explicit `inertia:{kind:'primitive-com',about:'com',frame:'body-local'}`. Its box inertia is the local COM diagonal `m/3 * [hy²+hz², hx²+hz², hx²+hy²]`. Capsule inertia integrates a uniform cylinder and two hemispheres. For radius `r`, half centreline length `h`, cylinder mass `mc=m*3h/(3h+2r)` and cap mass `ms=m-mc`, its local Y moment is `mc*r²/2 + 2*ms*r²/5`. The X/Z moments are `mc*(r²/4+h²/3) + ms*(2*r²/5+h²+3*h*r/4)`. These primitive models do not recover exact CAD mass properties. Supply the correct mass and model before interpreting the motion. For the independent pendulum example, `comDistanceM` is the pivot-to-COM distance. Its state angle is zero when the COM is below the origin on −Y. Positive angle turns about +Z, and `comPositionM = [L*sin(angle), -L*cos(angle), 0]`. The pivot equation is `I_pivot * angleAcceleration = -massKg * gravityMps2 * L * sin(angle)`. A COM moment and a pivot moment cannot be substituted without the parallel-axis term. ## Off-origin CAD proxy example The public adapter admits one selected native Surface from the exact source text and revision. It returns `body:RigidBody`, `collider:Collider` and `binding:SourceBinding`. Add these values to the model's `bodies`, `colliders` and `sourceBindings` arrays. The binding has source revision/digest, occurrence/model IDs, numerical entity references and approximation metadata. Exact source text and native bounds remain with the adapter. They do not enter the numerical World. The body's input position is `proxy.body.initial.positionM`; geometry is `proxy.collider.geometry`. The accepted body state uses `orientationXYZW`. `cadProxyPose` reads that state and returns the display pose's `rotation`, also XYZW. The fixture below has source bounds `[20,-30,40]` to `[120,10,100]` mm. Its centre is `[70,-10,70]` mm. The admitted box half extents are `[0.05,0.02,0.03]` m. A +0.1 m X offset places its body centre at `[0.17,-0.01,0.07]` m. ```js import { createPhysicsWorld, PhysicsError } from '@barocss/physics'; import { admitCadSurfaceProxy, cadProxyPose } from '@barocss/physics/cad-proxy'; ``` ```js const source = `@model units_fixture { version: 0; length-unit: mm; @surface #asymmetric_panel { type: nurbs; degree-u: 1; degree-v: 1; knots-u: [0,0,1,1]; knots-v: [0,0,1,1]; control-points: [[[20,-30,40],[20,-30,100]],[[120,10,40],[120,10,100]]]; weights: [[1,1],[1,1]]; } }`; ``` Turn the body +90° about Z while keeping that body centre. The literal quarter-turn matrix gives `R*[x,y,z] = [-y,x,z]`, so `R*sourceCenterMM = [10,70,70]` mm. The display translation is therefore `[170,-10,70] - [10,70,70] = [160,-80,0]` mm. A translation of `[100,0,0]` mm alone is correct only for this fixture's identity orientation. ```js const proxy = admitCadSurfaceProxy(source, { sourceVersion: 0, sourceRevision: 'unitsRev1', modelId: 'units_fixture', surfaceId: 'asymmetric_panel', kind: 'dynamic', proxy: 'box', massKg: 1, initialOffsetM: [0.1, 0, 0], }); vectorNear(proxy.sourceCenterMM, [70, -10, 70], 1e-6); assert.equal(proxy.collider.bodyId, proxy.body.id); assert.deepEqual(proxy.binding.entityIds, [proxy.body.id, proxy.collider.id]); assert.equal(proxy.binding.sourceRevision, 'unitsRev1'); assert.match(proxy.binding.sourceDigest, /^sha256:[0-9a-f]{64}$/); assert.equal(proxy.collider.geometry.kind, 'box'); vectorNear(proxy.collider.geometry.halfExtentsM, [0.05, 0.02, 0.03], 1e-9); vectorNear(proxy.body.initial.positionM, [0.17, -0.01, 0.07], 1e-9); const body = { id: proxy.bodyId, positionM: [...proxy.body.initial.positionM], orientationXYZW: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }; const pose = cadProxyPose(proxy, body, source, 'unitsRev1'); vectorNear(pose.translation, [160, -80, 0], 1e-6); // Independent +90° Z matrix: (x,y,z) -> (-y,x,z). const original = [[20, -30, 40], [20, -30, 100], [120, 10, 40], [120, 10, 100]]; const expected = [[190, -60, 40], [190, -60, 100], [150, 40, 40], [150, 40, 100]]; original.forEach(([x, y, z], i) => { const displayed = [-y + pose.translation[0], x + pose.translation[1], z + pose.translation[2]]; vectorNear(displayed, expected[i], 1e-6); vectorNear([displayed[1] + 80, 160 - displayed[0], displayed[2]], original[i], 1e-6); }); ``` The four expected display points are literal coordinates. The sample uses the quarter-turn matrix and an inverse transform rather than the adapter's quaternion helper to calculate its oracle. It compares admission lengths at `1e-9` m and display/inverse coordinates at `1e-6` mm. The source centre maps to the body centre `[170,-10,70]` mm under the same transform. The returned pose is a display transform of the original Surface. It is not a replacement collision mesh. A box proxy uses the Surface control-net AABB with minimum half extent; a sphere encloses that AABB. Keep the returned `lossLabel` with the simulation record. These source-adapter checks do not establish a compiled CAD consumer, a Viewer frame or exact Surface collision. ## Keep the source identity with the pose `assertCadProxyCurrent(proxy, currentSource, currentRevision)` and `cadProxyPose(...)` compare the complete source string and the caller revision. A changed string with an unchanged revision still gives `STALE_SOURCE`. A changed revision with the original string also gives `STALE_SOURCE`. An unknown or malformed binding is not permission to display a guessed pose. Keep the last accepted world state and frame after refusal. Re-admit the selected Surface explicitly when the source changes, then let the host replace the world and display binding. Do not silently reuse an old centre or apply the scale conversion twice. The documentation sample checks both stale cases and reuse of the original valid binding without changing retained input. For the numerical and product evidence boundaries, see [Physics verification](/reference/physics-verification). For command timing and state retention, see [profiles and lifecycle](./profiles-and-lifecycle). --- # Physics profiles and lifecycle Choose the numerical profile before creating a world. A larger body-count limit does not enable all smaller-profile features. Admission limits describe allowed inputs; numerical evidence covers the named cases only. This page describes the current unreleased branch, without a publication or active CAD adoption claim. Start with the [package overview](./) and [unit contract](./units-and-frames). ## Rigid world profiles All rigid-world profiles use `createPhysicsWorld(model, options)` from `@barocss/physics`. Unless a narrower profile fixes the step, `fixedStepSeconds` is in `[1/240, 1/30]` s. `step(commands?)` uses the configured value and takes no time argument. The limit is 3600 accepted steps. At least one dynamic body is required. | Selection | Capacity and combinations | Numerical scope and evidence route | | --- | --- | --- | | `profile:'rigid-discrete-v1'` | 1–32 spheres, oriented boxes or capsules; optional `broadPhase:'aabb'` | One contact point per pair and eight solver passes. Primitive contacts are not exact CAD collision. See [verification](/reference/physics-verification). | | `profile:'rigid-persistent-box-v1'` | At most four bodies; no `large-v1` or box-pair CCD | Awake, unfiltered dynamic/static boxes with zero restitution/friction and no joints/sensors/CCD use one global normal and all-pair position solve, with `broadPhase:'direct'` required and no failure fallback. Other material/role combinations retain their bounded manifold/contact laws. Minimum material restitution applies above the strict 0.5 m/s closing-speed switch. Selected centered and offset fixtures do not qualify arbitrary stacks. | | `profile:'rigid-stationary-cube-stack-v1'` | Exactly eight1kg half0.25m cubes and the original static floor;1200steps; direct broad phase, dt1/120, g=[0,-9.81,0], yaw-only poses, zero motion, original materials and empty commands | Exact32-point stationary witness; no fallback. Original three equilibrium scenes pass independent1200-step checks, public Source/compiled paths and actual desktop body-word parity. Unsupported contact chains refuse. This maintains equilibrium; falling, bounce, frictional settling and collapse are outside this profile. | | `profile:'rigid-large-v1'` | 1–64 bodies; requires `broadPhase:'aabb'`; requires an empty `joints` array; excludes CCD and persistent-box contact | Fixed collision filters and contact-island sleep. The named 63-sphere floor probe is a capacity case, not a general 64-body stack certificate. | | Anchored fixed or hinge joints | At most eight records. Each static/kinematic A connects to a uniquely jointed dynamic B | Body-local initial anchors must coincide within `1e-6` m. A hinge uses unit `axisWorld` and limits within ±π/2 that include zero. Connected bodies do not collide. | | One dynamic fixed joint | Exactly two dynamic spheres, no other bodies or joints | Inverse mass/inertia distribute corrections. The recorded equal-mass impulse fixture does not qualify general joint networks. | | One concentric dynamic hinge | Exactly two dynamic spheres at the same centre; zero gravity, zero initial motion, identity orientation, zero local anchors | Planar angular commands along the hinge axis only. An optional motor drives relative B/A speed with equal and opposite impulses. | | One offset dynamic hinge | Exactly two 1 kg spheres of radius 0.1 m; centres at ±0.1 m on X; opposing 0.1 m local X anchors | Fixed +Z hinge, limits `[-0.8,0.8]`, zero gravity and 1/120 s step. Motor target 0.5 rad/s, impulse cap 0.0001 N·m·s and reaction cap 0.01 N·m·s. This is one fixture. | | Two disjoint dynamic hinges | Exactly four 1 kg spheres of radius 0.1 m, forming the offset pair at Z=0 and Z=1 m | `rigid-discrete-v1`, direct broad phase, zero gravity, exact identity initial quaternions, zero initial motion, restitution 0, friction 1/0.7. Both hinges use the offset limits/motor above. Only empty commands; cross-component contact refuses. See the bounded evidence below. | | Sphere/static-box CCD | One CCD dynamic sphere and 1–8 static nonsensor oriented boxes; no joints or other bodies | Euclidean rounded-box sweep with selected independent face/edge/vertex/grazing evidence. Initial touch/overlap remains discrete-owned; arbitrary numerical scales and rotating fixtures are not qualified. | | Dynamic-sphere-pair CCD | Exactly two nonsensor dynamic spheres, exactly one with `ccd:true`; zero gravity, no joints | Exact represented endpoint/radius predicates with finite independent head-on/grazing/miss/initial/endpoint evidence. Both 5e-10 m inward biases remain. Extreme output accuracy and remaining-time integration are separate. `colliderId` denotes the other dynamic sphere's collider. | | Axis-aligned-box-pair CCD | One CCD dynamic box and one static nonsensor box, both axis-aligned; no joints or persistent boxes | Both signs of the identity quaternion are admitted with the same orientation/angular thresholds. Finite centered face-event boundaries have separate numerical and desktop proof. Nonzero angular commands refuse. Contact-induced rotation refuses the candidate. General rotation and tied-axis/corner events remain unqualified. | CCD stops at the earliest admitted hit with a `1e-9` m inward offset. It does not integrate the remaining fraction of that step. Initial overlap/touch uses the discrete path. Capsule CCD, general oriented-box CCD and arbitrary moving-body networks are outside these profiles. An anchored hinge motor uses `motor:{targetSpeedRadps,maxImpulseNms,maxReactionNms}`. Target speed is within ±2 rad/s. Its positive motor impulse cap is at most 0.05 N·m·s and its positive reaction cap is at most 1 N·m·s. It stops pushing outward at a hinge limit. Exceeding the reaction cap gives `NUMERIC_LIMIT`; it is not a material break-strength model. The offset profile fixes narrower values. Discrete static friction now solves both tangent constraints. Centered anisotropic cuboid impacts and original sphere/static-box branch inputs have separate numerical and desktop proof. The persistent manifold friction solver has its own cache/iteration law and is not qualified by those discrete results. General off-center normal/tangent coupling remains unqualified. The public persistent-box limit remains four bodies. The separate stationary cube profile uses the sole common World API and qualifies only the named equilibrium cases. It does not extend moving persistent-box dynamics. The disjoint-hinge profile has a separate qualification; it does not admit connected two-link mechanisms. Keep historical NO_GO results and unresolved causes alongside later bounded results in [Physics verification](/reference/physics-verification). The changing-normal persistent friction qualification currently has a public NO_GO: its accepted aggregate tangent is not in the reported normal plane, and the accepted paired contact witness fails independent native geometry. Existing centered impact and support results remain bounded proofs. No general tilted contact, contact-cache accuracy or stable-stack claim follows from admission. ### Two cubes and a floor The zero-friction island shares the common World, clock and recorder. Supply only initial conditions and commands. Render the accepted body state after a step. The renderer does not solve contacts or advance time. ```js const initial = positionM => ({ positionM, orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] }); const cube = (id, y) => ({ id, kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: initial([0, y, 0]) }); const model = { format: 'barocss-physics-model', version: 1, revision: 'docsCoupledCubes1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2: [0, -9.81, 0], bodies: [cube('lower', 0.5), cube('upper', 1.75), { id: 'floor', kind: 'static', initial: { positionM: [0, -0.5, 0], orientationXYZW: [0, 0, 0, 1] } }], colliders: ['lower', 'upper', 'floor'].map(bodyId => ({ id: `hull:${bodyId}`, bodyId, geometry: { kind: 'box', halfExtentsM: bodyId === 'floor' ? [2, 0.5, 2] : [0.5, 0.5, 0.5] }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 }, })), joints: [], cloths: [], fluids: [], sourceBindings: [], }; const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' }; ``` ```js const world = createPhysicsWorld(model, options); try { for (let i = 0; i < 32; i++) world.step([]); const state = world.getState(); // Render state.bodies; rendering does not advance the World. assert.equal(state.stepIndex, 32); assert.equal(state.timeSeconds, 32 / 120); assert.equal(state.contacts.length, 2); for (const [id, height] of [['lower', 0.5], ['upper', 1.5]]) { const body = state.bodies.find(value => value.id === id); assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10); assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10); } } finally { world.dispose(); } ``` This executable example covers two aligned2kg cubes, a prescribed static floor, gravity−9.81m/s², zero restitution/friction and a1/120s step. The32/256-step Source and actual compiled World checks pass the unchanged independent global projection and1e-12m representative-geometry gates. The original step27 failure is preserved. Actual restore/continuation, failure recovery and same-Native desktop rendering also pass, with separate receipts in [Physics verification](/reference/physics-verification). Admission alone does not qualify arbitrary mass ratios, tilted boxes, friction, simultaneous elastic impact or moving eight-body stacks. The island prepares every body's tensor. Its historical rotated-anisotropic precontact refusal is preserved. The later symmetric tensor construction passes the bounded precontact cases below; this does not qualify general tilted contact. The isolated rotor example further below uses `rigid-discrete-v1` and has separate G1 evidence. The same World also passes the aligned three-cube/floor case within the existing four-body cap. Lower and middle supports start at step1; the falling top joins the chain at27. Source/compiled256-step results pass an independent3DOF global reference and actual same-Native desktop state/word/pixel checks. This extends the stated equal2kg, zero-friction/restitution120Hz family only. ```js const chain = structuredClone(model); chain.revision = 'docsThreeCubes1'; chain.bodies.find(body => body.id === 'upper').initial.positionM[1] = 2.75; chain.bodies.push(cube('middle', 1.5)); chain.colliders.push({ ...structuredClone(chain.colliders[0]), id: 'hull:middle', bodyId: 'middle' }); const world = createPhysicsWorld(chain, options); try { for (let i = 0; i < 32; i++) world.step([]); const state = world.getState(); assert.equal(state.stepIndex, 32); assert.equal(state.contacts.length, 3); for (const [id, height] of [['lower', 0.5], ['middle', 1.5], ['upper', 2.5]]) { const body = state.bodies.find(value => value.id === id); assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10); assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10); } } finally { world.dispose(); } ``` The numerical case has0 restore calls; earlier two-cube recorder restoration is separate evidence. General four-body topology and moving8 remain unqualified. ### Rotated noncubic box before contact The same `rigid-persistent-box-v1` World now advances the original rotated 2 kg box without its old precontact tensor-symmetry refusal. Primitive COM, direct broad phase and existing limits remain. This executable example runs a single noncubic box for 12 contact-free steps: ```js const model = orientationXYZW => ({ format: 'barocss-physics-model', version: 1, revision: 'docsAnisotropic1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2: [0, -9.81, 0], bodies: [{ id: 'box', kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 5, 0], orientationXYZW, velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } }], colliders: [{ id: 'boxHull', bodyId: 'box', geometry: { kind: 'box', halfExtentsM: [0.25, 0.5, 0.75] }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 } }], joints: [], cloths: [], fluids: [], sourceBindings: [], }); const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' }; ``` A world-frame angular impulse acts once. The example maps body X to world Y and checks the analytic principal-axis speed of 3/13 rad/s: ```js const world = createPhysicsWorld(model([0, 0, Math.SQRT1_2, Math.SQRT1_2]), options); try { world.step([{ kind: 'angularImpulse', bodyId: 'box', angularImpulseNms: [0, 1 / 8, 0] }]); for (let n = 1; n < 12; n++) world.step([]); const state = world.getState(), body = state.bodies[0]; // Body X is world Y in this initial pose. I_x = 13/24 kg·m². assert.ok(Math.abs(body.angularVelocityRadps[1] - 3 / 13) <= 1e-10); assert.equal(state.stepIndex, 12); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` Separate Source/actual compiled verification uses a lower cube and floor as well: 64-step natural and principal-spin cases, both at three matched-time step sizes, rollback/restore and actual desktop state-word/GPU checks pass. Upper clearance stays positive. This proves precontact motion and selected lower-floor support, not anisotropic impact, general contact or friction. Continuous gravity position error at 64/120 s is 0.0218 m; dt refinement confirms first-order kick-drift. See [verification](/reference/physics-verification#rotated-anisotropic-precontact-repair). ### Isolated noncubic rotor The common World accepts primitive-COM noncubic boxes within the existing mass, dimension, pose and fixed-step ranges. There is no literal rotor whitelist or one-step horizon. Sphere, cube and capsule inertia use the same angular flow; capsules now use uniform-volume cylinder and hemisphere moments about their COM. Existing contact, joint and CCD admission limits remain separate. Use `freeModel()` and `worldOptions` from the [overview](./) with this example. Its mass, half extents and loads are sample values, not required constants: ```js const isolatedRotorModel = () => ({ ...freeModel([0, 0, 0]), revision: 'docsRotor1', bodies: [{ id: 'rotor', kind: 'dynamic', massKg: 1, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [1, 1, 1] } }], colliders: [{ ...freeModel().colliders[0], id: 'rotorHull', bodyId: 'rotor', geometry: { kind: 'box', halfExtentsM: [0.1, 0.2, 0.3] } }], }); ``` J acts once at step start. World-frame torque acts continuously during that step and expires. The next call advances the same World and configured clock: ```js const world = createPhysicsWorld(isolatedRotorModel(), worldOptions); try { const accepted = world.step([ { kind: 'angularImpulse', bodyId: 'rotor', angularImpulseNms: [1 / 1024, -1 / 2048, 1 / 4096] }, { kind: 'torque', bodyId: 'rotor', torqueNm: [1 / 128, -1 / 256, 1 / 512] }, ]); assert.equal(accepted.stepIndex, 1); const continued = world.step(); assert.equal(continued.stepIndex, 2); near(continued.timeSeconds, 2 * dt); assert.notDeepEqual(continued.bodies[0].orientationXYZW, accepted.bodies[0].orientationXYZW); near(continued.bodies[0].orientationXYZW.reduce((sum, x) => sum + x * x, 0), 1); assert.ok(continued.bodies[0].angularVelocityRadps.every(Number.isFinite)); assert.deepEqual(world.getState(), continued); } finally { world.dispose(); } ``` The free solver uses eighth-order geometric composition. Constant-torque integration uses eighth-order modified-midpoint extrapolation. A priori subdivisions are capped at64; finite-arithmetic, movement or conditioning failures return `NUMERIC_LIMIT` without committing state or recording. This cap is not a change to contact iterations or physical tolerances. See [Physics verification](/reference/physics-verification#g1-general-continuous-rotation) for the measured profiles and preserved initial failures. Long-time conservation does not prove long-time phase accuracy. No integrator option or compatibility World exists. ### Use the selected disjoint-hinge model Both directed pairs have local anchors `[0.1,0,0]` and `[-0.1,0,0]` m. The centres are `[-0.1,0,0]`, `[0.1,0,0]`, `[-0.1,0,1]` and `[0.1,0,1]` m. Initial quaternions must be exactly `[+0,+0,+0,1]`; normalization aliases and negative-zero quaternion components refuse. No body is shared between joints. The existing common World owns both pairs and one accepted clock. ```js const disjointHingeModel = () => { const model = freeModel([0, 0, 0]); model.revision = 'docsHinge2'; const ids = ['pairA0', 'pairB0', 'pairA1', 'pairB1']; model.bodies = ids.map((id, index) => ({ ...freeBody(), id, massKg: 1, initial: { positionM: [index % 2 === 0 ? -0.1 : 0.1, 0, Math.floor(index / 2)], orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } })); model.colliders = ids.map(id => ({ ...freeModel().colliders[0], id: `collider:${id}`, bodyId: id, material: { restitution: 0, friction: { static: 1, dynamic: 0.7 } } })); model.joints = [0, 1].map(index => ({ id: `hinge${index}`, kind: 'hinge', bodyAId: ids[index * 2], bodyBId: ids[index * 2 + 1], anchorALocalM: [0.1, 0, 0], anchorBLocalM: [-0.1, 0, 0], axisWorld: [0, 0, 1], limitRad: [-0.8, 0.8], motor: { targetSpeedRadps: 0.5, maxImpulseNms: 0.0001, maxReactionNms: 0.01 } })); return model; }; ``` Use the imports and `worldOptions` from the [overview](./). The helper above also uses its `freeModel()` and `freeBody()` data builders. Empty arrays are the supported command input for this profile. Nonempty angular commands along the axis also refuse. Do not substitute a prescribed motion path. ```js const world = createPhysicsWorld(disjointHingeModel(), worldOptions); try { world.step([]); const state = world.step([]); assert.equal(state.stepIndex, 2); assert.equal(state.timeSeconds, 2 / 120); assert.equal(state.joints.length, 2); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` This short example verifies API use. The separate original 1,200-step campaign and its precise source/emitted boundaries are in [verification](/reference/physics-verification#p3-disjoint-hinge-qualification). It does not establish arbitrary joint networks, contact coupling, a convergence order, cross-runtime equality or measured machine accuracy. ### Rigid input bounds The model declares all entity arrays, including empty `joints`, `cloths`, `fluids` and `sourceBindings`. Rigid profiles refuse nonempty cloth/fluid arrays. Each rigid body has exactly one collider with an identity local transform. `ccd`, sensor flags, geometry, material and collision filters belong to the collider. The body declares mass/inertia for dynamics and its explicit `initial` state. State carries numerical motion; read copied `getModel()` data for initial conditions, collider geometry and source bindings. Body IDs are unique ASCII identifiers with at most 64 characters and a starting letter. Each position component is within ±10000 m. Velocity components are within ±1000 m/s and gravity components within ±1000 m/s². Mass is `1e-6`–`1e6` kg. Sphere radius, box half extents and capsule length parameters are `1e-4`–1000 m. Restitution is 0–1. Explicit material friction satisfies `0 <= dynamic <= static <= 2`; supply both coefficients, including zero values. A step accepts at most 64 dense plain-object commands. Each body can receive one command of each applicable kind. Force and torque components are bounded by ±`1e6` N or N·m; linear and angular impulse components by ±`1e5` N·s or N·m·s. Angular velocity components are within ±1000 rad/s. A candidate refuses movement or measured penetration above 10 m, or angular displacement above 10 rad per step. Limits are numerical guards, not recommended physical operating conditions. ## Visual domains, recording and independent helpers Cloth and fluid use the root common World. They share its fixed clock, candidate commit and idempotent disposal. Their selected profiles admit one domain plus fixed static colliders. They refuse dynamic mixtures and do not exchange forces with moving rigid bodies or with each other. The old domain factory subpaths are removed. CAD data admission is not another simulation owner. | Entry and selection | Step and capacity | Boundary | | --- | --- | --- | | Root World, `fluid-basin-visual-v1` or `fluid-basin-xsph-visual-v1` | Exactly256 particles in a0.7 ×1.3 ×0.5m basin;1/120s;3600-step admission cap | Qualified horizon720steps. XSPH coefficient0.15 is a visual parameter. No calibrated viscosity, emitters or moving obstacles. | | Root World, `cloth-pinned-sphere-visual-v1` | Fixed289vertices and512triangles;1/120s;240host steps | Two pinned corners and one static sphere. No fabric calibration, self-collision, tearing or arbitrary mesh admission. | | `admitCadFluidStaticData`, then root `fluid-static-box-visual-v1` | Version1 water and one static axis-aligned CAD box proxy | Qualified horizon240steps. Caller checks exact current source/revision before stepping. No XSPH combination or moving CAD obstacle. | | `/replay` |512frames,4096total commands,128KiB canonical model and1MiB binary recording including8-byte magic | Bounded accepted rigid command log. Cloth attach refuses `WORLD_LIMIT`; fluid attach refuses `INVALID_SNAPSHOT`. No domain restore is qualified. | | Independent example `createPlanarPendulum`, outside the public root | Step1e-6–1/30s; dt × natural frequency ≤0.05;1–1000000steps | One reduced angle, velocity Verlet, no contacts, motors or damping. Pivot+Z, gravity−Y. | | Root `createUprightCapsuleQuery`, `upright-capsule-box-v1` |0–32immutable static boxes; query displacement norm≤2m | Fixed upright capsule: radius0.15m, half segment0.35m. Scene box centres±10m, half extents0.0001–5m; query centres±5m. Query does not advance a World. | | Root `createUprightCapsuleController`, `upright-capsule-controller-v1` | Exactly1/120s; at most240steps | Bounded capsule query,−Y gravity,0.002m skin,0.1m step limit and10°walkable slope. No general dynamic obstacles. | See the [fixed visual model example](./#fixed-cloth-and-fluid-model-data) and [verification](/reference/physics-verification#p5-common-world-visual-profiles). An admission cap is separate from the executed horizon. ## Own the clock and retain accepted state `PhysicsWorld.step(commands?)` advances one configured step. It does not read wall time or change the step size to match display refresh. The host can accumulate elapsed display time and request whole fixed steps, subject to its own work budget. A dropped display frame does not authorize a larger Physics step. `getState()` and successful `step()` return independent copies, including nested body vectors, contacts, events, joints, CCD hits and pair counts. Editing returned arrays does not edit the world. The world commits only an accepted candidate. An invalid command or numerical candidate leaves the last accepted state available. Do not hide refusal with an automatic retry or a changed gate. ```js const world = createPhysicsWorld(freeModel([0, 0, 0]), worldOptions); const accepted = world.step(); assert.throws(() => world.step(dt / 2), hasCode('INVALID_COMMAND')); assert.deepEqual(world.getState(), accepted); accepted.bodies[0].positionM[0] = 999; accepted.bodies[0].orientationXYZW[3] = 0; const copied = world.getState(); const modelCopy = world.getModel(); modelCopy.bodies[0].initial.positionM[1] = 999; near(world.getModel().bodies[0].initial.positionM[1], 2); const hit = world.query({ kind: 'overlap-sphere', centerM: copied.bodies[0].positionM, radiusM: 0.01, includeSensors: false }); assert.deepEqual(hit, { kind: 'overlap-sphere', colliderIds: ['collider:ball'] }); assert.throws(() => world.query({ kind: 'overlap-sphere', centerM: [NaN, 0, 0], radiusM: 0.01, includeSensors: false }), hasCode('INVALID_QUERY')); assert.deepEqual(world.getState(), copied); near(copied.bodies[0].positionM[0], dt); assert.deepEqual(copied.bodies[0].orientationXYZW, [0, 0, 0, 1]); world.dispose(); world.dispose(); // Idempotent. assert.throws(() => world.getState(), hasCode('DISPOSED')); assert.throws(() => world.step(), hasCode('DISPOSED')); ``` This sample uses the imports, `dt`, `worldOptions` and `freeModel()` fixture shown on the [overview](./). Its `hasCode(code)` helper accepts only `error instanceof PhysicsError && error.code === code`. The test checks refusal after one accepted step, edits returned data, then checks the retained world. `dispose()` is idempotent. Later reads, queries and steps give `DISPOSED`. The rigid world has no public reset or arbitrary state setter. Create a new world for a new initial condition. ## Handle typed refusals | Code | Caller action | | --- | --- | | `INVALID_CONFIG` | Correct the input model or select a supported profile before creating another instance. | | `INVALID_STEP` | For numerical helpers and independent reference APIs that take `dt`, supply their configured step. A numeric argument to common World `step` gives `INVALID_COMMAND`. | | `INVALID_COMMAND` / `INVALID_QUERY` | Correct the command or query; do not alter accepted state to conceal the refusal. | | `WORLD_LIMIT` | The admitted step, frame or command budget is exhausted. Choose an explicit new session. | | `NUMERIC_LIMIT` | Stop advancing this model. Record the first failed input and the retained state before investigating. | | `STALE_SOURCE` | Re-admit the CAD source/revision explicitly before replacing the binding. | | `WORLD_OWNED` | Advance through the attached recorder; reads and queries remain available. | | `STALE_SNAPSHOT` | Model, source, configuration or provider identity differs. Restore only against the intended matching identity. | | `INVALID_SNAPSHOT` | Reject malformed, unsupported or damaged replay data. | | `INITIAL_OVERLAP` / `ITERATION_LIMIT` | Capsule-query refusal: initial penetration or unresolved bounded search. This is not a partial valid sweep. | | `DISPOSED` | Create a new instance. A disposed object cannot resume. | State has `identity`, tagged query results use collider IDs, and bodies report `orientationXYZW`. Contacts use `bodyAId`, `bodyBId`, `colliderAId`, `colliderBId`, `normalImpulseNs` and `tangentImpulseOnBNs`. Joint reactions use `linearImpulseOnBNs` and `angularImpulseOnBNms`. `PhysicsError.details` identifies the operation, phase, domain, entity IDs and last accepted step/time. Use `PhysicsError.code` for branching. Error messages supply context and are not a stable protocol. The root and its replay/CAD adapter entries share the error constructor within one installed package instance. Do not assume `instanceof` identity across versions, realms or separate source/compiled bundles. ## Restore a command log, not arbitrary state Attach `createPhysicsRecorder(world)` at step0, before any World step. The recorder supplies `step(commands?)`, `getState()`, copied `saveRecording()` and `dispose()`. The configured `dt` owns time; `step` takes no step-size argument. A direct or cached `world.step` call and a second attachment refuse with `WORLD_OWNED`. World reads and queries remain available. Recorder disposal detaches it without disposing the World. Dispose both objects when finished. World disposal invalidates its recorder. Disposal releases recording/options references; no garbage-collection timing or out-of-memory recovery guarantee follows. An advanced World cannot acquire a new recording history. `restorePhysicsRecording(recording,{model,options,providerDigest})` validates complete recording shape and bounds before expected model, configuration and provider identity. Source revisions are model `sourceBindings` data. Use the intended current World's `getState().identity.providerDigest` as the external expected provider digest. Restore reconstructs an isolated World, replays indexed accepted commands and compares final state at `1e-12` absolute/relative numeric tolerance. It returns `{world,recorder}` only on success. Dispose both objects. The command frame and log budgets are checked before candidate calculation. Final state, returned copy and complete bounded encoding are prepared before the nonthrowing shared physical/log commit. Changed identity gives `STALE_SNAPSHOT`; damaged data gives `INVALID_SNAPSHOT`. Persist with `serializePhysicsRecording(recording):Uint8Array` and read with `deserializePhysicsRecording(bytes)`. The wire format is ASCII `BCPHREC1` followed by bounded canonical typed encoding. It preserves binary64 number bits, including `-0`. The decoder refuses JSON, unknown tags, nonfinite numbers, truncated/trailing bytes and unsupported versions. Record keys use canonical ASCII order; arrays retain their order. There is no old-version migration, arbitrary body-state import or bitwise cross-platform trajectory promise. ```js import { createPhysicsRecorder, restorePhysicsRecording, serializePhysicsRecording, deserializePhysicsRecording } from '@barocss/physics/replay'; ``` ```js const model = freeModel([-0, 0, 0]); const world = createPhysicsWorld(model, worldOptions); const session = createPhysicsRecorder(world); const expected = { model, options: worldOptions, providerDigest: world.getState().identity.providerDigest }; let restored; try { session.step([{ kind: 'impulse', bodyId: 'part:ball', impulseNs: [2, 0, 0] }]); const recording = session.saveRecording(); const bytes = serializePhysicsRecording(recording); assert.equal(Buffer.from(bytes.subarray(0, 8)).toString('ascii'), 'BCPHREC1'); const decoded = deserializePhysicsRecording(bytes); assert.ok(Object.is(decoded.model.gravityMps2[0], -0)); restored = restorePhysicsRecording(decoded, expected); assert.deepEqual(restored.recorder.getState(), session.getState()); assert.deepEqual(restored.recorder.step(), session.step()); recording.frames[0].commands[0].impulseNs[0] = 999; near(session.saveRecording().frames[0].commands[0].impulseNs[0], 2); assert.throws(() => deserializePhysicsRecording(bytes.subarray(0, -1)), hasCode('INVALID_SNAPSHOT')); } finally { restored?.recorder.dispose(); restored?.world.dispose(); session.dispose(); world.dispose(); } ``` P2_DONE_LOCALSELECTED: public source05/emitted05 pass11/11 each; test-only preparation faults pass15/15 each across four step preparation points plus attach output preparation, each in three rigid profiles. Native03 passes staged published maps, strict positive/negative declarations, shared ownership registry, CAD release consumer and four README blocks. Ordinary probes and foundation checks pass21 per source/emitted graph; documentation samples pass174/174 in run03. Final recording callers pass3 per graph; documentation build/site/link receipts are docs-check/build/links-01. Historical P1b receipts apply only to their original providers. Whole-engine acceptance remains NO_GO. Keep a source-run receipt separate from a compiled-consumer receipt. Workspace aliases can resolve source even after a build. A compiled check must resolve each transitive package through its published entry map; the compiled root also needs sibling `dist/types.js`. See [Physics verification](/reference/physics-verification) for provenance and the accepted evidence stages. Neither replay equality nor a plausible animation validates contact loads, control hardware or manufacturing. --- # Connect CAD and Viewer Use one Physics World for one simulation. CAD, rendering and React do not own another numerical World. This page describes the current unreleased branch and the host boundary. CAD React is owned by a separate Work and is not inspected or changed here. This page does not establish CAD Studio integration. Existing Studio, manufacturing and equipment HOLDs stay. ## Data ownership | Layer | Owns | Sends to the next layer | | --- | --- | --- | | `@barocss/cad` | Native geometry and geometric queries | Stable geometry references, bounds and display tessellation | | `@barocss/cad-model/api` | Authored part definitions, IDs, units and available mass properties | A revision-bound model for an explicit Physics admission adapter | | Host admission adapter | Unit/frame conversion, supported collision approximation and body-to-part binding | A supported SI `PhysicsModel` and `WorldOptions` | | `@barocss/physics` | Accepted model/state, commands, fixed-step advancement and numerical failure | `PhysicsState`; optionally the existing recorder owns stepping | | Display adapter | Mapping accepted body IDs and poses to display objects | A Viewer motion frame or GPU transform data | | `@barocss/viewer` / `@barocss/gpu` | Camera, display resources, picking and drawing | Pixels and display interaction; no physics advancement | | React or Studio host | Lifecycle, user commands, selection and subscription | Commands to the sole simulation owner; display requests from accepted snapshots | Do not tessellate or rebuild CAD after every physics step. Keep the authored CAD model and reusable display meshes. Apply transient accepted poses to those meshes. A user command to commit a final pose to CAD would need its own document edit/undo contract; it is outside the current simulation work. The current CAD proxy entry is `@barocss/physics/cad-proxy`. `admitCadSurfaceProxy` admits a selected Source-v0 Surface as a bounded box or sphere approximation. `assertCadProxyCurrent` rejects a changed source or revision. These APIs do not provide exact B-rep collision or a general solid- mass/full-tensor import. CAD-model root exports no API; use the `/api` subpath. Generic COM offsets, principal axes, full tensors and collider-local offsets remain the G3 prerequisite before a general CAD part importer. ## Convert units and frames once CAD lengths use mm. The CAD-model mass API uses g and g·mm². Physics uses m, kg, s and radians. Convert length and mass by `1e-3`, inertia by `1e-9`. Return positions to mm only in the display adapter. Keep body-local dimensions and world-frame angular velocity, gravity, torque and impulses distinct. For an off-origin CAD proxy, use `cadProxyPose`; translation is not just the body centre in mm. It includes `-R(q) * sourceCenterMM`. See the independently checked [off-origin example](./units-and-frames#off-origin-cad-proxy-example). Viewer's `applyMotionFrame` and `applyGeometryMotionFrame` require an explicit `{basis:'part-xyz-matches-rhyup'}` agreement and use translation in mm with XYZW rotation. That flag does not perform a basis conversion. Choose and verify the host frame first. Changing the camera up vector alone does not convert model positions, rotations, gravity or inertia. The current contact examples use Y gravity. The earlier CAD consumer kept CAD XYZ and explicitly used Z gravity; that consumer is not proof of a general CAD-to-Viewer frame converter. For loaded primitive Surface packets, the existing Viewer call shape is: ```ts const pose = cadProxyPose(proxy, acceptedBody, source, revision); viewer.applyMotionFrame( { contextId: 'simulation', timeSeconds: acceptedState.timeSeconds, poses: [pose] }, [{ contextId: 'simulation', targetId: proxy.bodyId, ref: { modelId: proxy.modelId, surfaceId: proxy.surfaceId } }], { basis: 'part-xyz-matches-rhyup' }, ); ``` This excerpt shows the existing API boundary. The host must have loaded matching geometry, verified its basis and retained its binding. It is not a complete React component or an arbitrary CAD assembly adapter. The current primitive packet path admits at most four geometry entries. Viewer currently refuses overriding authored assembly poses. `examples/physics-lab/display.mjs` contains an actual accepted-state-to-Viewer implementation for its display proxies. ## Desktop display density `Viewer.resize(width,height)` takes backing-store device pixels. The host owns CSS layout and DPR. A fixed640×360 backing store stretched across a desktop canvas looks blurred even when the physics and pose tests pass. The contact sample uses the canvas's CSS content size times actual browser DPR, up to DPR2. It scales both axes together to retain the current public Viewer limits: at most4096 per axis and4194304 total pixels. It floors the final device pixel dimensions. Thus a large desktop may use a lower effective scale than2; this does not change numerical dt, state or solver tolerance. Resize and DPR changes must leave the accepted Physics state and clock unchanged. Actual native `Viewer.readPixels()` covers that backing store. The sample's 640×360 nearest-centre pixel sample is only a bounded test observer; it is not the display resolution or a second renderer. Native dimensions and byte counts must be checked separately. Desktop DPR1 and2, layout changes, real GPU pixels and state-word comparison belong to separate checks. Mobile is outside scope. ## Viewer and the current Studio viewport `@barocss/viewer` already exposes `applyMotionFrame` for loaded primitive Surface packets and `applyGeometryMotionFrame` for loaded primitive Surface/curve data. The common World can feed those APIs through an explicit accepted-pose adapter. Do not add another physics solver to Viewer or GPU. Viewer owns presentation; Physics owns the numerical state and commands. The current Studio does not use `@barocss/viewer`. Its `apps/cad-studio/src/viewport/gpuRenderer.ts` uses `@barocss/gpu/viewer` and has a host method `setInstanceTransforms`; `Viewport.tsx` supplies its `instanceTransforms` map. A future Studio adapter should target that existing host path. Adopting Physics does not require replacing the Studio renderer. `setInstanceTransforms` is a Studio host method, not a new public Physics/GPU API. Before Studio integration, define body-to-instance IDs, model revision, units, frame and absolute-versus-relative placement. Kinematic/FK preview and dynamics must not both write the same instance pose. Late Worker replies from an old revision must not replace the current display. Camera and picking must not step physics. No Studio source, dependency, build or screen test is changed here; its HOLD remains. CAD React belongs to another Work. It can later consume the same accepted-pose contract through its own lifecycle adapter. That does not create a second World or authorize changes to that Work in this task. ## Integrate in this order First qualify the selected numerical profile through the public World. Next verify a Viewer adapter with the same accepted states, independent transform checks and actual desktop GPU pixels. CAD React lifecycle work remains with its separate owner. A future Studio adapter should reuse the same pose contract with Studio's existing GPU viewport, only within an authorized integration scope. Existing Studio work stays on HOLD; this sequence does not resume its workers or change app dependencies. Keep kinematic playback separate from dynamics. CAD-model Robot/FK paths replay joint-space poses; they do not establish dynamic forces or contact accuracy. Exact CAD collision, arbitrary connected mechanisms, moving eight-body contact, real-equipment prediction and manufacturing approval remain outside the current qualified profile. See [verification](/reference/physics-verification) and [profiles and lifecycle](./profiles-and-lifecycle). --- # @barocss/gpu The studio's WebGPU viewer, and a small CSS-shaped scene and material language. It depends only on `@barocss/cad`. This package supplies the low-level canvas renderer. For the `Viewer` SDK class and its review-state API, see [`@barocss/viewer`](/packages/viewer/). - **Workspace use.** Source imports use TypeScript. The library build emits JavaScript and declarations. - **How the studio uses it.** The studio draws with this viewer when the browser has WebGPU. Its WebGL2 fallback is the studio's own renderer, not part of this package (see [WebGPU and WebGL2](#webgpu-and-webgl2)). - **In code.** `@barocss/gpu/api` describes a scene as an immutable object: a part's meshes, their materials, lights and a camera view. `show(viewer, scene)` puts it in the viewer below. See [Object API](/packages/api#scenes). ### Model meshes in a scene Pass a CAD part's or CAD Model assembly's `meshes()` to `scene().add()`. Use `{ lines: true }` to add its display edges. The meshes use the model's Z-up coordinates in mm. `Assembly.meshes()` includes the base and visible placed parts; it omits hidden instances. Its keys are `base/` or `/`. An `explode` value offsets placed meshes for display only; it does not change the assembly's placements or mates. `Scene.add()` returns a new Scene but shares the supplied geometry arrays. Treat those arrays as read-only. A model change does not update an existing Scene or Viewer automatically. Get `meshes()` from the updated part or assembly, build a new Scene with the desired settings, and call `show(viewer, newScene)` to display it. The show operation clears the Viewer before adding the new meshes and fitting the view. ## The viewer `@barocss/gpu/viewer` is one WebGPU renderer for a canvas. It: - owns one device and canvas context; - keeps geometry in long-lived buffers; - draws on demand, at most one frame per animation frame; - follows the canvas's size and pixel ratio; - replaces a lost device and uploads the scene again. ```js import { createViewer } from '@barocss/gpu/viewer'; const viewer = await createViewer(canvas, { background: { top: '#2e3035', bottom: '#18191b' }, grid: true }); const box = viewer.add({ positions, normals, indices, faces }, { material: { color: '#c0c4cc', roughness: 0.5 } }); viewer.add({ positions: edgeSegments, topology: 'lines' }, { material: { color: '#111111', unlit: true, lineWidth: 1.5 } }); viewer.lights = [{ kind: 'directional', direction: [-0.4, 0.6, -1], castShadow: true }]; viewer.environment = { ambientOcclusion: { strength: 1 } }; viewer.fit(); const hit = viewer.raycast(x, y); // the mesh, triangle, face, instance and point, on the CPU const gpuHit = await viewer.pick(x, y); // the same from the GPU's id and depth targets box.outline = '#e8c25a'; // a selection outline round the visible part ``` This example is the package README's. It needs a browser with WebGPU, so it isn't one of this site's samples. The package's own browser tests drive it in Chrome. - **Camera.** - Perspective, with an infinite far plane, or orthographic. - Reversed depth, and clip planes fitted to the scene. - `fit()`, and rays from the cursor. - Orbit, pan, and zoom to the point under the cursor; `controls: false` lets you drive the camera yourself. - **Materials.** - Metal–roughness, lit by directional, point and spot lights and a hemisphere ambient; or unlit. - Vertex colours, colour maps with mipmaps, transparency drawn back to front, shadow catchers. - Shader materials, below. - **Lines.** Screen-space width, segment ids, and `pickLine()`. - **The scene.** - Instancing (one draw for many copies) and frustum culling. - Directional, spot and point shadows within the [light limits below](#light-and-shadow-limits). - Ambient occlusion, a gradient or transparent background, and a ground grid. - Contact shadows: `environment.contactShadows: { length?, strength? }` darkens where the depth buffer blocks a short ray toward the first shadow caster among the first four directional lights, in the creases the shadow map is too coarse for. - Bloom: `environment.bloom: { strength?, threshold?, knee? }` adds a glow from pixels above a linear-light threshold before tone mapping. Defaults are strength 0.05, threshold 1 and a soft knee one quarter of the threshold. Set `bloom` to false, omit it, or set strength to 0 to turn it off. A half-resolution prefilter and a downsample/upsample chain spread the highlights; the targets are recreated on resize and released with the viewer. - 4× MSAA, exposure and ACES tone mapping in a linear half-float pipeline. - Clip planes and cap hatching for sections. ### PBR data maps Triangle materials accept `normalMap`, `roughnessMap` and `metallicMap` through the geometry's UVs, in raster rendering and progressive stills. Create these textures with `{ srgb: false }`: they hold linear data, not colour. This SDK example assumes an existing `viewer`, triangle `box`, matching `uvs` and RGBA pixel arrays: ```js const normalMap = viewer.createTexture({ width, height, data: normalPixels }, { srgb: false }); const packed = viewer.createTexture({ width, height, data: packedPixels }, { srgb: false }); box.geometry.setUVs(uvs); box.material = { normalMap, normalScale: [1, 1], roughnessMap: packed, roughness: 1, metallicMap: packed, metallic: 1, }; viewer.requestRender(); ``` Normal RGB encodes a tangent-space +Y normal. `normalScale` scales X/Y and defaults to `[1, 1]`; use a negative Y scale for the opposite convention. A missing or degenerate UV frame keeps the original surface normal. The roughness map's green channel and metallic map's blue channel multiply their material values, so one packed texture can serve both roles. Set a map to `null` to remove it. For a uniform RGBA8 data texture `[255, 128, 64, 255]` created with `{ srgb: false }`, the green and blue samples are `128/255` and `64/255`. With material roughness `0.8` and metallic `0.6`, the parameters become: | Parameter | Calculation | Approximate result | | --- | --- | --- | | Roughness | `0.8 × (128/255)` | `0.401569` | | Metallic | `0.6 × (64/255)` | `0.150588` | These are parameter calculations before lighting, not final pixel RGB values or captured API results. Byte `128` is `128/255`, not exactly `0.5`. Filtering can mix samples from a non-uniform texture. Data maps require live textures and triangle geometry. They cannot be combined with a scalar-field `Mesh.colorMap`. A data map that is not a live `ImageTexture` with `srgb: false` refuses with `TEXTURE_INVALID`. A `normalScale` without exactly two finite f32 numbers refuses with `MATERIAL_INVALID`, as do data maps on non-triangle geometry or in combination with a scalar-field colour map. Disposing an accepted map restores the raster material's unmapped value. An existing frozen still retains its own pixels and material snapshot; remove or replace disposed references before creating another still. ### Surface analysis shaders (Zebra, Draft and Curvature) The WebGPU viewer provides real-time surface continuity and manufacturability inspection shaders through `SurfaceAnalysisOptions` (`mode: 'none' | 'zebra' | 'draft' | 'curvature'`). When `mode` is `'none'` (the default), the standard PBR surface shader runs untouched. | Mode | Purpose | Options & Defaults | | --- | --- | --- | | `'zebra'` | View-space reflection stripes for G0/G1/G2 surface continuity inspection | `stripeCount` (`16`, clamped `1..128`), `axis` (`'horizontal' \| 'vertical' \| 'diagonal'`), `contrast` (`0.92`, `0..1`) | | `'draft'` | World-space mold pull-angle classification | `pullAxis` (`'x' \| 'y' \| 'z' \| '-x' \| '-y' \| '-z'`, default `'z'`), `draftAngle` (`3°`, clamped `0.1..45°`) | | `'curvature'` | Screen-space surface curvature heatmap | `curvatureScale` (`0.5` `1/world-unit`, clamped `0.01..100`) | ```js // Inspect fillet continuity with diagonal Zebra reflection stripes viewer.surfaceAnalysis = { mode: 'zebra', stripeCount: 24, axis: 'diagonal', contrast: 0.92 }; // Switch to mold draft-angle inspection along +Z with a 2° minimum threshold viewer.surfaceAnalysis = { mode: 'draft', pullAxis: 'z', draftAngle: 2 }; // Switch to curvature heatmap, or pass null / { mode: 'none' } to return to PBR viewer.surfaceAnalysis = { mode: 'curvature', curvatureScale: 0.8 }; ``` Unsupported mode or axis strings and non-finite numeric values refuse with `ViewerError('MATERIAL_INVALID')`. ### Light and shadow limits The renderer uses the first lights of each kind in `viewer.lights`, not the first lights with shadows enabled. Set `castShadow: true` on a light within that set. `viewer.shadowMapSize` sets each shadow map's resolution. Setting `intensity: 0` still uses a light slot and does not disable shadow checks. If its `castShadow` is true, a point light still counts toward the one-caster limit. Set `castShadow: false` to disable its shadow. PCF averages nearby shadow-map comparisons. PCSS searches for blockers and varies the filter radius with blocker and receiver depth. | Light kind | Lights used | Shadow support and softness | | --- | --- | --- | | Directional | First 4 | Each can cast a shadow. `environment.softShadows` sets their shared angular size in degrees for PCSS. Zero or omission retains the hard, 3×3-filtered edge. | | Spot | First 4 | Each can cast a shadow. Zero or omitted `shadowRadius` uses PCF; a positive radius enables bounded PCSS. | | Point | First 8 | At most one can cast a shadow, using six 90-degree faces. Zero or omitted `shadowRadius` uses PCF; a positive radius enables bounded PCSS. A second enabled caster causes `LIGHT_INVALID`. | For an enabled spot shadow, position and direction must be finite f32 vectors, and direction must be nonzero. The cone half-angle is in degrees and must be strictly between 0 and 90; the default is 30. Range must be finite and nonnegative; zero or omission fits the shadow depth to the scene. `shadowRadius` is a light disk radius in scene world units, not degrees or CSS pixels. It must be finite, nonnegative and representable in f32 without rounding a positive value to zero. Invalid enabled inputs refuse with `LIGHT_INVALID`. `penumbra` is a separate 0–1 share of the cone used to fade its lighting edge. It does not set shadow softness. Spot PCSS uses bounded blocker-search and filter radii; it approximates a disk light, not an area-light renderer. `environment.softShadows` applies to directional shadows, not spot or point shadows. These SDK settings use the existing spot and point examples. They assume an existing WebGPU viewer and scene; the positions, range and radius use that scene's world units, which are not automatically mm. ```js // Spot example: source [5, -3, 7], aimed at [0, 0, 0.6]. viewer.lights = [{ kind: 'spot', position: [5, -3, 7], direction: [-5, 3, -6.4], angle: 30, penumbra: 0.2, shadowRadius: 0.4, range: 18, intensity: 80, castShadow: true }]; viewer.requestRender(); // Alternative point example: this assignment replaces the light list. viewer.lights = [{ kind: 'point', position: [1, -1, 3.5], range: 18, intensity: 100, shadowRadius: 0.25, castShadow: true }]; viewer.requestRender(); ``` For an enabled point shadow, position must be a finite f32 vector. Both `range` and `shadowRadius` must be finite, nonnegative and representable in f32 without rounding a positive value to zero. A positive range keeps the spherical lighting cutoff and limits each face's far plane; zero or omission fits the faces to the scene and cap bounds. Inputs that cannot form a finite f32 depth projection refuse with `LIGHT_INVALID`. These shadow admission checks apply only to enabled casters among the first four spot lights or first eight point lights. Point PCSS approximates the emitter with a disk perpendicular to each receiver ray. It uses the six shadow faces with bounded blocker-search and filter radii. The radius uses the scene's world units. It is not an area-light simulation. The Viewer checks shadow inputs during creation and before each draw. Direct assignment to `viewer.lights` does not run these checks. ### Capture pixels and release the viewer `viewer.capture()` draws a frame and returns a promise for `{ width, height, data }`. The dimensions are `canvas.width` and `canvas.height`: canvas backing pixels, not CSS pixels or model units. `data` is a `Uint8Array` of packed RGBA bytes. Rows run from top to bottom; each pixel has four consecutive bytes. | Returned data | Byte layout | | --- | --- | | One pixel at `(x, y)` | R, G, B, A at offsets `4 * (y * width + x)` through `4 * (y * width + x) + 3` | | One row | `width * 4` bytes, with no row padding in the returned array | | A 640 × 480 backing image | `640 * 480 * 4 = 1,228,800` bytes | ![Calculated RGBA row layout for a 640 by 480 backing image; this is not an API capture](/diagrams/capture-rows.svg) [Open the byte layout at full size](/diagrams/capture-rows.svg). The renderer removes GPU readback row padding and converts BGRA to RGBA when needed. The result is raw pixels, not a PNG file. A caller must encode them to create an image file. Studio's image export adds that encoding step with `ImageData` and an `OffscreenCanvas`. | Method | Caller action and result | | --- | --- | | `requestRender()` | Request a draw after changing public camera or light fields. Built-in scheduling combines requests into one frame. With `onRequestRender`, each request calls that callback instead. | | `frame()` | Request a frame and return `Promise` for the frame waiter. It can also resolve after GPU-work failure or disposal; it returns no image bytes. | | `capture()` | Draw and read the RGBA bytes; handle its asynchronous failure separately. | | `dispose()` | Release the viewer when its canvas is no longer needed. Repeated calls are safe. | `dispose()` cancels scheduled work, removes controls and resize observation, and releases GPU resources. After disposal, `capture()` rejects with `DISPOSED`, while `requestRender()` returns without scheduling work. Disposal also releases pending frame waiters; a resolved `frame()` promise alone is not proof of a successful capture. Keep the viewer alive until operations that need it have finished. ### Progressive still images `viewer.createPathTrace()` creates a separate offscreen still with frozen scene, camera, materials and lighting. Later viewer edits do not update it; create another session for the edited scene. Raster controls remain independent. Width and height are output backing pixels, independent of the interactive canvas; omission uses the canvas size. `bounces` is an integer from 1 to 16 and defaults to 6. This SDK example uses an existing populated WebGPU viewer: ```js const still = await viewer.createPathTrace({ width: 640, height: 480, bounces: 6 }); try { await still.sample(8); const raw = await still.capture(false); await still.start(samples => { if (samples >= 32) still.stop(); }); const frame = await still.capture(true); console.log(frame.width, frame.height, frame.samples, frame.data); console.log(raw.samples); // Remains 8 after the later sampling. } finally { still.dispose(); } ``` Each manual `sample()` batch accepts 1–64 samples. Stop progressive sampling before calling it; an active session refuses manual sampling with `PATH_TRACE_BUSY`. `start()` resolves after sampling stops; `stop()` ends progressive sampling. Sample before capture: capture with no completed samples also refuses with `PATH_TRACE_BUSY`. Unlike raster `viewer.capture()`, `still.capture()` returns `{ width, height, samples, data }`. Its top-to-bottom RGBA `Uint8Array` is raw pixels, not PNG data. `capture(false)` skips denoising; `capture(true)` uses geometry-aware denoising. `frame.samples` is fixed for those pixels when the queued capture starts. The live `still.samples` can advance later, so use `frame.samples` when labelling or exporting the image. Dispose each session when finished. The still includes visible, bounded triangle surfaces. Active section clips and caps, custom material shaders, scalar maps and contours refuse with `PATH_TRACE_UNSUPPORTED`. Lines, labels, overlays and raster shadow catchers are not included. Raster effects such as depth of field, bloom, SSAO, contact shadows and outlines do not apply. ### Depth of field The low-level viewer accepts `environment.depthOfField` as `false` or `{ focus, blur? }`: ```js viewer.environment = { ...viewer.environment, depthOfField: { focus: 160, blur: 6 }, }; ``` `focus` is a positive distance along the camera's view axis in the scene's world units. `blur` is a maximum radius in CSS pixels. Omitting `blur` uses 8; positive values are capped at 24. The renderer scales CSS pixels by the device pixel ratio. Omitting the effect, setting it to `false`, or using zero blur disables it. Non-finite or non-positive focus, and non-finite or non-positive blur, do not enable the effect. The example assumes an existing WebGPU viewer and its scene units; 160 is not automatically 160 mm. Studio stores its focus distance in mm and both its focus and blur values, as described under [Focus and blur](/studio/rendering#focus-and-blur). These are image settings, not geometric or physical accuracy bounds. ![View-axis focus depth is 80 mm while eye-to-point distance is 100 mm; blur is a separate CSS-pixel value](/diagrams/focus-distance.svg) [Open the focus diagram at full size](/diagrams/focus-distance.svg). This coordinate example uses Studio mm; use the GPU scene's own world unit when applying the same view-axis rule. ## The scene and material language The Render tab's props and its authored materials are written in this language. It runs on the CPU, so these samples run in Node: ```js // The Render tab's props: a plinth under the part. const props = compileGpu({ kind: 'scene', source: `@scene props { version: 0; box #plinth; } #plinth { size: 9 .4 6; translate: 3.2 -.25 -1.6; color: #6d727a; }` }); assert.equal(props.ok, true); const cone = compileGpu({ kind: 'scene', source: '@scene s {\n version: 0;\n cone #c;\n}\n' }); assert.equal(cone.ok, false); assert.deepEqual(cone.diagnostics[0], { code: 'VALIDATION', severity: 'error', message: 'Unsupported scene declaration', range: { start: 27, end: 31, line: 3, column: 3 } }); ``` ```js const paint = materialShader(`@shader #paint { @uniform amount: float(0, 1, .35); @fragment { color: mix(#d0643c, #3c78b4, amount); } }`); assert.equal(paint.ok, true); assert.deepEqual(paint.uniforms, [{ name: 'amount', min: 0, max: 1, default: 0.35, index: 0 }]); assert.equal(paint.usesUV, false); assert.match(paint.shader.declarations, /fn material_mix/); // WGSL the viewer draws with ``` - **Scenes.** - A scene has exactly one `@scene`, a version, and objects styled by type or id selectors. - It has no classes, inheritance, expressions or scripts. - Anything it doesn't take is refused, with its line and column. Nothing is silently ignored. - **Materials.** An `@shader` material declares its uniforms and a fragment colour, and lowers to the WGSL the viewer draws with. - **Showing a scene.** `showScene(viewer, source, options?)` returns a `SceneView`. If the first source fails to compile, it throws `SceneViewError` with code `SCENE_VIEW` and its `diagnostics`. `view.meshes` maps object IDs to meshes; `view.result` holds the last successful compile result. `view.update(source)` returns `{ ok: true }` after showing a successfully compiled source. A compile failure returns `{ ok: false, diagnostics }` and keeps the previous displayed scene, meshes and `result`. This preservation applies to compile failure; it does not guarantee recovery from every rendering or GPU error. `view.dispose()` removes its meshes and disposes its cached geometry; calling it again does nothing. It does not dispose the viewer. After disposal, `view.update(source)` throws `SceneViewError` with code `SCENE_VIEW` and a `STATE` diagnostic instead of returning `{ ok: false, diagnostics }`. The package README is the language's full reference. ## Errors gpu refuses with its own `BarocssError`, of the same shape as the other packages': a `code`, and a message that starts with it in brackets. gpu imports neither cad package, so the class is its own. Each error class is one of these, and some codes are shared by several classes, so tell refusals apart by `code`. - **The viewer's input** is refused with a `ViewerError`: | Code | What it refuses | |---|---| | `GEOMETRY_INVALID` | Geometry input: positions, indices, topology counts, normals, faces, edges, UVs, labels, colours and their range, scalar fields | | `INSTANCES_INVALID` | Instance transforms or colours of the wrong length, or instancing a mesh that isn't triangles | | `TRANSFORM_INVALID` | A transform that isn't 16 numbers | | `COLOR_MAP_INVALID` | A colour map with fewer than two stops, or stops that don't rise | | `COLOR_INVALID` | A colour that isn't hex, when a frame is drawn | | `MATERIAL_INVALID` | A shader material with more than 16 parameters, when a frame is drawn | | `CLIP_INVALID` | Too many clip planes, or a plane without a normal or a finite offset | | `TEXTURE_INVALID` | A texture without a size, or data that isn't width × height RGBA | | `SIZE_INVALID` | A backing size under 1 × 1 | | `MATRIX_SINGULAR` | Inverting a matrix that has no inverse | When it can't start or draw, it refuses with `WEBGPU_UNAVAILABLE`, `NO_ADAPTER`, `NO_CONTEXT`, `SHADER`, `PIPELINE`, `DEVICE_LOST` or `DISPOSED`. - **The package entry's inputs** are refused with a `GpuInputError`, with the same words as before its code. Where it wraps a check, its cause is that check's own error: | Code | Entry | |---|---| | `SCENE_INVALID` | `parseScene`, `compileScene` | | `MESH_PACKET_INVALID` | `validatePreviewPacket` | | `MESH_OPTIONS_INVALID` | `validateMeshOptions` | | `MESH_INVALID` | `prepareMesh` | | `CAMERA_INVALID` | `validateMeshCamera`, `prepareCamera` | | `FACE_PREVIEW_INVALID` | `prepareKernelFacePreview`, `resolveKernelFaceReference` | | `PRIMITIVE_FRAME_INVALID` | `preparePrimitiveSceneFrame` | | `BOOLEAN_BUFFERS_INVALID` | `prepareCoplanarBooleanBuffers`, `prepareBooleanShellBuffers` | | `GPU_BVH_DEPTH` | A hierarchy too deep for a GPU analysis (`computeExperimental`) | - **Compiling the language** doesn't throw: `compileGpu` and `materialShader` return `{ ok: false, diagnostics }`, each diagnostic with its code and where it is. - **The object facade's** codes are on [Object API](/packages/api#scenes). ## WebGPU and WebGL2 The studio keeps one interface over two renderers: - **WebGPU** is this package's viewer, used when the browser has an adapter. - **WebGL2** is the studio's own renderer (`apps/cad-studio/src/viewport/renderer.ts`): a multisampled scene pass, screen-space ambient occlusion and an id pass for picking. Both draw the model, the display modes, sections, overlays and placed parts. The analysis maps and the mould's halves draw only with WebGPU; on WebGL2 their buttons are disabled and say why. `?renderer=webgl2` forces WebGL2. ## Compute analyses `computeExperimental` runs analyses on the GPU: - **Wall thickness:** for each display triangle, a ray inward from its centre to the next wall. The local thickness is the sphere that fits there. - **3-axis access:** from each sample, a ray along each of ±X, ±Y and ±Z, and whether it leaves the part. Both trace the kernel's triangle hierarchy, packed for WGSL, and each has a CPU mirror. They are for display only: the exact values a report uses stay the CPU's. The namespace may change before its API is stabilized. ## Frame costs With `viewer.costs` on, each mesh counts what the last frame cost it: - its draw calls; - the triangles, lines and points they drew; - its draws by pass: `shadow`, `surface`, `transparent`, `oit`, `hiddenLines`, `caps` and `outlineMask`. These are work counts, not times; a frame's CPU time is in its stats. The studio reads them per body and display mode, but doesn't show them yet. ### Measured The studio's heaviest scenes were measured on both renderers: an orbit per display mode, at 1440 × 900 on an Apple M-series machine in headless Chrome, with other work running. The scenes ranged from a 38-body assembly and a 120-bracket pattern to a 114,000-triangle spring. - **Frame rate.** Every scene held 60 Hz: the frame interval's median was 16.7 ms. - **Headroom.** - The main thread's work stayed under about 4 ms a frame. - On WebGPU, the GPU's time stayed under about 5 ms a submit. That leaves at least three times the 16.7 ms budget. The full tables are in `apps/cad-studio/handover/notes/g11-scene-profile.md`. Times depend on the machine. Only the counts are the same everywhere. How the viewer renders, step by step: [Rendering a model on the GPU](/how/gpu). --- # Viewer review files `@barocss/viewer` is currently used from source. `@barocss/viewer` can capture and restore a review of a loaded CAD scene: its camera, visible geometry and selected geometry. The host app supplies file Save/Open. Opening a review does not load CAD geometry or modify the CAD model. ![Viewer review flow: load the matching CAD scene, save review JSON, validate it and restore the view](/diagrams/viewer-review-flow.svg) ## Capture and apply | API | Result | |---|---| | `viewer.captureReviewState()` | A detached, JSON-safe `ViewerReviewStateV1` snapshot | | `viewer.applyReviewState(input: unknown)` | Validates and applies the review; returns `void` or throws | Serialize the captured object with `JSON.stringify`. Later, parse the host's file text and pass the resulting `unknown` value to `applyReviewState`. Changing a captured snapshot does not change the Viewer. Do not save the whole `getState()` object as a review file. The example loads the CAD document before exposing review Save/Open functions. The caller supplies original CAD document JSON and 1..4 existing body IDs. The declared authored XYZ basis must match the Viewer's right-handed Y-up millimetre basis; the option is an assertion, not a coordinate conversion. `createViewer` requires `background`: three finite RGB components, each from 0 to 1. ```ts import { createViewer } from '@barocss/viewer'; import { parseBaroCadDocument } from '@barocss/cad-interop/document'; async function createReviewHost( canvas: HTMLCanvasElement, cadDocumentText: string, bodyIds: string[], ) { const viewer = await createViewer(canvas, { mmToSceneUnit: 0.15, background: [0.025, 0.04, 0.065], }); try { viewer.loadDocument(parseBaroCadDocument(cadDocumentText), { native: { sourceVersion: 0, countU: 8, countV: 8, unitsPerMillimeter: 1, curveDisplay: { version: 1, chordToleranceMM: 0.02, maxSegments: 512, maxDepth: 16, }, }, basis: 'authored-xyz-matches-rhyup', bodyIds, }); } catch (error) { viewer.dispose(); throw error; } return { viewer, saveReview(): string { return JSON.stringify(viewer.captureReviewState(), null, 2); }, openReview(text: string): void { const input: unknown = JSON.parse(text); viewer.applyReviewState(input); }, }; } ``` The host writes the returned text to a file and supplies file text to `openReview`. It handles JSON parsing, read/write errors and file-size limits. It also disposes the Viewer when finished. Loading and applying can throw; show the error and keep the review file for correction rather than treating a failed Open as a new accepted view. ## Pointer and keyboard controls Call `viewer.attachPointerControls(options)` or `viewer.attachKeyboardControls(options)` on the existing Viewer. Each accepts an optional plain options object with only `onError?: (error: unknown) => void`. The methods return a `ViewerPointerControls` or `ViewerKeyboardControls` handle, respectively. Keep each handle and call its `dispose()` to remove the listeners it installed. See [Host lifetime](#host-lifetime) for the cleanup order. | Adapter | Input | Action | |---|---|---| | Pointer | Primary-button drag | Orbit the camera | | Pointer | Shift + primary-button drag | Pan the camera | | Pointer | Wheel | Zoom | | Keyboard | Unmodified F | Fit the currently visible displayed geometry | | Keyboard | Escape | Clear the current Surface or Curve selection | Keyboard controls listen only on the Viewer canvas. Give the canvas `tabIndex=0` and let the host or user focus it. The adapter does not set focus. It ignores modified, repeated and composing keys. Pointer controls capture one primary pointer and use canvas CSS pixels. The host owns the canvas's `touch-action` CSS and click-to-select behavior. After a successful drag moves more than 3 CSS pixels from its start, releasing the pointer suppresses the next click. A click without such a drag still reaches the host's selection handler. The pointer adapter does not select geometry or change native measurements or display poses. Unsupported options are refused when attaching a control. Event-handling failures go to the optional `onError` callback. A failed keyboard action does not prevent the browser's default action. ## Host lifetime The host owns the Viewer and any pointer or keyboard control handles it attaches. Before removing the canvas or replacing its Viewer, stop the host's callbacks, dispose each control handle, then call `viewer.dispose()`. Disposing the Viewer does not remove the listeners installed by those separate control handles. Scene replacement, `viewer.clear()` and Viewer disposal release the Geometry owned by the SDK drawing, including its vertex/index buffers. Camera changes keep ownership bounded to the current drawing. If you use the GPU Core directly with shared Geometry, each caller still owns that Geometry: removing one Mesh leaves it available to other Meshes and later reuse; dispose it when that sharing ends. Both control-handle disposal and `viewer.dispose()` can be called again without repeating their cleanup. After Viewer disposal, `getState().status` is `disposed`; `captureReviewState()` and `applyReviewState()` refuse that instance. Create and load a new Viewer before offering review Save/Open again. A host can keep this cleanup callback with its canvas owner: ```ts import type { Viewer, ViewerPointerControls, ViewerKeyboardControls } from '@barocss/viewer'; export function reviewCleanup( viewer: Viewer, pointer: ViewerPointerControls, keyboard?: ViewerKeyboardControls, ): () => void { return () => { pointer.dispose(); keyboard?.dispose(); viewer.dispose(); }; } ``` ## What the file binds to The format is `schema: 'barocss-viewer-review'`, `version: 1`. Its fields are `scene`, `camera`, `visibleGeometry` and `selectedGeometry`. The scene pins come from the accepted loaded scene: - document or assembly kind, ID and revision; - the exact `mmToSceneUnit` scale; - the loaded body or instance inventory, including original document/asset revision references, in its original order. Load that same revision and subset before applying the file. A different scene, revision, member order, subset or scale is refused. Do not reorder or edit `scene.members` to make another scene match. The CAD producer must advance revisions when CAD data or assembly placements change. Pins identify declared revisions; they do not authenticate source contents or provide file integrity. The file contains no geometry, preview packets, CAD source, motion, materials, measurements or simulation layers. Save those inputs separately when the host needs them. Applying the review restores only camera, visibility and selection; it does not restore those other values. ## Supported scenes and visibility Review files support revisioned primitive CAD document and assembly scenes with the existing 1..4 loaded-object limit. All loaded objects may be hidden: `visibleGeometry` can be empty, with `selectedGeometry: null`. Otherwise, the selection must name visible geometry. Visibility references must be unique members of the loaded inventory. Existing material and layer restrictions can also refuse visibility or selection changes. Empty or disposed Viewers, native-source-only and model-set-only loads, Shell, mixed-depth and qualified Face scenes are outside this review profile. A review file is not a general serialization of every Viewer mode. ## Refusal and recovery `applyReviewState` checks the complete candidate before presentation. Unsupported fields, stale pins, invalid camera data, unknown or duplicate geometry and hidden selections are refused. Invalid input leaves the accepted state and drawing unchanged. The input must contain plain data; accessors and unsupported object shapes are not accepted as file fields. For an admitted candidate, the Viewer draws before committing the new CPU camera, visibility and selection. If presentation throws, it keeps the accepted CPU state and attempts to redraw the prior state. If recovery also fails, an `AggregateError` reports both errors. This recovery attempt cannot guarantee pixels after a device failure. Successful apply does not mutate the caller's object, CAD data or hierarchy. The repository's `examples/viewer-review` shows host controls for saving JSON and opening a real file. Its 32 KiB file-read limit belongs to that example host, not to the SDK review schema.