我正在为练习构建一个简单的 3D 游戏,但在使用索引渲染时,我无法将法线传递给我的着色器。对于多边形的每个面,每个顶点都有相同的法线值。对于具有 8 个顶点的立方体,将有 6 * 6 = 36 条法线(因为每个表面都使用两个三角形进行渲染)。使用索引绘图我只能传递 8 个,每个顶点一个。这不允许我通过表面法线,只能通过平均顶点法线。
如何将 36 个不同的法线传递给 36 个不同的索引?使用 glDrawArrays 显然很慢,所以我选择不使用它。
这是我的着色器:
#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 vertNormal;
smooth out vec4 colour;
uniform vec4 baseColour;
uniform mat4 modelToCameraTrans;
uniform mat3 modelToCameraLight;
uniform vec3 sunPos;
layout(std140) uniform Projection {
mat4 cameraToWindowTrans;
};
void main() {
gl_Position = cameraToWindowTrans * modelToCameraTrans * vec4(position, 1.0f);
vec3 dirToLight = normalize((modelToCameraLight * position) - sunPos);
vec3 camSpaceNorm = normalize(modelToCameraLight * vertNormal);
float angle = clamp(dot(camSpaceNorm, dirToLight), 0.0f, 1.0f);
colour = baseColour * angle * 0.07;
}
这是我目前用来绑定到 VAO 的代码:
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, polygonBuffer);
// The position input to the shader is index 0
glEnableVertexAttribArray(POSITION_ATTRIB);
glVertexAttribPointer(POSITION_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0);
// Add the vertex normal to the shader
glBindBuffer(GL_ARRAY_BUFFER, vertexNormBuffer);
glEnableVertexAttribArray(VERTEX_NORMAL_ATTRIB);
glVertexAttribPointer(VERTEX_NORMAL_ATTRIB, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
这是我的渲染器:
glBindVertexArray(vertexArray);
glDrawElements(GL_TRIANGLES, polygonVertexCount, GL_UNSIGNED_SHORT, 0);
glBindVertexArray(0);