@toolpath/viewer
v3.5.0
Published
React Three Fiber viewer for Toolpath Engine part reports
Keywords
Readme
Toolpath Viewer
Display CAD meshes in a React application — on the web, or in a React Native app
through Expo — with feature picking, camera controls, stock, section cuts, and
measurements. Use EnginePart for an analyzed Toolpath
report, or PartMesh for geometry and region/feature data you supply yourself.
The viewer does not read STEP files, run analysis, or require an API key to render
local geometry.
- Install
- Quick start: Engine report
- Use your own geometry
- Selection and hover
- Components and camera controls
- Toolbar, stock, section, and measurement recipes
- React Native (Expo)
- Engine loading, caching, and errors
- Reference
- Work on the package
Install
npm install @toolpath/viewerYour application must provide compatible peers:
| Dependency | Declared range | Needed for |
| -------------------- | -------------- | ---------------------------------- |
| react | ^19.0.0 | Both |
| react-dom | ^19.0.0 | The web (optional peer) |
| three | >=0.159.0 | Both |
| @react-three/fiber | ^9.7.0 | Both |
| @react-three/drei | ^10.7.8 | Both |
| react-native | >=0.79 | React Native, where it is required |
| expo-asset | >=11.1 | React Native, where it is required |
| expo-gl | >=15.1 | React Native, where it is required |
A web application installs react-dom itself; it is optional only so a React
Native app does not need it. The React Native peers are optional only so a web
application does not need them: dist/native imports expo-asset and
expo-gl as it loads. For React Native, see
React Native (Expo).
For a new application, this is the combination used by the repository's example:
npm install @toolpath/viewer [email protected] [email protected] [email protected] @react-three/[email protected] @react-three/[email protected]TypeScript applications also need React and three.js types, for example
@types/react, @types/react-dom, and @types/three. Match the three.js types to
your installed three.js release. Keep one compatible copy of each renderer/peer
in your application; React Three Fiber 9 uses React 19.
This is an ESM package with included TypeScript declarations. Its declared Node floor is 20; the tested three.js release needs a browser with WebGL2 support. Use your framework's client component boundary for interactive React code and its normal bundler setup. See the React Three Fiber installation guide for framework-specific setup.
Current packaging limitation: direct, unbundled Node ESM imports of both
JavaScript entries fail with CameraControls.install is not a function. Use an
application bundler; for SSR, verify the framework's server dependency bundling
as well as its client component boundary. The declared Node floor does not make
these entries standalone Node utilities.
Styles
The canvas does not need Tailwind or @toolpath/ui. Give the viewer a nonzero
height. It fills its wrapper, and its transparent canvas shows the background you
set on the wrapper or parent.
For the optional toolbar, import its plain CSS through your application's CSS entry point or client entry:
@import '@toolpath/viewer/toolbar.css';Measurement labels and hover-card content need your own styling; the toolbar stylesheet does not style them. See Measuring and Theming.
Quick start
Pass a completed analysis report to EnginePart. It validates the report, loads
its mesh, and renders the result. It accepts unknown, so the viewer does not
require an SDK dependency just to display a report.
This example uses react-error-boundary:
npm install react-error-boundary'use client'
import { Suspense, useState } from 'react'
import { ErrorBoundary } from 'react-error-boundary'
import { Axes, Grid, ViewCube, Viewer, type FeatureTag } from '@toolpath/viewer'
import { EnginePart } from '@toolpath/viewer/engine'
export const PartViewer = ({ report }: { report: unknown }) => {
const [selection, setSelection] = useState<Array<FeatureTag>>([])
return (
<ErrorBoundary
fallback={<p role="alert">This part could not be displayed.</p>}
resetKeys={[report]}
>
<Suspense fallback={<p>Loading part…</p>}>
<Viewer style={{ height: 500 }} onPointerMissed={() => setSelection([])}>
<EnginePart
report={report}
selection={selection}
onPick={(pick) => setSelection(pick.best ? [pick.best] : [])}
/>
<Grid />
<Axes />
<ViewCube />
</Viewer>
</Suspense>
</ErrorBoundary>
)
}Suspense supplies loading UI; the error boundary handles invalid report data.
An accepted analysis job is not a report: finish the API workflow
before passing its result here. When changing parts/results, key PartViewer by
analysis-result identity to reset selection, the camera, and one-time overlay
bounds. Refreshing URLs for the same artifact does not require a new key.
How it works
- Geometry and tool dimensions are millimetres, with Z up. Vectors and stock must use the same coordinate frame; converting display units does not change mesh coordinates.
- Regions identify surfaces and cover half-open triangle ranges
[start, end). A feature refers to one or more regions. Several direction-dependent features can share one surface, so a click can have several valid owners. PartMeshemits picks and hover information. Your application owns selection, filtering, DFM rules, annotations, and persistence.- The viewer frames its content when it first appears and renders on demand.
It still renders during interaction and transitions; this is not a zero-cost
guarantee for an idle mounted scene. Call
fit()after later content changes when you want to reframe, or remount the viewer to start a new view.
Using it without the Engine
Supply a PartModel and a non-indexed three.js BufferGeometry. Region ranges
must cover every triangle without gaps or overlaps; buildRegionIndex validates
that mapping. Preserve triangle order when preparing geometry.
This complete example renders a 20 mm cube and disposes the caller-owned geometry on unmount:
import { useEffect, useMemo } from 'react'
import { BoxGeometry } from 'three'
import { PartMesh, Viewer, ViewCube, buildRegionIndex, type PartModel } from '@toolpath/viewer'
export const Cube = () => {
const { model, geometry } = useMemo(() => {
const indexed = new BoxGeometry(20, 20, 20)
const geometry = indexed.toNonIndexed()
indexed.dispose()
const regions = Array.from({ length: 6 }, (_, idx) => ({
idx,
splitOrigin: idx,
shapeKind: 'Plane',
area: 400,
triangles: { start: idx * 2, end: idx * 2 + 2 },
}))
const features = [
{
tag: 'top',
featureType: 'face',
machiningDirection: { x: 0, y: 0, z: 1 },
axis: null,
regionIdxs: [4],
},
]
const model: PartModel = {
partId: 'local-cube',
kernelVersion: '',
regions,
features,
candidateDirections: [{ x: 0, y: 0, z: 1 }],
mesh: { pointCount: 36, triangleCount: 12, glbUrl: null, stlUrl: null, thumbnailUrl: null },
regionIndex: buildRegionIndex({ regions, features, triangleCount: 12 }),
warnings: [],
}
return { model, geometry }
}, [])
useEffect(() => () => geometry.dispose(), [geometry])
return (
<Viewer style={{ height: 400 }}>
<PartMesh model={model} geometry={geometry} selection={['top']} />
<ViewCube />
</Viewer>
)
}The feature covers only the top face; surfaces without a feature remain drawable
and pickable, but have no pick.best. An application-supplied model does not go
through the Engine kernel-version gate. Keep geometry/model references stable
between renders. PartMesh manages its rendering resources, but never disposes
the input geometry; the caller owns that lifetime.
Selection and hover
Viewer identity is FeatureTag (model.features[i].tag, sourced from an Engine
report's featureTag). Do not replace it with an array index or an API
featureId. Region indices are local to their report and cannot join unrelated
results. FeatureType and ShapeKind allow unknown strings for newer data.
| PartPick field | Meaning |
| ------------------------- | ----------------------------------------------------------------------------------- |
| best | Highest-ranked feature tag, or null. |
| ranked | Owners ranked for the camera and active direction. |
| owners | All owners in report order, before active-direction filtering. |
| region, triangleIndex | Surface index and triangle hit. |
| point, normal | Hit position and outward normal; three-number tuples. The normal is in world space. |
| pointer | Optional browser clientX/clientY for DOM overlays. |
| modifiers | alt, ctrl, meta, shift, and secondary (right button). |
| doubled | This pick completed a double-click. |
| sharpCorner | Optional corner hit when sharp-corner visualization is enabled. |
onPick reports primary and secondary clicks. Decide whether secondary clicks,
double-clicks, or modifier keys should change selection. Double-click retargeting
still works independently. onHover receives a pick or null; hover={false}
disables hover feedback and callbacks while leaving click picking enabled.
This inspector shares selection between a list and the mesh, cycles overlapping owners on repeated clicks, and draws application-owned hover text:
import { useState } from 'react'
import type { BufferGeometry } from 'three'
import {
HoverCard,
PartMesh,
Viewer,
focusForPick,
type PartModel,
type PartPick,
} from '@toolpath/viewer'
export const FeatureInspector = ({
model,
geometry,
}: {
model: PartModel
geometry: BufferGeometry
}) => {
const [selected, setSelected] = useState<string | null>(null)
const [hovered, setHovered] = useState<string | null>(null)
const [pick, setPick] = useState<PartPick | null>(null)
const [lastRegion, setLastRegion] = useState<number | null>(null)
return (
<>
<ul>
{model.features.map((feature) => (
<li key={feature.tag}>
<button
type="button"
onClick={() => setSelected(feature.tag)}
onMouseEnter={() => setHovered(feature.tag)}
onMouseLeave={() => setHovered(null)}
>
{feature.featureType}: {feature.tag}
</button>
</li>
))}
</ul>
<Viewer style={{ height: 400 }} onPointerMissed={() => setSelected(null)}>
<PartMesh
model={model}
geometry={geometry}
selection={selected ? [selected] : []}
hoveredFeatureIds={hovered ? [hovered] : []}
focusFeature={selected}
onHover={setPick}
onPick={(next) => {
if (next.modifiers.secondary || next.doubled) {
return
}
setSelected(focusForPick(next, lastRegion, selected))
setLastRegion(next.region)
}}
/>
</Viewer>
<HoverCard pick={pick}>
{(current) => <span>{current.best ?? `Region ${current.region}`}</span>}
</HoverCard>
</>
)
}HoverCard is a DOM element; keep it outside the canvas and style its contents.
focusFeature frames the feature when its value changes. The focus prop is
different: focus={{ opacity: 0.12 }} makes regions outside selection
translucent. Its default outside opacity is 0.15, and an empty selection leaves
the part opaque. For multiselection, update your own tag array and avoid duplicates.
Components
| Component | Purpose |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Viewer | Canvas, camera, lighting, controls, initial framing, and viewer-owned section state. |
| EnginePart | Validated Engine report plus cached mesh loading; imports from /engine. |
| PartMesh | Your normalized model and prepared geometry; selection, paint, picking, sections. |
| ExplodedPart | A part pulled apart into supplied pieces, with layout, motion, paint and picking. |
| VisibilityGroup | Hides what it holds from drawing, framing and picking, and keeps it mounted. |
| ViewCube | 26 orientation targets: faces, edges, and corners. |
| Grid, Axes | Reference geometry excluded from camera framing. |
| DirectionArrows | Candidate and optional named/preview machining directions. |
| Stock | Geometry, GLB bytes, box, or cylinder stock. |
| SectionTool, SectionView | Interactive section placement or a supplied section visualization. |
| MeasureTool | Measures faces, holes and points by what is clicked, with labels. |
| ToolMarks | Supplied cutter/profile geometry and labels; no datasheet inference. |
| Banana | Optional bundled 154 mm scale reference; loads its GLB on mount and suspends. Also @toolpath/viewer/banana. |
| CadCameraControls | Lower-level camera controls for custom R3F scenes. Viewer already installs them. |
| ViewerToolbar | DOM controls configured through ViewerToolbarProvider. |
| viewerToolGroups | The toolbar controls in groups, with labels, notes and icons, for ToolDock. |
| HoverCard | Cursor-following DOM content for a pick. |
<Viewer>
| Prop | Default | Behavior |
| ----------------------- | ----------------- | ------------------------------------------------------------------------------------- |
| projection | orthographic | perspective is also supported. Changing it remounts the canvas and resets the view. |
| controls | toolpath | Navigation preset, independent of projection. |
| zoomTo | cursor | Zoom toward the pointer or centre. |
| freeOrbit | true | Allow rotation through the poles. |
| retargetOnDoubleClick | true | Double-click a part to move the orbit target there. |
| recentreOnDoubleClick | true | Double middle-click to fit content. |
| showOrbitTarget | false | Show the pivot marker. |
| theme | Default lighting | Override lighting; part/cube/tool colors have their own theme props. |
| onPointerMissed | — | Empty-space primary click, with drag guarding; use it to clear selection. |
| webglUnavailable | Default message | Content of the alert shown instead of the canvas when WebGL is unavailable. |
| style, className | Full-size wrapper | Set dimensions and background on the wrapper or parent. |
| ref | — | ViewerHandle for controls outside the canvas. |
ViewerHandle exposes fit(), reset(), setView(name),
setViewDirection({ x, y, z }), frameBox(box), and setSection(options | null).
fit and frameBox preserve view direction; reset returns to the opening view.
Named views are top, bottom, front, back, left, right, and isometric.
Direction vectors point from the part toward the camera.
Viewer checks for WebGL2 once per page, on the client. If the browser will not create a context
(hardware acceleration off or the GPU blocklisted), it renders a role="alert"
element (viewer-webgl-unavailable, data-viewer-webgl-unavailable="true") in
place of the canvas, asking the user to turn on graphics acceleration; children are
not rendered. Pass webglUnavailable to replace that message. Server rendering assumes
WebGL is available; the check runs on the client after hydration.
CAD controls
| Preset | Rotate | Pan | Zoom |
| -------------------- | ----------------------------------------------- | ------------------------------- | --------------------------- |
| toolpath | Left-drag | Right-drag | Wheel |
| fusion, inventor | Shift + middle-drag / Shift + two-finger scroll | Middle-drag / two-finger scroll | Trackpad pinch |
| alias | Left-drag | Middle-drag | Wheel |
| solidworks | Middle-drag | Ctrl + middle-drag | Shift + middle-drag / wheel |
| tinkercad | Right-drag | Shift + right-drag | Wheel |
| powermill | Middle-drag | Shift + middle-drag | Wheel |
| onshape | Right-drag | Middle-drag | Wheel |
CONTROL_SCHEME_OPTIONS supplies labels/values for a settings UI. Preferences are
application-owned.
On a touch screen, one finger orbits, two fingers pinch to zoom and move together
to pan, and three fingers pan. The pinch zooms an orthographic camera and dollies
a perspective one, as the wheel does. Fusion/Inventor use their CAD scroll
behavior for two fingers. ExtendedCameraControls exposes the same moves as
orbitBy(dx, dy, viewportMin), zoomAt(scale, at, viewport) and
panBy(dx, dy, viewport), in canvas pixels, for an application driving the camera
itself; constructed without an element, the controls listen to nothing and move
only through these.
<EnginePart>
report is its one required additional prop. It inherits PartMeshProps except
model and geometry, which it creates. Mesh loading prefers GLB and tries STL if
GLB fails or is absent. It does not fetch a report or start an Engine job.
withoutFeatures leaves features out of the part by tag, as withoutFeatures(model,
tags) does; see "Leaving features out".
Leaving features out
Some features the Engine reports are ones nothing machines: a T-slot whose
datasheet says no disc cutter can cut it, for one. withoutFeatures(model, tags)
leaves them out as if the report never listed them: out of model.features and
of the region index, so no pick resolves to them, directionHighlights paints
by the faces' other owners, and a face only they held is owned by nothing. The
faces stay drawn. Tags compare in any case; with none left out the model itself
comes back.
The tags come from the features' datasheets, which the report does not carry:
@toolpath/dfm's invalidFeatureTags(sheets). Until they are read, pass none,
and the part shows every feature.
import { useMemo } from 'react'
import { invalidFeatureTags, type FeatureSheets } from '@toolpath/dfm'
import { directionHighlights } from '@toolpath/viewer'
import { EnginePart, normalizePartReport } from '@toolpath/viewer/engine'
export const Part = ({ report, sheets }: { report: unknown; sheets: FeatureSheets }) => {
const leftOut = useMemo(() => invalidFeatureTags(sheets), [sheets])
// Any model the app builds beside the part leaves out the same features.
const wash = useMemo(
() => directionHighlights(normalizePartReport(report, { withoutFeatures: leftOut })),
[report, leftOut],
)
return <EnginePart report={report} withoutFeatures={leftOut} regionHighlights={wash} />
}Build every model the app reads from the same list, so the part, its own
direction wash and a plan editor's readings agree. EnginePart reads the list
by its tags, so a new array holding the same ones keeps the part; a change
rebuilds the part's paint against the mesh already loaded. A selection naming a
tag left out paints nothing; clear it in the app.
<PartMesh>
| Props | Behavior |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| model, geometry | Required normalized data and non-indexed geometry. |
| selection, candidates | Selected feature tags and secondary candidates. |
| highlights, regionHighlights | Feature/region colors. Hover and selection overlay the direction wash. |
| pickedRegions, hoveredFeatureIds | Application-driven region/feature feedback. |
| hover, onHover, onPick | Hover enablement and interaction callbacks. |
| focus, focusFeature | Selection X-ray rendering versus camera framing. |
| activeDirection | Candidate-direction index; null/omitted means all directions. |
| display, showEdges | solid or wireframe; outlines default on. Wireframe always shows semantic face boundaries, not triangle diagonals. |
| opacity | 0–1, default 1. Below 1 the part is see-through, drawn after solid parts; it still takes the pointer. |
| depthLayer | 0–63, default 0. Where two parts' surfaces coincide, the lower layer is drawn. |
| sharpCorners | { features: tags } for externally flagged features, or null. |
| threads | { threads: marks } to draw threads in their holes, or null. See "Showing threads". |
| section, onSectionChange | Controlled section options and change reporting. Omit section to follow the viewer's section store. |
| onAdjacency | Receive touching-region sets for the prepared mesh. |
| theme | Partial ViewerTheme for the part. |
| visible | false hides the part from drawing, picking and, outside a collection, framing; keeps paint, selection and cut. |
| children | R3F overlays that can read usePartContext(). Not hidden with the part: an <ExplodedPart> stands in for it. |
With an active direction, picking ranks only reachable owners; a face with none
has best === null. owners still carries all owners. directionHighlights(model,
index) produces region paint matching DirectionArrows; it does not hide geometry
or establish that an unpainted face is impossible to machine.
<ExplodedPart>
Pulls a part's surfaces apart into application-defined pieces, inside <Viewer> or an R3F
canvas. The application chooses the pieces and the approach each one moves out along; the
viewer spaces them, animates them, and draws, paints and picks them. It reads no planning data
and makes no API requests.
Place it inside the part it stands in for, and hide that part while the pieces are apart. A
child of <PartMesh> or <EnginePart> reads the part's model and mesh, and stays drawn while
visible={false} hides the part. Past EXPLODE_LIMITS the pieces draw nothing, so hide the
part only when explodeFits(model, groups):
import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'
import {
EnginePart,
ExplodedPart,
Viewer,
createExplodeMotion,
explodeFits,
explodeLayout,
usePartContext,
type ExplodeAssignment,
type ExplodeMotion,
} from '@toolpath/viewer'
// Inside the part, which supplies its model and mesh to the layout and the pieces.
const Pieces = ({
assignments,
motion,
shown,
selection,
onFits,
}: {
assignments: readonly ExplodeAssignment[]
motion: ExplodeMotion
shown: boolean
selection: readonly string[]
onFits: (fits: boolean) => void
}) => {
const { model, geometry } = usePartContext()
const groups = useMemo(
() => explodeLayout(model, geometry, assignments),
[model, geometry, assignments],
)
const fits = groups.length > 0 && explodeFits(model, groups)
useEffect(() => onFits(fits), [fits, onFits])
const explode = useMemo(() => ({ groups, amount: motion }), [groups, motion])
return <ExplodedPart explode={explode} visible={shown} selectedFeatures={selection} />
}
const ExplodingPart = ({
report,
assignments,
selection,
}: {
report: unknown
assignments: readonly ExplodeAssignment[]
selection: readonly string[]
}) => {
const [motion] = useState(() => createExplodeMotion(0))
const [fits, setFits] = useState(false)
const active = useSyncExternalStore(motion.subscribe, () => motion.getSnapshot().active)
// The pieces stand in for the part only when they draw.
const shown = active && fits
return (
<>
<button disabled={!fits} onClick={() => motion.moveTo(active ? 0 : 1)}>
{active ? 'Collapse' : 'Explode'}
</button>
<Viewer>
<EnginePart report={report} visible={!shown} selection={selection}>
<Pieces
assignments={assignments}
motion={motion}
shown={shown}
selection={selection}
onFits={setFits}
/>
</EnginePart>
</Viewer>
</>
)
}Hide what else is drawn with the part, such as stock or direction arrows, in a
<VisibilityGroup visible={!shown}>: kept mounted, and left out of drawing, Fit and every
raycast, which three.js would otherwise still run against hidden objects.
explodeLayout(model, geometry, assignments) places pieces. Each ExplodeAssignment has a
unique id, regionIdxs, a direction (null keeps the piece in place), a numeric RGB
color, and optional featureTags. Each piece moves clear of the part along its direction;
pieces sharing surfaces and a direction stack rather than overlap, in the order given. Grouping
policy stays with the application: one piece per feature, per setup, or per surface set.
Groups can also be written by hand. Each ExplodeGroup contains a unique id, regionIdxs,
an offset: { x, y, z } in millimetres in the source geometry's frame, a color, and
optionally featureTags and direction. Groups may contain any region set, and different
groups can share the same surfaces without being merged. Region IDs must come from the same
model and mesh. Source geometry must be non-indexed and match model.mesh.triangleCount. An
empty groups array draws nothing. Invalid IDs, regions, or offsets throw before allocation.
A layout past EXPLODE_LIMITS (4096 pieces, one million copied triangles) draws nothing;
explodeFits(model, groups) says so first, so an application can say why.
explode.amount interpolates all offsets from zero to their full translations. Values outside
[0, 1] are clamped and nonfinite amounts use zero. createExplodeMotion(initial, options?)
returns an amount that animates itself: moveTo(target) eases over 1800 ms for a full move,
in real elapsed time, pausing while the tab is hidden, and jumps instead where the person
prefers reduced motion; moveTo(target, { immediate: true }) jumps; set(amount) jumps now
and stops any move. A move waits until every <ExplodedPart> it drives has warmed its shaders
and buffers, so it starts on prepared pieces; one motion can drive several parts. For React
readouts, getSnapshot() returns { amount, mode, active, preparing }, a new object at most
ten times a second while moving: active means pieces are apart or moving and should be drawn
in place of the part, and preparing that a part is still warming. A plain number or a
createExplodeAmount(initial) controller still works where the application owns the clock;
optional onReady runs once a layout is warm. The renderer never moves the camera; Fit and
Reset remain explicit.
Keep the groups array stable across amount, selection, and color changes. Pieces take paint
as <PartMesh> does: highlights and regionHighlights color their surfaces as they are
colored on the assembled part. explode.colors (by group ID) and explode.regionColors (by
group ID, then region index) override colors without rebuilding the layout, and the latter win
over the paint. Unknown group/region keys are ignored. Color changes retain geometry buffers,
pick identities, and shader programs.
selectedFeatures and hoveredFeatures take feature tags, as <PartMesh selection> and
hoveredFeatureIds do: every piece whose featureTags include one is lit. A clicked piece takes
its own features' selection from their other pieces, until the selection that click produced
changes; pieces of the other selected features stay lit, so a click that adds to the selection
keeps the rest. The piece under
the pointer is lit and reported unless hover={false}. selected and hovered take group IDs
directly, one or several treated as one piece, and replace those. Selecting a piece highlights
its original surfaces and draws one connector from them to where it is.
onPick and onHover return an ExplodePick: the usual source region and triangleIndex,
the explodeGroupId, the displayed world-space point/normal, modelPoint in the source
geometry's frame, and explodeDirection, the group's direction or null. On a group with
featureTags, owners, ranked and best name only those features. Picking otherwise works
as on <PartMesh>: ranked from the orbit target, scoped by activeDirection, a right-click
judged on release, a double click reported as doubled and re-aiming the orbit, hover reported
once per piece and face, and nothing picked while a <SectionTool> holds the pointer. The
ghost of the source part and the source overlays do not accept picks, and a pick that finds
nothing passes to what is behind.
visible={false} retains buffers while excluding the pieces from rendering, picking, and
framing. theme?: Partial<ViewerTheme> styles the pieces: part colors the source ghost and
is what highlights paint covers, as on <PartMesh>, partEmissive sets emissive lighting, edge/edgeOpacity control the outlines, highlight
and hover tint the selected and hovered piece, and picked colors its source surfaces.
Without highlight and hover, pieces tint toward the viewer's selection colors, or toward
blue when the colors shown are mostly warm, as rule paint is, so the tint reads either way.
Theme changes update materials in place without rebuilding geometry or moving the camera.
<PartCollection>
Use PartCollection for a complete multi-body scene: meshes in a shared CAD
coordinate frame. Each item has a caller-owned id plus the existing PartMesh
props. Pick and hover callbacks receive (id, pick), and an item's leave is
reported before the next item's entry. Feature tags and region
numbers remain local to their item. Put scene tools inside the collection so
sections and grids use its combined bounds. Selection and visibility remain
controlled by the application. The collection draws one section cap and handle
for all of its items.
Inside a collection the nearest item stops pointer moves, clicks, and
right-button picks, so the bodies behind it, and handlers on the collection's
parent groups, do not receive them. A <PartMesh> on its own passes them on.
In React, load the meshes with usePartCollection(models, { concurrency? })
from /engine. Pass every body as { id, model }, keeping each model object the
same while it is unchanged, or as { id, key, model: () => PartModel }, which
builds the model only when the key changes, such as a report's job id. A builder
that throws is that body's failure. items is null until every body has
loaded, so the scene appears complete. failures lists the bodies whose latest
build or load failed, with kind saying which, and retry(id?) tries them
again, reusing the meshes that loaded. A new model for a body, such as its DFM analysis, loads while the body's
current mesh stays on screen, listed in waiting, and replaces it once ready;
paint the analysis's features only once the body has left waiting. The hook
frees meshes the scene stops showing, drops results for models since replaced,
and aborts loading on unmount. Geometry stays in CAD coordinates, and normals
are smoothed within regions.
import { Grid, PartCollection, SectionTool, Viewer, ViewCube } from '@toolpath/viewer'
import { usePartCollection } from '@toolpath/viewer/engine'
// models: [{ id: 'body-0', model }, { id: 'body-1', model }], each model kept stable
const Scene = ({ models }) => {
const bodies = usePartCollection(models)
if (!bodies.items) {
return bodies.failures.length ? (
<button onClick={() => bodies.retry()}>Retry failed bodies</button>
) : (
<p>Loading every body…</p>
)
}
return (
<Viewer>
<PartCollection items={bodies.items} onPick={(id, pick) => inspect(id, pick)}>
<Grid />
<SectionTool />
<ViewCube />
</PartCollection>
</Viewer>
)
}Without React, createPartCollectionLoader({ fetch?, signal?, concurrency? })
from /engine is what the hook runs on. load accepts { id, model } items and
resolves with ordered items and failures once every request has finished;
successful meshes stay cached for retries. After the scene renders a result,
pass everything it shows to keep(items): meshes it showed before and no
longer does are freed, and meshes a load returned that it has not shown yet are
held for it. discard(item) frees a mesh a load returned that will not be
shown, such as a result for a model replaced while it loaded. Call dispose()
after unmounting the collection. The loader owns
geometry; PartCollection does not.
To draw a body before its analysis, make its model from its part's display mesh
with displayMeshModel(mesh) from /engine: pass the Get part mesh
(GET /v1/parts/{id}/mesh) response as it is. Each face of the body becomes one
region, which draws its edges and shades each face on its own. A mesh without
face spans has no regions: it is drawn without edges, shaded flat, and offers
nothing to pick.
Each item takes the PartMesh props, so bodies can look different:
theme={{ part, partEmissive, hover }} colours one, and an opacity below 1
draws it see-through, for stock or a body that is not quoted. bodyColors(ids)
gives each id a colour from BODY_PALETTE, distinct for the first sixteen and
apart from the default hover; give copies of one body the same id to share one.
Bodies saved one on another, as successive stages of one part often are, share
surfaces. Where they do, the item earlier in items is drawn, rather than the
two fighting over each pixel; set an item's depthLayer (0 to 63, lower in
front) to put another body there, such as the one being pointed at. To show
one body at a time, as when stepping through a list of them, set the others'
visible to false: a hidden item draws nothing and lets the pointer through,
and showing it again rebuilds nothing. Its children are not hidden with it. It
still counts toward the shared bounds, so the frame, grid, and section do not
jump when a body is hidden.
To show a whole file and also one body as a part, switch between
<PartCollection> and <EnginePart> inside one <Viewer>, and call
ViewerHandle.fit() after switching, since the viewer frames its first content
only.
To pull the bodies apart so each one can be seen, pass explode={{ amount }}.
Each item moves as a whole, with its edges, paint, threads and children, by its
offset times the amount; picks, hover, and the section cap follow it. The
amount is a number from 0 to 1 or an ExplodeAmount, such as a
createExplodeMotion that animates itself: the collection reads it on each
frame with no React render, and needs no preparation, so it never holds a move.
explode.offsets sets each item's full displacement by id, in world units;
without it, collectionExplodeOffsets(items, { gap? }) places them: each body
moves out from the collection's centre towards its own, just far enough that its
bounding box clears the others by gap (a fraction of the collection's
diagonal, 0.05 by default). Bodies centred on the collection's centre, such as
nested ones, stack upwards instead. While explode is given, the shared bounds
hold the bodies both assembled and apart, so the grid and section stay put.
collectionBounds(items, { offsets }) measures that extent for framing:
const Exploding = ({ items }) => {
const viewer = useRef<ViewerHandle>(null)
const [motion] = useState(() => createExplodeMotion(0))
const offsets = useMemo(() => collectionExplodeOffsets(items), [items])
const explode = () => {
viewer.current?.frameBox(collectionBounds(items, { offsets }))
motion.moveTo(1)
}
return (
<>
<button onClick={explode}>Explode</button>
<Viewer ref={viewer}>
<PartCollection items={items} explode={{ amount: motion, offsets }} />
</Viewer>
</>
)
}The collection never uploads files or starts Engine analysis.
<ViewCube>, <Grid>, and <Axes>
ViewCube defaults to alignment="top-right" and margin={[80, 80]} (pixels).
onViewChange receives a ViewName, including diagonal names. Its theme controls
cube colors. Grid chooses a step from part size unless you supply step/extent;
it accepts color and opacity (default 0.35). Axes has a size in millimetres
(default 25). These controls/reference objects do not enlarge normal part framing.
Recipes
Toolbar and camera buttons
This scene uses caller-owned geometry. The provider supplies actions; it does not implement toggling, persistence, measurement state, or stock creation for you. The containing DOM element is positioned so the toolbar sits over this viewer.
import { useRef, useState } from 'react'
import type { BufferGeometry } from 'three'
import {
Axes,
Grid,
MeasureTool,
PartMesh,
SectionTool,
Stock,
ViewCube,
Viewer,
ViewerToolbar,
ViewerToolbarProvider,
type MeasureGroup,
type PartModel,
type ViewerHandle,
} from '@toolpath/viewer'
import '@toolpath/viewer/toolbar.css'
export const Workbench = ({ model, geometry }: { model: PartModel; geometry: BufferGeometry }) => {
const viewer = useRef<ViewerHandle>(null)
const [stock, setStock] = useState(false)
const [mode, setMode] = useState<'section' | 'measure' | null>(null)
const [measurements, setMeasurements] = useState<readonly MeasureGroup[]>([])
const toggle = (next: 'section' | 'measure') =>
setMode((current) => (current === next ? null : next))
return (
<ViewerToolbarProvider
controls={{
stock: { pressed: stock, onClick: () => setStock((shown) => !shown) },
section: { pressed: mode === 'section', onClick: () => toggle('section') },
measure: { pressed: mode === 'measure', onClick: () => toggle('measure') },
fit: { onClick: () => viewer.current?.fit() },
reset: { onClick: () => viewer.current?.reset() },
top: { onClick: () => viewer.current?.setView('top') },
}}
>
<div style={{ position: 'relative', height: 500 }}>
<Viewer ref={viewer}>
<PartMesh model={model} geometry={geometry}>
{mode === 'measure' && (
<MeasureTool measurements={measurements} onChange={setMeasurements} />
)}
</PartMesh>
{stock && <Stock box={{ partGeometry: geometry, allowance: { wall: 3, floor: 3 } }} />}
{mode === 'section' && <SectionTool />}
<Grid />
<Axes />
<ViewCube />
</Viewer>
<ViewerToolbar />
</div>
</ViewerToolbarProvider>
)
}Call Fit after toggling stock if you want to frame the blank. When switching from
Section to Measure, the viewer's existing cut remains until cleared with Escape
while the section tool is active or viewer.current?.setSection(null). The example
retains measurements in React state when the tool is unmounted.
With no children, ViewerToolbar renders configured controls in standard order.
For custom composition use ViewerToolbar.Controls, ViewerToolbar.Divider, and
its *Button components. A button without a matching provider control throws.
The supported action names are stock, axes, grid, banana, tools,
directions, dfm, sharpCorners, threads, hover, focus, wireframe, explode,
section, measure, fit, reset, and top; button names capitalize the action, such as
ViewerToolbar.SharpCornersButton. useViewerToolbar() reads those controls. A control with
disabled: true is shown greyed, and a click does nothing.
viewerToolGroups(controls, options?) describes the same controls for a toolbar
that groups, explains and pins its tools, such as @toolpath/ui's ToolDock. It
puts them in four groups (scene, dfm, tools, view), each tool with its
label, a line on what it does, its icon, whether it is on, and its onClick. A
control you did not supply is left out, and so is a group left with none.
explode is the last of the dfm group; it keeps one label, so pass
labels: { explode: 'Collapse' } while the part is apart. options.labels renames a tool, options.notes replaces its line, and
options.gates says why a tool cannot work yet:
import { ToolDock } from '@toolpath/ui'
import { viewerToolGroups } from '@toolpath/viewer'
const groups = viewerToolGroups(controls, {
gates: { directions: report ? null : 'Waits for the DFM check' },
})
export const PartTools = () => (
<ToolDock groups={groups} defaultLayout="grouped" defaultPins={['section', 'measure']} />
)Stock and display controls
Stock takes exactly one source. Stock stays in part coordinates, is included in
Fit/Reset, and does not intercept part picks or follow its section cut.
| Source | Input |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- |
| geometry | A caller-owned BufferGeometry; dispose it yourself after use. |
| glb | An ArrayBuffer of GLB bytes you fetched. Keep the buffer reference stable. Stock decodes/disposes its own geometry. |
| box preview | { partGeometry, allowance, offset? } or { partGeometry, dimensions, position?, positionOffset?, offset? }. |
| box resolved | { lower, upper, frame? }. |
| cylinder preview | { partGeometry, diameter, length, position?, positionOffset? }. |
| cylinder resolved | { origin, axis, diameter, length }; origin is the base center, axis points along its length. |
Allowances are per side: { wall, floor } expands X/Y and Z respectively;
a number or { x, y, z } is also accepted. The Workbench's 3 mm allowance is an
example, not a stock recommendation. Fixed preview dimensions are { x, y, z }.
Positions are model_centered, offset_from_top, and offset_from_bottom, with
positionOffset in millimetres. Preview options and resolved figures are mutually
exclusive. Use boxStockBounds / fixedBoxStockBounds for corresponding dimensions.
Centered stock is centered on the part's bounds. For top positioning its upper Z
is part.max.z + positionOffset; for bottom positioning its lower Z is
part.min.z - positionOffset. These rules also position cylinder previews along Z.
A box's optional frame has location, axis, and refDirection. Its local point
maps to location + x·refDirection + y·(axis × refDirection) + z·axis; the axis is
normalized and the reference direction projected perpendicular and normalized.
Without a frame, corners are already in part coordinates. A cylinder preview is
Z-aligned and centered on the part's bounding box. Treat previews as visualization;
prefer the operation's resolved stock when the selected API contract supplies it.
Negative/non-finite allowances, invalid coordinates, degenerate frames/axes, and
non-positive dimensions throw RangeError. GLB node transforms are applied without
centering, rescaling, or axis conversion. Stock does not fetch, cache, decompress
HTTP responses itself, or need an analysis report; the browser handles HTTP gzip.
Appearance props are color, emissive, flatShading, opacity (default 0.2),
edgeColor, edgeOpacity, and showEdges. renderStyle="legacy-workpiece" selects
the legacy two-pass material/edge appearance. With showEdges={false}, outlines
are not built until needed. retainPrevious applies to GLB playback: keep the
previous decode visible until the replacement is ready. Key the stock subtree by
part/calculation identity to prevent carrying geometry into a different run.
Without it, changing GLB bytes hides the previous geometry during decoding.
Migration from 1.x: replace removed BoxStock with Stock's box source.
StockProps is a union; use an intersection type rather than extending it with an
interface. StockAppearanceProps describes just the shared appearance options.
Direction coloring
Keep the same candidate index in PartMesh.activeDirection and the arrows. Use
shownDirection={null} for all arrows, an index/list to choose arrows, or -1
for none. activeDirection also scopes arrows when shownDirection is omitted.
previewDirection and namedDirections add non-candidate directions.
import { useMemo, useState } from 'react'
import type { BufferGeometry } from 'three'
import {
DirectionArrows,
PartMesh,
Viewer,
directionHighlights,
type PartModel,
} from '@toolpath/viewer'
export const DirectionViewer = ({
model,
geometry,
}: {
model: PartModel
geometry: BufferGeometry
}) => {
const [direction, setDirection] = useState<number | null>(null)
const colors = useMemo(() => directionHighlights(model, direction), [model, direction])
return (
<Viewer style={{ height: 400 }}>
<PartMesh
model={model}
geometry={geometry}
activeDirection={direction}
regionHighlights={colors}
/>
<DirectionArrows
directions={model.candidateDirections}
shownDirection={direction}
onPickDirection={(index) => setDirection((current) => (current === index ? null : index))}
/>
</Viewer>
)
}Arrows point toward the part. Picking an arrow does not clear selection through
onPointerMissed. Use groupByDirection, directionLabel, and directionColor
for a matching list/legend. Wireframe and direction coloring are independent props;
any mutual exclusion in the example app is application behavior.
Section view
Mount SectionTool inside Viewer beside a part with no explicit section prop.
It previews the surface under the pointer, places a cut on click, and offers X/Y/Z
planes. A drag handle moves the cut; Escape clears it while the tool is mounted.
It writes the viewer-owned section store and suppresses normal part hover/picks
while active. Unmounting the tool restores part interactions, not the uncut solid.
For application-controlled cuts, supply section directly. Here normal points
toward the retained half; offset ranges from 0 (whole part) to 1 (cut away).
import { useState } from 'react'
import type { BufferGeometry } from 'three'
import { PartMesh, Viewer, type PartModel } from '@toolpath/viewer'
export const SectionViewer = ({
model,
geometry,
}: {
model: PartModel
geometry: BufferGeometry
}) => {
const [offset, setOffset] = useState(0.5)
return (
<>
<label>
Section offset
<input
type="range"
min="0"
max="1"
step="0.01"
value={offset}
onChange={(event) => setOffset(Number(event.target.value))}
/>
</label>
<Viewer style={{ height: 400 }}>
<PartMesh
model={model}
geometry={geometry}
section={{ enabled: true, normal: { x: 0, y: 0, z: 1 }, offset }}
onSectionChange={(state) => setOffset(state.offset)}
/>
</Viewer>
</>
)
}Passing onSectionChange also enables the controlled cut's drag handle. The callback
reports SectionState, including enabled, normal, offset, plane, depth,
constant, and depth bounds. Use sectionFromPick({ point, normal }) to create a
surface placement, then { enabled: true, plane, depth } to cut inward by a depth
in millimetres. Pick tuples must be converted to { x, y, z } for that helper.
sectionMeasurement(state) supplies a readout for your own slider or label.
Measuring
MeasureTool mounts inside PartMesh or EnginePart, as their child. It has no
modes: what a click measures is read off what it lands on.
- A click on a face takes the whole face; on a hole, the whole hole, with how many of the same hole the part has.
- With Alt (Option) held, or with the
pointsprop, a click places a point, snapped to a corner, the middle of a straight edge, or an edge where one is near, and on the face where none is. - A second pick is read with the first where the two make a dimension: point to point (with X/Y/Z legs), point to plane, plane to plane (gap or angle), and a hole's centre line to a plane along its axis. Anything else starts a new measurement.
- Shift, or the
keepprop, keeps what is on screen and starts another. A click on a face already held drops it; Delete/Backspace drops the last pick unless focus is in a form field; a click off the part clears them all. - A double click aims the orbit at the point clicked, as it does without the tool, and measures once.
onChange reports readonly MeasureGroup[], each one pick or two; pass
measurements too to control and retain the list, as the Workbench does. Without
controlled state, unmounting the tool drops its measurements. An app's own Undo
button can set dropLastPick(measurements), which is what Delete does. Normal part
hover/picks are suppressed while measuring. Before a click, the face under the pointer
is tinted and a caption beside the pointer says what a click there takes.
The tool measures the part as a section cut leaves it. The cut face is solid to the
tool: an Alt point lands on it and snaps to its outline's corners, and nothing behind
it is offered. If a mounted SectionTool has no cut yet, measuring waits so its first
placement click is not also a pick. viewCube names the ViewCube's alignment
and margin when they are not the defaults, so clicks on the cube are left to it;
pass null when there is no cube.
Labels are unstyled DOM overlays with class toolpath-measure-label
(MEASURE_LABEL_CLASS); add CSS such as:
.toolpath-measure-label {
pointer-events: auto;
cursor: copy;
white-space: nowrap;
font:
600 12px/1.2 system-ui,
sans-serif;
color: white;
background: #141721dd;
border: 1px solid var(--measure-color, #4f8ef7);
border-radius: 4px;
padding: 2px 6px;
}
.toolpath-measure-label[data-measure-label='delta'] {
font-size: 11px;
}
.toolpath-measure-label[data-copied]::after {
content: ' Copied';
}
.toolpath-measure-hint {
padding: 1px 6px;
border-radius: 4px;
background: #000000b3;
color: white;
font:
500 11px system-ui,
sans-serif;
}data-measure-label is face for a reading of the picks or delta for one leg of a
distance, and legs also have data-axis. Each measurement has its own colour, set on
its face labels as --measure-color. A click on a label copies its number, from its
[data-measure-value], and marks the label data-copied for a moment. With
onLabelPress, the click calls it with { text, value } instead, the label as drawn
and its bare number, and nothing is copied. A label takes the pointer only where the
stylesheet gives it pointer-events: auto. Labels that would overlap are moved apart
by their inline translate, which leaves a stylesheet's transform alone. The caption
by the pointer has class toolpath-measure-hint (MEASURE_HINT_CLASS) and is placed
but not styled. labelClassName adds a class. Lengths default to millimetres; the
format(mm) callback changes their displayed string, not geometry units or angles
(which remain degrees).
On React Native the same MeasureTool takes taps. There is no Alt, Shift or Delete,
so an app gives the choices as props: points for points, keep to keep what is on
screen, and dropLastPick for its Undo. A tap off the part clears, a pinch's lift is
not a tap, and a double tap aims the orbit. With no hover, what was tapped stays
painted until the measurements are cleared. Labels are drawn as
native labels (scene-label-face, scene-label-delta),
pressable only when onLabelPress is given. What a press does is the app's, so
labelHint says it to a screen reader, such as "Copies the measurement"; without it a
pressable label is announced as a button with no hint. labelHint is ignored on the
web, and labelClassName on React Native.
Showing threads
The Engine cuts a modeled internal thread out of the mesh, so a tapped hole arrives as a
plain bore. Pass threads={{ threads: marks }} to draw each thread back in as shading
over its hole's cylinders, at its pitch and hand. Build a mark from a hole's Engine
datasheet with threadMark(feature, datasheet) from @toolpath/viewer/engine; it is
null unless the datasheet carries a thread, so only threads the Engine reports are
drawn. A ThreadMark is { regions, pitch, majorDiameter }: pitch is in mm and
negative for a left-hand thread, and cylinders wider than majorDiameter (a counterbore)
stay plain. The axis is fitted from the mesh, so marks need no coordinates. The datasheet
gives no thread length, so a tap-drill section of the same bore below the thread is
drawn threaded too.
Showing sharp corners and tool marks
DFM decisions belong to the application. Pass flagged feature tags as
sharpCorners={{ features: tags }}; the viewer draws qualifying inside corners
along those features' machining directions. It does not flag features or guess
missing manufacturing data. Use a closed mesh with report region boundaries;
findSharpCorners/sharpCornerPositions operate on surfaceCreases for custom
inspection. A hovered corner appears as pick.sharpCorner with its feature,
endpoints, length, and angle. Feature tag matching for these flags is case-insensitive.
Mount ToolMarks under a part to illustrate supplied cutters or profiles. For
example, this is a 6 mm bull-nose cutter standing along +Z:
import type { ToolMark } from '@toolpath/viewer'
export const toolMarks: Array<ToolMark> = [
{
base: { x: 12, y: 4, z: -8 },
axis: { x: 0, y: 0, z: 1 },
diameter: 6,
height: 8,
cornerRadius: 0.5,
label: '⌀ 6 mm',
note: 'Bull nose R 0.5',
},
]Use ToolMarks's marks prop for that array. A ToolMark can instead supply a
rotational profile of { r, z } points. visible toggles display;
labelClassName styles labels. Marks use the measure-label CSS hook with
data-measure-label="tool", optional value/note spans, take no pointer events,
and are excluded from camera framing. They do not read datasheets themselves.
Labels in the scene
SceneLabel pins a text label to a point in the scene. On the web it is an
unstyled DOM element over the canvas with the MEASURE_LABEL_CLASS class plus
className, data-measure-label={kind}, and optional data-axis and
data-measurement-id; its text is in a data-measure-value span and its note
in a data-measure-note one. color sets --measure-color, layer its z-index
layer, and it takes no pointer events. ToolMarks draws its labels with it.
<SceneLabel kind="note" position={[0, 0, 25]} text="Datum A" className="part-note" />Theming
Colors in ViewerTheme are numeric hex values. Set lighting on Viewer, part
colors on PartMesh/EnginePart, and overlay colors on their components; passing
part colors only to Viewer does not theme its children automatically.
DEFAULT_THEME lists the keys. Selection palettes are HIGHLIGHT_COLORS; direction
colors cycle through DIRECTION_COLORS.
Part keys include part, partEmissive, hover, highlight, picked, edge,
edgeOpacity, and sharpCorner. Section keys include sectionCap, sectionHatch,
sectionOutline, sectionHandle, and sectionHandleOutline. ToolMarks uses
measure (measureSnap is unused and deprecated); cube keys are cube, cubeEdge, and cubeLabel.
The canvas background comes from the wrapper/parent, independently of those colors.
labels (optional, CSS colour strings) styles scene labels on React Native, where
there is no DOM to style; see React Native (Expo).
Stable DOM classes include viewer-root, viewer-webgl-unavailable,
viewer-canvas-container, viewer-canvas-frame, viewer-canvas, viewer-hover-card,
viewer-toolbar-stack, viewer-toolbar, viewer-toolbar-button, viewer-toolbar-icon,
viewer-toolbar-tooltip, and viewer-toolbar-divider. Caller className values
append to the component's hook. Corresponding data-viewer-* attributes identify
the DOM boundaries; data-viewer-toolbar-action contains the control's action name.
Style the hover card yourself; it is a pointer-events-free fixed-position shell.
Custom R3F objects can go inside Viewer and participate in framing. Set
userData={{ [EXCLUDE_FROM_FRAME]: true }} to exclude an object. Use the exported
EXCLUDE_FROM_FRAME constant, not a guessed string.
React Native (Expo)
The package runs under React Native through Metro: React Three Fiber's native
build (@react-three/fiber/native) on expo-gl. Import it exactly as on the web.
Its react-native export condition gives Metro a native build of both
@toolpath/viewer and @toolpath/viewer/engine, built from the package's
.native files where it has them. The native root leaves out the web-only
exports.
| Export | Web | React Native |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --- | ----------------------------------- |
| Viewer, PartMesh, EnginePart, ExplodedPart, PartCollection, VisibilityGroup, Stock, DirectionArrows, SectionView, SectionTool, MeasureTool, ToolMarks, Axes, Grid, ViewCube, SceneLabel | yes | yes |
| Banana, BANANA_MODEL_URL | yes | from @toolpath/viewer/banana only |
| Every pure function, constant and type from the models, rendering helpers and Engine adapter | yes | yes |
| HoverCard, ViewerToolbar, viewerToolGroups, labelTexture, createExplodeMotion | yes | no: not exported |
| ViewerToolbarProvider, useViewerToolbar | yes | yes (the context has no DOM) |
On React Native, one finger orbits, two fingers pinch to zoom and pan, and a tap
picks, as on the web; double tap re-targets. A tap on a face with SectionTool
up cuts, and the handle drags the cut. With MeasureTool up a tap measures; see
Measuring.
The react-native condition also gives TypeScript the native build's own
declarations (with customConditions: ["react-native"], which Expo's base
tsconfig sets). There, Viewer's style is a View's StyleProp<ViewStyle>,
for the View that holds the canvas, and Viewer has no className or
webglUnavailable: expo-gl always creates a context.
The canvas has nothing a screen reader can read, so pass Viewer an
accessibilityLabel (and an accessibilityHint, such as where the view's
controls are) for VoiceOver and TalkBack to announce the view as an image. The
scene's pressable labels stay reachable on their own.
A finger doesn't hover, so on React Native PartMesh and ExplodedPart light no
face under a moving finger, and onHover isn't called. PartMesh's picks go
through a bounding volume hierarchy
(three-mesh-bvh), built once
per geometry and kept with it, so a large part stays smooth to touch under
Hermes.
App setup
Install the native modules with Expo, and three.js, React Three Fiber 9.7 or later, and drei:
npx expo install expo-gl expo-asset expo-file-system npm install @toolpath/viewer three @react-three/fiber @react-three/dreiIn
metro.config.js, wrap the app's config inwithToolpathViewer:const { getDefaultConfig } = require('expo/metro-config') const { withToolpathViewer } = require('@toolpath/viewer/metro') module.exports = withToolpathViewer(getDefaultConfig(__dirname))It gives the app one copy of three.js. Fiber's native build
requires three, which would otherwise resolve tothree.cjsbeside thethree.module.jsthat ESM imports get, andinstanceofchecks between the two copies fail; from three 0.186,three.cjsalso callsprocess.emitWarning, which
