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