# OpenGL Unexpected results when calculating with Projection Matrix

## Recommended Posts

Hi, I'm doing my first steps in OpenGL and I'm trying to understand the way the ModelView and Projection matrices work. I, more or less, know what their use is but I'm getting unexpected results when doing some test-calculations. As I see it: The Projection Matrix is a simple matrix that defines the Viewing-frustum of your "camera" and holds the information about how OpenGL should transform the 3D-vertices in your scene to equivalent 2D-coordinates on your screen. So far, so good, but now I wanted to test this myself. If I multiply a random vertex with the projection matrix I should get the projected value (as I would see it on screen) right? Here is my code:
Vector3* v = new Vector3(16.0f, 7.0f,10.0f);

float buffer[16];
glGetFloat(GL_PROJECTION_MATRIX, buffer);

Vector3* proj = new Vector3(v.x*buffer[0] + v.y*buffer[1] + v.z*buffer[2],
v.x*buffer[3] + v.y*buffer[4] + v.z*buffer[5],
v.x*buffer[6] + v.y*buffer[7] + v.z*buffer[8]);

The camera is in position (0, 0, 6) and the result I get here is: (20.784609, 17.320507, 0.0). The Z-coordinate is 0, that seems right, but in what coordinate-system are the X and Y values? Am I making a mistake? Thank you.

##### Share on other sites
(1) The matrices in OpenGL are given in "column major order", what means that the indices are not as you assume (you assume "row major order"). So the first correction would be:
Vector3* proj = new Vector3(v.x*buffer[0] + v.y*buffer[4] + v.z*buffer[8],                            v.x*buffer[1] + v.y*buffer[5] + v.z*buffer[9],                            v.x*buffer[2] + v.y*buffer[6] + v.z*buffer[10]);

(Notice that this "major order" thingy comes from the fact that the 2D matrix is accessed by a 1D indexing.)

(2) You use a vertex, and a vertex is a "position vector". But you use it as a "direction vector". Look at the homogeneous co-ordinate w for the difference: w is 1 for a (normalized) position vector, but 0 for a direction vector! So the second correction would be:
Vector3* proj = new Vector3(v.x*buffer[0] + v.y*buffer[4] + v.z*buffer[8] + buffer[12],                            v.x*buffer[1] + v.y*buffer[5] + v.z*buffer[9] + buffer[13],                            v.x*buffer[2] + v.y*buffer[6] + v.z*buffer[10] + buffer[14]);

(3) The projection matrix is special in that it does _not_ provide an affine transformation. So you have to take also the lowest row into account, since it stores the perspective stuff if you do a perspective projection (as far as I remember; maybe I'm wrong here).
Vector3* proj = new Vector3(v.x*buffer[0] + v.y*buffer[4] + v.z*buffer[8] + buffer[12],                            v.x*buffer[1] + v.y*buffer[5] + v.z*buffer[9] + buffer[13],                            v.x*buffer[2] + v.y*buffer[6] + v.z*buffer[10] + buffer[14]);float proj_w = v.x*buffer[3] + v.y*buffer[7] + v.z*buffer[11] + v.z*buffer[15];proj /= proj_w; // normalize

[Edited by - haegarr on November 23, 2005 4:39:49 AM]

##### Share on other sites
Vertices go through multiple transformations to get from camera space to the screen. The following code mirrors what OpenGL does. First, the projection matrix transforms a camera-space vertex into homogeneous clip-space coordinates (hence the 4-dimensional vector 'clip'). Then, the clip-space position is divided by its w-coordinate to obtain 3D normalized device coordinates. In NDC, the view frustum has been mapped to the unit cube extending from -1 to 1 in each direction. Finally, the viewport transformation is applied to map positions from NDC to the viewport. The z-coordinate in viewport space is the depth that's written to the depth buffer.

Vector3 v(16.0F, 7.0F, 10.0F);// Calculate clip-space coordinatesfloat buffer[16];glGetFloat(GL_PROJECTION_MATRIX, buffer);Vector4 clip(buffer[0]*v.x + buffer[4]*v.y + buffer[8]*v.z + buffer[12],             buffer[1]*v.x + buffer[5]*v.y + buffer[9]*v.z + buffer[13],             buffer[2]*v.x + buffer[6]*v.y + buffer[10]*v.z + buffer[14],             buffer[3]*v.x + buffer[7]*v.y + buffer[11]*v.z + buffer[15]);// Calculate normalized device coordinatesfloat invW = 1.0F / clip.w;Vector3 ndc(clip.x * invW, clip.y * invW, clip.z * invW);// Calculate (x,y) viewport coordinatesglGetFloat(GL_VIEWPORT, buffer);float w = buffer[2] * 0.5F;float h = buffer[3] * 0.5F;float x = (ndc.x + 1.0F) * w + buffer[0];float y = (ndc.y + 1.0F) * h + buffer[1];// Calculate z depthglGetFloat(GL_DEPTH_RANGE, buffer);float d = (buffer[1] - buffer[0]) * 0.5F;float z = (ndc.z + 1.0F) * d + buffer[0];

##### Share on other sites
Thank you both. Things are clearing up now :-)

## 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

• ### Forum Statistics

• Total Topics
628327
• Total Posts
2982089
• ### 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.

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

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