math.glsl 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* math.glsl -- Contains everything you need for maths
  2. *
  3. * Copyright (c) 2025 Le Juez Victor
  4. *
  5. * This software is provided 'as-is', without any express or implied warranty.
  6. * For conditions of distribution and use, see accompanying LICENSE file.
  7. */
  8. /* === Constants === */
  9. #define M_PI 3.1415926535897931
  10. #define M_TAU 6.2831853071795862
  11. #define M_INV_PI 0.3183098861837907
  12. /* === Functions === */
  13. vec3 M_Rotate3D(vec3 v, vec4 q)
  14. {
  15. vec3 t = 2.0 * cross(q.xyz, v);
  16. return v + q.w * t + cross(q.xyz, t);
  17. }
  18. mat3 M_OrthonormalBasis(vec3 n)
  19. {
  20. // Previously we used Frisvad's method to generate a stable orthonormal basis
  21. // SEE: https://backend.orbit.dtu.dk/ws/portalfiles/portal/126824972/onb_frisvad_jgt2012_v2.pdf
  22. // However, it can cause visible artifacts (eg. bright pixels on the -Z face of irradiance cubemaps)
  23. // So now we use the revised method by Duff et al., it's more accurate, though slightly slower
  24. // SEE: https://graphics.pixar.com/library/OrthonormalB/paper.pdf
  25. float sgn = n.z >= 0.0 ? 1.0 : -1.0;
  26. float a = -1.0 / (sgn + n.z);
  27. float b = n.x * n.y * a;
  28. vec3 t = vec3(1.0 + sgn * n.x * n.x * a, sgn * b, -sgn * n.x);
  29. vec3 bt = vec3(b, sgn + n.y * n.y * a, -n.y);
  30. return mat3(t, bt, n);
  31. }
  32. vec2 M_OctahedronWrap(vec2 val)
  33. {
  34. // Reference(s):
  35. // - Octahedron normal vector encoding
  36. // https://web.archive.org/web/20191027010600/https://knarkowicz.wordpress.com/2014/04/16/octahedron-normal-vector-encoding/comment-page-1/
  37. return (1.0 - abs(val.yx)) * mix(vec2(-1.0), vec2(1.0), vec2(greaterThanEqual(val.xy, vec2(0.0))));
  38. }
  39. vec3 M_DecodeOctahedral(vec2 encoded)
  40. {
  41. encoded = encoded * 2.0 - 1.0;
  42. vec3 normal;
  43. normal.z = 1.0 - abs(encoded.x) - abs(encoded.y);
  44. normal.xy = normal.z >= 0.0 ? encoded.xy : M_OctahedronWrap(encoded.xy);
  45. return normalize(normal);
  46. }
  47. vec2 M_EncodeOctahedral(vec3 normal)
  48. {
  49. normal /= abs(normal.x) + abs(normal.y) + abs(normal.z);
  50. normal.xy = normal.z >= 0.0 ? normal.xy : M_OctahedronWrap(normal.xy);
  51. normal.xy = normal.xy * 0.5 + 0.5;
  52. return normal.xy;
  53. }
  54. vec3 M_NormalScale(vec3 normal, float scale)
  55. {
  56. normal.xy *= scale;
  57. normal.z = sqrt(1.0 - clamp(dot(normal.xy, normal.xy), 0.0, 1.0));
  58. return normal;
  59. }
  60. float M_HashIGN(vec2 pos)
  61. {
  62. // http://www.iryoku.com/next-generation-post-processing-in-call-of-duty-advanced-warfare
  63. const vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189);
  64. return fract(magic.z * fract(dot(pos, magic.xy)));
  65. }