# OpenGL Bottom Row of 4x4 Matrix

## Recommended Posts

I'm writing a matrix library.

In an opengl matrix, you have:

R R R T
R R R T
R R R T
A A A B

where R is rotation and T is translation.

what is A and B?

how would I apply A and B to a Vec3? ( I know how to translate and rotate )

how would I invert A and B?

##### Share on other sites
well first take a look at this:
http://www.songho.ca/opengl/gl_transform.html
(the other pages are very useful too!!! so look around)

I'm not really sure if A is used at all, I did this a long time ago, but B is supposed to be the perspective divide element.
Or at least B and the projection matrix modify the 4th element of the position, so that in clip space if you divide by it, you get the ndc coordinates.
like when you do the transformations:
-Model (world) space (apply T here):
model_space_pos = model_mat * vertex
-View (camera) space (apply R here):
view_space_pos = view_mat * model_space_pos
-Clip space (apply projection matrix here):
clip_space_pos = projection_mat * view_space_pos
-normalized device coordinates (do the perspective divide, apply B here):
ndc_pos = clip_space_pos.xyz / clip_space_pos.w
-viewport coordinates (scale & bias to get texture coordinates, scale by window coordinates)
viewport_pos = (ndc_pos.xy * 0.5 + 0.5) * vec2( screen_width, screen_height )

and to the other questions:
you would apply the 4x4 matrix to a 4 component vector (ie vec4)
and you would invert A and B by inverting the 4x4 matrix.

##### Share on other sites
[quote name='Yours3!f' timestamp='1355648608' post='5011208']
I'm not really sure if A is used at all, I did this a long time ago, but B is supposed to be the perspective divide element.
Or at least B and the projection matrix modify the 4th element of the position, so that in clip space if you divide by it, you get the ndc coordinates.
[/quote]
The entire bottom row is used for the perspective division, not just the B-element.

For example, for an orthographic projection, the bottom row is [0, 0, 0, x] where x is some value depending on the parameters of the projection matrix. That means that the fourth component of the resulting vector after multiplication is the fourth component of the in multiplying vector, to some scale factor. For glOrtho, x=1 at all times though, which means that as long as the Z-coordinate of the input is 1.0, which is often the case, there fourth component of the resulting vector is also 1.0, and there is effectively no perspective division, hence no perspective since it is an orthographic projection.

On the other hand, for a perspective matrix, the bottom row is [0, 0, x, 0]. That means that the fourth component of the resulting vector is the third component of the multiplying vector, to some scale factor x. The third component is the depth, and hence the perspective division is now dependent on the depth; you now get a perspective effect.

Likewise, the first two elements of the bottom row can also be non-zero to get a perspective effect along the X and/or the Y-axis instead.

[quote name='caibbor' timestamp='1355629211' post='5011155']
how would I apply A and B to a Vec3? ( I know how to translate and rotate )
[/quote]
It doesn't make much sense to talk about how to apply these elements to a 3-element vector. You simply cannot multiply a 3-element vector by a 4-by-4 matrix in the first place. What you do when adding multiplying the 3-element vector by the rotation part and then adding the translation part as a separate step is really just assuming that the missing fourth component of the 3-element vector is unity. In order to handle the fourth row of the matrix correctly, you have to do the same assumption again, carry out the multiplication, and see how the bottom row affects the other three elements, as well as performing the final perspective division to ensure that the assumption that the fourth component really is unity even after the multiplication.

In the end, you really have to carry out a full 4-vector times 4x4-matrix multiplication, although you can assume that one element is unity and eliminate its multiplication with the corresponding elements of the matrix, and just add them. Edited by Brother Bob

##### Share on other sites
thank you for the insight. I'm still re-reading this a few times to let it sink in.

one problem I'm having is trying to create a frustum from a unit cube by multiplying each of the cube's vertices by the inverse of a projection matrix (as I'm told that is how it's done) so I can do basic view-frustum culling with world objects. currently, the result I'm getting is not a frustum.

##### Share on other sites
okay, I think I understand everything you've said.

doing this wihtout inverting for the first try:

I've got a vector (1,2,3) and I want to multiply it by my perspective matrix:

0.75 0 0 0
0 1 0 0
0 0 -1.0001 -0.20001
0 0 -1 0

after applying rotation and translation, I have this:

0.75,2,-3.20031

and then to apply the projection division... this is where I'm not totally sure how to apply it.. but I think I would end up with a Vec4:

0.75,2,-3.20031,-1

##### Share on other sites
I addressed that in my last paragraph; you have to perform a full 4-dimensional multiplication because you cannot multiply a 3-dimensional by a 4x4 matrix. You have to expand the multiplication using a full 4-dimensional vector.

