Search code examples
openglglsllwjgl

Vertex displacement breaking mesh


I'm doing some OpenGL stuff in Java (lwjgl) for a project, part of which includes importing 3d models in OBJ format. Everything looks ok, until I try to displace vertices, then the models break up, you can see right through them. Here is Suzanne from blender, UV mapped with a completely black texture (for visibility's sake). In the frag shader I'm adding some white colour to the fragment depending on the fragments angle between its normal and the world's up vector:

enter image description here

So far so good. But when I apply a small Y component displacement to the same vertices, I expect to see the faces 'stretch' up. Instead this happens:

enter image description here

Vertex shader:

#version 150

in vec3 position;
in vec2 texCoords;
in vec3 normal;

void main()
{
    vertPosModel = position;                        

    cosTheta = dot(vec3(0.0, 1.0, 0.0), normal);    

    if(cosTheta > 0.0 && cosTheta < 1.0)     
        vertPosModel += vec3(0.0, 0.15, 0.0); 

    gl_Position = transform * vec4(vertPosModel, 1.0);
}

Fragment shader:

#version 150

uniform sampler2D objTexture;
in vec2 texcoordOut;
in float cosTheta;
out vec4 fragColor;

void main()
{
    fragColor = vec4(texture(objTexture, texcoordOut.st).rgb, 1.0) + vec4(cosTheta);

}

Solution

  • So, your algorithm offsets a vertex's position, based on a property derived from the vertex's normal. This will only produce a connected mesh if your mesh is completely smooth. That is, where two triangles meet, the normals of the shared vertices must be the same on both sides of the triangle.

    If the model has discontinuous normals over the surface, then breaks can appear anywhere that the normal stops being continuous. That is, the edges where there is a normal discontinuity may become disconnected.

    I'm pretty sure that Blender3D can generate a smooth version of Suzanne. So... did you generate a smooth mesh? Or is it faceted?