关于three.js:Threejs教程顶点索引复用顶点数据

5次阅读

共计 2196 个字符,预计需要花费 6 分钟才能阅读完成。

举荐:将 NSDT 场景编辑器退出你 3D 工具链
其余工具系列:NSDT 简石数字孪生

顶点索引复用顶点数据

通过几何体 BufferGeometry 的顶点索引属性 BufferGeometry.index 能够设置几何体顶点索引数据,如果你有 WebGL 根底很容易了解顶点索引的概念,如果没有也没有关系,上面会通过一个简略的例子形象阐明。比方绘制一个矩形网格模型, 至多须要两个三角形拼接而成,两个三角形,每个三角形有三个顶点,也就是说须要定义 6 个顶点地位数据。对于矩形网格模型而言,两个三角形有两个顶点地位是重合的。也就是说能够反复的地位能够定义一次,而后通过通过顶点数组的索引值获取这些顶点地位数据。

不应用顶点索引

上面通过几何体六个顶点定义了两个三角形,几何体的顶点地位数据、顶点法向量数据都是 6 个。

var geometry = new THREE.BufferGeometry(); // 申明一个空几何体对象
// 类型数组创立顶点地位 position 数据
var vertices = new Float32Array([
  0, 0, 0, // 顶点 1 坐标
  80, 0, 0, // 顶点 2 坐标
  80, 80, 0, // 顶点 3 坐标

  0, 0, 0, // 顶点 4 坐标   和顶点 1 地位雷同
  80, 80, 0, // 顶点 5 坐标  和顶点 3 地位雷同
  0, 80, 0, // 顶点 6 坐标
]);
// 创立属性缓冲区对象
var attribue = new THREE.BufferAttribute(vertices, 3); // 3 个为一组
// 设置几何体 attributes 属性的地位 position 属性
geometry.attributes.position = attribue
var normals = new Float32Array([
  0, 0, 1, // 顶点 1 法向量
  0, 0, 1, // 顶点 2 法向量
  0, 0, 1, // 顶点 3 法向量

  0, 0, 1, // 顶点 4 法向量
  0, 0, 1, // 顶点 5 法向量
  0, 0, 1, // 顶点 6 法向量
]);
// 设置几何体 attributes 属性的地位 normal 属性
geometry.attributes.normal = new THREE.BufferAttribute(normals, 3); // 3 个为一组, 示意一个顶点的 xyz 坐标

顶点索引

上面代码通过几何体 BufferGeometry 的顶点索引 BufferGeometry.index 定义了一个矩形。通过顶点索引组织网格模型三角形的绘制,因为矩形的两个三角形有两个顶点地位反复,所以顶点地位数据、顶点法向量数据都只须要定义 4 个就能够。

var geometry = new THREE.BufferGeometry(); // 申明一个空几何体对象
// 类型数组创立顶点地位 position 数据
var vertices = new Float32Array([
  0, 0, 0, // 顶点 1 坐标
  80, 0, 0, // 顶点 2 坐标
  80, 80, 0, // 顶点 3 坐标
  0, 80, 0, // 顶点 4 坐标
]);
// 创立属性缓冲区对象
var attribue = new THREE.BufferAttribute(vertices, 3); // 3 个为一组
// 设置几何体 attributes 属性的地位 position 属性
geometry.attributes.position = attribue
var normals = new Float32Array([
  0, 0, 1, // 顶点 1 法向量
  0, 0, 1, // 顶点 2 法向量
  0, 0, 1, // 顶点 3 法向量
  0, 0, 1, // 顶点 4 法向量
]);
// 设置几何体 attributes 属性的地位 normal 属性
geometry.attributes.normal = new THREE.BufferAttribute(normals, 3); // 3 个为一组, 示意一个顶点的 xyz 坐标
通过顶点索引组织顶点数据,顶点索引数组 indexes 通过索引值指向顶点地位 geometry.attributes.position、顶点法向量 geometry.attributes.normal 中顶面数组。// Uint16Array 类型数组创立顶点索引数据
var indexes = new Uint16Array([
  // 0 对应第 1 个顶点地位数据、第 1 个顶点法向量数据
  // 1 对应第 2 个顶点地位数据、第 2 个顶点法向量数据
  // 索引值 3 个为一组,示意一个三角形的 3 个顶点
  0, 1, 2,
  0, 2, 3,
])
// 索引数据赋值给几何体的 index 属性
geometry.index = new THREE.BufferAttribute(indexes, 1); // 1 个为一组

创立顶点索引数组的时候,能够依据顶点的数量抉择类型数组 Uint8Array、Uint16Array、Uint32Array。对于顶点索引而言抉择整型类型数组,对于非索引的顶点数据,须要应用浮点类型数组 Float32Array 等。

类型数组 位数 字节 类型形容 C 语言等价类型
Int8Array 8 1 有符号 8 位整型 int8_t
Int16Array 16 2 有符号 16 位整型 int16_t
Uint16Array 16 2 无符号 16 位整型 int16_t
Int32Array 32 4 有符号 32 位整型 int32_t
Uint32Array 32 4 无符号 32 位整型 uint32_t
Float32Array 32 4 单精度 (32 位) 浮点数 float
Float64Array 64 8 双精度 (64 位) 浮点数 double

3D 建模学习工作室

正文完
 0