• ### Announcements

#### Archived

This topic is now archived and is closed to further replies.

# OpenGL what do think of this ? (opengl states)

## 19 posts in this topic

hello, right, from what I understand using glEnable()/glDisable() is expensive (right ?) so I started writing a few "state manager" functions, well 2 actually...:
// all states a false by default
bool bState_Texture2D=false;
bool bState_DepthTest=false;
bool bState_Blend=false;

// enables a state unless its already enabled
void mglEnable(int state)
{
switch(state)
{
case GL_TEXTURE_2D: if(!bState_Texture2D)
{
glEnable(GL_TEXTURE_2D);
bState_Texture2D = true;
}
break;

case GL_DEPTH_TEST:	if(!bState_DepthTest)
{
glEnable(GL_DEPTH_TEST);
bState_DepthTest = true;
}
break;

case GL_BLEND:		if(!bState_Blend)
{
glEnable(GL_BLEND);
bState_Blend = true;
}
break;
};
}

// disables a state unless already disabled
void mglDisable(int state)
{
switch(state)
{
case GL_TEXTURE_2D: if(bState_Texture2D)
{
glDisable(GL_TEXTURE_2D);
bState_Texture2D = false;
}
break;

case GL_DEPTH_TEST:	if(bState_DepthTest)
{
glDisable(GL_DEPTH_TEST);
bState_DepthTest = false;
}
break;

case GL_BLEND:		if(bState_Blend)
{
glDisable(GL_BLEND);
bState_Blend = false;
}
break;
};
}

Would this result in a speed increase at all or is this a complete waste of time ? or is there a different/better way of doing this ? cheers, rich Edit: code formattings a bit wonky, ah well Edited by - burnseh on December 30, 2001 6:44:09 PM Edited by - burnseh on December 30, 2001 6:44:55 PM
0

##### Share on other sites
>>Would this result in a speed increase at all<<

yes, i do it (though a lot more complicated)

http://uk.geocities.com/sloppyturds/gotterdammerung.html
0

##### Share on other sites
its the same thing i did and the speed increase is a real thing since i''m using a sort of ''shader'' for each object before rendering.

0

##### Share on other sites
zedzeek,

Would you mind elaborating on what you do, I am interested in building my own state manager.

Also, would a rendering manager by similar to a state manager? For example, to reduce state changes, I WOULD build a tree. Each node would be a state change and a linked list of data to render under that state. Then, rendering would traverse this tree of state nodes with data associated with each. Would this idea be the same as what is being discussed here??

Edited by - GalaxyQuest on January 2, 2002 8:31:52 PM
0

##### Share on other sites
It''s faster than just calling glEnable everytime, but that switch is a bottleneck, especially if you have a lot of cases. An easy way to avoid this is just writing some functions like mglEnableTexture2D and so on. Or define them as macros what''ll save you the function''s overhead. I use some trick of mine to optimize my code where I would need a switch, making the code as fast as seperate functions, but it needs special values for all cases and a lot of assembler, making it only usable if you may define all constants by yourself.
0

##### Share on other sites
my opengl statemanager
*handles sorting of states (for optimal performance).
*it will also LOG out all current states (so i can see if something is enabled which shouldnt be)
*a lot of error checking etc

btw its 3000+ LOC so its not a short piece of code

http://uk.geocities.com/sloppyturds/gotterdammerung.html
0

##### Share on other sites
There was an interesting discussion about redundant state changed on opengl.org''s forums and the thing that came out was that the redundant state changes should be avoided at any cost(well, almost at any cost). NVIDIA driver does not ignore them, while the driver _could_ check for redundant state changes they do not do it to favor well-written applications over badly-written(this was one of the points, search the advanced forum for more details).

While with many cases the state-manager could be a little slow, its still faster than a redundant state change in 99%. To speed up one could use macros, or, which I prefer, inline functions.

-Lev
0

##### Share on other sites
as lev saiz its a bad think if the driver checked. if it checked its gonna be slower so no drivers will do this for statechanges

