gbuffer.glsl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. vec2 octahedron_wrap(const vec2 v) {
  2. return (1.0 - abs(v.yx)) * (vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0));
  3. }
  4. vec3 get_nor(const vec2 enc) {
  5. vec3 n;
  6. n.z = 1.0 - abs(enc.x) - abs(enc.y);
  7. n.xy = n.z >= 0.0 ? enc.xy : octahedron_wrap(enc.xy);
  8. n = normalize(n);
  9. return n;
  10. }
  11. vec3 get_pos_view(const vec3 view_ray, const float depth, const vec2 camera_proj) {
  12. float linear_depth = camera_proj.y / (camera_proj.x - depth);
  13. // float linear_depth = camera_proj.y / ((depth * 0.5 + 0.5) - camera_proj.x);
  14. return view_ray * linear_depth;
  15. }
  16. vec3 get_pos(const vec3 eye, const vec3 eye_look, const vec3 view_ray, const float depth, const vec2 camera_proj) {
  17. // eye_look, view_ray should be normalized
  18. float linear_depth = camera_proj.y / ((depth * 0.5 + 0.5) - camera_proj.x);
  19. float view_z_dist = dot(eye_look, view_ray);
  20. vec3 wposition = eye + view_ray * (linear_depth / view_z_dist);
  21. return wposition;
  22. }
  23. // GBuffer helper - Sebastien Lagarde
  24. // https://seblagarde.wordpress.com/2018/09/02/gbuffer-helper-packing-integer-and-float-together/
  25. float pack_f32_i16(const float f, const uint i) {
  26. // Constant optimize by compiler
  27. const int num_bit_target = 16;
  28. const int num_bit_i = 4;
  29. const float prec = float(1 << num_bit_target);
  30. const float maxi = float(1 << num_bit_i);
  31. const float prec_minus_one = prec - 1.0;
  32. const float t1 = ((prec / maxi) - 1.0) / prec_minus_one;
  33. const float t2 = (prec / maxi) / prec_minus_one;
  34. // Code
  35. return t1 * f + t2 * float(i);
  36. }
  37. void unpack_f32_i16(const float val, OUT(float, f), OUT(uint, i)) {
  38. // Constant optimize by compiler
  39. const int num_bit_target = 16;
  40. const int num_bit_i = 4;
  41. const float prec = float(1 << num_bit_target);
  42. const float maxi = float(1 << num_bit_i);
  43. const float prec_minus_one = prec - 1.0;
  44. const float t1 = ((prec / maxi) - 1.0) / prec_minus_one;
  45. const float t2 = (prec / maxi) / prec_minus_one;
  46. // Code
  47. // extract integer part
  48. // + rcp(prec_minus_one) to deal with precision issue
  49. i = uint((val / t2) + (1.0 / prec_minus_one));
  50. // Now that we have i, solve formula in pack_f32_i16 for f
  51. //f = (val - t2 * float(i)) / t1 => convert in mads form
  52. f = clamp((-t2 * float(i) + val) / t1, 0.0, 1.0); // Saturate in case of precision issue
  53. }