We can see how all these concepts apply in practice. Everything is covered in the
"matrices_transformations" example in the BeforeTheMesh repository.
In that example, we create a simple scene with a rotating cube and a camera orbiting around it.
The cube's model matrix is updated every frame to apply rotation, while the view matrix is set to
position the camera. The projection matrix is configured for perspective projection.
By examining the code, you can see how these matrices are constructed and combined to render the
scene correctly.
void calculate_sample_mvp()
{
// calculate a sample Model-View-Projection (MVP) matrix for rendering an object.
// This is just an example to show how the transformations work.
btm::fmat4 translation = btm::Translation<float>(0.0f, 0.0f, -5.0f); // translate the object 5 units into the screen
btm::fmat4 rotation = btm::Rotation<float>(0, 0, 0); // no rotation for now, but you could set this to rotate the object around its axes
btm::fmat4 scale = btm::Scale<float>(1.0f, 1.0f, 1.0f); // no scaling for now, but you could set this to make the object larger or smaller
btm::fmat4 model = translation * rotation * scale; // the model matrix transforms the object from its local model space to world space
// sample setup for the camera's view and projection matrices.
// In a real application, these would be computed based on the camera's parameters and the viewport size.
btm::fvec3 cameraPos(0, 0, 20); // position the camera 20 units away from the origin along the z-axis
btm::fvec3 cameraTarget(0, 0, 0); // look at the origin where the object is located
btm::fvec3 upVector(0, 1, 0); // define the up direction for the camera (positive y-axis)
btm::fmat4 view = btm::LookAt<float>(cameraPos, cameraTarget, upVector); // the view matrix transforms world space to camera (view) space
// calculate a perspective projection matrix with a 20 degree field of view,
// an aspect ratio of 800/600, and near/far planes at 0.1 and 100.
float fov = btm::dtr(20.f); // convert 20 degrees to radians
float aspect = 800.0f / 600.0f; // example aspect ratio
float nearPlane = 0.1f; // near plane distance
float farPlane = 100.0f; // far plane distance
btm::fmat4 projection = btm::Perspective<float>(fov, aspect, nearPlane, farPlane);
// finally, we combine the model, view, and projection matrices to get the MVP matrix
// that will be used in the vertex shader to transform the vertices of the object from model space to clip space.
btm::fmat4 mvp = projection * view * model;
}
This is the exact structure used in modern rendering.