Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a GLTF file from scratch using js

I have some vertices and faces data just simple x,y,z coordinate Like this :

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]

Is it possible to create a gltf file from just those information's ?

like image 474
A bou Avatar asked Jul 24 '26 11:07

A bou


1 Answers

If you're able to create a mesh or scene in three.js, you can export using THREE.GLTFExporter. For complex models this is probably the easiest JavaScript-only solution. To create a model without using a full 3D library/engine, try gltf-transform or gltf-js-utils as shown below.

gltf-transform

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 = await new WebIO().writeBinary(doc); // → Uint8Array (.glb)

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,
});

In either case, consider checking that your model was created correctly (with http://github.khronos.org/glTF-Validator/ or http://gltf-viewer.donmccurdy.com/) and filing bugs on the tools if they're not working properly.

like image 94
Don McCurdy Avatar answered Jul 27 '26 00:07

Don McCurdy