ShaderMaths.cginc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #ifndef SHADER_MATHS_INCLUDED
  2. #define SHADER_MATHS_INCLUDED
  3. #if defined(USE_LWRP)
  4. #include "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Core.hlsl"
  5. #elif defined(USE_URP)
  6. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
  7. #else
  8. #include "UnityCG.cginc"
  9. #endif
  10. ////////////////////////////////////////
  11. // Maths functions
  12. //
  13. inline half3 safeNormalize(half3 inVec)
  14. {
  15. half dp3 = max(0.001f, dot(inVec, inVec));
  16. return inVec * rsqrt(dp3);
  17. }
  18. inline float dotClamped(float3 a, float3 b)
  19. {
  20. #if (SHADER_TARGET < 30 || defined(SHADER_API_PS3))
  21. return saturate(dot(a, b));
  22. #else
  23. return max(0.0h, dot(a, b));
  24. #endif
  25. }
  26. inline float oneDividedBy(float value)
  27. {
  28. //Catches NANs
  29. float sign_value = sign(value);
  30. float sign_value_squared = sign_value*sign_value;
  31. return sign_value_squared / ( value + sign_value_squared - 1.0);
  32. }
  33. inline half pow5 (half x)
  34. {
  35. return x*x*x*x*x;
  36. }
  37. inline float4 quat_from_axis_angle(float3 axis, float angleRadians)
  38. {
  39. float4 qr;
  40. float half_angle = (angleRadians * 0.5);
  41. qr.x = axis.x * sin(half_angle);
  42. qr.y = axis.y * sin(half_angle);
  43. qr.z = axis.z * sin(half_angle);
  44. qr.w = cos(half_angle);
  45. return qr;
  46. }
  47. inline float3 rotate_vertex_position(float3 position, float3 axis, float angleRadians)
  48. {
  49. float4 q = quat_from_axis_angle(axis, angleRadians);
  50. float3 v = position.xyz;
  51. return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);
  52. }
  53. float3 EncodeFloatRGB(float value)
  54. {
  55. const float max24int = 256*256*256-1;
  56. float3 decomp = floor( value * float3( max24int/(256*256), max24int/256, max24int ) ) / 255.0;
  57. decomp.z -= decomp.y * 256.0;
  58. decomp.y -= decomp.x * 256.0;
  59. return decomp;
  60. }
  61. float DecodeFloatRGB(float3 decomp)
  62. {
  63. return dot( decomp.xyz, float3( 255.0/256, 255.0/(256*256), 255.0/(256*256*256) ) );
  64. }
  65. #endif // SHADER_MATHS_INCLUDED