Use LinkableValueNode members functions when possible in the derived valuenodes.
[synfig.git] / src / synfig / layer_shape.cpp
1 /* === S Y N F I G ========================================================= */
2 /*!     \file layer_shape.cpp
3 **      \brief Implementation of the "Shape" layer
4 **
5 **      $Id$
6 **
7 **      \legal
8 **      Copyright (c) 2002-2005 Robert B. Quattlebaum Jr., Adrian Bentley
9 **      Copyright (c) 2007 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_shape.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 "float.h"
43 #include "blur.h"
44
45 #include "curve_helper.h"
46
47 #include <vector>
48
49 #include <deque>
50
51 #endif
52
53 /* === U S I N G =========================================================== */
54
55 using namespace synfig;
56 using namespace std;
57 using namespace etl;
58
59 /* === G L O B A L S ======================================================= */
60
61 SYNFIG_LAYER_INIT(Layer_Shape);
62 SYNFIG_LAYER_SET_NAME(Layer_Shape,"shape");
63 SYNFIG_LAYER_SET_LOCAL_NAME(Layer_Shape,N_("Shape"));
64 SYNFIG_LAYER_SET_CATEGORY(Layer_Shape,N_("Internal"));
65 SYNFIG_LAYER_SET_VERSION(Layer_Shape,"0.1");
66 SYNFIG_LAYER_SET_CVS_ID(Layer_Shape,"$Id$");
67
68 #define EPSILON 1e-12
69
70 template < class T >
71 inline bool IsZero(const T &n)
72 {
73         return (n < EPSILON) && (n > -EPSILON);
74 }
75
76 /* === C L A S S E S ======================================================= */
77
78 //Assumes 64 byte aligned structures if at all
79 struct Primitive
80 {
81         int             operation;
82         int             number;
83
84         //Point data[0];
85
86         enum Operations
87         {
88                 NONE = -1,
89                 MOVE_TO = 0,            //(x,y)+                                after first point treated as line_to
90                 CLOSE,                          //                                              NOT RUNLENGTH enabled
91                 LINE_TO,                        //(x,y)+                                continuous func
92                 CONIC_TO,                       //(x1,y1,x,y)+                  "   "
93                 CONIC_TO_SMOOTH,        //(x,y)+                                "   "
94                 CUBIC_TO,                       //(x1,y1,x2,y2,x,y)+    "   "
95                 CUBIC_TO_SMOOTH,        //(x2,y2,x,y)+                  "   "
96                 END
97         };
98 };
99
100 //******** CURVE FUNCTIONS *****************
101 const int       MAX_SUBDIVISION_SIZE = 64;
102 const int       MIN_SUBDIVISION_DRAW_LEVELS = 4;
103
104 static void Subd_Conic_Stack(Point *arc)
105 {
106         /*
107
108         b0
109         *               0+1 a
110         b1 b    *               1+2*1+2 a
111         *               1+2     b       *
112         b2              *
113         *
114
115         0.1.2 ->        0.1 2 3.4
116
117         */
118
119         Real a,b;
120
121
122         arc[4][0] = arc[2][0];
123         b = arc[1][0];
124
125         a = arc[1][0] = (arc[0][0] + b)/2;
126         b = arc[3][0] = (arc[4][0] + b)/2;
127         arc[2][0] = (a + b)/2;
128
129
130         arc[4][1] = arc[2][1];
131         b = arc[1][1];
132
133         a = arc[1][1] = (arc[0][1] + b)/2;
134         b = arc[3][1] = (arc[4][1] + b)/2;
135         arc[2][1] = (a + b)/2;
136
137         /* //USING SIMD
138
139         arc[4] = arc[2];
140
141         arc[3] = (arc[2] + arc[1])/2;
142         arc[1] = (arc[0] + arc[1])/2;
143
144         arc[2] = (arc[1] + arc[3])/2;
145
146         */
147
148 }
149
150 static void Subd_Cubic_Stack(Point *arc)
151 {
152         Real a,b,c;
153
154         /*
155
156         b0
157         *               0+1 a
158         b1 b    *               1+2*1+2 a
159         *               1+2     b       *                       0+3*1+3*2+3
160         b2 c    *               1+2*2+2 b       *
161         *               2+3     c       *
162         b3              *
163         *
164
165         0.1 2.3 ->      0.1 2 3 4 5.6
166
167         */
168
169         arc[6][0] = arc[3][0];
170
171         b = arc[1][0];
172         c = arc[2][0];
173
174         a = arc[1][0] = (arc[0][0] + b)/2;
175         b = (b + c)/2;
176         c = arc[5][0] = (arc[6][0] + c)/2;
177
178         a = arc[2][0] = (a + b)/2;
179         b = arc[4][0] = (b + c)/2;
180
181         arc[3][0] = (a + b)/2;
182
183
184         arc[6][1] = arc[3][1];
185
186         b = arc[1][1];
187         c = arc[2][1];
188
189         a = arc[1][1] = (arc[0][1] + b)/2;
190         b = (b + c)/2;
191         c = arc[5][1] = (arc[6][1] + c)/2;
192
193         a = arc[2][1] = (a + b)/2;
194         b = arc[4][1] = (b + c)/2;
195
196         arc[3][1] = (a + b)/2;
197
198         /* //USING SIMD
199         temp
200
201         arc[6] = arc[3];
202
203         //backwards to avoid overwriting
204         arc[5] = (arc[2] + arc[3])/2;
205         temp = (arc[1] + arc[2])/2;
206         arc[1] = (arc[0] + arc[1])/2;
207
208         arc[4] = (temp + arc[5])/2;
209         arc[2] = (arc[1] + temp)/2;
210
211         arc[3] = (arc[2] + arc[4])/2;
212
213         */
214 }
215
216 //************** PARAMETRIC RENDERER SUPPORT STRUCTURES ****************
217
218 // super segment
219 struct MonoSegment
220 {
221         Rect    aabb;
222         int             ydir;
223         vector<Point>   pointlist;
224
225         MonoSegment(int dir = 0, Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
226         {
227                 aabb.minx = x0;
228                 aabb.maxx = x1;
229                 aabb.miny = y0;
230                 aabb.maxy = y1;
231
232                 ydir = dir;
233         }
234
235         int intersect(Real x,Real y) const
236         {
237                 if((y < aabb.miny+EPSILON) || (y > aabb.maxy) || (x < aabb.minx)) return 0;
238                 if(x > aabb.maxx) return ydir;
239
240                 //int i = 0;
241                 //int size = pointlist.size();
242                 //vector<Point>::const_iterator end = pointlist.end();
243                 vector<Point>::const_iterator p = pointlist.begin();
244
245                 //assumes that the rect culled away anything that would be beyond the edges
246                 if(ydir > 0)
247                 {
248                         while(y > (*++p)[1]);
249                 }
250                 else
251                 {
252                         while(y < (*++p)[1]);
253                 }
254
255                 //for the loop to break there must have been a slope (straight line would do nothing)
256                 //vector<Point>::const_iterator p1 = p-1;
257                 Real dy = p[-1][1] - p[0][1];
258                 Real dx = p[-1][0] - p[0][0];
259
260                 assert(dy != 0);
261
262                 Real xi = p[0][0] + (y - p[0][1]) * dx / dy;
263                 return (x > xi)*ydir;
264         }
265 };
266
267 struct CurveArray
268 {
269         Rect    aabb;   //not necessarily as effective - can only reject values
270         vector<Point>   pointlist;      //run length - p0, p1, p2, p3 = p10, p11, p12, p13 = p20 ...
271         vector<char>    degrees;
272
273         CurveArray(Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
274         {
275                 aabb.set(x0,y0,x1,y1);
276         }
277
278         void reset(Real x0 = 0, Real x1 = 0, Real y0 = 0, Real y1 = 0)
279         {
280                 aabb.set(x0,y0,x1,y1);
281                 pointlist.clear();
282                 degrees.clear();
283         }
284
285         int size () const
286         {
287                 return degrees.size();
288         }
289
290         void Start(Point m)
291         {
292                 reset(m[0],m[0],m[1],m[1]);
293                 pointlist.push_back(m);
294         }
295
296         void AddCubic(Point p1, Point p2, Point dest)
297         {
298                 aabb.expand(p1[0],p1[1]);
299                 aabb.expand(p2[0],p2[1]);
300                 aabb.expand(dest[0],dest[1]);
301
302                 pointlist.push_back(p1);
303                 pointlist.push_back(p2);
304                 pointlist.push_back(dest);
305
306                 degrees.push_back(3);
307         }
308
309         void AddConic(Point p1, Point dest)
310         {
311                 aabb.expand(p1[0],p1[1]);
312                 aabb.expand(dest[0],dest[1]);
313
314                 pointlist.push_back(p1);
315                 pointlist.push_back(dest);
316
317                 degrees.push_back(2);
318         }
319
320         static int intersect_conic(Real x, Real y, Point *p, int /*level*/ = 0)
321         {
322                 Real ymin,ymax,xmin,xmax;
323                 int intersects = 0;
324
325                 //sort the overall curve ys - degenerate detection
326                 ymin = min(p[0][1],p[2][1]);
327                 ymax = max(p[0][1],p[2][1]);
328
329                 xmin = min(min(p[0][0],p[1][0]),p[2][0]);
330                 xmax = max(max(p[0][0],p[1][0]),p[2][0]);
331
332                 //to the left, to the right and out of range y, or completely out of range y
333                 if( x < xmin ) return 0;
334                 if( x > xmax  && (y > ymax || y < ymin) ) return 0;
335                 if( (y > ymax && y > p[1][1]) || (y < ymin && y < p[1][1]) ) return 0;
336
337                 //degenerate line max
338                 if(ymin == ymax == p[1][1])
339                         return 0;
340
341                 //degenerate accept - to the right and crossing the base line
342                 if(x > xmax)
343                 {
344                         return (y <= ymax && y >= ymin);
345                 }
346
347                 //solve for curve = y
348
349                 //real roots:
350                 //0 roots       - 0 intersection
351                 //1 root        - get x, and figure out x
352                 //2 roots (non-double root)     - get 2 xs, and count xs to the left
353
354                 //for conic we can assume 1 intersection for monotonic curve
355                 Real    a = p[2][1] -   2*p[1][1] +     p[0][1],
356                                 b =                     2*p[1][1] -     2*p[0][1],
357                                 c =                                                     p[0][1]         -       y;
358
359                 Real t1 = -1, t2 = -1;
360
361                 if(a == 0)
362                 {
363                         //linear - easier :)
364                         if(b == 0) return 0; //may not need this check
365
366                         t1 = - c / b; //bt + c = 0 solved
367                 }else
368                 {
369                         //2 degree polynomial
370                         Real b2_4ac = b*b - 4*a*c;
371
372                         //if there are double/no roots - no intersections (in real #s that is)
373                         if(b2_4ac <= 0)
374                         {
375                                 return 0;
376                         }
377
378                         b2_4ac = sqrt(b2_4ac);
379
380                         t1 = (-b - b2_4ac) / 2*a,
381                         t2 = (-b + b2_4ac) / 2*a;
382                 }
383
384                 //calculate number of intersections
385                 if(t1 >= 0 && t1 <= 1)
386                 {
387                         const Real t = t1;
388                         const Real invt = 1 - t;
389
390                         //find x val and it counts if it's to the left of the point
391                         const Real xi = invt*invt*p[0][0] + 2*t*invt*p[1][0] + t*t*p[2][0];
392                         const Real dy_t = 2*a*t + b;
393
394                         if(dy_t)
395                         {
396                                 intersects += (x >= xi) * ( dy_t > 0 ? 1 : -1);
397                         }
398                 }
399
400                 if(t2 >= 0 && t2 <= 1)
401                 {
402                         const Real t = t2;
403                         const Real invt = 1 - t;
404
405                         //find x val and it counts if it's to the left of the point
406                         const Real xi = invt*invt*p[0][0] + 2*t*invt*p[1][0] + t*t*p[2][0];
407                         const Real dy_t = 2*a*t + b;
408
409                         if(dy_t)
410                         {
411                                 intersects += (x >= xi) * ( dy_t > 0 ? 1 : -1);
412                         }
413                 }
414
415                 return intersects;
416         }
417
418         static int      quadratic_eqn(Real a, Real b, Real c, Real *t0, Real *t1)
419         {
420                 const Real b2_4ac = b*b - 4*a*c;
421
422                 //degenerate reject (can't take sqrt)
423                 if(b2_4ac < 0)
424                 {
425                         return 0;
426                 }
427
428                 const Real sqrtb2_4ac = sqrt(b2_4ac);
429                 const Real signb = b < 0 ? -1 : 1;
430                 const Real q = - 0.5 * (b + signb * sqrtb2_4ac);
431
432                 *t0 = q/a;
433                 *t1 = c/q;
434
435                 return sqrtb2_4ac == 0 ? 1 : 2;
436         }
437
438         //Newton-Raphson root polishing (we don't care about bounds, assumes very near the desired root)
439         static Real polish_cubicroot(Real a, Real b, Real c, Real d, Real t, Real *dpdt)
440         {
441                 const Real cn[4] = {a,b,c,d};
442                 Real p,dp,newt,oldpmag=FLT_MAX;
443
444                 //eval cubic eqn and its derivative
445                 for(;;)
446                 {
447                         p = cn[0]*t + cn[1];
448                         dp = cn[0];
449
450                         for(int i = 2; i < 4; i++)
451                         {
452                                 dp = p + dp*t;
453                                 p = cn[i] + p*t;
454                         }
455
456                         if(dp == 0)
457                         {
458                                 synfig::warning("polish_cubicroot: Derivative should not vanish!!!");
459                                 return t;
460                         }
461
462                         newt = t - p/dp;
463
464                         if(newt == t || fabs(p) >= oldpmag)
465                         {
466                                 *dpdt = dp;
467                                 return t;
468                         }
469
470                         t = newt;
471                         oldpmag = fabs(p);
472                 }
473         }
474
475         static int intersect_cubic(Real x, Real y, Point *p, int /*level*/ = 0)
476         {
477                 const Real INVALIDROOT = -FLT_MAX;
478                 Real ymin,ymax,xmin,xmax;
479                 Real ymin2,ymax2,ymintot,ymaxtot;
480                 int intersects = 0;
481
482                 //sort the overall curve ys and xs - degenerate detection
483
484                 //open span for the two end points
485                 ymin = min(p[0][1],p[3][1]);
486                 ymax = max(p[0][1],p[3][1]);
487
488                 //other points etc.
489                 ymin2 = min(p[1][1],p[2][1]);
490                 ymax2 = max(p[1][1],p[2][1]);
491
492                 ymintot = min(ymin,ymin2);
493                 ymaxtot = max(ymax,ymax2);
494
495                 //the entire curve control polygon is in this x range
496                 xmin = min(min(p[0][0],p[1][0]),min(p[2][0],p[3][0]));
497                 xmax = max(max(p[0][0],p[1][0]),max(p[2][0],p[3][0]));
498
499                 //outside all y boundaries (no intersect)
500                 if( (y > ymaxtot) || (y < ymintot) ) return 0;
501
502                 //left of curve (no intersect)
503                 if(x < xmin) return 0;
504
505                 //right of curve (and outside base range)
506                 if( x > xmax )
507                 {
508                         if( (y > ymax) || (y < ymin) ) return 0;
509
510                         //degenerate accept - to the right and inside the [ymin,ymax] range (already rejected if out of range)
511                         const Real n = p[3][1] - p[0][1];
512
513                         //extract the sign from the value (we need valid data)
514                         return n < 0 ? -1 : 1;
515                 }
516
517                 //degenerate horizontal line max -- doesn't happen enough to check for
518                 if( ymintot == ymaxtot ) return 0;
519
520                 //calculate roots:
521                 // can have 0,1,2, or 3 real roots
522                 // if any of them are double then reject the two...
523
524                 // y-coefficients for f_y(t) - y = 0
525                 Real    a = p[3][1]     - 3*p[2][1]     + 3*p[1][1]     -   p[0][1],
526                                 b =                       3*p[2][1]     - 6*p[1][1]     + 3*p[0][1],
527                                 c =                                                       3*p[1][1]     - 3*p[0][1],
528                                 d =                                                                             p[0][1] - y;
529
530                 Real    ax = p[3][0]    - 3*p[2][0]     + 3*p[1][0]     -   p[0][0],
531                                 bx =                      3*p[2][0]     - 6*p[1][0]     + 3*p[0][0],
532                                 cx =                                              3*p[1][0]     - 3*p[0][0],
533                                 dx =                                                                            p[0][0];
534
535                 Real t1 = INVALIDROOT, t2 = INVALIDROOT, t3 = INVALIDROOT, t, dydt;
536
537                 if(a == 0)
538                 {
539                         //only 2nd degree
540                         if(b == 0)
541                         {
542                                 //linear
543                                 if(c == 0) return 0;
544
545                                 t1 = - d / c; //equation devolved into: ct + d = 0 - solve...
546                         }else
547                         {
548                                 //0 roots = 0 intersections, 1 root = 2 intersections at the same place (0 effective)
549                                 if(quadratic_eqn(a,b,c,&t1,&t2) != 2) return 0;
550                         }
551                 }else
552                 {
553                         //cubic - sigh....
554
555                         //algorithm courtesy of Numerical Recipes in C (algorithm copied from pg. 184/185)
556                         Real an = b / a,
557                                  bn = c / a,
558                                  cn = d / a;
559
560                         //if cn is 0 (or really really close), then we can simplify this...
561                         if(IsZero(cn))
562                         {
563                                 t3 = 0;
564
565                                 //0 roots = 0 intersections, 1 root = 2 intersections at the same place (0 effective)
566                                 if(quadratic_eqn(a,b,c,&t1,&t2) != 2)
567                                 {
568                                         t1 = t2 = INVALIDROOT;
569                                 }
570                         }
571                         else
572                         {
573                                 //otherwise run the normal cubic root equation
574                                 Real Q = (an*an - 3.0*bn) / 9.0;
575                                 Real R = ((2.0*an*an - 9.0*bn)*an + 27.0*cn)/54.0;
576
577                                 if(R*R < Q*Q*Q)
578                                 {
579                                         Real theta = acos(R / sqrt(Q*Q*Q));
580
581                                         t1 = -2.0*sqrt(Q)*cos(theta/3) - an/3.0;
582                                         t2 = -2.0*sqrt(Q)*cos((theta+2*PI)/3.0) - an/3.0;
583                                         t3 = -2.0*sqrt(Q)*cos((theta-2*PI)/3.0) - an/3.0;
584
585                                         //don't need to reorder,l just need to eliminate double/triple roots
586                                         //if(t3 == t2 && t1 == t2) t2 = t3 = INVALIDROOT;
587                                         if(t3 == t2) t2 = t3 = INVALIDROOT;
588                                         if(t1 == t2) t1 = t2 = INVALIDROOT;
589                                         if(t1 == t3) t1 = t3 = INVALIDROOT;
590                                 }else
591                                 {
592                                         Real signR = R < 0 ? -1 : 1;
593                                         Real A = - signR * pow(signR*R + sqrt(R*R - Q*Q*Q),1/3.0);
594
595                                         Real B;
596                                         if(A == 0) B = 0;
597                                         else B = Q / A;
598
599                                         //single real root in this case
600                                         t1 = (A + B) - an/3.0;
601                                 }
602                         }
603                 }
604
605                 //if(t1 != INVALIDROOT)
606                 {
607                         t = t1;//polish_cubicroot(a,b,c,d,t1,&dydt);
608                         if(t >= 0 && t < 1)
609                         {
610                                 //const Real invt = 1 - t;
611
612                                 //find x val and it counts if it's to the left of the point
613                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
614                                 dydt = (3*a*t + 2*b)*t + c;
615
616                                 if(dydt)
617                                 {
618                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
619                                 }
620                         }
621                 }
622
623                 //if(t2 != INVALIDROOT)
624                 {
625                         t = t2;//polish_cubicroot(a,b,c,d,t2,&dydt);
626                         if(t >= 0 && t < 1)
627                         {
628                                 //const Real invt = 1 - t;
629
630                                 //find x val and it counts if it's to the left of the point
631                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
632                                 dydt = (3*a*t + 2*b)*t + c;
633
634                                 if(dydt)
635                                 {
636                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
637                                 }
638                         }
639                 }
640
641                 //if(t3 != INVALIDROOT)
642                 {
643                         t = t3;//polish_cubicroot(a,b,c,d,t3,&dydt);
644                         if(t >= 0 && t < 1)
645                         {
646                                 //const Real invt = 1 - t;
647
648                                 //find x val and it counts if it's to the left of the point
649                                 const Real xi = ((ax*t + bx)*t + cx)*t + dx;
650                                 dydt = (3*a*t + 2*b)*t + c;
651
652                                 if(dydt)
653                                 {
654                                         intersects += (x >= xi) * ( dydt > 0 ? 1 : -1);
655                                 }
656                         }
657                 }
658
659                 return intersects;
660         }
661
662         int intersect(Real x,Real y, Point *table) const
663         {
664                 if((y < aabb.miny) || (y > aabb.maxy) || (x < aabb.minx)) return 0;
665
666                 int i, curdeg, intersects = 0;
667                 const int numcurves = degrees.size();
668
669                 vector<Point>::const_iterator   p = pointlist.begin();
670
671                 for(i=0; i < numcurves; i++)
672                 {
673                         curdeg = degrees[i];
674
675                         switch(curdeg)
676                         {
677                                 case 2:
678                                 {
679                                         table[0] = *p++;
680                                         table[1] = *p++;
681                                         table[2] = *p;  //we want to include the last point for the next curve
682
683                                         intersects += intersect_conic(x,y,table);
684
685                                         break;
686                                 }
687
688                                 case 3:
689                                 {
690                                         table[0] = *p++;
691                                         table[1] = *p++;
692                                         table[2] = *p++;
693                                         table[3] = *p;  //we want to include the last point for the next curve
694
695                                         intersects += intersect_cubic(x,y,table);
696
697                                         break;
698                                 }
699
700                                 default:
701                                 {
702                                         warning("Invalid degree (%d) inserted into the list (index: %d)\n", curdeg, i);
703                                         return 0;
704                                 }
705                         }
706                 }
707
708                 return intersects;
709         }
710 };
711
712 struct Layer_Shape::Intersector
713 {
714         Rect    aabb;
715
716         //! true iff aabb hasn't been initialized yet
717         bool    initaabb;
718
719         int     flags;
720
721         enum IntersectorFlags
722         {
723                 NotClosed = 0x8000
724         };
725
726         enum PrimitiveType
727         {
728                 TYPE_NONE = 0,
729                 TYPE_LINE,
730                 TYPE_CURVE
731         };
732
733         Real    cur_x,cur_y;
734         Real    close_x,close_y;
735
736         vector<MonoSegment>                             segs;   //monotonically increasing
737         vector<CurveArray>                              curves; //big array of consecutive curves
738
739         int                                                             prim;
740         Vector                                                  tangent;
741
742         Intersector()
743         {
744                 clear();
745         }
746
747         bool notclosed()
748         {
749                 return (flags & NotClosed) || (cur_x != close_x) || (cur_y != close_y);
750         }
751
752         void move_to(Real x, Real y)
753         {
754                 close();
755
756                 close_x = cur_x = x;
757                 close_y = cur_y = y;
758
759                 tangent[0] = tangent[1] = 0;
760
761                 if(initaabb)
762                 {
763                         aabb.set_point(x,y);
764                         initaabb = false;
765                 }else aabb.expand(x,y);
766
767                 prim = TYPE_NONE;
768         }
769
770         void line_to(Real x, Real y)
771         {
772                 int dir = (y > cur_y)*1 + (-1)*(y < cur_y);
773
774                 //check for context (if not line start a new segment)
775                 //if we're not in line mode (covers 0 set case), or if directions are different (not valid for 0 direction)
776                 if(prim != TYPE_LINE || (dir && segs.back().ydir != dir))
777                 {
778                         MonoSegment             seg(dir,x,x,y,y);
779
780                         seg.aabb.expand(cur_x,cur_y);
781                         seg.pointlist.push_back(Point(cur_x,cur_y));
782                         seg.pointlist.push_back(Point(x,y));
783                         segs.push_back(seg);
784                 }
785                 //add to the last segment, because it works
786                 else
787                 {
788                         segs.back().pointlist.push_back(Point(x,y));
789                         segs.back().aabb.expand(x,y);
790                 }
791
792
793
794                 cur_x = x;
795                 cur_y = y;
796                 aabb.expand(x,y); //expand the entire thing's bounding box
797
798                 tangent[0] = x - cur_x;
799                 tangent[1] = x - cur_y;
800
801                 flags |= NotClosed;
802                 prim = TYPE_LINE;
803         }
804
805         void conic_to_smooth(Real x, Real y)
806         {
807                 const Real x1 = tangent[0]/2.0 + cur_x;
808                 const Real y1 = tangent[1]/2.0 + cur_y;
809
810                 conic_to(x1,y1,x,y);
811         }
812
813         void conic_to(Real x1, Real y1, Real x, Real y)
814         {
815                 //if we're not already a curve start one
816                 if(prim != TYPE_CURVE)
817                 {
818                         CurveArray      c;
819
820                         c.Start(Point(cur_x,cur_y));
821                         c.AddConic(Point(x1,y1),Point(x,y));
822
823                         curves.push_back(c);
824                 }else
825                 {
826                         curves.back().AddConic(Point(x1,y1),Point(x,y));
827                 }
828
829                 cur_x = x;
830                 cur_y = y;
831
832                 aabb.expand(x1,y1);
833                 aabb.expand(x,y);
834
835                 tangent[0] = 2*(x - x1);
836                 tangent[1] = 2*(y - y1);
837
838                 flags |= NotClosed;
839                 prim = TYPE_CURVE;
840         }
841
842         void curve_to_smooth(Real x2, Real y2, Real x, Real y)
843         {
844                 Real x1 = tangent[0]/3.0 + cur_x;
845                 Real y1 = tangent[1]/3.0 + cur_y;
846
847                 curve_to(x1,y1,x2,y2,x,y);
848         }
849
850         void curve_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
851         {
852                 //if we're not already a curve start one
853                 if(prim != TYPE_CURVE)
854                 {
855                         CurveArray      c;
856
857                         c.Start(Point(cur_x,cur_y));
858                         c.AddCubic(Point(x1,y1),Point(x2,y2),Point(x,y));
859
860                         curves.push_back(c);
861                 }else
862                 {
863                         curves.back().AddCubic(Point(x1,y1),Point(x2,y2),Point(x,y));
864                 }
865
866                 cur_x = x;
867                 cur_y = y;
868
869                 //expand bounding box around ALL of it
870                 aabb.expand(x1,y1);
871                 aabb.expand(x2,y2);
872                 aabb.expand(x,y);
873
874                 tangent[0] = 3*(x - x2);
875                 tangent[1] = 3*(y - y2);
876
877                 flags |= NotClosed;
878                 prim = TYPE_CURVE;
879         }
880
881         void close()
882         {
883                 if(flags & NotClosed)
884                 {
885                         if(cur_x != close_x || cur_y != close_y)
886                         {
887                                 line_to(close_x,close_y);
888                         }
889
890                         flags &= ~NotClosed;
891                 }
892         }
893
894         //assumes the line to count the intersections with is (-1,0)
895         int     intersect (Real x, Real y) const
896         {
897                 int inter = 0;
898                 unsigned int i;
899                 vector<MonoSegment>::const_iterator s = segs.begin();
900                 vector<CurveArray>::const_iterator c = curves.begin();
901
902                 Point   memory[3*MAX_SUBDIVISION_SIZE + 1];
903
904                 for(i = 0; i < segs.size(); i++,s++)
905                 {
906                         inter += s->intersect(x,y);
907                 }
908
909                 for(i=0; i < curves.size(); i++,c++)
910                         inter += c->intersect(x,y,memory);
911
912                 return inter;
913         }
914
915         //intersect an arbitrary line
916         //int   intersect (Real x, Real y, Real vx, Real vy) {return 0;}
917
918         void clear()
919         {
920                 segs.clear();
921                 curves.clear();
922
923                 flags = 0;
924                 cur_x = cur_y = close_x = close_y = 0;
925                 prim = TYPE_NONE;
926                 tangent[0] = tangent[1] = 0;
927                 initaabb = true;
928         }
929 };
930
931 //*********** SCANLINE RENDERER SUPPORT STRUCTURES ***************
932 struct PenMark
933 {
934         int y,x;
935         Real cover,area;
936
937         PenMark(){}
938         PenMark(int xin, int yin, Real c, Real a)
939                 :y(yin),x(xin),cover(c),area(a) {}
940
941         void set(int xin, int yin, Real c, Real a)      { y = yin; x = xin; cover = c; area = a;        }
942
943         void setcoord(int xin, int yin)                         { y = yin; x = xin;     }
944
945         void setcover(Real c, Real a)                           { cover = c; area = a; }
946         void addcover(Real c, Real a)                           { cover += c; area += a; }
947
948         bool operator < (const PenMark &rhs) const
949         {
950                 return y == rhs.y ? x < rhs.x : y < rhs.y;
951         }
952 };
953
954 typedef rect<int> ContextRect;
955
956 class Layer_Shape::PolySpan
957 {
958 public:
959         typedef deque<PenMark>  cover_array;
960
961         Point                   arc[3*MAX_SUBDIVISION_SIZE + 1];
962
963         cover_array             covers;
964         PenMark                 current;
965
966         int                             open_index;
967
968         //ending position of last primitive
969         Real                    cur_x;
970         Real                    cur_y;
971
972         //starting position of current primitive list
973         Real                    close_x;
974         Real                    close_y;
975
976         //flags for the current segment
977         int                             flags;
978
979         //the window that will be drawn (used for clipping)
980         ContextRect             window;
981
982         //for assignment to flags value
983         enum PolySpanFlags
984         {
985                 NotSorted = 0x8000,
986                 NotClosed =     0x4000
987         };
988
989         //default constructor - 0 everything
990         PolySpan() :current(0,0,0,0),flags(NotSorted)
991         {
992                 cur_x = cur_y = close_x = close_y = 0;
993                 open_index = 0;
994         }
995
996         bool notclosed() const
997         {
998                 return (flags & NotClosed) || (cur_x != close_x) || (cur_y != close_y);
999         }
1000
1001         //0 out all the variables involved in processing
1002         void clear()
1003         {
1004                 covers.clear();
1005                 cur_x = cur_y = close_x = close_y = 0;
1006                 open_index = 0;
1007                 current.set(0,0,0,0);
1008                 flags = NotSorted;
1009         }
1010
1011         //add the current cell, but only if there is information to add
1012         void addcurrent()
1013         {
1014                 if(current.cover || current.area)
1015                 {
1016                         covers.push_back(current);
1017                 }
1018         }
1019
1020         //move to the next cell (cover values 0 initially), keeping the current if necessary
1021         void move_pen(int x, int y)
1022         {
1023                 if(y != current.y || x != current.x)
1024                 {
1025                         addcurrent();
1026                         current.set(x,y,0,0);
1027                 }
1028         }
1029
1030         //close the primitives with a line (or rendering will not work as expected)
1031         void close()
1032         {
1033                 if(flags & NotClosed)
1034                 {
1035                         if(cur_x != close_x || cur_y != close_y)
1036                         {
1037                                 line_to(close_x,close_y);
1038                                 addcurrent();
1039                                 current.setcover(0,0);
1040                         }
1041                         flags &= ~NotClosed;
1042                 }
1043         }
1044
1045         // Not recommended - destroys any separation of spans currently held
1046         void merge_all()
1047         {
1048                 sort(covers.begin(),covers.end());
1049                 open_index = 0;
1050         }
1051
1052         //will sort the marks if they are not sorted
1053         void sort_marks()
1054         {
1055                 if(flags & NotSorted)
1056                 {
1057                         //only sort the open index
1058                         addcurrent();
1059                         current.setcover(0,0);
1060
1061                         sort(covers.begin() + open_index,covers.end());
1062                         flags &= ~NotSorted;
1063                 }
1064         }
1065
1066         //encapsulate the current sublist of marks (used for drawing)
1067         void encapsulate_current()
1068         {
1069                 //sort the current list then reposition the open list section
1070                 sort_marks();
1071                 open_index = covers.size();
1072         }
1073
1074         //move to start a new primitive list (enclose the last primitive if need be)
1075         void move_to(Real x, Real y)
1076         {
1077                 close();
1078                 if(isnan(x))x=0;
1079                 if(isnan(y))y=0;
1080                 move_pen((int)floor(x),(int)floor(y));
1081                 close_y = cur_y = y;
1082                 close_x = cur_x = x;
1083         }
1084
1085         //primitive_to functions
1086         void line_to(Real x, Real y);
1087         void conic_to(Real x1, Real y1, Real x, Real y);
1088         void cubic_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y);
1089
1090         void draw_scanline(int y, Real x1, Real y1, Real x2, Real y2);
1091         void draw_line(Real x1, Real y1, Real x2, Real y2);
1092
1093         Real ExtractAlpha(Real area, WindingStyle winding_style)
1094         {
1095                 if (area < 0)
1096                         area = -area;
1097
1098                 if (winding_style == WINDING_NON_ZERO)
1099                 {
1100                         // non-zero winding style
1101                         if (area > 1)
1102                                 return 1;
1103                 }
1104                 else // if (winding_style == WINDING_EVEN_ODD)
1105                 {
1106                         // even-odd winding style
1107                         while (area > 1)
1108                                 area -= 2;
1109
1110                         // want pyramid like thing
1111                         if (area < 0)
1112                                 area = -area;
1113                 }
1114
1115                 return area;
1116         }
1117 };
1118
1119 /* === M E T H O D S ======================================================= */
1120
1121 Layer_Shape::Layer_Shape(const Real &a, const Color::BlendMethod m):
1122         Layer_Composite (a,m),
1123         edge_table              (new Intersector),
1124         color                   (Color::black()),
1125         offset                  (0,0),
1126         invert                  (false),
1127         antialias               (true),
1128         blurtype                (Blur::FASTGAUSSIAN),
1129         feather                 (0),
1130         winding_style   (WINDING_NON_ZERO),
1131         bytestream              (0),
1132         lastbyteop              (Primitive::NONE),
1133         lastoppos               (-1)
1134 {
1135 }
1136
1137 Layer_Shape::~Layer_Shape()
1138 {
1139         delete edge_table;
1140 }
1141
1142 void
1143 Layer_Shape::clear()
1144 {
1145         edge_table->clear();
1146         bytestream.clear();
1147 }
1148
1149 bool
1150 Layer_Shape::set_param(const String & param, const ValueBase &value)
1151 {
1152         IMPORT(color);
1153         IMPORT(offset);
1154         IMPORT(invert);
1155         IMPORT(antialias);
1156         IMPORT(feather);
1157         IMPORT(blurtype);
1158         IMPORT(winding_style);
1159
1160         return Layer_Composite::set_param(param,value);
1161 }
1162
1163 ValueBase
1164 Layer_Shape::get_param(const String &param)const
1165 {
1166         EXPORT(color);
1167         EXPORT(offset);
1168         EXPORT(invert);
1169         EXPORT(antialias);
1170         EXPORT(feather);
1171         EXPORT(blurtype);
1172         EXPORT(winding_style);
1173
1174         EXPORT_NAME();
1175         EXPORT_VERSION();
1176
1177         return Layer_Composite::get_param(param);
1178 }
1179
1180 Layer::Vocab
1181 Layer_Shape::get_param_vocab()const
1182 {
1183         Layer::Vocab ret(Layer_Composite::get_param_vocab());
1184
1185         ret.push_back(ParamDesc("color")
1186                 .set_local_name(_("Color"))
1187                 .set_description(_("Layer_Shape Color"))
1188         );
1189         ret.push_back(ParamDesc("offset")
1190                 .set_local_name(_("Position"))
1191         );
1192         ret.push_back(ParamDesc("invert")
1193                 .set_local_name(_("Invert"))
1194         );
1195         ret.push_back(ParamDesc("antialias")
1196                 .set_local_name(_("Antialiasing"))
1197         );
1198         ret.push_back(ParamDesc("feather")
1199                 .set_local_name(_("Feather"))
1200                 .set_is_distance()
1201         );
1202         ret.push_back(ParamDesc("blurtype")
1203                 .set_local_name(_("Type of Feather"))
1204                 .set_description(_("Type of feathering to use"))
1205                 .set_hint("enum")
1206                 .add_enum_value(Blur::BOX,"box",_("Box Blur"))
1207                 .add_enum_value(Blur::FASTGAUSSIAN,"fastgaussian",_("Fast Gaussian Blur"))
1208                 .add_enum_value(Blur::CROSS,"cross",_("Cross-Hatch Blur"))
1209                 .add_enum_value(Blur::GAUSSIAN,"gaussian",_("Gaussian Blur"))
1210                 .add_enum_value(Blur::DISC,"disc",_("Disc Blur"))
1211         );
1212         ret.push_back(ParamDesc("winding_style")
1213                 .set_local_name(_("Winding Style"))
1214                 .set_description(_("Winding style to use"))
1215                 .set_hint("enum")
1216                 .add_enum_value(WINDING_NON_ZERO,"nonzero",_("Non Zero"))
1217                 .add_enum_value(WINDING_EVEN_ODD,"evenodd",_("Even/Odd"))
1218         );
1219
1220         return ret;
1221 }
1222
1223 synfig::Layer::Handle
1224 Layer_Shape::hit_check(synfig::Context context, const synfig::Point &p)const
1225 {
1226         Point pos(p-offset);
1227
1228         int intercepts = edge_table->intersect(pos[0],pos[1]);
1229
1230         // If we have an odd number of intercepts, we are inside.
1231         // If we have an even number of intercepts, we are outside.
1232         bool intersect = ((!!intercepts) ^ invert);
1233
1234         if(get_amount() == 0 || get_blend_method() == Color::BLEND_ALPHA_OVER)
1235         {
1236                 intersect = false;
1237         }
1238
1239         if(intersect)
1240         {
1241                 synfig::Layer::Handle tmp;
1242                 if(get_blend_method()==Color::BLEND_BEHIND && (tmp=context.hit_check(p)))
1243                         return tmp;
1244                 if(Color::is_onto(get_blend_method()))
1245                 {
1246                         //if there's something in the lower layer then we're set...
1247                         if(!context.hit_check(p).empty())
1248                                 return const_cast<Layer_Shape*>(this);
1249                 }else if(get_blend_method() == Color::BLEND_ALPHA_OVER)
1250                 {
1251                         synfig::info("layer_shape::hit_check - we've got alphaover");
1252                         //if there's something in the lower layer then we're set...
1253                         if(color.get_a() < 0.1 && get_amount() > .9)
1254                         {
1255                                 synfig::info("layer_shape::hit_check - can see through us... so nothing");
1256                                 return Handle();
1257                         }else return context.hit_check(p);
1258                 }else
1259                         return const_cast<Layer_Shape*>(this);
1260         }
1261
1262         return context.hit_check(p);
1263 }
1264
1265 Color
1266 Layer_Shape::get_color(Context context, const Point &p)const
1267 {
1268         Point pp = p;
1269
1270         if(feather)
1271                 pp = Blur(feather,feather,blurtype)(p);
1272
1273         Point pos(pp-offset);
1274
1275         int intercepts = edge_table->intersect(pos[0],pos[1]);
1276
1277         // If we have an odd number of intercepts, we are inside.
1278         // If we have an even number of intercepts, we are outside.
1279         bool intersect = ((!!intercepts) ^ invert);
1280
1281         if(!intersect)
1282                 return context.get_color(pp);
1283
1284         //Ok, we're inside... bummmm ba bum buM...
1285         if(get_blend_method() == Color::BLEND_STRAIGHT && get_amount() == 1)
1286                 return color;
1287         else
1288                 return Color::blend(color,context.get_color(p),get_amount(),get_blend_method());
1289 }
1290
1291 //************** SCANLINE RENDERING *********************
1292 void Layer_Shape::PolySpan::line_to(Real x, Real y)
1293 {
1294         Real n[4];
1295         bool afterx = false;
1296
1297         const Real xin(x), yin(y);
1298
1299         Real dx = x - cur_x;
1300         Real dy = y - cur_y;
1301
1302         //CLIP IT!!!!
1303         try {
1304         //outside y - ignore entirely
1305         if(      (cur_y >= window.maxy && y >= window.maxy)
1306            ||(cur_y <  window.miny && y <  window.miny) )
1307         {
1308                 cur_x = x;
1309                 cur_y = y;
1310         }
1311         else //not degenerate - more complicated
1312         {
1313                 if(dy > 0) //be sure it's not tooooo small
1314                 {
1315                         // cur_y ... window.miny ... window.maxy ... y
1316
1317                         //initial degenerate - initial clip
1318                         if(cur_y < window.miny)
1319                         {
1320                                 //new clipped start point (must also move pen)
1321                                 n[2] = cur_x + (window.miny - cur_y) * dx / dy;
1322
1323                                 cur_x = n[2];
1324                                 cur_y = window.miny;
1325                                 move_pen((int)floor(cur_x),window.miny);
1326                         }
1327
1328                         //generate data for the ending clipped info
1329                         if(y > window.maxy)
1330                         {
1331                                 //initial line to intersection (and degenerate)
1332                                 n[2] = x + (window.maxy - y) * dx / dy;
1333
1334                                 //intersect coords
1335                                 x = n[2];
1336                                 y = window.maxy;
1337                         }
1338                 }
1339                 else
1340                 {
1341                         //initial degenerate - initial clip
1342                         if(cur_y > window.maxy)
1343                         {
1344                                 //new clipped start point (must also move pen)
1345                                 n[2] = cur_x + (window.maxy - cur_y) * dx / dy;
1346
1347                                 cur_x = n[2];
1348                                 cur_y = window.maxy;
1349                                 move_pen((int)floor(cur_x),window.maxy);
1350                         }
1351
1352                         //generate data for the ending clipped info
1353                         if(y < window.miny)
1354                         {
1355                                 //initial line to intersection (and degenerate)
1356                                 n[2] = x + (window.miny - y) * dx / dy;
1357
1358                                 //intersect coords
1359                                 x = n[2];
1360                                 y = window.miny;
1361                         }
1362                 }
1363
1364                 //all degenerate - but require bounded clipped values
1365                 if(   (cur_x >= window.maxx && x >= window.maxx)
1366                         ||(cur_x <  window.minx && x <  window.minx) )
1367                 {
1368                         //clip both vertices - but only needed in the x direction
1369                         cur_x = max(cur_x,      (Real)window.minx);
1370                         cur_x = min(cur_x,      (Real)window.maxx);
1371
1372                         //clip the dest values - y is already clipped
1373                         x = max(x,(Real)window.minx);
1374                         x = min(x,(Real)window.maxx);
1375
1376                         //must start at new point...
1377                         move_pen((int)floor(cur_x),(int)floor(cur_y));
1378
1379                         draw_line(cur_x,cur_y,x,y);
1380
1381                         cur_x = xin;
1382                         cur_y = yin;
1383                 }
1384                 else
1385                 {
1386                         //clip x
1387                         if(dx > 0)
1388                         {
1389                                 //initial degenerate - initial clip
1390                                 if(cur_x < window.minx)
1391                                 {
1392                                         //need to draw an initial segment from clippedx,cur_y to clippedx,intersecty
1393                                         n[2] = cur_y + (window.minx - cur_x) * dy / dx;
1394
1395                                         move_pen(window.minx,(int)floor(cur_y));
1396                                         draw_line(window.minx,cur_y,window.minx,n[2]);
1397
1398                                         cur_x = window.minx;
1399                                         cur_y = n[2];
1400                                 }
1401
1402                                 //generate data for the ending clipped info
1403                                 if(x > window.maxx)
1404                                 {
1405                                         //initial line to intersection (and degenerate)
1406                                         n[2] = y + (window.maxx - x) * dy / dx;
1407
1408                                         n[0] = window.maxx;
1409                                         n[1] = y;
1410
1411                                         //intersect coords
1412                                         x = window.maxx;
1413                                         y = n[2];
1414                                         afterx = true;
1415                                 }
1416                         }else
1417                         {
1418                                 //initial degenerate - initial clip
1419                                 if(cur_x > window.maxx)
1420                                 {
1421                                         //need to draw an initial segment from clippedx,cur_y to clippedx,intersecty
1422                                         n[2] = cur_y + (window.maxx - cur_x) * dy / dx;
1423
1424                                         move_pen(window.maxx,(int)floor(cur_y));
1425                                         draw_line(window.maxx,cur_y,window.maxx,n[2]);
1426
1427                                         cur_x = window.maxx;
1428                                         cur_y = n[2];
1429                                 }
1430
1431                                 //generate data for the ending clipped info
1432                                 if(x < window.minx)
1433                                 {
1434                                         //initial line to intersection (and degenerate)
1435                                         n[2] = y + (window.minx - x) * dy / dx;
1436
1437                                         n[0] = window.minx;
1438                                         n[1] = y;
1439
1440                                         //intersect coords
1441                                         x = window.minx;
1442                                         y = n[2];
1443                                         afterx = true;
1444                                 }
1445                         }
1446
1447                         move_pen((int)floor(cur_x),(int)floor(cur_y));
1448                         //draw the relevant line (clipped)
1449                         draw_line(cur_x,cur_y,x,y);
1450
1451                         if(afterx)
1452                         {
1453                                 draw_line(x,y,n[0],n[1]);
1454                         }
1455
1456                         cur_x = xin;
1457                         cur_y = yin;
1458                 }
1459         }
1460         } catch(...) { synfig::error("line_to: cur_x=%f, cur_y=%f, x=%f, y=%f", cur_x, cur_y, x, y); throw; }
1461
1462         flags |= NotClosed|NotSorted;
1463 }
1464
1465 static inline bool clip_conic(const Point *const p, const ContextRect &r)
1466 {
1467         const Real minx = min(min(p[0][0],p[1][0]),p[2][0]);
1468         const Real miny = min(min(p[0][1],p[1][1]),p[2][1]);
1469         const Real maxx = max(max(p[0][0],p[1][0]),p[2][0]);
1470         const Real maxy = max(max(p[0][1],p[1][1]),p[2][1]);
1471
1472         return  (minx > r.maxx) ||
1473                         (maxx < r.minx) ||
1474                         (miny > r.maxy) ||
1475                         (maxy < r.miny);
1476 }
1477
1478 static inline bool clip_cubic(const Point *const p, const ContextRect &r)
1479 {
1480         /*const Real minx = min(min(p[0][0],p[1][0]),min(p[2][0],p[3][0]));
1481         const Real miny = min(min(p[0][1],p[1][1]),min(p[2][1],p[3][1]));
1482         const Real maxx = max(max(p[0][0],p[1][0]),max(p[2][0],p[3][1]));
1483         const Real maxy = max(max(p[0][1],p[1][1]),max(p[2][1],p[3][1]));
1484
1485         return  (minx > r.maxx) ||
1486                         (maxx < r.minx) ||
1487                         (miny > r.maxy) ||
1488                         (maxy < r.miny);*/
1489
1490         return  ((p[0][0] > r.maxx) && (p[1][0] > r.maxx) && (p[2][0] > r.maxx) && (p[3][0] > r.maxx)) ||
1491                         ((p[0][0] < r.minx) && (p[1][0] < r.minx) && (p[2][0] < r.minx) && (p[3][0] < r.minx)) ||
1492                         ((p[0][1] > r.maxy) && (p[1][1] > r.maxy) && (p[2][1] > r.maxy) && (p[3][1] > r.maxy)) ||
1493                         ((p[0][1] < r.miny) && (p[1][1] < r.miny) && (p[2][1] < r.miny) && (p[3][1] < r.miny));
1494 }
1495
1496 static inline Real max_edges_cubic(const Point *const p)
1497 {
1498         const Real x1 = p[1][0] - p[0][0];
1499         const Real y1 = p[1][1] - p[0][1];
1500
1501         const Real x2 = p[2][0] - p[1][0];
1502         const Real y2 = p[2][1] - p[1][1];
1503
1504         const Real x3 = p[3][0] - p[2][0];
1505         const Real y3 = p[3][1] - p[2][1];
1506
1507         const Real d1 = x1*x1 + y1*y1;
1508         const Real d2 = x2*x2 + y2*y2;
1509         const Real d3 = x3*x3 + y3*y3;
1510
1511         return max(max(d1,d2),d3);
1512 }
1513
1514 static inline Real max_edges_conic(const Point *const p)
1515 {
1516         const Real x1 = p[1][0] - p[0][0];
1517         const Real y1 = p[1][1] - p[0][1];
1518
1519         const Real x2 = p[2][0] - p[1][0];
1520         const Real y2 = p[2][1] - p[1][1];
1521
1522         const Real d1 = x1*x1 + y1*y1;
1523         const Real d2 = x2*x2 + y2*y2;
1524
1525         return max(d1,d2);
1526 }
1527
1528 void Layer_Shape::PolySpan::conic_to(Real x1, Real y1, Real x, Real y)
1529 {
1530         Point *current = arc;
1531         int             level = 0;
1532         int     num = 0;
1533         bool    onsecond = false;
1534
1535         arc[0] = Point(x,y);
1536         arc[1] = Point(x1,y1);
1537         arc[2] = Point(cur_x,cur_y);
1538
1539         //just draw the line if it's outside
1540         if(clip_conic(arc,window))
1541         {
1542                 line_to(x,y);
1543                 return;
1544         }
1545
1546         //Ok so it's not super degenerate, subdivide and draw (run through minimum subdivision levels first)
1547         while(current >= arc)
1548         {
1549                 if(num >= MAX_SUBDIVISION_SIZE)
1550                 {
1551                         warning("Curve subdivision somehow ran out of space while tessellating!");
1552
1553                         //do something...
1554                         assert(0);
1555                         return;
1556                 }else
1557                 //if the curve is clipping then draw degenerate
1558                 if(clip_conic(current,window))
1559                 {
1560                         line_to(current[0][0],current[0][1]); //backwards so front is destination
1561                         current -= 2;
1562                         if(onsecond) level--;
1563                         onsecond = true;
1564                         num--;
1565                         continue;
1566                 }else
1567                 //if we are not at the level minimum
1568                 if(level < MIN_SUBDIVISION_DRAW_LEVELS)
1569                 {
1570                         Subd_Conic_Stack(current);
1571                         current += 2;           //cursor on second curve
1572                         level ++;
1573                         num ++;
1574                         onsecond = false;
1575                         continue;
1576                 }else
1577                 //split it again, if it's too big
1578                 if(max_edges_conic(current) > 0.25) //distance of .5 (cover no more than half the pixel)
1579                 {
1580                         Subd_Conic_Stack(current);
1581                         current += 2;           //cursor on second curve
1582                         level ++;
1583                         num ++;
1584                         onsecond = false;
1585                 }
1586                 else    //NOT TOO BIG? RENDER!!!
1587                 {
1588                         //cur_x,cur_y = current[2], so we need to go 1,0
1589                         line_to(current[1][0],current[1][1]);
1590                         line_to(current[0][0],current[0][1]);
1591
1592                         current -= 2;
1593                         if(onsecond) level--;
1594                         num--;
1595                         onsecond = true;
1596                 }
1597         }
1598 }
1599
1600 void Layer_Shape::PolySpan::cubic_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
1601 {
1602         Point *current = arc;
1603         int             num = 0;
1604         int             level = 0;
1605         bool    onsecond = false;
1606
1607         arc[0] = Point(x,y);
1608         arc[1] = Point(x2,y2);
1609         arc[2] = Point(x1,y1);
1610         arc[3] = Point(cur_x,cur_y);
1611
1612         //just draw the line if it's outside
1613         if(clip_cubic(arc,window))
1614         {
1615                 line_to(x,y);
1616                 return;
1617         }
1618
1619         //Ok so it's not super degenerate, subdivide and draw (run through minimum subdivision levels first)
1620         while(current >= arc) //once current goes below arc, there are no more curves left
1621         {
1622                 if(num >= MAX_SUBDIVISION_SIZE)
1623                 {
1624                         warning("Curve subdivision somehow ran out of space while tessellating!");
1625
1626                         //do something...
1627                         assert(0);
1628                         return;
1629                 }else
1630
1631                 //if we are not at the level minimum
1632                 if(level < MIN_SUBDIVISION_DRAW_LEVELS)
1633                 {
1634                         Subd_Cubic_Stack(current);
1635                         current += 3;           //cursor on second curve
1636                         level ++;
1637                         num ++;
1638                         onsecond = false;
1639                         continue;
1640                 }else
1641                 //if the curve is clipping then draw degenerate
1642                 if(clip_cubic(current,window))
1643                 {
1644                         line_to(current[0][0],current[0][1]); //backwards so front is destination
1645                         current -= 3;
1646                         if(onsecond) level--;
1647                         onsecond = true;
1648                         num --;
1649                         continue;
1650                 }
1651                 else
1652                 //split it again, if it's too big
1653                 if(max_edges_cubic(current) > 0.25) //could use max_edges<3>
1654                 {
1655                         Subd_Cubic_Stack(current);
1656                         current += 3;           //cursor on second curve
1657                         level ++;
1658                         num ++;
1659                         onsecond = false;
1660                 }
1661                 else //NOT TOO BIG? RENDER!!!
1662                 {
1663                         //cur_x,cur_y = current[3], so we need to go 2,1,0
1664                         line_to(current[2][0],current[2][1]);
1665                         line_to(current[1][0],current[1][1]);
1666                         line_to(current[0][0],current[0][1]);
1667
1668                         current -= 3;
1669                         if(onsecond) level--;
1670                         num --;
1671                         onsecond = true;
1672                 }
1673         }
1674 }
1675
1676 //******************** LINE ALGORITHMS ****************************
1677 // THESE CALCULATE THE AREA AND THE COVER FOR THE MARKS, TO THEN SCAN CONVERT
1678 // - BROKEN UP INTO SCANLINES (draw_line - y intersections),
1679 //   THEN THE COVER AND AREA PER TOUCHED PIXEL IS CALCULATED (draw_scanline - x intersections)
1680 void Layer_Shape::PolySpan::draw_scanline(int y, Real x1, Real fy1, Real x2, Real fy2)
1681 {
1682         int     ix1 = (int)floor(x1);
1683         int     ix2 = (int)floor(x2);
1684         Real fx1 = x1 - ix1;
1685         Real fx2 = x2 - ix2;
1686
1687         Real dx,dy,dydx,mult;
1688
1689         dx = x2 - x1;
1690         dy = fy2 - fy1;
1691
1692         //case horizontal line
1693         if(fy1 == fy2)
1694         {
1695                 move_pen(ix2,y); //pen needs to be at the last coord
1696                 return;
1697         }
1698
1699         //case all in same pixel
1700         if(ix1 == ix2)  //impossible for degenerate case (covered by the previous cases)
1701         {
1702                 current.addcover(dy,(fx1 + fx2)*dy/2); //horizontal trapezoid area
1703                 return;
1704         }
1705
1706         if(dx > 0)
1707         {
1708                 // ---->        fx1...1  0...1  ...  0...1  0...fx2
1709                 dydx = dy / dx;
1710
1711                 //set initial values
1712                 //Iterate through the covered pixels
1713                 mult = (1 - fx1)*dydx;  //next y intersection diff value (at 1)
1714
1715                 //first pixel
1716                 current.addcover(mult,(1 + fx1)*mult/2);        // fx1,fy1,1,fy@1 - starting trapezoidal area
1717
1718                 //move to the next pixel
1719                 fy1 += mult;
1720                 ix1++;
1721
1722                 move_pen(ix1,y);
1723
1724                 //set up for whole ones
1725                 while(ix1 != ix2)
1726                 {
1727                         //trapezoid(0,y1,1,y1+dydx);
1728                         current.addcover(dydx,dydx/2);  //accumulated area 1/2 the cover
1729
1730                         //move to next pixel (+1)
1731                         ix1++;
1732                         fy1 += dydx;
1733                         move_pen(ix1,y);
1734                 }
1735
1736                 //last pixel
1737                 //final y-pos - last intersect pos
1738                 mult = fx2 * dydx;
1739                 current.addcover(mult,(0+fx2)*mult/2);
1740         }else
1741         {
1742                 // fx2...1  0...1  ...  0...1  0...fx1   <----
1743                 //mult = (0 - fx1) * dy / dx;
1744                 //neg sign sucked into dydx
1745                 dydx = -dy / dx;
1746
1747                 //set initial values
1748                 //Iterate through the covered pixels
1749                 mult = fx1*dydx;        //next y intersection diff value
1750
1751                 //first pixel
1752                 current.addcover(mult,fx1*mult/2);      // fx1,fy1,0,fy@0 - starting trapezoidal area
1753
1754                 //move to next pixel
1755                 fy1 += mult;
1756                 ix1--;
1757
1758                 move_pen(ix1,y);
1759
1760                 //set up for whole ones
1761                 while(ix1 != ix2)
1762                 {
1763                         //trapezoid(0,y1,1,y1+dydx);
1764                         current.addcover(dydx,dydx/2);  //accumulated area 1/2 the cover
1765
1766                         //move to next pixel (-1)
1767                         fy1 += dydx;
1768                         ix1--;
1769                         move_pen(ix1,y);
1770                 }
1771
1772                 //last pixel
1773                 mult = fy2 - fy1; //final y-pos - last intersect pos
1774
1775                 current.addcover(mult,(fx2+1)*mult/2);
1776         }
1777 }
1778
1779 void Layer_Shape::PolySpan::draw_line(Real x1, Real y1, Real x2, Real y2)
1780 {
1781         int iy1 = (int)floor(y1);
1782         int iy2 = (int)floor(y2);
1783         Real fy1 = y1 - iy1;
1784         Real fy2 = y2 - iy2;
1785
1786         assert(!isnan(fy1));
1787         assert(!isnan(fy2));
1788
1789         Real dx,dy,dxdy,mult,x_from,x_to;
1790
1791         const Real SLOPE_EPSILON = 1e-10;
1792
1793         //case all one scanline
1794         if(iy1 == iy2)
1795         {
1796                 draw_scanline(iy1,x1,y1,x2,y2);
1797                 return;
1798         }
1799
1800         //difference values
1801         dy = y2 - y1;
1802         dx = x2 - x1;
1803
1804         //case vertical line
1805         if(dx < SLOPE_EPSILON && dx > -SLOPE_EPSILON)
1806         {
1807                 //calc area and cover on vertical line
1808                 if(dy > 0)
1809                 {
1810                         // ---->        fx1...1  0...1  ...  0...1  0...fx2
1811                         Real sub;
1812
1813                         int      ix1 = (int)floor(x1);
1814                         Real fx1 = x1 - ix1;
1815
1816                         //current pixel
1817                         sub = 1 - fy1;
1818
1819                         current.addcover(sub,fx1*sub);
1820
1821                         //next pixel
1822                         iy1++;
1823
1824                         //move pen to next pixel
1825                         move_pen(ix1,iy1);
1826
1827                         while(iy1 != iy2)
1828                         {
1829                                 //accumulate cover
1830                                 current.addcover(1,fx1);
1831
1832                                 //next pixel
1833                                 iy1++;
1834                                 move_pen(ix1,iy1);
1835                         }
1836
1837                         //last pixel
1838                         current.addcover(fy2,fy2*fx1);
1839                 }else
1840                 {
1841                         Real sub;
1842
1843                         int      ix1 = (int)floor(x1);
1844                         Real fx1 = x1 - ix1;
1845
1846                         //current pixel
1847                         sub = 0 - fy1;
1848
1849                         current.addcover(sub,fx1*sub);
1850
1851                         //next pixel
1852                         iy1--;
1853
1854                         move_pen(ix1,iy1);
1855
1856                         while(iy1 != iy2)
1857                         {
1858                                 //accumulate in current pixel
1859                                 current.addcover(-1,-fx1);
1860
1861                                 //move to next
1862                                 iy1--;
1863                                 move_pen(ix1,iy1);
1864                         }
1865
1866                         current.addcover(fy2-1,(fy2-1)*fx1);
1867                 }
1868                 return;
1869         }
1870
1871         //case normal line - guaranteed dx != 0 && dy != 0
1872
1873         //calculate the initial intersection with "next" scanline
1874         if(dy > 0)
1875         {
1876                 dxdy = dx / dy;
1877
1878                 mult = (1 - fy1) * dxdy;
1879
1880                 //x intersect scanline
1881                 x_from = x1 + mult;
1882                 draw_scanline(iy1,x1,fy1,x_from,1);
1883
1884                 //move to next line
1885                 iy1++;
1886
1887                 move_pen((int)floor(x_from),iy1);
1888
1889                 while(iy1 != iy2)
1890                 {
1891                         //keep up on the x axis, and render the current scanline
1892                         x_to = x_from + dxdy;
1893                         draw_scanline(iy1,x_from,0,x_to,1);
1894                         x_from = x_to;
1895
1896                         //move to next pixel
1897                         iy1++;
1898                         move_pen((int)floor(x_from),iy1);
1899                 }
1900
1901                 //draw the last one, fractional
1902                 draw_scanline(iy2,x_from,0,x2,fy2);
1903
1904         }else
1905         {
1906                 dxdy = -dx / dy;
1907
1908                 mult = fy1 * dxdy;
1909
1910                 //x intersect scanline
1911                 x_from = x1 + mult;
1912                 draw_scanline(iy1,x1,fy1,x_from,0);
1913
1914                 //each line after
1915                 iy1--;
1916
1917                 move_pen((int)floor(x_from),iy1);
1918
1919                 while(iy1 != iy2)
1920                 {
1921                         x_to = x_from + dxdy;
1922                         draw_scanline(iy1,x_from,1,x_to,0);
1923                         x_from = x_to;
1924
1925                         iy1--;
1926                         move_pen((int)floor(x_from),iy1);
1927                 }
1928                 //draw the last one, fractional
1929                 draw_scanline(iy2,x_from,1,x2,fy2);
1930         }
1931 }
1932
1933 //****** LAYER PEN OPERATIONS (move_to, line_to, etc.) ******
1934 void Layer_Shape::move_to(Real x, Real y)
1935 {
1936         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
1937         Primitive       op;
1938         Point           p(x,y);
1939
1940         op.operation = Primitive::MOVE_TO;
1941         op.number = 1;  //one point for now
1942
1943         if(lastbyteop == Primitive::MOVE_TO)
1944         {
1945                 char *ptr = &bytestream[lastoppos];
1946                 memcpy(ptr,&op,sizeof(op));
1947                 memcpy(ptr+sizeof(op),&p,sizeof(p));
1948         }
1949         else //make a new op
1950         {
1951                 lastbyteop = Primitive::MOVE_TO;
1952                 lastoppos = bytestream.size();
1953
1954                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
1955                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
1956         }
1957
1958         edge_table->move_to(x,y);
1959 }
1960
1961 void Layer_Shape::close()
1962 {
1963         Primitive op;
1964
1965         op.operation = Primitive::CLOSE;
1966         op.number = 0;
1967
1968         if(lastbyteop == Primitive::CLOSE)
1969         {
1970         }else
1971         {
1972                 lastbyteop = Primitive::CLOSE;
1973                 lastoppos = bytestream.size();
1974
1975                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1)); //insert header
1976         }
1977
1978         edge_table->close();
1979         //should not affect the bounding box since it would just be returning to old point...
1980 }
1981
1982 void Layer_Shape::endpath()
1983 {
1984         Primitive op;
1985
1986         op.operation = Primitive::END;
1987         op.number = 0;
1988
1989         if(lastbyteop == Primitive::END || lastbyteop == Primitive::NONE)
1990         {
1991         }else
1992         {
1993                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));
1994         }
1995         //should not affect the bounding box since it would just be returning to old point... if at all
1996 }
1997
1998 void Layer_Shape::line_to(Real x, Real y)
1999 {
2000         assert(!isnan(x));
2001         assert(!isnan(y));
2002
2003         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
2004         Primitive       op;
2005         Point           p(x,y);
2006
2007         op.operation = Primitive::LINE_TO;
2008         op.number = 1;  //one point for now
2009
2010         if(lastbyteop == Primitive::MOVE_TO || lastbyteop == Primitive::LINE_TO)
2011         {
2012                 //only need to insert the point
2013                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2014
2015                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2016                 prim->number++; //increment number of points in the list
2017         }else
2018         {
2019                 lastbyteop = Primitive::LINE_TO;
2020                 lastoppos = bytestream.size();
2021
2022                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2023                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2024         }
2025
2026         edge_table->line_to(x,y);
2027 }
2028
2029 void Layer_Shape::conic_to(Real x1, Real y1, Real x, Real y)
2030 {
2031         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*2;
2032         Primitive       op;
2033         Point           p(x,y);
2034         Point           p1(x1,y1);
2035
2036         op.operation = Primitive::CONIC_TO;
2037         op.number = 2;  //2 points for now
2038
2039         if(lastbyteop == Primitive::CONIC_TO)
2040         {
2041                 //only need to insert the new points
2042                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));
2043                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2044
2045                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2046                 prim->number += 2; //increment number of points in the list
2047         }else
2048         {
2049                 lastbyteop = Primitive::CONIC_TO;
2050                 lastoppos = bytestream.size();
2051
2052                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2053                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));  //insert the bytes for data
2054                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2055         }
2056
2057         edge_table->conic_to(x1,y1,x,y);
2058 }
2059
2060 void Layer_Shape::conic_to_smooth(Real x, Real y)                               //x1,y1 derived from current tangent
2061 {
2062         //const int sizeblock = sizeof(Primitive)+sizeof(Point);
2063         Primitive       op;
2064         Point           p(x,y);
2065
2066         op.operation = Primitive::CONIC_TO_SMOOTH;
2067         op.number = 1;  //2 points for now
2068
2069         if(lastbyteop == Primitive::CONIC_TO_SMOOTH)
2070         {
2071                 //only need to insert the new point
2072                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2073
2074                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2075                 prim->number += 1; //increment number of points in the list
2076         }else
2077         {
2078                 lastbyteop = Primitive::CONIC_TO_SMOOTH;
2079                 lastoppos = bytestream.size();
2080
2081                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2082                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2083         }
2084
2085         edge_table->conic_to_smooth(x,y);
2086 }
2087
2088 void Layer_Shape::curve_to(Real x1, Real y1, Real x2, Real y2, Real x, Real y)
2089 {
2090         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*3;
2091         Primitive       op;
2092         Point           p(x,y);
2093         Point           p1(x1,y1);
2094         Point           p2(x2,y2);
2095
2096         op.operation = Primitive::CUBIC_TO;
2097         op.number = 3;  //3 points for now
2098
2099         if(lastbyteop == Primitive::CUBIC_TO)
2100         {
2101                 //only need to insert the new points
2102                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));
2103                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));
2104                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2105
2106                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2107                 prim->number += 3; //increment number of points in the list
2108         }else
2109         {
2110                 lastbyteop = Primitive::CUBIC_TO;
2111                 lastoppos = bytestream.size();
2112
2113                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2114                 bytestream.insert(bytestream.end(),(char*)&p1,(char*)(&p1+1));  //insert the bytes for data
2115                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));  //insert the bytes for data
2116                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2117         }
2118
2119         edge_table->curve_to(x1,y1,x2,y2,x,y);
2120 }
2121
2122 void Layer_Shape::curve_to_smooth(Real x2, Real y2, Real x, Real y)             //x1,y1 derived from current tangent
2123 {
2124         //const int sizeblock = sizeof(Primitive)+sizeof(Point)*3;
2125         Primitive       op;
2126         Point           p(x,y);
2127         Point           p2(x2,y2);
2128
2129         op.operation = Primitive::CUBIC_TO_SMOOTH;
2130         op.number = 2;  //3 points for now
2131
2132         if(lastbyteop == Primitive::CUBIC_TO_SMOOTH)
2133         {
2134                 //only need to insert the new points
2135                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));
2136                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));
2137
2138                 Primitive * prim = (Primitive *)&bytestream[lastoppos];
2139                 prim->number += 2; //increment number of points in the list
2140         }else
2141         {
2142                 lastbyteop = Primitive::CUBIC_TO_SMOOTH;
2143                 lastoppos = bytestream.size();
2144
2145                 bytestream.insert(bytestream.end(),(char*)&op,(char*)(&op+1));  //insert the bytes for the header
2146                 bytestream.insert(bytestream.end(),(char*)&p2,(char*)(&p2+1));  //insert the bytes for data
2147                 bytestream.insert(bytestream.end(),(char*)&p,(char*)(&p+1));    //insert the bytes for data
2148         }
2149 }
2150
2151 // ACCELERATED RENDER FUNCTION - TRANSLATE BYTE CODE INTO FUNCTION CALLS
2152
2153 bool Layer_Shape::render_polyspan(Surface *surface, PolySpan &polyspan,
2154                                                                 Color::BlendMethod got_blend_method, Color::value_type got_amount) const
2155 {
2156         Surface::alpha_pen p(surface->begin(),got_amount,_BlendFunc(got_blend_method));
2157         PolySpan::cover_array::iterator cur_mark = polyspan.covers.begin();
2158         PolySpan::cover_array::iterator end_mark = polyspan.covers.end();
2159
2160         Real cover,area,alpha;
2161
2162         int     y,x;
2163
2164         p.set_value(color);
2165         cover = 0;
2166
2167         if(cur_mark == end_mark)
2168         {
2169                 //no marks at all
2170                 if(invert)
2171                 {
2172                         p.move_to(polyspan.window.minx,polyspan.window.miny);
2173                         p.put_block(polyspan.window.maxy - polyspan.window.miny,polyspan.window.maxx - polyspan.window.minx);
2174                 }
2175                 return true;
2176         }
2177
2178         //fill initial rect / line
2179         if(invert)
2180         {
2181                 //fill all the area above the first vertex
2182                 p.move_to(polyspan.window.minx,polyspan.window.miny);
2183                 y = polyspan.window.miny;
2184                 int l = polyspan.window.maxx - polyspan.window.minx;
2185
2186                 p.put_block(cur_mark->y - polyspan.window.miny,l);
2187
2188                 //fill the area to the left of the first vertex on that line
2189                 l = cur_mark->x - polyspan.window.minx;
2190                 p.move_to(polyspan.window.minx,cur_mark->y);
2191                 if(l) p.put_hline(l);
2192         }
2193
2194         for(;;)
2195         {
2196                 y = cur_mark->y;
2197                 x = cur_mark->x;
2198
2199                 p.move_to(x,y);
2200
2201                 area = cur_mark->area;
2202                 cover += cur_mark->cover;
2203
2204                 //accumulate for the current pixel
2205                 while(++cur_mark != polyspan.covers.end())
2206                 {
2207                         if(y != cur_mark->y || x != cur_mark->x)
2208                                 break;
2209
2210                         area += cur_mark->area;
2211                         cover += cur_mark->cover;
2212                 }
2213
2214                 //draw pixel - based on covered area
2215                 if(area)        //if we're ok, draw the current pixel
2216                 {
2217                         alpha = polyspan.ExtractAlpha(cover - area, winding_style);
2218                         if(invert) alpha = 1 - alpha;
2219
2220                         if(!antialias)
2221                         {
2222                                 if(alpha >= .5) p.put_value();
2223                         }
2224                         else if(alpha) p.put_value_alpha(alpha);
2225
2226                         p.inc_x();
2227                         x++;
2228                 }
2229
2230                 //if we're done, don't use iterator and exit
2231                 if(cur_mark == end_mark) break;
2232
2233                 //if there is no more live pixels on this line, goto next
2234                 if(y != cur_mark->y)
2235                 {
2236                         if(invert)
2237                         {
2238                                 //fill the area at the end of the line
2239                                 p.put_hline(polyspan.window.maxx - x);
2240
2241                                 //fill area at the beginning of the next line
2242                                 p.move_to(polyspan.window.minx,cur_mark->y);
2243                                 p.put_hline(cur_mark->x - polyspan.window.minx);
2244                         }
2245
2246                         cover = 0;
2247
2248                         continue;
2249                 }
2250
2251                 //draw span to next pixel - based on total amount of pixel cover
2252                 if(x < cur_mark->x)
2253                 {
2254                         alpha = polyspan.ExtractAlpha(cover, winding_style);
2255                         if(invert) alpha = 1 - alpha;
2256
2257                         if(!antialias)
2258                         {
2259                                 if(alpha >= .5) p.put_hline(cur_mark->x - x);
2260                         }
2261                         else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2262                 }
2263         }
2264
2265         //fill the after stuff
2266         if(invert)
2267         {
2268                 //fill the area at the end of the line
2269                 p.put_hline(polyspan.window.maxx - x);
2270
2271                 //fill area at the beginning of the next line
2272                 p.move_to(polyspan.window.minx,y+1);
2273                 p.put_block(polyspan.window.maxy - y - 1,polyspan.window.maxx - polyspan.window.minx);
2274         }
2275
2276         return true;
2277 }
2278
2279 bool Layer_Shape::render_polyspan(etl::surface<float> *surface, PolySpan &polyspan) const
2280 {
2281         etl::surface<float>::pen p(surface->begin());
2282         PolySpan::cover_array::iterator cur_mark = polyspan.covers.begin();
2283         PolySpan::cover_array::iterator end_mark = polyspan.covers.end();
2284
2285         Real cover,area,alpha;
2286
2287         int     y,x;
2288
2289         cover = 0;
2290
2291         //the pen always writes 1 (unless told to do otherwise)
2292         p.set_value(1);
2293
2294         if(cur_mark == end_mark)
2295         {
2296                 //no marks at all
2297                 if(invert)
2298                 {
2299                         p.move_to(polyspan.window.minx,polyspan.window.miny);
2300                         p.put_block(polyspan.window.maxy - polyspan.window.miny,polyspan.window.maxx - polyspan.window.minx);
2301                 }
2302                 return true;
2303         }
2304
2305         //fill initial rect / line
2306         if(invert)
2307         {
2308                 //fill all the area above the first vertex
2309                 p.move_to(polyspan.window.minx,polyspan.window.miny);
2310                 y = polyspan.window.miny;
2311                 int l = polyspan.window.maxx - polyspan.window.minx;
2312
2313                 p.put_block(cur_mark->y - polyspan.window.miny,l);
2314
2315                 //fill the area to the left of the first vertex on that line
2316                 l = cur_mark->x - polyspan.window.minx;
2317                 p.move_to(polyspan.window.minx,cur_mark->y);
2318                 if(l) p.put_hline(l);
2319
2320                 for(;;)
2321                 {
2322                         y = cur_mark->y;
2323                         x = cur_mark->x;
2324
2325                         p.move_to(x,y);
2326
2327                         area = cur_mark->area;
2328                         cover += cur_mark->cover;
2329
2330                         //accumulate for the current pixel
2331                         while(++cur_mark != polyspan.covers.end())
2332                         {
2333                                 if(y != cur_mark->y || x != cur_mark->x)
2334                                         break;
2335
2336                                 area += cur_mark->area;
2337                                 cover += cur_mark->cover;
2338                         }
2339
2340                         //draw pixel - based on covered area
2341                         if(area)        //if we're ok, draw the current pixel
2342                         {
2343                                 alpha = 1 - polyspan.ExtractAlpha(cover - area, winding_style);
2344                                 if(!antialias)
2345                                 {
2346                                         if(alpha >= .5) p.put_value();
2347                                 }
2348                                 else if(alpha) p.put_value(alpha);
2349
2350                                 p.inc_x();
2351                                 x++;
2352                         }
2353
2354                         //if we're done, don't use iterator and exit
2355                         if(cur_mark == end_mark) break;
2356
2357                         //if there is no more live pixels on this line, goto next
2358                         if(y != cur_mark->y)
2359                         {
2360                                 //fill the area at the end of the line
2361                                 p.put_hline(polyspan.window.maxx - x);
2362
2363                                 //fill area at the beginning of the next line
2364                                 p.move_to(polyspan.window.minx,cur_mark->y);
2365                                 p.put_hline(cur_mark->x - polyspan.window.minx);
2366
2367                                 cover = 0;
2368
2369                                 continue;
2370                         }
2371
2372                         //draw span to next pixel - based on total amount of pixel cover
2373                         if(x < cur_mark->x)
2374                         {
2375                                 alpha = 1 - polyspan.ExtractAlpha(cover, winding_style);
2376                                 if(!antialias)
2377                                 {
2378                                         if(alpha >= .5) p.put_hline(cur_mark->x - x);
2379                                 }
2380                                 else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2381                         }
2382                 }
2383
2384                 //fill the area at the end of the line
2385                 p.put_hline(polyspan.window.maxx - x);
2386
2387                 //fill area at the beginning of the next line
2388                 p.move_to(polyspan.window.minx,y+1);
2389                 p.put_block(polyspan.window.maxy - y - 1,polyspan.window.maxx - polyspan.window.minx);
2390         }else
2391         {
2392                 for(;;)
2393                 {
2394                         y = cur_mark->y;
2395                         x = cur_mark->x;
2396
2397                         p.move_to(x,y);
2398
2399                         area = cur_mark->area;
2400                         cover += cur_mark->cover;
2401
2402                         //accumulate for the current pixel
2403                         while(++cur_mark != polyspan.covers.end())
2404                         {
2405                                 if(y != cur_mark->y || x != cur_mark->x)
2406                                         break;
2407
2408                                 area += cur_mark->area;
2409                                 cover += cur_mark->cover;
2410                         }
2411
2412                         //draw pixel - based on covered area
2413                         if(area)        //if we're ok, draw the current pixel
2414                         {
2415                                 alpha = polyspan.ExtractAlpha(cover - area, winding_style);
2416                                 if(!antialias)
2417                                 {
2418                                         if(alpha >= .5) p.put_value();
2419                                 }
2420                                 else if(alpha) p.put_value(alpha);
2421
2422                                 p.inc_x();
2423                                 x++;
2424                         }
2425
2426                         //if we're done, don't use iterator and exit
2427                         if(cur_mark == end_mark) break;
2428
2429                         //if there is no more live pixels on this line, goto next
2430                         if(y != cur_mark->y)
2431                         {
2432                                 cover = 0;
2433
2434                                 continue;
2435                         }
2436
2437                         //draw span to next pixel - based on total amount of pixel cover
2438                         if(x < cur_mark->x)
2439                         {
2440                                 alpha = polyspan.ExtractAlpha(cover, winding_style);
2441                                 if(!antialias)
2442                                 {
2443                                         if(alpha >= .5) p.put_hline(cur_mark->x - x);
2444                                 }
2445                                 else if(alpha) p.put_hline(cur_mark->x - x,alpha);
2446                         }
2447                 }
2448         }
2449
2450         return true;
2451 }
2452
2453 bool
2454 Layer_Shape::accelerated_render(Context context,Surface *surface,int quality, const RendDesc &renddesc, ProgressCallback *cb)const
2455 {
2456         const unsigned int w = renddesc.get_w();
2457         const unsigned int h = renddesc.get_h();
2458
2459         const Real pw = abs(renddesc.get_pw());
2460         const Real ph = abs(renddesc.get_ph());
2461
2462         //const Real OFFSET_EPSILON = 1e-8;
2463         SuperCallback stageone(cb,1,10000,15001+renddesc.get_h());
2464         SuperCallback stagetwo(cb,10000,10001+renddesc.get_h(),15001+renddesc.get_h());
2465         SuperCallback stagethree(cb,10001+renddesc.get_h(),15001+renddesc.get_h(),15001+renddesc.get_h());
2466
2467         // Render what is behind us
2468
2469         //clip if it satisfies the invert solid thing
2470         if(is_solid_color() && invert)
2471         {
2472                 Rect aabb = edge_table->aabb;
2473                 Point tl = renddesc.get_tl() - offset;
2474
2475                 Real    pw = renddesc.get_pw(),
2476                                 ph = renddesc.get_ph();
2477
2478                 Rect    nrect;
2479
2480                 Real    pixelfeatherx = abs(feather/pw),
2481                                 pixelfeathery = abs(feather/ph);
2482
2483                 nrect.set_point((aabb.minx - tl[0])/pw,(aabb.miny - tl[1])/ph);
2484                 nrect.expand((aabb.maxx - tl[0])/pw,(aabb.maxy - tl[1])/ph);
2485
2486                 RendDesc        optdesc(renddesc);
2487
2488                 //make sure to expand so we gain subpixels rather than lose them
2489                 nrect.minx = floor(nrect.minx-pixelfeatherx); nrect.miny = floor(nrect.miny-pixelfeathery);
2490                 nrect.maxx = ceil(nrect.maxx+pixelfeatherx); nrect.maxy = ceil(nrect.maxy+pixelfeathery);
2491
2492                 //make sure the subwindow is clipped with our tile window (minimize useless drawing)
2493                 set_intersect(nrect,nrect,Rect(0,0,renddesc.get_w(),renddesc.get_h()));
2494
2495                 //must resize the surface first
2496                 surface->set_wh(renddesc.get_w(),renddesc.get_h());
2497                 surface->clear();
2498
2499                 //only render anything if it's visible from our current tile
2500                 if(nrect.valid())
2501                 {
2502                         //set the subwindow to the viewable pixels and render it to the subsurface
2503                         optdesc.set_subwindow((int)nrect.minx, (int)nrect.miny,
2504                                 (int)(nrect.maxx - nrect.minx), (int)(nrect.maxy - nrect.miny));
2505
2506                         Surface optimizedbacksurf;
2507                         if(!context.accelerated_render(&optimizedbacksurf,quality,optdesc,&stageone))
2508                                 return false;
2509
2510                         //blit that onto the original surface so we can pretend that nothing ever happened
2511                         Surface::pen p = surface->get_pen((int)nrect.minx,(int)nrect.miny);
2512                         optimizedbacksurf.blit_to(p);
2513                 }
2514         }else
2515         {
2516                 if(!context.accelerated_render(surface,quality,renddesc,&stageone))
2517                         return false;
2518         }
2519
2520         if(cb && !cb->amount_complete(10000,10001+renddesc.get_h())) return false;
2521
2522         if(feather)
2523         {
2524                 //we have to blur rather than be crappy
2525
2526                 //so make a separate surface
2527                 RendDesc        workdesc(renddesc);
2528
2529                 etl::surface<float>     shapesurface;
2530
2531                 //the expanded size = 1/2 the size in each direction rounded up
2532                 int     halfsizex = (int) (abs(feather*.5/pw) + 3),
2533                         halfsizey = (int) (abs(feather*.5/ph) + 3);
2534
2535                 //expand by 1/2 size in each direction on either side
2536                 switch(blurtype)
2537                 {
2538                         case Blur::DISC:
2539                         case Blur::BOX:
2540                         case Blur::CROSS:
2541                         {
2542                                 workdesc.set_subwindow(-max(1,halfsizex),-max(1,halfsizey),w+2*max(1,halfsizex),h+2*max(1,halfsizey));
2543                                 break;
2544                         }
2545                         case Blur::FASTGAUSSIAN:
2546                         {
2547                                 if(quality < 4)
2548                                 {
2549                                         halfsizex*=2;
2550                                         halfsizey*=2;
2551                                 }
2552                                 workdesc.set_subwindow(-max(1,halfsizex),-max(1,halfsizey),w+2*max(1,halfsizex),h+2*max(1,halfsizey));
2553                                 break;
2554                         }
2555                         case Blur::GAUSSIAN:
2556                         {
2557                         #define GAUSSIAN_ADJUSTMENT             (0.05)
2558                                 Real    pw = (Real)workdesc.get_w()/(workdesc.get_br()[0]-workdesc.get_tl()[0]);
2559                                 Real    ph = (Real)workdesc.get_h()/(workdesc.get_br()[1]-workdesc.get_tl()[1]);
2560
2561                                 pw=pw*pw;
2562                                 ph=ph*ph;
2563
2564                                 halfsizex = (int)(abs(pw)*feather*GAUSSIAN_ADJUSTMENT+0.5);
2565                                 halfsizey = (int)(abs(ph)*feather*GAUSSIAN_ADJUSTMENT+0.5);
2566
2567                                 halfsizex = (halfsizex + 1)/2;
2568                                 halfsizey = (halfsizey + 1)/2;
2569                                 workdesc.set_subwindow( -halfsizex, -halfsizey, w+2*halfsizex, h+2*halfsizey );
2570
2571                                 break;
2572                         }
2573                 }
2574
2575                 shapesurface.set_wh(workdesc.get_w(),workdesc.get_h());
2576                 shapesurface.clear();
2577
2578                 //render the shape
2579                 if(!render_shape(&shapesurface,quality,workdesc,&stagetwo))return false;
2580
2581                 //blur the image
2582                 Blur(feather,feather,blurtype,&stagethree)(shapesurface,workdesc.get_br()-workdesc.get_tl(),shapesurface);
2583
2584                 //blend with stuff below it...
2585                 unsigned int u = halfsizex, v = halfsizey, x = 0, y = 0;
2586                 for(y = 0; y < h; y++,v++)
2587                 {
2588                         u = halfsizex;
2589                         for(x = 0; x < w; x++,u++)
2590                         {
2591                                 float a = shapesurface[v][u];
2592                                 if(a)
2593                                 {
2594                                         //a = floor(a*255+0.5f)/255;
2595                                         (*surface)[y][x]=Color::blend(color,(*surface)[y][x],a*get_amount(),get_blend_method());
2596                                 }
2597                                 //else (*surface)[y][x] = worksurface[v][u];
2598                         }
2599                 }
2600
2601                 //we are done
2602                 if(cb && !cb->amount_complete(100,100))
2603                 {
2604                         synfig::warning("Layer_Shape: could not set amount complete");
2605                         return false;
2606                 }
2607
2608                 return true;
2609         }else
2610         {
2611                 //might take out to reduce code size
2612                 return render_shape(surface,true,quality,renddesc,&stagetwo);
2613         }
2614
2615 }
2616
2617 bool
2618 Layer_Shape::render_shape(Surface *surface,bool useblend,int /*quality*/,
2619                                                         const RendDesc &renddesc, ProgressCallback *cb)const
2620 {
2621         int tmp(0);
2622
2623         SuperCallback   progress(cb,0,renddesc.get_h(),renddesc.get_h());
2624
2625         // If our amount is set to zero, no need to render anything
2626         if(!get_amount())
2627                 return true;
2628
2629         //test new polygon renderer
2630         // Build edge table
2631         // Width and Height of a pixel
2632         const int       w = renddesc.get_w();
2633         const int       h = renddesc.get_h();
2634         const Real      pw = renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
2635         const Real      ph = renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
2636
2637         const Point     tl = renddesc.get_tl();
2638
2639         Vector tangent (0,0);
2640
2641         PolySpan        span;
2642
2643         // if the pixels are zero sized then we're too zoomed out to see anything
2644         if (pw == 0 || ph == 0)
2645                 return true;
2646
2647         //optimization for tessellating only inside tiles
2648         span.window.minx = 0;
2649         span.window.miny = 0;
2650         span.window.maxx = w;
2651         span.window.maxy = h;
2652
2653         //pointers for processing the bytestream
2654         const char *current     = &bytestream[0];
2655         const char *end                 = &bytestream[bytestream.size()];
2656
2657         int     operation       = Primitive::NONE;
2658         int number              = 0;
2659         int curnum;
2660
2661         Primitive       *curprim;
2662         Point           *data;
2663
2664         Real x,y,x1,y1,x2,y2;
2665
2666
2667         while(current < end)
2668         {
2669                 tmp++;
2670
2671                 try {
2672
2673                 //get the op code safely
2674                 curprim = (Primitive *)current;
2675
2676                 //advance past indices
2677                 current += sizeof(Primitive);
2678                 if(current > end)
2679                 {
2680                         warning("Layer_Shape::accelerated_render - Error in the byte stream, not enough space for next declaration");
2681                         return false;
2682                 }
2683
2684                 //get the relevant data
2685                 operation       = curprim->operation;
2686                 number          = curprim->number;
2687
2688                 if(operation == Primitive::END)
2689                         break;
2690
2691                 if(operation == Primitive::CLOSE)
2692                 {
2693                         if(span.notclosed())
2694                         {
2695                                 tangent[0] = span.close_x - span.cur_x;
2696                                 tangent[1] = span.close_y - span.cur_y;
2697                                 span.close();
2698                         }
2699                         continue;
2700                 }
2701
2702                 data = (Point*)current;
2703                 current += sizeof(Point)*number;
2704
2705                 //check data positioning
2706                 if(current > end)
2707                 {
2708                         warning("Layer_Shape::accelerated_render - Error in the byte stream, in sufficient data space for declared number of points");
2709                         return false;
2710                 }
2711
2712                 } catch(...) { synfig::error("Layer_Shape::render_shape()1: Caught an exception after %d loops, rethrowing...", tmp); throw; }
2713
2714                 //transfer all the data - RLE optimized
2715                 for(curnum=0; curnum < number;)
2716                 {
2717                         switch(operation)
2718                         {
2719                                 case Primitive::MOVE_TO:
2720                                 {
2721                                         x = data[curnum][0];
2722                                         x = (x - tl[0] + offset[0])*pw;
2723                                         y = data[curnum][1];
2724                                         y = (y - tl[1] + offset[1])*ph;
2725
2726                                         if(curnum == 0)
2727                                         {
2728                                                 span.move_to(x,y);
2729
2730                                                 tangent[0] = 0;
2731                                                 tangent[1] = 0;
2732                                         }
2733                                         else
2734                                         {
2735                                                 tangent[0] = x - span.cur_x;
2736                                                 tangent[1] = y - span.cur_y;
2737
2738                                                 span.line_to(x,y);
2739                                         }
2740
2741                                         curnum++; //only advance one point
2742
2743                                         break;
2744                                 }
2745
2746                                 case Primitive::LINE_TO:
2747                                 {
2748                                         x = data[curnum][0];
2749                                         x = (x - tl[0] + offset[0])*pw;
2750                                         y = data[curnum][1];
2751                                         y = (y - tl[1] + offset[1])*ph;
2752
2753                                         tangent[0] = x - span.cur_x;
2754                                         tangent[1] = y - span.cur_y;
2755
2756                                         span.line_to(x,y);
2757                                         curnum++;
2758                                         break;
2759                                 }
2760
2761                                 case Primitive::CONIC_TO:
2762                                 {
2763                                         x = data[curnum+1][0];
2764                                         x = (x - tl[0] + offset[0])*pw;
2765                                         y = data[curnum+1][1];
2766                                         y = (y - tl[1] + offset[1])*ph;
2767
2768                                         x1 = data[curnum][0];
2769                                         x1 = (x1 - tl[0] + offset[0])*pw;
2770                                         y1 = data[curnum][1];
2771                                         y1 = (y1 - tl[1] + offset[1])*ph;
2772
2773                                         tangent[0] = 2*(x - x1);
2774                                         tangent[1] = 2*(y - y1);
2775
2776                                         span.conic_to(x1,y1,x,y);
2777                                         curnum += 2;
2778                                         break;
2779                                 }
2780
2781                                 case Primitive::CONIC_TO_SMOOTH:
2782                                 {
2783                                         x = data[curnum][0];
2784                                         x = (x - tl[0] + offset[0])*pw;
2785                                         y = data[curnum][1];
2786                                         y = (y - tl[1] + offset[1])*ph;
2787
2788                                         x1 = span.cur_x + tangent[0]/2;
2789                                         y1 = span.cur_y + tangent[1]/2;
2790
2791                                         tangent[0] = 2*(x - x1);
2792                                         tangent[1] = 2*(y - y1);
2793
2794                                         span.conic_to(x1,y1,x,y);
2795                                         curnum ++;
2796
2797                                         break;
2798                                 }
2799
2800                                 case Primitive::CUBIC_TO:
2801                                 {
2802                                         x = data[curnum+2][0];
2803                                         x = (x - tl[0] + offset[0])*pw;
2804                                         y = data[curnum+2][1];
2805                                         y = (y - tl[1] + offset[1])*ph;
2806
2807                                         x2 = data[curnum+1][0];
2808                                         x2 = (x2 - tl[0] + offset[0])*pw;
2809                                         y2 = data[curnum+1][1];
2810                                         y2 = (y2 - tl[1] + offset[1])*ph;
2811
2812                                         x1 = data[curnum][0];
2813                                         x1 = (x1 - tl[0] + offset[0])*pw;
2814                                         y1 = data[curnum][1];
2815                                         y1 = (y1 - tl[1] + offset[1])*ph;
2816
2817                                         tangent[0] = 2*(x - x2);
2818                                         tangent[1] = 2*(y - y2);
2819
2820                                         span.cubic_to(x1,y1,x2,y2,x,y);
2821                                         curnum += 3;
2822
2823                                         break;
2824                                 }
2825
2826                                 case Primitive::CUBIC_TO_SMOOTH:
2827                                 {
2828                                         x = data[curnum+1][0];
2829                                         x = (x - tl[0] + offset[0])*pw;
2830                                         y = data[curnum+1][1];
2831                                         y = (y - tl[1] + offset[1])*ph;
2832
2833                                         x2 = data[curnum][0];
2834                                         x2 = (x2 - tl[0] + offset[0])*pw;
2835                                         y2 = data[curnum][1];
2836                                         y2 = (y2 - tl[1] + offset[1])*ph;
2837
2838                                         x1 = span.cur_x + tangent[0]/3.0;
2839                                         y1 = span.cur_y + tangent[1]/3.0;
2840
2841                                         tangent[0] = 2*(x - x2);
2842                                         tangent[1] = 2*(y - y2);
2843
2844                                         span.cubic_to(x1,y1,x2,y2,x,y);
2845                                         curnum += 2;
2846
2847                                         break;
2848                                 }
2849                         }
2850                 }
2851         }
2852
2853         //sort the bastards so we can render everything
2854         span.sort_marks();
2855
2856         return render_polyspan(surface, span,
2857                         useblend?get_blend_method():Color::BLEND_STRAIGHT,
2858                         useblend?get_amount():1.0);
2859 }
2860
2861 bool
2862 Layer_Shape::render_shape(etl::surface<float> *surface,int /*quality*/,
2863                                                         const RendDesc &renddesc, ProgressCallback */*cb*/)const
2864 {
2865         // If our amount is set to zero, no need to render anything
2866         if(!get_amount())
2867                 return true;
2868
2869         //test new polygon renderer
2870         // Build edge table
2871         // Width and Height of a pixel
2872         const int       w = renddesc.get_w();
2873         const int       h = renddesc.get_h();
2874         const Real      pw = renddesc.get_w()/(renddesc.get_br()[0]-renddesc.get_tl()[0]);
2875         const Real      ph = renddesc.get_h()/(renddesc.get_br()[1]-renddesc.get_tl()[1]);
2876
2877         const Point     tl = renddesc.get_tl();
2878
2879         Vector tangent (0,0);
2880
2881         PolySpan        span;
2882
2883         //optimization for tessellating only inside tiles
2884         span.window.minx = 0;
2885         span.window.miny = 0;
2886         span.window.maxx = w;
2887         span.window.maxy = h;
2888
2889         //pointers for processing the bytestream
2890         const char *current     = &bytestream[0];
2891         const char *end                 = &bytestream[bytestream.size()];
2892
2893         int     operation       = Primitive::NONE;
2894         int number              = 0;
2895         int curnum;
2896
2897         Primitive       *curprim;
2898         Point           *data;
2899
2900         Real x,y,x1,y1,x2,y2;
2901
2902         while(current < end)
2903         {
2904                 //get the op code safely
2905                 curprim = (Primitive *)current;
2906
2907                 //advance past indices
2908                 current += sizeof(Primitive);
2909                 if(current > end)
2910                 {
2911                         warning("Layer_Shape::accelerated_render - Error in the byte stream, not enough space for next declaration");
2912                         return false;
2913                 }
2914
2915                 //get the relevant data
2916                 operation       = curprim->operation;
2917                 number          = curprim->number;
2918
2919                 if(operation == Primitive::END)
2920                         break;
2921
2922                 if(operation == Primitive::CLOSE)
2923                 {
2924                         if(span.notclosed())
2925                         {
2926                                 tangent[0] = span.close_x - span.cur_x;
2927                                 tangent[1] = span.close_y - span.cur_y;
2928                                 span.close();
2929                         }
2930                         continue;
2931                 }
2932
2933                 data = (Point*)current;
2934                 current += sizeof(Point)*number;
2935
2936                 //check data positioning
2937                 if(current > end)
2938                 {
2939                         warning("Layer_Shape::accelerated_render - Error in the byte stream, in sufficient data space for declared number of points");
2940                         return false;
2941                 }
2942
2943                 //transfer all the data
2944                 for(curnum=0; curnum < number;)
2945                 {
2946                         switch(operation)
2947                         {
2948                                 case Primitive::MOVE_TO:
2949                                 {
2950                                         x = data[curnum][0];
2951                                         x = (x - tl[0] + offset[0])*pw;
2952                                         y = data[curnum][1];
2953                                         y = (y - tl[1] + offset[1])*ph;
2954
2955                                         if(curnum == 0)
2956                                         {
2957                                                 span.move_to(x,y);
2958
2959                                                 tangent[0] = 0;
2960                                                 tangent[1] = 0;
2961                                         }
2962                                         else
2963                                         {
2964                                                 tangent[0] = x - span.cur_x;
2965                                                 tangent[1] = y - span.cur_y;
2966
2967                                                 span.line_to(x,y);
2968                                         }
2969
2970                                         curnum++; //only advance one point
2971
2972                                         break;
2973                                 }
2974
2975                                 case Primitive::LINE_TO:
2976                                 {
2977                                         x = data[curnum][0];
2978                                         x = (x - tl[0] + offset[0])*pw;
2979                                         y = data[curnum][1];
2980                                         y = (y - tl[1] + offset[1])*ph;
2981
2982                                         tangent[0] = x - span.cur_x;
2983                                         tangent[1] = y - span.cur_y;
2984
2985                                         span.line_to(x,y);
2986                                         curnum++;
2987                                         break;
2988                                 }
2989
2990                                 case Primitive::CONIC_TO:
2991                                 {
2992                                         x = data[curnum+1][0];
2993                                         x = (x - tl[0] + offset[0])*pw;
2994                                         y = data[curnum+1][1];
2995                                         y = (y - tl[1] + offset[1])*ph;
2996
2997                                         x1 = data[curnum][0];
2998                                         x1 = (x1 - tl[0] + offset[0])*pw;
2999                                         y1 = data[curnum][1];
3000                                         y1 = (y1 - tl[1] + offset[1])*ph;
3001
3002                                         tangent[0] = 2*(x - x1);
3003                                         tangent[1] = 2*(y - y1);
3004
3005                                         span.conic_to(x1,y1,x,y);
3006                                         curnum += 2;
3007                                         break;
3008                                 }
3009
3010                                 case Primitive::CONIC_TO_SMOOTH:
3011                                 {
3012                                         x = data[curnum][0];
3013                                         x = (x - tl[0] + offset[0])*pw;
3014                                         y = data[curnum][1];
3015                                         y = (y - tl[1] + offset[1])*ph;
3016
3017                                         x1 = span.cur_x + tangent[0]/2;
3018                                         y1 = span.cur_y + tangent[1]/2;
3019
3020                                         tangent[0] = 2*(x - x1);
3021                                         tangent[1] = 2*(y - y1);
3022
3023                                         span.conic_to(x1,y1,x,y);
3024                                         curnum ++;
3025
3026                                         break;
3027                                 }
3028
3029                                 case Primitive::CUBIC_TO:
3030                                 {
3031                                         x = data[curnum+2][0];
3032                                         x = (x - tl[0] + offset[0])*pw;
3033                                         y = data[curnum+2][1];
3034                                         y = (y - tl[1] + offset[1])*ph;
3035
3036                                         x2 = data[curnum+1][0];
3037                                         x2 = (x2 - tl[0] + offset[0])*pw;
3038                                         y2 = data[curnum+1][1];
3039                                         y2 = (y2 - tl[1] + offset[1])*ph;
3040
3041                                         x1 = data[curnum][0];
3042                                         x1 = (x1 - tl[0] + offset[0])*pw;
3043                                         y1 = data[curnum][1];
3044                                         y1 = (y1 - tl[1] + offset[1])*ph;
3045
3046                                         tangent[0] = 2*(x - x2);
3047                                         tangent[1] = 2*(y - y2);
3048
3049                                         span.cubic_to(x1,y1,x2,y2,x,y);
3050                                         curnum += 3;
3051
3052                                         break;
3053                                 }
3054
3055                                 case Primitive::CUBIC_TO_SMOOTH:
3056                                 {
3057                                         x = data[curnum+1][0];
3058                                         x = (x - tl[0] + offset[0])*pw;
3059                                         y = data[curnum+1][1];
3060                                         y = (y - tl[1] + offset[1])*ph;
3061
3062                                         x2 = data[curnum][0];
3063                                         x2 = (x2 - tl[0] + offset[0])*pw;
3064                                         y2 = data[curnum][1];
3065                                         y2 = (y2 - tl[1] + offset[1])*ph;
3066
3067                                         x1 = span.cur_x + tangent[0]/3.0;
3068                                         y1 = span.cur_y + tangent[1]/3.0;
3069
3070                                         tangent[0] = 2*(x - x2);
3071                                         tangent[1] = 2*(y - y2);
3072
3073                                         span.cubic_to(x1,y1,x2,y2,x,y);
3074                                         curnum += 2;
3075
3076                                         break;
3077                                 }
3078                         }
3079                 }
3080         }
3081
3082         //sort the bastards so we can render everything
3083         span.sort_marks();
3084
3085         return render_polyspan(surface, span);
3086 }
3087
3088 Rect
3089 Layer_Shape::get_bounding_rect()const
3090 {
3091         if(invert)
3092                 return Rect::full_plane();
3093
3094         if (edge_table->initaabb)
3095                 return Rect::zero();
3096
3097         Rect bounds(edge_table->aabb+offset);
3098         bounds.expand(max((bounds.get_min() - bounds.get_max()).mag()*0.01,
3099                                           feather));
3100
3101         return bounds;
3102 }