cube_to_dp.glsl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #[vertex]
  2. #version 450
  3. #VERSION_DEFINES
  4. layout(push_constant, std430) uniform Params {
  5. float z_far;
  6. float z_near;
  7. vec2 texel_size;
  8. vec4 screen_rect;
  9. }
  10. params;
  11. layout(location = 0) out vec2 uv_interp;
  12. void main() {
  13. vec2 base_arr[4] = vec2[](vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(1.0, 0.0));
  14. uv_interp = base_arr[gl_VertexIndex];
  15. vec2 screen_pos = uv_interp * params.screen_rect.zw + params.screen_rect.xy;
  16. gl_Position = vec4(screen_pos * 2.0 - 1.0, 0.0, 1.0);
  17. }
  18. #[fragment]
  19. #version 450
  20. #VERSION_DEFINES
  21. layout(location = 0) in vec2 uv_interp;
  22. layout(set = 0, binding = 0) uniform samplerCube source_cube;
  23. layout(push_constant, std430) uniform Params {
  24. float z_far;
  25. float z_near;
  26. vec2 texel_size;
  27. vec4 screen_rect;
  28. }
  29. params;
  30. void main() {
  31. vec2 uv = uv_interp;
  32. vec2 texel_size = abs(params.texel_size);
  33. uv = clamp(uv * (1.0 + 2.0 * texel_size) - texel_size, vec2(0.0), vec2(1.0));
  34. vec3 normal = vec3(uv * 2.0 - 1.0, 0.0);
  35. normal.z = 0.5 * (1.0 - dot(normal.xy, normal.xy)); // z = 1/2 - 1/2 * (x^2 + y^2)
  36. normal = normalize(normal);
  37. normal.y = -normal.y; //needs to be flipped to match projection matrix
  38. if (params.texel_size.x >= 0.0) { // Sign is used to encode Z flip
  39. normal.z = -normal.z;
  40. }
  41. float depth = texture(source_cube, normal).r;
  42. // absolute values for direction cosines, bigger value equals closer to basis axis
  43. vec3 unorm = abs(normal);
  44. if ((unorm.x >= unorm.y) && (unorm.x >= unorm.z)) {
  45. // x code
  46. unorm = normal.x > 0.0 ? vec3(1.0, 0.0, 0.0) : vec3(-1.0, 0.0, 0.0);
  47. } else if ((unorm.y > unorm.x) && (unorm.y >= unorm.z)) {
  48. // y code
  49. unorm = normal.y > 0.0 ? vec3(0.0, 1.0, 0.0) : vec3(0.0, -1.0, 0.0);
  50. } else if ((unorm.z > unorm.x) && (unorm.z > unorm.y)) {
  51. // z code
  52. unorm = normal.z > 0.0 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 0.0, -1.0);
  53. } else {
  54. // oh-no we messed up code
  55. // has to be
  56. unorm = vec3(1.0, 0.0, 0.0);
  57. }
  58. float depth_fix = 1.0 / dot(normal, unorm);
  59. depth = 2.0 * depth - 1.0;
  60. float linear_depth = 2.0 * params.z_near * params.z_far / (params.z_far + params.z_near + depth * (params.z_far - params.z_near));
  61. // linear_depth equal to view space depth
  62. depth = (params.z_far - linear_depth * depth_fix) / params.z_far;
  63. gl_FragDepth = depth;
  64. }