Search code examples
c++openglglm-mathperspectivecamera

OpenGL clips an object for no apparent reason


I'm trying to visualize a simple quad made of -1 to 1 vertices along x and y axis. Why opengl clips the object? The code seems correct to me

glm::mat4 m = glm::translate(glm::mat4{1.0f}, toGlmVec3(objectPosition));
glm::mat4 v = glm::lookAtLH(toGlmVec3(cameraPosition), toGlmVec3(objectPosition), glm::vec3(0, 1, 0));
glm::mat4 p = glm::perspective(glm::radians(50.f), float(640.f) / 480.f, 0.0001f, 100.f);
glm::mat4 mvp = /* p* */ v * m; // when I take p back, the object disappears completely

testShader.use();
testShader.setVector4("u_color", math::Vector4f(0.f, 1.f, 0.f, 1.f));
testShader.setMatrix4("u_mMVP", mvp);

in shader's code only a line

gl_Position = u_mMVP * vec4(a_Pos, 1.0);

enter image description here
after moving the camera a bit along z axis
enter image description here

if I comment out v *, then it works fine and object moves along x and y axis on the screen

without view matrix, only model:
enter image description here
move the object along x and y
enter image description here

so it looks like the rendering code is working fine but what is wrong with view and projection matrices?


Solution

  • The object is clipped by the near and far plane of the Orthographic projection. If you don't explicitly set an projection matrix, the projection matrix is the Identity matrix. The near plane far pane are at +/- 1.

    Use glm::ortho to define a different projection matrix. e.g.:

    glm::mat4 p = glm::ortho(-1, 1, -1, 1, -10, 10);
    

    The orthographic projection matrix defines a cuboid viewing volume around the position of the viewer. All geometry outside of this volume is clipped.