Skip to content

Rendering Architecture

Purpose and Scope

This document provides an architectural overview of Three.js's rendering subsystems, covering how scenes are transformed from scene graph representations to pixels on screen. The rendering architecture encompasses both WebGL and WebGPU backends, shader program management, state caching, and resource coordination.

For detailed information about specific subsystems:

For scene graph structure and object hierarchy: see Scene Graph & Object3D

Renderer Architecture Overview

Three.js provides two primary rendering backends implemented as separate classes. The WebGLRenderer class (used since r163, WebGL 2 only) serves as the primary production renderer, while the WebGPU renderer represents the next-generation graphics API support.

High-Level Renderer Structure

SVG
100%

Rendering Subsystem Organization

The WebGLRenderer delegates specialized tasks to modular subsystems, each managing a specific aspect of the rendering pipeline.

SubsystemPrimary ClassResponsibility
Shader ManagementWebGLProgramsProgram selection, compilation, caching
State CachingWebGLStateGL state change tracking, deduplication
Geometry UploadWebGLGeometriesVBO creation, attribute binding
Texture ManagementWebGLTexturesTexture upload, parameter caching
Render CoordinationWebGLRenderListsObject sorting (opaque/transparent)
Lighting SetupWebGLRenderStatesPer-scene light accumulation
Shadow RenderingWebGLShadowMapShadow map generation, filtering
Capability DetectionWebGLCapabilitiesGPU limits, extension availability
Resource TrackingWebGLInfoDraw call counts, memory stats

Frame Rendering Flow

The rendering process follows a well-defined sequence from scene traversal to final pixel output. The WebGLRenderer.render() method orchestrates this multi-stage pipeline.

Render Method Execution Flow

SVG
100%

Shader Program Pipeline

Shader programs are the compiled GPU code that transforms vertices and computes fragment colors. The WebGLPrograms subsystem manages program selection, compilation, and caching based on material properties and scene context.

Program Selection and Compilation Flow

SVG
100%

Built-in Shader Library

The ShaderLib provides template shaders for all standard material types. Each entry contains uniform definitions, vertex shader source, and fragment shader source. These shaders are composed from reusable ShaderChunk modules.

ShaderLib Material Types

ShaderLib KeyMaterial TypeLighting Model
basicMeshBasicMaterialUnlit
lambertMeshLambertMaterialLambertian diffuse
phongMeshPhongMaterialBlinn-Phong specular
standardMeshStandardMaterialPBR (metallic/roughness)
physicalMeshPhysicalMaterialPBR + clearcoat/transmission
toonMeshToonMaterialCel-shaded
matcapMeshMatcapMaterialMatcap texture
pointsPointsMaterialPoint sprites
dashedLineDashedMaterialDashed lines
depthMeshDepthMaterialDepth encoding
normalMeshNormalMaterialNormal visualization
distanceMeshDistanceMaterialDistance from point

Shader Composition with ShaderChunk

SVG
100%

State Management and Caching

The WebGLState class wraps all WebGL state-changing calls to minimize redundant GPU commands. It tracks the current state and only issues GL calls when the desired state differs from the cached state.

Cached State Categories

SVG
100%

Resource Upload and Caching

Geometry and texture data must be uploaded to GPU memory before rendering. The renderer maintains separate subsystems for managing these resources with intelligent caching.

Resource Management Subsystems

ClassUpload TargetCache Strategy
WebGLAttributesVertex Buffer Objects (VBOs)By BufferAttribute.uuid
WebGLGeometriesComplete geometriesBy BufferGeometry.id + attribute versions
WebGLTexturesTexture dataBy Texture.id + source version + parameters
WebGLRenderTargetFramebuffer Objects (FBOs)By render target instance
WebGLCubeMapsCube environment mapsBy texture instance with PMREMGenerator
WebGLCubeUVMapsCubeUV environment mapsBy texture instance, managed lifetime

Texture Upload Flow

SVG
100%

Render Lists and Sorting

Before rendering, the scene graph must be traversed to build lists of renderable objects. The WebGLRenderLists system organizes objects into opaque and transparent groups, then sorts them for correct rendering order.

Render List Population

SVG
100%

Sorting Strategy

Object TypePrimary SortSecondary SortDirection
OpaquerenderOrder then material.idz (depth)Front to back (optimization)
TransparentrenderOrderz (depth)Back to front (correctness)

Transparent objects must render back-to-front for correct alpha blending. Opaque objects render front-to-back to leverage early depth testing and reduce overdraw.

Backend Comparison: WebGL vs WebGPU

Three.js supports two rendering backends with different architectures. The WebGL backend is mature and production-ready, while WebGPU represents next-generation GPU APIs with compute shader support.

Architectural Differences

