Skip to content

Latest commit

 

History

History
397 lines (308 loc) · 25.2 KB

File metadata and controls

397 lines (308 loc) · 25.2 KB
title Modeling API
description Browse the Code3D TypeScript API by modeling task, from primitives and sketches to solid operations, placement, topology and measurements.
sidebar
order hidden
1
true

Construct geometry, combine models and query the result with the public Core API. For a first runnable model, see the Core example.

Browse by task

Choose a starting shape, build the part, then place and measure it. Functions, model methods and reference properties are grouped by what they do.

Category APIs and reading
Solid primitives box, cylinder, sphere, ellipsoid, frustum, regularPrism, tube and coil
Points, curves and profiles point, line, arc, bezier, spline, circle, ellipse, rectangle and regularPolygon
Sketches sketch, entities, constraints, point / derive, face / faces, plane / relate
Text and fonts text, font, googleFont
Shape construction extrude and loft, revolve, sweep, wrap and thicken
Booleans and solid modifications union, cut and intersect; fillet, chamfer and shell
Origins and local transforms originPoint, originVertex, originOffset, originCenter and model.rotate; scaled
Groups and placement group and expose; frame; relate, on and align; offset, rotate and pivot/axis selectors; coupleRotation
Topology and references vertex / vertices, edge / edges, surface / surfaces; reference elements, directional bounds, flip / reverse
Geometry measurements distance, length, area, volume, bounds, position
Materials and appearance material and colors, Three.js integration
Parameters, time and caching input, timeOffset and cache

For reusable library development, see definePrimitive and Replicad, model data and custom inspectors, group member inspection and annotations. Execution hosts use the separate tooling integration API. The model values guide explains the capabilities of different model kinds.

Imports and types

The complete export index maps every public function, type and model member to its primary reference, including tooling and interoperability.

Model types and capabilities explains all model aliases, kind mappings, capability interfaces, named elements and common vectors.

Import these functions from @code3d/core. The editor's TypeScript signatures provide exact overloads and inferred model interfaces.

Types used by the authoring API are also exported, including generic constraints, named-element result types, and capability interfaces. Use import type from @code3d/core for types such as ElementKind, ModelKind, ModelForKind, TopologyKind, NamedElements, ExposedElements, Bound, and TopologyId. Replicad builder types such as Shape3D are available from @code3d/core/replicad alongside definePrimitive.

Use input('Width', 40, {min: 4, max: 100, step: 1}) for a numeric form parameter with a slider; the options argument is optional. It returns a number that can drive ordinary model code.

For time-dependent assembly motion, read timeOffset() and derive angles or offsets with ordinary TypeScript. See time offset for playback and evaluation semantics.

Solid primitives

Function Meaning
box(x, y, z) Box dimensions along X, Y, and Z
cylinder(radius, y) Cylinder with its axis along Y
sphere(radius) Sphere of the given radius
ellipsoid(xRadius, yRadius, zRadius) Ellipsoid with three axis radii
frustum(bottomRadius, topRadius, y) Truncated cone
regularPrism(radius, y, sides, rotation?) Regular polygonal prism
tube(outerRadius, innerRadius, y) Straight tube with a through bore
coil(coilRadius, wireRadius, pitch, turns) Circular-wire coil along Y

Choose a constructor by its section: rectangular, circular, spherical, ellipsoidal, tapered, polygonal, hollow or helical. Each reference explains its own dimensions, local origin, reference elements, measurements and constraints. See the basic shapes example to inspect all eight solids in one source file.

Use @code3d/screws for standard fasteners and matching hole tools. Use @code3d/gears for nominal spur, helical and internal gear parts.

To build a solid beyond these primitives, import definePrimitive and replicad from @code3d/core/replicad. See custom primitives for a complete example.

Profiles and curves

Planar profiles lie in the local XZ plane with a +Y normal.

Function Meaning
circle(radius) Circular face
ellipse(xRadius, zRadius) Elliptical face
rectangle(x, z) Rectangular face
regularPolygon(radius, sides, rotation?) Regular polygonal face
point() or point([x, y, z]) Vertex model
line([x, y, z]) or line(start, end) Straight edge
arc(start, middle, end) Arc through three points
bezier(points) Bézier curve
spline(points) B-spline fitted to ordered samples
loft(sections, options?) Solid through sections; optional curve spine
extrude(faceOrFaces, distance) Solid extruded along one face's local normal
revolve(profile, axis, config) Solid rotated about a straight directed axis, with optional axial advance
sweep(profile, spine) Solid formed by carrying one face along an open curve
wrap(profiles, target, options?) Curved faces mapped from one planar layout onto a finite surface
thicken(faceOrFaces, thickness) Solids offset along oriented surface normals

