WhiteBalanceNode.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System.Reflection;
  2. using UnityEngine;
  3. namespace UnityEditor.ShaderGraph
  4. {
  5. [Title("Artistic", "Adjustment", "White Balance")]
  6. class WhiteBalanceNode : CodeFunctionNode
  7. {
  8. public WhiteBalanceNode()
  9. {
  10. name = "White Balance";
  11. }
  12. protected override MethodInfo GetFunctionToConvert()
  13. {
  14. return GetType().GetMethod("Unity_WhiteBalance", BindingFlags.Static | BindingFlags.NonPublic);
  15. }
  16. static string Unity_WhiteBalance(
  17. [Slot(0, Binding.None)] Vector3 In,
  18. [Slot(1, Binding.None)] Vector1 Temperature,
  19. [Slot(2, Binding.None)] Vector1 Tint,
  20. [Slot(3, Binding.None)] out Vector3 Out)
  21. {
  22. Out = Vector3.zero;
  23. return @"
  24. {
  25. // Range ~[-1.67;1.67] works best
  26. $precision t1 = Temperature * 10 / 6;
  27. $precision t2 = Tint * 10 / 6;
  28. // Get the CIE xy chromaticity of the reference white point.
  29. // Note: 0.31271 = x value on the D65 white point
  30. $precision x = 0.31271 - t1 * (t1 < 0 ? 0.1 : 0.05);
  31. $precision standardIlluminantY = 2.87 * x - 3 * x * x - 0.27509507;
  32. $precision y = standardIlluminantY + t2 * 0.05;
  33. // Calculate the coefficients in the LMS space.
  34. $precision3 w1 = $precision3(0.949237, 1.03542, 1.08728); // D65 white point
  35. // CIExyToLMS
  36. $precision Y = 1;
  37. $precision X = Y * x / y;
  38. $precision Z = Y * (1 - x - y) / y;
  39. $precision L = 0.7328 * X + 0.4296 * Y - 0.1624 * Z;
  40. $precision M = -0.7036 * X + 1.6975 * Y + 0.0061 * Z;
  41. $precision S = 0.0030 * X + 0.0136 * Y + 0.9834 * Z;
  42. $precision3 w2 = $precision3(L, M, S);
  43. $precision3 balance = $precision3(w1.x / w2.x, w1.y / w2.y, w1.z / w2.z);
  44. $precision3x3 LIN_2_LMS_MAT = {
  45. 3.90405e-1, 5.49941e-1, 8.92632e-3,
  46. 7.08416e-2, 9.63172e-1, 1.35775e-3,
  47. 2.31082e-2, 1.28021e-1, 9.36245e-1
  48. };
  49. $precision3x3 LMS_2_LIN_MAT = {
  50. 2.85847e+0, -1.62879e+0, -2.48910e-2,
  51. -2.10182e-1, 1.15820e+0, 3.24281e-4,
  52. -4.18120e-2, -1.18169e-1, 1.06867e+0
  53. };
  54. $precision3 lms = mul(LIN_2_LMS_MAT, In);
  55. lms *= balance;
  56. Out = mul(LMS_2_LIN_MAT, lms);
  57. }
  58. ";
  59. }
  60. }
  61. }