Pack.glsl 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2009-2015, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. /// Pack 3D normal to 2D vector
  6. /// See the clean code in comments in revision < r467
  7. vec2 packNormal(in vec3 normal)
  8. {
  9. const float SCALE = 1.7777;
  10. float scalar1 = (normal.z + 1.0) * (SCALE * 2.0);
  11. return normal.xy / scalar1 + 0.5;
  12. }
  13. /// Reverse the packNormal
  14. vec3 unpackNormal(in vec2 enc)
  15. {
  16. const float SCALE = 1.7777;
  17. vec2 nn = enc * (2.0 * SCALE) - SCALE;
  18. float g = 2.0 / (dot(nn.xy, nn.xy) + 1.0);
  19. vec3 normal;
  20. normal.xy = g * nn.xy;
  21. normal.z = g - 1.0;
  22. return normal;
  23. }
  24. #if GL_ES || __VERSION__ < 400
  25. // Vectorized version. See clean one at <= r1048
  26. uint packUnorm4x8(in vec4 v)
  27. {
  28. vec4 a = clamp(v, 0.0, 1.0) * 255.0;
  29. uvec4 b = uvec4(a) << uvec4(0U, 8U, 16U, 24U);
  30. uvec2 c = b.xy | b.zw;
  31. return c.x | c.y;
  32. }
  33. // Vectorized version. See clean one at <= r1048
  34. vec4 unpackUnorm4x8(in highp uint u)
  35. {
  36. uvec4 a = uvec4(u) >> uvec4(0U, 8U, 16U, 24U);
  37. uvec4 b = a & uvec4(0xFFU);
  38. vec4 c = vec4(b);
  39. return c * (1.0 / 255.0);
  40. }
  41. #endif
  42. // Populate the G buffer
  43. void writeGBuffer(
  44. in vec3 diffColor, in vec3 normal, in float specColor, in float specPower,
  45. out vec4 fai0, out vec4 fai1)
  46. {
  47. vec3 unorm = normal * 0.5 + 0.5;
  48. fai0 = vec4(diffColor, specPower);
  49. fai1 = vec4(unorm.xyz, specColor);
  50. }
  51. // Read from the G buffer
  52. void readGBuffer(
  53. in sampler2D fai0, in sampler2D fai1,
  54. in vec2 texCoord,
  55. out vec3 diffColor, out vec3 normal, out float specColor,
  56. out float specPower)
  57. {
  58. vec4 comp = textureRt(fai0, texCoord);
  59. diffColor = comp.rgb;
  60. specPower = comp.a;
  61. comp = textureRt(fai1, texCoord);
  62. normal = normalize(comp.xyz * 2.0 - 1.0);
  63. specColor = comp.a;
  64. }
  65. // Read only normal from G buffer
  66. void readNormalFromGBuffer(
  67. in sampler2D fai1,
  68. in vec2 texCoord,
  69. out vec3 normal)
  70. {
  71. normal = normalize(textureRt(fai1, texCoord).xyz * 2.0 - 1.0);
  72. }
  73. // Read only normal and specular color from G buffer
  74. void readNormalSpecularColorFromGBuffer(
  75. in sampler2D fai1,
  76. in vec2 texCoord,
  77. out vec3 normal,
  78. out float specColor)
  79. {
  80. vec4 comp = textureRt(fai1, texCoord);
  81. normal = normalize(comp.xyz * 2.0 - 1.0);
  82. specColor = comp.a;
  83. }