Fix 1684240: Several places were multiplying the A component of the color by itself...
[synfig.git] / synfig-core / trunk / src / synfig / gradient.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file gradient.cpp
3 **      \brief Color Gradient Class Member Definitions
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 */
21 /* ========================================================================= */
22
23 /* === H E A D E R S ======================================================= */
24
25 #ifdef USING_PCH
26 #       include "pch.h"
27 #else
28 #ifdef HAVE_CONFIG_H
29 #       include <config.h>
30 #endif
31
32 #include "gradient.h"
33 #include "general.h"
34 #include <stdexcept>
35 #include "exception.h"
36
37 #include <ETL/misc>
38 #endif
39
40 /* === U S I N G =========================================================== */
41
42 using namespace std;
43 using namespace etl;
44 using namespace synfig;
45
46 /* === M A C R O S ========================================================= */
47
48 /* === G L O B A L S ======================================================= */
49
50 /* === P R O C E D U R E S ================================================= */
51
52 /* === M E T H O D S ======================================================= */
53
54 synfig::Gradient::Gradient(const Color &c1, const Color &c2)
55 {
56         push_back(CPoint(0.0,c1));
57         push_back(CPoint(1.0,c2));
58 }
59
60 synfig::Gradient::Gradient(const Color &c1, const Color &c2, const Color &c3)
61 {
62         push_back(CPoint(0.0,c1));
63         push_back(CPoint(0.5,c2));
64         push_back(CPoint(1.0,c3));
65 }
66
67 // This sort algorithm MUST be stable
68 // ie: it must not change the order of items with the same value.
69 // I am using a bubble sort.
70 // This algorithm will sort a nearly-sorted list at ~O(N), and
71 // it will sort an inverse sorted list at ~O(N*N).
72 void
73 synfig::Gradient::sort()
74 {
75         stable_sort(begin(),end());
76         /*
77         iterator iter;
78         iterator iter2,next;
79
80         for(iter=begin();iter!=end();iter++)
81         {
82                 for(next=iter, iter2=next--;iter2!=begin();iter2=next--)
83                 {
84                         if(*iter<*next)
85                         {
86                                 //insert(next,*iter);
87                                 //erase(iter);
88                                 iter_swap(next,iter);
89
90                                 continue;
91                         }
92                         else
93                                 break;
94                 }
95         }
96         */
97 }
98
99 static synfig::ColorAccumulator
100 supersample_helper(const synfig::Gradient::CPoint &color1, const synfig::Gradient::CPoint &color2, float begin, float end, float &weight)
101 {
102         if(color1.pos==color2.pos || color1.pos>=end || color2.pos<=begin)
103         {
104                 weight=0;
105                 return Color::alpha();
106         }
107         if(color1.pos>=begin && color2.pos<end)
108         {
109                 weight=color2.pos-color1.pos;
110                 ColorAccumulator ret=Color::blend(color2.color,color1.color, 0.5, Color::BLEND_STRAIGHT).premult_alpha()*weight;
111                 return ret;
112         }
113         if(color1.pos>=begin && color2.pos>=end)
114         {
115                 weight=end-color1.pos;
116                 float pos((end+color1.pos)*0.5);
117                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
118                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
119                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
120                 return ret;
121         }
122         if(color1.pos<begin && color2.pos<end)
123         {
124                 weight=color2.pos-begin;
125                 float pos((begin+color2.pos)*0.5);
126                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
127                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
128                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
129                 return ret;
130         }
131         synfig::error("color1.pos=%f",color1.pos);
132         synfig::error("color2.pos=%f",color2.pos);
133         synfig::error("begin=%f",begin);
134         synfig::error("end=%f",end);
135
136         weight=0;
137         return Color::alpha();
138
139 //      assert(0);
140 }
141
142 Color
143 synfig::Gradient::operator()(const Real &x,float supersample)const
144 {
145         if(empty())
146                 return Color(0,0,0,0);
147         if(supersample<0)
148                 supersample=-supersample;
149         if(supersample>2.0)
150                 supersample=2.0f;
151
152         float begin_sample(x-supersample*0.5);
153         float end_sample(x+supersample*0.5);
154
155         if(size()==1 || end_sample<=front().pos || isnan(x))
156                 return front().color;
157
158         if(begin_sample>=back().pos)
159                 return back().color;
160
161         /*
162         if(end_sample>=back().pos)
163                 end_sample=back().pos;
164
165         if(begin_sample<=front().pos)
166                 begin_sample=front().pos;
167         */
168
169         const_iterator iter,next;
170
171         /*
172         //optimizize...
173         Real    left = x-supersample/2, right = x+supersample/2;
174
175         if(left < front().pos) left = front().pos;
176         if(right > back().pos) right = back().pos;
177
178         //find using binary search...
179         const_iterator iterl,iterr;
180
181         //the binary search should give us the values BEFORE the point we're looking for...
182         iterl = binary_find(begin(),end(),left);
183         iterr = binary_find(iterl,end(),right);
184
185         //now integrate over the range of left to right...
186
187         if(iterl == iterr)
188         {
189                 iterr++; //let's look at the next one shall we :)
190
191                 //interpolate neighboring colors
192                 const Real one = iterr->pos - iterl->pos;
193                 const Real lambda = (x - iterl->pos)/one;
194
195                 //(1-l)iterl + (l)iterr
196                 return iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
197
198                 //return Color::blend(iterr->color,iterl->color,lambda,Color::BLEND_STRAIGHT);
199         }else
200         {
201                 //itegration madness
202                 const_iterator i = iterl, ie = iterr+1;
203                 Real wlast = left;
204
205                 ColorAccumulator clast,cwork;
206                 {
207                         const Real lambda = (x - iterl->pos)/(iterr->pos - iterl->pos);
208
209                         //premultiply because that's the form in which we can combine things...
210                         clast = iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
211                         //Color::blend((i+1)->color,i->color,(left - i->pos)/((i+1)->pos - i->pos),Color::BLEND_STRAIGHT);
212                 }
213
214                 ColorAccumulator        accum = 0;
215
216                 //loop through all the trapezoids and integrate them as we go...
217                 //      area of trap = (yi + yi1)*(xi1 - xi)
218                 //      yi = clast, xi = wlast, yi1 = i->color, xi1 = i->pos
219
220                 for(;i<=iterr; wlast=i->pos,clast=i->color.premult_alpha(),++i)
221                 {
222                         const Real diff = i->pos - wlast;
223                         if(diff > 0) //only accumulate if there will be area to add
224                         {
225                                 cwork = i->color.premult_alpha();
226                                 accum += (cwork + clast)*diff;
227                         }
228                 }
229
230                 {
231                         const_iterator ibef = i-1;
232                         const Real diff = right - ibef->pos;
233
234                         if(diff > 0)
235                         {
236                                 const Real lambda = diff/(i->pos - ibef->pos);
237                                 cwork = ibef->color.premult_alpha()*(1-lambda) + i->color.premult_alpha()*lambda;
238
239                                 accum += (cwork + clast)*diff; //can probably optimize this more... but it's not too bad
240                         }
241                 }
242
243                 accum /= supersample; //should be the total area it was sampled over...
244                 return accum.demult_alpha();
245         }*/
246
247         next=begin(),iter=next++;
248
249         //add for optimization
250         next = binary_find(begin(),end(),(Real)begin_sample);
251         iter = next++;
252
253         //! As a future optimization, this could be performed faster
254         //! using a binary search.
255         for(;iter<end();iter=next++)
256         {
257                 if(next==end() || x>=iter->pos &&  x<next->pos && iter->pos!=next->pos)
258                 {
259                         // If the supersample region falls square in between
260                         // two CPoints, then we don't have to do anything special.
261                         if(next!=end() && (!supersample || (iter->pos<=begin_sample && next->pos>=end_sample)))
262                         {
263                                 const Real dist(next->pos-iter->pos);
264                                 const Real pos(x-iter->pos);
265                                 const Real amount(pos/dist);
266                                 return Color::blend(next->color,iter->color, amount, Color::BLEND_STRAIGHT);
267                         }
268                         // In this case our supersample region extends over one or more
269                         // CPoints. So, we need to calculate our coverage amount.
270                         ColorAccumulator pool(Color::alpha());
271                         float divisor(0.0),weight(0);
272
273                         const_iterator iter2,next2;
274                         iter2=iter;
275                         if(iter==begin() && iter->pos>x)
276                         {
277                                 weight=x-iter->pos;
278                                 //weight*=iter->color.get_a();
279                                 pool+=ColorAccumulator(iter->color).premult_alpha()*weight;
280                                 divisor+=weight;
281                         }
282                         else
283                         {
284                                 while(iter2->pos>=begin_sample)
285                                 {
286                                         if(iter2==begin())
287                                         {
288                                                 weight=iter2->pos-(begin_sample);
289                                                 //weight*=iter2->color.get_a();
290                                                 pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
291                                                 divisor+=weight;
292                                                 break;
293                                         }
294                                         next2=iter2--;
295                                         pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
296                                         divisor+=weight;
297                                 }
298                         }
299
300                         next2=iter;
301                         iter2=next2++;
302                         while(iter2->pos<=end_sample)
303                         {
304                                 if(next2==end())
305                                 {
306                                         weight=(end_sample)-iter2->pos;
307                                         pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
308                                         divisor+=weight;
309                                         break;
310                                 }
311                                 pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
312                                 divisor+=weight;
313                                 iter2=next2++;
314                         }
315
316                         if(divisor && pool.get_a() && pool.is_valid())
317                         {
318 /*
319                                 pool.set_r(pool.get_r()/pool.get_a());
320                                 pool.set_g(pool.get_g()/pool.get_a());
321                                 pool.set_b(pool.get_b()/pool.get_a());
322                                 pool.set_a(pool.get_a()/divisor);
323 */
324                                 pool/=divisor;
325                                 pool.set_r(pool.get_r()/pool.get_a());
326                                 pool.set_g(pool.get_g()/pool.get_a());
327                                 pool.set_b(pool.get_b()/pool.get_a());
328                                 if(pool.is_valid())
329                                         return pool;
330                                 else
331                                         return Color::alpha();
332                         }
333                         else
334                                 return Color::alpha();
335                 }
336         }
337
338         // We should never get to this point.
339
340         synfig::error("synfig::Gradient::operator()(): Logic Error (x=%f)",x);
341         assert(0);
342         throw std::logic_error(strprintf("synfig::Gradient::operator()(): Logic Error (x=%f)",x));
343 }
344
345 synfig::Gradient::iterator
346 synfig::Gradient::proximity(const Real &x)
347 {
348         iterator iter;
349         float dist(100000000);
350         float prev_pos(-0230);
351         // This algorithm requires a sorted list.
352         for(iter=begin();iter<end();iter++)
353         {
354                 float new_dist;
355
356                 if(prev_pos==iter->pos)
357                         new_dist=(abs(x-iter->pos-0.00001));
358                 else
359                         new_dist=(abs(x-iter->pos));
360
361                 if(new_dist>dist)
362                 {
363                         iter--;
364                         return iter;
365                 }
366                 dist=new_dist;
367                 prev_pos=iter->pos;
368         }
369         iter--;
370         return iter;
371 }
372
373 synfig::Gradient::const_iterator
374 synfig::Gradient::proximity(const Real &x)const
375 {
376         return const_cast<Gradient*>(this)->proximity(x);
377         /*
378         const_iterator iter;
379         float dist(100000000);
380
381         // This algorithm requires a sorted list.
382         for(iter=begin();iter<end();iter++)
383         {
384                 const float new_dist(abs(x-iter->pos));
385                 if(new_dist>dist)
386                 {
387                         iter--;
388                         return iter;
389                 }
390                 dist=new_dist;
391         }
392         iter--;
393         return iter;
394         */
395 }
396
397 synfig::Gradient::iterator
398 synfig::Gradient::find(const UniqueID &id)
399 {
400         iterator iter;
401
402         for(iter=begin();iter<end();iter++)
403         {
404                 if(id==*iter)
405                         return iter;
406         }
407
408         throw Exception::NotFound("synfig::Gradient::find(): Unable to find UniqueID in gradient");
409 }
410
411 synfig::Gradient::const_iterator
412 synfig::Gradient::find(const UniqueID &id)const
413 {
414         const_iterator iter;
415
416         for(iter=begin();iter<end();iter++)
417         {
418                 if(id==*iter)
419                         return iter;
420         }
421
422         throw Exception::NotFound("synfig::Gradient::find()const: Unable to find UniqueID in gradient");
423 }