Sign in to follow this  
zorro68

OpenGL Problems with rotations

Recommended Posts

Hi, i'm new here. I was looking for a good opengl forum, and i think this would be. I want to rotate the axes first 90 degree around the x axe, then 90 degree around y axe and then 90 degree around z axe. This is easy, and works fine in my program. But if I want to rotate 90 degree around the x axe, then 90 degree around z axe and then 90 degree around y axe, I have a problem. I use this: glRotatef(90,1,0,0); glRotatef(90,0,1,0); glRotatef(90,0,0,1); So the problem is the order in the matrix multiplication (always multiply the y axe matrix before z axe matrix). But I don't know how to do this only using glRotatef. (I have read about quaternions, euler angle, ... , but I want to do, if it is possible, only with glRotatef). Thanks

Share this post


Link to post
Share on other sites
Actually, if I'm not much mistaken, you've posted the code for rotations about the z, y and x-axes in that order, rather than the other way around. Since the matrices are post-multiplied, the last operation is essentially performed first on the vertices. That is, in your example, if, before your glRotate calls are performed, the transformation matrix is A, and we call your rotations B, C and D respectively, then the result after making the glRotate calls should be:

ABCD (A multiplied by B multiplied by C multiplied by D)

In matrix mathematics, this results in the operation D "taking effect" first when the matrix is applied to a vertex, followed by C, B and A, in that order.

(A note: this is the result of the matrix mathematics, as I recall, rather than OpenGL doing anything funny with the actual calls.)

PS: The English singular of "axes" is "axis", by the way - one axis, two axes. ^_^

Share this post


Link to post
Share on other sites
I know.

So you say that I have to change the order of glRotatef. I have tried and this is not the main problem.

I have a picture to show you the problem, but i don't know how to attach a picture here.

Thanks and thanks for the english correction.

[Edited by - zorro68 on May 7, 2008 8:18:48 AM]

Share this post


Link to post
Share on other sites
glRotatef(90,1,0,0);
glRotatef(90,0,1,0);
glRotatef(90,0,0,1);

This is doing what you wanted to do. It rotates X then Y then Z if you want X Z Y

This will do X,Z,Y
glRotatef(90,1,0,0);
glRotatef(90,0,0,1);
glRotatef(90,0,1,0);

Share this post


Link to post
Share on other sites
Quote:
Original post by Thaumaturge
That is, in your example, if, before your glRotate calls are performed, the transformation matrix is A, and we call your rotations B, C and D respectively, then the result after making the glRotate calls should be:

ABCD (A multiplied by B multiplied by C multiplied by D)

No, that's not the order OpenGL uses. If A is the original matrix and you call a matrix function with a matrix B, the resulting matrix is BA, not AB. Your sequence will be DCBA.

Zorro68: I'm not quite sure what your problem is, but are trying to say that you wonder why the resulting rotation is different when you change the order? Or are you experiencing gimbal lock, which is what happens when you rotate so, that rotating around one axis no longer is possible?

Share this post


Link to post
Share on other sites
Quote:
Original post by SnotBob
Quote:
Original post by Thaumaturge
That is, in your example, if, before your glRotate calls are performed, the transformation matrix is A, and we call your rotations B, C and D respectively, then the result after making the glRotate calls should be:

ABCD (A multiplied by B multiplied by C multiplied by D)

No, that's not the order OpenGL uses. If A is the original matrix and you call a matrix function with a matrix B, the resulting matrix is BA, not AB. Your sequence will be DCBA.

Err, well, Thaumaturge isn't wrong but right! OpenGL uses column vectors, and OpenGL does post-multiplication (i.e. on the right side) when glTranslate, glRotate, glScale, or glMultMatrix is invoked. Hence, in an abstract form, the sequence
glAnyTransformation(A);
glAnyTransformation(B);
glAnyTransformation(C);
glVertex(v);
means mathematically
v' := A * B * C * v
Although OpenGL computes that (due to the order matrices are supplied) as
v' := ( ( A * B ) * C ) * v
it is true that the parantheses have no mathematical effect. E.g. the form
v' := A * ( B * ( C * v ) )
will give the identical result! I've chosen this form because it shows best what's "logically" happens: It is C that is applied to v, and B that is applied to the already transformed vertex, and A that is applied to those already twice transformed vertex.

Share this post


Link to post
Share on other sites
Thank you, Haegarr. ^_^

Zorro, in order to display an image, first upload it to an image host and then include the relevant code in html <img> tags.

If you use ImageShack, then I believe that the code given for an image under "sites" should work (without any additional tags).

