branchFreeTernary.glsl 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * Branchless ternary operator to be used when it's inexpensive to explicitly
  3. * evaluate both possibilities for a float expression.
  4. *
  5. * @name czm_branchFreeTernary
  6. * @glslFunction
  7. *
  8. * @param {bool} comparison A comparison statement
  9. * @param {float} a Value to return if the comparison is true.
  10. * @param {float} b Value to return if the comparison is false.
  11. *
  12. * @returns {float} equivalent of comparison ? a : b
  13. */
  14. float czm_branchFreeTernary(bool comparison, float a, float b) {
  15. float useA = float(comparison);
  16. return a * useA + b * (1.0 - useA);
  17. }
  18. /**
  19. * Branchless ternary operator to be used when it's inexpensive to explicitly
  20. * evaluate both possibilities for a vec2 expression.
  21. *
  22. * @name czm_branchFreeTernary
  23. * @glslFunction
  24. *
  25. * @param {bool} comparison A comparison statement
  26. * @param {vec2} a Value to return if the comparison is true.
  27. * @param {vec2} b Value to return if the comparison is false.
  28. *
  29. * @returns {vec2} equivalent of comparison ? a : b
  30. */
  31. vec2 czm_branchFreeTernary(bool comparison, vec2 a, vec2 b) {
  32. float useA = float(comparison);
  33. return a * useA + b * (1.0 - useA);
  34. }
  35. /**
  36. * Branchless ternary operator to be used when it's inexpensive to explicitly
  37. * evaluate both possibilities for a vec3 expression.
  38. *
  39. * @name czm_branchFreeTernary
  40. * @glslFunction
  41. *
  42. * @param {bool} comparison A comparison statement
  43. * @param {vec3} a Value to return if the comparison is true.
  44. * @param {vec3} b Value to return if the comparison is false.
  45. *
  46. * @returns {vec3} equivalent of comparison ? a : b
  47. */
  48. vec3 czm_branchFreeTernary(bool comparison, vec3 a, vec3 b) {
  49. float useA = float(comparison);
  50. return a * useA + b * (1.0 - useA);
  51. }
  52. /**
  53. * Branchless ternary operator to be used when it's inexpensive to explicitly
  54. * evaluate both possibilities for a vec4 expression.
  55. *
  56. * @name czm_branchFreeTernary
  57. * @glslFunction
  58. *
  59. * @param {bool} comparison A comparison statement
  60. * @param {vec3} a Value to return if the comparison is true.
  61. * @param {vec3} b Value to return if the comparison is false.
  62. *
  63. * @returns {vec3} equivalent of comparison ? a : b
  64. */
  65. vec4 czm_branchFreeTernary(bool comparison, vec4 a, vec4 b) {
  66. float useA = float(comparison);
  67. return a * useA + b * (1.0 - useA);
  68. }