Sign in to follow this  
IncidentRay

OpenGL Dealing with bind-to-edit in OpenGL

Recommended Posts

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?

 

 

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.

Share this post


Link to post
Share on other sites
As mhagain pointed out, direct state access is a great solution to your problem.

However, you have alternatives. It really depends on the GL version you're aiming to support. Suppose it's 4, then you can force your textures to be created only once (let's say in the constructor), and from there on they can only be modified by ARB_copy_image, or casted by ARB_texture_view. Also, the only entity that can create textures is the device. With this design you'll have less problems, and it also resembles the D3D design.

Also, what mhagain said about the state being cached in the driver is true. Generally the driver stores the current state in a local copy. It's just less pretty to have all those glGet in your code. A rule of thumb is that if you have to resort to glGet to query the state, then your design has flaws. Edited by max343

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

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

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

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.

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) { ... }

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).

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.

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

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

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.

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.

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.

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.

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628314
    • Total Posts
      2982024
  • Similar Content

    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
    • By Abecederia
      So I've recently started learning some GLSL and now I'm toying with a POM shader. I'm trying to optimize it and notice that it starts having issues at high texture sizes, especially with self-shadowing.
      Now I know POM is expensive either way, but would pulling the heightmap out of the normalmap alpha channel and in it's own 8bit texture make doing all those dozens of texture fetches more cheap? Or is everything in the cache aligned to 32bit anyway? I haven't implemented texture compression yet, I think that would help? But regardless, should there be a performance boost from decoupling the heightmap? I could also keep it in a lower resolution than the normalmap if that would improve performance.
      Any help is much appreciated, please keep in mind I'm somewhat of a newbie. Thanks!
    • By test opty
      Hi,
      I'm trying to learn OpenGL through a website and have proceeded until this page of it. The output is a simple triangle. The problem is the complexity.
      I have read that page several times and tried to analyse the code but I haven't understood the code properly and completely yet. This is the code:
       
      #include <glad/glad.h> #include <GLFW/glfw3.h> #include <C:\Users\Abbasi\Desktop\std_lib_facilities_4.h> using namespace std; //****************************************************************************** void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; const char *vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; const char *fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\n\0"; //******************************* int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "My First Triangle", nullptr, nullptr); if (window == nullptr) { cout << "Failed to create GLFW window" << endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { cout << "Failed to initialize GLAD" << endl; return -1; } // build and compile our shader program // vertex shader int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << endl; } // fragment shader int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << endl; } // link shaders int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog); cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up vertex data (and buffer(s)) and configure vertex attributes float vertices[] = { -0.5f, -0.5f, 0.0f, // left 0.5f, -0.5f, 0.0f, // right 0.0f, 0.5f, 0.0f // top }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), //and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO // as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally // modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind // VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to // bind it every time, but we'll do so to keep things a bit more organized glDrawArrays(GL_TRIANGLES, 0, 3); // glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; } //************************************************** // process all input: query GLFW whether relevant keys are pressed/released // this frame and react accordingly void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } //******************************************************************** // glfw: whenever the window size changed (by OS or user resize) this callback function executes void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } As you see, about 200 lines of complicated code only for a simple triangle. 
      I don't know what parts are necessary for that output. And also, what the correct order of instructions for such an output or programs is, generally. That start point is too complex for a beginner of OpenGL like me and I don't know how to make the issue solved. What are your ideas please? What is the way to figure both the code and the whole program out correctly please?
      I wish I'd read a reference that would teach me OpenGL through a step-by-step method. 
  • Popular Now