9ae4af210be82bd182d2619e174e2edfc6268bb6
[synfig.git] / synfig-core / trunk / src / modules / mod_gradient / curvegradient.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file curvegradient.cpp
3 **      \brief Template Header
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 ** === N O T E S ===========================================================
22 **
23 ** ========================================================================= */
24
25 /* === H E A D E R S ======================================================= */
26
27 #ifdef USING_PCH
28 #       include "pch.h"
29 #else
30 #ifdef HAVE_CONFIG_H
31 #       include <config.h>
32 #endif
33
34 #include "curvegradient.h"
35
36 #include <synfig/string.h>
37 #include <synfig/time.h>
38 #include <synfig/context.h>
39 #include <synfig/paramdesc.h>
40 #include <synfig/renddesc.h>
41 #include <synfig/surface.h>
42 #include <synfig/value.h>
43 #include <synfig/valuenode.h>
44 #include <ETL/bezier>
45 #include <ETL/hermite>
46 #include <ETL/calculus>
47
48 #endif
49
50 /* === M A C R O S ========================================================= */
51
52 /* === G L O B A L S ======================================================= */
53
54 SYNFIG_LAYER_INIT(CurveGradient);
55 SYNFIG_LAYER_SET_NAME(CurveGradient,"curve_gradient");
56 SYNFIG_LAYER_SET_LOCAL_NAME(CurveGradient,_("Curve Gradient"));
57 SYNFIG_LAYER_SET_CATEGORY(CurveGradient,_("Gradients"));
58 SYNFIG_LAYER_SET_VERSION(CurveGradient,"0.0");
59 SYNFIG_LAYER_SET_CVS_ID(CurveGradient,"$Id$");
60
61 /* === P R O C E D U R E S ================================================= */
62
63 inline float calculate_distance(const synfig::BLinePoint& a,const synfig::BLinePoint& b)
64 {
65 #if 1
66         const Point& c1(a.get_vertex());
67         const Point c2(a.get_vertex()+a.get_tangent2()/3);
68         const Point c3(b.get_vertex()-b.get_tangent1()/3);
69         const Point& c4(b.get_vertex());
70         return (c1-c2).mag()+(c2-c3).mag()+(c3-c4).mag();
71 #else
72 #endif
73 }
74
75 inline float calculate_distance(const std::vector<synfig::BLinePoint>& bline)
76 {
77         std::vector<synfig::BLinePoint>::const_iterator iter,next,ret;
78         std::vector<synfig::BLinePoint>::const_iterator end(bline.end());
79
80         float dist(0);
81
82         if (bline.empty()) return dist;
83
84         next=bline.begin();
85
86         //if(loop)
87         //      iter=--bline.end();
88         //else
89         iter=next++;
90
91         for(;next!=end;iter=next++)
92         {
93                 // Setup the curve
94                 etl::hermite<Vector> curve(
95                         iter->get_vertex(),
96                         next->get_vertex(),
97                         iter->get_tangent2(),
98                         next->get_tangent1());
99
100 //              dist+=calculate_distance(*iter,*next);
101                 dist+=curve.length();
102         }
103
104         return dist;
105 }
106
107 std::vector<synfig::BLinePoint>::const_iterator
108 find_closest(bool fast, const std::vector<synfig::BLinePoint>& bline,const Point& p,float& t,bool loop=false,float *bline_dist_ret=0)
109 {
110         std::vector<synfig::BLinePoint>::const_iterator iter,next,ret;
111         std::vector<synfig::BLinePoint>::const_iterator end(bline.end());
112
113         ret=bline.end();
114         float dist(100000000000.0);
115
116         next=bline.begin();
117
118         float best_bline_dist(0);
119         float best_bline_len(0);
120         float total_bline_dist(0);
121         float best_pos(0);
122         etl::hermite<Vector> best_curve;
123
124         if(loop)
125                 iter=--bline.end();
126         else
127                 iter=next++;
128
129         Point bp;
130
131         for(;next!=end;iter=next++)
132         {
133                 // Setup the curve
134                 etl::hermite<Vector> curve(
135                         iter->get_vertex(),
136                         next->get_vertex(),
137                         iter->get_tangent2(),
138                         next->get_tangent1());
139
140                 /*
141                 const float t(curve.find_closest(p,6,0.01,0.99));
142                 bp=curve(t);if((bp-p).mag_squared()<dist) { ret=iter; dist=(bp-p).mag_squared(); ret_t=t; }
143                 */
144
145                 float thisdist(0);
146                 float len(0);
147                 if(bline_dist_ret)
148                 {
149                         //len=calculate_distance(*iter,*next);
150                         len=curve.length();
151                 }
152
153                 if (fast)
154                 {
155 #define POINT_CHECK(x) bp=curve(x);     thisdist=(bp-p).mag_squared(); if(thisdist<dist) { ret=iter; dist=thisdist; best_bline_dist=total_bline_dist; best_bline_len=len; best_curve=curve; }
156                         POINT_CHECK(0.0001);
157                         POINT_CHECK((1.0/6.0));
158                         POINT_CHECK((2.0/6.0));
159                         POINT_CHECK((3.0/6.0));
160                         POINT_CHECK((4.0/6.0));
161                         POINT_CHECK((5.0/6.0));
162                         POINT_CHECK(0.9999);
163                 }
164                 else
165                 {
166                         float pos = curve.find_closest(fast, p);
167                         thisdist=(curve(pos)-p).mag_squared();
168                         if(thisdist<dist)
169                         {
170                                 ret=iter;
171                                 dist=thisdist;
172                                 best_bline_dist=total_bline_dist;
173                                 best_bline_len=len;
174                                 best_curve=curve;
175                                 best_pos = pos;
176                         }
177                 }
178
179                 total_bline_dist+=len;
180         }
181
182         t = best_pos;
183
184         if(bline_dist_ret)
185         {
186                 //! \todo is this a redundant call to find_closest()?
187                 // note bline_dist_ret is null except when 'perpendicular' is true
188                 *bline_dist_ret=best_bline_dist+best_curve.find_distance(0,best_curve.find_closest(fast, p));
189 //              *bline_dist_ret=best_bline_dist+best_curve.find_closest(fast, p)*best_bline_len;
190         }
191
192         return ret;
193 }
194
195 /* === M E T H O D S ======================================================= */
196
197 inline void
198 CurveGradient::sync()
199 {
200         curve_length_=calculate_distance(bline);
201 }
202
203
204 CurveGradient::CurveGradient():
205         offset(0,0),
206         width(0.25),
207         gradient(Color::black(), Color::white()),
208         loop(false),
209         zigzag(false),
210         perpendicular(false),
211         fast(true)
212 {
213         bline.push_back(BLinePoint());
214         bline.push_back(BLinePoint());
215         bline.push_back(BLinePoint());
216         bline[0].set_vertex(Point(0,1));
217         bline[1].set_vertex(Point(0,-1));
218         bline[2].set_vertex(Point(1,0));
219         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
220         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
221         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
222         bline[0].set_width(1.0f);
223         bline[1].set_width(1.0f);
224         bline[2].set_width(1.0f);
225         bline_loop=true;
226
227         sync();
228 }
229
230 inline Color
231 CurveGradient::color_func(const Point &point_, int quality, float supersample)const
232 {
233         Vector tangent;
234         Vector diff;
235         Point p1;
236         Real thickness;
237         Real dist;
238
239         float perp_dist;
240
241         if(bline.size()==0)
242                 return Color::alpha();
243         else if(bline.size()==1)
244         {
245                 tangent=bline.front().get_tangent1();
246                 p1=bline.front().get_vertex();
247                 thickness=bline.front().get_width();
248         }
249         else
250         {
251                 float t;
252                 Point point(point_-offset);
253
254                 std::vector<synfig::BLinePoint>::const_iterator iter,next;
255
256                 // Figure out the BLinePoints we will be using,
257                 // Taking into account looping.
258                 if(perpendicular)
259                 {
260                         next=find_closest(fast,bline,point,t,bline_loop,&perp_dist);
261                         perp_dist/=curve_length_;
262                 }
263                 else
264                 {
265                         next=find_closest(fast,bline,point,t,bline_loop);
266                 }
267
268                 iter=next++;
269                 if(next==bline.end()) next=bline.begin();
270
271                 // Setup the curve
272                 etl::hermite<Vector> curve(
273                         iter->get_vertex(),
274                         next->get_vertex(),
275                         iter->get_tangent2(),
276                         next->get_tangent1()
277                         );
278
279                 // Setup the derivative function
280                 etl::derivative<etl::hermite<Vector> > deriv(curve);
281
282                 int search_iterations(7);
283
284                 /*if(quality==0)search_iterations=8;
285                   else if(quality<=2)search_iterations=10;
286                   else if(quality<=4)search_iterations=8;
287                 */
288                 if(!perpendicular)
289                 {
290                         if(quality<=6)search_iterations=7;
291                         else if(quality<=7)search_iterations=6;
292                         else if(quality<=8)search_iterations=5;
293                         else search_iterations=4;
294                 }
295                 else
296                 {
297                         if(quality>7)
298                                 search_iterations=4;
299                 }
300
301                 // Figure out the closest point on the curve
302                 if (fast)
303                         t = curve.find_closest(fast, point,search_iterations);
304
305
306                 // Calculate our values
307                 p1=curve(t);
308                 tangent=deriv(t).norm();
309
310                 if(perpendicular)
311                 {
312                         tangent*=curve_length_;
313                         p1-=tangent*perp_dist;
314                         tangent=-tangent.perp();
315                 }
316                 else
317                 {
318                         thickness=(next->get_width()-iter->get_width())*t+iter->get_width();
319                 }
320                 //}
321         }
322
323         if(!perpendicular)
324         {
325                 diff=tangent.perp()*thickness*width;
326                 p1-=diff*0.5;
327                 const Real mag(diff.inv_mag());
328                 supersample=supersample*mag;
329                 diff*=mag*mag;
330                 dist=((point_-offset)*diff-p1*diff);
331         }
332         else
333         {
334                 if(quality>7)
335                 {
336                         dist=perp_dist;
337 /*                      diff=tangent.perp();
338                         const Real mag(diff.inv_mag());
339                         supersample=supersample*mag;
340 */
341                         supersample=0;
342                 }
343                 else
344                 {
345                         diff=tangent.perp();
346                         //p1-=diff*0.5;
347                         const Real mag(diff.inv_mag());
348                         supersample=supersample*mag;
349                         diff*=mag*mag;
350                         dist=((point_-offset)*diff-p1*diff);
351                 }
352         }
353
354         if(loop)
355                 dist-=floor(dist);
356
357         if(zigzag)
358         {
359                 dist*=2.0;
360                 supersample*=2.0;
361                 if(dist>1)dist=2.0-dist;
362         }
363
364         if(loop)
365         {
366                 if(dist+supersample*0.5>1.0)
367                 {
368                         float  left(supersample*0.5-(dist-1.0));
369                         float right(supersample*0.5+(dist-1.0));
370                         Color pool(gradient(1.0-(left*0.5),left).premult_alpha()*left/supersample);
371                         if (zigzag) pool+=gradient(1.0-right*0.5,right).premult_alpha()*right/supersample;
372                         else            pool+=gradient(right*0.5,right).premult_alpha()*right/supersample;
373                         return pool.demult_alpha();
374                 }
375                 if(dist-supersample*0.5<0.0)
376                 {
377                         float  left(supersample*0.5-dist);
378                         float right(supersample*0.5+dist);
379                         Color pool(gradient(right*0.5,right).premult_alpha()*right/supersample);
380                         if (zigzag) pool+=gradient(left*0.5,left).premult_alpha()*left/supersample;
381                         else            pool+=gradient(1.0-left*0.5,left).premult_alpha()*left/supersample;
382                         return pool.demult_alpha();
383                 }
384         }
385         return gradient(dist,supersample);
386 }
387
388 float
389 CurveGradient::calc_supersample(const synfig::Point &x, float pw,float ph)const
390 {
391         return pw;
392 }
393
394 synfig::Layer::Handle
395 CurveGradient::hit_check(synfig::Context context, const synfig::Point &point)const
396 {
397         if(get_blend_method()==Color::BLEND_STRAIGHT && get_amount()>=0.5)
398                 return const_cast<CurveGradient*>(this);
399         if(get_amount()==0.0)
400                 return context.hit_check(point);
401         if((get_blend_method()==Color::BLEND_STRAIGHT || get_blend_method()==Color::BLEND_COMPOSITE|| get_blend_method()==Color::BLEND_ONTO) && color_func(point).get_a()>0.5)
402                 return const_cast<CurveGradient*>(this);
403         return context.hit_check(point);
404 }
405
406 bool
407 CurveGradient::set_param(const String & param, const ValueBase &value)
408 {
409
410
411         IMPORT(offset);
412         IMPORT(perpendicular);
413         IMPORT(fast);
414
415         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
416         {
417                 bline=value;
418                 bline_loop=value.get_loop();
419                 sync();
420
421                 return true;
422         }
423
424         IMPORT(width);
425         IMPORT(gradient);
426         IMPORT(loop);
427         IMPORT(zigzag);
428         return Layer_Composite::set_param(param,value);
429 }
430
431 ValueBase
432 CurveGradient::get_param(const String & param)const
433 {
434         EXPORT(offset);
435         EXPORT(bline);
436         EXPORT(gradient);
437         EXPORT(loop);
438         EXPORT(zigzag);
439         EXPORT(width);
440         EXPORT(perpendicular);
441         EXPORT(fast);
442
443         EXPORT_NAME();
444         EXPORT_VERSION();
445
446         return Layer_Composite::get_param(param);
447 }
448
449 Layer::Vocab
450 CurveGradient::get_param_vocab()const
451 {
452         Layer::Vocab ret(Layer_Composite::get_param_vocab());
453
454         ret.push_back(ParamDesc("offset")
455                                   .set_local_name(_("Offset")));
456
457         ret.push_back(ParamDesc("width")
458                                   .set_is_distance()
459                                   .set_local_name(_("Width")));
460
461         ret.push_back(ParamDesc("bline")
462                                   .set_local_name(_("Vertices"))
463                                   .set_origin("offset")
464                                   .set_scalar("width")
465                                   .set_description(_("A list of BLine Points")));
466
467         ret.push_back(ParamDesc("gradient")
468                                   .set_local_name(_("Gradient")));
469         ret.push_back(ParamDesc("loop")
470                                   .set_local_name(_("Loop")));
471         ret.push_back(ParamDesc("zigzag")
472                                   .set_local_name(_("ZigZag")));
473         ret.push_back(ParamDesc("perpendicular")
474                                   .set_local_name(_("Perpendicular")));
475         ret.push_back(ParamDesc("fast")
476                                   .set_local_name(_("Fast")));
477
478         return ret;
479 }
480
481 Color
482 CurveGradient::get_color(Context context, const Point &point)const
483 {
484         const Color color(color_func(point,0));
485
486         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
487                 return color;
488         else
489                 return Color::blend(color,context.get_color(point),get_amount(),get_blend_method());
490 }
491
492 bool
493 CurveGradient::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
494 {
495         SuperCallback supercb(cb,0,9500,10000);
496
497         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
498         {
499                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
500         }
501         else
502         {
503                 if(!context.accelerated_render(surface,quality,renddesc,&supercb))
504                         return false;
505                 if(get_amount()==0)
506                         return true;
507         }
508
509
510         int x,y;
511
512         Surface::pen pen(surface->begin());
513         const Real pw(renddesc.get_pw()),ph(renddesc.get_ph());
514         Point pos;
515         Point tl(renddesc.get_tl());
516         const int w(surface->get_w());
517         const int h(surface->get_h());
518
519         if(get_amount()==1.0 && get_blend_method()==Color::BLEND_STRAIGHT)
520         {
521                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
522                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
523                                 pen.put_value(color_func(pos,quality,calc_supersample(pos,pw,ph)));
524         }
525         else
526         {
527                 for(y=0,pos[1]=tl[1];y<h;y++,pen.inc_y(),pen.dec_x(x),pos[1]+=ph)
528                         for(x=0,pos[0]=tl[0];x<w;x++,pen.inc_x(),pos[0]+=pw)
529                                 pen.put_value(Color::blend(color_func(pos,quality,calc_supersample(pos,pw,ph)),pen.get_value(),get_amount(),get_blend_method()));
530         }
531
532         // Mark our progress as finished
533         if(cb && !cb->amount_complete(10000,10000))
534                 return false;
535
536         return true;
537 }