threejs-geometry

threejs-geometry

熱門

Three.js 幾何體建立 — 內建形狀、BufferGeometry、自訂幾何體與實例化 rendering(Instancing)。適用於建立 3D 形狀、處理頂點、建構自訂網格或透過實例化渲染進行效能最佳化。

6.3萬星標
7980分支
更新於 2026/9/6
SKILL.md
唯讀
名稱
threejs-geometry
描述

Three.js 幾何體建立 — 內建形狀、BufferGeometry、自訂幾何體與實例化 rendering(Instancing)。適用於建立 3D 形狀、處理頂點、建構自訂網格或透過實例化渲染進行效能最佳化。

Three.js 幾何體(Geometry)

快速開始

import * as THREE from "three";

// 內建幾何體
const box = new THREE.BoxGeometry(1, 1, 1);
const sphere = new THREE.SphereGeometry(0.5, 32, 32);
const plane = new THREE.PlaneGeometry(10, 10);

// 建立網格(Mesh)
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const mesh = new THREE.Mesh(box, material);
scene.add(mesh);

內建幾何體

基本形狀

// 立方體 (Box) - width, height, depth, widthSegments, heightSegments, depthSegments
new THREE.BoxGeometry(1, 1, 1, 1, 1, 1);

// 球體 (Sphere) - radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength
new THREE.SphereGeometry(1, 32, 32);
new THREE.SphereGeometry(1, 32, 32, 0, Math.PI * 2, 0, Math.PI); // 完整球體
new THREE.SphereGeometry(1, 32, 32, 0, Math.PI); // 半球體

// 平面 (Plane) - width, height, widthSegments, heightSegments
new THREE.PlaneGeometry(10, 10, 1, 1);

// 圓形 (Circle) - radius, segments, thetaStart, thetaLength
new THREE.CircleGeometry(1, 32);
new THREE.CircleGeometry(1, 32, 0, Math.PI); // 半圓

// 圓柱體 (Cylinder) - radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded
new THREE.CylinderGeometry(1, 1, 2, 32, 1, false);
new THREE.CylinderGeometry(0, 1, 2, 32); // 圓錐體
new THREE.CylinderGeometry(1, 1, 2, 6); // 六角柱

// 圓錐體 (Cone) - radius, height, radialSegments, heightSegments, openEnded
new THREE.ConeGeometry(1, 2, 32, 1, false);

// 圓環 (Torus) - radius, tube, radialSegments, tubularSegments, arc
new THREE.TorusGeometry(1, 0.4, 16, 100);

// 環面扭結 (TorusKnot) - radius, tube, tubularSegments, radialSegments, p, q
new THREE.TorusKnotGeometry(1, 0.4, 100, 16, 2, 3);

// 圓環面 (Ring) - innerRadius, outerRadius, thetaSegments, phiSegments
new THREE.RingGeometry(0.5, 1, 32, 1);

進階形狀

// 膠囊體 (Capsule) - radius, length, capSegments, radialSegments
new THREE.CapsuleGeometry(0.5, 1, 4, 8);

// 十二面體 (Dodecahedron) - radius, detail
new THREE.DodecahedronGeometry(1, 0);

// 二十面體 (Icosahedron) - radius, detail (0 = 20 個面,數值越高越平滑)
new THREE.IcosahedronGeometry(1, 0);

// 八面體 (Octahedron) - radius, detail
new THREE.OctahedronGeometry(1, 0);

// 四面體 (Tetrahedron) - radius, detail
new THREE.TetrahedronGeometry(1, 0);

// 多面體 (Polyhedron) - vertices, indices, radius, detail
const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
new THREE.PolyhedronGeometry(vertices, indices, 1, 0);

基於路徑的形狀

// 旋轉體 (Lathe) - points[], segments, phiStart, phiLength
const points = [
  new THREE.Vector2(0, 0),
  new THREE.Vector2(0.5, 0),
  new THREE.Vector2(0.5, 1),
  new THREE.Vector2(0, 1),
];
new THREE.LatheGeometry(points, 32);

