Partially fix 1568818: Define mathematical operators so that we can animate gradients.
[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 #include <algorithm>
37
38 #include <ETL/misc>
39 #endif
40
41 /* === U S I N G =========================================================== */
42
43 using namespace std;
44 using namespace etl;
45 using namespace synfig;
46
47 /* === M A C R O S ========================================================= */
48
49 /* === G L O B A L S ======================================================= */
50
51 /* === P R O C E D U R E S ================================================= */
52
53 /* === M E T H O D S ======================================================= */
54
55 synfig::Gradient::Gradient(const Color &c1, const Color &c2)
56 {
57         push_back(CPoint(0.0,c1));
58         push_back(CPoint(1.0,c2));
59 }
60
61 synfig::Gradient::Gradient(const Color &c1, const Color &c2, const Color &c3)
62 {
63         push_back(CPoint(0.0,c1));
64         push_back(CPoint(0.5,c2));
65         push_back(CPoint(1.0,c3));
66 }
67
68 // This sort algorithm MUST be stable
69 // ie: it must not change the order of items with the same value.
70 // I am using a bubble sort.
71 // This algorithm will sort a nearly-sorted list at ~O(N), and
72 // it will sort an inverse sorted list at ~O(N*N).
73 void
74 synfig::Gradient::sort()
75 {
76         stable_sort(begin(),end());
77         /*
78         iterator iter;
79         iterator iter2,next;
80
81         for(iter=begin();iter!=end();iter++)
82         {
83                 for(next=iter, iter2=next--;iter2!=begin();iter2=next--)
84                 {
85                         if(*iter<*next)
86                         {
87                                 //insert(next,*iter);
88                                 //erase(iter);
89                                 iter_swap(next,iter);
90
91                                 continue;
92                         }
93                         else
94                                 break;
95                 }
96         }
97         */
98 }
99
100 static synfig::ColorAccumulator
101 supersample_helper(const synfig::Gradient::CPoint &color1, const synfig::Gradient::CPoint &color2, float begin, float end, float &weight)
102 {
103         if(color1.pos==color2.pos || color1.pos>=end || color2.pos<=begin)
104         {
105                 weight=0;
106                 return Color::alpha();
107         }
108         if(color1.pos>=begin && color2.pos<end)
109         {
110                 weight=color2.pos-color1.pos;
111                 ColorAccumulator ret=Color::blend(color2.color,color1.color, 0.5, Color::BLEND_STRAIGHT).premult_alpha()*weight;
112                 return ret;
113         }
114         if(color1.pos>=begin && color2.pos>=end)
115         {
116                 weight=end-color1.pos;
117                 float pos((end+color1.pos)*0.5);
118                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
119                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
120                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
121                 return ret;
122         }
123         if(color1.pos<begin && color2.pos<end)
124         {
125                 weight=color2.pos-begin;
126                 float pos((begin+color2.pos)*0.5);
127                 float amount((pos-color1.pos)/(color2.pos-color1.pos));
128                 //if(abs(amount)>1)amount=(amount>0)?1:-1;
129                 ColorAccumulator ret(Color::blend(color2.color,color1.color, amount, Color::BLEND_STRAIGHT).premult_alpha()*weight);
130                 return ret;
131         }
132         synfig::error("color1.pos=%f",color1.pos);
133         synfig::error("color2.pos=%f",color2.pos);
134         synfig::error("begin=%f",begin);
135         synfig::error("end=%f",end);
136
137         weight=0;
138         return Color::alpha();
139
140 //      assert(0);
141 }
142
143 Gradient &
144 synfig::Gradient::operator+=(const Gradient &rhs)
145 {
146         CPointList ret;
147         const_iterator iter1 = begin(), iter2 = rhs.begin(), left_same, right_same;
148         CPoint left, right;
149         if (iter1 != end()) left = *iter1;
150         if (iter2 != rhs.end()) right = *iter2;
151         if (iter1 != end() && iter2 != rhs.end())
152                 while(true)
153                 {
154                         if (left.pos < right.pos)
155                         {
156                                 ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
157                                 if(++iter1 == end()) break;
158                                 left=*iter1;
159                         }
160                         else if (left.pos > right.pos)
161                         {
162                                 ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
163                                 if(++iter2 == rhs.end()) break;
164                                 right=*iter2;
165                         }
166                         else
167                         {
168                                 for(left_same = iter1++; (*iter1).pos == left.pos; iter1++);
169                                 for(right_same = iter2++; (*iter2).pos == right.pos; iter2++);
170                                 if (iter1 == left_same+1 && iter2 == right_same+1)
171                                         ret.push_back(CPoint(left.pos, left.color + right.color));
172                                 else
173                                 {
174                                         ret.push_back(CPoint(left.pos, left.color + right.color));
175                                         ret.push_back(CPoint(left.pos, (*(iter1-1)).color + (*(iter2-1)).color));
176                                 }
177                                 if (iter1 != end()) left=*iter1;
178                                 if (iter2 == rhs.end()) break;
179                                 right = *iter2;
180                                 if (iter1 == end()) break;
181                         }
182                 }
183
184         if (iter1 != end())
185                 while(true)
186                 {
187                         ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
188                         if(++iter1 == end()) break;
189                         left = *iter1;
190                 }
191
192         if (iter2 != rhs.end())
193                 while(true)
194                 {
195                         ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
196                         if(++iter2 == rhs.end()) break;
197                         right = *iter2;
198                 }
199
200         cpoints = ret;
201         return *this;
202 }
203
204 Gradient &
205 synfig::Gradient::operator-=(const Gradient &rhs)
206 {
207         return (*this)+=(rhs*-1);
208 }
209
210 Gradient &
211 synfig::Gradient::operator*=(const float    &rhs)
212 {
213         for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
214                 (*iter).color *= rhs;
215         return *this;
216 }
217
218 Gradient &
219 synfig::Gradient::operator/=(const float    &rhs)
220 {
221         for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
222                 (*iter).color /= rhs;
223         return *this;
224 }
225
226 Color
227 synfig::Gradient::operator()(const Real &x,float supersample)const
228 {
229         if(cpoints.empty())
230                 return Color(0,0,0,0);
231         if(supersample<0)
232                 supersample=-supersample;
233         if(supersample>2.0)
234                 supersample=2.0f;
235
236         float begin_sample(x-supersample*0.5);
237         float end_sample(x+supersample*0.5);
238
239         if(cpoints.size()==1 || end_sample<=cpoints.front().pos || isnan(x))
240                 return cpoints.front().color;
241
242         if(begin_sample>=cpoints.back().pos)
243                 return cpoints.back().color;
244
245         /*
246         if(end_sample>=back().pos)
247                 end_sample=back().pos;
248
249         if(begin_sample<=front().pos)
250                 begin_sample=front().pos;
251         */
252
253         const_iterator iter,next;
254
255         /*
256         //optimizize...
257         Real    left = x-supersample/2, right = x+supersample/2;
258
259         if(left < front().pos) left = front().pos;
260         if(right > back().pos) right = back().pos;
261
262         //find using binary search...
263         const_iterator iterl,iterr;
264
265         //the binary search should give us the values BEFORE the point we're looking for...
266         iterl = binary_find(begin(),end(),left);
267         iterr = binary_find(iterl,end(),right);
268
269         //now integrate over the range of left to right...
270
271         if(iterl == iterr)
272         {
273                 iterr++; //let's look at the next one shall we :)
274
275                 //interpolate neighboring colors
276                 const Real one = iterr->pos - iterl->pos;
277                 const Real lambda = (x - iterl->pos)/one;
278
279                 //(1-l)iterl + (l)iterr
280                 return iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
281
282                 //return Color::blend(iterr->color,iterl->color,lambda,Color::BLEND_STRAIGHT);
283         }else
284         {
285                 //itegration madness
286                 const_iterator i = iterl, ie = iterr+1;
287                 Real wlast = left;
288
289                 ColorAccumulator clast,cwork;
290                 {
291                         const Real lambda = (x - iterl->pos)/(iterr->pos - iterl->pos);
292
293                         //premultiply because that's the form in which we can combine things...
294                         clast = iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
295                         //Color::blend((i+1)->color,i->color,(left - i->pos)/((i+1)->pos - i->pos),Color::BLEND_STRAIGHT);
296                 }
297
298                 ColorAccumulator        accum = 0;
299
300                 //loop through all the trapezoids and integrate them as we go...
301                 //      area of trap = (yi + yi1)*(xi1 - xi)
302                 //      yi = clast, xi = wlast, yi1 = i->color, xi1 = i->pos
303
304                 for(;i<=iterr; wlast=i->pos,clast=i->color.premult_alpha(),++i)
305                 {
306                         const Real diff = i->pos - wlast;
307                         if(diff > 0) //only accumulate if there will be area to add
308                         {
309                                 cwork = i->color.premult_alpha();
310                                 accum += (cwork + clast)*diff;
311                         }
312                 }
313
314                 {
315                         const_iterator ibef = i-1;
316                         const Real diff = right - ibef->pos;
317
318                         if(diff > 0)
319                         {
320                                 const Real lambda = diff/(i->pos - ibef->pos);
321                                 cwork = ibef->color.premult_alpha()*(1-lambda) + i->color.premult_alpha()*lambda;
322
323                                 accum += (cwork + clast)*diff; //can probably optimize this more... but it's not too bad
324                         }
325                 }
326
327                 accum /= supersample; //should be the total area it was sampled over...
328                 return accum.demult_alpha();
329         }*/
330
331         next=begin(),iter=next++;
332
333         //add for optimization
334         next = binary_find(begin(),end(),(Real)begin_sample);
335         iter = next++;
336
337         //! As a future optimization, this could be performed faster
338         //! using a binary search.
339         for(;iter<end();iter=next++)
340         {
341                 if(next==end() || x>=iter->pos &&  x<next->pos && iter->pos!=next->pos)
342                 {
343                         // If the supersample region falls square in between
344                         // two CPoints, then we don't have to do anything special.
345                         if(next!=end() && (!supersample || (iter->pos<=begin_sample && next->pos>=end_sample)))
346                         {
347                                 const Real dist(next->pos-iter->pos);
348                                 const Real pos(x-iter->pos);
349                                 const Real amount(pos/dist);
350                                 return Color::blend(next->color,iter->color, amount, Color::BLEND_STRAIGHT);
351                         }
352                         // In this case our supersample region extends over one or more
353                         // CPoints. So, we need to calculate our coverage amount.
354                         ColorAccumulator pool(Color::alpha());
355                         float divisor(0.0),weight(0);
356
357                         const_iterator iter2,next2;
358                         iter2=iter;
359                         if(iter==begin() && iter->pos>x)
360                         {
361                                 weight=x-iter->pos;
362                                 //weight*=iter->color.get_a();
363                                 pool+=ColorAccumulator(iter->color).premult_alpha()*weight;
364                                 divisor+=weight;
365                         }
366                         else
367                         {
368                                 while(iter2->pos>=begin_sample)
369                                 {
370                                         if(iter2==begin())
371                                         {
372                                                 weight=iter2->pos-(begin_sample);
373                                                 //weight*=iter2->color.get_a();
374                                                 pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
375                                                 divisor+=weight;
376                                                 break;
377                                         }
378                                         next2=iter2--;
379                                         pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
380                                         divisor+=weight;
381                                 }
382                         }
383
384                         next2=iter;
385                         iter2=next2++;
386                         while(iter2->pos<=end_sample)
387                         {
388                                 if(next2==end())
389                                 {
390                                         weight=(end_sample)-iter2->pos;
391                                         pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
392                                         divisor+=weight;
393                                         break;
394                                 }
395                                 pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
396                                 divisor+=weight;
397                                 iter2=next2++;
398                         }
399
400                         if(divisor && pool.get_a() && pool.is_valid())
401                         {
402 /*
403                                 pool.set_r(pool.get_r()/pool.get_a());
404                                 pool.set_g(pool.get_g()/pool.get_a());
405                                 pool.set_b(pool.get_b()/pool.get_a());
406                                 pool.set_a(pool.get_a()/divisor);
407 */
408                                 pool/=divisor;
409                                 pool.set_r(pool.get_r()/pool.get_a());
410                                 pool.set_g(pool.get_g()/pool.get_a());
411                                 pool.set_b(pool.get_b()/pool.get_a());
412                                 if(pool.is_valid())
413                                         return pool;
414                                 else
415                                         return Color::alpha();
416                         }
417                         else
418                                 return Color::alpha();
419                 }
420         }
421
422         // We should never get to this point.
423
424         synfig::error("synfig::Gradient::operator()(): Logic Error (x=%f)",x);
425         assert(0);
426         throw std::logic_error(strprintf("synfig::Gradient::operator()(): Logic Error (x=%f)",x));
427 }
428
429 synfig::Gradient::iterator
430 synfig::Gradient::proximity(const Real &x)
431 {
432         iterator iter;
433         float dist(100000000);
434         float prev_pos(-0230);
435         // This algorithm requires a sorted list.
436         for(iter=begin();iter<end();iter++)
437         {
438                 float new_dist;
439
440                 if(prev_pos==iter->pos)
441                         new_dist=(abs(x-iter->pos-0.00001));
442                 else
443                         new_dist=(abs(x-iter->pos));
444
445                 if(new_dist>dist)
446                 {
447                         iter--;
448                         return iter;
449                 }
450                 dist=new_dist;
451                 prev_pos=iter->pos;
452         }
453         iter--;
454         return iter;
455 }
456
457 synfig::Gradient::const_iterator
458 synfig::Gradient::proximity(const Real &x)const
459 {
460         return const_cast<Gradient*>(this)->proximity(x);
461         /*
462         const_iterator iter;
463         float dist(100000000);
464
465         // This algorithm requires a sorted list.
466         for(iter=begin();iter<end();iter++)
467         {
468                 const float new_dist(abs(x-iter->pos));
469                 if(new_dist>dist)
470                 {
471                         iter--;
472                         return iter;
473                 }
474                 dist=new_dist;
475         }
476         iter--;
477         return iter;
478         */
479 }
480
481 synfig::Gradient::iterator
482 synfig::Gradient::find(const UniqueID &id)
483 {
484         iterator iter;
485
486         for(iter=begin();iter<end();iter++)
487         {
488                 if(id==*iter)
489                         return iter;
490         }
491
492         throw Exception::NotFound("synfig::Gradient::find(): Unable to find UniqueID in gradient");
493 }
494
495 synfig::Gradient::const_iterator
496 synfig::Gradient::find(const UniqueID &id)const
497 {
498         const_iterator iter;
499
500         for(iter=begin();iter<end();iter++)
501         {
502                 if(id==*iter)
503                         return iter;
504         }
505
506         throw Exception::NotFound("synfig::Gradient::find()const: Unable to find UniqueID in gradient");
507 }