使用聚光灯在OpenGL中进行阴影贴图会产生异常效果

时间:2014-07-09 04:26:33

标签: opengl glsl shadow shadow-mapping

我一直在尝试实施阴影贴图。虽然我认为我现在已经接近了,但我却遇到了一种奇怪的效果(如下图所示):

Shadow Mapping

如您所见,阴影区域显得太小。对立方体本身也有不寻常的影响。

正在渲染的几何体是尺寸为100.0的方形平面上的尺寸为1.0的立方体。场景包含一个聚光灯,其角度(从一侧到另一侧)为0.5弧度,范围为100.0。这个聚光灯围绕y轴运行并调整其旋转以查看原点。

我设置了帧缓冲和深度纹理(512 x 512),如下所示:

// Create and configure the depth texture.
glGenTextures(1, &m_depthTexture);
glBindTexture(GL_TEXTURE_2D, m_depthTexture);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

GLfloat border[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, (void*)0);

// Assign the depth texture to texture channel 0.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_depthTexture);

// Create and configure the framebuffer.
glGenFramebuffers(1, &m_framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
GLenum drawBuffers[] = { GL_NONE };
glDrawBuffers(1, drawBuffers);

然后我从聚光灯的角度将场景渲染到阴影贴图帧缓冲区。这似乎有效。使用OpenGL调试工具检查深度纹理显示以下内容:

Depth Texture

第二次渲染场景,我为深度纹理和阴影矩阵设置制服:

glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, shadowMap.depthTexture());
program->uniform("shadowMap", 1);

const M3D::Matrix4 lightViewMatrix = lightTransformComponent->transformationMatrix().inverse();

const float invTanHalfFov = 1.0f / std::tan(coneAngle * 0.5f);
const float nearClipPlane = 0.3f;
const float farClipPlane = lightLightComponent->range();
const float zRange = nearClipPlane - farClipPlane;
const Matrix4 lightProjectionMatrix(
    invTanHalfFov, 0.0f, 0.0f, 0.0f,
    0.0f, invTanHalfFov, 0.0f, 0.0f,
    0.0f, 0.0f, -(nearClipPlane + farClipPlane) / zRange, 2.0f * nearClipPlane * farClipPlane / zRange,
    0.0f, 0.0f, 1.0f, 0.0f
);

const Matrix4 shadowMatrix = lightProjectionMatrix * lightViewMatrix * modelMatrix;
program->uniform("shadowMatrix", shadowMatrix);

我在顶点着色器中计算阴影坐标:

f_shadowCoordinate = shadowMatrix * vec4(v_position, 1.0f);

然后,在片段着色器中,我投射该坐标并将其偏置到区间[0,1]中的范围。

vec2 projectedShadowCoordinates = (f_shadowCoordinate.xy / f_shadowCoordinate.w) * 0.5f + vec2(0.5f, 0.5f);
float shadowDistance = texture(shadowMap, projectedShadowCoordinates).x;
return vec4(1.0f) * shadowDistance;

修改

令人讨厌的是,这个问题是由于在渲染到阴影帧缓冲区时错误地将投影矩阵设置为相机的投影矩阵(而不是光的投影矩阵)而引起的。

0 个答案:

没有答案