I don't think that this site allows for uploads from free accounts, I'm afraid.

Quote:
Originally posted by MARS_999
glRotatef(90,1,0,0);
glRotatef(90,0,1,0);
glRotatef(90,0,0,1);

This is doing what you wanted to do. It rotates X then Y then Z if you want X Z Y

This will do X,Z,Y
glRotatef(90,1,0,0);
glRotatef(90,0,0,1);
glRotatef(90,0,1,0);


I'm pretty sure that the order is the opposite way around - respectively, I believe that those sets of calls would produce rotations about z, x and then y, and y, z, and then x.

Share this post


Link to post
Share on other sites
Thanks to all for a quickly answer.

But I (due to my bad english) don't explain you what is my problem. First at all, i say that i know the order of matrix, and what happend if you change this order. I know the gimbal lock problem, so I'm going to try to explain better:

I have 3 slices, one to rotate in the x axis, other to rotate in the y axis, and other for z axis.
If I move the slices in this order, first x , y and z (the program execute glRotatef(90,1,0,0), glRotatef(90,0,1,0), glRotatef(90,0,0,1);) and all works right.
But if I move the slices in this order, first x, z and y (the program execute the same, so the rotation is bad, I have to change the code).

So if I move the slices in different order, I have to change the code, and I need a code with glRotatef that always work.

I don't know if this is possible or not (with glRotatef) or if I need to implement quaternions or Euler angles or ....

Thanks and I hope you understand my problem.


Free Image Hosting at www.ImageShack.us

Share this post


Link to post
Share on other sites
What I don't understand is that, if your rotating an object about its own local coordinates, which is what I assume your trying to do, those 3 rotations in any order is going to produce a similar affect? The main difference is going to be which faces are facing forward.

For instance if you have a square rotated about x, then y, then z at 90 degrees a piece, your always going to get the same square back, but by switching the order of rotations a different face will be front facing.

From your picture it looks to me that the rotations are working as they should, if you want it to produce a different result then you need to change the rotations.

Share this post


Link to post
Share on other sites
The picture lets me assume you want to rotate around local axes, while your code lets me assume you want to rotate around global axes. Perhaps your problem is to distinuish these 2 cases?

For this you must be aware that a transformation happens ever in its global co-ordinate frame. From your picture it seems me that you want to rotate around local axes. If so, you cannot simply use global axes! Instead, you have to figure out how the desired local axis is currently oriented in global space, and use that as argument to the glRotate function.

E.g. the y axis of your co-ordinate cross is
y = [ 0 1 0 ]T
in global space before any transformation. After a rotation by 90° around (global) x axis
y' := Rgx(90°) * y = [ 0 0 1 ]T
the result will point along the global z axis! See the difference: The global y axis is, of course, still [ 0 1 0 ]T w.r.t. the global space, but the local y axis is now [ 0 0 1 ]T w.r.t. the global space.

