ssao.vs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #START VS
  2. #version 330 core
  3. layout (location = 0) in vec2 in_position;
  4. layout (location = 1) in vec2 in_uv;
  5. out vec2 uv;
  6. void main()
  7. {
  8. uv = in_uv;
  9. gl_Position = vec4(in_position.x, in_position.y, 0.0, 1.0);
  10. }
  11. #END VS
  12. #START FS
  13. #version 330 core
  14. in vec2 uv;
  15. out float frag_color;
  16. uniform sampler2D u_gposition;
  17. uniform sampler2D u_gnormal;
  18. uniform sampler2D u_noise;
  19. uniform vec3 u_samples[32];
  20. uniform mat4 u_projection;
  21. uniform mat4 u_view;
  22. uniform vec2 u_screensize;
  23. int kernel_size = 32;
  24. float radius = 0.8;
  25. float bias = 0.2;
  26. void main()
  27. {
  28. vec2 noise_scale = vec2(u_screensize.x/4.0, u_screensize.y/4.0);
  29. // ssao input
  30. vec3 fragpos = texture(u_gposition, uv).xyz;
  31. vec3 normal = normalize(texture(u_gnormal, uv).rgb);
  32. vec3 randomvec = normalize(texture(u_noise, uv * noise_scale).xyz);
  33. // generate TBN
  34. vec3 tangent = normalize(randomvec - normal * dot(randomvec, normal));
  35. vec3 bitangent = cross(normal, tangent);
  36. mat3 TBN = mat3(tangent, bitangent, normal);
  37. // calculate occlusion factor
  38. float occlusion = 0.0;
  39. for (int i=0; i<kernel_size; i++) {
  40. // convert from tangent to view space
  41. vec3 sample = TBN * u_samples[i];
  42. // get sample pos
  43. sample = fragpos + sample * radius;
  44. vec4 offset = vec4(sample, 1.0);
  45. offset = u_projection * offset;
  46. offset.xyz /= offset.w;
  47. offset.xyz = offset.xyz * 0.5 + 0.5;
  48. float sampledepth = texture(u_gposition, offset.xy).z;
  49. float rangecheck = smoothstep(0.0, 1.0, radius / abs(fragpos.z - sampledepth));
  50. occlusion += (sampledepth >= sample.z + bias ? 1.0 : 0.0) * rangecheck;
  51. }
  52. occlusion = 1.0 - (occlusion / kernel_size);
  53. frag_color = pow(occlusion, 1.0);
  54. }
  55. #END FS