7

I'm rendering an object with textures using MTL and OBJ files with Three.js. My code here works but my model is displayed as flat shaded. How do I enable smooth shading?

var scene = new THREE.Scene();  
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath('assets/');
mtlLoader.setBaseUrl('assets/');
mtlLoader.load('asset.mtl', function(materials) {

    materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('assets/');
    objLoader.load('asset.obj', function(object) {

       //
       // This solved my problem
       //
       object.traverse(function(child) {
           if(child instanceof THREE.Mesh)
           {
              child.material.shading = THREE.SmoothShading;
           }
       });
       //
       //

       scene.add(object);
    });
});

EDIT: I updated my code with a solution that fixed my problem based on the accepted answer.

5
  • most probably: stackoverflow.com/questions/29202480/…
    – gaitat
    Jun 25, 2017 at 19:28
  • I had tried that one already but it doesn't do anything for me.
    – Berry Blue
    Jun 25, 2017 at 20:52
  • Have you taken a look in asset.mtl ? Maybe it is set in there somewhere
    – 2pha
    Jun 26, 2017 at 1:56
  • 1
    can you post an image of what you are rendering?
    – gaitat
    Jun 26, 2017 at 12:47
  • 1
    Does the shading look "flat" or "faceted"? Better if you share a screenshot. Jun 27, 2017 at 8:14

2 Answers 2

9

It could be one of two things that I can think of right now.

It could be that the material is set to FlatShading. In this case just somehow retrieve the object and use object.material.shading = THREE.SmoothShading; to fix.

If that doesn't change it, it's possible that the object contains per-vertex-normals (meaning that every vertex of every triangle has a normal attached to it) and that all normals for each triangle point in the same direction. This is something that should better be solved in the 3d-editing process, but you can also re-compute the normals in three.js:

object.geometry.computeVertexNormals(true);

This should [1] recompute the normals for smooth surfaces. However, it will only work for regular Geometries and Indexed BufferGeometries (or, to put it the other way around: it won't work if the geometry doesn't have information about vertices being reused for adjacent faces)

[1]: I didn't test it myself and just go after what I just read in the code

0
0

You may need to smooth geometry as follows:

geometry = BufferGeometryUtils.mergeVertices(geometry, 0.1);
geometry.computeVertexNormals(true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.