如何将顶点变换移动到顶点着色器

时间:2013-03-18 01:44:33

标签: glsl vertex-shader

我需要你的帮助!我试图将顶点变换部分从cpu代码移动到顶点着色器,这是顶点变换的cpp代码:

//calculate the transform matrix of a refelcting surface
//@point: a point on the surface
//@normal: the normalized normal of the surface
//@return: the transform matrix
glm::mat4 flatReflect(glm::vec3& point, glm::vec3& normal)
{
    glm::vec4 R = glm::vec4(point,1);
    glm::vec4 N = glm::vec4(normal,0);
    GLfloat d = glm::dot(R,N);
    glm::mat4 result;
    result[0][0] = 1 - 2* N.x*N.x;
    result[0][1] = -2*N.x*N.y;
    result[0][2] = -2*N.x*N.z;
    result[0][3] = -2*N.x*d;
    result[1][0] = result[0][1];
    result[1][1] = 1 - 2*N.y*N.y;
    result[1][2] = -2*N.y*N.z;
    result[1][3] = -2*N.y*d;
    result[2][0] = result[0][2];
    result[2][1] = result[1][2];
    result[2][2] = 1-2*N.z*N.z;
    result[2][3] = -2*N.z*d;
    result[3][0] = 0;
    result[3][1] = 0;
    result[3][2] = 0;
    result[3][3] = 1;
    return result;
}

有什么想法吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

你可以很容易地翻译它。首先,翻译这些行:

glm::vec4 R = glm::vec4(point,1);
glm::vec4 N = glm::vec4(normal,0);
GLfloat d = glm::dot(R,N);

这些类型和函数本身存在于GLSL中,不需要限定条件,因此:

vec4 R = vec4(point,  1.0);  // An explicit decimal is important; some drivers do
vec4 N = vec4(normal, 0.0);  // not perform implicit coercions.
float d = dot(R, N);

构造矩阵略有不同;而不是声明矩阵并设置其元素,您可以一次创建并返回它,例如(对于单位矩阵):

return mat4(1.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1.0);

访问向量的元素就像在C ++中一样。知道了,其余的翻译应该很容易。祝你好运!