Skip to content

索引

Index

▶ 在线运行案例

索引

你将学到什么

  • 索引绘制 vs 非索引绘制 的区别
  • geometry.index 如何用 4 个顶点拼出 2 个三角形
  • 同一 Geometry 可同时用于 Points、Line、Mesh

效果说明

同一组顶点数据,同时以 黄色点红色线蓝色面 三种方式渲染,展示 WebGL 不同 图元模式(points / lines / triangles)。

核心概念

非索引 vs 索引

方式顶点数(矩形)说明
非索引6(每三角独立 3 顶点)网格 案例
索引4 顶点 + 6 索引值顶点可复用,节省内存
js
// 4 个唯一顶点
const vertices = new Float32Array([
    0, 0, 0,    // 索引 0
    50, 0, 0,   // 索引 1
    50, 0, 50,  // 索引 2
    0, 0, 50,   // 索引 3
]);

// 索引表:每 3 个索引构成一个三角形
const indexes = new Uint16Array([
    0, 1, 2,   // 三角面 1
    0, 3, 2,   // 三角面 2
]);
geometry.index = new THREE.BufferAttribute(indexes, 1);
geometry.attributes.position = new THREE.BufferAttribute(vertices, 3);

同一 Geometry,三种 Object

ObjectMaterial渲染模式
PointsPointsMaterialGL_POINTS
LineLineBasicMaterialGL_LINE_STRIP 等
MeshMeshBasicMaterialGL_TRIANGLES

实现步骤

  1. 定义 4 顶点 + 6 索引
  2. 分别创建 Points、Line、Mesh 加入 scene
  3. OrbitControls 交互

代码要点

js
// index 的 itemSize 固定为 1(每个索引一个整数)
geometry.index = new THREE.BufferAttribute(indexes, 1);

// Line 会按顶点顺序连线;Mesh 按 index 组三角面
const line = new THREE.Line(geometry, lineMaterial);
const mesh = new THREE.Mesh(geometry, meshMaterial);

大型模型

glTF / FBX 导入的模型几乎都用索引。百万级顶点场景,索引复用对内存和带宽至关重要。

源码

完整源码见 在线案例

js
const geometry = new THREE.BufferGeometry();
const vertices = new Float32Array([0,0,0, 50,0,0, 50,0,50, 0,0,50]);
const indexes = new Uint16Array([0, 1, 2, 0, 3, 2]);

geometry.index = new THREE.BufferAttribute(indexes, 1);
geometry.attributes.position = new THREE.BufferAttribute(vertices, 3);

const points = new THREE.Points(geometry, new THREE.PointsMaterial({ color: 0xffff00, size: 10 }));
const line = new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0xff0000 }));
const mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: 0x0000ff, side: THREE.DoubleSide }));
scene.add(points, line, mesh);

小结

入门案例 · Three.js · 7/15