1eea2e9f1b7de0870b028db935feed5d43931fa8
[synfig.git] / synfig-core / src / synfig / layer_pastecanvas.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file layer_pastecanvas.cpp
3 **      \brief Implementation of the "Paste Canvas" layer
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 #ifdef USING_PCH
27 #       include "pch.h"
28 #else
29 #ifdef HAVE_CONFIG_H
30 #       include <config.h>
31 #endif
32
33 #include "layer_pastecanvas.h"
34 #include "string.h"
35 #include "time.h"
36 #include "context.h"
37 #include "paramdesc.h"
38 #include "renddesc.h"
39 #include "surface.h"
40 #include "value.h"
41 #include "valuenode.h"
42 #include "canvas.h"
43
44 #endif
45
46 /* === U S I N G =========================================================== */
47
48 using namespace etl;
49 using namespace std;
50 using namespace synfig;
51
52 /* === M A C R O S ========================================================= */
53
54 #define MAX_DEPTH 10
55
56 // if this isn't defined, the 'dead heads' in examples/pirates.sifz don't render properly
57 #define SYNFIG_CLIP_PASTECANVAS
58
59 //#ifdef __APPLE__
60 //#undef SYNFIG_CLIP_PASTECANVAS
61 //#endif
62
63 /* === C L A S S E S ======================================================= */
64
65 class depth_counter     // Makes our recursive depth counter exception-safe
66 {
67         int *depth;
68 public:
69         depth_counter(int &x):depth(&x) { (*depth)++; }
70         ~depth_counter() { (*depth)--; }
71 };
72
73 /* === G L O B A L S ======================================================= */
74
75 SYNFIG_LAYER_INIT(Layer_PasteCanvas);
76 SYNFIG_LAYER_SET_NAME(Layer_PasteCanvas,"PasteCanvas"); // todo: use paste_canvas
77 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_PasteCanvas,N_("Paste Canvas"));
78 SYNFIG_LAYER_SET_CATEGORY(Layer_PasteCanvas,N_("Other"));
79 SYNFIG_LAYER_SET_VERSION(Layer_PasteCanvas,"0.1");
80 SYNFIG_LAYER_SET_CVS_ID(Layer_PasteCanvas,"$Id$");
81
82 /* === M E T H O D S ======================================================= */
83
84 Layer_PasteCanvas::Layer_PasteCanvas():
85         origin(0,0),
86         focus(0,0),
87         depth(0),
88         zoom(0),
89         time_offset(0),
90         extra_reference(false),
91         origin_static(false),
92         focus_static(false),
93         canvas_static(false),
94         zoom_static(false),
95         offset_static(false),
96         children_lock_static(true)
97 {
98         children_lock=false;
99         muck_with_time_=true;
100         curr_time=Time::begin();
101 }
102
103 Layer_PasteCanvas::~Layer_PasteCanvas()
104 {
105 /*      if(canvas)
106                 canvas->parent_set.erase(this);
107 */
108
109         //if(canvas)DEBUGINFO(strprintf("%d",canvas->count()));
110
111         set_sub_canvas(0);
112
113         //if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
114         //if(extra_reference)
115         //      canvas->unref();
116 }
117
118 String
119 Layer_PasteCanvas::get_local_name()const
120 {
121         if(!canvas)     return _("Pasted Canvas");
122         if(canvas->is_inline()) return _("Inline Canvas");
123         if(canvas->get_root()==get_canvas()->get_root()) return '[' + canvas->get_id() + ']';
124
125         return '[' + canvas->get_file_name() + ']';
126 }
127
128 Layer::Vocab
129 Layer_PasteCanvas::get_param_vocab()const
130 {
131         Layer::Vocab ret(Layer_Composite::get_param_vocab());
132
133         ret.push_back(ParamDesc("origin")
134                 .set_local_name(_("Origin"))
135                 .set_description(_("Point where you want the origin to be"))
136         );
137         ret.push_back(ParamDesc("canvas")
138                 .set_local_name(_("Canvas"))
139                 .set_description(_("Canvas to paste"))
140         );
141         ret.push_back(ParamDesc("zoom")
142                 .set_local_name(_("Zoom"))
143                 .set_description(_("Size of canvas"))
144         );
145
146         ret.push_back(ParamDesc("time_offset")
147                 .set_local_name(_("Time Offset"))
148         );
149
150         ret.push_back(ParamDesc("children_lock")
151                 .set_local_name(_("Children Lock"))
152         );
153
154         ret.push_back(ParamDesc("focus")
155                 .set_local_name(_("Focus Point"))
156                 .set_origin("origin")
157                 .set_connect("origin")
158                 .set_description(_("Point to remain fixed when zooming"))
159         //      .set_invisible_duck()
160         );
161
162         // optimize_layers() in canvas.cpp makes a new PasteCanvas layer
163         // and copies over the parameters of the old layer.  the
164         // 'curr_time' member wasn't being copied, so I've added it as a
165         // hidden, non critical parameter, and now it will be.  this
166         // allows a single exported subcanvas to be used more than once at
167         // a time, with different time offets in each.  see bug #1896557.
168         ret.push_back(ParamDesc("curr_time")
169                 .set_local_name(_("Current Time"))
170                 .not_critical()
171                 .hidden()
172         );
173
174         return ret;
175 }
176
177 bool
178 Layer_PasteCanvas::set_param(const String & param, const ValueBase &value)
179 {
180         IMPORT(origin);
181         IMPORT(focus);
182
183         // IMPORT(canvas);
184         if(param=="canvas" && value.same_type_as(Canvas::Handle()))
185         {
186                 set_sub_canvas(value.get(Canvas::Handle()));
187                 set_param_static(param, value.get_static());
188                 return true;
189         }
190         //! \todo this introduces bug 1844764 if enabled; it was introduced in r954.
191         // http://synfig.org/images/3/3d/Moving-waypoints.sifz is an
192         // example of an animation that has its waypoints displayed
193         // incorrectly without this fix; select the outer layer and drag
194         // the time slider.  The linear waypoints don't take effect until
195         // 5s, but the time slider appears to pass the first one at 3s.
196 #if 0
197         if (param=="time_offset" && value.same_type_as(time_offset))
198         {
199                 if (time_offset != value.get(Time()))
200                 {
201                         value.put(&time_offset);
202                         // notify that the time_offset has changed so we can update the
203                         // waypoint positions in parent layers
204                         changed();
205                 }
206                 return true;
207         }
208 #else
209         IMPORT(time_offset);
210 #endif
211
212         IMPORT(children_lock);
213         IMPORT(zoom);
214         IMPORT(curr_time);
215
216         return Layer_Composite::set_param(param,value);
217 }
218
219 void
220 Layer_PasteCanvas::set_sub_canvas(etl::handle<synfig::Canvas> x)
221 {
222         if(canvas && muck_with_time_)
223                 remove_child(canvas.get());
224
225         // if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
226         if (extra_reference)
227                 canvas->unref();
228
229         child_changed_connection.disconnect();
230
231         if (canvas != x) signal_subcanvas_changed()();
232
233         canvas=x;
234
235         /*if(canvas)
236                 child_changed_connection=canvas->signal_changed().connect(
237                         sigc::mem_fun(
238                                 *this,
239                                 &Layer_PasteCanvas::changed
240                         )
241                 );
242         */
243         if(canvas)
244                 bounds = ((canvas->get_context().get_full_bounding_rect() - focus) * exp(zoom) + origin + focus);
245
246         if(canvas && muck_with_time_)
247                 add_child(canvas.get());
248
249         if(canvas && (canvas->is_inline() || !get_canvas() || get_canvas()->get_root()!=canvas->get_root()))
250         {
251                 canvas->ref();
252                 extra_reference = true;
253         }
254         else
255                 extra_reference = false;
256
257         if(canvas)
258                 on_canvas_set();
259 }
260
261 // when a pastecanvas that contains another pastecanvas is copy/pasted
262 // from one document to another, only the outermost pastecanvas was
263 // getting its renddesc set to match that of its new parent.  this
264 // function is used to recurse through the pastecanvas copying its
265 // renddesc to any pastecanvases it contains (bug #2116947, svn r2200)
266 void
267 Layer_PasteCanvas::update_renddesc()
268 {
269         if(!get_canvas() || !canvas || !canvas->is_inline()) return;
270
271         canvas->rend_desc()=get_canvas()->rend_desc();
272         for (Context context = canvas->get_context(); !context->empty(); context++)
273         {
274                 etl::handle<Layer_PasteCanvas> paste = etl::handle<Layer_PasteCanvas>::cast_dynamic(*context);
275                 if (paste) paste->update_renddesc();
276         }
277 }
278
279 // This is called whenever the parent canvas gets set/changed
280 void
281 Layer_PasteCanvas::on_canvas_set()
282 {
283         if(get_canvas() && canvas && canvas->is_inline() && canvas->parent()!=get_canvas())
284         {
285                 canvas->set_inline(get_canvas());
286         }
287 }
288
289 ValueBase
290 Layer_PasteCanvas::get_param(const String& param)const
291 {
292         EXPORT(origin);
293         EXPORT(focus);
294         EXPORT(canvas);
295         EXPORT(zoom);
296         EXPORT(time_offset);
297         EXPORT(children_lock);
298         EXPORT(curr_time);
299
300         EXPORT_NAME();
301         EXPORT_VERSION();
302
303         return Layer_Composite::get_param(param);
304 }
305
306 void
307 Layer_PasteCanvas::set_time(Context context, Time time)const
308 {
309         if(depth==MAX_DEPTH)return;depth_counter counter(depth);
310         curr_time=time;
311
312         context.set_time(time);
313         if(canvas)
314         {
315                 canvas->set_time(time+time_offset);
316
317                 bounds=(canvas->get_context().get_full_bounding_rect()-focus)*exp(zoom)+origin+focus;
318         }
319         else
320                 bounds=Rect::zero();
321 }
322
323 synfig::Layer::Handle
324 Layer_PasteCanvas::hit_check(synfig::Context context, const synfig::Point &pos)const
325 {
326         if(depth==MAX_DEPTH)return 0;depth_counter counter(depth);
327
328         if (canvas) {
329                 Point target_pos=(pos-focus-origin)/exp(zoom)+focus;
330
331                 if(canvas && get_amount() && canvas->get_context().get_color(target_pos).get_a()>=0.25)
332                 {
333                         if(!children_lock)
334                         {
335                                 return canvas->get_context().hit_check(target_pos);
336                         }
337                         return const_cast<Layer_PasteCanvas*>(this);
338                 }
339         }
340         return context.hit_check(pos);
341 }
342
343 Color
344 Layer_PasteCanvas::get_color(Context context, const Point &pos)const
345 {
346         if(!canvas || !get_amount())
347                 return context.get_color(pos);
348
349         if(depth==MAX_DEPTH)return Color::alpha();depth_counter counter(depth);
350
351         Point target_pos=(pos-focus-origin)/exp(zoom)+focus;
352
353         return Color::blend(canvas->get_context().get_color(target_pos),context.get_color(pos),get_amount(),get_blend_method());
354 }
355
356
357 bool
358 Layer_PasteCanvas::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
359 {
360         if(cb && !cb->amount_complete(0,10000)) return false;
361
362         if(depth==MAX_DEPTH)
363                 // if we are at the extent of our depth,
364                 // then we should just return whatever is under us.
365                 return context.accelerated_render(surface,quality,renddesc,cb);
366
367         depth_counter counter(depth);
368
369         if(!canvas || !get_amount())
370                 return context.accelerated_render(surface,quality,renddesc,cb);
371
372         SuperCallback stageone(cb,0,4500,10000);
373         SuperCallback stagetwo(cb,4500,9000,10000);
374         SuperCallback stagethree(cb,9000,9999,10000);
375
376         RendDesc desc(renddesc);
377         Vector::value_type zoomfactor=1.0/exp(zoom);
378         desc.clear_flags();
379         desc.set_tl((desc.get_tl()-focus-origin)*zoomfactor+focus);
380         desc.set_br((desc.get_br()-focus-origin)*zoomfactor+focus);
381         desc.set_flags(RendDesc::PX_ASPECT);
382
383         if (is_solid_color() || context->empty())
384         {
385                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
386                 surface->clear();
387         }
388         else if (!context.accelerated_render(surface,quality,renddesc,&stageone))
389                 return false;
390
391         if(muck_with_time_ && curr_time!=Time::begin() /*&& canvas->get_time()!=curr_time+time_offset*/)
392                 canvas->set_time(curr_time+time_offset);
393
394         Color::BlendMethod blend_method(get_blend_method());
395         const Rect full_bounding_rect(canvas->get_context().get_full_bounding_rect());
396
397         bool blend_using_straight = false; // use 'straight' just for the central blit
398
399         // sometimes the user changes the parameters while we're
400         // rendering, causing our pasted canvas' bounding box to shrink
401         // and no longer overlap with our tile.  if that has happened,
402         // let's just stop now - we'll be refreshing soon anyway
403         //! \todo shouldn't a mutex ensure this isn't needed?
404         // http://synfig.org/images/d/d2/Bbox-change.sifz is an example
405         // that shows this happening - open the encapsulation, select the
406         // 'shade', and toggle the 'invert' parameter quickly.
407         // Occasionally you'll see:
408         //   error: Context::accelerated_render(): Layer "shade" threw a bad_alloc exception!
409         // where the shade layer tries to allocate itself a canvas of
410         // negative proportions, due to changing bounding boxes.
411         if (!etl::intersect(desc.get_rect(), full_bounding_rect))
412         {
413                 warning("%s:%d bounding box shrank while rendering?", __FILE__, __LINE__);
414                 return true;
415         }
416
417         // we have rendered what's under us, if necessary
418         if(context->empty())
419         {
420                 // if there's nothing under us, and we're blending 'onto', then we've finished
421                 if (Color::is_onto(blend_method)) return true;
422
423                 // there's nothing under us, so using straight blending is
424                 // faster than and equivalent to using composite, but we don't
425                 // want to blank the surrounding areas
426                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
427         }
428
429         if (!etl::intersect(context.get_full_bounding_rect(),(full_bounding_rect-focus)*exp(zoom)+origin+focus))
430         {
431                 // if there's no intersection between the context and our
432                 // surface, and we're rendering 'onto', then we're done
433                 if (Color::is_onto(blend_method) && !Color::is_straight(blend_method))
434                         return true;
435
436                 /* 'straight' is faster than 'composite' and has the same
437                  * effect if the affected area of the lower layer is
438                  * transparent;  however, if we're not clipping the blit to
439                  * just the bounding rectangle, the affected area is the whole
440                  * tile, so we can't use this optimisation.  if we are
441                  * clipping, then we can use 'straight' to blit the clipped
442                  * rectangle, but we shouldn't set blend_method to 'straight',
443                  * or the surrounding areas will be blanked, which we don't
444                  * want.
445                  */
446 #ifdef SYNFIG_CLIP_PASTECANVAS
447                 if (blend_method==Color::BLEND_COMPOSITE) blend_using_straight = true;
448 #endif  // SYNFIG_CLIP_PASTECANVAS
449         }
450
451 #ifdef SYNFIG_CLIP_PASTECANVAS
452         Rect area(desc.get_rect() & full_bounding_rect);
453
454         Point min(area.get_min());
455         Point max(area.get_max());
456
457         if (desc.get_tl()[0] > desc.get_br()[0]) swap(min[0], max[0]);
458         if (desc.get_tl()[1] > desc.get_br()[1]) swap(min[1], max[1]);
459
460         const int x(floor_to_int((min[0] - desc.get_tl()[0]) / desc.get_pw()));
461         const int y(floor_to_int((min[1] - desc.get_tl()[1]) / desc.get_ph()));
462         const int w( ceil_to_int((max[0] - desc.get_tl()[0]) / desc.get_pw()) - x);
463         const int h( ceil_to_int((max[1] - desc.get_tl()[1]) / desc.get_ph()) - y);
464
465         const int tw = desc.get_w();
466         const int th = desc.get_h();
467
468         desc.set_subwindow(x,y,w,h);
469
470         // \todo this used to also have "area.area()<=0.000001 || " - is it useful?
471         //               it was causing bug #1809480 (Zoom in beyond 8.75 in nested canvases fails)
472         if(desc.get_w()==0 || desc.get_h()==0)
473         {
474                 if(cb && !cb->amount_complete(10000,10000)) return false;
475                 return true;
476         }
477
478         // SYNFIG_CLIP_PASTECANVAS is defined, so we are only touching the
479         // pixels within the affected rectangle.  If the blend method is
480         // 'straight', then we need to blend transparent pixels with the
481         // clipped areas of this tile, because with the 'straight' blend
482         // method, even transparent pixels have an effect on the layers below
483         if (Color::is_straight(blend_method))
484         {
485                 Surface clearsurface;
486
487                 Surface::alpha_pen apen(surface->begin());
488                 apen.set_alpha(get_amount());
489
490                 // the area we're about to blit is transparent, so it doesn't
491                 // matter whether we use 'straight' or 'straight onto' here
492                 if (blend_method == Color::BLEND_ALPHA_BRIGHTEN)
493                         apen.set_blend_method(blend_method);
494                 else
495                         apen.set_blend_method(Color::BLEND_STRAIGHT);
496
497                 /* This represents the area we're pasting into the tile,
498                  * within the tile as a whole.  Areas (A), (B), (C) and (D)
499                  * need blending with the underlying context if they're not
500                  * zero-sized:
501                  *
502                  *               0         x             x+w      tw
503                  *       0       +------------------------+
504                  *               |                                                |
505                  *               |                      (A)                       |
506                  *               |                                                |
507                  *       y       | - - +----------+ - - - |
508                  *               |         |              |               |
509                  *               | (C) |  w by h  |      (D)  |
510                  *               |         |              |               |
511                  *       y+h | - - +----------+ - - - |
512                  *               |                                                |
513                  *               |                      (B)                       |
514                  *               |                                                |
515                  *       tw      +------------------------+
516                  */
517
518                 if (y > 0)                              // draw the full-width strip above the rectangle (A)
519                 { apen.move_to(0,0);   clearsurface.set_wh(tw,y);        clearsurface.clear(); clearsurface.blit_to(apen); }
520                 if (y+h < th)                   // draw the full-width strip below the rectangle (B)
521                 { apen.move_to(0,y+h); clearsurface.set_wh(tw,th-(y+h)); clearsurface.clear(); clearsurface.blit_to(apen); }
522                 if (x > 0)                              // draw the box directly left of the rectangle (C)
523                 { apen.move_to(0,y);   clearsurface.set_wh(x,h);         clearsurface.clear(); clearsurface.blit_to(apen); }
524                 if (x+w < tw)                   // draw the box directly right of the rectangle (D)
525                 { apen.move_to(x+w,y); clearsurface.set_wh(tw-(x+w),h);  clearsurface.clear(); clearsurface.blit_to(apen); }
526         }
527 #endif  // SYNFIG_CLIP_PASTECANVAS
528
529         // render the canvas to be pasted onto pastesurface
530         Surface pastesurface;
531         if(!canvas->get_context().accelerated_render(&pastesurface,quality,desc,&stagetwo))
532                 return false;
533
534 #ifdef SYNFIG_CLIP_PASTECANVAS
535         Surface::alpha_pen apen(surface->get_pen(x,y));
536 #else  // SYNFIG_CLIP_PASTECANVAS
537         Surface::alpha_pen apen(surface->begin());
538 #endif  // SYNFIG_CLIP_PASTECANVAS
539
540         apen.set_alpha(get_amount());
541         apen.set_blend_method(blend_using_straight ? Color::BLEND_STRAIGHT : blend_method);
542         pastesurface.blit_to(apen);
543
544         if(cb && !cb->amount_complete(10000,10000)) return false;
545
546         return true;
547 }
548
549 Rect
550 Layer_PasteCanvas::get_bounding_rect()const
551 {
552         return bounds;
553 }
554
555 void Layer_PasteCanvas::get_times_vfunc(Node::time_set &set) const
556 {
557         Node::time_set tset;
558         if(canvas) tset = canvas->get_times();
559
560         Node::time_set::iterator i = tset.begin(), end = tset.end();
561
562         //Make sure we offset the time...
563         //! \todo: SOMETHING STILL HAS TO BE DONE WITH THE OTHER DIRECTION
564         //                 (recursing down the tree needs to take this into account too...)
565         for(; i != end; ++i)
566                 set.insert(*i
567 #ifdef ADJUST_WAYPOINTS_FOR_TIME_OFFSET // see node.h
568                                    - time_offset
569 #endif
570                         );
571
572         Layer::get_times_vfunc(set);
573 }
574
575
576 bool
577 Layer_PasteCanvas::set_param_static(const String &param, const bool x)
578 {
579         SET_STATIC(origin, x)
580         SET_STATIC(focus, x)
581         SET_STATIC(canvas, x)
582         SET_STATIC(zoom, x)
583         SET_STATIC(time_offset, x)
584         SET_STATIC(children_lock, x)
585
586         return Layer_Composite::set_param_static(param, x);
587 }
588
589
590 bool
591 Layer_PasteCanvas::get_param_static(const String &param) const
592 {
593         GET_STATIC(origin)
594         GET_STATIC(focus)
595         GET_STATIC(canvas)
596         GET_STATIC(zoom)
597         GET_STATIC(time_offset)
598         GET_STATIC(children_lock)
599
600         return Layer_Composite::get_param_static(param);
601 }