color_ramp.h
1 /*
2  * color_ramp.h
3  */
4 
5 #ifndef SCENE_RESOURCES_COLOR_RAMP_H_
6 #define SCENE_RESOURCES_COLOR_RAMP_H_
7 
8 #include "resource.h"
9 
10 class ColorRamp: public Resource {
11  OBJ_TYPE( ColorRamp, Resource );
12  OBJ_SAVE_TYPE( ColorRamp );
13 
14 public:
15  struct Point {
16 
17  float offset;
18  Color color;
19  bool operator<(const Point& p_ponit) const {
20  return offset<p_ponit.offset;
21  }
22  };
23 
24 private:
25  Vector<Point> points;
26  bool is_sorted;
27 
28 protected:
29  static void _bind_methods();
30 
31 public:
32  ColorRamp();
33  virtual ~ColorRamp();
34 
35  void add_point(float p_offset, const Color& p_color);
36  void remove_point(int p_index);
37 
38  void set_points(Vector<Point>& points);
39  Vector<Point>& get_points();
40 
41  void set_offset(int pos, const float offset);
42  float get_offset(int pos) const;
43 
44  void set_color(int pos, const Color& color);
45  Color get_color(int pos) const;
46 
47  void set_offsets(const Vector<float>& offsets);
48  Vector<float> get_offsets() const;
49 
50  void set_colors(const Vector<Color>& colors);
51  Vector<Color> get_colors() const;
52 
53  _FORCE_INLINE_ Color get_color_at_offset(float p_offset) {
54 
55  if (points.empty())
56  return Color(0,0,0,1);
57 
58  if(!is_sorted)
59  {
60  points.sort();
61  is_sorted = true;
62  }
63 
64  //binary search
65  int low = 0;
66  int high = points.size() -1;
67  int middle;
68 
69  while( low <= high )
70  {
71  middle = ( low + high ) / 2;
72  Point& point = points[middle];
73  if( point.offset > p_offset ) {
74  high = middle - 1; //search low end of array
75  } else if ( point.offset < p_offset) {
76  low = middle + 1; //search high end of array
77  } else {
78  return point.color;
79  }
80  }
81 
82  //return interpolated value
83  if (points[middle].offset>p_offset)
84  {
85  middle--;
86  }
87  int first=middle;
88  int second=middle+1;
89  if(second>=points.size())
90  return points[points.size()-1].color;
91  if(first<0)
92  return points[0].color;
93  Point& pointFirst = points[first];
94  Point& pointSecond = points[second];
95  return pointFirst.color.linear_interpolate(pointSecond.color, (p_offset-pointFirst.offset)/(pointSecond.offset - pointFirst.offset));
96  }
97 
98  int get_points_count() const;
99 };
100 
101 #endif /* SCENE_RESOURCES_COLOR_RAMP_H_ */
Definition: color.h:37
Definition: resource.h:89
Definition: color_ramp.h:15
Definition: color_ramp.h:10