libvisual  0.5.0
lv_palette.cpp
1 /* Libvisual - The audio visualisation framework.
2  *
3  * Copyright (C) 2012 Libvisual team
4  * 2004-2006 Dennis Smit
5  *
6  * Authors: Chong Kai Xiong <kaixiong@codeleft.sg>
7  * Dennis Smit <ds@nerds-incorporated.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU Lesser General Public License as
11  * published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22  */
23 
24 #include "config.h"
25 #include "lv_palette.h"
26 #include "lv_common.h"
27 
28 namespace LV {
29 
30  Palette::Palette (unsigned int ncolors)
31  : colors (ncolors)
32  {
33  // empty
34  }
35 
36  Palette::~Palette ()
37  {
38  // empty
39  }
40 
41  void Palette::allocate_colors (unsigned int ncolors)
42  {
43  colors.resize (ncolors);
44  }
45 
46  void Palette::blend (Palette const& src1, Palette const& src2, float rate)
47  {
48  visual_return_if_fail (src1.size () != src2.size ());
49  visual_return_if_fail (size () != src1.size ());
50 
51  for (unsigned int i = 0; i < colors.size (); i++) {
52  colors[i].r = src1.colors[i].r + ((src2.colors[i].r - src1.colors[i].r) * rate);
53  colors[i].g = src1.colors[i].g + ((src2.colors[i].g - src1.colors[i].g) * rate);
54  colors[i].b = src1.colors[i].b + ((src2.colors[i].b - src1.colors[i].b) * rate);
55  }
56  }
57 
58  VisColor Palette::color_cycle (float rate)
59  {
60  int irate = int (rate);
61 
62  float rdiff = rate - irate;
63 
64  // If rate is exactly an item, return that item
65  if (rdiff == 0) {
66  return colors[irate];
67  }
68 
69  irate %= colors.size ();
70 
71  uint8_t alpha = rdiff * 255;
72 
73  auto const tmp1 = &colors[irate];
74  Color const* tmp2;
75 
76  if (irate == int (size() - 1))
77  tmp2 = &colors[0];
78  else
79  tmp2 = &colors[irate + 1];
80 
81  return Color ((alpha * (tmp1->r - tmp2->r) >> 8) + tmp2->r,
82  (alpha * (tmp1->g - tmp2->g) >> 8) + tmp2->g,
83  (alpha * (tmp1->b - tmp2->b) >> 8) + tmp2->b);
84  }
85 
86  int Palette::find_color (Color const& color) const
87  {
88  for (unsigned int i = 0; i < colors.size(); i++) {
89  if (colors[i] == color)
90  return i;
91  }
92 
93  return -1;
94  }
95 
96 } // LV namespace
97 
98