Skip to content

Three.js Overview

Purpose and Scope

This document provides a high-level overview of the Three.js library architecture, including its module organization, distribution formats, core systems, and how different subsystems interact. For detailed information about specific subsystems, see:

What is Three.js

Three.js is a cross-platform JavaScript 3D graphics library designed to simplify WebGL and WebGPU programming. It provides a high-level abstraction over GPU APIs, offering a scene graph-based architecture for rendering 3D content in web browsers.

Current Version: REVISION = '183dev' as defined in src/constants.js1

Primary Capabilities:

  • Hardware-accelerated 3D rendering via WebGL 2 and WebGPU
  • Scene graph management with hierarchical transformations
  • Material system with physically-based rendering (PBR)
  • Animation, skeletal rigging, and morph targets
  • Import/export of common 3D file formats (GLTF, FBX, OBJ)
  • Post-processing effects and shadows

Distribution Formats

Three.js is distributed in multiple build variants to support different use cases and rendering backends:

Build OutputEntry PointFormatPurpose
three.core.jssrc/Three.Core.jsESMCore math, scene graph, geometry systems
three.module.jssrc/Three.jsESMCore + WebGL renderer
three.webgpu.jssrc/Three.WebGPU.jsESMCore + WebGPU renderer + node material system
three.cjssrc/Three.Core.jsCommonJSNode.js compatibility
three.tsl.jssrc/Three.TSL.jsESMThree Shading Language (TSL) exports for WebGPU

Package Exports (from package.json8-20):

"exports": {
  ".": {
    "import": "./build/three.module.js",
    "require": "./build/three.cjs"
  },
  "./webgpu": "./build/three.webgpu.js",
  "./tsl": "./build/three.tsl.js",
  "./addons": "./examples/jsm/Addons.js"
}

High-Level Architecture

System Organization Diagram

SVG
100%

Core Subsystems

Scene Graph and Rendering Pipeline

Three.js follows a scene graph paradigm where 3D objects are organized in a hierarchical tree structure. The rendering process transforms this logical scene representation into GPU commands.

SVG
100%

Key Classes:

Math and Transformation System

The core mathematics layer provides the primitives for 3D transformations, spatial queries, and geometric calculations.

SVG
100%

Transformation Hierarchy: Each Object3D maintains both a local transform (matrix) and a world-space transform (matrixWorld). World matrices are computed by multiplying parent world matrices down the scene graph during traversal.

Material and Shader System

Materials define surface appearance and control shader generation. Three.js uses a template-based shader system where GLSL code is assembled from reusable chunks based on material properties.

SVG
100%

Shader Compilation Process:

  1. Material properties determine required shader features (e.g., USE_MAP, USE_NORMALMAP)
  2. WebGLPrograms generates a program configuration hash
  3. If not cached, GLSL source is assembled from ShaderLib templates and ShaderChunk includes
  4. Shader is compiled and linked via WebGLProgram src/renderers/webgl/WebGLProgram.js309-495

Geometry and Buffer Management

Geometry data is stored in BufferGeometry using typed arrays, which are efficiently uploaded to GPU buffers.

SVG
100%

Key Classes:

Rendering Backend: WebGL vs WebGPU

Three.js supports two rendering backends with different architectures:

FeatureWebGLRendererWebGPURenderer
Entry Pointsrc/renderers/WebGLRenderer.jsIncluded in three.webgpu.js
APIWebGL 2WebGPU
Material SystemFixed material typesNode-based (NodeMaterial)
Shader LanguageGLSL (template-based)WGSL (node-graph)
Coordinate SystemWebGLCoordinateSystemWebGPUCoordinateSystem
Multi-targetSingle render targetMultiple Render Targets (MRT)

WebGL Architecture src/renderers/WebGLRenderer.js64-2500:

  • Manages 20+ subsystems (state, programs, textures, geometries, etc.)
  • Shader compilation via WebGLPrograms caching system
  • State management minimizes redundant GPU calls via WebGLState

WebGPU Architecture build/three.webgpu.js1-2485272:

  • Node-based material system where shaders are constructed from node graphs
  • TSL (Three Shading Language) for expressing shader logic in JavaScript
  • Modern GPU features: compute shaders, storage buffers, MRT

Constants System

Three.js uses numeric and string constants throughout the codebase for configuration. These are centralized in src/constants.js1-1071

Key Constant Categories:

CategoryExamplesPurpose
BlendingNoBlending, NormalBlending, AdditiveBlendingControl alpha compositing
CullingCullFaceNone, CullFaceBack, FrontSide, DoubleSideFace visibility
Depth TestingLessDepth, LessEqualDepth, AlwaysDepthZ-buffer comparison
Texture FilteringNearestFilter, LinearFilter, LinearMipmapLinearFilterTexture sampling
Texture FormatsRGBAFormat, RGBFormat, DepthFormatPixel format specification
Shadow MappingBasicShadowMap, PCFShadowMap, VSMShadowMapShadow filtering algorithms
Tone MappingNoToneMapping, ACESFilmicToneMapping, AgXToneMappingHDR to LDR conversion

Build System

The build system uses Rollup to produce multiple distribution formats from TypeScript-free JavaScript source code.

Build Configuration utils/build/rollup.config.js66-143:

SVG
100%

Build Outputs:

  1. three.core.js: Core library without renderers
  2. three.module.js: Core + WebGLRenderer
  3. three.webgpu.js: Core + WebGPURenderer + node material system
  4. three.tsl.js: TSL (Three Shading Language) re-exports for WebGPU
  5. Minified versions (.min.js) for production

GLSL Processing utils/build/rollup.config.js4-36: The glsl() plugin minifies GLSL shader code by removing comments and excess whitespace from template literals marked with /* glsl */.

Module Organization

The source code is organized into logical directories:

src/
├── constants.js          # System-wide constants
├── Three.js              # WebGL entry point
├── Three.Core.js         # Core-only entry point
├── Three.WebGPU.js       # WebGPU entry point
├── Three.TSL.js          # TSL re-exports
├── animation/            # Animation system
├── cameras/              # Camera types
├── core/                 # Object3D, BufferGeometry, Raycaster
├── geometries/           # Procedural geometry generators
├── lights/               # Light types
├── loaders/              # Loader base classes
├── materials/            # Material base classes
├── math/                 # Math primitives
├── objects/              # Mesh, Line, Points, Sprite
├── renderers/            # WebGLRenderer and subsystems
│   ├── webgl/           # WebGL backend components
│   ├── shaders/         # GLSL shader library
│   └── webxr/           # WebXR support
├── scenes/               # Scene, Fog
└── textures/             # Texture classes

examples/jsm/             # Add-on modules (not in core)
├── loaders/              # GLTFLoader, FBXLoader, etc.
├── controls/             # OrbitControls, etc.
├── postprocessing/       # Post-processing effects
└── exporters/            # Scene exporters

Core vs Examples:

  • Core (src/): Bundled in main distribution, stable API
  • Examples (examples/jsm/): Add-on modules, imported separately via /addons/* paths

Usage Patterns

Basic Rendering Setup

The typical Three.js application follows this pattern (from README.md24-58):

import * as THREE from 'three';

// 1. Create scene
const scene = new THREE.Scene();

// 2. Create camera
const camera = new THREE.PerspectiveCamera(
    70,                          // FOV
    window.innerWidth / window.innerHeight,  // aspect ratio
    0.01,                        // near plane
    10                           // far plane
);

// 3. Create geometry and material
const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
const material = new THREE.MeshNormalMaterial();

// 4. Create mesh and add to scene
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

// 5. Create renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 6. Animation loop
renderer.setAnimationLoop((time) => {
    mesh.rotation.x = time / 2000;
    mesh.rotation.y = time / 1000;
    renderer.render(scene, camera);
});

Key Technical Details

Coordinate System

Color Space Management

  • Linear workflow: Internally operates in linear color space
  • Automatic conversion: sRGB textures converted to linear on GPU
  • Tone mapping: HDR to LDR conversion applied in final shader pass
  • Color spaces: SRGBColorSpace, LinearSRGBColorSpace, NoColorSpace src/constants.js804-840

Memory Management

  • Manual disposal: GPU resources must be explicitly freed via .dispose() methods
  • Resource tracking: WebGLProperties uses WeakMap to associate GPU objects with JS objects
  • Context loss: Automatic recovery via webglcontextlost events src/renderers/WebGLRenderer.js1073-1103

Performance Considerations

Rendering Optimization

  • Draw call batching: BatchedMesh combines multiple objects into single draw call
  • Instanced rendering: InstancedMesh for rendering many copies of same geometry
  • Frustum culling: Automatic visibility determination via bounding volumes
  • Level of Detail (LOD): Automatic mesh switching based on distance

Shader Compilation

  • Program caching: WebGLPrograms caches compiled shaders by material+lighting hash
  • Lazy compilation: Shaders compiled on first render, not construction
  • Warm-up: renderer.compile(scene, camera) pre-compiles all materials src/renderers/WebGLRenderer.js1350-1420

Extension Points

Custom Materials

  • ShaderMaterial: Full control over vertex and fragment shaders
  • onBeforeCompile: Hook to modify built-in material shaders before compilation
  • NodeMaterial (WebGPU): Node-graph-based material system

Custom Geometry

  • BufferGeometry: Direct manipulation of vertex attributes
  • Procedural generation: Create geometry programmatically in JavaScript
  • Compute shaders (WebGPU): GPU-side geometry generation

Render Pipeline

  • onBeforeRender/onAfterRender: Per-object callbacks during rendering
  • Render targets: Off-screen rendering for effects and shadows
  • Multi-pass rendering: Manual control over render sequence