64eb7821e941f2ae0ad203b6fb2f621559e2b40f
[mussa.git] / alg / color.cpp
1 #include "alg/color.hpp"
2 #include <math.h>
3
4 Color::Color() 
5 {
6   set(0.0, 0.0, 0.0, 0.0);
7 }
8
9 Color::Color(const Color &c)
10 {
11   set(c.colors[RedChannel], 
12       c.colors[GreenChannel], 
13       c.colors[BlueChannel], 
14       c.colors[AlphaChannel]);
15 }
16
17 Color::Color(float red, float green, float blue, float alpha)
18 {
19   set(red, green, blue, alpha);
20 }
21
22 void Color::set(float r, float g, float b, float a)
23 {
24   colors[RedChannel]   = r;
25   colors[GreenChannel] = g;
26   colors[BlueChannel]  = b;
27   colors[AlphaChannel] = a;
28 }
29
30 const float *const Color::get() const
31 {
32   return colors;
33 }
34
35 void Color::setR(float r)
36 {
37   colors[RedChannel]   = r;
38 }
39
40 float Color::r() const
41 {
42   return colors[RedChannel];
43 }
44
45 void Color::setG(float g)
46 {
47   colors[GreenChannel]   = g;
48 }
49
50 float Color::g() const
51 {
52   return colors[GreenChannel];
53 }
54
55 void Color::setB(float b)
56 {
57   colors[BlueChannel]   = b;
58 }
59
60 float Color::b() const
61 {
62   return colors[BlueChannel];
63 }
64
65 void Color::setA(float a)
66 {
67   colors[AlphaChannel]   = a;
68 }
69
70 float Color::a() const
71 {
72   return colors[AlphaChannel];
73 }
74
75 static bool close(float l, float r, float t=1e-6)
76 {
77   float difference = fabsf(l-r);
78   l = fabsf(l);
79   r = fabsf(r);
80    
81   return (difference <= (t*l) or difference <= (t*r));
82 }
83 bool operator==(const Color &x, const Color &y)
84 {
85   return (close(x.colors[Color::RedChannel]  ,y.colors[Color::RedChannel]) and
86          close(x.colors[Color::GreenChannel],y.colors[Color::GreenChannel]) and 
87          close(x.colors[Color::BlueChannel] ,y.colors[Color::BlueChannel]) and
88          close(x.colors[Color::AlphaChannel],y.colors[Color::AlphaChannel]));
89 }
90
91 std::ostream &operator<<(std::ostream &out, const Color &c)
92 {
93   out << c.r() << " " << c.g() << " " << c.b() << " " << c.a();
94   return out;
95 }