You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
1.8KB

  1. #include <color.hpp>
  2. #include <math.hpp>
  3. namespace rack {
  4. namespace color {
  5. bool isEqual(NVGcolor a, NVGcolor b) {
  6. for (int i = 0; i < 4; i++) {
  7. if (a.rgba[i] != b.rgba[i])
  8. return false;
  9. }
  10. return true;
  11. }
  12. NVGcolor clamp(NVGcolor a) {
  13. for (int i = 0; i < 4; i++)
  14. a.rgba[i] = math::clamp(a.rgba[i], 0.f, 1.f);
  15. return a;
  16. }
  17. NVGcolor minus(NVGcolor a, NVGcolor b) {
  18. for (int i = 0; i < 3; i++)
  19. a.rgba[i] -= b.rgba[i];
  20. return a;
  21. }
  22. NVGcolor plus(NVGcolor a, NVGcolor b) {
  23. for (int i = 0; i < 3; i++)
  24. a.rgba[i] += b.rgba[i];
  25. return a;
  26. }
  27. NVGcolor mult(NVGcolor a, NVGcolor b) {
  28. for (int i = 0; i < 3; i++)
  29. a.rgba[i] *= b.rgba[i];
  30. return a;
  31. }
  32. NVGcolor mult(NVGcolor a, float x) {
  33. for (int i = 0; i < 3; i++)
  34. a.rgba[i] *= x;
  35. return a;
  36. }
  37. NVGcolor lerp(NVGcolor a, NVGcolor b, float t) {
  38. NVGcolor c;
  39. for (int i = 0; i < 4; i++)
  40. c.rgba[i] = a.rgba[i] * (1 - t) + b.rgba[i] * t;
  41. return c;
  42. }
  43. NVGcolor screen(NVGcolor a, NVGcolor b) {
  44. if (a.a == 0.f)
  45. return b;
  46. if (b.a == 0.f)
  47. return a;
  48. a = mult(a, a.a);
  49. b = mult(b, b.a);
  50. NVGcolor c = minus(plus(a, b), mult(a, b));
  51. c.a = a.a + b.a - a.a * b.a;
  52. c = mult(c, 1.f / c.a);
  53. c = clamp(c);
  54. return c;
  55. }
  56. NVGcolor alpha(NVGcolor a, float alpha) {
  57. a.a *= alpha;
  58. return a;
  59. }
  60. NVGcolor fromHexString(std::string s) {
  61. uint8_t r = 0;
  62. uint8_t g = 0;
  63. uint8_t b = 0;
  64. uint8_t a = 255;
  65. // If only three hex pairs are given, this will leave `a` unset.
  66. sscanf(s.c_str(), "#%2hhx%2hhx%2hhx%2hhx", &r, &g, &b, &a);
  67. return nvgRGBA(r, g, b, a);
  68. }
  69. std::string toHexString(NVGcolor c) {
  70. uint8_t r = std::round(c.r * 255);
  71. uint8_t g = std::round(c.g * 255);
  72. uint8_t b = std::round(c.b * 255);
  73. uint8_t a = std::round(c.a * 255);
  74. if (a == 255)
  75. return string::f("#%02x%02x%02x", r, g, b);
  76. else
  77. return string::f("#%02x%02x%02x%02x", r, g, b, a);
  78. }
  79. } // namespace network
  80. } // namespace rack