AspectWebGLRendererWebGPU Renderer
API VersionWebGL 2.0 only (since r163)WebGPU (Chrome 113+)
Shader LanguageGLSL ES 3.0WGSL
Material SystemTraditional propertiesNode-based materials (TSL)
State ManagementGlobal state machine (cached)Command encoders (stateless)
Compute ShadersNot supportedFully supported
Build Outputthree.module.jsthree.webgpu.js, three.tsl.js
Coordinate SystemY-up, right-handedConfigurable

WebGPU Architecture (briefly, detailed in WebGPU & Node Materials)

The WebGPU backend uses a fundamentally different approach:

  • Node materials: Material properties defined via node graphs instead of simple properties
  • Render bundles: Pre-recorded command sequences for repeated draws
  • Compute passes: GPU compute shaders for physics, particles, post-processing
  • Multiple render targets: Native support for rendering to multiple textures simultaneously

Initialization and Context Creation

The renderer must acquire a WebGL context and initialize all subsystems before rendering can begin. This process includes capability detection, extension loading, and subsystem instantiation.

Renderer Initialization Sequence

SVG
100%

Context Attributes

The renderer requests a WebGL2 context with specific attributes defined at construction:

// From WebGLRenderer constructor
const contextAttributes = {
    alpha: true,
    depth: true,
    stencil: false,
    antialias: false,
    premultipliedAlpha: true,
    preserveDrawingBuffer: false,
    powerPreference: 'default',
    failIfMajorPerformanceCaveat: false,
};

Material-to-Shader Mapping

Different material types require different shader programs. The WebGLPrograms system analyzes material properties and scene context to generate appropriate shader code.

Material Type to ShaderLib Mapping

SVG
100%

Shader Variant Generation

For each material type, hundreds of shader variants may be generated based on:

  • Texture usage (map, normalMap, roughnessMap, etc.)
  • Lighting configuration (number and type of lights)
  • Feature flags (fog, shadows, morphTargets, skinning)
  • Material properties (transparency, double-sided, etc.)

Example parameter combination for MeshStandardMaterial:

// Generated in WebGLPrograms.getParameters()
{
    map: true,
    normalMap: true,
    roughnessMap: true,
    metalnessMap: true,
    envMap: true,
    lights: true,
    shadowMapEnabled: true,
    numDirLights: 2,
    numPointLights: 3,
    // ... many more parameters
}

Each unique combination results in a different compiled shader program.

Render Target System

Render targets allow rendering to off-screen textures instead of the canvas. This enables multi-pass rendering, post-processing effects, shadow maps, and environment map generation.

WebGLRenderTarget Structure

A render target consists of:

  • One or more color textures (attachments)
  • Optional depth buffer (renderbuffer or texture)
  • Optional stencil buffer
  • Dimensions and pixel format specifications

Render Target Usage Pattern

SVG
100%

Common Render Target Applications

Use CaseConfigurationConsumer
Shadow MapsDepth texture, single channelWebGLShadowMap generates, materials sample
Post-processingRGBA color textureEffects read previous frame output
Reflection MapsCube render target (6 faces)Environment mapping on materials
PickingInteger format for object IDsMouse interaction / selection
MultisamplingMSAA samples > 1Antialiasing without postprocess

Performance Monitoring

The WebGLInfo object tracks rendering statistics useful for performance analysis and debugging. It counts draw calls, geometry uploads, texture uploads, and shader compilations.

WebGLInfo Statistics

// Accessed via renderer.info
{
    memory: {
        geometries: 42,  // Number of BufferGeometries uploaded
        textures: 18     // Number of Textures on GPU
    },
    render: {
        calls: 156,      // Number of draw calls this frame
        triangles: 84320,  // Total triangles rendered
        points: 0,
        lines: 0,
        frame: 0         // Frame counter
    },
    programs: [...]  // Array of compiled WebGLPrograms
}

By monitoring render.calls and render.triangles, developers can identify performance bottlenecks. High draw call counts suggest excessive scene fragmentation, while high triangle counts indicate geometry complexity.

Summary

The Three.js rendering architecture is organized into modular subsystems that collaborate to transform scene graphs into rendered pixels:

  1. WebGLRenderer orchestrates the overall rendering process and owns all subsystems
  2. WebGLPrograms manages shader selection, compilation, and caching based on material/scene parameters
  3. WebGLState wraps GL state changes to minimize redundant GPU commands
  4. WebGLGeometries and WebGLTextures handle resource upload and caching
  5. WebGLRenderLists organize objects for efficient rendering with proper sorting
  6. WebGLRenderStates accumulate lighting information per scene/camera
  7. WebGLShadowMap implements shadow mapping via depth-only render passes

This architecture enables high-performance rendering while maintaining flexibility for diverse material types and rendering techniques. The caching and state management layers ensure minimal GPU overhead even in complex scenes.

For implementation details of each subsystem, see the child pages: WebGL Rendering Pipeline, Shader Programs & ShaderLib, State & Resource Management, Shadow Mapping, and WebGPU & Node Materials.