shag - i havent been working much on gotterdammerung lately (been staying in a tent 5 days out of seven 4 the last couple of months whilst im away picking fruit thus no access to a computer) though the bright side is ive saved up enuf cash to buy me a geforce2mx if i can just make it to a decent sized town ill grab one (the nearest is 300km distance

http://uk.geocities.com/sloppyturds/gotterdammerung.html
0

##### Share on other sites
I posted my idea of using a tree with state "nodes" where at each node has a linked list of data to render. At render time the tree is traversed, therby it should minimize state changes to what is needed....but no one really had any comments on whether this "sounds" good. Ive heard of this idea elsewhere. Sound good??
0

##### Share on other sites
Hi,

I think that the switch method is "too slow" because it costs a lot of "if" instructions.
I had implement the state management through flag.

- to enable a state you wrote :
Enable (CF_CULL_FACE);
- CF_CULL_FACE is a flag define like below
#define CF_CULL_FACE 0 //cull is the 0-th bit
- a flag with the value of the state is declared:
long states;
- All render state are in an array :
GLenum allGLstates[] = { GL_CULL_FACE, ... };
- and enable code is like this :
void Enable (const ulong flag)
{
if ( GetFlagValue (states, (1< {
glEnable ( *(allGLstates+flag) );
SetFlag (states, (1< }
}
I think that this method could be faster that the switch. But there are a lot of methods to do it.

Vko
0

##### Share on other sites
Shag, even if certain drivers did actually ignore redundancy, there''s no guarantee of such a thing in the OpenGL specification. Therefore, if you were to make that assumption, your app might break somewhere. Never make assumptions.
0

##### Share on other sites
To Galaxy Quest , i ''ve heard too this kind of tree for opengl state switching but i think it has to deal with a lot of precomputing, in fact before rnedering you should check which of you actual calls to the opengl api are more expensive than other and thus put in the tree, then render it, i think its a good idea coupling with a sort of list of the slowest state change
done during initialization , but after some struggle i preferred to write an opengl state manager with inlined function and the speed gain is neat at the cost of some if , moreover i don''t think that some driver does a redundant check, at least at my actual knowledge

0

##### Share on other sites
If you actually inline the mglEnable and mglDisable functions, the compiler should optimise away the entire switch/case block, provided you use only constants as parameters.
0

##### Share on other sites
I should know by now never to post when pissed!!! I was bound to get it the wrong way round!

*quietly deleting above post*

Sorry for the misinformation!

Edited by - Shag on January 3, 2002 11:38:37 AM
0

##### Share on other sites
The faster way is to take the shader description from a file (Quake3 uses text plain files). While interpreting the shader, make an OpenGL Display List. To activate the shader you must call the glCallList function. I thought that''s the faster way.

"If you''''re gonna die, die with your boots on"
0

##### Share on other sites
Im sorta new to 3d, so I am unfamiliar with this term "SHADER" thrown around??

I also notice it referenced to quake(3). Did carmack coin this or is it specific to quake? I dont understand how this "shader" refers to states....
0

##### Share on other sites
Shaders allow to define a lot of triangles properties such as if the depth test is enble, the culling, textures stage (envmode, gentex...), rgb color ...

So all of that use states in OpenGL so to set up a shader system, you must have a good states switching manager.

For the glList it is a excellent methods to improve the speed !

Vko
0

##### Share on other sites
I haven't read any of the above replies yet so this may have already been said, but you can enumerate the names or place them in an array of some sort

glEnable(GL_TEXTURE_2D);
bState_Texture2D = true;

use stuff something like

Sorry, had to edit this. the source call doesn't understand the define statement or the // comments very well, or breaks either.
// following line not really necessary but makes it neat#define Statements_Number 3// texturing on by default#define Statements_Default_1 TRUE// depthtest on by default#define Statements_Default_2 TRUE// blend off by default#define Statements_Default_3 FALSEtypedef struct __mglState{ long int enable; char flag;}_mglState;_mglState mglState[Statements_Number]={ {  GL_TEXTURE_2D,Statements_Default_1 }, {  GL_DEPTH_TEST,Statements_Default_2 }, {  GL_BLEND,Statements_Default_3 }};#define mglEnable(x)\{\ if(mglState[x].flag==FALSE)\ {\  glEnable(mglState[x].enable);\  mglState[x].flag=TRUE;\ }\}#define mglDisable(x)\{\ if(mglState[x].flag==TRUE)\ {\  glDisable(mglState[x].enable);\  mglState[x].flag=FALSE;\ }\}

Beer - the love catalyst
good ol' homepage

PS - check if it is long int or what for glEnable/glDisable. I forgot. Make sure it is the same (pososibly glint) as it will save on converting the number format.

Edited by - Dredge-Master on January 5, 2002 11:59:44 AM
0

##### Share on other sites
Guys... I have a question.

What is the benefit to doing all of that work instead of calling glIsEnabled( stateToCheck );

Is that function slow or something?
0

##### Share on other sites
quote:
Original post by smitty1276
Is that function slow or something?

Yes, very slow in some cases.

-Lev
0

• ### Similar Content

• So it's been a while since I took a break from my whole creating a planet in DX11. Last time around I got stuck on fixing a nice LOD.
A week back or so I got help to find this:
https://github.com/sp4cerat/Planet-LOD
In general this is what I'm trying to recreate in DX11, he that made that planet LOD uses OpenGL but that is a minor issue and something I can solve. But I have a question regarding the code
He gets the position using this row
vec4d pos = b.var.vec4d["position"]; Which is then used further down when he sends the variable "center" into the drawing function:
if (pos.len() < 1) pos.norm(); world::draw(vec3d(pos.x, pos.y, pos.z));
Inside the draw function this happens:
draw_recursive(p3[0], p3[1], p3[2], center); Basically the 3 vertices of the triangle and the center of details that he sent as a parameter earlier: vec3d(pos.x, pos.y, pos.z)
Now onto my real question, he does vec3d edge_center[3] = { (p1 + p2) / 2, (p2 + p3) / 2, (p3 + p1) / 2 }; to get the edge center of each edge, nothing weird there.
But this is used later on with:
vec3d d = center + edge_center[i]; edge_test[i] = d.len() > ratio_size; edge_test is then used to evaluate if there should be a triangle drawn or if it should be split up into 3 new triangles instead. Why is it working for him? shouldn't it be like center - edge_center or something like that? Why adding them togheter? I asume here that the center is the center of details for the LOD. the position of the camera if stood on the ground of the planet and not up int he air like it is now.

Full code can be seen here:
https://github.com/sp4cerat/Planet-LOD/blob/master/src.simple/Main.cpp
If anyone would like to take a look and try to help me understand this code I would love this person. I'm running out of ideas on how to solve this in my own head, most likely twisted it one time to many up in my head
Toastmastern

• I googled around but are unable to find source code or details of implementation.
What keywords should I search for this topic?
Things I would like to know:
A. How to ensure that partially covered pixels are rasterized?
Apparently by expanding each triangle by 1 pixel or so, rasterization problem is almost solved.
But it will result in an unindexable triangle list without tons of overlaps. Will it incur a large performance penalty?
How to ensure proper synchronizations in GLSL?
GLSL seems to only allow int32 atomics on image.
C. Is there some simple ways to estimate coverage on-the-fly?
In case I am to draw 2D shapes onto an exisitng target:
1. A multi-pass whatever-buffer seems overkill.
2. Multisampling could cost a lot memory though all I need is better coverage.
Besides, I have to blit twice, if draw target is not multisampled.

• By mapra99
Hello

I am working on a recent project and I have been learning how to code in C# using OpenGL libraries for some graphics. I have achieved some quite interesting things using TAO Framework writing in Console Applications, creating a GLUT Window. But my problem now is that I need to incorporate the Graphics in a Windows Form so I can relate the objects that I render with some .NET Controls.

To deal with this problem, I have seen in some forums that it's better to use OpenTK instead of TAO Framework, so I can use the glControl that OpenTK libraries offer. However, I haven't found complete articles, tutorials or source codes that help using the glControl or that may insert me into de OpenTK functions. Would somebody please share in this forum some links or files where I can find good documentation about this topic? Or may I use another library different of OpenTK?

Thanks!

• Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
• By KarimIO
EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
Update: No crash occurs if I don't draw, just clear and swap.
static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));

• 11
• 11
• 14
• 19
• 14