// 擠壓體 (Extrude) - shape, options
const shape = new THREE.Shape();
shape.moveTo(0, 0);
shape.lineTo(1, 0);
shape.lineTo(1, 1);
shape.lineTo(0, 1);
shape.lineTo(0, 0);

const extrudeSettings = {
  steps: 2,
  depth: 1,
  bevelEnabled: true,
  bevelThickness: 0.1,
  bevelSize: 0.1,
  bevelSegments: 3,
};
new THREE.ExtrudeGeometry(shape, extrudeSettings);

// 管道體 (Tube) - path, tubularSegments, radius, radialSegments, closed
const curve = new THREE.CatmullRomCurve3([
  new THREE.Vector3(-1, 0, 0),
  new THREE.Vector3(0, 1, 0),
  new THREE.Vector3(1, 0, 0),
]);
new THREE.TubeGeometry(curve, 64, 0.2, 8, false);

文字幾何體 (Text Geometry)

import { FontLoader } from "three/examples/jsm/loaders/FontLoader.js";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js";

const loader = new FontLoader();
loader.load("fonts/helvetiker_regular.typeface.json", (font) => {
  const geometry = new TextGeometry("Hello", {
    font: font,
    size: 1,
    depth: 0.2, // 舊版本中為 'height'
    curveSegments: 12,
    bevelEnabled: true,
    bevelThickness: 0.03,
    bevelSize: 0.02,
    bevelSegments: 5,
  });

  // 置中文字
  geometry.computeBoundingBox();
  geometry.center();

  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
});

BufferGeometry

所有幾何體的基類。將資料儲存為型別化陣列(Typed arrays)以提升 GPU 效率。

自訂 BufferGeometry

const geometry = new THREE.BufferGeometry();

// 頂點 (每個頂點 3 個浮點數: x, y, z)
const vertices = new Float32Array([
  -1,
  -1,
  0, // 頂點 0
  1,
  -1,
  0, // 頂點 1
  1,
  1,
  0, // 頂點 2
  -1,
  1,
  0, // 頂點 3
]);
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));

// 索引 (適用於索引幾何體 - 重複使用頂點)
const indices = new Uint16Array([
  0,
  1,
  2, // 三角形 1
  0,
  2,
  3, // 三角形 2
]);
geometry.setIndex(new THREE.BufferAttribute(indices, 1));

// 法向量 (光照運算所需)
const normals = new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]);
geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));

// UV (貼圖對齊所需)
const uvs = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
geometry.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));

// 顏色 (逐頂點顏色)
const colors = new Float32Array([
  1,
  0,
  0, // 紅色
  0,
  1,
  0, // 綠色
  0,
  0,
  1, // 藍色
  1,
  1,
  0, // 黃色
]);
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
// 需搭配設定:material.vertexColors = true

BufferAttribute 型別

// 常見屬性型別
new THREE.BufferAttribute(array, itemSize);

// 型別化陣列選項
new Float32Array(count * itemSize); // 位置、法向量、UV
new Uint16Array(count); // 索引(最多 65535 個頂點)
new Uint32Array(count); // 索引(較大的網格)
new Uint8Array(count * itemSize); // 顏色(0-255 範圍)

// 項目大小 (Item sizes)
// Position: 3 (x, y, z)
// Normal: 3 (x, y, z)
// UV: 2 (u, v)
// Color: 3 (r, g, b) 或 4 (r, g, b, a)
// Index: 1

修改 BufferGeometry

const positions = geometry.attributes.position;

// 修改頂點
positions.setXYZ(index, x, y, z);

// 存取頂點
const x = positions.getX(index);
const y = positions.getY(index);
const z = positions.getZ(index);

// 標記需要更新至 GPU
positions.needsUpdate = true;

// 位置變更後重新計算法向量
geometry.computeVertexNormals();

// 變更後重新計算邊界框/邊界球
geometry.computeBoundingBox();
geometry.computeBoundingSphere();

交錯緩衝區 (Interleaved Buffers,進階)

