Wednesday, December 16, 2020

Loading 3D models in glTF formats

The Best Way to Send 3D Assets Over the Web: glTF: 

There have been many attempts at creating a standard 3D asset exchange format over the last thirty years or so. FBX, OBJ (Wavefront) and DAE (Collada) formats were the most popular of these until recently, although they all have problems that prevented their widespread adoption. 


The original glTF Version 1 never found widespread use and is no longer supported by three.s. glTF files can contain models, animations, geometries, materials, lights, cameras, or even entire scenes. This means you can create an entire scene in an external program then load it into three.js.


However, recently, a newcomer called glTF has become the de facto standard format for exchanging 3D assets on the web. glTF (GL Transmission Format), sometimes referred to as the JPEG of 3D, was created by the Kronos Group, the same people who are in charge of WebGL, OpenGL, and a whole host of other graphics APIs.


Originally released in 2017, glTF is now the best format for exchanging 3D assets on the web, and in many other fields. In this book, we’ll always use glTF, and if possible, you should do the same. It’s designed for sharing models on the web, so the file size is as small as possible and your models will load quickly.

glTF files come in standard and binary form. These have different extensions:

Standard .gltf files are uncompressed and may come with an extra .bin data file.

Binary .glb files include all data in one single file.

Both standard and binary glTF files may contain textures embedded in the file or may reference external textures. Since binary .glb files are considerably smaller, it’s best to use this type. On the other hand, uncompressed .gltf are easily readable in a text editor, so they may be useful for debugging purposes.

The GLTFLoader Plugin#

To load glTF files, first, you need to add the GLTFLoader plugin to your app. This works the same way as adding the OrbitControls plugin. You can find the loader in examples/jsm/loaders/GLTFLoader.js on the repo, and we have also included this file in the editor


import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'

const loader = new GLTFLoader();

const loadedData = await loader.loadAsync('path/to/yourModel.glb');



Another issue is that we cannot mark a constructor as async. A common solution to this is to create a separate .init method.



class Foobazzer {

  constructor() {

    // constructor cannot be async: ERROR!

    await loader.loadAsync('yourModel.glb');

  }


  async init() {

    // inside an async function: OK!

    await loader.loadAsync('yourModel.glb')

  }

}




References:

https://discoverthreejs.com/book/first-steps/load-models/


No comments:

Post a Comment