携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情 >>
BufferGeometry
缓冲区类型几何体 BufferGeometry 是Three.js的核心类之一,立方体BoxBufferGeometry、圆柱体CylinderBufferGeometry、球体SphereBufferGeometry等几何体类的基类都是BufferGeometry。
BufferGeometry是面片、线或点几何体的有效表述。包括顶点位置,面片索引、法相量、颜色值、UV 坐标和自定义缓存属性值。使用 BufferGeometry 可以有效减少向 GPU 传输上述数据所需的开销。
// 创建一个缓冲类型的几何体对象
const geo = new THREE.BufferGeometry();
Float32Array
Float32Array 类型数组代表的是平台字节顺序为 32 位的浮点数型数组 (对应于 C 浮点数据类型) 例如,以下以长度作为参数的创建类型数组:
let f1 = new Float32Array(5);
f1 // [0,0,0,0,0]
BufferAttribute
这个类用于存储与 BufferGeometry 相关联的 attribute(例如顶点位置向量,面片索引,法向量,颜色值,UV坐标以及任何自定义 attribute )。利用 BufferAttribute,可以更高效的向GPU传递数据。
BufferAttribute( array : TypedArray, itemSize : Integer, normalized : Boolean )
array -- 必须是 TypedArray类型,用于实例化缓存。
itemSize -- 队列中与顶点相关的数据值的大小。举例,如果 attribute 存储的是三元组(例如顶点空间坐标、法向量或颜色值)则itemSize的值应该是3。
normalized -- (可选) 指明缓存中的数据如何与GLSL代码中的数据对应。
setAttribute
setAttribute(string name, string value):增加一个指定名称和值的新属性,或者把一个现有的属性设定为指定的值。
例如:
var input = document.createElement("input");\
input.setAttribute("type", "text");
代码示例
// 创建几何体对象
const geo = new THREE.BufferGeometry();
const count = 50;
// 50个三角形,每个三角形有三个顶点,每个点有xyz三个值,因此创建元素数量为(count*3*3)的类型数组
const positionsArray = new Float32Array(count * 3 * 3);
for (let i = 0; i < count * 3 * 3; i++) {
// 随机数
positionsArray[i] = (Math.random() - 0.5) * 2;
}
const positionAttribute = new THREE.BufferAttribute(positionsArray, 3);
// 给几何体对象的position属性添加值
geo.setAttribute("position", positionAttribute);
const mat = new THREE.MeshBasicMaterial({
color: "hotpink",
wireframe: true,
});
const cube = new THREE.Mesh(geo, mat);
scene.add(cube);