OpenGL - Translate after rotate

2019-08-27 17:48发布

问题:

I am trying to translate an object in world space after rotating it at the origin. The problem is, after I rotate an object while it's at the origin, its local coordinate system rotates as well, so its axes are not parallel with the world coordinate axes anymore. So, for example, if I needed to translate an object to the point (3, 0, 5) after rotating the object around the y-axis, I would not be able to do this since the object's local coordinate system isn't the same as the world coordinate system. For example:

glRotatef(45, 0.0, 1.0, 0.0);
glTranslatef(3.0, 0.0, 5.0);
glutSolidCube(1);               // This won't be at (3,0,5) like how I need it

How can I overcome this?

回答1:

This is not so much a property of OpenGL, but matrix math.

When you send in a vertex to the OpenGL fixed function pipeline, it gets transformed by the matrices modelview and projection, i.e.

 v_eye = MODELVIEW · v
v_clip = PROJECTION · v_eye

Now the modelview matrix is composed of all those sub-transformations. And they're non commutative, i.e. order of operations matters. For example

MODELVIEW = T_0 · R_0 · R_1 · T_1 · S_1 · R_2

Now you can rewrite the v_eye calculation above as

v_eye = T_0 · ( R_0 · ( R_1 · (T_1 · (S_1 · (R_2 · v)))))

As you can see, the v is multiplied (just like the matrices) right to left onto the stack of matrices you composed modelview of.

However what happens in OpenGL is, that the one matrix "MODELVIEW" is calculated, and v is transformed only with that 4×4 scheme of numbers. OpenGL does not "re-execute" all the matrix multiplication steps.



回答2:

opengl statement run on GPU in reverse order.

So Translate first then rotate.