• 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
Anessen

OpenGL
Confused: Very large environments

23 posts in this topic

I've got an idea for a 3D application, but I'm trying to understand how I'm going to get this to work. The 3D scene created with OpenGL uses 32bit integers. What if the environment that I want to render is bigger than this? I need to use 64bit integers to render a 3D model a certain distance away from the "camera". I've played games like Frontier First Encounters that render huge environments in 3D and I'm trying to understand how this is done without having to jump through many hoops... anyone tried anything like this before?
0

Share this post


Link to post
Share on other sites
I've never actually done it myself, but the principle is pretty simple, If some thing is close, you should render a high poly version of the model, and if some thing is far away, you should only render a low poly version of the model. THis is called Level of Detail (LOD).

Afaik openGL uses float for distance.. So I really don't see how thats a problem. If it's because of your own map format, you should consider to split your map into regions.

Hope this helps :)
0

Share this post


Link to post
Share on other sites
If you want to render a truly huge scene, such as a realistic-scale solar system, or worse yet, universe, then you have to use some sort of coordinate hierarchy.

The idea is that you might model the Earth in metres, and attach it to the solar system, which is modeled in kilometres. The solar system in turn is attached to the milky way, which is modeled in light-years, which is connected to the local cluster, measured in millions of lightyears.

When you go to render the scene, you traverse the hierarchy downwards, and at each level, a 32-bit float has plenty of precision.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by Anessen
The 3D scene created with OpenGL uses 32bit integers. What if the environment that I want to render is bigger than this? I need to use 64bit integers to render a 3D model a certain distance away from the "camera".


Where does it use integers?
0

Share this post


Link to post
Share on other sites
I've had a similar problem with a game I'm working on right now. You, probably, won't need to go as far as I have to solve the problem. Work out how large your game world (that is, one area of it at a time) and decide your units from there. In case you have ran into an actual problem with why floats are bad (you will want to be using floats, not integers in OpenGL, unless maybe you're on an embedded platform using OpenGL ES), this is my solution:

In my game I've divided the world up into zones - each zone is it's own coordinate system, but it has a 3D integer vector for it's location rather than a 32bit float or matrix transform - that way I get perfect precision for a zone's location. Each zone is 1000x1000x1000 units (-500 to 500), and that's float. Done it like this so I have perfect precision at all times, whilst not having too many zones (solar system...big place). It's all stored in a hash map for quick lookup and so I don't need to have zones exist that don't actually have anything in them. Dynamically create/destroy them as objects pass in and out of them. Rendering far away zones is done with some manual placement and scaling on the model view per zone - precision doesn't matter for rendering far off objects really, not in my case. For very far away zones I can just render them as a star, or not at all. For the record it's an outer space game. I worked out that just travelling earth-moon distance would put me well outside of decent precision, and I'm working in 1 unit is 1km! Sounds overkill, but it works nicely having 1Mmx1Mmx1Mm zones - as I only need good precision down to around 1m.
0

Share this post


Link to post
Share on other sites
Thanks for your responses!

And yeah I meant float for actually rendering the scene, the world coordinates of the objects are stored as integers. I will need to use LODs for objects otherwise the poly count is going to go just insane for a start.

What I am making a game that would have to model a whole solar system at a time in real scale. What I am having problems understanding is how you can get enough precision to render this scene using float values, because the player's movement must be smooth relative to close objects but at the same time I can see the 3D models of objects that are many thousands of kilometers away (very large planets, stars etc).

I understand that I can model the locations of objects in a very large environment using a coordinate hierarchy, basically subdividing out grid spaces. What I'm having problems with is drawing that. I am quite new to 3D graphics (moving from 2D) so maybe I'm just missing something obvious here.
0

Share this post


Link to post
Share on other sites
You need to keep track of your objects with 64-bit floating point vectors and matrices to model an entire solar system, yet be able to move the camera to any position and see small details on each planet. I did this in my engine for exactly this reason.

