Add ValueNode "Vector Length" for calculating the length of a vector.
[synfig.git] / synfig-core / trunk / src / synfig / valuenode.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file valuenode.cpp
3 **      \brief Implementation of the "Placeholder" valuenode conversion.
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007, 2008 Chris Moore
10 **
11 **      This package is free software; you can redistribute it and/or
12 **      modify it under the terms of the GNU General Public License as
13 **      published by the Free Software Foundation; either version 2 of
14 **      the License, or (at your option) any later version.
15 **
16 **      This package is distributed in the hope that it will be useful,
17 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
18 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 **      General Public License for more details.
20 **      \endlegal
21 */
22 /* ========================================================================= */
23
24 /* === H E A D E R S ======================================================= */
25
26 #define SYNFIG_NO_ANGLE
27
28 //#define HAS_HASH_MAP 1
29
30 #ifdef USING_PCH
31 #       include "pch.h"
32 #else
33 #ifdef HAVE_CONFIG_H
34 #       include <config.h>
35 #endif
36
37 #include "valuenode.h"
38 #include "general.h"
39 #include "canvas.h"
40 #include "paramdesc.h"
41 #include "releases.h"
42
43 #include "valuenode_const.h"
44 #include "valuenode_linear.h"
45 #include "valuenode_composite.h"
46 #include "valuenode_reference.h"
47 #include "valuenode_scale.h"
48 #include "valuenode_blinecalctangent.h"
49 #include "valuenode_blinecalcvertex.h"
50 #include "valuenode_blinecalcwidth.h"
51 #include "valuenode_blinereversetangent.h"
52 #include "valuenode_segcalctangent.h"
53 #include "valuenode_segcalcvertex.h"
54 #include "valuenode_repeat_gradient.h"
55 #include "valuenode_stripes.h"
56 #include "valuenode_range.h"
57 #include "valuenode_add.h"
58 #include "valuenode_subtract.h"
59 #include "valuenode_timedswap.h"
60 #include "valuenode_twotone.h"
61 #include "valuenode_bline.h"
62 #include "valuenode_dynamiclist.h"
63 #include "valuenode_radialcomposite.h"
64 #include "valuenode_gradientrotate.h"
65 #include "valuenode_sine.h"
66 #include "valuenode_cos.h"
67 #include "valuenode_atan2.h"
68 #include "valuenode_exp.h"
69 #include "valuenode_switch.h"
70 #include "valuenode_timeloop.h"
71 #include "valuenode_reciprocal.h"
72 #include "valuenode_duplicate.h"
73 #include "valuenode_integer.h"
74 #include "valuenode_step.h"
75 #include "valuenode_vectorangle.h"
76 #include "valuenode_vectorlength.h"
77
78 #include "layer.h"
79
80 #endif
81
82 /* === U S I N G =========================================================== */
83
84 using namespace std;
85 using namespace etl;
86 using namespace synfig;
87
88 /* === M A C R O S ========================================================= */
89
90 /* === G L O B A L S ======================================================= */
91
92 static int value_node_count(0);
93
94 static LinkableValueNode::Book *book_;
95
96
97 ValueNode::LooseHandle
98 synfig::find_value_node(const GUID& guid)
99 {
100         return guid_cast<ValueNode>(guid);
101 }
102
103 /* === P R O C E D U R E S ================================================= */
104
105 /* === M E T H O D S ======================================================= */
106
107 bool
108 ValueNode::subsys_init()
109 {
110         book_=new LinkableValueNode::Book();
111
112 #define ADD_VALUENODE(class,name,local,version)                                                                                                 \
113         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create);            \
114         (*book_)[name].check_type=&class::check_type;                                                                                           \
115         (*book_)[name].local_name=local;                                                                                                                        \
116         (*book_)[name].release_version=version
117
118 #define ADD_VALUENODE2(class,name,local,version)                                                                                                \
119         (*book_)[name].factory=reinterpret_cast<LinkableValueNode::Factory>(&class::create_from);       \
120         (*book_)[name].check_type=&class::check_type;                                                                                           \
121         (*book_)[name].local_name=local;                                                                                                                        \
122         (*book_)[name].release_version=version
123
124         ADD_VALUENODE(ValueNode_Linear,                   "linear",                       _("Linear"),                   RELEASE_VERSION_0_61_06);
125         ADD_VALUENODE(ValueNode_Composite,                "composite",            _("Composite"),                RELEASE_VERSION_0_61_06);
126         ADD_VALUENODE(ValueNode_RadialComposite,  "radial_composite", _("Radial Composite"), RELEASE_VERSION_0_61_06);
127         ADD_VALUENODE(ValueNode_Reference,                "reference",            _("Reference"),                RELEASE_VERSION_0_61_06);
128         ADD_VALUENODE(ValueNode_Scale,                    "scale",                        _("Scale"),                    RELEASE_VERSION_0_61_06);
129         ADD_VALUENODE(ValueNode_SegCalcTangent,   "segcalctangent",       _("Segment Tangent"),  RELEASE_VERSION_0_61_06);
130         ADD_VALUENODE(ValueNode_SegCalcVertex,    "segcalcvertex",        _("Segment Vertex"),   RELEASE_VERSION_0_61_06);
131         ADD_VALUENODE(ValueNode_Stripes,                  "stripes",              _("Stripes"),                  RELEASE_VERSION_0_61_06);
132         ADD_VALUENODE(ValueNode_Subtract,                 "subtract",             _("Subtract"),                 RELEASE_VERSION_0_61_06);
133         ADD_VALUENODE(ValueNode_TwoTone,                  "twotone",              _("Two-Tone"),                 RELEASE_VERSION_0_61_06);
134         ADD_VALUENODE(ValueNode_BLine,                    "bline",                        _("BLine"),                    RELEASE_VERSION_0_61_06);
135         ADD_VALUENODE2(ValueNode_DynamicList,     "dynamic_list",         _("Dynamic List"),     RELEASE_VERSION_0_61_06);
136         ADD_VALUENODE(ValueNode_GradientRotate,   "gradient_rotate",  _("Gradient Rotate"),      RELEASE_VERSION_0_61_06);
137         ADD_VALUENODE(ValueNode_Sine,                     "sine",                         _("Sine"),                     RELEASE_VERSION_0_61_06);
138
139         ADD_VALUENODE(ValueNode_TimedSwap,                "timed_swap",           _("Timed Swap"),               RELEASE_VERSION_0_61_07); // SVN r610
140         ADD_VALUENODE(ValueNode_Repeat_Gradient,  "repeat_gradient",  _("Repeat Gradient"),      RELEASE_VERSION_0_61_07); // SVN r666
141         ADD_VALUENODE(ValueNode_Exp,                      "exp",                          _("Exponential"),              RELEASE_VERSION_0_61_07); // SVN r739
142         ADD_VALUENODE(ValueNode_Add,                      "add",                          _("Add"),                              RELEASE_VERSION_0_61_07); // SVN r742
143         ADD_VALUENODE(ValueNode_BLineCalcTangent, "blinecalctangent", _("BLine Tangent"),        RELEASE_VERSION_0_61_07); // SVN r744
144         ADD_VALUENODE(ValueNode_BLineCalcVertex,  "blinecalcvertex",  _("BLine Vertex"),         RELEASE_VERSION_0_61_07); // SVN r744
145         ADD_VALUENODE(ValueNode_Range,                    "range",                        _("Range"),                    RELEASE_VERSION_0_61_07); // SVN r776
146
147         ADD_VALUENODE(ValueNode_Switch,                   "switch",                       _("Switch"),                   RELEASE_VERSION_0_61_08); // SVN r923
148         ADD_VALUENODE(ValueNode_Cos,                      "cos",                          _("Cos"),                              RELEASE_VERSION_0_61_08); // SVN r1111
149         ADD_VALUENODE(ValueNode_Atan2,                    "atan2",                        _("aTan2"),                    RELEASE_VERSION_0_61_08); // SVN r1132
150         ADD_VALUENODE(ValueNode_BLineRevTangent,  "blinerevtangent",  _("Reverse Tangent"),      RELEASE_VERSION_0_61_08); // SVN r1162
151         ADD_VALUENODE(ValueNode_TimeLoop,                 "timeloop",             _("Time Loop"),                RELEASE_VERSION_0_61_08); // SVN r1226
152         ADD_VALUENODE(ValueNode_Reciprocal,               "reciprocal",           _("Reciprocal"),               RELEASE_VERSION_0_61_08); // SVN r1238
153         ADD_VALUENODE(ValueNode_Duplicate,                "duplicate",            _("Duplicate"),                RELEASE_VERSION_0_61_08); // SVN r1267
154         ADD_VALUENODE(ValueNode_Integer,                  "fromint",              _("From Integer"),     RELEASE_VERSION_0_61_08); // SVN r1267
155         ADD_VALUENODE(ValueNode_Step,                     "step",                         _("Step"),                     RELEASE_VERSION_0_61_08); // SVN r1691
156         ADD_VALUENODE(ValueNode_BLineCalcWidth,   "blinecalcwidth",       _("BLine Width"),              RELEASE_VERSION_0_61_08); // SVN r1694
157
158         ADD_VALUENODE(ValueNode_VectorAngle,      "vectorangle",          _("Vector Angle"),     RELEASE_VERSION_0_61_09); // SVN r1880
159         ADD_VALUENODE(ValueNode_VectorLength,     "vectorlength",         _("Vector Length"),    RELEASE_VERSION_0_61_09); // SVN r1881
160
161 #undef ADD_VALUENODE
162 #undef ADD_VALUENODE2
163
164         return true;
165 }
166
167 bool
168 ValueNode::subsys_stop()
169 {
170         delete book_;
171 /*      if(global_value_node_map.size() || value_node_count)
172         {
173                 if(value_node_count)
174                         synfig::error("%d ValueNodes haven't been destroyed yet!",value_node_count);
175
176                 if(global_value_node_map.size()!=value_node_count)
177                         synfig::error("value node count mismatch! map.size()!=value_node_count (%d!=%d)",global_value_node_map.size(),value_node_count);
178
179                 GlobalValueNodeMap::iterator iter;
180                 for(iter=global_value_node_map.begin();iter!=global_value_node_map.end();++iter)
181                 {
182                         if(!iter->second->is_exported())
183                                 synfig::info(_("%s: count:%d name:%s type:%s"),
184                                         iter->first.get_string().c_str(),
185                                         iter->second->count(),
186                                         iter->second->get_name().c_str(),
187                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
188                                 );
189                         else
190                                 synfig::info(_("%s: id:%s count:%d name:%s type:%s"),
191                                         iter->first.get_string().c_str(),
192                                         iter->second->get_id().c_str(),
193                                         iter->second->count(),
194                                         iter->second->get_name().c_str(),
195                                         ValueBase::type_local_name(iter->second->get_type()).c_str()
196                                 );
197                 }
198         }
199 */
200         return true;
201 }
202
203 ValueNode::ValueNode(ValueBase::Type type):type(type)
204 {
205         value_node_count++;
206 }
207
208 LinkableValueNode::Book&
209 LinkableValueNode::book()
210 {
211         return *book_;
212 }
213
214 LinkableValueNode::Handle
215 LinkableValueNode::create(const String &name, const ValueBase& x)
216 {
217         if(!book().count(name))
218                 return 0;
219
220         if (!check_type(name, x.get_type()) &&
221                 // the Duplicate ValueNode is an exception - we don't want the
222                 // user creating it for themselves, so check_type() fails for
223                 // it even when it is valid
224                 !(name == "duplicate" && x.get_type() == ValueBase::TYPE_REAL))
225         {
226                 error(_("Bad type: ValueNode '%s' doesn't accept type '%s'"), book()[name].local_name.c_str(), ValueBase::type_local_name(x.get_type()).c_str());
227                 return 0;
228         }
229
230         return book()[name].factory(x);
231 }
232
233 bool
234 LinkableValueNode::check_type(const String &name, ValueBase::Type x)
235 {
236         if(!book().count(name) || !book()[name].check_type)
237                 return false;
238         return book()[name].check_type(x);
239 }
240
241 bool
242 LinkableValueNode::set_link(int i,ValueNode::Handle x)
243 {
244         ValueNode::Handle previous(get_link(i));
245
246         if(set_link_vfunc(i,x))
247         {
248                 if(previous)
249                         remove_child(previous.get());
250                 add_child(x.get());
251
252                 if(!x->is_exported() && get_parent_canvas())
253                 {
254                         x->set_parent_canvas(get_parent_canvas());
255                 }
256                 changed();
257                 return true;
258         }
259         return false;
260 }
261
262 ValueNode::LooseHandle
263 LinkableValueNode::get_link(int i)const
264 {
265         return get_link_vfunc(i);
266 }
267
268 void
269 LinkableValueNode::unlink_all()
270 {
271         for(int i=0;i<link_count();i++)
272         {
273                 ValueNode::LooseHandle value_node(get_link(i));
274                 if(value_node)
275                         value_node->parent_set.erase(this);
276         }
277 }
278
279 ValueNode::~ValueNode()
280 {
281         value_node_count--;
282
283         begin_delete();
284 }
285
286 void
287 ValueNode::on_changed()
288 {
289         etl::loose_handle<Canvas> parent_canvas = get_parent_canvas();
290         if(parent_canvas)
291                 do                                              // signal to all the ancestor canvases
292                         parent_canvas->signal_value_node_changed()(this);
293                 while (parent_canvas = parent_canvas->parent());
294         else if(get_root_canvas())
295                 get_root_canvas()->signal_value_node_changed()(this);
296
297         Node::on_changed();
298 }
299
300 int
301 ValueNode::replace(etl::handle<ValueNode> x)
302 {
303         if(x.get()==this)
304                 return 0;
305
306         while(parent_set.size())
307         {
308                 (*parent_set.begin())->add_child(x.get());
309                 (*parent_set.begin())->remove_child(this);
310                 //x->parent_set.insert(*parent_set.begin());
311                 //parent_set.erase(parent_set.begin());
312         }
313         int r(RHandle(this).replace(x));
314         x->changed();
315         return r;
316 }
317
318 void
319 ValueNode::set_id(const String &x)
320 {
321         if(name!=x)
322         {
323                 name=x;
324                 signal_id_changed_();
325         }
326 }
327
328 String
329 ValueNode::get_description(bool show_exported_name)const
330 {
331         String ret(_("ValueNode"));
332
333         if (dynamic_cast<const LinkableValueNode*>(this))
334                 return (dynamic_cast<const LinkableValueNode*>(this))->get_description(-1, show_exported_name);
335
336         if (show_exported_name && !is_exported())
337                 show_exported_name = false;
338
339         if (show_exported_name)
340                 ret += strprintf(" (%s)", get_id().c_str());
341
342         return ret;
343 }
344
345 ValueNodeList::ValueNodeList():
346         placeholder_count_(0)
347 {
348 }
349
350 bool
351 ValueNodeList::count(const String &id)const
352 {
353         const_iterator iter;
354
355         if(id.empty())
356                 return false;
357
358         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
359                 ;
360
361         if(iter==end())
362                 return false;
363
364         return true;
365 }
366
367 ValueNode::Handle
368 ValueNodeList::find(const String &id)
369 {
370         iterator iter;
371
372         if(id.empty())
373                 throw Exception::IDNotFound("Empty ID");
374
375         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
376                 ;
377
378         if(iter==end())
379                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
380
381         return *iter;
382 }
383
384 ValueNode::ConstHandle
385 ValueNodeList::find(const String &id)const
386 {
387         const_iterator iter;
388
389         if(id.empty())
390                 throw Exception::IDNotFound("Empty ID");
391
392         for(iter=begin();iter!=end() && id!=(*iter)->get_id();++iter)
393                 ;
394
395         if(iter==end())
396                 throw Exception::IDNotFound("ValueNode in ValueNodeList: "+id);
397
398         return *iter;
399 }
400
401 ValueNode::Handle
402 ValueNodeList::surefind(const String &id)
403 {
404         if(id.empty())
405                 throw Exception::IDNotFound("Empty ID");
406
407         ValueNode::Handle value_node;
408
409         try
410         {
411                 value_node=find(id);
412         }
413         catch(Exception::IDNotFound)
414         {
415                 value_node=PlaceholderValueNode::create();
416                 value_node->set_id(id);
417                 push_back(value_node);
418                 placeholder_count_++;
419         }
420
421         return value_node;
422 }
423
424 bool
425 ValueNodeList::erase(ValueNode::Handle value_node)
426 {
427         assert(value_node);
428
429         iterator iter;
430
431         for(iter=begin();iter!=end();++iter)
432                 if(value_node.get()==iter->get())
433                 {
434                         std::list<ValueNode::RHandle>::erase(iter);
435                         if(PlaceholderValueNode::Handle::cast_dynamic(value_node))
436                                 placeholder_count_--;
437                         return true;
438                 }
439         return false;
440 }
441
442 bool
443 ValueNodeList::add(ValueNode::Handle value_node)
444 {
445         if(!value_node)
446                 return false;
447         if(value_node->get_id().empty())
448                 return false;
449
450         try
451         {
452                 ValueNode::RHandle other_value_node=find(value_node->get_id());
453                 if(PlaceholderValueNode::Handle::cast_dynamic(other_value_node))
454                 {
455                         other_value_node->replace(value_node);
456                         placeholder_count_--;
457                         return true;
458                 }
459
460                 return false;
461         }
462         catch(Exception::IDNotFound)
463         {
464                 push_back(value_node);
465                 return true;
466         }
467
468         return false;
469 }
470
471 void
472 ValueNodeList::audit()
473 {
474         iterator iter,next;
475
476         for(next=begin(),iter=next++;iter!=end();iter=next++)
477                 if(iter->count()==1)
478                         std::list<ValueNode::RHandle>::erase(iter);
479 }
480
481
482 String
483 PlaceholderValueNode::get_name()const
484 {
485         return "placeholder";
486 }
487
488 String
489 PlaceholderValueNode::get_local_name()const
490 {
491         return _("Placeholder");
492 }
493
494 ValueNode*
495 PlaceholderValueNode::clone(const GUID& deriv_guid)const
496 {
497         ValueNode* ret(new PlaceholderValueNode());
498         ret->set_guid(get_guid()^deriv_guid);
499         return ret;
500 }
501
502 PlaceholderValueNode::Handle
503 PlaceholderValueNode::create(ValueBase::Type type)
504 {
505         return new PlaceholderValueNode(type);
506 }
507
508 ValueBase
509 PlaceholderValueNode::operator()(Time /*t*/)const
510 {
511         assert(0);
512         return ValueBase();
513 }
514
515 PlaceholderValueNode::PlaceholderValueNode(ValueBase::Type type):
516         ValueNode(type)
517 {
518 }
519
520 ValueNode*
521 LinkableValueNode::clone(const GUID& deriv_guid)const
522 {
523         {
524                 ValueNode* x(find_value_node(get_guid()^deriv_guid).get());
525                 if(x)
526                         return x;
527         }
528
529         int i;
530         LinkableValueNode *ret=create_new();
531         ret->set_guid(get_guid()^deriv_guid);
532
533         for(i=0;i<link_count();i++)
534         {
535                 ValueNode::Handle link=get_link_vfunc(i);
536                 if(!link->is_exported())
537                 {
538                         ValueNode::LooseHandle value_node(find_value_node(link->get_guid()^deriv_guid));
539                         if(!value_node)
540                                 value_node=link->clone(deriv_guid);
541                         ret->set_link(i,value_node);
542                 }
543                 else
544                         ret->set_link(i,link);
545         }
546
547         return ret;
548 }
549
550 String
551 ValueNode::get_relative_id(etl::loose_handle<const Canvas> x)const
552 {
553         assert(is_exported());
554         assert(canvas_);
555
556         if(x.get()==canvas_.get())
557                 return get_id();
558
559         return canvas_->_get_relative_id(x)+':'+get_id();
560 }
561
562 void
563 ValueNode::set_parent_canvas(etl::loose_handle<Canvas> x)
564 {
565         canvas_=x; if(x) root_canvas_=x->get_root();
566 }
567
568 void
569 ValueNode::set_root_canvas(etl::loose_handle<Canvas> x)
570 {
571         root_canvas_=x->get_root();
572 }
573
574 void LinkableValueNode::get_times_vfunc(Node::time_set &set) const
575 {
576         ValueNode::LooseHandle  h;
577
578         int size = link_count();
579
580         //just add it to the set...
581         for(int i=0; i < size; ++i)
582         {
583                 h = get_link(i);
584
585                 if(h)
586                 {
587                         const Node::time_set &tset = h->get_times();
588                         set.insert(tset.begin(),tset.end());
589                 }
590         }
591 }
592
593 String
594 LinkableValueNode::get_description(int index, bool show_exported_name)const
595 {
596         String description;
597
598         if (index == -1)
599         {
600                 if (show_exported_name && is_exported())
601                         description += strprintf(" (%s)", get_id().c_str());
602         }
603         else
604         {
605                 description = String(":") + link_local_name(index);
606
607                 if (show_exported_name)
608                 {
609                         ValueNode::LooseHandle link(get_link(index));
610                         if (link->is_exported())
611                                 description += strprintf(" (%s)", link->get_id().c_str());
612                 }
613         }
614
615         const synfig::Node* node = this;
616         LinkableValueNode::ConstHandle parent_linkable_vn = 0;
617
618         // walk up through the valuenodes trying to find the layer at the top
619         while (!node->parent_set.empty() && !dynamic_cast<const Layer*>(node))
620         {
621                 LinkableValueNode::ConstHandle linkable_value_node(dynamic_cast<const LinkableValueNode*>(node));
622                 if (linkable_value_node)
623                 {
624                         String link;
625                         int cnt = linkable_value_node->link_count();
626                         for (int i = 0; i < cnt; i++)
627                                 if (linkable_value_node->get_link(i) == parent_linkable_vn)
628                                 {
629                                         link = String(":") + linkable_value_node->link_local_name(i);
630                                         break;
631                                 }
632
633                         description = linkable_value_node->get_local_name() + link + (parent_linkable_vn?">":"") + description;
634                 }
635                 node = *node->parent_set.begin();
636                 parent_linkable_vn = linkable_value_node;
637         }
638
639         Layer::ConstHandle parent_layer(dynamic_cast<const Layer*>(node));
640         if(parent_layer)
641         {
642                 String param;
643                 const Layer::DynamicParamList &dynamic_param_list(parent_layer->dynamic_param_list());
644                 // loop to find the parameter in the dynamic parameter list - this gives us its name
645                 for (Layer::DynamicParamList::const_iterator iter = dynamic_param_list.begin(); iter != dynamic_param_list.end(); iter++)
646                         if (iter->second == parent_linkable_vn)
647                                 param = String(":") + parent_layer->get_param_local_name(iter->first);
648                 description = strprintf("(%s)%s>%s",
649                                                                 parent_layer->get_non_empty_description().c_str(),
650                                                                 param.c_str(),
651                                                                 description.c_str());
652         }
653
654         return description;
655 }