• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
IncidentRay

OpenGL
Dealing with bind-to-edit in OpenGL

15 posts in this topic

Hi all,

 

I'm looking for an elegant way to design a rendering API abstraction layer, but I keeping running into problems because of OpenGL's bind-to-edit model.  For example, one thing I want to do is cache/shadow the current render state to avoid redundant state changes, but bind-to-edit makes this especially difficult.

 

Here's some pseudocode (I'm pretending there is only one texture unit, for the sake of simplicity):

class Texture {
public:
    void Create()
    {
        glBindTexture(GL_TEXTURE_2D, m_name); // the wrong texture is now bound
        ... // code to create texture
    }
    GLuint GetGLName() const { return m_name; }
private:
    GLuint m_name;
};

class GraphicsDevice {
public:
    void SetTexture(Texture* texture)
    {
        if (texture != m_texture) {
            glBindTexture(GL_TEXTURE_2D, texture->GetGLName());
            m_texture = texture;
        }
    }
private:
    Texture* m_texture;
};

 

As you can see, the texture class needs to bind itself in order to create the OpenGL texture object, and so the the GraphicsDevice class now thinks a different texture is bound than the one that actually is.

 

The obvious way to fix this problem is to add a glGet(GL_TEXTURE_BINDING_2D) call in Texture::Create so that the previous texture can be bound afterwards, but glGet() calls are supposed to be avoided, right?

 

The only other solutions I can think of involve various ugly techniques such as circular dependencies, global variables, etc.

 

Is there a better way of solving this problem?

 

 

0

Share this post


Link to post
Share on other sites

It's probable that the value for this particular glGet will be cached by the driver and so won't need a round-trip to the GPU - as a general rule, if it doesn't rely on a previous draw call having completed in order to fetch the result, then you can assume that the driver may be able to do something intelligent with it (but do back up this assumption with some benchmarking first!)

 

On the other hand, you're still left with the annoyance of bind-to-modify.  One possible solution, if you're prepared to bump your hardware requirements appropriately, is to have a look at GL_EXT_direct_state_access - it may be just what you need.

2

Share this post


Link to post
Share on other sites

Direct state access does indeed look like a great solution, but I think the hardware requirements might be a bit high.  Interesting point about whether glGet values will be cached -- I'll remember that.

 

 

It really depends on the GL version you're aiming to support. Suppose it's 4...

 

 

That technique looks excellent, but unfortunately I need to support Mac OS X versions earlier than Lion, so I only have OpenGL 2.1 available.  If you have any suggestions that could work for OpenGL 2.1, that would be great.  I'm interested in your idea about having the device create the textures.  How would you implement this?  Would you just create the OpenGL texture object in a function in the GraphicsDevice class and then pass the GLuint into the Texture constructor? Or something else?

 

 

if you have to resort to glGet to query the state, then your design has flaws

 

 

Yeah, that's what I thought.  Do you have any pointers on how I could approach re-designing this so that I wouldn't need to use glGet?

 

Thanks!

Edited by IncidentRay
0

Share this post


Link to post
Share on other sites
It seems that in your case there are no shortcuts available, so you'll just have to do it the hard way.

You can do exactly what D3D11 does. This is pretty much like you suggested. Instead of having the method "Create" in the "Texture" class, move it to the "GraphicsDevice" class and rename it to something like "CreateTexture2D". This method will create the GL texture, create an object of "Texture", initialize its name (possibly through the constructor), restore the previously bounded texture correctly, and finally return the texture object. You'll have to do the same for copying (and probably a few more things). Your "Texture" class will essentially become a resource interface which will be able to do only simple things (like return its name, and delete itself).
Just keep in mind that if you're going to follow D3D11 on this, don't copy it exactly as it also supports views. This is way beyond the scope of 2.1 context. Not that it's impossible to emulate it (pretty much what FL9 does), but you'll just have to write a lot more code. Edited by max343
2

Share this post


Link to post
Share on other sites

Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

Also, what's FL9?  I googled it but I can't seem to find anything.

Edited by IncidentRay
0

Share this post


Link to post
Share on other sites

I have most of my resources pointed to as shared_ptr's. I know it is not the best solution but it works for now.

Also why do you need to cache the rendering state? In my code, a list is prepared containing all things to be rendered this frame. Then it is sorted to reduce state changes

and then rendered in a single function removing the need to store a global cache.

2

Share this post


Link to post
Share on other sites
Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

As a general rule, anything responsible for allocating memory should be responsible for deleting it: void GraphicsDevice::DestroyTexture(Texture t) { ... }

1

Share this post


Link to post
Share on other sites
Ok, that solution sounds good.
 