You need to perform one other "trick" to make this work with current GPUs (because they only support 32-bit floating-point numbers). When your camera is near a particular planet, you need to make that object (or the camera) the "zero point", and subtract that position from the position of every object to compute "current pseudo-world coordinates positions". In most cases, it is easier to make the camera position the origin of this coordinate system, though that is a bit problematic if your engine supports multiple cameras (like mine does). Once you convert the positions of other objects into this new coordinate system, you can convert those positions to 32-bit floating-point and let the GPU shaders render as usual.

BTW, you have a choice --- you can simply translate the origin of the world coordinate-system to the camera position, but leave the axes alone, or you can transform the coordinate system so the axes of the camera become the axes of your new coordinate system. I prefer the former, largely because I support multiple cameras.
0

Share this post


Link to post
Share on other sites
OK, I understand that. But, I just tried to make a very large environment using a 1 unit to 1 metre scale... I drew a very large box (imagine drawing a box around Jupiter, 142984000 metres in each direction) and I had a camera that I could move around and moved forwards and backwards in very large steps too (millions of metres). What I found is that there were a lot of graphical glitches with bits of the box disappearing as I moved the camera around.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by Anessen
What I found is that there were a lot of graphical glitches with bits of the box disappearing as I moved the camera around.
That is caused by a lack of depth buffer precision, which is the next issue you have to deal with. Sean O'Neil has a post on the subject, which method I am using currently. Ysenaya and a few others had a neater solution using logarithmic depth buffers, which you should be able to find around GameDev.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by swiftcoder
Quote:
Original post by Anessen
What I found is that there were a lot of graphical glitches with bits of the box disappearing as I moved the camera around.
That is caused by a lack of depth buffer precision, which is the next issue you have to deal with. Sean O'Neil has a post on the subject, which method I am using currently. Ysenaya and a few others had a neater solution using logarithmic depth buffers, which you should be able to find around GameDev.
Note that recent GPUs and shader-languages support floating-point depth buffers. I believe this is more-or-less equivalent to logarithmic depth buffers, except floating-point depth buffers are now a built-in capability, and therefore requires NO special code in your program or shaders.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by maxgpgpu
Quote:
Original post by swiftcoder
Quote:
Original post by Anessen
What I found is that there were a lot of graphical glitches with bits of the box disappearing as I moved the camera around.
That is caused by a lack of depth buffer precision, which is the next issue you have to deal with. Sean O'Neil has a post on the subject, which method I am using currently. Ysenaya and a few others had a neater solution using logarithmic depth buffers, which you should be able to find around GameDev.
Note that recent GPUs and shader-languages support floating-point depth buffers. I believe this is more-or-less equivalent to logarithmic depth buffers, except floating-point depth buffers are now a built-in capability, and therefore requires NO special code in your program or shaders.


It doesn't matter if you're planning ahead or not - not everyone can or wants to upgrade. It's still a very good idea to provide something for those who won't be upgrading to the most recent hardware.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by maxgpgpu
Note that recent GPUs and shader-languages support floating-point depth buffers. I believe this is more-or-less equivalent to logarithmic depth buffers, except floating-point depth buffers are now a built-in capability, and therefore requires NO special code in your program or shaders.
I can't comment on that (although cameni agrees with you). However, I personally found that a floating point depth buffer was insufficient even for a planetary renderer (let alone the entire solar system), thus why I am using a variation on Sean O'Neil's method. I may revisit this decision at some point in the future, as floating-point depth buffers become more common.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by swiftcoderI can't comment on that (although cameni agrees with you). However, I personally found that a floating point depth buffer was insufficient even for a planetary renderer (let alone the entire solar system), thus why I am using a variation on Sean O'Neil's method. I may revisit this decision at some point in the future, as floating-point depth buffers become more common.
Actually I haven't tried the floating point depth buffer yet, but as I think about it now there still can be the same problem to some extent, for the large scale rendering. With the logarithmic Z-buffer all 32 bits are used, whereas the exponent of the floating point number is only 8 bits. The 1/Z curve is really unfriendly in this regard.
0

Share this post


Link to post
Share on other sites
We all assume f32 (single-precision) depth-buffers, not f16... correct?

Do remember, most objects that are extremely far away are single pixels, unless you intend to [figuratively speaking] look through 1000 power telescopes. When objects are so far away they are only 1 or 2 pixels in size, you really won't visually notice any z-buffer errors.

Now, some exceptions do exist, but the realities of astronomy tend to make them non-problematic. For example, the sun and jupiter are so large that they will still be several pixels in size even at large distances. So you could imagine looking at jupiter pass in front or behind the sun from neptune, for example, and both objects might be larger than 1 pixel. However, their distances are sooooo extremely different from each other, even with problematic resolution in the z-buffer, the "depth" of the sun and jupiter surely will not be the same... will they? Can you give a real-universe example of a problem that a simple f32 depth-buffer cannot handle correctly?

Have you tested f32 depth-buffers and actually visually SEEN a problem in the graphics rendering? If so, I would be inclined to sit myself down, work out the math for several approaches, and pay very close attention to their consequences.

I do not understand the point of "designing for older systems" however. Unless I am missing something, only moderately new GPU hardware supports fragment shaders that let you perform the depth decision-making explicitly AND lets you store, retrieve and test 32-bit integer depth values. Thus I don't see that limiting ourselves to "fairly up-to-date GPUs" can be avoided at all for our purposes.

One other option. The current generation of GPUs supports f64 variables and math, and f64 variables are supported in OpenCL and CUDA. So one other approach is to perform the depth computation in a supporting OpenCL function. Unfortunately, I haven't studied how annoying or difficult it is to mix shader code with OpenCL code - I only know it can be done, and works.

I suppose another solution might be to keep two depth buffers, one being the "upper 32-bits" of distance, and the other being the "lower 32-bits of distance". Obviously, one or both of these depth-buffers needs to be held in a framebuffer object, because the built-in methodologies do not seem to support two depth-buffers. I suppose, if we didn't need a stencil buffer (we wish), we could write fragment shader code to put 32-bits of depth information in the stencil buffer, and another 32-bits of depth information in the depth-buffer. OTOH, I don't see how that's more efficient than reading and writing additional depth information into attached framebuffers ala depth-info = gl_FragData[n] and gl_FragData[n] = depth-info.
0

Share this post


Link to post
Share on other sites
the simple solution which works on allhardware + requires no math is to draw things in 2(or more) phases

eg

clear depth
set z from 100km -> ~100,000 km
draw stuff here

clear depth buffer
set z from 10 -> ~110k meters
draw stuff here

0

Share this post


Link to post
Share on other sites
Quote:
Original post by maxgpgpu
Now, some exceptions do exist, but the realities of astronomy tend to make them non-problematic. For example, the sun and jupiter are so large that they will still be several pixels in size even at large distances. So you could imagine looking at jupiter pass in front or behind the sun from neptune, for example, and both objects might be larger than 1 pixel. However, their distances are sooooo extremely different from each other, even with problematic resolution in the z-buffer, the "depth" of the sun and jupiter surely will not be the same... will they? Can you give a real-universe example of a problem that a simple f32 depth-buffer cannot handle correctly?
What you are saying would be perfectly true if the Z-buffer stored the depth value directly. The scales of things and distances when they are still visible would play nicely with the floating point depth. But instead it stores value of Z/W that has an abnormal resolution close to the near plane, but it falls down rapidly with distance.

Hmm, let's do a quick evaluation - for a scene like this: the near plane at 0.1m and the far plane at 300km (but that almost doesn't matter at all with the value of near plane). At 100km the Z/W value changes by 1e-10 per meter, at 10km the derivative is 1e-8. However, the problem here is that Z/W with rising Z approaches 1.0 (and not 0.0 where precision would be plenty), and the resolution of a 32b float around the value of 1.0 is somewhere around 1e-7, if I'm computing it right. That would make f32 depth buffer precision somewhere around 1km at that distance. Which is not what I'd expect from a floating point depth buffer at first thought [oh]

There might be something to be done about it though, as AFAIK the floating point depth values aren't clamped to 0..1, so it could be possible to set znear to a much larger value to reclaim the precision. If the clipping could be handled separately, somehow.

@zedz: yes, it looks simple, but having used it previously I must say that it is slower and/or there are problems at the boundaries, so one has to manage the terrain chunks and objects there. Can be done, but I wish there was a better and simpler solution with depth buffer.
0

Share this post


Link to post
Share on other sites
>>that it is slower

use

clear depoth
#A
glDepthRange(0,0.5);
#B
glDepthRange(0.5,1.0);

voila, no speedloss, what u are doing with Z/W will in fact result in a speed loss

>>there are problems at the boundaries
perhaps, but take your example 0.1m->300km.
now on earth u cant see anything 300km away typically due to curvature + haze, in the above picture of yours the furtherest mountain is ~10km

thus in such a scenario
A/ 0.1->20km // stuff on ground
B/ 10m->1000km // stuff in air
0

Share this post


Link to post
Share on other sites
Quote:
Original post by zedz
>>there are problems at the boundaries
perhaps, but take your example 0.1m->300km. now on earth u cant see anything 300km away typically due to curvature + haze, in the above picture of yours the furtherest mountain is ~10km
I have the Sun and Moon visible from the surface of the Earth, which makes at least 2 depth layers, plus at least 2 more for the Earth itself - complexity starts to add up fast.

The bigger issue with the depth layering is that it doesn't interact well with deferred rendering, because you can't reconstruct position from depth at different layers. Planetary effects such as oceans and atmospheric scattering are considerably cheaper to render with deferred shading, so I can't really afford to switch back to a forward renderer just to work around depth layers.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by cameni
Quote:
Original post by maxgpgpu
Now, some exceptions do exist, but the realities of astronomy tend to make them non-problematic. For example, the sun and jupiter are so large that they will still be several pixels in size even at large distances. So you could imagine looking at jupiter pass in front or behind the sun from neptune, for example, and both objects might be larger than 1 pixel. However, their distances are sooooo extremely different from each other, even with problematic resolution in the z-buffer, the "depth" of the sun and jupiter surely will not be the same... will they? Can you give a real-universe example of a problem that a simple f32 depth-buffer cannot handle correctly?
What you are saying would be perfectly true if the Z-buffer stored the depth value directly. The scales of things and distances when they are still visible would play nicely with the floating point depth. But instead it stores value of Z/W that has an abnormal resolution close to the near plane, but it falls down rapidly with distance.

Hmm, let's do a quick evaluation - for a scene like this: the near plane at 0.1m and the far plane at 300km (but that almost doesn't matter at all with the value of near plane). At 100km the Z/W value changes by 1e-10 per meter, at 10km the derivative is 1e-8. However, the problem here is that Z/W with rising Z approaches 1.0 (and not 0.0 where precision would be plenty), and the resolution of a 32b float around the value of 1.0 is somewhere around 1e-7, if I'm computing it right. That would make f32 depth buffer precision somewhere around 1km at that distance. Which is not what I'd expect from a floating point depth buffer at first thought [oh]

There might be something to be done about it though, as AFAIK the floating point depth values aren't clamped to 0..1, so it could be possible to set znear to a much larger value to reclaim the precision. If the clipping could be handled separately, somehow.

Am I correct to infer that you are willing to require GPU cards that support vertex and fragment shaders? I assume so. Then why not perform Z-depth tests on straightforward distance values in floating point. In other words, forget Z/W... just perform depth tests based upon Z == distance.

If you have a relatively new GPU card, you can store Z distances in glFragDepth. If you have older GPU cards, you can attach a simple f32 monochrome framebuffer to glFragData[1] (or [2], or [3]), and write your Z distances in there. In fact, unless I'm forgetting something, you should be able to store an f32 Z-distance value into a 32-bit integer depth-buffer, as long as you configure OpenGL to not read/write/test that buffer itself (disable depth-buffering in OpenGL, and you explicitly read/write/test the buffer yourself in fragment shader code).

To speed up the process, you can eliminate the divide-by-W (if it actually requires a divide operation... not certain off hand) by performing the Z/W in the vertex shader and passing the Z-distance in an interpolating out variable. This way the fragment shader gets exact, interpolated Z-depth values without any need to perform a [relatively-slowish] divide operation. I do this trick in my vertex shaders for a different purpose (to pass normalized light->object vectors to the fragment shader, with true distances in the .w components).

In short, I suspect the best approach is to find a way to make the GPU perform Z-depth tests (not Z/W pseudo-depth tests) with f32 values.

Wait a second. Why not convert the transformed position.xyzw in the vertex shader to position.xyz1 (w component == 1.0000)? Then if your application has OpenGL create an f32 depth-buffer, the Z/W depth-test in hardware is the same as a Z depth-test. No?
0

Share this post


Link to post
Share on other sites
Quote:
Original post by maxgpgpu
In short, I suspect the best approach is to find a way to make the GPU perform Z-depth tests (not Z/W pseudo-depth tests) with f32 values.

Wait a second. Why not convert the transformed position.xyzw in the vertex shader to position.xyz1 (w component == 1.0000)? Then if your application has OpenGL create an f32 depth-buffer, the Z/W depth-test in hardware is the same as a Z depth-test. No?
Well the problem is that the correct value of W is required because the rasterizer has to interpolate 1/W (and tex coords/W etc) to perform perspective correct texturing.

To get around that hardwired /W operation, value of Z can be premultiplied by W in the vertex shader, or, as you say, it can be written to glFragDepth in the pixel shader. Writing it in vertex shader leads to artifacts for polygons crossing the camera plane, where the 1/W changes rapidly. Using it in pixel shader with glFragDepth effectively disables fast-Z rejects, although this seems not to be a problem so far. Nevertheless, I'm using the vertex shader trick normally, and the pixel shader trick only on the objects close to the near camera plane.

However, unless there's something that can be done with the floating point depth buffer setup that would render these tricks in shaders unnecessary, I'll bet using the logarithmic depth buffer can give you a better precision due to better utilization of 32 bits.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by zedz
clear depoth
#A
glDepthRange(0,0.5);
#B
glDepthRange(0.5,1.0);

voila, no speedloss, what u are doing with Z/W will in fact result in a speed loss

>>there are problems at the boundaries
perhaps, but take your example 0.1m->300km.
now on earth u cant see anything 300km away typically due to curvature + haze, in the above picture of yours the furtherest mountain is ~10km

thus in such a scenario
A/ 0.1->20km // stuff on ground
B/ 10m->1000km // stuff in air

Of course I have been using the depth range partitioning. But I was trying to say that it is slower when I have to do all the management. On the terrain I can see mountains as far as 150km (even more so now because the haze is unrealistically thin), so I have terrain tiles covering that whole range. I had to split the range 3 times for that, and could not use just the quadtree level to determine what tiles go where because the error metric would occasionally determine that a more distant tile but with larger features requires a refine, resulting in z-buffer artifacts because of the overlapping depth ranges. Then there's splitting the in-air objects, etc etc

All in all, using the logarithmic depth buffer showed to be much easier and elegant for me and others doing planetary rendering, even though it's not without problems.
0

Share this post


Link to post
Share on other sites
Wow.. these threads on "super huge rendering ranges!" always make me think.
Sure, there is the distinct case of planet rendering, where you want to go from the surface of a planet, out into space, over to another planet.
But on the surface of a world?
How far away IS the horizon? not 150Km for sure. Now, given that I've been bored more than once while driving between states, I'll say for sure that lots of valleys and tall mountains will give you places where you can see mountains 10-20miles before you get to them.

There is a big difference between having a world that is 150Km in size, and needing to render ALL of that as visible.
0

Share this post


Link to post
Share on other sites
Of course, that depends on what you are trying to do.
On the ground the visibility of mountains can be 20-30 miles at best, but from a plane at 14,000 feet you can see mountains 200 miles distant due to thinner air.
If you want an engine capable of this all you have to handle it somehow.

But that doesn't matter. Even at 10 miles you will have the problems with depth buffer. I thought floating point depth buffer would handle that. But it looks like it's adding precision where there was already plenty, and not helping much with the problematic distant part.
0

Share this post


Link to post
Share on other sites
So it looks the solution to the floating point depth buffer precision problem is easy. Swapping the values of far and near plane and changing the depth function to "greater" inverts the z/w shape so that it iterates towards zero with rising distance, where there is a plenty of resolution in the floating point.

I've also found an earlier post by Humus where he says the same thing, and also gives more insight into the old W-buffers and various Z-buffer properties and optimizations.
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 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 DaniDesu
      #include "MyEngine.h" int main() { MyEngine myEngine; myEngine.run(); return 0; } MyEngine.h
      #pragma once #include "MyWindow.h" #include "MyShaders.h" #include "MyShapes.h" class MyEngine { private: GLFWwindow * myWindowHandle; MyWindow * myWindow; public: MyEngine(); ~MyEngine(); void run(); }; MyEngine.cpp
      #include "MyEngine.h" MyEngine::MyEngine() { MyWindow myWindow(800, 600, "My Game Engine"); this->myWindow = &myWindow; myWindow.createWindow(); this->myWindowHandle = myWindow.getWindowHandle(); // Load all OpenGL function pointers for use gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } MyEngine::~MyEngine() { this->myWindow->destroyWindow(); } void MyEngine::run() { MyShaders myShaders("VertexShader.glsl", "FragmentShader.glsl"); MyShapes myShapes; GLuint vertexArrayObjectHandle; float coordinates[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; vertexArrayObjectHandle = myShapes.drawTriangle(coordinates); while (!glfwWindowShouldClose(this->myWindowHandle)) { glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw something glUseProgram(myShaders.getShaderProgram()); glBindVertexArray(vertexArrayObjectHandle); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(this->myWindowHandle); glfwPollEvents(); } } MyShaders.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> #include "MyFileHandler.h" class MyShaders { private: const char * vertexShaderFileName; const char * fragmentShaderFileName; const char * vertexShaderCode; const char * fragmentShaderCode; GLuint vertexShaderHandle; GLuint fragmentShaderHandle; GLuint shaderProgram; void compileShaders(); public: MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName); ~MyShaders(); GLuint getShaderProgram(); const char * getVertexShaderCode(); const char * getFragmentShaderCode(); }; MyShaders.cpp
      #include "MyShaders.h" MyShaders::MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName) { this->vertexShaderFileName = vertexShaderFileName; this->fragmentShaderFileName = fragmentShaderFileName; // Load shaders from files MyFileHandler myVertexShaderFileHandler(this->vertexShaderFileName); this->vertexShaderCode = myVertexShaderFileHandler.readFile(); MyFileHandler myFragmentShaderFileHandler(this->fragmentShaderFileName); this->fragmentShaderCode = myFragmentShaderFileHandler.readFile(); // Compile shaders this->compileShaders(); } MyShaders::~MyShaders() { } void MyShaders::compileShaders() { this->vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); this->fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(this->vertexShaderHandle, 1, &(this->vertexShaderCode), NULL); glShaderSource(this->fragmentShaderHandle, 1, &(this->fragmentShaderCode), NULL); glCompileShader(this->vertexShaderHandle); glCompileShader(this->fragmentShaderHandle); this->shaderProgram = glCreateProgram(); glAttachShader(this->shaderProgram, this->vertexShaderHandle); glAttachShader(this->shaderProgram, this->fragmentShaderHandle); glLinkProgram(this->shaderProgram); return; } GLuint MyShaders::getShaderProgram() { return this->shaderProgram; } const char * MyShaders::getVertexShaderCode() { return this->vertexShaderCode; } const char * MyShaders::getFragmentShaderCode() { return this->fragmentShaderCode; } MyWindow.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyWindow { private: GLFWwindow * windowHandle; int windowWidth; int windowHeight; const char * windowTitle; public: MyWindow(int windowWidth, int windowHeight, const char * windowTitle); ~MyWindow(); GLFWwindow * getWindowHandle(); void createWindow(); void MyWindow::destroyWindow(); }; MyWindow.cpp
      #include "MyWindow.h" MyWindow::MyWindow(int windowWidth, int windowHeight, const char * windowTitle) { this->windowHandle = NULL; this->windowWidth = windowWidth; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->windowTitle = windowTitle; glfwInit(); } MyWindow::~MyWindow() { } GLFWwindow * MyWindow::getWindowHandle() { return this->windowHandle; } void MyWindow::createWindow() { // Use OpenGL 3.3 and GLSL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Limit backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Prevent resizing window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create window this->windowHandle = glfwCreateWindow(this->windowWidth, this->windowHeight, this->windowTitle, NULL, NULL); glfwMakeContextCurrent(this->windowHandle); } void MyWindow::destroyWindow() { glfwTerminate(); } MyShapes.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyShapes { public: MyShapes(); ~MyShapes(); GLuint & drawTriangle(float coordinates[]); }; MyShapes.cpp
      #include "MyShapes.h" MyShapes::MyShapes() { } MyShapes::~MyShapes() { } GLuint & MyShapes::drawTriangle(float coordinates[]) { GLuint vertexBufferObject{}; GLuint vertexArrayObject{}; // Create a VAO glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Send vertices to the GPU glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW); // Dertermine the interpretation of the array buffer glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *)0); glEnableVertexAttribArray(0); // Unbind the buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } MyFileHandler.h
      #pragma once #include <cstdio> #include <cstdlib> class MyFileHandler { private: const char * fileName; unsigned long fileSize; void setFileSize(); public: MyFileHandler(const char * fileName); ~MyFileHandler(); unsigned long getFileSize(); const char * readFile(); }; MyFileHandler.cpp
      #include "MyFileHandler.h" MyFileHandler::MyFileHandler(const char * fileName) { this->fileName = fileName; this->setFileSize(); } MyFileHandler::~MyFileHandler() { } void MyFileHandler::setFileSize() { FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fseek(fileHandle, 0L, SEEK_END); this->fileSize = ftell(fileHandle); rewind(fileHandle); fclose(fileHandle); return; } unsigned long MyFileHandler::getFileSize() { return (this->fileSize); } const char * MyFileHandler::readFile() { char * buffer = (char *)malloc((this->fileSize)+1); FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fread(buffer, this->fileSize, sizeof(char), fileHandle); fclose(fileHandle); buffer[this->fileSize] = '\0'; return buffer; } VertexShader.glsl
      #version 330 core layout (location = 0) vec3 VertexPositions; void main() { gl_Position = vec4(VertexPositions, 1.0f); } FragmentShader.glsl
      #version 330 core out vec4 FragmentColor; void main() { FragmentColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); } I am attempting to create a simple engine/graphics utility using some object-oriented paradigms. My first goal is to get some output from my engine, namely, a simple red triangle.
      For this goal, the MyShapes class will be responsible for defining shapes such as triangles, polygons etc. Currently, there is only a drawTriangle() method implemented, because I first wanted to see whether it works or not before attempting to code other shape drawing methods.
      The constructor of the MyEngine class creates a GLFW window (GLAD is also initialized here to load all OpenGL functionality), and the myEngine.run() method in Main.cpp is responsible for firing up the engine. In this run() method, the shaders get loaded from files via the help of my FileHandler class. The vertices for the triangle are processed by the myShapes.drawTriangle() method where a vertex array object, a vertex buffer object and vertrex attributes are set for this purpose.
      The while loop in the run() method should be outputting me the desired red triangle, but all I get is a grey window area. Why?
      Note: The shaders are compiling and linking without any errors.
      (Note: I am aware that this code is not using any good software engineering practices (e.g. exceptions, error handling). I am planning to implement them later, once I get the hang of OpenGL.)

       
    • 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));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
  • Popular Now