【发布时间】:2015-03-02 18:47:56
【问题描述】:
我想知道如何计算每个片段的法线以便能够为场景添加光!
我读取了从 libnoise 库生成的纹理 - http://libnoise.sourceforge.net,并通过计算几何着色器中的内容来创建地形,如下所示
地形看起来不错,但没有闪电..
我的代码如下所示:
const int TOTAL = (TERRAIN_WIDTH*TERRAIN_DEPTH);
const int TOTAL_INDICES = TOTAL*3*3;
glm::vec3 vertices[TOTAL];
GLuint indices[TOTAL_INDICES];
//...
int count = 0;
GLuint* id=&indices[0];
// Set up Geometry for terrain
for(int j = 0; j < TERRAIN_DEPTH; j++) {
for(int i = 0; i < TERRAIN_WIDTH; i++) {
//So I want to calculate position and normal here <-----
vertices[count] = glm::vec3((float(i)/(TERRAIN_WIDTH-1)), 1.0,(float(j)/(TERRAIN_DEPTH-1)));
count++;
}
}
for (int i = 0; i < TERRAIN_DEPTH-1; i++) {
for (int j = 0; j < TERRAIN_WIDTH-1; j++) {
int i0 = j+ i*TERRAIN_WIDTH;
int i1 = i0+1;
int i2 = i0+TERRAIN_WIDTH;
int i3 = i2+1;
*id++ = i0;
*id++ = i2;
*id++ = i1;
*id++ = i1;
*id++ = i2;
*id++ = i3;
}
}
...
GLubyte *pData = SOIL_load_image(filename, &textureWidth,
&textureHeight, &channels, SOIL_LOAD_L);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices) , &vertices[0], GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementArrayObject);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], GL_STATIC_DRAW);
glGenTextures(1, &heightMapTextureID);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, heightMapTextureID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, textureWidth, textureHeight, 0, GL_RED, GL_UNSIGNED_BYTE, pData);
几何着色器:
layout (triangles) in;
layout (triangle_strip, max_vertices=9) out;
uniform sampler2D heightMapTexture;
uniform mat4 projection;
uniform mat4 model;
uniform mat4 view;
void main()
{
for(int i=0;i<gl_in.length(); i++) {
vec4 position = gl_in[i].gl_Position;
float height = texture(heightMapTexture, position.xz).r;
vec2 xz = (position.xz*50); // the multiplication will decide how big the terrain will be
gl_Position = (projection * view * model) * vec4(xz.x,height*5,xz.y , 1.0);
EmitVertex();
}
EndPrimitive();
}
我的顶点和片段着色器是最基础的。
#version 330 core
layout(location = 0) out vec4 finalColor;
void main()
{
finalColor = vec4(vec3(1,1,1), 1.0f);
}
顶点:
#version 330 core
//inputs
layout(location = 0)in vec3 position;
void main()
{
gl_Position = vec4(position, 1.0f);
}
有人可以帮助我吗?
【问题讨论】:
-
计算每个片段法线的最简单方法是在片段着色器中取
gl_FragCoord的偏导数的叉积。这将使您获得屏幕空间法线。这是讨论here。不过,这些法线将是平坦的,所以我不知道这是否是您想要的?那就是使用视图空间法线,这需要插入一个额外的每个顶点属性。 我不确定您的应用程序需要哪个坐标空间法线。
标签: c++ opengl fragment-shader geometry-shader