Skip to content

Commit

Permalink
Added simple arithmatic operators to artist::colour and a test
Browse files Browse the repository at this point in the history
  • Loading branch information
bjnsock committed Mar 17, 2024
1 parent a810dfe commit cfc8047
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
25 changes: 25 additions & 0 deletions lib/include/artist/color.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -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
////////////////////////////////////////////////////////////////////////////
Expand Down
19 changes: 18 additions & 1 deletion test/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}

0 comments on commit cfc8047

Please sign in to comment.