// 大型網格更高效的記憶體配置方式
const interleavedBuffer = new THREE.InterleavedBuffer(
  new Float32Array([
    // pos.x, pos.y, pos.z, uv.u, uv.v (每個頂點重複)
    -1, -1, 0, 0, 0, 1, -1, 0, 1, 0, 1, 1, 0, 1, 1, -1, 1, 0, 0, 1,
  ]),
  5, // stride (每個頂點的浮點數數量)
);

geometry.setAttribute(
  "position",
  new THREE.InterleavedBufferAttribute(interleavedBuffer, 3, 0),
); // 大小 3,偏移量 0
geometry.setAttribute(
  "uv",
  new THREE.InterleavedBufferAttribute(interleavedBuffer, 2, 3),
); // 大小 2,偏移量 3

EdgesGeometry 與 WireframeGeometry

// 邊緣線 (僅硬邊)
const edges = new THREE.EdgesGeometry(boxGeometry, 15); // 15 = 臨界角度 (threshold angle)
const edgeMesh = new THREE.LineSegments(
  edges,
  new THREE.LineBasicMaterial({ color: 0xffffff }),
);

// 線框 (所有三角形)
const wireframe = new THREE.WireframeGeometry(boxGeometry);
const wireMesh = new THREE.LineSegments(
  wireframe,
  new THREE.LineBasicMaterial({ color: 0xffffff }),
);

點雲 (Points)

// 建立點雲 (Point cloud)
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(1000 * 3);

for (let i = 0; i < 1000; i++) {
  positions[i * 3] = (Math.random() - 0.5) * 10;
  positions[i * 3 + 1] = (Math.random() - 0.5) * 10;
  positions[i * 3 + 2] = (Math.random() - 0.5) * 10;
}

geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));

const material = new THREE.PointsMaterial({
  size: 0.1,
  sizeAttenuation: true, // 尺寸隨距離衰減
  color: 0xffffff,
});

const points = new THREE.Points(geometry, material);
scene.add(points);

線條 (Lines)

// 線段 (連續連接的點)
const points = [
  new THREE.Vector3(-1, 0, 0),
  new THREE.Vector3(0, 1, 0),
  new THREE.Vector3(1, 0, 0),
];
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(
  geometry,
  new THREE.LineBasicMaterial({ color: 0xff0000 }),
);

// 閉合線段 (LineLoop)
const loop = new THREE.LineLoop(geometry, material);

// 獨立線段 (LineSegments,每兩點一對)
const segmentsGeometry = new THREE.BufferGeometry();
segmentsGeometry.setAttribute(
  "position",
  new THREE.BufferAttribute(
    new Float32Array([
      -1,
      0,
      0,
      0,
      1,
      0, // 線段 1
      0,
      1,
      0,
      1,
      0,
      0, // 線段 2
    ]),
    3,
  ),
);
const segments = new THREE.LineSegments(segmentsGeometry, material);

實例化網格 (InstancedMesh)

高效渲染大量相同幾何體的複本。

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const count = 1000;

const instancedMesh = new THREE.InstancedMesh(geometry, material, count);

// 設定每個實例(Instance)的變換矩陣
const dummy = new THREE.Object3D();
const matrix = new THREE.Matrix4();

for (let i = 0; i < count; i++) {
  dummy.position.set(
    (Math.random() - 0.5) * 20,
    (Math.random() - 0.5) * 20,
    (Math.random() - 0.5) * 20,
  );
  dummy.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, 0);
  dummy.scale.setScalar(0.5 + Math.random());
  dummy.updateMatrix();

  instancedMesh.setMatrixAt(i, dummy.matrix);
}

// 標記需要更新至 GPU
instancedMesh.instanceMatrix.needsUpdate = true;

// 選用:逐實例自訂顏色
instancedMesh.instanceColor = new THREE.InstancedBufferAttribute(
  new Float32Array(count * 3),
  3,
);
for (let i = 0; i < count; i++) {
  instancedMesh.setColorAt(
    i,
    new THREE.Color(Math.random(), Math.random(), Math.random()),
  );
}
instancedMesh.instanceColor.needsUpdate = true;

scene.add(instancedMesh);

在執行階段更新實例

