some1else2
some1else2

Reputation: 25

Unable to load GLTF object

I'm attempting to render a GLTF model with three.js but have been unable to do so. If anyone could pinpoint what the error in my code is, I'd be glad.

        import {GLTFLoader} from "./GLTFLoader.js";

        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth/window.innerHeight,
            .01,
            1000
        );
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);

        var loader = new THREE.GLTFLoader();

        loader.load("scene.gltf",function(gltf){
            var obj;
            scene.add(gltf.scene);
        });
        var light = new THREE.HemisphereLight(0xFFFFFF, 0x000000, 2);
        scene.add(light);
        camera.position.set(0,0,100);
        function animate(){
            requestAnimationFrame(animate);
            renderer.render(scene,camera);
        }
        animate();

Upvotes: 0

Views: 4011

Answers (2)

Rafael Kuhn
Rafael Kuhn

Reputation: 67

First check your browser's console, (shortcut generally ctrl+shift+i), if there's an error there, the path could be wrong, also you could console.log(gltf) to see if the object really loaded in your "onload" function, if it logs undefined, there's probably an error.

It could also be that your model is too big and not rendering (it's outside of your camera render area) or it's your camera that's inside of it and all the object faces are pointing outwards (inward faces are culled by default in some materials, it's called back-face culling). To test this in your mesh, you can add inside your "onload" function:

gltf.scene.traverse(obj => {
  if (obj.type === "Mesh") {
    obj.doubleSided = true;
    // or maybe
    // obj.material.side = THREE.DoubleSide;
  }
})

This will iterate through all of the objects inside your gltf file, check which ones are meshes, and mark them as double sided, so both inwards and outwards faces will render and back-faces won't be culled.

Also check if reducing your object's scale to something like 0.1 or 0.01 makes it visible.

Upvotes: 0

kartik chitade
kartik chitade

Reputation: 31

First you can download the free 3d model gltf file from sketchfab and then convert it into glb format using this website. Then compress the file with:

npx gltf-pipeline -i scene.glb -o model.glb --draco.compressionLevel=10

By using:

npx gltfjsx model.glb

You will get a js file. Just copy the model function and * boom! * your work will be done. For an example, you can refer visit demo.

Upvotes: 3

Related Questions