Now, rotating by glRotatef(90,0,1,0) around the (global) y axis will result in
yg" := Rgy(90°) * y' = [ 1 0 0 ]T
in a vector pointing along global x axis, while rotating around the "local" y axis using glRotate(90,0,0,1) results in
yl" := Rly(90°) * y' = [ 0 0 1 ]T
(doesn't change anything, because y axis rotated around y axis ;) ). Perhaps I've used a wrong sign anywhere, but the principle should became clear.


Using Euler angles means nothing else to use a specific order of a sequence of 3 glRotate invocations, each one with a defined axis. Several Euler triples exist; in principle your XYZ rotation is one of them. Using a quaternion means nothing more than to use a single glRotate, but with a "arbitrary" axis, i.e. where [ x y z ]T will typically differ all from 0. Although you can compute the belonging matrices by yourself, IMHO it doesn't effectively change anything significant here. So go with glRotate, but clarify which axes you want to rotate around.

[Edited by - haegarr on May 8, 2008 9:26:03 AM]

Share this post


Link to post
Share on other sites
haegarr, thanks for your explanation. I understand all you say, but there's something that I don't understand. I explain you:

The program always run this sentences continously:

glRotatef(rotx,1,0,0);
glRotatef(roty,0,1,0);
glRotatef(rotz,0,0,1);

so, as you say, when rotx=90, roty=0 and rotz=0, I have the local y axis pointing out of the screen [0 0 1], along the positive global z axis. Is it ok? (I think so)

Then I change the value of roty=90 (rotx=90,roty=90,rotz=0), so when I compute the three sentences glRotatef, I have to obtain the local y axis looking at the direction of positive x axis [1 0 0]. Is it ok? (I think so)

But I don't get this. If you show my picture you can see that I get a rotation around the global z axis (out the screen) so the local y axis doesn't move, and get the local y axis [0 0 1].

What's happend, or what is what i don't understand?

Pds: I understand that glRotatef always rotate around global axis, as you say.

Thanks for your time.

Share this post


Link to post
Share on other sites
I think you still don't consider all aspects. Let's see ...
Still using column vectors and right handed co-ordinate systems:

Quote:
Original post by zorro68
so, as you say, when rotx=90, roty=0 and rotz=0, I have the local y axis pointing out of the screen [0 0 1], along the positive global z axis. Is it ok? (I think so)

Yes, its okay, because the mathematical equivalent is
v' := Rx(90°) * Ry(0°) * Rz(0°) * [ 0 1 0 ]T
== Rx(90°) * I * I * [ 0 1 0 ]T
== Rx(90°) * [ 0 1 0 ]T
== [ 0 0 1 ]T

Quote:
Original post by zorro68
Then I change the value of roty=90 (rotx=90,roty=90,rotz=0), so when I compute the three sentences glRotatef, I have to obtain the local y axis looking at the direction of positive x axis [1 0 0]. Is it ok? (I think so)

Nope. Because the mathematical equivalent is
v' := Rx(90°) * Ry(90°) * Rz(0°) * [ 0 1 0 ]T
== Rx(90°) * Ry(90°) * I * [ 0 1 0 ]T
== Rx(90°) * Ry(90°) * [ 0 1 0 ]T
== Rx(90°) * [ 0 1 0 ]T
== [ 0 0 1 ]T

Keep in mind that (as already written in one of the previous answers) mathematically
A * B * C == ( A * B ) * C == A * ( B * C )
is all the same.

I suggest you: Don't think in code with stuff like this! Think in mathematical terms, and then translate that to code.

[Edited by - haegarr on May 8, 2008 11:14:14 AM]

Share this post


Link to post
Share on other sites
I see what you say (I see better with maths).

So if I think in math terms, the solution of my problem is to multiply the three matrix before apply to the scene. (ok?)

But how can I do this with glRotatef function only?

PD: I have to do this in my paintGL() functions that is always running.

Thanks very much.

Share this post


Link to post
Share on other sites
Quote:
Original post by zorro68
So if I think in math terms, the solution of my problem is to multiply the three matrix before apply to the scene. (ok?)

Err, not primarily; I'm not sure whether I understood you correctly here, so my following explanation may be superfluous, but what should I do ;) Make yourself clear what happens step-by-step. Assume you use the pseudecode sequence
glLoadIdentity();
glRotate(A);
glRotate(B);
glBegin(...);
glVertex3(v);

Now, glLoadIdentity() prepares OpenGL's matrix stack:
M := I

The 1st rotation glRotate(A) then causes
M := I * A
being on the stack.

The 2nd rotation glRotate(B) then causes
M := I * A * B
being on the stack.

Applying that to the vertex glVertex3(v) then means
v' := M * v = I * A * B * v

Now, the sequence of invocations has computed this actually as
( ( I * A ) * B ) * v
but, as already said several times, it is mathematically absolutely the same as
I * ( A * ( B * v ) )
or any other (syntactically correct) arrangement of parantheses!

In other words, using glRotate has definitely build up the matrix as a whole internally before the first vertex is transformed by it, but it plays no role for the result (only for the performance). You could use quaternions, multiply them together, convert the result to a matrix, and use glMultMatrix; whatever ... it'll change nothing.

Unfortunately, I still have no real clue what you are desired to reach. So I tell you again what's going wrong, but am not able to hint in the correct direction. I'm pretty sure that the results you want to reach are possible using glRotate (it must be since glRotate does nothing more than converting into a rotation matrix and multiply that). Could you perhaps illustrate in detail what should happen? And why are you forced to use that specific sequence of rotations?

Share this post


Link to post
Share on other sites
I have no clue what he the OP is trying to do, but I have tried the rotations you asked for and found the cube will end up back at the starting point after you move the axes in the order you wanted.

To check this yourself grab a dice, mark all 6 sides as front, back, left, right, bottom, top. Now keep the front facing you to start with, rotate X,Z,Y mind you you need to rotate in a CW direction when you do this. You will be back at the front facing you after all three have moved. Is this what you want?

Share this post


Link to post
Share on other sites
If you are trying to implement a rotation user interface, do not use Euler angle.

Using Euler angle is a bad idea.

By the way, this is going to help...
http://www.gamedev.net/community/forums/topic.asp?topic_id=463800

Share this post


Link to post
Share on other sites
u can use eular angles no problems, what u shouldnt do though is perform several glRotatef(..) commands in a row as this will often end in gimbal lock
see the matrix faq

read this
http://www.j3d.org/matrix_faq/matrfaq_latest.html

Q33. How do I combine rotation matrices?
Q34. What is Gimbal Lock?

Share this post


Link to post
Share on other sites
Quote:
Original post by zedz
u can use eular angles no problems, what u shouldnt do though is perform several glRotatef(..) commands in a row as this will often end in gimbal lock

How are you using Euler angles w/o performing several glRotates in row (or, as an equivalent, compose the matrix by yourself)? Euler angles means ever a composition of consecutive rotations.

Share this post


Link to post
Share on other sites
Quote:
Original post by haegarr
In other words, using glRotate has definitely build up the matrix as a whole internally before the first vertex is transformed by it, but it plays no role for the result (only for the performance). You could use quaternions, multiply them together, convert the result to a matrix, and use glMultMatrix; whatever ... it'll change nothing.


Yes you are right.

Quote:
Original post by MARS_999
To check this yourself grab a dice, mark all 6 sides as front, back, left, right, bottom, top. Now keep the front facing you to start with, rotate X,Z,Y mind you you need to rotate in a CW direction when you do this. You will be back at the front facing you after all three have moved. Is this what you want?


I'm going to explain you what I need?

Quote:
Original post by ma_hty
If you are trying to implement a rotation user interface, do not use Euler angle.
Using Euler angle is a bad idea.


I have read this. By the way, thanks for the gimbal lock discussion.

Quote:
Original post by zedz
read this
http://www.j3d.org/matrix_faq/matrfaq_latest.html


It's a very good summarized in maths.


I thought the rotation problem was a closed theme (in maths and in opengl), but I can see that there's a lots of doubts.

I'm going to explain what I am doing and what is my problem. I'm programming a molecular viewer with opengl. I have seen other molecular viewer and when you click with the mouse into the scene and move the mouse you rotate all the scene (in my case, the molecule). But I have seen that all of them has a problem, if you rotate the scene with the mouse you can see the rotation of the scene and it seems that is all ok. But you are rotating the scene sometimes around global axis and sometime around local axes. This is the same effect that I am having when I use, three times, glRotatef function. Due to the matrix order multiplication, it seems that you are rotating the scene sometime around its local axes and sometime around its global axes. (Show what I'm trying to say in the picture)

Free Image Hosting at www.ImageShack.us

What I am trying to program is that when I click and move the mouse (left click + left-right move around x axis, left click + top-down move around y axis, right click + left-right move around z axes, and right click + top-down zoom the scene) or move the slices the scene seems to rotate ALWAYS around the global axes, or seems to rotate ALWAYS around the local axes. But not a mix of them.

I hope you understand me. If not, show me and I'll try again.

Pd: My main problem is that I cannot explain in English like I would like.

Thanks to all of you.

Share this post


Link to post
Share on other sites
ATM I think your desire is not 100% possible to be realized (but perhaps someone else from the cummunity will contradict). However, I furthur think you've several more-or-less good options to work around:

(a) Make the user clear that s/he is varying an Euler angle like set-up with the 3 sliders. This solution doesn't touch the math, but is IMHO user unfriendly, since the user shouldn't be burdened with such stuff.

(b) Rotate the molecule by the currently dragged slider always as an incremental rotation around the local axis, but decompose the resulting orientation back into its 3 angles, and adapt the sliders accordingly. This allows you to still show the absolute angles (but only w.r.t. the equivalent rotations of a defined order). DCC packages often offer this way.

(c) Don't use absolute angles but relative ones. I.e. remake the GUI so that pulling a slider's knob changes its belonging angle incrementally around the local axis, but releasing the knob lets it snap back to the neutral position. The molecule, on the other hand, is left as is. So at most one slider knob is outside of 0, and that only temporarily. This simulates a kind of turn table but with sliders, so restricting the kinds of rotation axes (see below).

(d) Drop the usage of slides totally, and go with the tool approach (e.g. turn table like). I.e. manipulate the model directly inside the view, not indirectly and beneath it. Besides the tool idea, this is similar to (c), but also allows for more or less arbitrary rotation axes.

(e) One of (b) or (c) above but using global axes.

Other options may exist, too. I personally would prefer the tool approach. But that is the opinion of a programmer of a 3D DCC editor, not of a chemist :)

Share this post


Link to post
Share on other sites
Quote:
Original post by zorro68
...
But I have seen that all of them has a problem, if you rotate the scene with the mouse you can see the rotation of the scene and it seems that is all ok. But you are rotating the scene sometimes around global axis and sometime around local axes.
...


This is a typical defect introduced by mapping Euler angle to the user interface directly. As long as you are using Euler angle honestly, there is no way you can solve this problem.

Why don't you give up Euler angle and use Axis-angle instead? If you are using Axis-angle correctly, there will not be such a problem. Well well, you are probably going to make a lengthy statements to defend your idea (that's what had happened repeatedly whenever there is discussion about Euler angle user interface).