However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.
 
Do you have any ideas on how to fix this issue?
 
Also, what's FL9?  I googled it but I can't seem to find anything.

FL9 is feature level 9 mode of D3D11.

As for your first question, then yes it could potentially cause a problem, though this problem is much easier to identify with a simple assert during bind, just check whether the texture name seems valid (for instance, you can keep track on how many textures you've allocated).
This way of deletion is just how D3D does things, you don't have to do the same. As Aldacron already said, your GraphicsDevice can handle the deletion (and check if what you're deleting is currently bound). However, as far as the state goes textures can delete themselves because for that you don't need to bind them (you don't alter the state).
1

Share this post


Link to post
Share on other sites

Thanks for the replies!

 

I have most of my resources pointed to as shared_ptr's. I know it is not the best solution but it works for now.

Also why do you need to cache the rendering state? In my code, a list is prepared containing all things to be rendered this frame. Then it is sorted to reduce state changes

and then rendered in a single function removing the need to store a global cache.

 

This would definitely work, but I just prefer it if the caching is implemented in the graphics API layer, so that the user doesn't have to worry about it.  It seems to me that you might end up implementing render state caching multiple times, for each type of graphics you need to draw; e.g., the actual game world, the UI, etc.  I also think this could pose a problem if you are dynamically generating geometry -- i.e., filling a vertex buffer with data, then drawing it, filling it with new data, and so on.  How would you have a list of objects in this case?

 

 

Ok, that solution sounds good.

 

However, one thing I just thought of that could be a problem with both these designs is texture deletion.  Once the Texture instance is destroyed (either with the delete keyword or when it goes out of scope) won't the GraphicsDevice class have a dangling pointer? For example, if you called CreateTexture2D() and the object pointed to by m_texture had been deleted, when the GraphicsDevice instances tries to restore the previously bound texture, it will be calling a member function of a deleted object, causing a crash.

 

Do you have any ideas on how to fix this issue?

 

As a general rule, anything responsible for allocating memory should be responsible for deleting it: void GraphicsDevice::DestroyTexture(Texture t) { ... }

 

This is a good idea.  What's interesting though, is the texture class doesn't really do anything in this case -- it just stores a texture name and returns it.  Also, if you need an instance of GraphicsDevice to destroy a texture, it would then be necessary to pass a pointer/reference to it around more.  For example, if an object creates a texture in its constructor, and destroys it in its destructor, it would need to maintain either a pointer or a reference to the GraphicsDevice, so that it could call DestroyTexture.  This wouldn't be needed if you could delete a texture without needing the device, but I'm not quite sure how to get around this.

 

 

[quote name='max343' timestamp='1356428689' post='5014135']
FL9 is feature level 9 mode of D3D11.
[/quote]

 

Ah ok, I'm not too familiar with D3D terminology.

 

[quote name='max343' timestamp='1356428689' post='5014135']
As for your first question, then yes it could potentially cause a problem, though this problem is much easier to identify with a simple assert during bind, just check whether the texture name seems valid (for instance, you can keep track on how many textures you've allocated).
This way of deletion is just how D3D does things, you don't have to do the same. As Aldacron already said, your GraphicsDevice can handle the deletion (and check if what you're deleting is currently bound). However, as far as the state goes textures can delete themselves because for that you don't need to bind them (you don't alter the state).
[/quote]

 

I'm having trouble understanding how this would be implemented.  How would you get the texture name without calling a function of the Texture object (which might have been deleted)?  I'm also not sure how keeping a count of the number of textures allocated would help you determine whether a texture name is valid.  I thought OpenGL wasn't required to return a contiguous range of texture names.  I do like the idea of being able to model D3D on this -- could you maybe give a simple example of some code for this?  Many thanks.

0

Share this post


Link to post
Share on other sites
As opposed to general rendering errors (binding invalid textures), controlled crashes (asserts) are good! They're much easier to debug.

Suppose your GraphicsDevice object holds an already deleted pointer to some Texture. While running in debug mode, when an object is being deleted its associated memory is being overwritten with something like BAADF00D. So you just call the method GetName of your invalid Texture object, and in almost all cases one of the two will happen, either you'll get an exception for trying to read an unallocated memory, or you'll get the magic number. Those magic numbers are big, I mean really big, there's no way you're going to allocate billion textures. So you can just make your assert like this (in SetTexture or directly in GetName):
assert(glIsTexture(texture->GetName()) == GL_TRUE);

