Tidying up a little.
[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 static void show_gradient(const Gradient::CPointList x)
144 {
145         int i = 0;
146         for (Gradient::const_iterator iter = x.begin(); iter != x.end(); iter++)
147                 printf("%3d : %.3f %s\n", i++, (*iter).pos, (*iter).color.get_string().c_str());
148 }
149
150 Gradient &
151 synfig::Gradient::operator+=(const Gradient &rhs)
152 {
153         bool print=false;                       // for debugging
154         if (print) { printf("\nadding lhs:\n"); show_gradient(this->cpoints); printf("\n"); }
155         if (print) { printf("adding rhs:\n"); show_gradient(rhs.cpoints); printf("\n"); }
156         CPointList ret;
157         const_iterator iter1 = begin(), iter2 = rhs.begin(), left_same, right_same;
158         CPoint left, right;
159         if (iter1 != end()) left = *iter1;
160         if (iter2 != rhs.end()) right = *iter2;
161         int pos1 = 0, pos2 = 0;
162         CPoint old1, old2;
163
164         // if there are cpoints in both gradients run through both until one runs out
165         if (iter1 != end() && iter2 != rhs.end())
166                 while(true)
167                         // if the left one has the first cpoint
168                         if (left.pos < right.pos)
169                         {
170                                 // add on the right gradient's value at this point
171                                 if (print) printf("using pos %.2f from left %d in loop\n", left.pos, pos1++);
172                                 ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
173                                 if(++iter1 == end()) break;
174                                 left=*iter1;
175                         }
176                         // if the right one has the first cpoint
177                         else if (left.pos > right.pos)
178                         {
179                                 // add on the left gradient's value at this point
180                                 if (print) printf("using pos %.2f from right %d in loop\n", right.pos, pos2++);
181                                 ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
182                                 if(++iter2 == rhs.end()) break;
183                                 right=*iter2;
184                         }
185                         // they both have a cpoint at the same time
186                         else
187                         {
188                                 int tpos1 = pos1, tpos2 = pos2;
189                                 // skip past all cpoints at the same position
190                                 for(left_same = ++iter1; iter1 != end() && (*iter1).pos == left.pos; iter1++, pos1++)
191                                         if (print) printf("skipping past pos %d in left\n", pos1);
192                                 for(right_same = ++iter2; iter2 != rhs.end() && (*iter2).pos == right.pos; iter2++, pos2++)
193                                         if (print) printf("skipping past pos %d in right\n", pos2);
194
195                                 // if there is only one cpoint at this position in each gradient,
196                                 // there's only one corresponding cpoint in the sum
197                                 if (iter1 == left_same && iter2 == right_same)
198                                 {
199                                         if (print) printf("two singles at left %d and right %d\n", pos1++, pos2++);
200                                         ret.push_back(CPoint(left.pos, left.color + right.color));
201                                 }
202                                 // otherwise we sum the first in each, and the last in each
203                                 else
204                                 {
205                                         if (print) printf("[copying %d from left %d and %d from right %d at %.2f]\n", iter1-left_same+1, tpos1, iter2-right_same+1, tpos2, left.pos);
206                                         // merge the front two cpoints
207                                         if (print) printf("  copy front from left %d right %d\n", tpos1++, tpos2++);
208                                         ret.push_back(CPoint(left.pos, left.color + right.color));
209
210                                         // merge the middle pairs of points - each middle point merges with its counterpart
211                                         while(left_same < iter1-1 && right_same < iter2-1)
212                                         {
213                                                 old1 = *(left_same++);
214                                                 old2 = *(right_same++);
215                                                 if (print) printf("  copy middle from left %d and right %d\n", tpos1++, tpos2++);
216                                                 ret.push_back(CPoint(old1.pos, old1.color+old2.color));
217                                         }
218                                         // if one gradient has more middle points than the other, merge the rest with the last point in the other gradient
219                                         for(old2 = (*(iter2-1)); left_same < iter1-1; left_same++)
220                                         {
221                                                 old1 = *left_same;
222                                                 if (print) printf("  copy middle from left %d plus end of right\n", tpos1++);
223                                                 ret.push_back(CPoint(old1.pos, old1.color + old2.color));
224                                         }
225                                         for(old1 = (*(iter1-1)); right_same < iter2-1; right_same++)
226                                         {
227                                                 old2 = *right_same;
228                                                 if (print) printf("  copy middle from right %d plus end of left\n", tpos2++);
229                                                 ret.push_back(CPoint(old2.pos, old1.color + old2.color));
230                                         }
231                                         // merge the back two cpoints
232                                         if (print) printf("  copy end from left %d right %d\n", pos1++, pos2++);
233                                         ret.push_back(CPoint(left.pos, (*(iter1-1)).color + (*(iter2-1)).color));
234                                 }
235                                 // make sure we update 'left' and 'right'
236                                 if (iter1 != end()) left=*iter1;
237                                 if (iter2 == rhs.end()) break;
238                                 right = *iter2;
239                                 if (iter1 == end()) break;
240                         }
241
242         // one of the gradients has run out of points
243         // does the left one have points left?
244         if (iter1 != end())
245                 while(true)
246                 {
247                         if (print) printf("finish end from left %d\n", pos1++);
248                         ret.push_back(CPoint(left.pos, left.color + rhs(left.pos)));
249                         if(++iter1 == end()) break;
250                         left = *iter1;
251                 }
252         // the left one was empty, so maybe the right one has points left
253         else if (iter2 != rhs.end())
254                 while(true)
255                 {
256                         if (print) printf("finish end from right %d\n", pos2++);
257                         ret.push_back(CPoint(right.pos, right.color + (*this)(right.pos)));
258                         if(++iter2 == rhs.end()) break;
259                         right = *iter2;
260                 }
261
262         if (print) { printf("\nsummed ret:\n"); show_gradient(ret); printf("\n"); }
263         cpoints = ret;
264         return *this;
265 }
266
267 Gradient &
268 synfig::Gradient::operator-=(const Gradient &rhs)
269 {
270         return (*this)+=(rhs*-1);
271 }
272
273 Gradient &
274 synfig::Gradient::operator*=(const float    &rhs)
275 {
276         if (rhs == 0)
277                 cpoints.clear();
278         else
279                 for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
280                         (*iter).color *= rhs;
281         return *this;
282 }
283
284 Gradient &
285 synfig::Gradient::operator/=(const float    &rhs)
286 {
287         for (iterator iter = cpoints.begin(); iter!=cpoints.end(); iter++)
288                 (*iter).color /= rhs;
289         return *this;
290 }
291
292 Color
293 synfig::Gradient::operator()(const Real &x,float supersample)const
294 {
295         if(cpoints.empty())
296                 return Color(0,0,0,0);
297         if(supersample<0)
298                 supersample=-supersample;
299         if(supersample>2.0)
300                 supersample=2.0f;
301
302         float begin_sample(x-supersample*0.5);
303         float end_sample(x+supersample*0.5);
304
305         if(cpoints.size()==1 || end_sample<=cpoints.front().pos || isnan(x))
306                 return cpoints.front().color;
307
308         if(begin_sample>=cpoints.back().pos)
309                 return cpoints.back().color;
310
311         /*
312         if(end_sample>=back().pos)
313                 end_sample=back().pos;
314
315         if(begin_sample<=front().pos)
316                 begin_sample=front().pos;
317         */
318
319         const_iterator iter,next;
320
321         /*
322         //optimizize...
323         Real    left = x-supersample/2, right = x+supersample/2;
324
325         if(left < front().pos) left = front().pos;
326         if(right > back().pos) right = back().pos;
327
328         //find using binary search...
329         const_iterator iterl,iterr;
330
331         //the binary search should give us the values BEFORE the point we're looking for...
332         iterl = binary_find(begin(),end(),left);
333         iterr = binary_find(iterl,end(),right);
334
335         //now integrate over the range of left to right...
336
337         if(iterl == iterr)
338         {
339                 iterr++; //let's look at the next one shall we :)
340
341                 //interpolate neighboring colors
342                 const Real one = iterr->pos - iterl->pos;
343                 const Real lambda = (x - iterl->pos)/one;
344
345                 //(1-l)iterl + (l)iterr
346                 return iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
347
348                 //return Color::blend(iterr->color,iterl->color,lambda,Color::BLEND_STRAIGHT);
349         }else
350         {
351                 //itegration madness
352                 const_iterator i = iterl, ie = iterr+1;
353                 Real wlast = left;
354
355                 ColorAccumulator clast,cwork;
356                 {
357                         const Real lambda = (x - iterl->pos)/(iterr->pos - iterl->pos);
358
359                         //premultiply because that's the form in which we can combine things...
360                         clast = iterl->color.premult_alpha()*(1-lambda) + iterr->color.premult_alpha()*lambda;
361                         //Color::blend((i+1)->color,i->color,(left - i->pos)/((i+1)->pos - i->pos),Color::BLEND_STRAIGHT);
362                 }
363
364                 ColorAccumulator        accum = 0;
365
366                 //loop through all the trapezoids and integrate them as we go...
367                 //      area of trap = (yi + yi1)*(xi1 - xi)
368                 //      yi = clast, xi = wlast, yi1 = i->color, xi1 = i->pos
369
370                 for(;i<=iterr; wlast=i->pos,clast=i->color.premult_alpha(),++i)
371                 {
372                         const Real diff = i->pos - wlast;
373                         if(diff > 0) //only accumulate if there will be area to add
374                         {
375                                 cwork = i->color.premult_alpha();
376                                 accum += (cwork + clast)*diff;
377                         }
378                 }
379
380                 {
381                         const_iterator ibef = i-1;
382                         const Real diff = right - ibef->pos;
383
384                         if(diff > 0)
385                         {
386                                 const Real lambda = diff/(i->pos - ibef->pos);
387                                 cwork = ibef->color.premult_alpha()*(1-lambda) + i->color.premult_alpha()*lambda;
388
389                                 accum += (cwork + clast)*diff; //can probably optimize this more... but it's not too bad
390                         }
391                 }
392
393                 accum /= supersample; //should be the total area it was sampled over...
394                 return accum.demult_alpha();
395         }*/
396
397         next=begin(),iter=next++;
398
399         //add for optimization
400         next = binary_find(begin(),end(),(Real)begin_sample);
401         iter = next++;
402
403         //! As a future optimization, this could be performed faster
404         //! using a binary search.
405         for(;iter<end();iter=next++)
406         {
407                 if(next==end() || x>=iter->pos &&  x<next->pos && iter->pos!=next->pos)
408                 {
409                         // If the supersample region falls square in between
410                         // two CPoints, then we don't have to do anything special.
411                         if(next!=end() && (!supersample || (iter->pos<=begin_sample && next->pos>=end_sample)))
412                         {
413                                 const Real dist(next->pos-iter->pos);
414                                 const Real pos(x-iter->pos);
415                                 const Real amount(pos/dist);
416                                 return Color::blend(next->color,iter->color, amount, Color::BLEND_STRAIGHT);
417                         }
418                         // In this case our supersample region extends over one or more
419                         // CPoints. So, we need to calculate our coverage amount.
420                         ColorAccumulator pool(Color::alpha());
421                         float divisor(0.0),weight(0);
422
423                         const_iterator iter2,next2;
424                         iter2=iter;
425                         if(iter==begin() && iter->pos>x)
426                         {
427                                 weight=x-iter->pos;
428                                 //weight*=iter->color.get_a();
429                                 pool+=ColorAccumulator(iter->color).premult_alpha()*weight;
430                                 divisor+=weight;
431                         }
432                         else
433                         {
434                                 while(iter2->pos>=begin_sample)
435                                 {
436                                         if(iter2==begin())
437                                         {
438                                                 weight=iter2->pos-(begin_sample);
439                                                 //weight*=iter2->color.get_a();
440                                                 pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
441                                                 divisor+=weight;
442                                                 break;
443                                         }
444                                         next2=iter2--;
445                                         pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
446                                         divisor+=weight;
447                                 }
448                         }
449
450                         next2=iter;
451                         iter2=next2++;
452                         while(iter2->pos<=end_sample)
453                         {
454                                 if(next2==end())
455                                 {
456                                         weight=(end_sample)-iter2->pos;
457                                         pool+=ColorAccumulator(iter2->color).premult_alpha()*weight;
458                                         divisor+=weight;
459                                         break;
460                                 }
461                                 pool+=supersample_helper(*iter2, *next2, begin_sample, end_sample, weight);
462                                 divisor+=weight;
463                                 iter2=next2++;
464                         }
465
466                         if(divisor && pool.get_a() && pool.is_valid())
467                         {
468 /*
469                                 pool.set_r(pool.get_r()/pool.get_a());
470                                 pool.set_g(pool.get_g()/pool.get_a());
471                                 pool.set_b(pool.get_b()/pool.get_a());
472                                 pool.set_a(pool.get_a()/divisor);
473 */
474                                 pool/=divisor;
475                                 pool.set_r(pool.get_r()/pool.get_a());
476                                 pool.set_g(pool.get_g()/pool.get_a());
477                                 pool.set_b(pool.get_b()/pool.get_a());
478                                 if(pool.is_valid())
479                                         return pool;
480                                 else
481                                         return Color::alpha();
482                         }
483                         else
484                                 return Color::alpha();
485                 }
486         }
487
488         // We should never get to this point.
489
490         synfig::error("synfig::Gradient::operator()(): Logic Error (x=%f)",x);
491         assert(0);
492         throw std::logic_error(strprintf("synfig::Gradient::operator()(): Logic Error (x=%f)",x));
493 }
494
495 synfig::Gradient::iterator
496 synfig::Gradient::proximity(const Real &x)
497 {
498         iterator iter;
499         float dist(100000000);
500         float prev_pos(-0230);
501         // This algorithm requires a sorted list.
502         for(iter=begin();iter<end();iter++)
503         {
504                 float new_dist;
505
506                 if(prev_pos==iter->pos)
507                         new_dist=(abs(x-iter->pos-0.00001));
508                 else
509                         new_dist=(abs(x-iter->pos));
510
511                 if(new_dist>dist)
512                 {
513                         iter--;
514                         return iter;
515                 }
516                 dist=new_dist;
517                 prev_pos=iter->pos;
518         }
519         iter--;
520         return iter;
521 }
522
523 synfig::Gradient::const_iterator
524 synfig::Gradient::proximity(const Real &x)const
525 {
526         return const_cast<Gradient*>(this)->proximity(x);
527         /*
528         const_iterator iter;
529         float dist(100000000);
530
531         // This algorithm requires a sorted list.
532         for(iter=begin();iter<end();iter++)
533         {
534                 const float new_dist(abs(x-iter->pos));
535                 if(new_dist>dist)
536                 {
537                         iter--;
538                         return iter;
539                 }
540                 dist=new_dist;
541         }
542         iter--;
543         return iter;
544         */
545 }
546
547 synfig::Gradient::iterator
548 synfig::Gradient::find(const UniqueID &id)
549 {
550         iterator iter;
551
552         for(iter=begin();iter<end();iter++)
553         {
554                 if(id==*iter)
555                         return iter;
556         }
557
558         throw Exception::NotFound("synfig::Gradient::find(): Unable to find UniqueID in gradient");
559 }
560
561 synfig::Gradient::const_iterator
562 synfig::Gradient::find(const UniqueID &id)const
563 {
564         const_iterator iter;
565
566         for(iter=begin();iter<end();iter++)
567         {
568                 if(id==*iter)
569                         return iter;
570         }
571
572         throw Exception::NotFound("synfig::Gradient::find()const: Unable to find UniqueID in gradient");
573 }