No Description

deferred.frag 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #version 450
  2. #extension GL_ARB_separate_shader_objects : enable
  3. #extension GL_ARB_shading_language_420pack : enable
  4. layout (binding = 1) uniform sampler2DMS samplerPosition;
  5. layout (binding = 2) uniform sampler2DMS samplerNormal;
  6. layout (binding = 3) uniform sampler2DMS samplerAlbedo;
  7. layout (location = 0) in vec2 inUV;
  8. layout (location = 0) out vec4 outFragcolor;
  9. struct Light {
  10. vec4 position;
  11. vec3 color;
  12. float radius;
  13. };
  14. layout (binding = 4) uniform UBO
  15. {
  16. Light lights[6];
  17. vec4 viewPos;
  18. ivec2 windowSize;
  19. } ubo;
  20. layout (constant_id = 0) const int NUM_SAMPLES = 8;
  21. #define NUM_LIGHTS 6
  22. // Manual resolve for MSAA samples
  23. vec4 resolve(sampler2DMS tex, ivec2 uv)
  24. {
  25. vec4 result = vec4(0.0);
  26. for (int i = 0; i < NUM_SAMPLES; i++)
  27. {
  28. vec4 val = texelFetch(tex, uv, i);
  29. result += val;
  30. }
  31. // Average resolved samples
  32. return result / float(NUM_SAMPLES);
  33. }
  34. vec3 calculateLighting(vec3 pos, vec3 normal, vec4 albedo)
  35. {
  36. vec3 result = vec3(0.0);
  37. for(int i = 0; i < NUM_LIGHTS; ++i)
  38. {
  39. // Vector to light
  40. vec3 L = ubo.lights[i].position.xyz - pos;
  41. // Distance from light to fragment position
  42. float dist = length(L);
  43. // Viewer to fragment
  44. vec3 V = ubo.viewPos.xyz - pos;
  45. V = normalize(V);
  46. // Light to fragment
  47. L = normalize(L);
  48. // Attenuation
  49. float atten = ubo.lights[i].radius / (pow(dist, 2.0) + 1.0);
  50. // Diffuse part
  51. vec3 N = normalize(normal);
  52. float NdotL = max(0.0, dot(N, L));
  53. vec3 diff = ubo.lights[i].color * albedo.rgb * NdotL * atten;
  54. // Specular part
  55. vec3 R = reflect(-L, N);
  56. float NdotR = max(0.0, dot(R, V));
  57. vec3 spec = ubo.lights[i].color * albedo.a * pow(NdotR, 8.0) * atten;
  58. result += diff + spec;
  59. }
  60. return result;
  61. }
  62. void main()
  63. {
  64. ivec2 attDim = textureSize(samplerPosition);
  65. ivec2 UV = ivec2(inUV * attDim);
  66. #define ambient 0.15
  67. // Ambient part
  68. vec4 alb = resolve(samplerAlbedo, UV);
  69. vec3 fragColor = vec3(0.0);
  70. // Calualte lighting for every MSAA sample
  71. for (int i = 0; i < NUM_SAMPLES; i++)
  72. {
  73. vec3 pos = texelFetch(samplerPosition, UV, i).rgb;
  74. vec3 normal = texelFetch(samplerNormal, UV, i).rgb;
  75. vec4 albedo = texelFetch(samplerAlbedo, UV, i);
  76. fragColor += calculateLighting(pos, normal, albedo);
  77. }
  78. fragColor = (alb.rgb * ambient) + fragColor / float(NUM_SAMPLES);
  79. outFragcolor = vec4(fragColor, 1.0);
  80. }