Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
@carbon/viewer
3D model + animated assembly-instruction rendering (three.js / react-three-fiber). Backs the ERP assembly editor and the MES shop-floor player.
Key Domain Concepts
- graph.json (
AssemblyGraph) — assembly tree written by the geometry service/convert; leaf nodes carry a stablenodeId(also baked into GLB node extras asuserData.nodeId). All joins between steps, plans, and scene objects are bynodeId. - plan.json (
AssemblyPlan) — per-component insertionMotion, sequence, subassemblygroups, and body-levelcontacts, written by the geometry service/plan.CURRENT_PLAN_VERSION(currently3) — stored plans below it are STALE and must be treated as absent so the pipeline re-plans. - Step (
AssemblyStep) — one build instruction:componentNodeIds, aMotion, optionalcamera,fastener, per-stephiddenComponentNodeIds, an optionalorientation, and the sub-assembly fieldsisSubAssembly/parentStepId/usedInStepId. Built from a plan bybuildAssemblyStepGroups. - Build orientation (
orientation.ts) — a step'sorientationis a unit quaternion turning the model frame into the bench frame (both Z-up); it holds from that step on within its own build (resolveOrientations, keyed bystepWorlds: the main build and each sub-assembly keep separate chains, a sub-assembly starts upright). The player shows it as a CAMERA FRAME, never by turning the model — turning a root node would break everything that works in world space (buildStepClip, the path editor, box select).useBuildFrameowns the frame:camera.up=upForOrientation(q), and a new orientation turns the camera, its target and up about the build's center (the framed bounds' center) bynext⁻¹ · appliedoverTURN_MS, so on screen the build turns over in place (turning about the target swung an off-center build round in an arc). Playback and framing wait for the turn (isTurning), and grabbing the controls finishes it. When the center moves (entering or leaving a sub-assembly) the new frame SNAPS instead of turning about the other build's center, and unmounting hands the camera back upright, because the camera outlives a remounted scene. A turned step with no saved view keeps the camera's bench direction (keptDirection) rather than re-aiming — any geometry-scored framer undoes a spin, since a spin is just an orbit — and the editor's turn buttons save the current view with the orientation, so playback lands on what the author saw.keptDirection(where the camera looks from once the pending turn lands) is the current direction for every step's framing, so stepping back from a turned step to an upright one scores its candidates from the post-turn view, not the pre-turn one. A saved view (captureCameraPose;isSavedViewtells it from a plan hint) is stored in the BENCH frame (toBench/fromBench, about the same center), so turning a step keeps its view and turns the build; a plan hint is used only on an upright build (it turns with the model); a turn on the active step never re-frames (orientation is not inframingKey), and the camera's pending glide target (desiredPoseRef) is held in the bench frame too — held in the model frame, a target set by playback and not yet reached dragged the camera back after a turn made while paused; dreiGizmoHelperwritescamera.upon every frame of a viewcube tween and resets it when the tween ends, so the hook restores the build's up whenever no turn is playing; the framing effect takes the STEP's up, not the mid-turncamera.up.turnOrientationapplies one editor turn (flip180°,tipForward/tipBack/spinLeft/spinRight90°) about a SQUARE bench axis picked from the view and snaps the result to the 24 right-angle orientations (axis by axis, never entry rounding);describeOrientationnames the pose (upright / upside down / on its side) for the editor. - Sub-assemblies (
subassembly.ts) — a header step (isSubAssembly) groups the steps whoseparentStepIdpoints at it; those steps sit directly before it in play order and are BUILT ON THEIR OWN: while one is active the player isolates its sub-assembly's parts (focus-style, ancestors kept, not cleared by playback, framed on their own bounds). A header'susedInStepIdnames the later step that carries the finished unit in. A header whosemotionis notnonehas a path of its own: the unit plays it (buildStepClip'sunits, one after another in sub-assembly order) before the step's own parts move — a step with no animation of its own fades its parts in only after those units seat (fadeProgress). OnestepClipTimingper step feeds the timeline segment, the clip and the fade delay; while picking components it gives the units and the glide no time.buildCarryPlansis THE per-step answer to which units fly (pathUnits), which glide, what the step's own insertion moves (ownMovingPartIds) and whether the step is an unused header joining on its own path (joinsOnOwnPath: that path is the header's motion, so it has no insertion of its own);carriesUnitssays whether a step brings any unit in. The clip, the fade, the path editor and the framing all read it. Each header's unit parts come frombuildSubAssemblyPlan(unitPartIds). A unit whose header has no path of its own (motionnone) glides from beside the build (CARRY_IN_GLIDE_SECONDS/buildStepClip'sglide.nodeIds), then rides the using step's insertion. A header nothing uses is where its unit joins the main build; a USED header plays nothing (0-length segment, skipped by prev/next). A step whose own insertion moves nothing (stepClipTiming'sownParts: false, e.g. a header joining on its own path) gets a slot of just its units and the hold — the fixednoneslot is for process-only steps and own parts that fade in. No nesting — a step USES a finished sub-assembly instead, so chains of any length work.arrivalIndexByNode(steps, world)is THE answer to "when does this part appear in the build on screen" and drives visibility;validateSubAssembliesis THE structural rule the ERP service and editor share.scopeStepIdslimits the timeline to an opened sub-assembly. - Motion — discriminated union
linear | L | helix | path | waypoints | none.waypointsis editor-authored: poses relative to the seated pose, turning about the moving set's seated bounds center, then shifting (waypointMatrix), so one motion fits a part, a rigid group or a sub-assembly. The player takes that center from graph.json's seated bounds for the clip (buildStepClip's requiredpivot), the path editor and the framed start pose alike — the live nodes are mid-animation when framing runs.resampleEasedkeeps every input keyframe (at its eased time) besides its evenly spaced samples, so easing never cuts a turning leg's 15° samples short. The path editor saveslinear/Luntil a waypoint is turned (editorWaypointsToMotion); it has a Move / Rotate tool (pathToolLabelson the player, host-translated — no labels, no switch): Rotate shows dreiTransformControlsrings on the selected waypoint and stops the spheres dragging, because the rings' invisible free-rotation grip sits over the sphere. Insertion motion; the player derives removal (reverse) and start poses.flagged/blockedBysteps usenoneand fade in (no collision-free path exists — a synthesized path would clip through geometry). - Artifact tiers — a model renders from best-available: LOD GLB → optimised GLB → lossless GLB → raw WASM (in-browser occt-import-js) fallback.
- pmi.json (
PmiDocument,pmi.ts) — a STEP AP242 model's PMI (dimensions, geometric tolerances, datums, graphic-only notes, saved views), written by the optimize ingest (crates/converter/src/pmi.rsis the other half of the contract). World mm in the optimised GLB's frame; each referenced face ships its own triangles, so the highlight never depends on the GLB's mesh layout.ModelPreviewtakespmiUrl, draws it throughPmiLayerinsideModelCanvas, and lists it in the PMI panel;formatPmiItembuilds every label (mm/in, the file's decimals only in its own unit). Only over a server GLB — never the raw tier.selectedPmiItemId/onPmiItemSelectmake the selection controlled.pmiInspectionCharacteristics(@carbon/viewer/pmi, pure) maps a document to the inspection characteristics thepmi-inspection-planjob writes: one per dimension and geometric tolerance, datums and notes left out.
Always
- MUST key everything by
nodeId— scene objects (useAssemblynodesById), plan components, and steps all join on it. Stale/unknown nodeIds (post re-upload) are skipped, never assumed. - MUST keep the three-free import path clean: server/Inngest code imports plan logic from
@carbon/viewer/steps(re-exportsbuildAssemblyStepGroups,assignStepPhases,indexAssemblyGraph,CURRENT_PLAN_VERSION, the step flags), NOT the barrel.— the barrel pulls in three.js/R3F. - MUST treat plans below
CURRENT_PLAN_VERSIONas absent (re-plan), never resurrect their motions. - MUST keep this package free of
@carbon/reactrouter/i18n peers in the pure/motion/plan modules —cnis re-implemented locally inutils.tsfor that reason. (ModelPreview.tsxis the one component that does import@carbon/react.) - MUST prefer server artifacts over the raw tier — the raw WASM fallback renders only when there is no server GLB.
- MUST keep
visualForComponentandoccluderWeight(visibility.ts) in agreement: anything the first renders"hidden"the second must scorenull(not an occluder). They are two views of the same timeline — what the operator sees, and what the camera's AABB view-direction scoring treats as in the way. When they drift, the camera frames around geometry it is not drawing.visibility.test.tsasserts the invariant across every mode combination; a component no step installs counts as future in BOTH (it is never "already there"), which is exactly where the two previously disagreed. - MUST expose visibility to the user as the named views in
ASSEMBLY_VIEWS/VIEW_MODES(visibility.ts), not as the two raw axes. The axes are the renderer's model; nine combinations, most of them meaningless, is not a control anyone can read — an earlier two-icon-triplet toolbar was rejected for exactly that. A new view means a new entry in that table (andVIEW_LABELSinAssemblyPlayer.tsx), never a new axis or a fourth rendering mode. The table is Build / Focus / Full: anisolateview (both sides hidden) was dropped — Focus shows the step in place, and the author's per-step hidden parts (hiddenComponentNodeIds) remove the clutter they choose.viewForModesseats the initial view from the still-axis-shapeddefault*Modeprops, falling back to"build"for an unnamed pair.
Ask First
- Changing
types.ts(Motion,AssemblyGraph,AssemblyPlan,AssemblyStep) — these are a shared contract with the geometry service and the ERP/Inngest layer; change all three together (see the header comment intypes.ts). - Changing the
pmi.tstypes — a contract withcrates/converter/src/pmi.rs; an incompatible change bumpsPMI_VERSIONon both sides (parsePmiDocumentdrops any other version). - Bumping
CURRENT_PLAN_VERSION— it invalidates every stored plan and forces a re-plan across the fleet; coordinate with the geometry service'sPLAN_VERSION. (Note: the heuristic step-building inplan.tsis tuned freely and is NOT a version event.)
Never
- Never fabricate a motion for a
flagged/blockedBycomponent — it must staynoneand fade in at the seated pose. - Never add ordering assumptions between components sharing a
wave— they are parallel-buildable by definition. - Never let a step animate two components whose swept
motionCorridors overlap simultaneously — they must take separate steps (subassemblygroupIdmembers are the one exempt rigid-body case).
Validation Commands
pnpm --filter @carbon/viewer test # vitest — camera, clip, display, fallback, graph, keyframes, orientation, path-editing, plan, pmi, quat, step-flags, subassembly, timing, validate-motion, visibility (shared helpers: src/test-utils.ts)
pnpm --filter @carbon/viewer typecheck # tsc --noEmit
Key Exports
| Subpath | Provides |
|---|---|
. |
AssemblyPlayer (+ AssemblyPlayerHandle/Props), AssemblyViewer, ModelCanvas, all plan/motion/graph/camera/describe/visibility helpers and types |
./steps |
Three-free plan→steps logic for server code: buildAssemblyStepGroups, assignStepPhases, indexAssemblyGraph, CURRENT_PLAN_VERSION, the sub-assembly structure helpers, and the step flags isSavedView / hasCustomMotion / isPlanFlagged (also on .) |
./canvas |
ModelCanvas — standalone static GLB viewer (orbit + view, no steps) |
./pmi |
pmi.ts alone (types, parsing, labels, pmiInspectionCharacteristics) — no React, so @carbon/jobs reads it |
./model-upload-preview |
ModelUploadPreview — a read-only preview of a stored model (useOptimizedModel + ModelPreview); pmiLinks / selectedLinkId / onLinkSelect tie host records (inspection characteristics) to PMI items both ways. modelPreviewUrls(artifacts) is the one place artifact paths become ModelPreview URLs, also used by ERP CadModel and the MES model tab |
./model-preview |
ModelPreview — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view; pmiUrl adds the PMI layer and panel |
./optimize-progress |
OptimizeProgress — optimise-status chip |
./use-optimized-model |
useOptimizedModel — TanStack Query polling of the model optimise lifecycle (shared by ERP CadModel + MES model tab) |
Internal modules (no subpath of their own; some of their functions are re-exported from .): useAssembly.ts (loads meshopt GLB + graph.json, indexes nodes by nodeId), the motion modules — timing.ts (stepClipTiming, motionDuration), validate-motion.ts (isPlayableMotion, isFiniteTuple — shape checks on raw JSON), keyframes.ts (motionToKeyframes, resampleEased, waypointMatrix), clip.ts (buildStepClip), display.ts (displayMotionForStep, naturalizeMotion), path-editing.ts (motion ↔ editor waypoints) — plus step-flags.ts (isSavedView / hasCustomMotion / isPlanFlagged, three-free and zod-free), quat.ts (tuple ↔ three.js helpers, sameOrientation), useBuildFrame.ts (the build-orientation camera frame), fallback.ts (synthesizeFallbackMotion — AABB escape for legacy none motions), subassembly.ts (buildSubAssemblyPlan / buildCarryPlans / arrivalIndexByNode / validateSubAssemblies / usableSubAssemblies / displayOrder), camera.ts (frameStepPose — the pure per-step framing: direction choice, AABB scoring and frustum fit; fitFraming — the frustum fit itself), raw/ (WASM fallback tier: loadRawModel via occt-import-js).
Cross-References
- Consumers: ERP
apps/erp/app/components/CadModel.tsx,apps/erp/app/modules/production/ui/Assemblies/*, routeapps/erp/app/routes/x+/assembly+/$id.tsx; MESapps/mes/app/components/AssemblyView.tsx+JobOperation; Inngestpackages/jobs/src/inngest/functions/tasks/assembly-plan.ts(imports@carbon/viewer/steps). - Contracts:
src/types.tsis the contract itself (thedocs/specs/animated-work-instructions-contracts.mdit once mirrored no longer exists). The ERP mirrorsMotionas zod inmotionSchema(apps/erp/app/modules/production/production.models.ts); the MES checks raw rows withisPlayableMotion(validate-motion.ts), which checks every field keyframe generation reads. - Model paths / raw limits:
@carbon/utils(modelPathOptimizeFormat,MODEL_RAW_KEEP_MAX_BYTES).