What are some best practices for OpenGL coding (esp. w.r.t. object orientation)?

前端 未结 5 1394
走了就别回头了
走了就别回头了 2020-12-12 10:01

This semester, I took a course in computer graphics at my University. At the moment, we\'re starting to get into some of the more advanced stuff like heightmaps, averaging n

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 10:24

    A standard technique is to insulate the objects' effect on the render state from each other by doing all changes from some default OpenGL state within a glPushAttrib/glPopAttrib scope. In C++ define a class with constructor containing

      glPushAttrib(GL_ALL_ATTRIB_BITS);
      glPushClientAttrib(GL_CLIENT_ALL_ATTRIB_BITS);
    

    and destructor containing

      glPopClientAttrib();
      glPopAttrib();
    

    and use the class RAII-style to wrap any code which messes with the OpenGL state. Provided you follow the pattern, each object's render method gets a "clean slate" and doesn't need to worry about prodding every possibly modified bit of openGL state to be what it needs.

    As an optimisation, typically you'd set the OpenGL state once at app startup into some state which is as close as possible to what everything wants; this minimisies the number of calls which need to be made within the pushed scopes.

    The bad news is these aren't cheap calls. I've never really investigated how many per second you can get away with; certainly enough to be useful in complex scenes. The main thing is to try and make the most of states once you've set them. If you've got an army of orcs to render, with different shaders, textures etc for armour and skin, don't iterate over all the orcs rendering armour/skin/armour/skin/...; make sure you set up the state for the armour once and render all the orcs' armour, then setup to render all the skin.

提交回复
热议问题