Fix possible crash when right click on a Paste Canvas Layer that doesn't have a canva...
[synfig.git] / synfig-core / src / synfig / layer_bitmap.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file layer_bitmap.cpp
3 **      \brief Template Header
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **
10 **      This package is free software; you can redistribute it and/or
11 **      modify it under the terms of the GNU General Public License as
12 **      published by the Free Software Foundation; either version 2 of
13 **      the License, or (at your option) any later version.
14 **
15 **      This package is distributed in the hope that it will be useful,
16 **      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 **      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 **      General Public License for more details.
19 **      \endlegal
20 */
21 /* ========================================================================= */
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 "layer_bitmap.h"
33 #include "layer.h"
34 #include "time.h"
35 #include "string.h"
36 #include "vector.h"
37
38 #include "context.h"
39 #include "time.h"
40 #include "color.h"
41 #include "surface.h"
42 #include "renddesc.h"
43 #include "target.h"
44
45 #include "general.h"
46 #include "paramdesc.h"
47 #include <ETL/misc>
48
49 #endif
50
51 /* === U S I N G =========================================================== */
52
53 using namespace synfig;
54 using namespace std;
55 using namespace etl;
56
57 /* === G L O B A L S ======================================================= */
58
59 /* === P R O C E D U R E S ================================================= */
60
61 /* === M E T H O D S ======================================================= */
62
63 synfig::Layer_Bitmap::Layer_Bitmap():
64     Layer_Composite     (1.0,Color::BLEND_COMPOSITE),
65         tl                              (-0.5,0.5),
66         br                              (0.5,-0.5),
67         c                               (1),
68         surface                 (128,128),
69         trimmed                 (false),
70         gamma_adjust    (1.0)
71 {
72         Layer::Vocab voc(get_param_vocab());
73         Layer::fill_static(voc);
74         set_param_static("c", true);
75 }
76
77 bool
78 synfig::Layer_Bitmap::set_param(const String & param, ValueBase value)
79 {
80         IMPORT(tl);
81         IMPORT(br);
82         IMPORT(c);
83         if(param=="gamma_adjust"&& value.get_type()==ValueBase::TYPE_REAL)
84         {
85                 gamma_adjust=1.0/value.get(Real());
86                 //gamma_adjust.set_gamma(1.0/value.get(Real()));
87                 return true;
88         }
89
90         return Layer_Composite::set_param(param,value);
91 }
92
93 ValueBase
94 synfig::Layer_Bitmap::get_param(const String & param)const
95 {
96         EXPORT(tl);
97         EXPORT(br);
98         EXPORT(c);
99         if(param=="gamma_adjust")
100                 return 1.0/gamma_adjust;
101
102         if(param=="_width")
103         {
104                 if (trimmed) return int(width);
105                 return surface.get_w();
106         }
107         if(param=="_height")
108         {
109                 if (trimmed) return int(height);
110                 return surface.get_h();
111         }
112
113         return Layer_Composite::get_param(param);
114 }
115
116 Layer::Vocab
117 Layer_Bitmap::get_param_vocab()const
118 {
119         Layer::Vocab ret(Layer_Composite::get_param_vocab());
120
121         ret.push_back(ParamDesc("tl")
122                 .set_local_name(_("Top-Left"))
123                 .set_description(_("Upper left-hand Corner of image"))
124         );
125
126         ret.push_back(ParamDesc("br")
127                 .set_local_name(_("Bottom-Right"))
128                 .set_description(_("Lower right-hand Corner of image"))
129         );
130
131         ret.push_back(ParamDesc("c")
132                 .set_local_name(_("Interpolation"))
133                 .set_description(_("What type of interpolation to use"))
134                 .set_hint("enum")
135                 .add_enum_value(0,"nearest",_("Nearest Neighbor"))
136                 .add_enum_value(1,"linear",_("Linear"))
137                 .add_enum_value(2,"cosine",_("Cosine"))
138                 .add_enum_value(3,"cubic",_("Cubic"))
139         );
140
141         ret.push_back(ParamDesc("gamma_adjust")
142                 .set_local_name(_("Gamma Adjustment"))
143         );
144
145         return ret;
146 }
147
148 synfig::Layer::Handle
149 Layer_Bitmap::hit_check(synfig::Context context, const synfig::Point &pos)const
150 {
151         Point surface_pos;
152         surface_pos=pos-tl;
153
154         surface_pos[0]/=br[0]-tl[0];
155         if(surface_pos[0]<=1.0 && surface_pos[0]>=0.0)
156         {
157                 surface_pos[1]/=br[1]-tl[1];
158                 if(surface_pos[1]<=1.0 && surface_pos[1]>=0.0)
159                 {
160                         return const_cast<Layer_Bitmap*>(this);
161                 }
162         }
163
164         return context.hit_check(pos);
165 }
166
167 inline
168 const Color&
169 synfig::Layer_Bitmap::filter(Color& x)const
170 {
171         if(gamma_adjust!=1.0)
172         {
173                 x.set_r(powf((float)x.get_r(),gamma_adjust));
174                 x.set_g(powf((float)x.get_g(),gamma_adjust));
175                 x.set_b(powf((float)x.get_b(),gamma_adjust));
176         }
177         return x;
178 }
179
180 Color
181 synfig::Layer_Bitmap::get_color(Context context, const Point &pos)const
182 {
183         Point surface_pos;
184
185         if(!get_amount())
186                 return context.get_color(pos);
187
188         surface_pos=pos-tl;
189
190         surface_pos[0]/=br[0]-tl[0];
191         if(surface_pos[0]<=1.0 && surface_pos[0]>=0.0)
192         {
193                 surface_pos[1]/=br[1]-tl[1];
194                 if(surface_pos[1]<=1.0 && surface_pos[1]>=0.0)
195                 {
196                         if (trimmed)
197                         {
198                                 surface_pos[0]*=width;
199                                 surface_pos[1]*=height;
200
201                                 if (surface_pos[0] > left+surface.get_w() || surface_pos[0] < left || surface_pos[1] > top+surface.get_h() || surface_pos[1] < top)
202                                         return context.get_color(pos);
203
204                                 surface_pos[0] -= left;
205                                 surface_pos[1] -= top;
206                         }
207                         else
208                         {
209                                 surface_pos[0]*=surface.get_w();
210                                 surface_pos[1]*=surface.get_h();
211                         }
212
213                         Color ret(Color::alpha());
214
215                         switch(c)
216                         {
217                         case 6: // Undefined
218                         case 5: // Undefined
219                         case 4: // Undefined
220                         case 3: // Cubic
221                                 ret=surface.cubic_sample(surface_pos[0],surface_pos[1]);
222                                 break;
223
224                         case 2: // Cosine
225                                 ret=surface.cosine_sample(surface_pos[0],surface_pos[1]);
226                                 break;
227                         case 1: // Linear
228                                 ret=surface.linear_sample(surface_pos[0],surface_pos[1]);
229                                 break;
230                         case 0: // Nearest Neighbor
231                         default:
232                                 {
233                                         int x(min(surface.get_w()-1,max(0,round_to_int(surface_pos[0]))));
234                                         int y(min(surface.get_h()-1,max(0,round_to_int(surface_pos[1]))));
235                                         ret= surface[y][x];
236                                 }
237                         break;
238                         }
239
240                         ret=filter(ret);
241
242                         if(get_amount()==1 && get_blend_method()==Color::BLEND_STRAIGHT)
243                                 return ret;
244                         else
245                                 return Color::blend(ret,context.get_color(pos),get_amount(),get_blend_method());
246                 }
247         }
248
249         return context.get_color(pos);
250 }
251
252 bool
253 Layer_Bitmap::accelerated_render(Context context,Surface *out_surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)  const
254 {
255         int interp=c;
256         if(quality>=10)
257                 interp=0;
258         else if(quality>=5 && interp>1)
259                 interp=1;
260
261         // We can only handle NN and Linear at the moment
262         //if(interp>1)
263         //      return Layer_Composite::accelerated_render(context,out_surface,quality,renddesc,cb);
264
265         //if we don't actually have a valid surface just skip us
266         if(!surface.is_valid())
267         {
268                 // Render what is behind us
269                 return context.accelerated_render(out_surface,quality,renddesc,cb);
270         }
271
272         SuperCallback subcb(cb,1,10000,10001+renddesc.get_h());
273
274         if(     get_amount()==1 &&
275                 get_blend_method()==Color::BLEND_STRAIGHT &&
276                 !trimmed &&
277                 renddesc.get_tl()==tl &&
278                 renddesc.get_br()==br)
279         {
280                 // Check for the trivial case
281                 if(surface.get_w()==renddesc.get_w() && surface.get_h()==renddesc.get_h() && gamma_adjust==1.0f)
282                 {
283                         if(cb && !cb->amount_complete(0,100)) return false;
284                         *out_surface=surface;
285                         if(cb && !cb->amount_complete(100,100)) return false;
286                         return true;
287                 }
288                 out_surface->set_wh(renddesc.get_w(),renddesc.get_h());
289         }
290         else
291         {
292                 // Render what is behind us
293                 if(!context.accelerated_render(out_surface,quality,renddesc,&subcb))
294                         return false;
295         }
296
297         if(cb && !cb->amount_complete(10000,10001+renddesc.get_h())) return false;
298
299         Point   obr     = renddesc.get_br(),
300                         otl = renddesc.get_tl();
301
302         //Vector::value_type pw=renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
303         //Vector::value_type ph=renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
304
305         //A = representation of input (just tl,br)      //just a scaling right now
306         //B = representation of output (just tl,br)     //just a scaling right now
307         //sa = scaling for input (0,1) -> (0,w/h)
308         //sb = scaling for output (0,1) -> (0,w/h)
309
310         float   outwf = obr[0] - otl[0];
311         float   outhf = obr[1] - otl[1];
312
313         int             inw = surface.get_w();
314         int             inh = surface.get_h();
315
316         int             outw = renddesc.get_w();
317         int             outh = renddesc.get_h();
318
319         float   inwf, inhf;
320         Point   itl, ibr;
321
322         if (trimmed)
323         {
324                 inwf = (br[0] - tl[0])*surface.get_w()/width;
325                 inhf = (br[1] - tl[1])*surface.get_h()/height;
326                 itl = Point(tl[0] + (br[0]-tl[0])*left/width,
327                                         tl[1] + (br[1]-tl[1])*top/height);
328                 ibr = Point(tl[0] + (br[0]-tl[0])*(left+inw)/width,
329                                         tl[1] + (br[1]-tl[1])*(top+inh)/height);
330         }
331         else
332         {
333                 inwf = br[0] - tl[0];
334                 inhf = br[1] - tl[1];
335                 itl = tl;
336                 ibr = br;
337         }
338
339         //need to get the input coords in output space, so we can clip
340
341         //get the desired corners of the bitmap (in increasing order) in integers
342         //floating point corners
343         float x1f = (itl[0] - otl[0])*outw/outwf;
344         float x2f = (ibr[0] - otl[0])*outw/outwf;
345         float y1f = (itl[1] - otl[1])*outh/outhf;
346         float y2f = (ibr[1] - otl[1])*outh/outhf;
347
348         if(x1f > x2f) swap(x1f,x2f);
349         if(y1f > y2f) swap(y1f,y2f);
350
351         int x_start = max(0,(int)floor(x1f));   //probably floor
352         int x_end       = min(outw,(int)ceil(x2f));     //probably ceil
353         int y_start = max(0,(int)floor(y1f));   //probably floor
354         int y_end       = min(outh,(int)ceil(y2f));     //probably ceil
355
356         //need to get the x,y,dx,dy values from output space to input, so we can do fast interpolation
357
358         //get the starting position in input space... for interpolating
359
360         // in int -> out float:
361         // Sb(B^-1)A(Sa^-1) x
362         float inx_start = (((x_start/*+0.5f*/)*outwf/outw + otl[0]) - itl[0])*inw/inwf; //may want to bias this (center of pixel)???
363         float iny_start = (((y_start/*+0.5f*/)*outhf/outh + otl[1]) - itl[1])*inh/inhf; //may want to bias this (center of pixel)???
364
365         //calculate the delta values in input space for one pixel movement in output space
366         //same matrix but with a vector instead of a point...
367         float indx = outwf*(inw)/((outw)*inwf);         //translations died
368         float indy = outhf*(inh)/((outh)*inhf);         //translations died
369
370         //perhaps use a DDA algorithm... if faster...
371         //   will still want pixel fractions to be floating point since colors are
372
373         //synfig::info("xstart:%d ystart:%d xend:%d yend:%d",x_start,y_start,x_end,y_end);
374
375         //start drawing at the start of the bitmap (either origin or corner of input...)
376         //and get other info
377         Surface::alpha_pen pen(out_surface->get_pen(x_start,y_start));
378         pen.set_alpha(get_amount());
379         pen.set_blend_method(get_blend_method());
380
381         //check if we should use the downscale filtering
382         if(quality <= 7)
383         {
384                 //the stride of the value should be inverted because we want to downsample
385                 //when the stride is small, not big
386                 //int multw = (int)ceil(indx);
387                 //int multh = (int)ceil(indy);
388
389                 if(indx > 1.7 || indy > 1.7)
390                 {
391                         /*synfig::info("Decided to downsample? ratios - (%f,%f) -> (%d,%d)",
392                                                 indx, indy, multw, multh);      */
393
394                         //use sample rect here...
395
396                         float iny, inx;
397                         int x,y;
398
399                         //Point sample - truncate
400                         iny = iny_start;//+0.5f;
401                         for(y = y_start; y < y_end; ++y, pen.inc_y(), iny += indy)
402                         {
403                                 inx = inx_start;//+0.5f;
404                                 for(x = x_start; x < x_end; x++, pen.inc_x(), inx += indx)
405                                 {
406                                         Color rc = surface.sample_rect_clip(inx,iny,inx+indx,iny+indy);
407                                         pen.put_value(filter(rc));
408                                 }
409                                 pen.dec_x(x_end-x_start);
410                         }
411
412                         //Color c = (*out_surface)[0][0];
413                         //synfig::info("ValueBase of first pixel = (%f,%f,%f,%f)",c.get_r(),c.get_g(),c.get_b(),c.get_a());
414
415                         return true;
416                 }
417         }
418
419         //perform normal interpolation
420         if(interp==0)
421         {
422                 //synfig::info("Decided to do nearest neighbor");
423                 float iny, inx;
424                 int x,y;
425
426                 //Point sample - truncate
427                 iny = iny_start;//+0.5f;
428                 for(y = y_start; y < y_end; y++, pen.inc_y(), iny += indy)
429                 {
430                         inx = inx_start;//+0.5f;
431                         int yclamp = min(inh-1, max(0, round_to_int(iny)));
432                         for(x = x_start; x < x_end; x++, pen.inc_x(), inx += indx)
433                         {
434                                 int xclamp = min(inw-1, max(0, round_to_int(inx)));
435                                 Color c = filter(surface[yclamp][xclamp]);
436                                 pen.put_value(c); //must get rid of the clip
437                         }
438                         pen.dec_x(x_end-x_start);
439                 }
440         }
441         else
442         if(interp==1)
443         {
444                 //bilinear filtering
445
446                 //float         xmf,xpf,ymf,ypf;
447                 //int           xm,xp,ym,yp;
448                 float   inx,iny;
449                 int             x,y;
450
451                 //can probably buffer for x values...
452
453                 //loop and based on inx,iny sample input image
454                 iny = iny_start;
455                 for(y = y_start; y < y_end; y++, pen.inc_y(), iny += indy)
456                 {
457                         inx = inx_start;
458                         for(x = x_start; x < x_end; x++, pen.inc_x(), inx += indx)
459                         {
460                                 Color col(surface.linear_sample(inx,iny));
461                                 pen.put_value(filter(col));
462                         }
463                         pen.dec_x(x_end-x_start);
464
465                 }
466         }
467         else
468         if(interp==2)
469         {
470                 //cosine filtering
471
472                 //float         xmf,xpf,ymf,ypf;
473                 //int           xm,xp,ym,yp;
474                 float   inx,iny;
475                 int             x,y;
476
477                 //can probably buffer for x values...
478
479                 //loop and based on inx,iny sample input image
480                 iny = iny_start;
481                 for(y = y_start; y < y_end; y++, pen.inc_y(), iny += indy)
482                 {
483                         inx = inx_start;
484                         for(x = x_start; x < x_end; x++, pen.inc_x(), inx += indx)
485                         {
486                                 Color col(surface.cosine_sample(inx,iny));
487                                 pen.put_value(filter(col));
488                         }
489                         pen.dec_x(x_end-x_start);
490
491                 }
492         }
493         else
494         {
495                 //cubic filtering
496
497                 //float         xmf,xpf,ymf,ypf;
498                 //int           xm,xp,ym,yp;
499                 float   inx,iny;
500                 int             x,y;
501
502                 //can probably buffer for x values...
503
504                 //loop and based on inx,iny sample input image
505                 iny = iny_start;
506                 for(y = y_start; y < y_end; y++, pen.inc_y(), iny += indy)
507                 {
508                         inx = inx_start;
509                         for(x = x_start; x < x_end; x++, pen.inc_x(), inx += indx)
510                         {
511                                 Color col(surface.cubic_sample(inx,iny));
512                                 pen.put_value(filter(col));
513                         }
514                         pen.dec_x(x_end-x_start);
515
516                 }
517         }
518
519         return true;
520 }
521
522 Rect
523 Layer_Bitmap::get_bounding_rect()const
524 {
525         return Rect(tl,br);
526 }