Advertisement
Guest User

Untitled

a guest
Dec 21st, 2024
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.95 KB | None | 0 0
  1. float ShadowCalculation(vec3 fragPosWorldSpace)
  2. {
  3.     // select cascade layer
  4.     vec4 fragPosViewSpace = view * vec4(fragPosWorldSpace, 1.0);
  5.     float depthValue = abs(fragPosViewSpace.z);
  6.  
  7.     int layer = -1;
  8.     for (int i = 0; i < cascadeCount; ++i)
  9.     {
  10.         if (depthValue < cascadePlaneDistances[i])
  11.         {
  12.             layer = i;
  13.             break;
  14.         }
  15.     }
  16.     if (layer == -1)
  17.     {
  18.         layer = cascadeCount;
  19.     }
  20.  
  21.     vec4 fragPosLightSpace = lightSpaceMatrices[layer] * vec4(fragPosWorldSpace, 1.0);
  22.     // perform perspective divide
  23.     vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
  24.     // transform to [0,1] range
  25.     projCoords = projCoords * 0.5 + 0.5;
  26.  
  27.     // get depth of current fragment from light's perspective
  28.     float currentDepth = projCoords.z;
  29.  
  30.     // keep the shadow at 0.0 when outside the far_plane region of the light's frustum.
  31.     if (currentDepth > 1.0)
  32.     {
  33.         return 0.0;
  34.     }
  35.     // calculate bias (based on depth map resolution and slope)
  36.     vec3 normal = normalize(fs_in.Normal);
  37.     float bias = max(0.05 * (1.0 - dot(normal, lightDir)), 0.005);
  38.     const float biasModifier = 0.5f;
  39.     if (layer == cascadeCount)
  40.     {
  41.         bias *= 1 / (farPlane * biasModifier);
  42.     }
  43.     else
  44.     {
  45.         bias *= 1 / (cascadePlaneDistances[layer] * biasModifier);
  46.     }
  47.  
  48.     // PCF
  49.     float shadow = 0.0;
  50.     vec2 texelSize = 1.0 / vec2(textureSize(shadowMap, 0));
  51.     for(int x = -1; x <= 1; ++x)
  52.     {
  53.         for(int y = -1; y <= 1; ++y)
  54.         {
  55.             float pcfDepth = texture(shadowMap, vec3(projCoords.xy + vec2(x, y) * texelSize, layer)).r;
  56.             shadow += (currentDepth - bias) > pcfDepth ? 1.0 : 0.0;        
  57.         }    
  58.     }
  59.     shadow /= 9.0;
  60.  
  61.     // keep the shadow at 0.0 when outside the far_plane region of the light's frustum.
  62.     if (projCoords.z > 1.0)
  63.     {
  64.         shadow = 0.0;
  65.     }
  66.        
  67.     return shadow;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement