我有一些顶点和面数据只是简单的 x,y,z 坐标像这样:
var vertices = [1,0,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,0]
var triangles = [0,1,2,2,3,0,4,5,1,1,0,4,6,7,5,5,4,6,3,2,7,7,6,3,7,1,5,7,2,1,4,0,6,0,3,6]
是否可以仅从这些信息中创建一个 gltf 文件?
我有一些顶点和面数据只是简单的 x,y,z 坐标像这样:
var vertices = [1,0,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,0,1,0]
var triangles = [0,1,2,2,3,0,4,5,1,1,0,4,6,7,5,5,4,6,3,2,7,7,6,3,7,1,5,7,2,1,4,0,6,0,3,6]
是否可以仅从这些信息中创建一个 gltf 文件?
如果您能够在 three.js 中创建网格或场景,则可以使用THREE.GLTFExporter导出。对于复杂模型,这可能是最简单的纯 JavaScript 解决方案。要在不使用完整 3D 库/引擎的情况下创建模型,请尝试gltf-transform或gltf-js-utils,如下所示。
import { Document, WebIO } from '@gltf-transform/core';
const doc = new Document();
const buffer = doc.createBuffer();
const position = doc.createAccessor()
.setType('VEC3')
.setArray(new Float32Array(vertices))
.setBuffer(buffer);
const indices = doc.createAccessor()
.setType('SCALAR')
.setArray(new Uint16Array(triangles))
.setBuffer(buffer);
const prim = doc.createPrimitive()
.setAttribute('POSITION', position)
.setIndices(indices);
const mesh = doc.createMesh().addPrimitive(prim);
const node = doc.createNode().setMesh(mesh);
const scene = doc.createScene().addChild(node);
const glb = new WebIO().writeBinary(doc); // → ArrayBuffer
const asset = new GLTFUtils.GLTFAsset();
const scene = new GLTFUtils.Scene();
asset.addScene(scene);
const node = new GLTFUtils.Node();
scene.addNode(node);
const vertices = [];
for (let i = 0; i < vertices.length; i += 3) {
const vertex = new GLTFUtils.Vertex();
vertex.x = vertices[i];
vertex.y = vertices[i + 1];
vertex.z = vertices[i + 2];
vertices.push(vertex);
}
const mesh = new GLTFUtils.Mesh();
mesh.material = [new GLTFUtils.Material()];
for (let i = 0; i < triangles.length; i += 3) {
const v1 = vertices[triangles[i]];
const v2 = vertices[triangles[i + 1]];
const v3 = vertices[triangles[i + 2]];
mesh.addFace(v1, v2, v3, {r: 1, g: 1, b: 1}, 0);
}
node.mesh = mesh;
const object = GLTFUtils.exportGLTF(asset, {
bufferOutputType: GLTFUtils.BufferOutputType.DataURI,
imageOutputType: GLTFUtils.BufferOutputType.DataURI,
});
无论哪种情况,请考虑检查您的模型是否正确创建(使用http://github.khronos.org/glTF-Validator/或http://gltf-viewer.donmccurdy.com/)并在工具上提交错误(如果他们'工作不正常。