顶点着色器均匀失真

vertex shader uniform distortion

我有一个四边形,由两个三角形组成,定义如下:

glm::vec3 coords[] = {
        glm::vec3(-1.0f, -1.0f, -0.1f),
        glm::vec3( 1.0f, -1.0f, -0.1f),
        glm::vec3( 1.0f,  1.0f, -0.1f),
        glm::vec3(-1.0f,  1.0f, -0.1f)
    };

    glm::vec3 normals[] = {
        glm::vec3(0.0f, 0.0f, 1.0f),
        glm::vec3(0.0f, 0.0f, 1.0f),
        glm::vec3(0.0f, 0.0f, 1.0f),
        glm::vec3(0.0f, 0.0f, 1.0f)
    };

    glm::vec2 texCoords[] = {
        glm::vec2(0.0f, 0.0f),
        glm::vec2(1.0f, 0.0f),
        glm::vec2(1.0f, 1.0f),
        glm::vec2(0.0f, 1.0f)
    };

    unsigned int indices[] = {
        0, 1, 2,
        2, 3, 0
    };

我试图通过黑白 jpg 更改四边形的 'height',因此我编写了一个顶点着色器来执行此操作,但是转换并未直接应用于四边形的所有点。这是我正在使用的 jpg: 我预计图像会突然变白,但这是我得到的结果:https://i.gyazo.com/639a699e7aa12cda2f644201d787c507.gif。似乎只有左上角达到了最大高度,整个左边的三角形不知何故都在变形。

我的顶点着色器:

layout(location = 0) in vec3 vertex_position;
layout(location = 1) in vec3 vertex_normal;
layout(location = 2) in vec2 vertex_texCoord;
layout(location = 3) in vec4 vertex_color;

out vec2 v_TexCoord;
out vec4 v_Color;
out vec3 v_Position;
out vec3 v_Normal;

//model view projection matrix
uniform mat4 u_MVP;
uniform mat4 u_ModelMatrix;
uniform sampler2D u_Texture1_Height;

void main()
{
    v_TexCoord = vertex_texCoord;
    v_Color = vertex_color;
    v_Normal = mat3(u_ModelMatrix) * vertex_normal;

    vec4 texHeight = texture(u_Texture1_Height, v_TexCoord);
    vec3 offset = vertex_normal * (texHeight.r + texHeight.g + texHeight.b) * 0.33;
    
    v_Position = vec3(u_ModelMatrix * vec4(vertex_position + offset, 1.0f));

    gl_Position = u_MVP * vec4(vertex_position + offset, 1.0f);
}

凹凸贴图只是按顶点计算而不是按片段计算,因为您在顶点着色器中进行计算。顶点着色器仅针对每个顶点(针对四边形的每个角)执行。比较 Vertex Shader and Fragment Shader.

无法为每个片段置换剪辑 space 坐标。您必须将几何体(四边形)细分为许多小四边形。由于顶点着色器是针对每个片段执行的,因此几何体会针对网格中的每个角点进行位移。这是常见的方法。参见 this 模拟。

另一种可能性是实现视差映射,其中通过在片段着色器中置换纹理坐标和扭曲法向量来实现深度效果。参见 Normal, Parallax and Relief mapping respectively LearnOpenGL - Parallax Mapping or Bump Mapping with glsl