使用js从头开始创建GLTF文件

A b*_*bou 7 html javascript 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]
Run Code Online (Sandbox Code Playgroud)

是否可以仅根据这些信息创建 gltf 文件?

Don*_*rdy 11

如果您能够在 Three.js 中创建网格或场景,则可以使用THREE.GLTFExporter导出。对于复杂模型,这可能是最简单的纯 JavaScript 解决方案。要在不使用完整 3D 库/引擎的情况下创建模型,请尝试gltf-transformgltf-js-utils,如下所示。

\n

gltf 变换

\n
import { Document, WebIO } from \'@gltf-transform/core\';\n\nconst doc = new Document();\n\nconst buffer = doc.createBuffer();\n\nconst position = doc.createAccessor()\n  .setType(\'VEC3\')\n  .setArray(new Float32Array(vertices))\n  .setBuffer(buffer);\nconst indices = doc.createAccessor()\n  .setType(\'SCALAR\')\n  .setArray(new Uint16Array(triangles))\n  .setBuffer(buffer);\n\nconst prim = doc.createPrimitive()\n  .setAttribute(\'POSITION\', position)\n  .setIndices(indices);\n\nconst mesh = doc.createMesh().addPrimitive(prim);\nconst node = doc.createNode().setMesh(mesh);\nconst scene = doc.createScene().addChild(node);\n\nconst glb = await new WebIO().writeBinary(doc); // \xe2\x86\x92 Uint8Array (.glb)\n
Run Code Online (Sandbox Code Playgroud)\n

gltf-js-utils

\n
const asset = new GLTFUtils.GLTFAsset();\nconst scene = new GLTFUtils.Scene();\nasset.addScene(scene);\n\nconst node = new GLTFUtils.Node();\nscene.addNode(node);\n\nconst vertices = [];\nfor (let i = 0; i < vertices.length; i += 3) {\n  const vertex = new GLTFUtils.Vertex();\n  vertex.x = vertices[i];\n  vertex.y = vertices[i + 1];\n  vertex.z = vertices[i + 2];\n  vertices.push(vertex);\n}\n\nconst mesh = new GLTFUtils.Mesh();\nmesh.material = [new GLTFUtils.Material()];\nfor (let i = 0; i < triangles.length; i += 3) {\n  const v1 = vertices[triangles[i]];\n  const v2 = vertices[triangles[i + 1]];\n  const v3 = vertices[triangles[i + 2]];\n  mesh.addFace(v1, v2, v3, {r: 1, g: 1, b: 1}, 0);\n}\nnode.mesh = mesh;\n\nconst object = GLTFUtils.exportGLTF(asset, {\n  bufferOutputType: GLTFUtils.BufferOutputType.DataURI,\n  imageOutputType: GLTFUtils.BufferOutputType.DataURI,\n});\n
Run Code Online (Sandbox Code Playgroud)\n

无论哪种情况,请考虑检查您的模型是否已正确创建(使用http://github.khronos.org/glTF-Validator/http://gltf-viewer.donmccurdy.com/),并在工具上提交错误(如果存在) \ 无法正常工作。

\n

  • 在 /sf/ask/4712362231/#67320885 中进一步回答。看起来 gltf-js-utils 不适用于 Node.js,您需要向他们报告功能请求。第一个解决方案(使用 gltf-transform)将在 Web 和 Node.js 中运行。 (2认同)
  • 这个 glTF 变换是我见过的第一个让我在可查看文件中生成立方体的示例。我找不到另一个“最小”的例子。 (2认同)