diff --git a/lib/include/artist/color.hpp b/lib/include/artist/color.hpp index 3f3fa4aa..f9fbf56b 100755 --- a/lib/include/artist/color.hpp +++ b/lib/include/artist/color.hpp @@ -34,6 +34,11 @@ namespace cycfi::artist constexpr bool operator==(color const& a, color const& b); constexpr bool operator!=(color const& a, color const& b); + constexpr color operator+(color const& a, color const& b); + constexpr color operator-(color const& a, color const& b); + constexpr color operator*(color const& a, float b); + constexpr color operator*(float a, color const& b); + //////////////////////////////////////////////////////////////////////////// // Inlines //////////////////////////////////////////////////////////////////////////// @@ -176,6 +181,26 @@ namespace cycfi::artist return r; } + constexpr color operator+(color const& a, color const& b) + { + return color(a.red + b.red, a.green + b.green, a.blue + b.blue, a.alpha + b.alpha*(1.0-a.alpha)); + } + + constexpr color operator-(color const& a, color const& b) + { + return color(a.red - b.red, a.green - b.green, a.blue - b.blue, a.alpha + b.alpha*(1.0-a.alpha)); + } + + constexpr color operator*(color const& a, float b) + { + return color(a.red * b, a.green * b, a.blue * b, a.alpha); + } + + constexpr color operator*(float a, color const& b) + { + return color(a * b.red, a * b.green, a * b.blue, b.alpha); + } + //////////////////////////////////////////////////////////////////////////// // Common colors //////////////////////////////////////////////////////////////////////////// diff --git a/test/main.cpp b/test/main.cpp index ca1870de..8db62175 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -986,4 +986,21 @@ TEST_CASE("Misc") } - +TEST_CASE("Color Maths") +{ + color a(0.2, 0.25, 0.5, 1.0); + color b(0.5, 0.6, 0.1, 1.0); + + auto check = [&](color result, color check) + { + REQUIRE_THAT(result.red, Catch::WithinRel(check.red, 0.001f)); + REQUIRE_THAT(result.green, Catch::WithinRel(check.green, 0.001f)); + REQUIRE_THAT(result.blue, Catch::WithinRel(check.blue, 0.001f)); + REQUIRE_THAT(result.alpha, Catch::WithinRel(check.alpha, 0.001f)); + }; + + check(a + b, color(0.7, 0.85, 0.6, 1.0)); + check(a - b, color(-0.3, -0.35, 0.4, 1.0)); + check(a * 2, color(0.4, 0.5, 1.0, 1.0)); + check(2 * a, color(0.4, 0.5, 1.0, 1.0)); +}