See local coordinates and placement for the coordinate frame of a model, reference, or composition.

Position coordinates use arrays; dimensions, offsets and angles use scalar arguments. point([x, y, z]) equals point().originOffset(-x, -y, -z). line([x, y, z]) starts at zero; the two-array form uses both supplied local endpoints. Curve tangents do not redefine the model's XYZ axes.

Profiles and curves are model values that can be inspected and related to other models.

See extrude for signed straight extrusion and loft for ordered sections and optional spine guidance.

Rotational solids

revolve covers planar profiles, directed axes and optional axial advance. coil provides a circular-wire shortcut with pitch checks.

Path sweeps

sweep explains open paths, starting alignment and supported holes.

Curved surface wrapping

wrap maps one shared planar layout to a finite curved surface. thicken adds signed thickness for relief or engraving. See their references for localization, seams, curvature and numerical limits.

Measurements

Read numeric geometry results using these references. Results are ordinary values computed at the call; later model values do not update earlier measurements.

Length and area

length measures finite edge arc length; area measures trimmed faces or every boundary face of a solid. See their references for units, model capabilities, scale and read-only inspection.

Volume

volume measures solid material, excluding holes and cavities.

Distance between references

distance measures shortest distance or projected clearance between finite geometry in its solved placement. Its reference explains axis forms, groups, finite versus infinite anchors, query timing and the fitted-beam example.

Independent placement transformations

Use offset and rotate as separate placement steps inside relate. Complete a chosen rotation center or axis with one rotation: pivot, pivotVertex, pivotPoint, axisEdge or axisLine. Their references describe frame conventions, pivotOffset/axisOffset and the resulting transformation types.

Runtime defaults while editing

The dimension-based primitives and numeric methods below keep their required TypeScript parameters, but their implementations supply defaults for omitted or undefined arguments. For example, box() previews a 10 × 10 × 10 box, while the editor still reports the missing arguments; box(20) previews 20 × 10 × 10. Finish the arguments to make the source type-correct. These defaults also apply in ordinary JavaScript execution and do not depend on the App.

Function Runtime defaults, in parameter order
box 10, 10, 10
cylinder 5, 10
sphere 5
frustum 5, 3, 10
regularPrism 5, 10, 6, 0
tube 5, 3, 10
coil 5, 1, 3, 3
circle 5
ellipse 5, 3
rectangle 10, 10
regularPolygon 5, 6, 0
Method or utility parameter Runtime defaults
Model/group rotate and independent/pivot rotate 0, 0, 0
Model/group originOffset and relation offset 0, 0, 0
Relation pivot [0, 0, 0]
Selector pivotOffset and axisOffset 0, 0, 0
axisLine(axis).rotate 0
Geometric model scaled 1
Face extrude and the extrude utility's distance 10
Face thicken and the thicken utility's thickness 1
Solid fillet, chamfer and shell 1

For example, box(20, 30, 40).rotate() previews the unchanged body, and .rotate(30) previews a 30-degree X rotation. Their missing-angle diagnostics remain until all three arguments are supplied. Relation offset() translates self from the relation's solution in the target reference axes. Like explicit offset(0, 0, 0), omitting its arguments preserves that solution and adds no tangential constraints. pivot() selects self's local origin. Geometry IDs, reference axes and input models still need explicit values.

Explicit arguments remain subject to their normal validation: box(0), for example, still reports an error. The parameter panel shows omitted defaults as placeholders and only writes arguments when you edit them. See parameter defaults.

Spatial controls use the rendered operation's position and frame, so omitted arguments do not hide its translation arrows or rotation rings. Committing a drag fills all remaining omitted defaults in that call: dragging the X ring of rotate() writes rotate(angle, 0, 0), and dragging pivot() writes all three coordinates. This also applies when editing an existing or upstream parameter. The parameter change and default completion form one undo step. Merely selecting a tool, cancelling a drag or returning to its starting value leaves the source unchanged. Existing editable expressions retain their normal editing behavior; opaque inputs such as pivot(coords) or rotate(...angles) are replaced with the current evaluated coordinates or angles when you commit the drag. Undo restores the original expression.

Editable sketch regions

