Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call glEnable and glDisable every time I draw something?

Tags:

opengl

How often should I call OpenGL functions like glEnable() or glEnableClientState() and their corresponding glDisable counterparts? Are they meant to be called once at the beginning of the application, or should I keep them disabled and only enable those features I immediately need for drawing something? Is there a performance difference?

like image 935
zoul Avatar asked Apr 29 '09 12:04

zoul


2 Answers

Warning: glPushAttrib / glPopAttrib are DEPRECATED in the modern OpenGL programmable pipeline.

If you find that you are checking the value of state variables often and subsequently calling glEnable/glDisable you may be able to clean things up a bit by using the attribute stack (glPushAttrib / glPopAttrib).

The attribute stack allows you to isolate areas of your code and such that changes to attribute in one sections does not affect the attribute state in other sections.

void drawObject1(){
  glPushAttrib(GL_ENABLE_BIT);
   
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_LIGHTING);    

  /* Isolated Region 1 */

  glPopAttrib();
}        

void drawObject2(){
  glPushAttrib(GL_ENABLE_BIT);

  glEnable(GL_FOG);
  glEnable(GL_GL_POINT_SMOOTH);    

   /* Isolated Region 2 */

  glPopAttrib();
}    
    
void drawScene(){
  drawObject1();
  drawObject2();
}

Although GL_LIGHTING and GL_DEPTH_TEST are set in drawObject1 their state is not preserved to drawObject2. In the absence of glPushAttrib this would not be the case. Also - note that there is no need to call glDisable at the end of the function calls, glPopAttrib does the job.

As far as performance, the overhead due of individual function calls to glEnable/glDisable is minimal. If you need to be handling lots of state you will probably need to create your own state manager or make numerous calls to glGetInteger... and then act accordingly. The added machinery and control flow could made the code less transparent, harder to debug, and more difficult to maintain. These issues may make other, more fruitful, optimizations more difficult.

The attribution stack can aid in maintaining layers of abstraction and create regions of isolation.

glPushAttrib manpage

like image 102
Marc Avatar answered Nov 11 '22 04:11

Marc


"That depends".

If you entire app only uses one combination of enable/disable states, then by all means just set it up at the beginning and go.

Most real-world apps need to mix, and then you're forced to call glEnable() to enable some particular state(s), do the draw calls, then glDisable() them again when you're done to "clear the stage".

State-sorting, state-tracking, and many optimization schemes stem from this, as state switching is sometimes expensive.

like image 42
unwind Avatar answered Nov 11 '22 05:11

unwind