// 更新單一實例
const matrix = new THREE.Matrix4();
instancedMesh.getMatrixAt(index, matrix);
// 修改矩陣...
instancedMesh.setMatrixAt(index, matrix);
instancedMesh.instanceMatrix.needsUpdate = true;

// 對 InstancedMesh 進行光線投射 (Raycasting)
const intersects = raycaster.intersectObject(instancedMesh);
if (intersects.length > 0) {
  const instanceId = intersects[0].instanceId;
}

InstancedBufferGeometry (進階)

用於變換(Transform)與顏色之外的逐實例自訂屬性。

const geometry = new THREE.InstancedBufferGeometry();
geometry.copy(new THREE.BoxGeometry(1, 1, 1));

// 新增逐實例屬性
const offsets = new Float32Array(count * 3);
for (let i = 0; i < count; i++) {
  offsets[i * 3] = Math.random() * 10;
  offsets[i * 3 + 1] = Math.random() * 10;
  offsets[i * 3 + 2] = Math.random() * 10;
}
geometry.setAttribute("offset", new THREE.InstancedBufferAttribute(offsets, 3));

// 在 Shader 中使用
// attribute vec3 offset;
// vec3 transformed = position + offset;

幾何體實用工具 (Geometry Utilities)

import * as BufferGeometryUtils from "three/examples/jsm/utils/BufferGeometryUtils.js";

// 合併幾何體 (必須具備相同的屬性)
const merged = BufferGeometryUtils.mergeGeometries([geo1, geo2, geo3]);

// 使用分組合併 (適用於多重材質)
const merged = BufferGeometryUtils.mergeGeometries([geo1, geo2], true);

// 計算切線 (法線貼圖所需)
BufferGeometryUtils.computeTangents(geometry);

// 交錯屬性以獲得更好的效能
const interleaved = BufferGeometryUtils.interleaveAttributes([
  geometry.attributes.position,
  geometry.attributes.normal,
  geometry.attributes.uv,
]);

常見模式

幾何體置中

geometry.computeBoundingBox();
geometry.center(); // 移動頂點,使中心點位於原點

縮放以適應尺寸

geometry.computeBoundingBox();
const size = new THREE.Vector3();
geometry.boundingBox.getSize(size);
const maxDim = Math.max(size.x, size.y, size.z);
geometry.scale(1 / maxDim, 1 / maxDim, 1 / maxDim);

複製與變換

const clone = geometry.clone();
clone.rotateX(Math.PI / 2);
clone.translate(0, 1, 0);
clone.scale(2, 2, 2);

變形目標 (Morph Targets)

// 基礎幾何體
const geometry = new THREE.BoxGeometry(1, 1, 1, 4, 4, 4);

// 建立變形目標
const morphPositions = geometry.attributes.position.array.slice();
for (let i = 0; i < morphPositions.length; i += 3) {
  morphPositions[i] *= 2; // X 軸縮放
  morphPositions[i + 1] *= 0.5; // Y 軸壓扁
}

geometry.morphAttributes.position = [
  new THREE.BufferAttribute(new Float32Array(morphPositions), 3),
];

const mesh = new THREE.Mesh(geometry, material);
mesh.morphTargetInfluences[0] = 0.5; // 50% 混合

效能建議

  1. 使用索引幾何體:透過索引重複使用頂點
  2. 合併靜態網格:使用 mergeGeometries 減少 Draw calls
  3. 使用 InstancedMesh:用於大量相同的物件
  4. 選擇合適的分段數量 (Segment counts):分段越多越平滑,但效能負擔較重
  5. 釋放未使用的幾何體:geometry.dispose()
// 常見用途的建議分段數
new THREE.SphereGeometry(1, 32, 32); // 良好品質
new THREE.SphereGeometry(1, 64, 64); // 高品質
new THREE.SphereGeometry(1, 16, 16); // 效能模式

// 使用完畢後釋放記憶體
geometry.dispose();

延伸閱讀

  • threejs-fundamentals - 場景設定與 Object3D
  • threejs-materials - 網格材質型別
  • threejs-shaders - 自訂頂點操作