Learn OpenGL 6

Transformations

Github source code: link
learning materials: learnopengl

Introduction

Transformations contain translation, scale, rotation or a combination of one or more of these. One thing to note is that when combing multiple matrices, the order should be read from right-to-left. If we want to do scale first then translation, It should look like this:

GLM

GLM stands for OpenGL Mathematics and is a header-only library. It is an easy-to-use OpenGL math library. Download it from official website, put glm folder under your project, include needed headers.

1
2
3
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

Demo

Transformation matrices can be passed to vertex shader using uniform from host program.

host

1
2
3
4
5
6
7
8
// activate shader
shader.activate();

// transform matrix
glm::mat4 trans = glm::mat4(1.0f);
trans = glm::translate(trans, glm::vec3(-0.5f, 0.5f, 0.0f));
trans = glm::rotate(trans, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); // axis needs to be unit
glUniformMatrix4fv(glGetUniformLocation(shader.getID(), "transform"), 1, GL_FALSE, glm::value_ptr(trans));

vertex shader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
layout (location = 2) in vec2 aTexture;

out vec3 ourColor;
out vec2 TexCoord;

uniform mat4 transform;

void main() {
gl_Position = transform * vec4(aPos, 1.0);
ourColor = aColor;
TexCoord = aTexture;
}

References

Author

Joe Chu

Posted on

2023-11-20

Updated on

2024-04-13

Licensed under

Comments