Here's your matrix and vector and the product of the two.
[code]
>> M
M =
0.7500 0 0 0
0 1.0000 0 0
0 0 -1.0001 -0.2000
0 0 -1.0000 0
>> v
v =
1
2
3
1
>> p = M*v
p =
0.7500
2.0000
-3.2003
-3.0000
[/code]
See how the fourth element of the vector [i]p[/i] is -3.0? That's because your 3-dimensional vector is actually a 4-dimensional vector with an implicit element at the end with a value of 1.0.

The perspective division is just dividing all elements of the vector by the fourth element:
[code]
>> p./p(4)
ans =
-0.2500
-0.6667
1.0668
1.0000
[/code]
So your resulting projected 3-dimensional vector is (-0.2500, -0.6667, 1.0668). Edited by Brother Bob

##### Share on other sites
oh wow, that's easy. thank you very much! sometimes it takes baby-speak and sock puppets to explain things to me

##### Share on other sites
I'm curious... what program are you using there in the last post? has some interesting notation

##### Share on other sites
My guess would be [url=http://en.wikipedia.org/wiki/Matlab]MatLab[/url] or [url=http://en.wikipedia.org/wiki/GNU_Octave]Octave[/url].

##### Share on other sites
[quote name='BitMaster' timestamp='1355733520' post='5011594']
My guess would be [url="http://en.wikipedia.org/wiki/Matlab"]MatLab[/url] or [url="http://en.wikipedia.org/wiki/GNU_Octave"]Octave[/url].
[/quote]
It's Matlab, to be specific.

##### Share on other sites
I am using Octave for this, and I can recommend it. I attached a zip file to this post that contains 4 simple macros to help you experiment with matrices. It helped me to quickly experiment and gain understanding.
rot: Create a rotation matrix.
scale(x,y,z): Create a scaling matrix
transl(x,y,z): Create a translation matrix
Shearz: Create a shear matrix in z.

Examples:
[CODE]octave:3> scale(1,2)
ans =
1 0 0 0
0 2 0 0
0 0 1 0
0 0 0 1
octave:4> v=[1;2;3;1]
v =
1
2
3
1
octave:6> scale(1,2)*v
ans =
1
4
3
1
octave:7> rot(pi/2)
ans =
1.00000 0.00000 0.00000 0.00000
0.00000 0.00000 -1.00000 0.00000
-0.00000 1.00000 0.00000 0.00000
0.00000 0.00000 0.00000 1.00000
octave:8> rot(pi/2)*v
ans =
1
-3
2
1
octave:9> inverse(rot(pi/2))
ans =
1.00000 0.00000 -0.00000 -0.00000
0.00000 0.00000 1.00000 -0.00000
0.00000 -1.00000 0.00000 -0.00000
0.00000 0.00000 0.00000 1.00000
octave:11> T=transl(1);
octave:19> S=scale(2);
octave:20> S*T*v
ans =
4
2
3
1
octave:21> T*S*v
ans =
3
2
3
1[/CODE]

##### Share on other sites
thank you, larspensjo. I was delighted to find octave available for my linux distro. but how about projection/perspective matrices?

I presume the way to invert the perspective section of a matrix is to just negate the values, just the same as negating the translation parts. is this correct?

##### Share on other sites
[quote name='caibbor' timestamp='1355778529' post='5011820']
thank you, larspensjo. I was delighted to find octave available for my linux distro. but how about projection/perspective matrices?

I presume the way to invert the perspective section of a matrix is to just negate the values, just the same as negating the translation parts. is this correct?
[/quote]
You cannot invert the individual sections of a matrix just like that. It just happens to work for translation under very specific circumstances. Likewise, you can invert other sections under other specific conditions.

If you have a matrix consisting of the perspective division component [b]only[/b], then you can invert it by negating the bottom row just like you do with translation. But if you have other components of the projection matrix, and a usual projection matrix does have both translation and non-uniform scaling, then you cannot do that anymore.

But take a look at how OpenGL's matrices are commonly designed [url="http://www.glprogramming.com/red/"]here[/url] in appendix F. It lists their inverse also.

##### Share on other sites
[quote name='Brother Bob' timestamp='1355781685' post='5011829']
But take a look at how OpenGL's matrices are commonly designed [url="http://www.glprogramming.com/red/"]here[/url] in appendix F. It lists their inverse also.
[/quote]

I tried implementing my own fucntions to generate a matrix based on those equations, as well as an inverse:
[img]http://www.glprogramming.com/red/images/Image23.gif[/img]

Multiplying a matrix together with it's own inverse should result in an identity matrix. I'm getting mostly identity, except col 3 row 4 is always -5.9, and col 4 row 3 is always -1.2. I've tripple-checked that my matrices match the ones in the image.

I think the problem is in my matrix multiplication. I know how to multiply the 3x3 rotation section of the matrix and then add the translation, but what do I do with the perspective section?

Edit: I've been googling and even looked into a few CG programming books. nobody seems to say how to handle the bottom row of a GL 4x4 when multiplying two matrices together... Edited by caibbor

##### Share on other sites
You have two 4x4 matrices so you have to multiply them as 4x4 matrices. The bottom row is just like any other row in the matrix, there is nothing special about it at all.

##### Share on other sites
alright, then riddle me this.

(all in column-major order)

The projection matrix I created is:
0.074978 0.000000 0.000000 0.000000 0.000000 0.099970 0.000000 0.000000 0.000000 0.000000 -1.000100 -1.000000 0.000000 0.000000 -0.200010 0.000000

It's inverse I calculated is:
13.337285 0.000000 0.000000 0.000000 0.000000 10.002963 0.000000 0.000000 0.000000 0.000000 0.000000 -4.999750 0.000000 0.000000 -1.000000 20001000.000000

an multiplying those matrices together should be identy, but instead I get:
1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 -20000994.000000 1.000000

All code related to this is shown below. I've been up and down and all the methods, as far as I can tell, look correct.
[source lang="cpp"]// Mat4f class is a 4x4 matrix of floats.
// Mat4f::data is a float[16], and is column-major

// returns float& intentionally, method is private
inline float& Mat4f::M( const int col, const int row ) {
assert( col < dim && row < dim && col >= 0 && row >= 0);
return data[row+col*4];
}

void Mat4f::Multiply( const Mat4f& mat, Mat4f& out ) const {
assert ( &mat != &out );
int r,c;

for ( c=0; c<4; c++ ) {
for ( r=0; r<4; r++ ) {
out.M(c,r) =
M(r,0) * mat.M(0,c) +
M(r,1) * mat.M(1,c) +
M(r,2) * mat.M(2,c) +
M(r,3) * mat.M(3,c);
}
}
}

// calculation from: http://www.glprogramming.com/red/images/Image23.gif
void my_glFrustum( float l, float r, float b, float t, float n, float f, Mat4f& out ) {
float n2 = n * 2.0f;
out.data[0]=n2/(r-l);
out.data[1]=0.0f;
out.data[2]=0.0f;
out.data[3]=0.0f;

out.data[4]=0.0f;
out.data[5]=n2/(t-b);
out.data[6]=0.0f;
out.data[7]=0.0f;

out.data[8]=(r+l)/(r-l);
out.data[9]=(t+b)/(t-b);
out.data[10]=-(f+n)/(f-n);
out.data[11]=-1.0f;

out.data[12]=0.0f;
out.data[13]=0.0f;
out.data[14]=-(n2*f)/(f-n);
out.data[15]=0.0f;
}

// calculation from: http://www.glprogramming.com/red/images/Image23.gif
void my_glFrustum_inv( float l, float r, float b, float t, float n, float f, Mat4f& out ) {
float n2 = n * 2.0f;
out.data[0]=(r-l)/n2;
out.data[1]=0.0f;
out.data[2]=0.0f;
out.data[3]=0.0f;

out.data[4]=0.0f;
out.data[5]=(t-b)/n2;
out.data[6]=0.0f;
out.data[7]=0.0f;

out.data[8]=0.0f;
out.data[9]=0.0f;
out.data[10]=0.0f;
out.data[11]=-(f-n)/(n2*f);

out.data[12]=(r+l)/n2;
out.data[13]=(t+b)/n2;
out.data[14]=-1.0f;
out.data[15]=(f+n)/n2*f;
}

void my_gluPerspective( float fov, float x,float y,float near,float far, Mat4f& out, bool invert = false );
void my_gluPerspective( float fov, float x,float y,float near,float far, Mat4f& out, bool invert ) {
// inspired by [url="http://www.cse.unsw.edu.au/~cs3421/labs/nate/frustsrc.html"]http://www.cse.unsw....e/frustsrc.html[/url]
float aspect = x / y;
float t = 1.0f/tanf(fov * 3.141f / 360.0f);
if ( invert ) {
my_glFrustum_inv(-t * aspect, t * aspect, -t, t, near, far, out);
} else {
my_glFrustum(-t * aspect, t * aspect, -t, t, near, far, out);
}
}

inline void my_gluPerspective_inv( float fov, float x,float y,float near,float far, Mat4f& out ) {
my_gluPerspective( fov, x, y, near, far, out, true );
}

int main ( void ) {
Mat4f should_be_identity;
Mat4f projection;
Mat4f projection_inverse;

my_gluPerspective(90,800,600,0.1f,2000,projection);
my_gluPerspective_inv(90,800,600,0.1f,2000,projection_inverse);

projection.Multiply(projection_inverse, should_be_identity);
for ( int i=0; i<16; i++ )
printf("%f ", should_be_identity.data[i] );

/*
expected output:
1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 1.000000

actual output:
1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 -20000994.000000 1.000000
*/
return 0;
}
[/source] Edited by caibbor

##### Share on other sites
Your element 15 of the inverse is incorrect. The denominator is missing a parenthesis to ensure that the multiplication by [i]f[/i] doesn't end up in the numerator.

##### Share on other sites
"I always do that. I always mess up some mundane detail." - Michael Bolton, Office Space

thanks.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627744
• Total Posts
2978895
• ### Similar Content

• Hello! As an exercise for delving into modern OpenGL, I'm creating a simple .obj renderer. I want to support things like varying degrees of specularity, geometry opacity, things like that, on a per-material basis. Different materials can also have different textures. Basic .obj necessities. I've done this in old school OpenGL, but modern OpenGL has its own thing going on, and I'd like to conform as closely to the standards as possible so as to keep the program running correctly, and I'm hoping to avoid picking up bad habits this early on.
Reading around on the OpenGL Wiki, one tip in particular really stands out to me on this page:
For something like a renderer for .obj files, this sort of thing seems almost ideal, but according to the wiki, it's a bad idea. Interesting to note!
So, here's what the plan is so far as far as loading goes:
Set up a type for materials so that materials can be created and destroyed. They will contain things like diffuse color, diffuse texture, geometry opacity, and so on, for each material in the .mtl file. Since .obj files are conveniently split up by material, I can load different groups of vertices/normals/UVs and triangles into different blocks of data for different models. When it comes to the rendering, I get a bit lost. I can either:
Between drawing triangle groups, call glUseProgram to use a different shader for that particular geometry (so a unique shader just for the material that is shared by this triangle group). or
Between drawing triangle groups, call glUniform a few times to adjust different parameters within the "master shader", such as specularity, diffuse color, and geometry opacity. In both cases, I still have to call glBindTexture between drawing triangle groups in order to bind the diffuse texture used by the material, so there doesn't seem to be a way around having the CPU do *something* during the rendering process instead of letting the GPU do everything all at once.
The second option here seems less cluttered, however. There are less shaders to keep up with while one "master shader" handles it all. I don't have to duplicate any code or compile multiple shaders. Arguably, I could always have the shader program for each material be embedded in the material itself, and be auto-generated upon loading the material from the .mtl file. But this still leads to constantly calling glUseProgram, much more than is probably necessary in order to properly render the .obj. There seem to be a number of differing opinions on if it's okay to use hundreds of shaders or if it's best to just use tens of shaders.
So, ultimately, what is the "right" way to do this? Does using a "master shader" (or a few variants of one) bog down the system compared to using hundreds of shader programs each dedicated to their own corresponding materials? Keeping in mind that the "master shaders" would have to track these additional uniforms and potentially have numerous branches of ifs, it may be possible that the ifs will lead to additional and unnecessary processing. But would that more expensive than constantly calling glUseProgram to switch shaders, or storing the shaders to begin with?
With all these angles to consider, it's difficult to come to a conclusion. Both possible methods work, and both seem rather convenient for their own reasons, but which is the most performant? Please help this beginner/dummy understand. Thank you!

• I want to make professional java 3d game with server program and database,packet handling for multiplayer and client-server communicating,maps rendering,models,and stuffs Which aspect of java can I learn and where can I learn java Lwjgl OpenGL rendering Like minecraft and world of tanks

• A friend of mine and I are making a 2D game engine as a learning experience and to hopefully build upon the experience in the long run.

-What I'm using:
C++;. Since im learning this language while in college and its one of the popular language to make games with why not.     Visual Studios; Im using a windows so yea.     SDL or GLFW; was thinking about SDL since i do some research on it where it is catching my interest but i hear SDL is a huge package compared to GLFW, so i may do GLFW to start with as learning since i may get overwhelmed with SDL.
-Questions
Knowing what we want in the engine what should our main focus be in terms of learning. File managements, with headers, functions ect. How can i properly manage files with out confusing myself and my friend when sharing code. Alternative to Visual studios: My friend has a mac and cant properly use Vis studios, is there another alternative to it?

• Both functions are available since 3.0, and I'm currently using glMapBuffer(), which works fine.
But, I was wondering if anyone has experienced advantage in using glMapBufferRange(), which allows to specify the range of the mapped buffer. Could this be only a safety measure or does it improve performance?
Note: I'm not asking about glBufferSubData()/glBufferData. Those two are irrelevant in this case.
• By xhcao
Before using void glBindImageTexture(    GLuint unit, GLuint texture, GLint level, GLboolean layered, GLint layer, GLenum access, GLenum format), does need to make sure that texture is completeness.

• 10
• 10
• 21
• 14
• 14