【问题标题】:3D Model Translation deforming the object使物体变形的 3D 模型平移
【发布时间】:2016-04-30 11:03:53
【问题描述】:

我创建了一个渲染 3d 立方体的程序,现在我想更改立方体的位置。我现在正在做的矩阵乘法似乎扭曲了立方体而不是改变它的位置。对于 0.1 - 0.4 范围内的值,失真很小,对于较大的值,失真会填满整个屏幕。

顶点着色器:

#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;

uniform mat4 projectionMatrix;
uniform mat4 cameraMatrix;
uniform mat4 modelMatrix;

out vec3 fragmentColor;

void main()
{
    gl_Position =  projectionMatrix * cameraMatrix * modelMatrix * vec4(vertexPosition_modelspace,1);
    fragmentColor = vertexColor;
}

Model.cpp(注意 modelMatrix 被初始化为单位矩阵,我使用的是 glm)

void Model::SetPos(glm::vec3 coords)
{
    modelMatrix[0][3] = coords[0];
    modelMatrix[1][3] = coords[1];
    modelMatrix[2][3] = coords[2];
}

void Model::Render()
{
    // Select the right program
    glUseProgram(program);

    // Set the model matrix in the shader
    GLuint MatrixID = glGetUniformLocation(program, "modelMatrix");
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, value_ptr(modelMatrix));

    // Setup the shader color attributes
    glEnableVertexAttribArray(1);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

    // Setup the shader vertex attributes
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

    // Draw the model
    glDrawArrays(GL_TRIANGLES, 0, triangles);

    // Now disable the attributes
    glDisableVertexAttribArray(0);
    glDisableVertexAttribArray(1);
}

其他矩阵是这样初始化的,保持不变:

cameraMatrix = glm::lookAt(pos, target, orient);
projectionMatrix = glm::perspective(45.0f, 1280.0f / 720.0f, 0.1f, 100.0f);

【问题讨论】:

    标签: c++ opengl matrix 3d


    【解决方案1】:

    glm 库生成列主矩阵。您还为 glUniformMatrix4fv 指定了 GL_FALSE,这对于列主矩阵是正确的。但是,当您设置位置时,您设置了错误的值。这段代码:

    void Model::SetPos(glm::vec3 coords)
    {
        modelMatrix[0][3] = coords[0];
        modelMatrix[1][3] = coords[1];
        modelMatrix[2][3] = coords[2];
    }
    

    导致矩阵在乘法后在 w 分量中产生非 1.0 值。这可能会导致一些奇怪的失真。您应该将 SetPos 更改为:

    void Model::SetPos(glm::vec3 coords)
    {
        modelMatrix[3][0] = coords[0];
        modelMatrix[3][1] = coords[1];
        modelMatrix[3][2] = coords[2];
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 1970-01-01
      • 2013-07-12
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多