Skip to main content

threejs-viewer

Lightweight Three.js viewer controlled from Python via WebSocket.

A textured extrusion bead being printed layer by layer

A Python client runs a WebSocket server that a browser-based Three.js viewer connects to. Designed for robotics visualization, additive manufacturing and machining toolpaths, scientific computing, and interactive 3D exploration. The browser tab survives Python restarts and reconnects on its own.

VS Code integration

Features

  • Simple API: Add primitives, load models, update transforms
  • PBR materials: Roughness, metalness, transparency, environment reflections and a shadow-casting sun on all objects
  • GLB/PBR support: Load GLB models with PBR materials, embedded skeletal/morph animations, Draco compression
  • Animation support: Pre-compute animations, scrub timeline, adjust playback speed
  • Binary channels: Efficient transfer of large animations (100k+ objects × frames)
  • Toolpath visualization: Extruded bead tubes with per-point colors, draw_range animation, and automatic LOD — handles 1M+ point toolpaths at 60 fps with smooth camera-distance-adaptive simplification via Web Worker
  • Bead textures: A colour, normal and roughness map wrapped around the bead and repeated along the path, so a printed part reads like extruded plastic (die lines, sharkskin ripple, chopped fibres)
  • 5-axis swept tool body: add_swept_tool lofts an oriented shank/holder profile about the per-station tool axis (decoupled from the path tangent) into a swept surface — visualizes 5-axis reorientation rate and tool-body collisions, with per-station heatmap colours and draw_range reveal
  • GPU point clouds: add_points renders millions of unconnected points (voxel fields, metrology/deviation clouds, LiDAR scans) in a single THREE.Points draw call, with per-point colormap colours, distance size-attenuation, and draw_range reveal
  • Live point streaming: append_points grows an existing cloud in place — only the new points cross the wire and only they are uploaded to the GPU, so a producer streaming for hours (a laser tracker at 1 kHz) stays O(new points) per update instead of re-sending the whole cloud
  • Per-point time windows: give each point a [birth, removal) lifetime and scrub a global time — points appear/disappear out of buffer order in the vertex shader (material-removal animations that a prefix reveal can't express), driven live or from the animation slider
  • Octree LOD streaming: add_points(lod=True) builds a Potree-style sampled octree in Python and streams node payloads on demand — draw a ~1.5M-point budget of the biggest-on-screen nodes out of clouds far larger than one draw call, refining as you zoom; composes with the time windows at every LOD
  • Interaction from the browser back to Python: pick a point along any line or bead, click objects, drag move/rotate gizmos, drag axis-control range widgets, press shortcuts on client-defined menus; every event lands in a Python callback
  • Annotations and section views: linear dimensions and labelled points, an interactive clipping plane or slab with gizmos, a shader floor grid, fog and eye-dome lighting depth cues for dense line drawings
  • Auto-reconnect: Browser reconnects automatically, animations persist
  • Z-up coordinates: Robotics convention (matches ROS, URDF)
  • No build step: Self-contained HTML viewer, just open in browser

Installation

pip install threejs-viewer

Quick Start

from threejs_viewer import viewer

# Start server and wait for browser to connect
v = viewer()

# Add objects
v.add_sphere("ball", radius=0.3, color=0xFF0000, position=[0, 0, 0.5])
v.add_box("ground", width=5, height=5, depth=0.1, color=0x444444)

# Keep running
input("Press Enter to exit")

The viewer opens automatically in your default browser. To open it manually:

threejs-viewer open
# Or: threejs-viewer path  (prints path to viewer.html)

Every image except the dimension annotations comes from a script in examples/, named under each one; tools/record_readme_media.py re-records them.

Toolpaths and beads

Textured bead, close-up of a corner Textured printed part
Colour + normal + roughness maps follow the bead around every corner. 37_bead_texture.py The same part: one continuous 8 x 3 mm bead, 14 layers, overhanging round side. 37_bead_texture.py
Six vases printed from a 1.2M-point toolpath Spiral vase printed by a draw_range animation
Six spiral vases from one 1.2M-point toolpath with tube LOD, round joins, travel hops and a nozzle on set_follow_path, coloured by wall lean. 40_million_point_toolpath.py A spiral vase bead revealed by a draw_ranges channel, viridis colours tinting the texture. 11_toolpath.py
Interrupted toolpath with travel moves Tube break mask
Travel moves taper the bead to zero width. 15_toolpath_interrupted.py Front: one spine bridging three rings with stray cones. Back: the same spine with break_before, three capped strips. 28_tube_breaks.py
5-axis swept tool body
A tilting tool lofted along a contact path, coloured by reorientation rate. 26_swept_tool.py

Point clouds

Deviation point cloud draw_range sweep over a point cloud
A million-point machined surface coloured by signed deviation, one draw call. 25_point_cloud.py The same cloud revealed along the toolpath by draw_ranges. 25_point_cloud.py
Octree LOD with birth and removal times Live point stream
Octree LOD streaming node detail on demand while a build front adds points and an erosion front removes them, out of buffer order. 27_points_octree_lod.py append_points growing a cloud a few thousand points at a time, only the new points cross the wire. 30_live_points_stream.py

Lines, picking and depth cues

Fog and eye-dome lighting on a dense polyline Polyline picking
A million-point native polyline under distance fog + eye-dome lighting (D / Shift+D). 20_line_depth_cues.py Hovering a line or bead glides a marker to the closest point and reads out the arc-length fraction; a click reaches Python. 22_polyline_picking.py

Models and animation

Robot cell posed by forward kinematics 600 primitives streamed at 60 fps
A 6-axis arm on a rail doing a pick-and-place, posed in the viewer from joint-space keyframes with set_kinematic_chain. 14_robot_cell.py 600 primitives racing along a million-point torus knot, every pose sent from Python in one batch_update per frame. 07_stress_test.py
Animation stress test Flying teapots
The same scene pre-computed as one Animation: 600 objects x 1800 frames in binary transforms and colors channels. 10_animation_stress_test.py A ring of OBJ teapots on a seamless looping animation. 04_flying_teapots.py
GLB models with PBR materials PBR material sampler
DamagedHelmet and Avocado with the built-in HDR environment. 08_glb_models.py Thirty labelled PBR materials from one glTF (clearcoat, sheen, anisotropy, IOR). 31_watch_gltf.py
Billboards
Checkered donuts in every set_billboard mode, kept facing the camera. 34_billboard_modes.py

Interaction and scene furniture

Click-to-inspect with dimensions Section caps
Clicking a part outlines it, frames it and adds its dimensions, all from a Python on_object_click callback. 39_cad_inspection.py A clipping slab with set_clipping_caps(True): primitives, a printed wall and a swept tool body cut as solids. 16_section_caps.py
Pinned move gizmos Axis-control range widgets
Six pinned gizmos: 1-, 2- and 3-DOF, in world and local space; drags report back to Python. 24_gizmo_dimensions.py Rotary and linear range widgets anchored to their target objects. 36_axis_control.py
Dimension annotations Shader floor grid
Linear dimensions, a diagonal and labelled points on a box. add_dimension / add_point_annotation An anti-aliased, distance-faded floor grid with screen-space-stable line width. 29_floor_grid.py
Client-defined menu Lighting panel
A Python-defined menu on the right rail: eyes, toggles, selects and shortcuts round-trip to Python. 35_client_menu.py The E panel: tone mapping, exposure, environment map, ambient and sun. 01_primitives.py with E pressed

Usage

Objects

from threejs_viewer import Toolpath, viewer

# Primitives with PBR materials
v.add_box("box1", width=1, height=2, depth=0.5, color=0x4A90D9, roughness=0.5, metalness=0.1)
v.add_sphere("ball", radius=0.5, position=[2, 0, 0], roughness=0.3, metalness=0.7)
v.add_cylinder("cyl1", radius_top=0.3, radius_bottom=0.5, height=1)

# 3D models (binary transfer)
v.add_model_binary("robot", "robot.stl", format="stl")

# Polylines with colormaps
v.add_polyline("path", points, colors=z_values, colormap="viridis", line_width=3)

# Bead toolpath (parametric tube, built client-side)
tp = Toolpath.from_points(points, bead_width=0.3, bead_height=0.08)
tp.colorize(per_point_rgb)
v.add_toolpath("bead", tp)

# Bead texture: colour + normal + roughness maps wrapped around the bead,
# repeated every `texture_length` units of path (examples/tools/bead_texture_maker.py
# generates a tiling extruded-plastic set)
v.add_toolpath("bead", tp, texture="bead_color.png", normal_map="bead_normal.png",
               roughness_map="bead_roughness.png", texture_length=25.0, roughness=1.0)

# Transparency
v.set_opacity("box1", 0.5)
v.set_color("ball", 0xFF0000, opacity=0.3)

Vector entities (DXF-style curves)

Circles, arcs, ellipses, NURBS splines, polylines with DXF bulges, lines and points keep their exact definitions in the viewer and re-tessellate as the camera moves, so they stay smooth at any zoom. Layers and linetypes work as in DXF: entities default to their layer's colour, linetype and width.

import math
from threejs_viewer import vector

v.set_layer("CENTER", color=0xFF6E6E, linetype="CENTER", line_width=1)
v.set_linetype("MYDASH", [0.01, -0.005, 0, -0.005])   # dash, gap, dot, gap (scene units)

v.add_circle("hole", [0, 0, 0], 0.035, color=0x5AB4FF)
v.add_arc("arc", [0, 0, 0], 0.09, 0, math.pi / 2, layer="CENTER")
v.add_spline("cam", control_points, degree=3, weights=w, closed=True)

# Many entities in one object, batched into a few draw calls per layer
v.add_vector_entities("drawing", [
    vector.line([-0.1, 0, 0], [0.1, 0, 0], layer="CENTER"),
    vector.polyline(slot_corners, bulges=[0, 1, 0, 1], closed=True),
    vector.ellipse([0, 0, 0], [0.02, 0, 0], 0.5, linetype="MYDASH"),
])
v.set_layer("CENTER", visible=False)   # hides the layer in every object

# Blocks and inserts (DXF BLOCK / INSERT / MINSERT): define once, place many
# times. The block is tessellated once per detail level; copies are transformed.
v.add_vector_entities(
    "bolt_pattern",
    [vector.insert("HOLE", bolt_centres, layer="HOLES"),
     vector.insert("HOLE", [0, 0, 0], rows=4, columns=6,
                   row_spacing=0.02, column_spacing=0.02, scale=0.5)],
    blocks={"HOLE": [vector.circle([0, 0, 0], 0.004), vector.circle([0, 0, 0], 0.006, linetype="HIDDEN")]},
)

examples/42_vector_entities.py draws a flange with bolt holes, slots, centre lines and a NURBS cam.

Layers and linetypes are viewer-wide: every vector object, including those loaded from glTF files, shares one table per name. A curve piece is drawn with at most 8192 segments, so a very large arc viewed at extreme zoom (radius above roughly ten million pixels) shows facets. set_highlight draws nothing on vector objects.

glTF and GLB files can carry the same entities in root extras.TJSV_vector_entities (the only place that survives glTF-Transform, Draco included). add_model / add_model_binary draw them with the model, merge the file's layers and linetypes (tables set from Python win), and hide fallback line primitives whose material extras carry {"TJSV_vector_entities": {"fallback": true}}. The format is described in plans/gltf-vector-entities.md.

USD BRep geometry

# Needs the usd_brep package, which tessellates the exact geometry.
# Shaded faces plus BRep edges; takes a usd_brep Brep or a USD file path.
v.add_usda(brep)
v.add_usda("part.usda")

# Calling it again with the same id replaces the geometry in place.
# Handy for re-running a modelling script or reloading a file when it changes.
v.add_usda("part.usda", id="part")

examples/38_usd_connecting_rod.py models an engine connecting rod and shows it on a floor grid.

Connecting rod modelled with usd_brep booleans

Transforms

# Single object
v.set_matrix("box1", matrix_4x4.flatten().tolist())

# Batch update (efficient for 60fps)
v.batch_update({
    "link1": {"position": [1, 2, 0.5]},
    "link2": {"position": [3, 0, 1], "rotation": [0, 0, 1.57]},
})

Picking points on lines & beads

# Click a point anywhere along any polyline or parametric tube; the pick
# travels back to Python. Hovering glides a marker to the closest point.
def on_pick(pick):
    print(f"{pick['kind']} {pick['id']}: {pick['fraction']:.1%} along  at {pick['point']}")

v.on_polyline_pick(on_pick)   # also enables picking

Each click sends {id, kind, fraction, point, local_point, segment, t} where kind is "line" or "tube". Movement is continuous — the marker never snaps to vertices. Picking is opt-out per object — pass pickable=False to add_polyline / add_parametric_tube to exclude one from picking (it stays rendered); adding objects costs nothing when picking is never enabled. For a tube, segment indexes the full-resolution spine 1:1 with the per-point arrays you built it from, so it doubles as a lookup key for other per-point data at the picked point. A browser embedder can subscribe in JS instead — viewer.onPolylinePick(cb) (click) / viewer.onPolylineHover(cb) (every hover move) — for a live readout with no Python round-trip. See examples/22_polyline_picking.py. A spine of more than 2048 points is scanned through a box index of 64-segment runs, so a hover costs well under a millisecond on a 400k-point tube (about 80 ms with a full scan) and finds the same point.

A fractional set_draw_range (or draw_range channel value) on a connected fat polyline draws the last visible segment up to the exact point, as a parametric tube's frontier does, so a reveal grows smoothly instead of segment by segment; picks stop at the cut. hasFeature('line_draw_frontier') marks it. Native (fat=False) lines and disjoint segments still cut at whole vertices.

Camera projection and plan views

# An orthographic plan view of one slice of a path, seen along its plane normal.
v.set_camera(position=[0, 0, 5], target=[0, 0, 0], up=[0, 1, 0],
             projection="orthographic")   # pose and projection in one frame
v.set_projection("perspective")            # or switch on its own
v.get_camera()["projection"]               # "perspective" | "orthographic"
v.set_navigation(rotate=False, left_button="pan")   # pan and zoom only

While rotation is off a click never moves the orbit pivot, picking keeps the plain left click, the gimbal bubbles and the projection key, button and menu item leave the view alone, and Home, F and a double click on empty space frame without reorienting. JS: viewer.setNavigation({rotate, pan, zoom, leftButton}).

viewer.onCameraChange(cb) reports each rendered frame in which the view changed (controls, damping, set_camera, framing, tweens, projection, resize) with the pose and worldPerPixel, so an overlay such as a scale bar follows the camera without polling.

await viewer.whenObjectReady(id) resolves once a blob-backed add (add_*_binary, models) has fetched and registered its object (false when it failed or was deleted), so an embedder that measures or adjusts a new object needs no polling.

viewer.setBottomInset(px) reserves room above the animation toolbar for a bar the page draws at the bottom of the canvas: the view gimbal and its orbit / P / Home buttons move up by px, and their hit-testing follows. hasFeature('bottom_inset') marks it.

viewer.setAnimationWindow(start, end) limits the animation toolbar to part of the clock: the bar, its readout and markers span [start, end], play stops or loops there, and frame steps, Home and End stay inside it. Starting play from a playhead outside it starts at start; a seek outside it while playing plays on from there. null clears it, and so does loading an animation; before an animation is loaded the call does nothing. The clock stays absolute, and getAnimationState().window reports the window. hasFeature('animation_window') marks it.

Coplanar paths, such as a planned and a measured one, are ordered with depth_offset on add_polyline / add_parametric_tube (depthOffset on the messages): a depth bias toward the camera in world units, applied in the shader, so nothing moves on screen and native lines honour it too. render_order sets THREE's renderOrder. The orthographic camera fits its near and far planes to the scene along the view, as the perspective camera does.

In JS the same calls are viewer.setProjection(mode), viewer.setCameraPose({..., projection}) and viewer.getCameraPose().projection. viewer.hasFeature(name) tells an embedder whether the viewer it runs against has an optional addition (viewer.features lists them), so a page can fall back on an older release.

Point clouds: live append, time windows & octree LOD

# Live streaming: seed the cloud once, then append as data arrives. Both the
# wire payload and the GPU upload cover the new points only, so this holds up
# for hours at a few flushes per second (the browser grows the buffer with
# spare capacity, doubling when it runs out).
v.add_points("live", first_chunk, colors=first_values, colormap="turbo",
             cmin=-0.5, cmax=0.5)      # fix the colour range up front...
while streaming:
    v.append_points("live", chunk, colors=values)   # ...appends clamp to it

Appending to an id that was never added (or was deleted, cleared, or created with lod= / birth_times) raises ValueError — a stream must not lose data silently. A cloud is not replayed when the browser reloads, so re-seed with add_points after a reconnect.

# Per-point lifetimes: a point is visible while birth_time <= t < removal_time.
# NaN = unbounded (never born-late / never removed).
v.add_points("stock", positions, colors=depth, colormap="turbo",
             birth_times=birth, removal_times=removal)
v.set_points_time("stock", 3.0)   # scrub the time directly...

# ...or map the animation slider onto it (drag to scrub points in/out):
anim = Animation(loop=True)
anim.set_frame_times(times)
anim.set_point_time_data(["stock"], times.reshape(-1, 1))
v.load_animation(anim)

# Octree LOD for clouds beyond one draw call (10M+ points): nodes stream
# on demand from Python under a point budget as the camera moves. Keep the
# Python process running — it serves node payloads.
v.add_points("big", positions, colors=scalars, lod=True)
# tunable: lod={"node_capacity": 15000, "point_budget": 1_500_000,
#               "refine_pixels": 12, "seed": 0}

Both compose: octree node samples are stratified over the time values, so scrubbing thins every LOD level uniformly. On LOD clouds use the time window instead of set_draw_range (buffer order is spatial there). See examples/27_points_octree_lod.py — point count tunable from the command line.

Animations

from threejs_viewer import Animation

animation = Animation(loop=True)
for t in times:
    animation.add_frame(
        time=t,
        transforms=compute_transforms(t),
        colors={"robot": 0xFF0000 if collision else 0x00FF00},
        clip_times={"glb_model": t},  # drive embedded GLTF animations
    )
animation.add_marker(3.5, "Collision detected")

client.load_animation(animation)

Viewer controls: Space (play/pause), Arrow keys (step frames), 1-5 (speed), L (loop)

Binary Channels (Large Animations)

For animations with many objects or frames, use binary channels instead of Frame dicts for much faster serialization and transfer:

import numpy as np
from threejs_viewer import Animation

animation = Animation(loop=True)
animation.set_frame_times(np.arange(n_frames) / 60.0)

# Transforms: (n_frames, n_objects, 16) float32
animation.set_transform_data(object_ids, transform_array)

# Draw ranges: (n_frames, n_objects) float32
animation.set_draw_range_data(object_ids, draw_range_array)

# Clip times for embedded GLTF animations: (n_frames, n_objects) float32
animation.set_clip_time_data(object_ids, clip_time_array)

# Colors with indexed colormap: (n_frames, n_objects) uint8
animation.add_channel("colors", object_ids, color_indices, dtype="uint8",
                       metadata={"colormap": [0x44AA44, 0xFF3333]})

# Visibility: (n_frames, n_objects) uint8 (0=hidden, 1=visible)
animation.add_channel("visibility", object_ids, vis_data, dtype="uint8")

client.load_animation(animation)

Binary channels and Frame-based JSON can be mixed. A binary channel supersedes the same-named Frame field.

GLB Models with Embedded Animations

# Load a GLB with embedded animations (skeletal, morph targets)
client.add_model_binary("fox", "fox.glb", format="glb")

# Seek embedded animation to a specific time (seconds)
client.set_clip_time("fox", 1.5)

Draw layers for coplanar glTF meshes

Surfaces that share a plane in one model (a floor, a path painted on it, borders on the path) flicker against each other. Give each node an integer extras.draw_layer from 0 to 15 (in Blender, an object custom property with "Include > Custom Properties" ticked on export). A higher layer always draws over a lower one in the same plane, for opaque and for transparent materials. Depth testing against the rest of the scene stays on, so a wall in front still hides the floor. The value must be a number; anything else is ignored with a console warning. Nodes inherit the layer of their nearest ancestor that sets one, and nodes without the property draw as before.

Documentation

CLI

threejs-viewer path    # Print path to viewer.html
threejs-viewer open    # Open in default browser
threejs-viewer code    # Open in VS Code (use "Show Preview" for docked view)

License

MIT

Metadata

Release files for threejs-viewer 0.0.80

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for threejs-viewer 0.0.80
File Size Uploaded Provenance Actions
threejs_viewer-0.0.80.tar.gz 1.5 MB With provenance Details for threejs_viewer-0.0.80.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for threejs-viewer 0.0.80
File Interpreter ABI Platform Actions
threejs_viewer-0.0.80-py3-none-any.whl Python 3 none any Details for threejs_viewer-0.0.80-py3-none-any.whl

Total release size: 3.0 MB

Release files / threejs_viewer-0.0.80.tar.gz

Download URL threejs_viewer-0.0.80.tar.gz
Size 1.5 MB
Tags Source
SHA-256 checksum
How to use checksums
9cae72a72be347c593aea9caee7b4e660f087f39f76657e69807541b811ec9c9
BLAKE2b-256 checksum
How to use checksums
9603caaef2d659d328daf74b9068a5145cc917708eb2a1e53d503a8a3b53277d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Release files / threejs_viewer-0.0.80-py3-none-any.whl

Download URL threejs_viewer-0.0.80-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
8e85e53adb5c6e41705effafe3150d70194d31b5dab3f11c9fa1d455462c7e64
BLAKE2b-256 checksum
How to use checksums
bacd939f65659ecdee882fa29257fe7259b3d774a9211da07349d46173b2c7e8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

Security for threejs-viewer 0.0.80

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for threejs_viewer-0.0.80.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.80 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page