'translation in GLSL shader
I'm trying to move figure inside vertex GLSL shader:
layout(location = 0) in vec3 Position;
layout(location = 1) in vec3 offset;
uniform mat4 ProjectionViewMatrix;
void main()
{
vec3 newPos = Position;
newPos.x += offset[0];
newPos.y += offset[1];
//newPos.z += offset[2];
mat4 translation;
translation[0][0] = 1;
translation[1][1] = 1;
translation[2][2] = 1;
translation[2][3] = offset[2];
translation[3][3] = 1;
gl_Position = ProjectionViewMatrix * (translation * vec4(newPos, 1.0));
}
I would like to draw many similar objects, with different coordinates, so I'm using glDrawArraysInstanced and layout(location = 1) in vec3 offset; - dynamic buffer;
With translation matrix it does not work. But if I will uncomment line newPos.z += offset[2]; and remove translation matrix it would work.
I prefer to use matrix because in future I would like pass in shader info about scaling dynamically. Why it does not work with matrix?
Solution 1:[1]
GLSL operates with matrices stored in column major order. Writing just the indices corresponding to a matrix the way you would normally write it:
[0][0] [1][0] [2][0] [3][0]
[0][1] [1][1] [2][1] [3][1]
[0][2] [1][2] [2][2] [3][2]
[0][3] [1][3] [2][3] [3][3]
To apply a translation while multiplying this matrix with a column vector on the right side, the translation vector goes into the first 3 elements of the last column, which are the index pairs [3][0]
, [3][1]
, and [3][2]
. This means that the z-offset goes into matrix element [3][2]
.
Solution 2:[2]
To be extra clear, it seems you can build a translation matrix like so:
mat4 BuildTranslation(vec3 delta)
{
mat4 m;
m[0][0] = 1;
m[1][1] = 1;
m[2][2] = 1;
m[3] = vec4(delta, 1.0);
return m;
}
Or this answer has another method:
mat4 BuildTranslation(vec3 delta)
{
return mat4(
vec4(1.0, 0.0, 0.0, 0.0),
vec4(0.0, 1.0, 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(delta, 1.0));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Reto Koradi |
Solution 2 | idbrii |