Before you do it, please read the previous discussion about Euler angle user interface first.

I have been participated in those discussions too many times. Therefore, even if you are decided to defend your idea anyway, I am not going to join your discussion. Instead, I give you the source code of what a correctly designed Axis-angle user interface should look like (i.e. almost the ArcBall).

/////////////////////////
// glutTest13.cpp
//
// Created by Gary Ho, ma_hty@hotmail.com, 2007
//

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include <GL/glut.h>

#define PI 3.14159265358979323846f

float v0[3], v1[3];
float mo[16] = { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 };

float clamp( float x, float a, float b );
float dot( const float *a, const float *b );
float norm( const float *a );
void vassign( float *a, float x, float y, float z );
void vassign( float *a, const float *b );
void cross( float *a, const float *b, const float *c );
void normalize( float *a );

void display();
void mousebutton(int button, int state, int x, int y );
void mousemove(int x, int y);


void main( int argc, char **argv )
{
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
glutInitWindowSize( 512, 512 );

glutCreateWindow( "test09" );
glutDisplayFunc( display );

glutMouseFunc( mousebutton );
glutMotionFunc( mousemove );

glutMainLoop();
}

void display()
{
GLint viewport[4];
glGetIntegerv( GL_VIEWPORT, viewport );

glEnable( GL_DEPTH_TEST );
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );

glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective( 45, double(viewport[2])/viewport[3], 0.1, 10 );

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( 0,0,3, 0,0,0, 0,1,0 );
glMultMatrixf( mo );

glutSolidTeapot(1);

glutSwapBuffers();
}

void mousebutton(int button, int state, int x, int y )
{
vassign( v0, 2.0*x/512-1, -2.0*y/512+1, 1 );
normalize(v0);
}

void mousemove(int x, int y)
{
float axis[3], angle;

vassign( v1, 2.0*x/512-1, -2.0*y/512+1, 1 );
normalize(v1);
if( v0[0]==v1[0] && v0[1]==v1[1] && v0[2]==v1[2] )
return;
cross(axis,v0,v1);
normalize(axis);
angle = acosf( clamp(dot(v0,v1),-1,1) );
vassign( v0, v1 );

glPushMatrix();
glLoadIdentity();
glRotatef( angle*180/PI, axis[0], axis[1], axis[2] );
glMultMatrixf( mo );
glGetFloatv( GL_MODELVIEW_MATRIX, mo );
glPopMatrix();
glutPostRedisplay();
}


float clamp( float x, float a, float b ){ return x<a ? a : (x<b?x:b); }
float dot( const float *a, const float *b ){ return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; }
float norm( const float *a ){ return sqrtf(dot(a,a)); }
void vassign( float *a, float x, float y, float z ){ a[0]=x; a[1]=y; a[2]=z; }
void vassign( float *a, const float *b ){ a[0]=b[0]; a[1]=b[1]; a[2]=b[2]; }

void cross( float *a, const float *b, const float *c )
{
a[0] = b[1]*c[2] - c[1]*b[2];
a[1] = -b[0]*c[2] + c[0]*b[2];
a[2] = b[0]*c[1] - c[0]*b[1];
}

void normalize( float *a )
{
float l = norm(a);
a[0]/=l; a[1]/=l; a[2]/=l;
}






This user interface is probably the implementation you wanted.

Euler angle? Forget it, it is not going to work. If you insist to use Euler angle, find a rotation matrix in the above program, convert it to Euler angle for storage and then convert the Euler angle to rotation matrix for computation. Just make sure you are not doing any calculation using Euler angle (beside storage), everything will be fine. Is it sound more comforting?

[Edited by - ma_hty on May 9, 2008 3:24:30 PM]

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  

  • Announcements

  • Forum Statistics

    • Total Topics
      628305
    • Total Posts
      2981967
  • 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