Computermatronic
Computermatronic

Reputation: 223

What order should the view matrix be caluculated in?

Currently I have been calculating the view matrix like this:

viewMatrix = cameraRot * cameraTrans

and the model matrix like this:

modelMatrix = modelTrans * modelScale

where cameraTrans and modelTrans are translation matrices, modelScale is a scaling matrix, and cameraRot and modelRot are rotation matrices produced by quaternions.

Is this correct? I've been googling this for a few hours, and no one mentions the order for the view matrix, just the model matrix. It all seems to work, but I wrote the matrix and quaternion implementations myself so I cant' tell if this is a bug.

(Note: The matrices are row major)

Upvotes: 2

Views: 611

Answers (2)

Amadeus
Amadeus

Reputation: 10695

Let us talk about transformation between coordinate system. Suppose you have a point defined on a local system. You want to describe it in a global system, so what you do is rotate this point, in order to align its axis, and then, translate it to its final position. You can described this mathematically by:

Pg = T*R*Pl, where M = T*R

In this way, M allows you describe any point, defined in a local coordinate system, into a global coordinate system.

You can do the same with camera, but what you really want is do exactly the inverse that you have done before, i.e., you want to describe any point in global coordinate system to the camera local coordinate system:

Pc = X*Pg, but what is the value of X?

You know that:

Pg = Tc*Rc*Pc, so Pc = inv(Tc*RC)*Pg

in order words:

X = inv(Tc*Rc) = inv(Rc) * inv(Tc)

Therefore, to describe a point, from its local coordinate system, to the camera coordinate system, you just need to concatenate those two matrices:

Pc = inv(Rc)*inv(Tc)*T*R*P, where
M' = inv(Rc)*inv(Tc)*T*R

Note that some systems (glm library, for example), define this matrix (X) as lookAt and its definition can be found here. I would suggest you to here this article too

Upvotes: 2

meepzh
meepzh

Reputation: 802

What you have is correct.

modelMatrix = modelTranslation * modelRotation * modelScale; // M=TRS
viewMatrix = cameraOrientation * cameraTranslation; // V=OT

To make this easier to remember, first note that matrices are essentially applied backwards. Let us consider that M=SRT. So you have a cube and you translate it. But if you rotate, it will rotate from the original pivot point. Then, once you apply a scaling factor, the model will be skewed because the scaling applies after the rotation. This is all hard to deal with- M=TRS is much easier for most purposes once you consider that. This is a little hard to describe in words, so let me know if you'd like some pictures.

Upvotes: 0

Related Questions