Added a new parameter to the plant layer, "Perpendicular Velocity" which controls...
[synfig.git] / synfig-core / trunk / src / modules / mod_particle / plant.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file plant.cpp
3 **      \brief Template
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 <synfig/angle.h>
33 #include "plant.h"
34 #include <synfig/string.h>
35 #include <synfig/time.h>
36 #include <synfig/context.h>
37 #include <synfig/paramdesc.h>
38 #include <synfig/renddesc.h>
39 #include <synfig/surface.h>
40 #include <synfig/value.h>
41 #include <synfig/valuenode.h>
42
43 #include <ETL/calculus>
44 #include <ETL/bezier>
45 #include <ETL/hermite>
46 #include <vector>
47
48 #include <synfig/valuenode_bline.h>
49
50 #endif
51
52 using namespace etl;
53
54 /* === M A C R O S ========================================================= */
55
56 #define SAMPLES         300
57 #define ROUND_END_FACTOR        (4)
58 #define CUSP_THRESHOLD          (0.15)
59 #define NO_LOOP_COOKIE          synfig::Vector(84951305,7836658)
60 #define EPSILON                         (0.000000001)
61 #define CUSP_TANGENT_ADJUST     (0.025)
62
63 /* === G L O B A L S ======================================================= */
64
65 SYNFIG_LAYER_INIT(Plant);
66 SYNFIG_LAYER_SET_NAME(Plant,"plant");
67 SYNFIG_LAYER_SET_LOCAL_NAME(Plant,_("Plant"));
68 SYNFIG_LAYER_SET_CATEGORY(Plant,_("Other"));
69 SYNFIG_LAYER_SET_VERSION(Plant,"0.1");
70 SYNFIG_LAYER_SET_CVS_ID(Plant,"$Id$");
71
72 /* === P R O C E D U R E S ================================================= */
73
74 /* === M E T H O D S ======================================================= */
75
76
77 Plant::Plant():
78         split_angle(Angle::deg(10)),
79         gravity(0,-0.1),
80         velocity(0.3),
81         perp_velocity(0.3),
82         step(0.01),
83         sprouts(10)
84 {
85         bounding_rect=Rect::zero();
86         random_factor=0.2;
87         random.set_seed(time(NULL));
88
89         bline.push_back(BLinePoint());
90         bline.push_back(BLinePoint());
91         bline.push_back(BLinePoint());
92         bline[0].set_vertex(Point(0,1));
93         bline[1].set_vertex(Point(0,-1));
94         bline[2].set_vertex(Point(1,0));
95         bline[0].set_tangent(bline[1].get_vertex()-bline[2].get_vertex()*0.5f);
96         bline[1].set_tangent(bline[2].get_vertex()-bline[0].get_vertex()*0.5f);
97         bline[2].set_tangent(bline[0].get_vertex()-bline[1].get_vertex()*0.5f);
98         bline[0].set_width(1.0f);
99         bline[1].set_width(1.0f);
100         bline[2].set_width(1.0f);
101         bline_loop=true;
102         mass=(0.5);
103         splits=5;
104         drag=0.1;
105         size=0.015;
106         needs_sync_=true;
107         sync();
108         size_as_alpha=false;
109 }
110
111 void
112 Plant::branch(int n,int depth,float t, float stunt_growth, synfig::Point position,synfig::Vector vel)const
113 {
114         float next_split((1.0-t)/(splits-depth)+t/*+random_factor*random(40+depth,t*splits,0,0)/splits*/);
115         for(;t<next_split;t+=step)
116         {
117                 vel[0]+=gravity[0]*step;
118                 vel[1]+=gravity[1]*step;
119                 vel*=(1.0-(drag)*step);
120                 position[0]+=vel[0]*step;
121                 position[1]+=vel[1]*step;
122
123                 particle_list.push_back(Particle(position, gradient(t)));
124                 if (particle_list.size() % 1000000 == 0)
125                         synfig::info("constructed %d million particles...", particle_list.size()/1000000);
126
127                 bounding_rect.expand(position);
128         }
129
130         if(t>=1.0-stunt_growth)return;
131
132         synfig::Real sin_v=synfig::Angle::cos(split_angle).get();
133         synfig::Real cos_v=synfig::Angle::sin(split_angle).get();
134
135         synfig::Vector velocity1(vel[0]*sin_v - vel[1]*cos_v + random_factor*random(Random::SMOOTH_COSINE, 30+n+depth, t*splits, 0.0f, 0.0f),
136                                                          vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 32+n+depth, t*splits, 0.0f, 0.0f));
137         synfig::Vector velocity2(vel[0]*sin_v + vel[1]*cos_v + random_factor*random(Random::SMOOTH_COSINE, 31+n+depth, t*splits, 0.0f, 0.0f),
138                                                         -vel[0]*cos_v + vel[1]*sin_v + random_factor*random(Random::SMOOTH_COSINE, 33+n+depth, t*splits, 0.0f, 0.0f));
139
140         Plant::branch(n,depth+1,t,stunt_growth,position,velocity1);
141         Plant::branch(n,depth+1,t,stunt_growth,position,velocity2);
142 }
143
144 void
145 Plant::calc_bounding_rect()const
146 {
147         std::vector<synfig::BLinePoint>::const_iterator iter,next;
148
149         bounding_rect=Rect::zero();
150
151         // Bline must have at least 2 points in it
152         if(bline.size()<2)
153                 return;
154
155         next=bline.begin();
156
157         if(bline_loop)
158                 iter=--bline.end();
159         else
160                 iter=next++;
161
162         for(;next!=bline.end();iter=next++)
163         {
164                 bounding_rect.expand(iter->get_vertex());
165                 bounding_rect.expand(next->get_vertex());
166                 bounding_rect.expand(iter->get_vertex()+iter->get_tangent2()*0.3333333333333);
167                 bounding_rect.expand(next->get_vertex()-next->get_tangent1()*0.3333333333333);
168                 bounding_rect.expand(next->get_vertex()+next->get_tangent2()*velocity);
169         }
170         bounding_rect.expand_x(gravity[0]);
171         bounding_rect.expand_y(gravity[1]);
172         bounding_rect.expand_x(size);
173         bounding_rect.expand_y(size);
174 }
175
176 void
177 Plant::sync()const
178 {
179         Mutex::Lock lock(mutex);
180         if (!needs_sync_) return;
181         particle_list.clear();
182
183         bounding_rect=Rect::zero();
184
185         // Bline must have at least 2 points in it
186         if(bline.size()<2)
187         {
188                 needs_sync_=false;
189                 return;
190         }
191
192         std::vector<synfig::BLinePoint>::const_iterator iter,next;
193
194         etl::hermite<Vector> curve;
195
196         Real step(abs(this->step));
197
198         int seg(0);
199
200         next=bline.begin();
201
202         if(bline_loop)  iter=--bline.end(); // iter is the last  bline in the list; next is the first  bline in the list
203         else                    iter=next++;            // iter is the first bline in the list; next is the second bline in the list
204
205         // loop through the bline; seg counts the blines as we do so; stop before iter is the last bline in the list
206         for(;next!=bline.end();iter=next++,seg++)
207         {
208                 curve.p1()=iter->get_vertex();
209                 curve.t1()=iter->get_tangent2();
210                 curve.p2()=next->get_vertex();
211                 curve.t2()=next->get_tangent1();
212                 curve.sync();
213                 etl::derivative<etl::hermite<Vector> > deriv(curve);
214
215                 Real f;
216
217                 int i=0, branch_count = 0, steps = round_to_int(1.0/step);
218                 for(f=0.0;f<1.0;f+=step,i++)
219                 {
220                         Point point(curve(f));
221
222                         particle_list.push_back(Particle(point, gradient(0)));
223                         if (particle_list.size() % 1000000 == 0)
224                                 synfig::info("constructed %d million particles...", particle_list.size()/1000000);
225
226                         bounding_rect.expand(point);
227
228                         Real stunt_growth(random_factor * random(Random::SMOOTH_COSINE,i,f+seg,0.0f,0.0f)/2.0+0.5);
229                         stunt_growth*=stunt_growth;
230
231                         if((((i+1)*sprouts + steps/2) / steps) > branch_count) {
232                                 Vector branch_velocity(deriv(f).norm()*velocity + deriv(f).perp().norm()*perp_velocity);
233
234                                 branch_velocity[0] += random_factor * random(Random::SMOOTH_COSINE, 1, f*splits, 0.0f, 0.0f);
235                                 branch_velocity[1] += random_factor * random(Random::SMOOTH_COSINE, 2, f*splits, 0.0f, 0.0f);
236
237                                 branch_count++;
238                                 branch(i, 0, 0,          // time
239                                            stunt_growth, // stunt growth
240                                            point, branch_velocity);
241                         }
242                 }
243         }
244
245         needs_sync_=false;
246 }
247
248 bool
249 Plant::set_param(const String & param, const ValueBase &value)
250 {
251         if(param=="bline" && value.get_type()==ValueBase::TYPE_LIST)
252         {
253                 bline=value;
254                 bline_loop=value.get_loop();
255                 needs_sync_=true;
256
257                 return true;
258         }
259         if(param=="seed" && value.same_type_as(int()))
260         {
261                 random.set_seed(value.get(int()));
262                 needs_sync_=true;
263                 return true;
264         }
265         IMPORT_PLUS(split_angle,needs_sync_=true);
266         IMPORT_PLUS(gravity,needs_sync_=true);
267         IMPORT_PLUS(gradient,needs_sync_=true);
268         IMPORT_PLUS(velocity,needs_sync_=true);
269         IMPORT_PLUS(perp_velocity,needs_sync_=true);
270         IMPORT_PLUS(step,needs_sync_=true);
271         IMPORT_PLUS(splits,needs_sync_=true);
272         IMPORT_PLUS(sprouts,needs_sync_=true);
273         IMPORT_PLUS(random_factor,needs_sync_=true);
274         IMPORT_PLUS(drag,needs_sync_=true);
275         IMPORT(size);
276         IMPORT(size_as_alpha);
277
278         return Layer_Composite::set_param(param,value);
279 }
280 /*
281 void
282 Plant::set_time(Context context, Time time)const
283 {
284         if(needs_sync==true)
285         {
286                 sync();
287                 needs_sync_=false;
288         }
289         //const_cast<Plant*>(this)->sync();
290         context.set_time(time);
291 }
292
293 void
294 Plant::set_time(Context context, Time time, Vector pos)const
295 {
296         if(needs_sync==true)
297         {
298                 sync();
299                 needs_sync_=false;
300         }
301         //const_cast<Plant*>(this)->sync();
302         context.set_time(time,pos);
303 }
304 */
305 ValueBase
306 Plant::get_param(const String& param)const
307 {
308         if(param=="seed")
309                 return random.get_seed();
310         EXPORT(bline);
311         EXPORT(split_angle);
312         EXPORT(gravity);
313         EXPORT(velocity);
314         EXPORT(perp_velocity);
315         EXPORT(step);
316         EXPORT(gradient);
317         EXPORT(splits);
318         EXPORT(sprouts);
319         EXPORT(random_factor);
320         EXPORT(drag);
321         EXPORT(size);
322
323         EXPORT(size_as_alpha);
324
325         EXPORT_NAME();
326         EXPORT_VERSION();
327
328         return Layer_Composite::get_param(param);
329 }
330
331 Layer::Vocab
332 Plant::get_param_vocab()const
333 {
334         Layer::Vocab ret(Layer_Composite::get_param_vocab());
335
336         ret.push_back(ParamDesc("bline")
337                 .set_local_name(_("Vertices"))
338                 .set_description(_("A list of BLine Points"))
339                 //.set_origin("offset")
340                 //.set_scalar("width")
341         );
342
343         ret.push_back(ParamDesc("gradient")
344                 .set_local_name(_("Gradient"))
345                 .set_description(_("Gradient to be used for coloring the plant"))
346         );
347
348         ret.push_back(ParamDesc("split_angle")
349                 .set_local_name(_("Split Angle"))
350                 .set_description(_("Angle by which each split deviates from its parent"))
351         );
352
353         ret.push_back(ParamDesc("gravity")
354                 .set_local_name(_("Gravity"))
355                 .set_description(_("Direction in which the shoots tend to face"))
356                 .set_is_distance()
357         );
358
359         ret.push_back(ParamDesc("velocity")
360                 .set_local_name(_("Tangential Velocity"))
361                 .set_description(_("Amount to which shoots tend to grow along the tangent to the BLine"))
362         );
363
364         ret.push_back(ParamDesc("perp_velocity")
365                 .set_local_name(_("Perpendicular Velocity"))
366                 .set_description(_("Amount to which shoots tend to grow perpendicular to the tangent to the BLine"))
367         );
368
369         ret.push_back(ParamDesc("size")
370                 .set_local_name(_("Stem Size"))
371                 .set_description(_("Size of the stem"))
372                 .set_is_distance()
373         );
374
375         ret.push_back(ParamDesc("size_as_alpha")
376                 .set_local_name(_("Size As Alpha"))
377                 .set_description(_("If enabled, the alpha channel from the gradient is multiplied by the stem size, and an alpha of 1.0 is used when rendering"))
378         );
379
380         ret.push_back(ParamDesc("step")
381                 .set_local_name(_("Step"))
382                 .set_description(_("Measure of the distance between points when rendering"))
383         );
384
385         ret.push_back(ParamDesc("seed")
386                 .set_local_name(_("Seed"))
387                 .set_description(_("Used to seed the pseudo-random number generator"))
388         );
389
390         ret.push_back(ParamDesc("splits")
391                 .set_local_name(_("Splits"))
392                 .set_description(_("Maximum number of times that each sprout can sprout recursively"))
393         );
394
395         ret.push_back(ParamDesc("sprouts")
396                 .set_local_name(_("Sprouts"))
397                 .set_description(_("Number of places that growth occurs on each bline section"))
398         );
399
400         ret.push_back(ParamDesc("random_factor")
401                 .set_local_name(_("Random Factor"))
402                 .set_description(_("Used to scale down all random effects.  Set to zero to disable randomness"))
403         );
404
405         ret.push_back(ParamDesc("drag")
406                 .set_local_name(_("Drag"))
407                 .set_description(_("Drag slows the growth"))
408         );
409
410         return ret;
411 }
412
413 bool
414 Plant::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
415 {
416         bool ret(context.accelerated_render(surface,quality,renddesc,cb));
417         if(is_disabled() || !ret)
418                 return ret;
419
420         Surface dest_surface;
421         dest_surface.set_wh(surface->get_w(),surface->get_h());
422         dest_surface.clear();
423
424         const Point     tl(renddesc.get_tl());
425         const Point br(renddesc.get_br());
426
427         const int       w(renddesc.get_w());
428         const int       h(renddesc.get_h());
429
430         // Width and Height of a pixel
431         const Real pw = (br[0] - tl[0]) / w;
432         const Real ph = (br[1] - tl[1]) / h;
433
434         if(needs_sync_==true)
435                 sync();
436
437         std::vector<Particle>::reverse_iterator iter;
438         const float size_factor(1);
439         float radius(size_factor*size*sqrt(1.0f/(abs(pw)*abs(ph)))), temp_radius;
440
441         if(radius>1.0f)
442         {
443                 radius*=1.0;                    // what does this do?
444                 int x1,y1,x2,y2;
445                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
446                 {
447                         temp_radius = radius;
448                         float radius(temp_radius);
449                         Color color(iter->color);
450                         if(size_as_alpha)
451                         {
452                                 radius*=color.get_a();
453                                 color.set_a(1);
454                         }
455
456                         // calculate the box that this particle will be drawn as
457                         x1=ceil_to_int((iter->point[0]-tl[0])/pw-(radius*0.5));
458                         y1=ceil_to_int((iter->point[1]-tl[1])/ph-(radius*0.5));
459                         x2=x1+round_to_int(radius);
460                         y2=y1+round_to_int(radius);
461
462                         // if the box is entirely off the canvas, go to the next particle
463                         if(x1>=surface->get_w() || y1>=surface->get_h() || x2<0 || y2<0) continue;
464
465                         // adjust the box so it's entirely on the canvas
466                         if(x2>=surface->get_w()) x2=surface->get_w();
467                         if(y2>=surface->get_h()) y2=surface->get_h();
468                         if(x1<0) x1=0;
469                         if(y1<0) y1=0;
470
471                         int w(min(round_to_int(radius),x2-x1));
472                         int h(min(round_to_int(radius),y2-y1));
473
474                         if(w<=0 || h<=0)
475                                 continue;
476
477                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x1,y1),1.0f);
478                         dest_surface.fill(color,surface_pen,w,h);
479                 }
480         }
481         else
482         {
483                 //radius/=0.01;
484                 radius*=sqrt(step)*12.0f;
485                 for(iter=particle_list.rbegin();iter!=particle_list.rend();++iter)
486                 {
487                         temp_radius = radius;
488                         float radius(temp_radius);
489                         Color color(iter->color);
490                         if(size_as_alpha)
491                         {
492                                 radius*=color.get_a();
493                                 color.set_a(1);
494                         }
495
496                         // calculate the point that this particle will be drawn as
497                         int x=floor_to_int((iter->point[0]-tl[0])/pw-0.5f);
498                         int y=floor_to_int((iter->point[1]-tl[1])/ph-0.5f);
499
500                         // if the point is off the canvas, go to the next particle
501                         // fixme: we're losing a whole row and a whole column of pixels from each tile
502                         //        by doing this.  even in the final rendered image there are visible
503                         //                horizontal stripes of damage:
504                         //          http://dooglus.rincevent.net/synfig/plant-corruption.png
505                         if(x>=surface->get_w()-1 || y>=surface->get_h()-1 || x<0 || y<0) continue;
506
507                         // calculate how much of the point is at (x) and how much at (x+1)
508                         float x1=((iter->point[0]-tl[0])/pw-0.5f-x)*radius, x0=radius-x1;
509
510                         // calculate how much of the point is at (y) and how much at (y+1)
511                         float y1=((iter->point[1]-tl[1])/ph-0.5f-y)*radius, y0=radius-y1;
512
513                         Surface::alpha_pen surface_pen(dest_surface.get_pen(x,y),1.0f);
514
515                         //     |  x0 |  x1
516                         //  ---+-----+-----
517                         //  y0 | 1st | 2nd
518                         //  ---+-----+-----
519                         //  y1 | 4th | 3rd
520
521                         surface_pen.set_alpha(x0*y0); surface_pen.put_value(color); surface_pen.inc_x();
522                         surface_pen.set_alpha(x1*y0); surface_pen.put_value(color); surface_pen.inc_y();
523                         surface_pen.set_alpha(x1*y1); surface_pen.put_value(color); surface_pen.dec_x();
524                         surface_pen.set_alpha(x0*y1); surface_pen.put_value(color);
525                 }
526         }
527
528         Surface::alpha_pen pen(surface->get_pen(0,0),get_amount(),get_blend_method());
529         dest_surface.blit_to(pen);
530
531         return true;
532 }
533
534 Rect
535 Plant::get_bounding_rect(Context context)const
536 {
537         if(needs_sync_==true)
538                 sync();
539
540         if(is_disabled())
541                 return Rect::zero();
542
543         if(Color::is_onto(get_blend_method()))
544                 return context.get_full_bounding_rect() & bounding_rect;
545
546         //if(get_blend_method()==Color::BLEND_BEHIND)
547         //      return context.get_full_bounding_rect() | bounding_rect;
548         return bounding_rect;
549 }