1

我正在尝试实现 Crytek 屏幕空间环境遮挡算法的简单变体。

据我了解的算法;

  1. 对于像素p ,在视图空间的球体中围绕p进行采样。
  2. 将采样点sp 投影到屏幕空间。
  3. 将采样点的深度与当前像素的深度进行比较。

这基本上应该就是它的全部了。如果采样点的深度更高(它位于几何之外),它不会遮挡当前像素(p)。

float z = gl_FragCoord.z; // depth-buffer value for the current pixel
int occluding_points = 0;
vec4 fPosition = model_transformation * vec4(position, 1.0f); // Really from vertex shader
#ifdef CRYTEK_AO
    const int NUM_SAMPLES = 10;
    float R = 3.0f;
    const float[10] steps = float[](0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f);
    for (int sample_id = 0; sample_id < NUM_SAMPLES; sample_id++) {
        // 1. Generate sample point in world space.
        float ang = steps[sample_id];
        vec4 sample_point = vec4(R * cos(2 * M_PI * ang) * sin(M_PI * ang) + fPosition.x,
                                 R * sin(2 * M_PI * ang) * sin(M_PI * ang) + fPosition.y,
                                 R * sin(M_PI * ang) + fPosition.z,
                                 1.0f);
        // 2. Transform sample point from view space to screen space to get its depth value.
        sample_point = projection * camera_view * sample_point; // Clip space
        sample_point = sample_point / sample_point.w;           // Perspective division - Normalized device coordinate
        float sample_depth = 0.5f * (sample_point.z + 1.0f);    // Viewport transform for z - window space

        // 3. Check whether sample_point is behind current pixel depth.
        if (sample_depth > z) { occluding_points++; }
    }
    occlusion_factor = occluding_points / float(NUM_SAMPLES);
    // Diffuse, specular components removed
    total_light += vec3(ambient_intensity) * (1.0f - occlusion_factor); // Ambient factor
    outColor = total_light;
#endif

下面是它的外观截图。出于某种原因,伪影仅在向下看 z 轴时出现,因此转换可能有些可疑,尽管在渲染对象和相机等时工作正常。

环境光遮挡出了问题...

基本上看任何其他角度时,您似乎希望将遮挡因子设置为 0.5(这将使您在所有颜色通道中变灰)。

没有异常

意外整数除法固定为浮点数除法后的结果。 在此处输入图像描述

在此处添加了闪烁的视频。

有什么线索吗?

编辑:四舍五入检测到一个问题。编辑:沿 z 轴移动时向工件添加了视频链接。

4

1 回答 1

2

您的代码有两个可疑之处。

整数除法

occlusion_factor = occluding_points / NUM_SAMPLES;

只需将 occluding_points 的类型更改为浮动,就可以了。

采样

    vec4 sample_point = vec4(R * cos(2 * M_PI * ang) * sin(M_PI * ang) + fPosition.x,
                             R * sin(2 * M_PI * ang) * sin(M_PI * ang) + fPosition.y,
                             R * sin(M_PI * ang) + fPosition.z,
                             1.0f);

这每次都会为您提供来自世界坐标中相同螺旋的样本,因此使用正确的表面,您将获得取决于视角的伪影。这就是我认为当您向下看 z 轴时,与上面的舍入误差配对时发生的情况。

于 2017-06-02T20:50:57.660 回答