Troubeshooting - vquanghuy/learn-opengl GitHub Wiki
Issue 1
An OpenGL rendering problem occurred where textures were not mapping correctly onto 3D geometry, resulting in visual artifacts like those shown in the provided image.
Solution
The core problem was an attribute mismatch: vertex data was being sent with three attributes (position, normal, texture coordinates), but the vertex shader was only configured to receive two (position, texture coordinates). This led to the texture coordinates being misinterpreted. The solution was to modify the vertex shader to include the missing normal attribute declaration.
// BEFORE
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aTexCoord; // Only 2 attributes declared
// AFTER
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aNormal; // Normal attribute added
layout (location = 2) in vec2 aTexCoord; // Corrected location
Issue 2
Objects or parts of objects that should have been behind others were being drawn in front, leading to incorrect rendering order and visual depth perception issues, as likely observed in the provided image of the textured crate.
Solution
The cause of the incorrect drawing order was that the depth test was not activated. Without the depth test, OpenGL draws fragments in the order they are provided, without considering their distance from the viewer. The solution involved enabling the depth test using glEnable(GL_DEPTH_TEST)
and ensuring the depth buffer was cleared at the beginning of each rendering loop using glClear(GL_DEPTH_BUFFER_BIT)
along with the color buffer (glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
). This allows OpenGL to discard fragments that are behind other fragments already drawn, ensuring correct depth sorting and proper occlusion.
If the depth buffer is not cleared at the start of each frame, it retains the depth information from the previous frame. This old depth data interferes with the rendering of the current frame, potentially causing parts of objects to be incorrectly discarded or drawn based on the previous frame's depth values, leading to visual glitches (possibly like those shown in the second provided image with the scattered lines).