首页 > 解决方案 > 屏幕空间阴影着色器代码的问题

问题描述

我有这个 GLSL 函数,它应该对深度缓冲区进行光线行进并检测屏幕空间阴影的遮挡。三次检查了世界位置、光照、视图矩阵、深度缓冲区等输入数据是否正确后,我不断得到 1.0,这意味着它从未找到遮挡物。什么可能是错的?我对深度值/比较做错了吗?

float ScreenSpaceShadow(vec3 worldPos, DirectionalLight light) {
    vec4 rayPos = ubo.view * vec4(worldPos, 1.0);
    vec4 rayDir = ubo.view * vec4(-light.direction.xyz, 0.0);

    vec3 rayStep = rayDir.xyz * 0.05 / 16.0;
    float occlusion = 0.0f;

    for(int i = 0; i < 16; i++) {
        rayPos.xyz += rayStep;

        // get the uv coordinates
        vec4 v = ubo.projection * rayPos; // project
        vec2 rayUV = v.xy / v.w; // perspective divide
        rayUV = rayUV * vec2(0.5) + 0.5; // -1, 1 to 0, 1

        if(rayUV.x < 1.0 && rayUV.x > 0.0 && rayUV.y < 1.0 && rayUV.y > 0.0) {
            // sample current ray point depth and convert it bback  to -1 , 1
            float ndc = texture(gDepth, rayUV).r * 2.0 - 1.0;
            // get linear scene depth 
            float near = 0.1;
            float far = 10000.0;
            float linearDepth = (2.0 * near * far) / (far + near - ndc * (far - near));

            // delta between scene and ray depth
            float delta = rayPos.z - linearDepth;

            // if the scene depth is larger than the ray depth, we found an occluder
            if((linearDepth > rayPos.z) && (abs(delta) < .05)) {
                occlusion = 1.0;
                break;
              }
        }
    }

    return 1.0 - occlusion;
}

标签: graphics3dglsl

解决方案


推荐阅读