Is there a difference between GLSL/GLM and Python/numpy when it comes to 4×4 matrix multiplication?

Question:

Basically, this works:

glUniformMatrix4fv(glGetUniformLocation(self.shader.program, "projection"), 1, GL_FALSE, self.P)
glUniformMatrix4fv(glGetUniformLocation(self.shader.program, "view"), 1, GL_FALSE, self.V)
glUniformMatrix4fv(glGetUniformLocation(self.shader.program, "model"), 1, GL_FALSE, self.M)
#version 330 core

layout (location=0) in vec3 vertexPos;
layout (location=1) in vec2 vertexTexCoord;
layout (location=2) in vec3 vertexNormal;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

out vec2 fragmentTexCoord;

void main(){
    gl_Position = projection * view * model * vec4(vertexPos, 1.0);
    fragmentTexCoord = vertexTexCoord;
}

But this doesn’t:

self.PVM = np.matmul(self.P, np.matmul(self.V, self.M))
glUniformMatrix4fv(glGetUniformLocation(self.shader.program, "PVM"), 1, GL_FALSE, self.PVM)
#version 330 core

layout (location=0) in vec3 vertexPos;
layout (location=1) in vec2 vertexTexCoord;
layout (location=2) in vec3 vertexNormal;

uniform mat4 PVM;

out vec2 fragmentTexCoord;

void main(){
    gl_Position = PVM * vec4(vertexPos, 1.0);
    fragmentTexCoord = vertexTexCoord;
}

Passing in each matrix individually then doing the multiplication within the shader produces expected result (i.e. I can see the model and move around, etc.). Calculating the PVM matrix in Python first makes the model disappear. The above code is all I’m changing.

Asked By: geo9

||

Answers:

numpy.matmul behaves different than a GLSL matrix multiplication. Compare numpy.matmul and GLSL Programming/Vector and Matrix Operations. You have to reverse the order of the matrix multiplication:

self.PVM = np.matmul(self.P, np.matmul(self.V, self.M))

self.PVM = np.matmul(self.M, np.matmul(self.V, self.P))
Answered By: Rabbid76
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.