sketch creates an immutable two-dimensional definition. See entity tuples for points, lines, circles and arcs; constraints for the complete condition union; point and derive for upstream references and local layers; and face and faces for closed regions, holes and islands. The editor workflow explains selection and drag behavior. Mark reference curves as construction geometry to retain their constraints and snap targets while excluding them from face boundaries.

Sketch placement and model context

plane and relate places an empty, open or closed sketch against model geometry. It explains the callback's self identity, inherited relations, finite/infinite geometry limits and editing in a model context.

Composition and boolean operations

Function Result
group(models, options?) Composition that preserves its separate parts
union(solids) Fused solid
cut(stock, tools) Stock with the tool volumes removed
intersect(solids) Shared solid volume

See group for supported members, nested hierarchy and coordinate frames. expose publishes typed member references for reuse.

Use {name: 'Assembly', frame: base} to name the group and explicitly select its local coordinate system. frame accepts an independent frame() value, a model's .frame, or an exposed frame. It contributes a reference, not an output member. Without this option, the first member defines the coordinates. See independent coordinate frames.

Relations are resolved at composition and geometry evaluation boundaries. Solids also provide .union(operands), .intersect(operands) and .cut(tools). These methods accept a single solid or a nonempty readonly array, with the receiver as the first operand. Free boolean functions take arrays. Arrays in booleans and loft describe the inputs of one operation; they do not automatically map it. intersect() requires a common solid volume across all inputs. Disjoint inputs or inputs that only touch produce a diagnostic rather than an empty solid.

Model operations

Available operations depend on the kind of geometry. TypeScript completion shows which operations are supported by the value you hold.

Materials

material captures complete appearance on a new model value, including colors, transparency and group-wide replacement. Three.js integration covers @code3d/core/three, loaded textures, UV mapping and the supported serialization boundary. Use @code3d/materials presets for common surfaces.

Scaling

.scaled(factor) uniformly scales a geometric model around local zero. See its reference for supported model kinds, factor validation, measurement scaling and placement semantics.

Rotation coupling

coupleRotation(other, {ratio, phase?}) couples the current model's cumulative placement angle to another model's fixed axis. See its reference for angular datums, full turns, translation freedom, configuration fields and the supported acyclic driving graph.

Origins and rotation

Every model has a frame and origin. Use originPoint, originVertex, originOffset or originCenter to choose local zero. Model rotate rotates local geometry; relation rotate places it in a composition.

Independent coordinate frames

frame(name?) creates an independent coordinate reference without geometry. Use it with align and select it in group options.

Model coordinate references

See frame and origin for references on model values.

Centering a collection

originCenter covers the free function's readonly collection form, shared bounds and preserved member placement.

Model metadata

Model metadata explains symbol-keyed snapshots, withMetadata and inheritance through modeling operations.

Anchors and relations

Reference elements distinguishes finite geometry, infinite axes/planes and coordinate frames. Build placement with relate, on, align and coupleRotation. Their references explain callback identity, supported geometry, solve order and remaining freedom.

Use separate offset and rotate steps after constraints. pivot, pivotVertex, pivotPoint, axisEdge and axisLine choose the rotation reference. Read the placement workflow for complete assemblies.

Package authors can attach symbol-keyed model data and publish named reference elements. These serve distinct purposes: package metadata and the model's public placement interface.

Topology

Select finite geometry with vertex / vertices, edge / edges and surface / surfaces. Each reference retains its owning model and topology ID. Child queries validate membership and keep the original namespace; see the individual selectors for ID paths, ordering, duplicates and empty selections.

Reference elements explains frames, origins, centers, axes, planes and curve points. Directional bounds provide finite contact boundaries; flip / reverse changes reference orientation without editing geometry.

See topology lineage for identities across construction and local edits, and the exporting guide for choosing the physical scale of model units.

Cached computations

cache covers both invocation forms, deterministic arguments, result value semantics, supported data, custom codecs and host persistence. Read input and timeOffset before entering a cached computation and pass their values explicitly.

Text

text creates connected planar faces with a shared baseline, then ordinary extrusion, union and cut build raised or engraved lettering. font loads local/remote font bytes; googleFont loads a named family and style with its subsets. Await font loading before synchronous geometry construction. Their references cover signatures, all options, coordinates, supported formats and caching. See the text workflow for complete layout and curved lettering.

Geometry measurements

bounds returns finite axis-aligned extents in the model's own frame or an explicit reference model's solved frame. position returns the model origin in an explicit reference frame. Both support groups; their references explain nested occurrences, ambiguity and value semantics.