【问题标题】:Create a GLTF file from scratch using js使用 js 从头开始​​创建 GLTF 文件
【发布时间】:2019-01-21 09:48:56
【问题描述】:

我有一些顶点和面数据只是简单的 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做一些研究
  • 我已经使用了threejs并按预期工作,但我需要一种纯javascript方式来使用这些数据创建缓冲区和访问器
  • 如果可以在threejs中创建网格,可以使用GLTFExporter导出。我不知道纯 JS 导出器,但是如果您稍微阅读一下 glTF 规范,从头开始编写应该不是不切实际的。
  • 其实这可能是你需要的:npmjs.com/package/gltf-js-utils
  • @DonMcCurdy 谢谢你,这对我很有帮助,你能把它作为答案发布,这样我就可以关闭问题了

标签: javascript html gltf


【解决方案1】:

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

gltf 变换

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

gltf-js-utils

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/),如果工具不能正常工作,请在工具上提交错误。

【讨论】:

  • 是否可以在 nodejs 上设置纹理 wint gltf-js-utils?我看到它只允许应用 HTMLImageTag
  • stackoverflow.com/questions/67319460/… 中进一步回答。看起来 gltf-js-utils 不是为在 node.js 中工作而设计的,您需要向他们报告功能请求。第一个解决方案(使用 gltf-transform)可以在 web 和 node.js 中运行。
  • gltf-transform 有更复杂的 API :( 想要 js-utils
猜你喜欢
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 2021-04-12
  • 2021-11-18
相关资源
最近更新 更多