glIsTexture is not a cheap call, but it's in the assert, so it'll run only in debug mode. If you want to do something similar in release mode, then you can make the check less costly (but also much less precise) by first overwriting the value of m_texture in the destructor with something big and by changing the check to:
if(texture->GetName() > 1<<20) // Or some other magic number
  throw TextureException;
Although a GL implementation isn't obligated to use contiguous numbers, all implementations I've worked with, do it.

As for your other questions. If GraphicsDevice is going to be responsible for deletion, then yes, you'll probably need to hold the object in many places. Though I think it's reasonable enough, because in 99% of cases there should be exactly one object of GraphicsDevice.
Also, planning to match D3D is good, but you need to know what version to target (10 or 11) and where to draw the line. What you want to do is probably closer to 10 than to 11. Targeting for 11 will require more abstraction in some layers, most notably separating the Device from RenderingContext. For instance, creating a texture is a Device operation, while binding a texture is a RenderingContext operation.
I really cannot summarize D3D10/11 in a few lines of text here, but you can use MSDN and the SDK for pointers on how to do it best. Edited by max343
0

Share this post


Link to post
Share on other sites

That looks useful for debugging, but how would you rewrite this code so that it doesn't cause the assert to fail?

GraphicsDevice device;
Texture* texture1 = device.CreateTexture(...);
device.SetTexture(texture1);
delete texture1;
Texture* texture2 = device.CreateTexture(...); // device dereferences dangling pointer; crash

 

 

Should I just just add a device.SetTexture(NULL) call before deleting the texture1 object?  This could become quite tedious in the generic case, with multiple texture units, though.  For example, before deleting any texture you would have to do,

for (unsigned i = 0; i < device.GetNumTextureUnits(); ++i) {
    if (device.GetTexture(i) == texture) {
        device.SetTexture(i, NULL);
    }
}
Edited by IncidentRay
0

Share this post


Link to post
Share on other sites

Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

If the resources get created first (CreateTexture), then a render starts with SetTexture serving as a bind that protects against a re-bind,

the GraphicsDevice doesn't need to have any knowledge about whether a texture object exists or not. Might want to have a reset method in GraphicsDevice that sets m_texture to NULL, as well as do that in the swapBuffer/Present method of GraphicsDevice and you're good to go.

0

Share this post


Link to post
Share on other sites

That looks useful for debugging, but how would you rewrite this code so that it doesn't cause the assert to fail?



GraphicsDevice device;
Texture* texture1 = device.CreateTexture(...);
device.SetTexture(texture1);
delete texture1;
Texture* texture2 = device.CreateTexture(...); // device dereferences dangling pointer; crash

 
 



This is problematic. Best way to deal with this is to let GraphicsDevice to deallocate the texture (instead of leaving it to Texture). If deallocating currently bound texture, then just reset the texture pointer to NULL.
There's also the option of using one texture unit as a temporary unit for all those things like creating textures. This is less pretty, and leaves you with one unit less, but it'll help minimize the amount of rebinds.
0

Share this post


Link to post
Share on other sites
Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

 

In theory this is a valid line of questioning.

 

In practice you may need to update a texture (or buffer object) at any point in time, and you may also have a state filtering system set up (to catch redundant glBind* calls) which would also be messed up.  Things are never quite so clean in the real world, unfortunately.

0

Share this post


Link to post
Share on other sites

[quote name='max343' timestamp='1356516002' post='5014372']
This is problematic. Best way to deal with this is to let GraphicsDevice to deallocate the texture (instead of leaving it to Texture). If deallocating currently bound texture, then just reset the texture pointer to NULL.
There's also the option of using one texture unit as a temporary unit for all those things like creating textures. This is less pretty, and leaves you with one unit less, but it'll help minimize the amount of rebinds.
[/quote]

 

Yeah, moving the deallocation function into the GraphicsDevice class is probably the best solution.  Reserving one texture unit for modifying/creating textures would work fairly well, but I don't think it's worth losing the extra texture unit, and this approach doesn't extend to other resource types (buffer objects, shaders, FBOs, etc.)

 

 

[quote name='beans222' timestamp='1356498994' post='5014334']

Do you really need to create a texture in the middle of a time when the GraphicsDevice will be caring which texture is bound?

[/quote]

 

This is a good point, but as mhagain says, there likely are some cases where you may need to modify or create resources in the middle of rendering.  In any case, I'd prefer a system where you can create resources whenever you want; I think it's exposing an implementation detail if you restrict users to only doing so at the start of a frame.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • By Toastmastern
      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
      Thanks in advance
      Toastmastern
       
       
    • By fllwr0491
      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?
      B. A-buffer like bitmask needs a read-modiry-write operation.
         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!
    • By Solid_Spy
      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));  
  • Popular Now