Core Library
Purpose and Scope
The Core Library provides the foundational classes and abstractions that form the basis of Three.js. It defines renderer-agnostic representations of 3D scenes, including the scene graph hierarchy, geometry data structures, material properties, and texture management. This layer sits between the mathematical primitives and the rendering systems, enabling the creation and manipulation of 3D content independently of the rendering backend.
For information about the mathematical primitives used by these core classes, see Math Primitives. For details on how these core classes are rendered to the screen, see Rendering Architecture.
Architecture Overview
The Core Library consists of four primary subsystems that work together to represent 3D scenes:
Core Library Architecture
Object3D: The Scene Graph Foundation
Object3D is the base class for all renderable and non-renderable objects in Three.js. It provides hierarchical transformation, event dispatching, and a common interface for scene graph traversal.
Object3D Core Properties and Relationships
Transformation System
Object3D maintains transformations in both Euler angles and quaternions, with automatic synchronization between the two representations. The transformation hierarchy is managed through local and world matrices:
| Property | Type | Purpose |
|---|---|---|
| position | Vector3 | Local position relative to parent |
| rotation | Euler | Local rotation as Euler angles (synced with quaternion) |
| quaternion | Quaternion | Local rotation as quaternion (synced with rotation) |
| scale | Vector3 | Local scale |
| matrix | Matrix4 | Local transformation matrix |
| matrixWorld | Matrix4 | World transformation matrix |
| matrixAutoUpdate | boolean | Automatically compute local matrix from position/rotation/scale |
| matrixWorldAutoUpdate | boolean | Automatically compute world matrix from hierarchy |
| pivot | Vector3 | Pivot point for rotation and scale transformations |
The transformation matrices are computed by updateMatrix() and updateMatrixWorld(). When matrixAutoUpdate is true, the local matrix is composed from position, rotation, and scale each frame. When matrixWorldAutoUpdate is true, the world matrix is computed by multiplying the parent's world matrix with the local matrix.
Hierarchy Management
The scene graph is built using parent-child relationships. Key methods for hierarchy manipulation:
| Method | Parameters | Purpose |
|---|---|---|
| add(object) | Object3D | Add child object, fires 'added' and 'childadded' events |
| remove(object) | Object3D | Remove child object, fires 'removed' and 'childremoved' events |
| removeFromParent() | - | Remove this object from its parent |
| clear() | - | Remove all child objects |
| attach(object) | Object3D | Add child while maintaining its world transform |
| traverse(callback) | Function | Execute callback on this object and all descendants |
| traverseVisible(callback) | Function | Execute callback only on visible objects |
| traverseAncestors(callback) | Function | Execute callback on all ancestors |
EventDispatcher Integration
Object3D extends EventDispatcher, providing a pub-sub event system. Built-in events include:
added: Fired when object is added to a parentremoved: Fired when object is removed from a parentchildadded: Fired when a child is added (includeschildproperty)childremoved: Fired when a child is removed (includeschildproperty)
BufferGeometry: Vertex Data Storage
BufferGeometry represents mesh, line, or point geometry using typed arrays stored in BufferAttribute instances. It provides efficient data transfer to the GPU and supports indexed and non-indexed geometry.
BufferGeometry Data Flow
Attribute Management
Geometry attributes are stored in a dictionary (attributes) keyed by attribute name. Common attributes include:
| Attribute | ItemSize | Type | Purpose |
|---|---|---|---|
| position | 3 | Float32 | Vertex positions (x, y, z) |
| normal | 3 | Float32 | Vertex normals |
| uv | 2 | Float32 | Texture coordinates |
| uv1 | 2 | Float32 | Second set of texture coordinates |
| color | 3 or 4 | Float32 | Vertex colors (RGB or RGBA) |
| tangent | 4 | Float32 | Tangent vectors (with handedness in w) |
| skinIndex | 4 | Uint16 | Bone indices for skinned meshes |
| skinWeight | 4 | Float32 | Bone weights for skinned meshes |
Key methods for attribute manipulation:
// From BufferGeometry class
setAttribute(name, attribute) // Set an attribute
getAttribute(name) // Retrieve an attribute
deleteAttribute(name) // Remove an attribute
hasAttribute(name) // Check if attribute existsIndexed vs Non-Indexed Geometry
Geometry can be indexed (vertices shared across triangles) or non-indexed (each triangle has unique vertices):
- Indexed Geometry: Uses an
indexattribute (Uint16 or Uint32) to reference vertices. Each three consecutive indices define a triangle. - Non-Indexed Geometry: When
indexis null, every three consecutive vertices define a triangle.
The toNonIndexed() method converts indexed geometry to non-indexed format by duplicating shared vertices.
Draw Groups
Groups allow rendering different parts of the geometry with different materials. Each group specifies:
| Property | Type | Purpose |
|---|---|---|
| start | number | First vertex (non-indexed) or first index (indexed) |
| count | number | Number of vertices or indices to render |
| materialIndex | number | Index into the material array |
Bounding Volume Computation
BufferGeometry computes axis-aligned bounding boxes (Box3) and bounding spheres (Sphere) for frustum culling and intersection testing:
computeBoundingBox(): ComputesboundingBoxfrom position attribute and morph targetscomputeBoundingSphere(): ComputesboundingSphereusing a tighter-fitting algorithm than the bounding box
Both methods account for morph target positions when morphAttributes.position is defined.
Normal and Tangent Generation
Geometry provides methods to compute vertex normals and tangents from position data:
computeVertexNormals(): Computes face normals and averages them for shared vertices (indexed) or assigns face normals directly (non-indexed)computeTangents(): Computes tangent vectors for normal mapping (requires position, normal, uv, and index attributes)
BufferAttribute: Typed Array Management
BufferAttribute wraps typed arrays with metadata for efficient GPU transfer. It provides methods for accessing and manipulating vertex data.
BufferAttribute Structure
Data Access Methods
BufferAttribute provides typed accessors for common item sizes:
| Method | Parameters | Purpose |
|---|---|---|
| getX(index) | index | Get first component |
| getY(index) | index | Get second component |
| getZ(index) | index | Get third component |
| getW(index) | index | Get fourth component |
| setX(index, x) | index, x | Set first component |
| setY(index, y) | index, y | Set second component |
| setZ(index, z) | index, z | Set third component |
| setW(index, w) | index, w | Set fourth component |
| setXY(index, x, y) | index, x, y | Set two components |
| setXYZ(index, x, y, z) | index, x, y, z | Set three components |
| setXYZW(index, x, y, z, w) | index, x, y, z, w | Set four components |
Interleaved Attributes
InterleavedBuffer and InterleavedBufferAttribute enable packing multiple attributes into a single typed array, reducing memory overhead and improving cache coherency:
Each InterleavedBufferAttribute references the shared buffer with an offset and itemSize, allowing efficient data layout: [x,y,z,nx,ny,nz,u,v, x,y,z,nx,ny,nz,u,v, ...]
Instanced Attributes
InstancedBufferAttribute extends BufferAttribute for instanced rendering, where each instance can have unique attribute values:
meshPerAttribute: Defines how many instances use each attribute value (typically 1)- Used with
InstancedBufferGeometryfor rendering multiple copies of geometry with varying properties
InstancedInterleavedBuffer provides the same functionality for interleaved data.
Material: Surface Appearance
Material is the abstract base class for all materials, defining properties that control how surfaces appear when rendered. It provides a common interface for blending, depth testing, stencil operations, and custom shader hooks.
Material Property Categories
Material Property Groups
Blending and Transparency
| Property | Type | Default | Purpose |
|---|---|---|---|
| blending | Constant | NormalBlending | Blending mode (Normal, Additive, Subtractive, Multiply, Custom, None) |
| transparent | boolean | false | Whether material is transparent (affects render order) |
| opacity | number | 1.0 | Material opacity (0.0 = fully transparent, 1.0 = opaque) |
| blendSrc | Constant | SrcAlphaFactor | Source blend factor (requires CustomBlending) |
| blendDst | Constant | OneMinusSrcAlphaFactor | Destination blend factor (requires CustomBlending) |
| blendEquation | Constant | AddEquation | Blend equation (Add, Subtract, ReverseSubtract, Min, Max) |
Depth and Stencil
| Property | Type | Default | Purpose |
|---|---|---|---|
| depthTest | boolean | true | Enable depth testing |
| depthWrite | boolean | true | Write to depth buffer |
| depthFunc | Constant | LessEqualDepth | Depth comparison function |
| stencilWrite | boolean | false | Enable stencil operations |
| stencilFunc | Constant | AlwaysStencilFunc | Stencil comparison function |
| stencilRef | number | 0 | Reference value for stencil test |
Material Callbacks
Materials provide hooks for customization during rendering:
| Callback | Parameters | Purpose |
|---|---|---|
| onBeforeRender | renderer, scene, camera, geometry, object, group | Called before rendering an object |
| onBeforeCompile | shaderobject, renderer | Modify shader source before compilation (WebGLRenderer only) |
| customProgramCacheKey | - | Return string key for shader cache identification |
The onBeforeCompile callback enables shader modification for WebGLRenderer:
material.onBeforeCompile = function(shader, renderer) {
// Modify shader.vertexShader or shader.fragmentShader
// Access shader.uniforms
}Texture: Image Data Management
Texture encapsulates image data and sampling parameters for materials. It uses a Source object to share image data across multiple textures.
Texture Structure and Relationships
Texture Coordinate Transformation
Textures support UV transformation through offset, repeat, center, and rotation:
offset: Translation in UV spacerepeat: Scale in UV space (values > 1 tile the texture)center: Rotation center in UV spacerotation: Rotation angle in radians
When matrixAutoUpdate is true, these properties are used to compute the matrix via updateMatrix(), which applies the transformation: matrix.setUvTransform(offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y)
Texture Source Sharing
The Source class (src/textures/Source.js) holds the actual image data and can be shared across multiple Texture instances. This is useful for:
- Creating multiple textures with different sampling parameters from the same image
- Implementing texture atlases where multiple textures reference the same source but with different UV transforms
Serialization and Loading
The Core Library includes loaders for deserializing Three.js objects from JSON format, supporting complete scene graphs with geometry, materials, textures, animations, and skeletal hierarchies.
ObjectLoader Data Flow
ObjectLoader Pipeline
ObjectLoader parses JSON-serialized scenes in stages:
- Shapes (src/loaders/ObjectLoader.js270-288): Parse 2D shapes for extrude geometries
- Geometries (src/loaders/ObjectLoader.js321-368): Parse geometry data using
BufferGeometryLoaderor procedural geometry classes - Images (src/loaders/ObjectLoader.js423-633): Load images via
ImageLoaderor deserialize embedded data textures - Textures (src/loaders/ObjectLoader.js635-740): Create
Textureinstances with sampling parameters - Materials (src/loaders/ObjectLoader.js371-399): Parse materials using
MaterialLoader - Objects (src/loaders/ObjectLoader.js743-1045): Recursively construct Object3D hierarchy
- Skeletons (src/loaders/ObjectLoader.js290-318): Parse skeletal data for skinned meshes
- Binding (src/loaders/ObjectLoader.js1047-1108): Attach skeletons to meshes and resolve light targets
MaterialLoader
MaterialLoader deserializes material properties from JSON, creating instances of concrete material classes:
// Material types recognized by createMaterialFromType()
MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial,
MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial,
MeshNormalMaterial, MeshMatcapMaterial, MeshDepthMaterial,
MeshDistanceMaterial, LineBasicMaterial, LineDashedMaterial,
PointsMaterial, SpriteMaterial, ShaderMaterial, RawShaderMaterial,
ShadowMaterialThe loader sets material properties and resolves texture references from a texture dictionary.
Serialization Format
Object3D.toJSON() and Material.toJSON() serialize objects to JSON format compatible with ObjectLoader:
| Metadata | Content |
|---|---|
| metadata.version | 4.7 |
| metadata.type | 'Object' or 'Material' |
| metadata.generator | 'Object3D.toJSON' or 'Material.toJSON' |
The serialization captures:
- Object hierarchy and transformations
- Geometry and material references (via UUID)
- Custom properties in
userData - Animation clips
- Skeletal bindings for
SkinnedMesh
WebGL Resource Management
While the Core Library is renderer-agnostic, it interfaces with WebGL through specialized resource management systems:
WebGL Resource Management Flow
WebGLGeometries
WebGLGeometries manages the lifecycle of geometry resources:
- Tracks geometries via
WeakMapusing geometry IDs - Registers disposal handlers via
EventDispatcher'dispose' events - Updates attribute buffers through
WebGLAttributes - Generates wireframe indices for wireframe rendering mode
- Manages
InstancedBufferGeometryinstance counts
WebGLAttributes
WebGLAttributes manages WebGL buffer objects for BufferAttribute data:
- Creates VBOs with
gl.createBuffer()and uploads data viagl.bufferData() - Updates buffers incrementally using
updateRangesviagl.bufferSubData() - Merges adjacent update ranges to minimize GPU command overhead
- Maps TypedArray types to WebGL constants (FLOAT, HALF_FLOAT, UNSIGNED_SHORT, etc.)
WebGLBindingStates
WebGLBindingStates manages Vertex Array Objects (VAOs) to cache attribute bindings:
- Creates unique VAO per (object, geometry, program, material) combination
- Caches vertex attribute pointer configurations
- Reduces state changes by binding cached VAOs
- Handles instanced attributes for
InstancedMesh - Tracks wireframe vs solid geometry variants
WebGLObjects
WebGLObjects orchestrates geometry and attribute updates per frame:
- Updates geometries once per frame using frame tracking
- Updates instance matrices for
InstancedMesh - Triggers skeleton updates for
SkinnedMesh - Manages disposal of instanced mesh resources
WebGLProperties
WebGLProperties provides a generic property store using WeakMap, allowing renderer-specific metadata to be attached to core objects without modifying their class definitions.
Relationship to Other Systems
The Core Library serves as the foundation for other Three.js systems:
| System | Relationship |
|---|---|
| Math Primitives (#2.1) | Core Library uses Vector3, Matrix4, Quaternion, etc. for transformations |
| Constants (#2.2) | Core Library references constants for blending modes, texture formats, etc. |
| Rendering (#3) | Renderers consume Core Library objects to generate GPU commands |
| Asset Pipeline (#4) | Loaders create Core Library objects from external file formats |
| Interaction Systems (#5) | Raycasting and animation systems operate on Core Library scene graphs |