Correct way to iterate over all faces of an object?

Hello. I’m very new to this technology, so I would appreciate patience.

I’m not sure how to obtain positions and info of every face of a given mesh. I can obtain individual vertices through geometry.attributes.position.array. I had assumed the verts given this way are put together in order, tri by tri. Therefore I tried to loop through the array to put the coordinates into vector3s, so that three vector3s one after another would constitute one triangle.
From there, I wanted to draw lines over the edges of those triangles - so I did it by drawing lines from vertice 1 to 2, 2 to 3, and 1 to 3. This however was the wrong way to go about it as it resulted in whatever this is: Imgur: The magic of the Internet

Maybe the part where I drew lines was wrong. But even besides this error, I’m curious about what would be the “correct” way to achieve this, as well as making sure the method works with any model (I think many of them may use quads instead of triangles after all.) Any help would be appreciated.

usually meshes are “indexed” so there is an attribute on the geometry “.index” that contains the array…
so to iterate triangles, you step through the index, 3 numbers at a time, and each number is the index of the vertex in the .position attribute.

So sometimes I’ll do something like:

let points = geometry.attributes.position.array;
let index = geometry.index.array;
let v0=new Vector3();
let v1=new Vector3();
let v2=new Vector3();
for(let i=0;i<index.length;i+=3){
   let i0 = index[i] * 3;
   let i1 = index[i+1] * 3;
   let i2 = index[i+2] * 3;
   v0.set(points[i0],points[i0+1],points[i0+2]);
   v1.set(points[i1],points[i1+1],points[i1+2]);
   v2.set(points[i2],points[i2+1],points[i2+2]);
}

If the geometry doesn’t have a .index, then you just loop through:
geometry.attributes.position.array and grab 3 vertices at a time. (each vertex being 3 floats in that array)

.fromBufferAttribute is also an option.

1 Like

… yeah that’s probably way better and works with interleaved formats… :smiley:

1 Like