Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

three-cad-viewer

> 编程语言
Open source

A CAD viewer component based on three.js

381 stars0 likes0 views
WebsiteGitHub

About

A CAD viewer component based on three.js

A threejs based CAD viewer

A CAD viewer component based on three.js. The CAD viewer can visualize low level threejs objects (tessellated objects)

⇒ Live Examples

Getting started

  1. Install yarn on your system (ie. npm i -g yarn) if not already done;
  2. Clone the repository: git clone https://github.com/bernhard-42/three-cad-viewer.git && cd three-cad-viewer;
  3. Run yarn install to install dependencies
  4. Start web server: yarn run start and go to the page displayed in the logs (ie. 127.0.0.1:8080)
  5. Build project: yarn run clean; yarn run build; yarn run docs;

Overview

Shape and Shapes

A Shape contains the attributes

  • vertices (the BufferGeometry attribute position)
  • triangles (the triangle index of the BufferGeometry)
  • normals (the BufferGeometry attribute normal)

as described e.g. in BufferGeometry or Three.js Custom BufferGeometry

plus additionally the attribute

  • edges

to define which edges of the mesh should be shown.

The 4 attributes (vertices, triangles, normals, edges) define an object called Shape, see Class Shape

Multiple Shapes can be arranged as an hierarchical tree. This tree is modelled as Shapes object, see Class Shapes

The ids on each level define a path to each node and leaf of tree, e.g. /level1/level2_obj1/level3_object7 and so on.

States

For each leaf of the tree a 2 dim tuple needs to be provided to define whether shape and edges should be shown

  • 0 = shape/edges hidden
  • 1 = shape/edges shown
  • 3 = shape/edges does not exist

The value 2 is reserved for nodes and shows a mixed state, i.d. some of the children are show, some not.

For the States object, see Class States

Skeleton:

xml

  
    
    

  

  
    

  

Dynamic Scene Updates

After the initial viewer.render(), parts can be added, removed, or updated without re-rendering the entire scene.

addPart / removePart

addPart(parentPath, partData) creates new Three.js objects (meshes, edges, clipping stencils) from the part data and inserts them into the scene graph and navigation tree. removePart(path) disposes the Three.js objects and removes the part from the scene.

javascript
viewer.addPart("/Group", partData); // creates "/Group/PartName"
viewer.removePart("/Group/PartName");

updatePart

updatePart(path, partData) updates an existing part's geometry without tearing down and recreating the Three.js objects. When the mesh topology is unchanged (same number of vertices, triangles, and edge segments), vertex positions, normals, and edge coordinates are written directly into the existing GPU buffers — this is significantly faster than a remove/add cycle. When the topology differs (e.g. a re-tessellation changed the face or edge count), updatePart automatically falls back to a batched removePart + addPart so the caller does not need to handle this case.

javascript
viewer.updatePart("/Group/PartName", updatedPartData);

Batching

Each of the three methods individually recomputes the bounding box, rebuilds clipping stencils, and (for add/remove) rebuilds the navigation tree. In a loop over N parts this becomes the dominant cost. All three methods accept an optional { skipBounds: true } parameter that defers this work. Call updateBounds() once after the loop to perform a single recomputation for the entire batch:

javascript
for (const part of partsToUpdate) {
  viewer.updatePart(`/Group/${part.name}`, part, { skipBounds: true });
}
for (const part of partsToAdd) {
  viewer.addPart("/Group", part, { skipBounds: true });
}
for (const path of pathsToRemove) {
  viewer.removePart(path, { skipBounds: true });
}
viewer.updateBounds();

Add, remove, and update calls can be freely mixed within a single batch.

ensureStencilSize

updateBounds() rebuilds clipping stencils whenever the scene's bounding box grows beyond the region that stencils were previously built for. This rebuild is the most expensive part of the bounds update. When the maximum extent of the geometry is known upfront (e.g. the full parameter range of a slider), call ensureStencilSize() once after the initial render to pre-size the stencil region. All subsequent updateBounds() calls whose geometry stays within this region will skip the stencil rebuild entirely:

javascript
viewer.render(shapes, renderOptions, viewerOptions);

viewer.ensureStencilSize({
  xmin: -200,
  xmax: 200,
  ymin: -200,
  ymax: 200,
  zmin: 0,
  zmax: 300,
});

// All updates within these bounds are now stencil-rebuild-free

Keyboard Shortcuts

The keymap serves two purposes:

  • Modifier keys (shift, ctrl, meta, alt) remap which physical modifier key is used for mouse interactions (e.g. shift-click to isolate, ctrl-rotate). Values are DOM event properties like "shiftKey", "ctrlKey", "metaKey", "altKey".
  • Action shortcuts map single keys (with or without Shift) to toolbar buttons, camera presets, tab switches, and animation control. Only plain keys are supported — Ctrl/Alt/Meta combinations are reserved for modifier-based mouse interactions.

Click on the viewer to give it focus, then press shortcut keys to trigger actions. Button and tab tooltips show a › key suffix when shortcuts are configured.

The default keymap:

…

Pass a partial keymap to override individual bindings — unspecified keys keep their defaults:

javascript
const displayOptions = {
  keymap: { axes: "q", reset: "!" }, // only these two change
};

Topo filter shortcuts. When the shape filter is visible (B-rep models), the lowercase keys a (All), v (Vertex), e (Edge), f (Face), s (Solid) set the picking filter. These are fixed (not part of the configurable keymap) — which is why axes and studio default to the uppercase A/S.

Examples

To understand the data format, a look at the simple 1 unit sized box might be helpful:

  • 1 unit sized box source code
  • addPart / removePart demo — dynamically adding and removing shapes and subtrees after render

APIs of Viewer, Display, Camera and Controls

  • API docs

Back to Github repo

Utilities

Logger

Control log verbosity with the built-in logger:

javascript
import { logger } from "three-cad-viewer";

// Default level is "warn" (only warnings and errors shown)
logger.setLevel("debug"); // Enable all logging
logger.setLevel("info"); // Info, warnings, and errors
logger.setLevel("warn"); // Warnings and errors (default)
logger.setLevel("error"); // Only errors
logger.setLevel("silent"); // Disable all logging

GPU Resource Tracker

Track GPU resource allocation to inspect current state or detect memory leaks:

javascript
import { gpuTracker } from "three-cad-viewer";

// Check resource counts at any time
console.log(gpuTracker.summary);
// { geometry: 5, material: 10, texture: 1, total: 16 }

// Log details of allocated resources
gpuTracker.details();

For detailed allocation info with stack traces:

javascript
// Enable debug mode BEFORE creating the viewer
gpuTracker.enableDebug();

const display = new Display(container, displayOptions);
const viewer = new Viewer(display, viewerOptions, nc);
viewer.render(shapes, renderOptions, viewerOptions);

// Inspect current allocations
gpuTracker.details();
// [1] geometry: BufferGeometry (shape) for /Assembly/Part1
//     Created at: 1234.56ms
//     Stack:
//       at NestedGroup.renderShape (nestedgroup.ts:425)
//       ...

// After disposal, any remaining resources are potential leaks
viewer.dispose();
gpuTracker.details();

The tracker is also available globally in the browser console as window.tcv_gpu.

Development

Run a web server in watch and debug mode

bash
yarn run debug

For the deployment, see Release.md

Changes

see Changes.md

Credit

  • The toycar example is downloaded from https://grabcad.com/library/toy-rider-car-1 and tessellated

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言