Sign in to follow this  
hamsham

OpenGL Hypothesizing a new lighting method.

Recommended Posts

Hi Everybody. This is my first post so please be nice. I'm new to graphics programming with OpenGL and have only done basic tutorials thus far.

 

After going through the deferred rendering tutorial at http://ogldev.atspace.co.uk/, I was kind of left with the impression that the process of deferred lighting is a bit backwards. Forward rendering looks great with all lights but the only problem is that rendering everything causes an absurd amount of iteration (render time = light count * mesh count). Deferred rendering shows promise (light count + mesh count) but it also means that, in some implementations, you may have to drastically increase the amount of vertices rendered. Additionally, shadows are a bit more difficult to implement. I was thinking of another approach to rendering lights with the speed of deferred rendering but the visual quality of forward rendering.

Basically, there could be two cube maps stored on the GPU which could hold the color, intensity, and position of every light in a scene. The renderer would place every light of the scene into these cube maps in a first pass, then render each mesh in a second pass. The first cube map could add individual RGB and Intensity values of every light, clamped to four individual byte values while the second cube map could hold each light's position (clamped to 3 individual bytes). Next, after each light has been rendered to the cube maps, every mesh of the scene can sample them when they're processed in another pass by the pixel/fragment shader. This means that you get the speed of a deferred renderer (render time = light count + mesh count) with a drastically reduced memory footprint.

 

Would anyone be able to shed some light as to the plausibility of rendering a scene this way? Right now, I have calculated that both buffers would be a total size of about 2.6 Mb, which seems like a hell of a lot less than what is typically required by a deferred renderer. Like I said above, I'm a graphics novice; this is all just theory and I have no idea how it would be implemented in practice, I'm just looking for feedback.

 

My memory calculation is as follows:

4 bytes for the first cube map + 3 bytes for the second cube map = 7 total bytes per pixel, across both cubemaps (math whiz here).

Each cube map is made of 6 2D textures.

Each 2D texture is 256 pixels wide by 256 pixels high.

Therefore, the total memory used by the entire process is 7 bytes * 256 wide * 256 high * 6 textures = 2752512 bytes = 2.6 Mb total.

 

 

Share this post


Link to post
Share on other sites

That could only work for non positional lights.

I was initially going to test this with point lights but I guess I'll have to figure out how to add directional and spot lighting. Throwing more textures at the GPU in order to hold each light's properties will end up using as much memory as regular deferred rendering.
At least with point lights, the light vector could be calculated pretty easily (in the fragment shader) by getting the vector from the camera to a mesh and reflecting that against the mesh's surface so that you can find what light[s] to pluck out from the first cube map. Once you do that, then you could also extract the lights position from the second cube map.

Share this post


Link to post
Share on other sites

"This means that you get the speed of a deferred renderer (render time = light count + mesh count) with a drastically reduced memory footprint."

 

The speed of a deferred renderer has nothing to do with your algorithm at all. The speed in deferred comes in the fact that you run the pixel shader once for every pixel on the screen. You make pixel shader overdraw = 0. In your algorithm you would still draw an object with a pixel shader and then another object can come along and redraw over that pixel and have to run a pixel shader again (2x for the same pixel).

The algorithm itself doesnt make much sense to me. Why is it a cube map again? What does a mesh use to find the correct light in the cubemap? Why wouldnt it just be a 2D texture of the lights? How exactly does the light get mapped into the cubemap?(its not a 3d Array, its simply 6 faces that designate up down left righ bottom top.

Yes, you don't have the experience enough to finalize your algorithm. I'm planning to do something similar to this, however you have some holes to get to the end and you are in no way related to deferred rendering by this approach.

Share this post


Link to post
Share on other sites

The speed of a deferred renderer has nothing to do with your algorithm at all. The speed in deferred comes in the fact that you run the pixel shader once for every pixel on the screen. You make pixel shader overdraw = 0. In your algorithm you would still draw an object with a pixel shader and then another object can come along and redraw over that pixel and have to run a pixel shader again (2x for the same pixel).

 

In this, the pixel shader would be run once for every light to store it in the cube maps, then once more for every mesh when rendering to a final output buffer; just like a deferred renderer. Overdraw can occur regardless of what rendering method is used but it can be reduced if each object is sorted in the scene based on its position from the camera (but I'm not really worried about it at the moment).

 

 

The algorithm itself doesnt make much sense to me. Why is it a cube map again? What does a mesh use to find the correct light in the cubemap? Why wouldnt it just be a 2D texture of the lights? How exactly does the light get mapped into the cubemap?(its not a 3d Array, its simply 6 faces that designate up down left righ bottom top.

 

The lights would be stored in a cubemap for nothing more than indexing really. I imagine it to be a 3D lookup table to get an angle of incidence between the camera, a mesh, and a light in the scene.

 

So for the first pass on the scene, each light's position is stored in one cube map, then its RGB and intensity values in the other. Think of having a skybox but with a bunch of lights' colors and positions only. In order to actually get the data into the cubemaps, I was imagining having the 6 sides of the cube maps set up as render targets that would be bound to the output of a fragment shader.

 

After each light has been rendered to, then in a second fragment shader, a scene's meshes could be rendered to from the view of a camera. Then, as I noted earlier, you could find out how to color each fragment by getting a vector from the camera's position towards the mesh, reflect that vector off the mesh, and finally find which light that reflection vector is pointing at in the cube maps. Since each light's position is stored, you can determine how to color a fragment based on its position and intensity with regards to the final scene.

Share this post


Link to post
Share on other sites

Ideas are just that. Consider throwing together a prototype/proof of concept that actually shows the lighting method and relevant shaders, and perhaps allows for some preliminary verification and performance testing. Also consider looking into tiled forward rendering, as I think that's where things are headed in the future.

Edited by Promit

Share this post


Link to post
Share on other sites


In this, the pixel shader would be run once for every light to store it in the cube maps

 

Generally, a cubemap represents the scene from a certain view point. For instance, they can be used to render the scene around a point and used to draw rough environment reflections on objects. "rough" because it will only be accurate from one specific position in the scene. Of course it works well for things like a skybox (which is "infinitely" far away and looks the same from every point in the scene).

 

So... what exactly are you putting in your cubemap? Is the end result that there will be a single texel somewhere in the cubemap for each light?

 

 


you could find out how to color each fragment by getting a vector from the camera's position towards the mesh, reflect that vector off the mesh, and finally find which light that reflection vector is pointing at in the cube maps.

 

What are the chances that that reflection vector will line up exactly with the texel that contains the light information? Pretty small. Or does your cubemap contain large areas that cover a light's influence? If so, how would you handle overlapping lights?

 

(also, reflecting the eye vector off the mesh will help you calculate the specular component, what about diffuse?)

 

Maybe I'm just not understanding your description, but I still don't see how your algorithm makes any sense. As Promit suggested, try coming up with a proof of concept. I think it will quickly become obvious where things fall apart.

Share this post


Link to post
Share on other sites

I'm not going to go into much depth here, but almost everything you have said really shows your inexperience. Based on that, I would just say don't plan on doing this. You can make games look good with forward rendering, deferred whatever. Don't try to implement the greatest lighting model when you aren't fully grasping things. Really quickly:

"then once more for every mesh when rendering to a final output buffer; just like a deferred renderer."Overdraw can occur regardless of what rendering method is used"
Uh....deferred rendering has 0 pixel shader overdraw. The initial filling of the buffers of course will have some overdraw, but its not like its wasting time running crazy pixel shaders. All lighting shaders are run once for ever pixel. 0 pixel shader (lighting) overdraw.

"but it can be reduced if each object is sorted in the scene based on its position from the camera (but I'm not really worried about it at the moment)."
Yes. In a deferred renderer you would be doing this as well to reduce the G-Buffer initial pass overdraw, but not the lighting pass overdraw.

"Think of having a skybox but with a bunch of lights' colors and positions only."
So I have a 3d light: A and B.  A = vec3(-100,10,0) B = vec3(-110,10,0). Where would these be rendered into the cube map?  If you use simply their position as a vector to render to the cube map....they render to the same spot. A cube map is 6 2D textures, it is not a 3d array. A 3D array would be a cube map with slices cut through it. and even then an actual 3d Texture wouldnt work for your algorithm. Not going to explain to you why because I don't think you will get it.


"Then, as I noted earlier, you could find out how to color each fragment by getting a vector from the camera's position towards the mesh, reflect that vector off the mesh, and"
This wont work. If you are actually rendering the cube map lights as actual spherical geometry... then what you have essentially is cube mapping/environment mapping. But you would have to render all the lights each frame for each mesh. So much wrong with this algorithm.
And if you are talking about rendering geometry, what happens when 2 lights geometry overlap in the cube map?
 

Share this post


Link to post
Share on other sites

"What are the chances that that reflection vector will line up exactly with the texel that contains the light information? Pretty small. Or does your cubemap contain large areas that cover a light's influence? If so, how would you handle overlapping lights?"

 

Same thing I said pretty much. If you are only rendering to 1 pixel your light information, then it is still wrong. Noither approaches will work.

Share this post


Link to post
Share on other sites

I'd like to also put it on record that shadow mapping with deferred shading is no harder than it is with forward shading, and in fact many games use a very simple deferred approach for shadows (Crysis 1 for example) rather than applying shadows in the forward pass.

Share this post


Link to post
Share on other sites

This may only work at all if you sample "cones" rather than reflection vectors, and only for lights at infinity. Surfaces are not perfect mirrors, so one point on the screen that you look at does not correspond to exactly one point in the "sky" (i.e. the cubemap). It corresponds to an area. Unless you come up with something very clever (something like a distance map with a direction vector to the closest "cardinal light" might actually be an idea...) you will need to do a lot of samples so it looks kind of good -- and then it's cheaper to just do normal forward rendering and evaluating all lights as usual.

 

Also, if a light is not "at infinity", let's say 5 meters above you, then an object which is at your position and an object which is  5 meters away will get light from the same angle and with the same intensity. Which is... just wrong, and just looks very bad.

 

Also I'm afraid that you are trying to solve the wrong problem. First of all, forward shading doesn't look better than deferred shading. It will usually look somewhat different, but not necessarily "better" as such. The one big advantage of forward shading is that transparency is a no-brainer (and also antialiasing is easier to get working), but other than that there is no reason why correctly implemented deferred shading should look any worse. On the contrary, you can get a much more consistent lighting and put a lot more shader work into every pixel.

 

On the other hand, deferred shading is not faster.  It is more scaleable in respect of geometry and lights (in particular shadow-casting lights) at the expense of higher memory and bandwidth demands. Deferred shading has a complexity of numbers of lights multiplied with [at most] the resolution plus a more-or-less constant setup, instead of numbers of lights multiplied with number of vertices. Also, deferred shading (if no such thing as clustered DS is done) needs one shadow map at a time, for the one light that is currently being shaded whereas forward shading needs shadow maps for all lights that may affect any of the drawn geometry at once.

Share this post


Link to post
Share on other sites

First of all, forward shading doesn't look better than deferred shading. It will usually look somewhat different, but not necessarily "better" as such. The one big advantage of forward shading is that transparency is a no-brainer (and also antialiasing is easier to get working), but other than that there is no reason why correctly implemented deferred shading should look any worse. On the contrary, you can get a much more consistent lighting and put a lot more shader work into every pixel.

 

Most deferred renderers will sacrifice some precision with normals, position(depth reconstruction is not 100% accurate) and with other paramaters that can cause some quality loss on final image. Luckily this is mostly last gen games where this is visible.

Share this post


Link to post
Share on other sites

This technique would work for the one point in the scene that you render as the center of the cube maps.  When you render the lights into the cube map, you're doing it relative to this one point.  So that one point would be lit correctly.  Everything else would be skewed.

Share this post


Link to post
Share on other sites

I used a technique on the Wii that's very similar to the one mentioned in the OP, to get lots of dynamic lights on it's crappy hardware... except, instead of global cube-maps for the scene, each object had it's own cube-map, so that directionality and attenuation worked properly (at least on a per-mesh granularity - not very good for large meshes). Also, instead of cube-maps, we used sphere-maps for simplicity.... and you can't just render a light into a single texel, you have to render a large diffused blob of light.

The lighting is obviously much more approximate than doing it traditionally per-pixel -- the surface normal is evaluated per-pixel, but the attenuation and direction to light are evaluated per mesh. This means that for small meshes, it's pretty good, but for large meshes, all lights start to look like directional lights.

The other down-side is that you can't use nice BRDF's like Blinn-Phong or anything...

 

In general, this is part of a family of techniques known as image based lighting, and yes, it's common to combine a bunch of non-primary lights into a cube-map, etc -- e.g. think of every pixel in your sky-dome as a small directional light. Using it as a replacement for primary lights, across an entire scene, is a bit less popular.

Share this post


Link to post
Share on other sites

I used a technique on the Wii that's very similar to the one mentioned in the OP, to get lots of dynamic lights on it's crappy hardware... except, instead of global cube-maps for the scene, each object had it's own cube-map, so that directionality and attenuation worked properly (at least on a per-mesh granularity - not very good for large meshes). Also, instead of cube-maps, we used sphere-maps for simplicity.... and you can't just render a light into a single texel, you have to render a large diffused blob of light.

The lighting is obviously much more approximate than doing it traditionally per-pixel -- the surface normal is evaluated per-pixel, but the attenuation and direction to light are evaluated per mesh. This means that for small meshes, it's pretty good, but for large meshes, all lights start to look like directional lights.

The other down-side is that you can't use nice BRDF's like Blinn-Phong or anything...

 

In general, this is part of a family of techniques known as image based lighting, and yes, it's common to combine a bunch of non-primary lights into a cube-map, etc -- e.g. think of every pixel in your sky-dome as a small directional light. Using it as a replacement for primary lights, across an entire scene, is a bit less popular.

For kinghunt http://www.youtube.com/watch?v=9mU-lcJnyvg

 

I did very similar trick but instead of sphere maps I used spherical harmonics. I also calculated aproximated visibility function per object against all other objects. This was so fast that even particles could be light emitters.

Edited by kalle_h

Share this post


Link to post
Share on other sites

While I can see how image-based lighting might work great on mobile devices, how do these translate to desktops where the ALU/TEX ratio is much higher? I would guess that using literally abundant ALU to compute a dozen lights that are visible from one fragment may very well be faster than to do yet an additional texture lookup?

Share this post


Link to post
Share on other sites

While I can see how image-based lighting might work great on mobile devices, how do these translate to desktops where the ALU/TEX ratio is much higher? I would guess that using literally abundant ALU to compute a dozen lights that are visible from one fragment may very well be faster than to do yet an additional texture lookup?

In console/PC games, it's standard to use IBL for background/fill/bounce/ambient lights (GI), instead of a flat ambient colour, and then compute the direct lighting analytically.

 

For film-quality IBL, you don't pre-convolve the probes, and each pixel has to read thousands of importance-sampled values from the IBL probes and integrate them using the BRDF (which is both ALU and TEX heavy)...

Share this post


Link to post
Share on other sites

 

While I can see how image-based lighting might work great on mobile devices, how do these translate to desktops where the ALU/TEX ratio is much higher? I would guess that using literally abundant ALU to compute a dozen lights that are visible from one fragment may very well be faster than to do yet an additional texture lookup?

In console/PC games, it's standard to use IBL for background/fill/bounce/ambient lights (GI), instead of a flat ambient colour, and then compute the direct lighting analytically.

 

For film-quality IBL, you don't pre-convolve the probes, and each pixel has to read thousands of importance-sampled values from the IBL probes and integrate them using the BRDF (which is both ALU and TEX heavy)...

 

 

Which is why most people pre-convolve the probes. I'm not sure UE4 does, then again I'm not sure exactly what it is they're even doing. All I've gathered is "cube map array" and their ability to relight the probes in realtime.

Share this post


Link to post
Share on other sites

 

 

While I can see how image-based lighting might work great on mobile devices, how do these translate to desktops where the ALU/TEX ratio is much higher? I would guess that using literally abundant ALU to compute a dozen lights that are visible from one fragment may very well be faster than to do yet an additional texture lookup?

In console/PC games, it's standard to use IBL for background/fill/bounce/ambient lights (GI), instead of a flat ambient colour, and then compute the direct lighting analytically.

 

For film-quality IBL, you don't pre-convolve the probes, and each pixel has to read thousands of importance-sampled values from the IBL probes and integrate them using the BRDF (which is both ALU and TEX heavy)...

 

 

Which is why most people pre-convolve the probes. I'm not sure UE4 does, then again I'm not sure exactly what it is they're even doing. All I've gathered is "cube map array" and their ability to relight the probes in realtime.

 

 

They pre-convolve their specular probes, by convolving the specular BRDF with a given roughness assuming that V=N. They also take the standard approach of storing the results for different roughness values in the mip levels of the cubemap (higher roughnesses go into lower-res mip levels), and then selecting the mip per-pixel based on the surface roughness. They also refactored things a bit so that they can approximate the appropriate BRDF response for different viewing angles by precomputing values into lookup textures and indexing them at runtime. This sort of approach is becoming fairly common.

I'm not sure what they do for diffuse, but I would assume that they store SH probes which is what most people do these days. 

Edited by MJP

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  

  • Forum Statistics

    • Total Topics
      628281
    • Total Posts
      2981797
  • 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