简体   繁体   中英

normalizing mesh in three.js

I'm loading a mesh from an obj file, then trying to normalize it. However, I'm getting strange results. Here is the code for loading and centering the mesh:

var manager = new THREE.LoadingManager();
var loader = new THREE.OBJLoader(manager);
loader.load('http://jamesdedge.com/threejs/bunny.obj', function(object) {
  object.traverse(function(child) {
    if(child instanceof THREE.Mesh)
    {
      var geometry = child.geometry;
      var verts = geometry.vertices;
      var ctr = new THREE.Vector3(0.0, 0.0, 0.0);


      for(i = 0; i < verts.length; ++i)
        ctr.add(verts[i]);

      ctr.divideScalar(verts.length);

      for(i = 0; i < verts.length; ++i)
        verts[i].sub(ctr);
    }
  });

  scene.add(object);
});

This code should just center the mesh on the average of the vertex positions, but it seems to be causing a strange effect. You can see it on my website here: http://jamesdedge.com/threejs/tjs_demo.html

I don't see what is causing this, the ctr variable is giving me a valid vector and subtracting a vector from all the vertices will only reposition it.

Many of the vertices in this model are duplicates (ie the same javascript object is contained in the object multiple times), so ctr gets detracted from those vertices multiple times.

One way to address this is issue is to merge the vertices at the start of your traversal function, ie

var geometry = child.geometry;
geometry.mergeVertices();

This will also make your code run a bit faster as it has to process a lot less vertices.

You can use GeometryUtils.center() to center your whole mesh conveniently in the middle of the scene at (0,0,0). Anyway, just look at the source code of that function https://github.com/mrdoob/three.js/blob/master/src/extras/GeometryUtils.js This should give you a good idea on how to conquer your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM