Incorrect lookat matrix

Viewed 877

I've started working on shadow maps for directional lights and for that I need a lookAt matrix, but when I tried constructing from example of an online tutorial it looked something like this:

enter image description here

It currently looks like this: https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif

I've tried multiple ways of constructing it but with no success, I checked if the normalization, cross and translation functions weren't correct but that wasn't the case. I've also tried changing from column-major matrices to row-major matrices but with no luck. Would someone be able to point out what I did wrong?

Lookat matrix constructing:

Center vector = (0, 0, 0), Up vector = (0, 1, 0)

Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
        Matrix4f out(1.0f); 

        Vector3f z = position.substract(center).normalize(); 


        Vector3f y = up;

        Vector3f x = y.cross(z).normalize();

        y = z.cross(x);

        out.mElements[0 * 4 + 0] = x.x;
        out.mElements[0 * 4 + 1] = x.y;
        out.mElements[0 * 4 + 2] = x.z;

        out.mElements[1 * 4 + 0] = y.x;
        out.mElements[1 * 4 + 1] = y.y;
        out.mElements[1 * 4 + 2] = y.z;

        out.mElements[2 * 4 + 0] = z.x;
        out.mElements[2 * 4 + 1] = z.y;
        out.mElements[2 * 4 + 2] = z.z;

        return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
    }
}

Credit for code: https://stackoverflow.com/users/5577765/rabbid76

This is how I pass a matrix to the shader:

void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
    glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}

After I've calculated the lookAt matrix I directly pass it to the vertex shader to the uniform: view and calculate a point like this:

gl_Position = projection * view * model * vec4(vertexPosition, 1.0);

And this is how my matrix multiplication works:

Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
    Matrix4f out;
    for (int y = 0; y < 4; y++) {
        for (int x = 0; x < 4; x++) {
            fl32 o = 0;
            for (int c = 0; c < 4; c++) {
                o += this->mElements[c + y * 4] * other.mElements[x + c * 4];                   }
            out.mElements[x + y * 4] = o;
        }
    }
    return out;
}

Edit: updated picture Edit: Added a more detailed description

3 Answers
Related