I want to convert the vertices of a triangle strip to independent triangles so I can draw them using OpenGL's GL_TRIANGLES primitive type.

However, none of the following two codes works and I cannot understand why:

for(int i = 0; i < triangleStripVertices.size() - 2; i++) {
    triangleVertices.add(triangleStripVertices.get(i));
    triangleVertices.add(triangleStripVertices.get(i + 1));
    triangleVertices.add(triangleStripVertices.get(i + 2));
}

and this one doesn't work either:

for(int i = 0; i < triangleStripVertices.size() - 2; i++) {
    if(i % 2 == 1) {
        triangleVertices.add(triangleStripVertices.get(i));
        triangleVertices.add(triangleStripVertices.get(i + 2));
        triangleVertices.add(triangleStripVertices.get(i + 1));         
    } else {
        triangleVertices.add(triangleStripVertices.get(i));
        triangleVertices.add(triangleStripVertices.get(i + 1));
        triangleVertices.add(triangleStripVertices.get(i + 2));
    }
}

what am I doing wrong here?

The broken output looks like:

broken output

有帮助吗?

解决方案

You're pretty close in your attempt, but there's one point you're missing. Triangle strips have a concept of the "oldest vertex", which is the one that is removed once a triangle is processed. Because of needing to keep the facedness (sometimes called vertex winding) of the triangles the same in the strip, the oldest vertex isn't the next one in the list; it flip-flops between the oldest and second oldest in the list.

For example, let's say you have a list of vertex indices

GLuint indices = { 0, 1, 2, 3, 4, 5 };

and you call glDrawElements() with that list. The following triangles will be rendered, using the vertex indices from the above list: (0, 1, 2), (2, 1, 3), (2, 3, 4), (4, 3, 5).

So, to unwind a triangle strip into a set of triangles, you need to take that into account. Here's a snippet that will do what you want:

for (int i = 0; i < triangleStripVertices.size() - 2; i++) {
    if (i % 2) {
        triangleVertices.add(triangleStripVertices.get(i + 1));
        triangleVertices.add(triangleStripVertices.get(i));
        triangleVertices.add(triangleStripVertices.get(i + 2));         
    } 
    else {
        triangleVertices.add(triangleStripVertices.get(i));
        triangleVertices.add(triangleStripVertices.get(i + 1));
        triangleVertices.add(triangleStripVertices.get(i + 2));
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top