Skip to content

场景图与 Object3D

目的与范围

本文档介绍了 Three.js 中的 Object3D 基类和场景图架构。它解释了 3D 对象如何组织成层次结构,如何通过 position/rotation/scale 属性和变换矩阵管理变换,以及对象如何通过生命周期挂钩与渲染管线交互。

关于几何体数据(顶点位置、法线、UV)的信息,请参阅 几何体系统。关于材质外观属性,请参阅 材质与纹理系统

Object3D 类概述

Object3D 类是 Three.js 中大多数对象的基类。它实现了场景图管理、空间变换和渲染生命周期挂钩的核心功能。所有可渲染对象(MeshLinePointsSprite)和组织对象(GroupScene)都扩展自 Object3D

主要职责:

  • 维护父子层次关系
  • 存储局部和世界变换数据
  • 提供变换方法(平移、旋转、缩放)
  • 定义渲染属性(可见性、图层、renderOrder)
  • 暴露渲染回调的生命周期挂钩

核心属性

PropertyTypeDefaultDescription
isObject3DbooleantrueType testing flag
idnumberauto-incrementAuto-incremented unique identifier starting at 0
uuidstringgeneratedUniversally unique identifier via generateUUID()
namestring''Optional human-readable name
typestring'Object3D'Class type identifier (e.g., "Mesh", "Group")
parentObject3D | nullnullReference to parent object
childrenArray<Object3D>[]Array of child objects
upVector3Object3D.DEFAULT_UPUp direction vector (default is (0,1,0))
userDataObject{}Custom application data storage

场景图层次结构

场景图是一种树结构,其中每个节点都是 Object3D。根通常是 Scene 对象,摄像机、灯光和网格作为后代。这种层次结构支持:

  • 分组变换: 子对象继承父对象变换
  • 组织结构: 相关对象的逻辑分组
  • 高效剔除: 整个分支可以被剔除或设置为不可见

层次结构类图

标题: 具有关键属性的 Object3D 类层次结构

SVG
100%

父子管理

添加子对象:

// Methods defined in Object3D
add( object )              // Add one or more children
attach( object )           // Add while preserving world transform

移除子对象:

remove( object )           // Remove child
removeFromParent()         // Remove self from parent
clear()                    // Remove all children

关键实现细节:

  • 子对象通过 parent 属性维护对其父对象的引用
  • 添加对象会自动将其从先前的父对象中移除
  • 事件被分派: addedremovedchildaddedchildremoved
  • 对象不能添加为自己的子对象

场景图遍历

The scene graph can be traversed using three methods:

MethodDescription
traverse(callback)Execute callback on this object and all descendants
traverseVisible(callback)Same as traverse() but skips invisible objects
traverseAncestors(callback)Execute callback on all ancestors

查找对象的遍历示例:

  • getObjectById(id) - 通过数字 ID 查找
  • getObjectByName(name) - 通过名称字符串查找
  • getObjectByProperty(name, value) - 通过任意属性查找
  • getObjectsByProperty(name, value, result) - 查找所有匹配对象

变换系统

Object3D 实现了变换的双重表示:

  1. 组件形式: positionrotation/quaternionscale 属性
  2. 矩阵形式: matrix(局部空间)和 matrixWorld(世界空间)

变换属性

标题: Object3D 中的变换数据流

SVG
100%

组件属性

PropertyTypeDefaultDescription
positionVector3(0,0,0)Local position
rotationEuler(0,0,0)Local rotation as Euler angles
quaternionQuaternion(0,0,0,1)Local rotation as quaternion
scaleVector3(1,1,1)Local scale
upVector3(0,1,0)Up vector for lookAt()

重要: rotationquaternion 会自动同步。修改其中一个会通过内部更改回调更新另一个。

矩阵属性

PropertyTypeDescription
matrixMatrix4Local transformation matrix
matrixWorldMatrix4World transformation matrix
modelViewMatrixMatrix4Model-view matrix (computed during rendering)
normalMatrixMatrix3Normal matrix (computed during rendering)

Matrix Update Flags:

FlagTypeDefaultDescription
matrixAutoUpdatebooleantrueAuto-compute matrix from position/rotation/scale
matrixWorldAutoUpdatebooleantrueAuto-compute matrixWorld from hierarchy
matrixWorldNeedsUpdatebooleanfalseForce world matrix update this frame

Transformation Update Flow

Title: Matrix Update Process During Rendering

SVG
100%

变换方法

设置变换:

// Rotation
setRotationFromAxisAngle(axis, angle)
setRotationFromEuler(euler)
setRotationFromMatrix(m)
setRotationFromQuaternion(q)

// Applying transformations
applyMatrix4(matrix)            // Apply matrix to object
applyQuaternion(q)              // Apply quaternion rotation

增量变换:

// Rotation
rotateOnAxis(axis, angle)       // Rotate in local space
rotateOnWorldAxis(axis, angle)  // Rotate in world space
rotateX(angle)                  // Rotate around local X axis
rotateY(angle)                  // Rotate around local Y axis
rotateZ(angle)                  // Rotate around local Z axis

// Translation
translateOnAxis(axis, distance) // Translate in local space
translateX(distance)            // Translate along local X axis
translateY(distance)            // Translate along local Y axis
translateZ(distance)            // Translate along local Z axis

实用方法:

lookAt(x, y, z)                 // Orient to face target point
localToWorld(vector)            // Convert local to world coordinates
worldToLocal(vector)            // Convert world to local coordinates

世界空间查询

检索世界空间变换数据的方法:

MethodReturnsDescription
getWorldPosition(target)Vector3Position in world space
getWorldQuaternion(target)QuaternionRotation in world space
getWorldScale(target)Vector3Scale in world space
getWorldDirection(target)Vector3Forward direction in world space

渲染属性

Object3D 提供控制对象渲染方式的属性:

可见性和剔除

PropertyTypeDefaultDescription
visiblebooleantrueWhether object is rendered
frustumCulledbooleantrueWhether object is culled by view frustum
renderOrdernumber0Override default rendering order

剔除行为:

  • 具有 frustumCulled=true 的对象会针对摄像机的视锥体进行测试
  • 不可见对象(visible=false)在渲染期间被跳过
  • traverseVisible() 尊重场景遍历的可见性

图层系统

The layers property (type Layers) provides a 32-bit mask for selective rendering:

// Object on layer 1
object.layers.set(1);

// Camera renders layers 0 and 1
camera.layers.enableAll();
camera.layers.enable(0);
camera.layers.enable(1);

// Check if object is visible to camera
if (object.layers.test(camera.layers)) {
    // Render object
}

用例:

  • 选择性渲染(例如 UI 层 vs 世界层)
  • 光线投射过滤器(从拾取中排除某些对象)
  • 后处理掩码

阴影属性

PropertyTypeDefaultDescription
castShadowbooleanfalseWhether object casts shadows
receiveShadowbooleanfalseWhether object receives shadows
customDepthMaterialMaterialundefinedCustom material for shadow depth pass
customDistanceMaterialMaterialundefinedCustom material for point light shadows

生命周期挂钩

Object3D 提供在渲染过程中调用的回调挂钩:

渲染生命周期图

标题: 渲染期间的 Object3D 生命周期挂钩

SVG
100%

挂钩签名

主渲染:

onBeforeRender(renderer, scene, camera, geometry, material, group)
onAfterRender(renderer, scene, camera, geometry, material, group)

阴影渲染:

onBeforeShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group)
onAfterShadow(renderer, object, camera, shadowCamera, geometry, depthMaterial, group)

Parameters:

ParameterTypeDescription
rendererWebGLRendererThe active renderer
sceneSceneThe scene being rendered
cameraCameraThe camera used for rendering
geometryBufferGeometryThe object's geometry
materialMaterialThe material being rendered
groupObjectGeometry group data (for multi-material objects)

常见用例:

  • 根据摄像机位置更新 uniform
  • 每帧修改材质属性
  • 根据距离切换可见性
  • 为阴影设置自定义深度材质

常见 Object3D 子类

类层次结构和用法

标题: Object3D 子类实现细节

SVG
100%

Scene

Scene 类通常是场景图的根:

其他属性:

  • background - 背景颜色或纹理
  • environment - 用于反射的环境贴图
  • fog - 雾效设置(线性或指数)
  • overrideMaterial - 覆盖所有对象材质

Group

用于组织对象的空容器:

  • 没有几何体或材质
  • 纯粹用于变换层次结构
  • 轻量级组织工具

Mesh

结合几何体和材质用于可渲染的三角表面:

其他属性:

  • geometry - BufferGeometry 实例
  • material - 材质或材质数组
  • morphTargetInfluences - 变形目标权重
  • morphTargetDictionary - 变形目标名称到索引的映射

方法:

  • raycast(raycaster, intersects) - 射线相交测试
  • updateMorphTargets() - 初始化变形目标数据

Sprite

始终面向摄像机的广告牌:

  • 使用 SpriteMaterial
  • 不投射阴影
  • 对粒子和 UI 元素高效

光线投射集成

Object3D 提供由可渲染子类实现的抽象 raycast() 方法:

raycast(raycaster, intersects)

Raycaster 流程:

标题: 通过场景图的光线投射过程

SVG
100%

相交结果结构:

{
    distance: number,          // Distance from ray origin
    point: Vector3,            // World space intersection point
    face: Face,                // Face index (if applicable)
    faceIndex: number,         // Face index
    object: Object3D,          // The intersected object
    uv: Vector2,               // UV coordinates at intersection
    instanceId: number         // Instance ID (for InstancedMesh)
}

序列化和克隆

JSON 序列化

Object3D 及其子类通过 ObjectLoader 支持 JSON 序列化:

序列化结构:

{
    metadata: { version: 4.7, type: 'Object', generator: 'Object3D.toJSON' },
    object: {
        uuid: string,
        type: string,        // Class name
        name: string,
        
        // Transformation
        matrix: [16 numbers],
        
        // Hierarchy
        children: [ ... ],
        
        // Rendering
        visible: boolean,
        castShadow: boolean,
        receiveShadow: boolean,
        frustumCulled: boolean,
        renderOrder: number,
        
        // Type-specific properties
        geometry: string,     // UUID reference (Mesh)
        material: string,     // UUID reference (Mesh)
        // ...
        
        userData: { ... }
    }
}

解析过程:

标题: ObjectLoader.parse() 管线

SVG
100%

克隆

clone()copy() 方法启用对象复制:

// 深度克隆(包含子对象)
const clone = object.clone();

// 浅拷贝(不包含子对象)
const copy = new Object3D().copy(object, false);

拷贝行为:

  • 变换属性被复制
  • 子对象可选择性地递归克隆
  • 父引用不被复制(克隆的对象是孤立的)
  • 几何体和材质引用被共享(不克隆)

其他属性

自定义数据

object.userData = {};  // Empty object for application data

userData 属性在序列化和克隆期间保留,但不应包含函数引用。

动画剪辑

object.animations = [];  // Array of AnimationClip instances

与对象关联的动画剪辑,通常由加载器填充。

静态优化 (WebGPU)

object.static = false;  // Mark object as unchanging

当为 true 时,表示对象在初始渲染后不会更改,允许 WebGPU 渲染器优化。

枢轴点

object.pivot = new Vector3(0.5, 0.5, 0);  // Custom pivot point

设置后,旋转和缩放变换围绕此点而不是原点进行。

关键架构模式

组合模式

场景图实现了组合模式:

  • Object3D 是组件接口
  • 叶节点(Mesh、Sprite、Camera)和组合节点(Group、Scene)共享相同的接口
  • 操作(traverse、transform、render)在单个对象或层次结构上统一工作

观察者模式

Object3D 扩展 EventDispatcher 以进行事件驱动的通信:

  • 层次结构更改分派 addedremovedchildaddedchildremoved 事件
  • 材质和几何体使用 dispose 事件进行清理

矩阵缓存

变换系统使用惰性求值:

  • 局部矩阵仅在 matrixAutoUpdate=true 或调用 updateMatrix() 时计算
  • 世界矩阵仅在需要时或被标记为 matrixWorldNeedsUpdate 时计算
  • 减少静态场景中不必要的矩阵乘法