简体   繁体   中英

How to improve the performance of the following code?

glBegin(GL_TRIANGLES)
for face in faces:
   for vertex_i in face:
      glVertex3f(*vertices[vertex_i])
glEnd()

Is there any way to replace the double for loops with a more efficient function/method?

Yes, you can use the fixed function attributes and define an array of vertex data glVertexPointer / glEnableClientState . In this case you can draw the triangles by glDrawElements . indices has to be an array of the triangle indices and vertexarray and array of the coordinate components. For Instance:

Once at initilization:

vertexarray = [c for v in vertices for c in v]
indices = [i for f in faces for i in f]

Per frame:

glVertexPointer(3, GL_FLOAT, 0, vertexarray)
glEnableClientState(GL_VERTEX_ARRAY)
glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, indices)
glDisableClientState(GL_VERTEX_ARRAY)

Alternatively you can use numpy.array

import numpy

vertexarray = numpy.array(vertices, dtype=numpy.float)
indices = numpy.array(faces, dtype=numpy.uint32)
glVertexPointer(3, GL_FLOAT, 0, vertexarray)
glEnableClientState(GL_VERTEX_ARRAY)
glDrawElements(GL_TRIANGLES, indices.size, GL_UNSIGNED_INT, indices)
glDisableClientState(GL_VERTEX_ARRAY)

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