0
\$\begingroup\$

I have a full 3D collision mesh that is represented by a list of vertices and another list of indices. I need to convert the list of vertices and the list of indices into a set of triangles.

First I tried to group every three vertices from the vertex list into a triangle, so vertices 0-2 were triangle 0, vertices 3-5 were triangle 1, etc. But that method did not produce the same triangles I see on the original mesh.

Then I remembered the indices list, but I didn't know how to use them. So I came here to ask: how can I use the indices list to make my list of triangles?

\$\endgroup\$
  • \$\begingroup\$ @DMGregory Is my latest edit useful \$\endgroup\$ – user116458 Aug 6 '18 at 11:17
  • 1
    \$\begingroup\$ Yes, you're finally at least mentioning what you've tried and what it is about the problem that you didn't understand. That lets users figure out what kind of help you need. Next time, start with that. ;) \$\endgroup\$ – DMGregory Aug 6 '18 at 11:20
4
\$\begingroup\$

Typically, your list of indices looks like this:

[ 1st vertex index of triangle 0,
  2nd vertex index of triangle 0,
  3rd vertex index of triangle 0,

  1st vertex index of triangle 1,
  2nd vertex index of triangle 1,
  3rd vertex index of triangle 1,

  1st vertex index of triangle 2,
  ...etc
]

So the three vertices of triangle i are:

  • vertices[indices[3 * i]]
  • vertices[indices[3 * i + 1]]
  • vertices[indices[3 * i + 2]]
\$\endgroup\$
0
\$\begingroup\$

Here is what worked for me. Hope it helps someone else:

List<Triangle> triangles = new ArrayList<>();

    for(int i = 0;i * 3 < indices.length;i++) {
        Triangle triangle = null;

        Vertex p = new Vertex(vertices.get(indices[3 * i]));
        Vertex p1 = new Vertex(vertices.get(indices[3 * i + 1]));
        Vertex p2 = new Vertex(vertices.get(indices[3 * i + 2]));

        triangle = new Triangle(p,p1,p2);

        triangles.add(triangle);
    }
\$\endgroup\$
  • 2
    \$\begingroup\$ You'll want your for loop to run over the indices, not the vertices. In general, each vertex could participate in many triangles, so you might have more triangles than vertices. Your for loop should look something like for(int i = 0; i*3 < indices.size(), i++) \$\endgroup\$ – DMGregory May 29 '18 at 17:35
  • \$\begingroup\$ @DMGregory like this \$\endgroup\$ – user116458 May 30 '18 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy