Sign in to follow this  
twig_monster

OpenGL glOrtho problem

Recommended Posts

Hi folks I'm trying to convert my simple 2D tile engine (originally in C#/MDX) over to a 3D solution, but I'm pretty much a newbie. Having decided on OpenGL I set about getting a checkerboard to display in an orthogonal projection (since I don't want perspective correction). That was fun, since all the tutorials for ortho are for 2D drawing and I wanted a 45 degree view where y and z both run vertically (like an isometric projection but with no rotation around the y axis) and the squares are all rendered on the 'floor' (ie every y value is 0). Got that working eventually (had trouble getting the 'tiles' to appear exactly half their height in screen coordinates as you would expect from the viewing angle) and did a quick C++ conversion to test speed differences since the framerate seemed rather low (got a 50% improvement using C++ btw). I then decided to add some geometry with height, and that's where I'm stuck. My problem is that the top/bottom clipping planes are not behaving as I expected. Assuming values of -500/500 respectvely (the range is a bit wider than that really), I cannot see all of an object which is 500 units tall. Furthermore, the clipping plane is wonky! I rendered a plane where one side was closer to the viewer than it's opposite. The near side gets clipped earlier (ie the lines forming the top/bottom of the plane do not run parallel, and I've double-checked that they should be) - if I decrease the y values of the 'top' vertices so that it is much shorter, clipping works correctly. How am I to get tall objects rendering correctly? This engine will be used in an indie RPG and I need to have tall buildings and such in view. At the moment, no matter what I try, the tallest fully-visible object cannot even by half a screen tall. Sorry for my long first post, so I'll say thanks in advance and leave you with the render function from my C++ source (the buffers are swapped elsewhere btw): int DrawGLScene(GLvoid) { glViewport(0,0,_width,_height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Although Z values from -768 to +768 are visible, we need to shrink these due to the 45 degree camera orientation // I don't quite understand this, and the value of 543.32 was found by trial and error: // C++ fix: the top/bottom need to equal the znear and zfar or it causes the view to change // (in C# you can use any values where one is the negated value of the other) glOrtho(-512.0f, 512.0f, -543.32f, 543.32f, -543.32f, 543.32f); // Rotate camera eye 45 degrees along the x axis towards a birds-eye view glRotatef(45.0f, 1.0f, 0.0f, 0.0f); glPushMatrix(); // Render the checkerboard int xstep = 64; int zstep = 64; glBegin(GL_QUADS); for (int z = -12; z < 12; z++) { for (int x = -8; x < 8; x++) { float f = abs((x + z) % 2) * 1.0f; glColor3f(f, f, f); int fx = x * xstep; int fz = z * zstep; glVertex3i(fx, 0, fz); glVertex3i(fx + xstep, 0, fz); glVertex3i(fx + xstep, 0, fz + zstep); glVertex3i(fx, 0, fz + zstep); } } // Render a red plane which has some height glColor3f(0.5f,0.0f,0.0f); glVertex3f(-35, 0.0, 303); glVertex3f(-35, 500, 303); glVertex3f(60, 500, 398); glVertex3f(60, 0, 398); // Despite the high y values fitting within the view volume, they get clipped....wonkily // TODO : Seek help! glEnd(); glPopMatrix(); return TRUE; }

Share this post


Link to post
Share on other sites
Currently I'm not sure what is causing your problem, but ...

(1) zNear/zFar and top/bottom are not interrelated.
(2) For a "normal" camera zNear should be close to 0, or else you can see also stuff behind the camera and waste z resolution. (But perhaps you _want_ to see behind the cam, then it would be okay.)
(3) If you alter glViewport (your code snippet hints at this since you invoke glViewport every time when drawing the scene) you also have to alter glScissor.
(4) If all is set-up well, then the left/right/top/bottom clipping planes restrict the viewing volume just at the borders of your viewport (e.g. window content area). So you shall not see clipping of geometry (besides near/far) inside the viewport. If you do, then glScissor may be the problem.
(5) The ratio (right-left)/(top-bottom) should normally match the rows/lines ratio of pixels of the window (assuming square pixels), or else the scene will be displayed distorted.

Share this post


Link to post
Share on other sites
Quote:
Original post by haegarr
Currently I'm not sure what is causing your problem, but ...

(1) zNear/zFar and top/bottom are not interrelated.
(2) For a "normal" camera zNear should be close to 0, or else you can see also stuff behind the camera and waste z resolution. (But perhaps you _want_ to see behind the cam, then it would be okay.)
(3) If you alter glViewport (your code snippet hints at this since you invoke glViewport every time when drawing the scene) you also have to alter glScissor.
(4) If all is set-up well, then the left/right/top/bottom clipping planes restrict the viewing volume just at the borders of your viewport (e.g. window content area). So you shall not see clipping of geometry (besides near/far) inside the viewport. If you do, then glScissor may be the problem.
(5) The ratio (right-left)/(top-bottom) should normally match the rows/lines ratio of pixels of the window (assuming square pixels), or else the scene will be displayed distorted.


1) Thanks, that's what I thought. But my top/bottom values affect the viewable z range in my C++ implementation - I use Colin Fahey's wrapper for C# and in my C# code the values don't have this effect (as long as each one is the negated value of the other). My guess is that they need to be the same because the 45 degree view results in the y/z axes having exactly the same scale.
2) Ah, I'm using this to control the vertical viewing distance. I admit I don't really understand ortho projection when not used in the traditional '2D' context, but unfortunately all tutorials I've found use it solely for this purpose. I just used these values since they gave me the correct viewing area with my angle of rotation along the x-axis!!
3) Just changes if the screen is resized.
4) The scissor is fine - it's not a problem with the screen being clipped prematurely, as the problem occurs in the middle of the view (you can copy my render function if you want to see what I meant in my post). I guess since glOrtho is primarily for 2D operations such as GUI/HUD elements that a view not looking directly forward is hard to describe properly?
5) Makes sense. But I do want to double the number of units along the z axis if I'm using a 45 degree top/down view don't I? I was using -768 and 768 (the view is supposed to be 1024x768 as both values are divisble by all powers of 2 up to 256), but had to fiddle with these so the correct number of squares (well, rectangles due to the camera orientation) were displayed vertically.

Basically I want to draw my geometry with the correct 3D placement:
The ground plane runs along x/z with a y elevation of 0.
Objects such as buildings will have a positive y value for any vertices not anchoring them to the ground. But very tall objects need to be renderable, as I plan on having some towers and trees which might take up more than one whole screen vertically.

The camera is supposed to look down/forward at a 45 degree angle so that there is a 3D view of the 'map' without perspective correction taking place. So the y/z values should appear at half scale (ie rotating a ground square 45 degrees around it's y axis would appear to be a diamond tile - the typical dimetric '2.5D' view used in many so-called 'isometric' RPG's).
I don't want to do this in 2D, as I want to be able to freely rotate objects and avoid the 'traditional' look. Plus, character animation using sprites is a memory hog.

Share this post


Link to post
Share on other sites
Orthogonal projection means that the projectors (i.e. those line running through each pixel if thinking of a ray tracer) hit the projection plane perpendicularly. It is a special kind of parallel projection, i.e. all projectors are also parallel. As for any parallel projection you get no depth foreshortening and hence see no perspective effect. Besides this, there is no real difference between perspective and orthogonal projection. However, notice please that projection takes place in VIEW space. glOrtho always projects along the VIEW's z axis. If you want to do other orthogonal projections, you have to make the projection matrix yourself. But, as your approach already shows, a way to reach the goal is to adapt the VIEW matrix properly and using the standard projection stuff.

You've said that the clipping occurs just in the middle of the screen. Looking at your scene drawing code and assuming that it is completely posted, I miss various things. The usual way of setting up OpenGL's matrices is like this:

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(...);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// set-up of VIEW portion (its the inverse of camera's local space transformation)
// set-up MODEL portion

where the projection stuff is usually done only once, while the MODELVIEW is set-up for each scene rendering round-trip. In your case, the VIEW portion IMHO should consist of 3 things: 1st pitch the camera, 2nd lift it up to the viewing height, and 3rd shift it around over the playfield. Here the 2nd and 3rd step define the camera's postion, of course. Especially, if the 2nd step is not done (and you don't do it), a sufficiently big ground plane at level 0 will be cutted horizontally on half of the screen! Maybe that is your problem.

Share this post


Link to post
Share on other sites
Thanks, I've resolved the problem now. You're right, it was my mis-interpretation of how orthogonal projection works. I'm now drawing all objects along the x/y axes instead and using the z axis for height (still find it hard remembering that y moves *up* the screen in 3D space, plus now I'll have to pre-rotate my models so that the +y axis becomes the +z axis). The 45 degree geometry rotation takes care of halving the scale of y and converting z values into a screen 'height' equal to half of z.
Still have to specify that weird floating-point value for the vertical viewport size(though I'm now using bottom/left values of 0, so it's doubled) in order to get exactly 1536 units visible along the y axis after rotation (multiply the required value by 0.7074479167). I call glTranslatef (512, 768) to center the view correctly.

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
      628282
    • Total Posts
      2981820
  • 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