sunlightshadow.frag 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. uniform sampler2D ntex;
  2. uniform sampler2D dtex;
  3. uniform sampler2DArrayShadow shadowtex;
  4. uniform float split0;
  5. uniform float split1;
  6. uniform float split2;
  7. uniform float splitmax;
  8. uniform float shadow_res;
  9. in vec2 uv;
  10. out vec4 Diff;
  11. out vec4 Spec;
  12. vec3 DecodeNormal(vec2 n);
  13. vec3 SpecularBRDF(vec3 normal, vec3 eyedir, vec3 lightdir, vec3 color, float roughness);
  14. vec3 DiffuseBRDF(vec3 normal, vec3 eyedir, vec3 lightdir, vec3 color, float roughness);
  15. vec4 getPosFromUVDepth(vec3 uvDepth, mat4 InverseProjectionMatrix);
  16. vec3 SunMRP(vec3 normal, vec3 eyedir);
  17. float getShadowFactor(vec3 pos, int index)
  18. {
  19. vec4 shadowcoord = (ShadowViewProjMatrixes[index] * InverseViewMatrix * vec4(pos, 1.0));
  20. shadowcoord.xy /= shadowcoord.w;
  21. vec2 shadowtexcoord = shadowcoord.xy * 0.5 + 0.5;
  22. float d = .5 * shadowcoord.z + .5;
  23. float result = 0.;
  24. for (float i = -1.; i <= 1.; i += 1.)
  25. {
  26. for (float j = -1.; j <= 1.; j += 1.)
  27. result += texture(shadowtex, vec4(shadowtexcoord + vec2(i,j) / shadow_res, float(index), d));
  28. }
  29. return result / 9.;
  30. }
  31. void main() {
  32. vec2 uv = gl_FragCoord.xy / screen;
  33. float z = texture(dtex, uv).x;
  34. vec4 xpos = getPosFromUVDepth(vec3(uv, z), InverseProjectionMatrix);
  35. vec3 norm = normalize(DecodeNormal(2. * texture(ntex, uv).xy - 1.));
  36. float roughness =texture(ntex, uv).z;
  37. vec3 eyedir = -normalize(xpos.xyz);
  38. vec3 Lightdir = SunMRP(norm, eyedir);
  39. float NdotL = clamp(dot(norm, Lightdir), 0., 1.);
  40. vec3 Specular = SpecularBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
  41. vec3 Diffuse = DiffuseBRDF(norm, eyedir, Lightdir, vec3(1.), roughness);
  42. // Shadows
  43. float factor;
  44. if (xpos.z < split0)
  45. factor = getShadowFactor(xpos.xyz, 0);
  46. else if (xpos.z < split1)
  47. factor = getShadowFactor(xpos.xyz, 1);
  48. else if (xpos.z < split2)
  49. factor = getShadowFactor(xpos.xyz, 2);
  50. else if (xpos.z < splitmax)
  51. factor = getShadowFactor(xpos.xyz, 3);
  52. else
  53. factor = 1.;
  54. Diff = vec4(factor * NdotL * Diffuse * sun_col, 1.);
  55. Spec = vec4(factor * NdotL * Specular * sun_col, 1.);
  56. }