]> granicus.if.org Git - imagemagick/blob - MagickCore/draw.c
(no commit message)
[imagemagick] / MagickCore / draw.c
1 /*
2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3 %                                                                             %
4 %                                                                             %
5 %                                                                             %
6 %                        DDDD   RRRR    AAA   W   W                           %
7 %                        D   D  R   R  A   A  W   W                           %
8 %                        D   D  RRRR   AAAAA  W W W                           %
9 %                        D   D  R RN   A   A  WW WW                           %
10 %                        DDDD   R  R   A   A  W   W                           %
11 %                                                                             %
12 %                                                                             %
13 %                     MagickCore Image Drawing Methods                        %
14 %                                                                             %
15 %                                                                             %
16 %                              Software Design                                %
17 %                                John Cristy                                  %
18 %                                 July 1998                                   %
19 %                                                                             %
20 %                                                                             %
21 %  Copyright 1999-2012 ImageMagick Studio LLC, a non-profit organization      %
22 %  dedicated to making software imaging solutions freely available.           %
23 %                                                                             %
24 %  You may not use this file except in compliance with the License.  You may  %
25 %  obtain a copy of the License at                                            %
26 %                                                                             %
27 %    http://www.imagemagick.org/script/license.php                            %
28 %                                                                             %
29 %  Unless required by applicable law or agreed to in writing, software        %
30 %  distributed under the License is distributed on an "AS IS" BASIS,          %
31 %  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   %
32 %  See the License for the specific language governing permissions and        %
33 %  limitations under the License.                                             %
34 %                                                                             %
35 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
36 %
37 % Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
38 % rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
39 % Graphics Gems, 1990.  Leonard Rosenthal and David Harr of Appligent
40 % (www.appligent.com) contributed the dash pattern, linecap stroking
41 % algorithm, and minor rendering improvements.
42 %
43 */
44 \f
45 /*
46   Include declarations.
47 */
48 #include "MagickCore/studio.h"
49 #include "MagickCore/annotate.h"
50 #include "MagickCore/artifact.h"
51 #include "MagickCore/blob.h"
52 #include "MagickCore/cache.h"
53 #include "MagickCore/cache-view.h"
54 #include "MagickCore/color.h"
55 #include "MagickCore/colorspace-private.h"
56 #include "MagickCore/composite.h"
57 #include "MagickCore/composite-private.h"
58 #include "MagickCore/constitute.h"
59 #include "MagickCore/draw.h"
60 #include "MagickCore/draw-private.h"
61 #include "MagickCore/enhance.h"
62 #include "MagickCore/exception.h"
63 #include "MagickCore/exception-private.h"
64 #include "MagickCore/gem.h"
65 #include "MagickCore/geometry.h"
66 #include "MagickCore/image-private.h"
67 #include "MagickCore/list.h"
68 #include "MagickCore/log.h"
69 #include "MagickCore/monitor.h"
70 #include "MagickCore/monitor-private.h"
71 #include "MagickCore/option.h"
72 #include "MagickCore/paint.h"
73 #include "MagickCore/pixel-accessor.h"
74 #include "MagickCore/pixel-private.h"
75 #include "MagickCore/property.h"
76 #include "MagickCore/resample.h"
77 #include "MagickCore/resample-private.h"
78 #include "MagickCore/resource_.h"
79 #include "MagickCore/string_.h"
80 #include "MagickCore/string-private.h"
81 #include "MagickCore/thread-private.h"
82 #include "MagickCore/token.h"
83 #include "MagickCore/transform.h"
84 #include "MagickCore/utility.h"
85 \f
86 /*
87   Define declarations.
88 */
89 #define BezierQuantum  200
90 \f
91 /*
92   Typedef declarations.
93 */
94 typedef struct _EdgeInfo
95 {
96   SegmentInfo
97     bounds;
98
99   double
100     scanline;
101
102   PointInfo
103     *points;
104
105   size_t
106     number_points;
107
108   ssize_t
109     direction;
110
111   MagickBooleanType
112     ghostline;
113
114   size_t
115     highwater;
116 } EdgeInfo;
117
118 typedef struct _ElementInfo
119 {
120   double
121     cx,
122     cy,
123     major,
124     minor,
125     angle;
126 } ElementInfo;
127
128 typedef struct _PolygonInfo
129 {
130   EdgeInfo
131     *edges;
132
133   size_t
134     number_edges;
135 } PolygonInfo;
136
137 typedef enum
138 {
139   MoveToCode,
140   OpenCode,
141   GhostlineCode,
142   LineToCode,
143   EndCode
144 } PathInfoCode;
145
146 typedef struct _PathInfo
147 {
148   PointInfo
149     point;
150
151   PathInfoCode
152     code;
153 } PathInfo;
154 \f
155 /*
156   Forward declarations.
157 */
158 static MagickBooleanType
159   DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,
160     ExceptionInfo *);
161
162 static PrimitiveInfo
163   *TraceStrokePolygon(const DrawInfo *,const PrimitiveInfo *);
164
165 static size_t
166   TracePath(PrimitiveInfo *,const char *);
167
168 static void
169   TraceArc(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
170   TraceArcPath(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo,
171     const double,const MagickBooleanType,const MagickBooleanType),
172   TraceBezier(PrimitiveInfo *,const size_t),
173   TraceCircle(PrimitiveInfo *,const PointInfo,const PointInfo),
174   TraceEllipse(PrimitiveInfo *,const PointInfo,const PointInfo,const PointInfo),
175   TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
176   TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
177   TraceRoundRectangle(PrimitiveInfo *,const PointInfo,const PointInfo,
178     PointInfo),
179   TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
180 \f
181 /*
182 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
183 %                                                                             %
184 %                                                                             %
185 %                                                                             %
186 %   A c q u i r e D r a w I n f o                                             %
187 %                                                                             %
188 %                                                                             %
189 %                                                                             %
190 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
191 %
192 %  AcquireDrawInfo() returns a DrawInfo structure properly initialized.
193 %
194 %  The format of the AcquireDrawInfo method is:
195 %
196 %      DrawInfo *AcquireDrawInfo(void)
197 %
198 */
199 MagickExport DrawInfo *AcquireDrawInfo(void)
200 {
201   DrawInfo
202     *draw_info;
203
204   draw_info=(DrawInfo *) AcquireMagickMemory(sizeof(*draw_info));
205   if (draw_info == (DrawInfo *) NULL)
206     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
207   GetDrawInfo((ImageInfo *) NULL,draw_info);
208   return(draw_info);
209 }
210 \f
211 /*
212 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
213 %                                                                             %
214 %                                                                             %
215 %                                                                             %
216 %   C l o n e D r a w I n f o                                                 %
217 %                                                                             %
218 %                                                                             %
219 %                                                                             %
220 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
221 %
222 %  CloneDrawInfo() makes a copy of the given draw_info structure.  If NULL
223 %  is specified, a new draw_info structure is created initialized to
224 %  default values, according to the given image_info.
225 %
226 %  The format of the CloneDrawInfo method is:
227 %
228 %      DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
229 %        const DrawInfo *draw_info)
230 %
231 %  A description of each parameter follows:
232 %
233 %    o image_info: the image info.
234 %
235 %    o draw_info: the draw info.
236 %
237 */
238 MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
239   const DrawInfo *draw_info)
240 {
241   DrawInfo
242     *clone_info;
243
244   ExceptionInfo
245     *exception;
246
247   clone_info=(DrawInfo *) AcquireMagickMemory(sizeof(*clone_info));
248   if (clone_info == (DrawInfo *) NULL)
249     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
250   GetDrawInfo(image_info,clone_info);
251   if (draw_info == (DrawInfo *) NULL)
252     return(clone_info);
253   exception=AcquireExceptionInfo();
254   (void) CloneString(&clone_info->primitive,draw_info->primitive);
255   (void) CloneString(&clone_info->geometry,draw_info->geometry);
256   clone_info->viewbox=draw_info->viewbox;
257   clone_info->affine=draw_info->affine;
258   clone_info->gravity=draw_info->gravity;
259   clone_info->fill=draw_info->fill;
260   clone_info->stroke=draw_info->stroke;
261   clone_info->stroke_width=draw_info->stroke_width;
262   if (draw_info->fill_pattern != (Image *) NULL)
263     clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
264       exception);
265   if (draw_info->stroke_pattern != (Image *) NULL)
266     clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
267       MagickTrue,exception);
268   clone_info->stroke_antialias=draw_info->stroke_antialias;
269   clone_info->text_antialias=draw_info->text_antialias;
270   clone_info->fill_rule=draw_info->fill_rule;
271   clone_info->linecap=draw_info->linecap;
272   clone_info->linejoin=draw_info->linejoin;
273   clone_info->miterlimit=draw_info->miterlimit;
274   clone_info->dash_offset=draw_info->dash_offset;
275   clone_info->decorate=draw_info->decorate;
276   clone_info->compose=draw_info->compose;
277   (void) CloneString(&clone_info->text,draw_info->text);
278   (void) CloneString(&clone_info->font,draw_info->font);
279   (void) CloneString(&clone_info->metrics,draw_info->metrics);
280   (void) CloneString(&clone_info->family,draw_info->family);
281   clone_info->style=draw_info->style;
282   clone_info->stretch=draw_info->stretch;
283   clone_info->weight=draw_info->weight;
284   (void) CloneString(&clone_info->encoding,draw_info->encoding);
285   clone_info->pointsize=draw_info->pointsize;
286   clone_info->kerning=draw_info->kerning;
287   clone_info->interline_spacing=draw_info->interline_spacing;
288   clone_info->interword_spacing=draw_info->interword_spacing;
289   clone_info->direction=draw_info->direction;
290   (void) CloneString(&clone_info->density,draw_info->density);
291   clone_info->align=draw_info->align;
292   clone_info->undercolor=draw_info->undercolor;
293   clone_info->border_color=draw_info->border_color;
294   (void) CloneString(&clone_info->server_name,draw_info->server_name);
295   if (draw_info->dash_pattern != (double *) NULL)
296     {
297       register ssize_t
298         x;
299
300       for (x=0; draw_info->dash_pattern[x] != 0.0; x++) ;
301       clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) x+1UL,
302         sizeof(*clone_info->dash_pattern));
303       if (clone_info->dash_pattern == (double *) NULL)
304         ThrowFatalException(ResourceLimitFatalError,
305           "UnableToAllocateDashPattern");
306       (void) CopyMagickMemory(clone_info->dash_pattern,draw_info->dash_pattern,
307         (size_t) (x+1)*sizeof(*clone_info->dash_pattern));
308     }
309   clone_info->gradient=draw_info->gradient;
310   if (draw_info->gradient.stops != (StopInfo *) NULL)
311     {
312       size_t
313         number_stops;
314
315       number_stops=clone_info->gradient.number_stops;
316       clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
317         number_stops,sizeof(*clone_info->gradient.stops));
318       if (clone_info->gradient.stops == (StopInfo *) NULL)
319         ThrowFatalException(ResourceLimitFatalError,
320           "UnableToAllocateDashPattern");
321       (void) CopyMagickMemory(clone_info->gradient.stops,
322         draw_info->gradient.stops,(size_t) number_stops*
323         sizeof(*clone_info->gradient.stops));
324     }
325   (void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
326   clone_info->bounds=draw_info->bounds;
327   clone_info->clip_units=draw_info->clip_units;
328   clone_info->render=draw_info->render;
329   clone_info->alpha=draw_info->alpha;
330   clone_info->element_reference=draw_info->element_reference;
331   clone_info->debug=IsEventLogging();
332   exception=DestroyExceptionInfo(exception);
333   return(clone_info);
334 }
335 \f
336 /*
337 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
338 %                                                                             %
339 %                                                                             %
340 %                                                                             %
341 +   C o n v e r t P a t h T o P o l y g o n                                   %
342 %                                                                             %
343 %                                                                             %
344 %                                                                             %
345 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
346 %
347 %  ConvertPathToPolygon() converts a path to the more efficient sorted
348 %  rendering form.
349 %
350 %  The format of the ConvertPathToPolygon method is:
351 %
352 %      PolygonInfo *ConvertPathToPolygon(const DrawInfo *draw_info,
353 %        const PathInfo *path_info)
354 %
355 %  A description of each parameter follows:
356 %
357 %    o Method ConvertPathToPolygon returns the path in a more efficient sorted
358 %      rendering form of type PolygonInfo.
359 %
360 %    o draw_info: Specifies a pointer to an DrawInfo structure.
361 %
362 %    o path_info: Specifies a pointer to an PathInfo structure.
363 %
364 %
365 */
366
367 #if defined(__cplusplus) || defined(c_plusplus)
368 extern "C" {
369 #endif
370
371 static int CompareEdges(const void *x,const void *y)
372 {
373   register const EdgeInfo
374     *p,
375     *q;
376
377   /*
378     Compare two edges.
379   */
380   p=(const EdgeInfo *) x;
381   q=(const EdgeInfo *) y;
382   if ((p->points[0].y-MagickEpsilon) > q->points[0].y)
383     return(1);
384   if ((p->points[0].y+MagickEpsilon) < q->points[0].y)
385     return(-1);
386   if ((p->points[0].x-MagickEpsilon) > q->points[0].x)
387     return(1);
388   if ((p->points[0].x+MagickEpsilon) < q->points[0].x)
389     return(-1);
390   if (((p->points[1].x-p->points[0].x)*(q->points[1].y-q->points[0].y)-
391        (p->points[1].y-p->points[0].y)*(q->points[1].x-q->points[0].x)) > 0.0)
392     return(1);
393   return(-1);
394 }
395
396 #if defined(__cplusplus) || defined(c_plusplus)
397 }
398 #endif
399
400 static void LogPolygonInfo(const PolygonInfo *polygon_info)
401 {
402   register EdgeInfo
403     *p;
404
405   register ssize_t
406     i,
407     j;
408
409   (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    begin active-edge");
410   p=polygon_info->edges;
411   for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
412   {
413     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"      edge %.20g:",
414       (double) i);
415     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"      direction: %s",
416       p->direction != MagickFalse ? "down" : "up");
417     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"      ghostline: %s",
418       p->ghostline != MagickFalse ? "transparent" : "opaque");
419     (void) LogMagickEvent(DrawEvent,GetMagickModule(),
420       "      bounds: %g %g - %g %g",p->bounds.x1,p->bounds.y1,
421       p->bounds.x2,p->bounds.y2);
422     for (j=0; j < (ssize_t) p->number_points; j++)
423       (void) LogMagickEvent(DrawEvent,GetMagickModule(),"        %g %g",
424         p->points[j].x,p->points[j].y);
425     p++;
426   }
427   (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end active-edge");
428 }
429
430 static void ReversePoints(PointInfo *points,const size_t number_points)
431 {
432   PointInfo
433     point;
434
435   register ssize_t
436     i;
437
438   for (i=0; i < (ssize_t) (number_points >> 1); i++)
439   {
440     point=points[i];
441     points[i]=points[number_points-(i+1)];
442     points[number_points-(i+1)]=point;
443   }
444 }
445
446 static PolygonInfo *ConvertPathToPolygon(
447   const DrawInfo *magick_unused(draw_info),const PathInfo *path_info)
448 {
449   long
450     direction,
451     next_direction;
452
453   PointInfo
454     point,
455     *points;
456
457   PolygonInfo
458     *polygon_info;
459
460   SegmentInfo
461     bounds;
462
463   register ssize_t
464     i,
465     n;
466
467   MagickBooleanType
468     ghostline;
469
470   size_t
471     edge,
472     number_edges,
473     number_points;
474
475   /*
476     Convert a path to the more efficient sorted rendering form.
477   */
478   polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
479   if (polygon_info == (PolygonInfo *) NULL)
480     return((PolygonInfo *) NULL);
481   number_edges=16;
482   polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory((size_t) number_edges,
483     sizeof(*polygon_info->edges));
484   if (polygon_info->edges == (EdgeInfo *) NULL)
485     return((PolygonInfo *) NULL);
486   direction=0;
487   edge=0;
488   ghostline=MagickFalse;
489   n=0;
490   number_points=0;
491   points=(PointInfo *) NULL;
492   (void) ResetMagickMemory(&point,0,sizeof(point));
493   (void) ResetMagickMemory(&bounds,0,sizeof(bounds));
494   for (i=0; path_info[i].code != EndCode; i++)
495   {
496     if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
497         (path_info[i].code == GhostlineCode))
498       {
499         /*
500           Move to.
501         */
502         if ((points != (PointInfo *) NULL) && (n >= 2))
503           {
504             if (edge == number_edges)
505               {
506                 number_edges<<=1;
507                 polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
508                   polygon_info->edges,(size_t) number_edges,
509                   sizeof(*polygon_info->edges));
510                 if (polygon_info->edges == (EdgeInfo *) NULL)
511                   return((PolygonInfo *) NULL);
512               }
513             polygon_info->edges[edge].number_points=(size_t) n;
514             polygon_info->edges[edge].scanline=(-1.0);
515             polygon_info->edges[edge].highwater=0;
516             polygon_info->edges[edge].ghostline=ghostline;
517             polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
518             if (direction < 0)
519               ReversePoints(points,(size_t) n);
520             polygon_info->edges[edge].points=points;
521             polygon_info->edges[edge].bounds=bounds;
522             polygon_info->edges[edge].bounds.y1=points[0].y;
523             polygon_info->edges[edge].bounds.y2=points[n-1].y;
524             points=(PointInfo *) NULL;
525             ghostline=MagickFalse;
526             edge++;
527           }
528         if (points == (PointInfo *) NULL)
529           {
530             number_points=16;
531             points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
532               sizeof(*points));
533             if (points == (PointInfo *) NULL)
534               return((PolygonInfo *) NULL);
535           }
536         ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
537         point=path_info[i].point;
538         points[0]=point;
539         bounds.x1=point.x;
540         bounds.x2=point.x;
541         direction=0;
542         n=1;
543         continue;
544       }
545     /*
546       Line to.
547     */
548     next_direction=((path_info[i].point.y > point.y) ||
549       ((path_info[i].point.y == point.y) &&
550        (path_info[i].point.x > point.x))) ? 1 : -1;
551     if ((direction != 0) && (direction != next_direction))
552       {
553         /*
554           New edge.
555         */
556         point=points[n-1];
557         if (edge == number_edges)
558           {
559             number_edges<<=1;
560             polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
561               polygon_info->edges,(size_t) number_edges,
562               sizeof(*polygon_info->edges));
563             if (polygon_info->edges == (EdgeInfo *) NULL)
564               return((PolygonInfo *) NULL);
565           }
566         polygon_info->edges[edge].number_points=(size_t) n;
567         polygon_info->edges[edge].scanline=(-1.0);
568         polygon_info->edges[edge].highwater=0;
569         polygon_info->edges[edge].ghostline=ghostline;
570         polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
571         if (direction < 0)
572           ReversePoints(points,(size_t) n);
573         polygon_info->edges[edge].points=points;
574         polygon_info->edges[edge].bounds=bounds;
575         polygon_info->edges[edge].bounds.y1=points[0].y;
576         polygon_info->edges[edge].bounds.y2=points[n-1].y;
577         number_points=16;
578         points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
579           sizeof(*points));
580         if (points == (PointInfo *) NULL)
581           return((PolygonInfo *) NULL);
582         n=1;
583         ghostline=MagickFalse;
584         points[0]=point;
585         bounds.x1=point.x;
586         bounds.x2=point.x;
587         edge++;
588       }
589     direction=next_direction;
590     if (points == (PointInfo *) NULL)
591       continue;
592     if (n == (ssize_t) number_points)
593       {
594         number_points<<=1;
595         points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
596           sizeof(*points));
597         if (points == (PointInfo *) NULL)
598           return((PolygonInfo *) NULL);
599       }
600     point=path_info[i].point;
601     points[n]=point;
602     if (point.x < bounds.x1)
603       bounds.x1=point.x;
604     if (point.x > bounds.x2)
605       bounds.x2=point.x;
606     n++;
607   }
608   if (points != (PointInfo *) NULL)
609     {
610       if (n < 2)
611         points=(PointInfo *) RelinquishMagickMemory(points);
612       else
613         {
614           if (edge == number_edges)
615             {
616               number_edges<<=1;
617               polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
618                 polygon_info->edges,(size_t) number_edges,
619                 sizeof(*polygon_info->edges));
620               if (polygon_info->edges == (EdgeInfo *) NULL)
621                 return((PolygonInfo *) NULL);
622             }
623           polygon_info->edges[edge].number_points=(size_t) n;
624           polygon_info->edges[edge].scanline=(-1.0);
625           polygon_info->edges[edge].highwater=0;
626           polygon_info->edges[edge].ghostline=ghostline;
627           polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
628           if (direction < 0)
629             ReversePoints(points,(size_t) n);
630           polygon_info->edges[edge].points=points;
631           polygon_info->edges[edge].bounds=bounds;
632           polygon_info->edges[edge].bounds.y1=points[0].y;
633           polygon_info->edges[edge].bounds.y2=points[n-1].y;
634           ghostline=MagickFalse;
635           edge++;
636         }
637     }
638   polygon_info->number_edges=edge;
639   qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
640     sizeof(*polygon_info->edges),CompareEdges);
641   if (IsEventLogging() != MagickFalse)
642     LogPolygonInfo(polygon_info);
643   return(polygon_info);
644 }
645 \f
646 /*
647 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
648 %                                                                             %
649 %                                                                             %
650 %                                                                             %
651 +   C o n v e r t P r i m i t i v e T o P a t h                               %
652 %                                                                             %
653 %                                                                             %
654 %                                                                             %
655 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
656 %
657 %  ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
658 %  path structure.
659 %
660 %  The format of the ConvertPrimitiveToPath method is:
661 %
662 %      PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
663 %        const PrimitiveInfo *primitive_info)
664 %
665 %  A description of each parameter follows:
666 %
667 %    o Method ConvertPrimitiveToPath returns a vector path structure of type
668 %      PathInfo.
669 %
670 %    o draw_info: a structure of type DrawInfo.
671 %
672 %    o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
673 %
674 %
675 */
676
677 static void LogPathInfo(const PathInfo *path_info)
678 {
679   register const PathInfo
680     *p;
681
682   (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    begin vector-path");
683   for (p=path_info; p->code != EndCode; p++)
684     (void) LogMagickEvent(DrawEvent,GetMagickModule(),
685       "      %g %g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
686       "moveto ghostline" : p->code == OpenCode ? "moveto open" :
687       p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
688       "?");
689   (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end vector-path");
690 }
691
692 static PathInfo *ConvertPrimitiveToPath(
693   const DrawInfo *magick_unused(draw_info),const PrimitiveInfo *primitive_info)
694 {
695   PathInfo
696     *path_info;
697
698   PathInfoCode
699     code;
700
701   PointInfo
702     p,
703     q;
704
705   register ssize_t
706     i,
707     n;
708
709   ssize_t
710     coordinates,
711     start;
712
713   /*
714     Converts a PrimitiveInfo structure into a vector path structure.
715   */
716   switch (primitive_info->primitive)
717   {
718     case PointPrimitive:
719     case ColorPrimitive:
720     case MattePrimitive:
721     case TextPrimitive:
722     case ImagePrimitive:
723       return((PathInfo *) NULL);
724     default:
725       break;
726   }
727   for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
728   path_info=(PathInfo *) AcquireQuantumMemory((size_t) (2UL*i+3UL),
729     sizeof(*path_info));
730   if (path_info == (PathInfo *) NULL)
731     return((PathInfo *) NULL);
732   coordinates=0;
733   n=0;
734   p.x=(-1.0);
735   p.y=(-1.0);
736   q.x=(-1.0);
737   q.y=(-1.0);
738   start=0;
739   for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
740   {
741     code=LineToCode;
742     if (coordinates <= 0)
743       {
744         coordinates=(ssize_t) primitive_info[i].coordinates;
745         p=primitive_info[i].point;
746         start=n;
747         code=MoveToCode;
748       }
749     coordinates--;
750     /*
751       Eliminate duplicate points.
752     */
753     if ((i == 0) || (fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||
754         (fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))
755       {
756         path_info[n].code=code;
757         path_info[n].point=primitive_info[i].point;
758         q=primitive_info[i].point;
759         n++;
760       }
761     if (coordinates > 0)
762       continue;
763     if ((fabs(p.x-primitive_info[i].point.x) < MagickEpsilon) &&
764         (fabs(p.y-primitive_info[i].point.y) < MagickEpsilon))
765       continue;
766     /*
767       Mark the p point as open if it does not match the q.
768     */
769     path_info[start].code=OpenCode;
770     path_info[n].code=GhostlineCode;
771     path_info[n].point=primitive_info[i].point;
772     n++;
773     path_info[n].code=LineToCode;
774     path_info[n].point=p;
775     n++;
776   }
777   path_info[n].code=EndCode;
778   path_info[n].point.x=0.0;
779   path_info[n].point.y=0.0;
780   if (IsEventLogging() != MagickFalse)
781     LogPathInfo(path_info);
782   return(path_info);
783 }
784 \f
785 /*
786 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
787 %                                                                             %
788 %                                                                             %
789 %                                                                             %
790 %   D e s t r o y D r a w I n f o                                             %
791 %                                                                             %
792 %                                                                             %
793 %                                                                             %
794 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
795 %
796 %  DestroyDrawInfo() deallocates memory associated with an DrawInfo
797 %  structure.
798 %
799 %  The format of the DestroyDrawInfo method is:
800 %
801 %      DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
802 %
803 %  A description of each parameter follows:
804 %
805 %    o draw_info: the draw info.
806 %
807 */
808 MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
809 {
810   if (draw_info->debug != MagickFalse)
811     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
812   assert(draw_info != (DrawInfo *) NULL);
813   assert(draw_info->signature == MagickSignature);
814   if (draw_info->primitive != (char *) NULL)
815     draw_info->primitive=DestroyString(draw_info->primitive);
816   if (draw_info->text != (char *) NULL)
817     draw_info->text=DestroyString(draw_info->text);
818   if (draw_info->geometry != (char *) NULL)
819     draw_info->geometry=DestroyString(draw_info->geometry);
820   if (draw_info->fill_pattern != (Image *) NULL)
821     draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
822   if (draw_info->stroke_pattern != (Image *) NULL)
823     draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
824   if (draw_info->font != (char *) NULL)
825     draw_info->font=DestroyString(draw_info->font);
826   if (draw_info->metrics != (char *) NULL)
827     draw_info->metrics=DestroyString(draw_info->metrics);
828   if (draw_info->family != (char *) NULL)
829     draw_info->family=DestroyString(draw_info->family);
830   if (draw_info->encoding != (char *) NULL)
831     draw_info->encoding=DestroyString(draw_info->encoding);
832   if (draw_info->density != (char *) NULL)
833     draw_info->density=DestroyString(draw_info->density);
834   if (draw_info->server_name != (char *) NULL)
835     draw_info->server_name=(char *)
836      RelinquishMagickMemory(draw_info->server_name);
837   if (draw_info->dash_pattern != (double *) NULL)
838     draw_info->dash_pattern=(double *) RelinquishMagickMemory(
839       draw_info->dash_pattern);
840   if (draw_info->gradient.stops != (StopInfo *) NULL)
841     draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
842       draw_info->gradient.stops);
843   if (draw_info->clip_mask != (char *) NULL)
844     draw_info->clip_mask=DestroyString(draw_info->clip_mask);
845   draw_info->signature=(~MagickSignature);
846   draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
847   return(draw_info);
848 }
849 \f
850 /*
851 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
852 %                                                                             %
853 %                                                                             %
854 %                                                                             %
855 +   D e s t r o y E d g e                                                     %
856 %                                                                             %
857 %                                                                             %
858 %                                                                             %
859 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
860 %
861 %  DestroyEdge() destroys the specified polygon edge.
862 %
863 %  The format of the DestroyEdge method is:
864 %
865 %      ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
866 %
867 %  A description of each parameter follows:
868 %
869 %    o polygon_info: Specifies a pointer to an PolygonInfo structure.
870 %
871 %    o edge: the polygon edge number to destroy.
872 %
873 */
874 static size_t DestroyEdge(PolygonInfo *polygon_info,
875   const size_t edge)
876 {
877   assert(edge < polygon_info->number_edges);
878   polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
879     polygon_info->edges[edge].points);
880   polygon_info->number_edges--;
881   if (edge < polygon_info->number_edges)
882     (void) CopyMagickMemory(polygon_info->edges+edge,polygon_info->edges+edge+1,
883       (size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
884   return(polygon_info->number_edges);
885 }
886 \f
887 /*
888 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
889 %                                                                             %
890 %                                                                             %
891 %                                                                             %
892 +   D e s t r o y P o l y g o n I n f o                                       %
893 %                                                                             %
894 %                                                                             %
895 %                                                                             %
896 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
897 %
898 %  DestroyPolygonInfo() destroys the PolygonInfo data structure.
899 %
900 %  The format of the DestroyPolygonInfo method is:
901 %
902 %      PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
903 %
904 %  A description of each parameter follows:
905 %
906 %    o polygon_info: Specifies a pointer to an PolygonInfo structure.
907 %
908 */
909 static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
910 {
911   register ssize_t
912     i;
913
914   for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
915     polygon_info->edges[i].points=(PointInfo *)
916       RelinquishMagickMemory(polygon_info->edges[i].points);
917   polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
918   return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
919 }
920 \f
921 /*
922 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
923 %                                                                             %
924 %                                                                             %
925 %                                                                             %
926 %     D r a w A f f i n e I m a g e                                           %
927 %                                                                             %
928 %                                                                             %
929 %                                                                             %
930 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
931 %
932 %  DrawAffineImage() composites the source over the destination image as
933 %  dictated by the affine transform.
934 %
935 %  The format of the DrawAffineImage method is:
936 %
937 %      MagickBooleanType DrawAffineImage(Image *image,const Image *source,
938 %        const AffineMatrix *affine,ExceptionInfo *exception)
939 %
940 %  A description of each parameter follows:
941 %
942 %    o image: the image.
943 %
944 %    o source: the source image.
945 %
946 %    o affine: the affine transform.
947 %
948 %    o exception: return any errors or warnings in this structure.
949 %
950 */
951
952 static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
953   const double y,const SegmentInfo *edge)
954 {
955   double
956     intercept,
957     z;
958
959   register double
960     x;
961
962   SegmentInfo
963     inverse_edge;
964
965   /*
966     Determine left and right edges.
967   */
968   inverse_edge.x1=edge->x1;
969   inverse_edge.y1=edge->y1;
970   inverse_edge.x2=edge->x2;
971   inverse_edge.y2=edge->y2;
972   z=affine->ry*y+affine->tx;
973   if (affine->sx >= MagickEpsilon)
974     {
975       intercept=(-z/affine->sx);
976       x=intercept;
977       if (x > inverse_edge.x1)
978         inverse_edge.x1=x;
979       intercept=(-z+(double) image->columns)/affine->sx;
980       x=intercept;
981       if (x < inverse_edge.x2)
982         inverse_edge.x2=x;
983     }
984   else
985     if (affine->sx < -MagickEpsilon)
986       {
987         intercept=(-z+(double) image->columns)/affine->sx;
988         x=intercept;
989         if (x > inverse_edge.x1)
990           inverse_edge.x1=x;
991         intercept=(-z/affine->sx);
992         x=intercept;
993         if (x < inverse_edge.x2)
994           inverse_edge.x2=x;
995       }
996     else
997       if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
998         {
999           inverse_edge.x2=edge->x1;
1000           return(inverse_edge);
1001         }
1002   /*
1003     Determine top and bottom edges.
1004   */
1005   z=affine->sy*y+affine->ty;
1006   if (affine->rx >= MagickEpsilon)
1007     {
1008       intercept=(-z/affine->rx);
1009       x=intercept;
1010       if (x > inverse_edge.x1)
1011         inverse_edge.x1=x;
1012       intercept=(-z+(double) image->rows)/affine->rx;
1013       x=intercept;
1014       if (x < inverse_edge.x2)
1015         inverse_edge.x2=x;
1016     }
1017   else
1018     if (affine->rx < -MagickEpsilon)
1019       {
1020         intercept=(-z+(double) image->rows)/affine->rx;
1021         x=intercept;
1022         if (x > inverse_edge.x1)
1023           inverse_edge.x1=x;
1024         intercept=(-z/affine->rx);
1025         x=intercept;
1026         if (x < inverse_edge.x2)
1027           inverse_edge.x2=x;
1028       }
1029     else
1030       if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
1031         {
1032           inverse_edge.x2=edge->x2;
1033           return(inverse_edge);
1034         }
1035   return(inverse_edge);
1036 }
1037
1038 static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
1039 {
1040   AffineMatrix
1041     inverse_affine;
1042
1043   double
1044     determinant;
1045
1046   determinant=MagickEpsilonReciprocal(affine->sx*affine->sy-affine->rx*
1047     affine->ry);
1048   inverse_affine.sx=determinant*affine->sy;
1049   inverse_affine.rx=determinant*(-affine->rx);
1050   inverse_affine.ry=determinant*(-affine->ry);
1051   inverse_affine.sy=determinant*affine->sx;
1052   inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
1053     inverse_affine.ry;
1054   inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
1055     inverse_affine.sy;
1056   return(inverse_affine);
1057 }
1058
1059 static inline ssize_t MagickAbsoluteValue(const ssize_t x)
1060 {
1061   if (x < 0)
1062     return(-x);
1063   return(x);
1064 }
1065
1066 static inline double MagickMax(const double x,const double y)
1067 {
1068   if (x > y)
1069     return(x);
1070   return(y);
1071 }
1072
1073 static inline double MagickMin(const double x,const double y)
1074 {
1075   if (x < y)
1076     return(x);
1077   return(y);
1078 }
1079
1080 MagickExport MagickBooleanType DrawAffineImage(Image *image,
1081   const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)
1082 {
1083   AffineMatrix
1084     inverse_affine;
1085
1086   CacheView
1087     *image_view,
1088     *source_view;
1089
1090   MagickBooleanType
1091     status;
1092
1093   PixelInfo
1094     zero;
1095
1096   PointInfo
1097     extent[4],
1098     min,
1099     max,
1100     point;
1101
1102   register ssize_t
1103     i;
1104
1105   SegmentInfo
1106     edge;
1107
1108   size_t
1109     height,
1110     width;
1111
1112   ssize_t
1113     start,
1114     stop,
1115     y;
1116
1117   /*
1118     Determine bounding box.
1119   */
1120   assert(image != (Image *) NULL);
1121   assert(image->signature == MagickSignature);
1122   if (image->debug != MagickFalse)
1123     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1124   assert(source != (const Image *) NULL);
1125   assert(source->signature == MagickSignature);
1126   assert(affine != (AffineMatrix *) NULL);
1127   extent[0].x=0.0;
1128   extent[0].y=0.0;
1129   extent[1].x=(double) source->columns-1.0;
1130   extent[1].y=0.0;
1131   extent[2].x=(double) source->columns-1.0;
1132   extent[2].y=(double) source->rows-1.0;
1133   extent[3].x=0.0;
1134   extent[3].y=(double) source->rows-1.0;
1135   for (i=0; i < 4; i++)
1136   {
1137     point=extent[i];
1138     extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
1139     extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
1140   }
1141   min=extent[0];
1142   max=extent[0];
1143   for (i=1; i < 4; i++)
1144   {
1145     if (min.x > extent[i].x)
1146       min.x=extent[i].x;
1147     if (min.y > extent[i].y)
1148       min.y=extent[i].y;
1149     if (max.x < extent[i].x)
1150       max.x=extent[i].x;
1151     if (max.y < extent[i].y)
1152       max.y=extent[i].y;
1153   }
1154   /*
1155     Affine transform image.
1156   */
1157   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1158     return(MagickFalse);
1159   status=MagickTrue;
1160   edge.x1=MagickMax(min.x,0.0);
1161   edge.y1=MagickMax(min.y,0.0);
1162   edge.x2=MagickMin(max.x,(double) image->columns-1.0);
1163   edge.y2=MagickMin(max.y,(double) image->rows-1.0);
1164   inverse_affine=InverseAffineMatrix(affine);
1165   GetPixelInfo(image,&zero);
1166   start=(ssize_t) ceil(edge.y1-0.5);
1167   stop=(ssize_t) ceil(edge.y2-0.5);
1168   height=(size_t) (floor(edge.y2+0.5)-ceil(edge.y1-0.5));
1169   width=(size_t) (floor(edge.x2+0.5)-ceil(edge.x1-0.5));
1170   source_view=AcquireVirtualCacheView(source,exception);
1171   image_view=AcquireAuthenticCacheView(image,exception);
1172 #if defined(MAGICKCORE_OPENMP_SUPPORT)
1173   #pragma omp parallel for schedule(static) shared(status) \
1174     dynamic_number_threads(image,width,height,1)
1175 #endif
1176   for (y=start; y <= stop; y++)
1177   {
1178     PixelInfo
1179       composite,
1180       pixel;
1181
1182     PointInfo
1183       point;
1184
1185     register ssize_t
1186       x;
1187
1188     register Quantum
1189       *restrict q;
1190
1191     SegmentInfo
1192       inverse_edge;
1193
1194     ssize_t
1195       x_offset;
1196
1197     inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
1198     if (inverse_edge.x2 < inverse_edge.x1)
1199       continue;
1200     q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
1201       0.5),y,(size_t) ((ssize_t) floor(inverse_edge.x2+0.5)-(ssize_t) floor(
1202       inverse_edge.x1+0.5)+1),1,exception);
1203     if (q == (Quantum *) NULL)
1204       continue;
1205     pixel=zero;
1206     composite=zero;
1207     x_offset=0;
1208     for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
1209     {
1210       point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
1211         inverse_affine.tx;
1212       point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
1213         inverse_affine.ty;
1214       (void) InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,
1215         point.x,point.y,&pixel,exception);
1216       GetPixelInfoPixel(image,q,&composite);
1217       CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,
1218         &composite);
1219       SetPixelInfoPixel(image,&composite,q);
1220       x_offset++;
1221       q+=GetPixelChannels(image);
1222     }
1223     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
1224       status=MagickFalse;
1225   }
1226   source_view=DestroyCacheView(source_view);
1227   image_view=DestroyCacheView(image_view);
1228   return(status);
1229 }
1230 \f
1231 /*
1232 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1233 %                                                                             %
1234 %                                                                             %
1235 %                                                                             %
1236 +   D r a w B o u n d i n g R e c t a n g l e s                               %
1237 %                                                                             %
1238 %                                                                             %
1239 %                                                                             %
1240 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1241 %
1242 %  DrawBoundingRectangles() draws the bounding rectangles on the image.  This
1243 %  is only useful for developers debugging the rendering algorithm.
1244 %
1245 %  The format of the DrawBoundingRectangles method is:
1246 %
1247 %      void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
1248 %        PolygonInfo *polygon_info,ExceptionInfo *exception)
1249 %
1250 %  A description of each parameter follows:
1251 %
1252 %    o image: the image.
1253 %
1254 %    o draw_info: the draw info.
1255 %
1256 %    o polygon_info: Specifies a pointer to a PolygonInfo structure.
1257 %
1258 %    o exception: return any errors or warnings in this structure.
1259 %
1260 */
1261 static void DrawBoundingRectangles(Image *image,const DrawInfo *draw_info,
1262   const PolygonInfo *polygon_info,ExceptionInfo *exception)
1263 {
1264   DrawInfo
1265     *clone_info;
1266
1267   double
1268     mid;
1269
1270   PointInfo
1271     end,
1272     resolution,
1273     start;
1274
1275   PrimitiveInfo
1276     primitive_info[6];
1277
1278   register ssize_t
1279     i;
1280
1281   SegmentInfo
1282     bounds;
1283
1284   ssize_t
1285     coordinates;
1286
1287   clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
1288   (void) QueryColorCompliance("#0000",AllCompliance,&clone_info->fill,
1289     exception);
1290   resolution.x=DefaultResolution;
1291   resolution.y=DefaultResolution;
1292   if (clone_info->density != (char *) NULL)
1293     {
1294       GeometryInfo
1295         geometry_info;
1296
1297       MagickStatusType
1298         flags;
1299
1300       flags=ParseGeometry(clone_info->density,&geometry_info);
1301       resolution.x=geometry_info.rho;
1302       resolution.y=geometry_info.sigma;
1303       if ((flags & SigmaValue) == MagickFalse)
1304         resolution.y=resolution.x;
1305     }
1306   mid=(resolution.x/72.0)*ExpandAffine(&clone_info->affine)*
1307     clone_info->stroke_width/2.0;
1308   bounds.x1=0.0;
1309   bounds.y1=0.0;
1310   bounds.x2=0.0;
1311   bounds.y2=0.0;
1312   if (polygon_info != (PolygonInfo *) NULL)
1313     {
1314       bounds=polygon_info->edges[0].bounds;
1315       for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
1316       {
1317         if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
1318           bounds.x1=polygon_info->edges[i].bounds.x1;
1319         if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
1320           bounds.y1=polygon_info->edges[i].bounds.y1;
1321         if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
1322           bounds.x2=polygon_info->edges[i].bounds.x2;
1323         if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
1324           bounds.y2=polygon_info->edges[i].bounds.y2;
1325       }
1326       bounds.x1-=mid;
1327       bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
1328         image->columns ? (double) image->columns-1 : bounds.x1;
1329       bounds.y1-=mid;
1330       bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
1331         image->rows ? (double) image->rows-1 : bounds.y1;
1332       bounds.x2+=mid;
1333       bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
1334         image->columns ? (double) image->columns-1 : bounds.x2;
1335       bounds.y2+=mid;
1336       bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
1337         image->rows ? (double) image->rows-1 : bounds.y2;
1338       for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
1339       {
1340         if (polygon_info->edges[i].direction != 0)
1341           (void) QueryColorCompliance("red",AllCompliance,&clone_info->stroke,
1342             exception);
1343         else
1344           (void) QueryColorCompliance("green",AllCompliance,&clone_info->stroke,
1345             exception);
1346         start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
1347         start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
1348         end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
1349         end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
1350         primitive_info[0].primitive=RectanglePrimitive;
1351         TraceRectangle(primitive_info,start,end);
1352         primitive_info[0].method=ReplaceMethod;
1353         coordinates=(ssize_t) primitive_info[0].coordinates;
1354         primitive_info[coordinates].primitive=UndefinedPrimitive;
1355         (void) DrawPrimitive(image,clone_info,primitive_info,exception);
1356       }
1357     }
1358   (void) QueryColorCompliance("blue",AllCompliance,&clone_info->stroke,
1359     exception);
1360   start.x=(double) (bounds.x1-mid);
1361   start.y=(double) (bounds.y1-mid);
1362   end.x=(double) (bounds.x2+mid);
1363   end.y=(double) (bounds.y2+mid);
1364   primitive_info[0].primitive=RectanglePrimitive;
1365   TraceRectangle(primitive_info,start,end);
1366   primitive_info[0].method=ReplaceMethod;
1367   coordinates=(ssize_t) primitive_info[0].coordinates;
1368   primitive_info[coordinates].primitive=UndefinedPrimitive;
1369   (void) DrawPrimitive(image,clone_info,primitive_info,exception);
1370   clone_info=DestroyDrawInfo(clone_info);
1371 }
1372 \f
1373 /*
1374 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1375 %                                                                             %
1376 %                                                                             %
1377 %                                                                             %
1378 %   D r a w C l i p P a t h                                                   %
1379 %                                                                             %
1380 %                                                                             %
1381 %                                                                             %
1382 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1383 %
1384 %  DrawClipPath() draws the clip path on the image mask.
1385 %
1386 %  The format of the DrawClipPath method is:
1387 %
1388 %      MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
1389 %        const char *name,ExceptionInfo *exception)
1390 %
1391 %  A description of each parameter follows:
1392 %
1393 %    o image: the image.
1394 %
1395 %    o draw_info: the draw info.
1396 %
1397 %    o name: the name of the clip path.
1398 %
1399 %    o exception: return any errors or warnings in this structure.
1400 %
1401 */
1402 MagickExport MagickBooleanType DrawClipPath(Image *image,
1403   const DrawInfo *draw_info,const char *name,ExceptionInfo *exception)
1404 {
1405   char
1406     filename[MaxTextExtent];
1407
1408   Image
1409     *clip_mask;
1410
1411   const char
1412     *value;
1413
1414   DrawInfo
1415     *clone_info;
1416
1417   MagickStatusType
1418     status;
1419
1420   assert(image != (Image *) NULL);
1421   assert(image->signature == MagickSignature);
1422   if (image->debug != MagickFalse)
1423     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1424   assert(draw_info != (const DrawInfo *) NULL);
1425   (void) FormatLocaleString(filename,MaxTextExtent,"%s",name);
1426   value=GetImageArtifact(image,filename);
1427   if (value == (const char *) NULL)
1428     return(MagickFalse);
1429   clip_mask=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
1430   if (clip_mask == (Image *) NULL)
1431     return(MagickFalse);
1432   (void) QueryColorCompliance("#0000",AllCompliance,
1433     &clip_mask->background_color,exception);
1434   clip_mask->background_color.alpha=(Quantum) TransparentAlpha;
1435   (void) SetImageBackgroundColor(clip_mask,exception);
1436   if (image->debug != MagickFalse)
1437     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
1438       draw_info->clip_mask);
1439   clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
1440   (void) CloneString(&clone_info->primitive,value);
1441   (void) QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
1442     exception);
1443   clone_info->clip_mask=(char *) NULL;
1444   status=NegateImage(clip_mask,MagickFalse,exception);
1445   (void) SetImageMask(image,clip_mask,exception);
1446   clip_mask=DestroyImage(clip_mask);
1447   clone_info=DestroyDrawInfo(clone_info);
1448   status=DrawImage(image,clone_info,exception);
1449   if (image->debug != MagickFalse)
1450     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
1451   return(status != 0 ? MagickTrue : MagickFalse);
1452 }
1453 \f
1454 /*
1455 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1456 %                                                                             %
1457 %                                                                             %
1458 %                                                                             %
1459 +   D r a w D a s h P o l y g o n                                             %
1460 %                                                                             %
1461 %                                                                             %
1462 %                                                                             %
1463 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1464 %
1465 %  DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
1466 %  image while respecting the dash offset and dash pattern attributes.
1467 %
1468 %  The format of the DrawDashPolygon method is:
1469 %
1470 %      MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
1471 %        const PrimitiveInfo *primitive_info,Image *image,
1472 %        ExceptionInfo *exception)
1473 %
1474 %  A description of each parameter follows:
1475 %
1476 %    o draw_info: the draw info.
1477 %
1478 %    o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
1479 %
1480 %    o image: the image.
1481 %
1482 %    o exception: return any errors or warnings in this structure.
1483 %
1484 */
1485 static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
1486   const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
1487 {
1488   DrawInfo
1489     *clone_info;
1490
1491   double
1492     length,
1493     maximum_length,
1494     offset,
1495     scale,
1496     total_length;
1497
1498   MagickStatusType
1499     status;
1500
1501   PrimitiveInfo
1502     *dash_polygon;
1503
1504   register ssize_t
1505     i;
1506
1507   register double
1508     dx,
1509     dy;
1510
1511   size_t
1512     number_vertices;
1513
1514   ssize_t
1515     j,
1516     n;
1517
1518   assert(draw_info != (const DrawInfo *) NULL);
1519   if (image->debug != MagickFalse)
1520     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    begin draw-dash");
1521   clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
1522   clone_info->miterlimit=0;
1523   for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
1524   number_vertices=(size_t) i;
1525   dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
1526     (2UL*number_vertices+1UL),sizeof(*dash_polygon));
1527   if (dash_polygon == (PrimitiveInfo *) NULL)
1528     return(MagickFalse);
1529   dash_polygon[0]=primitive_info[0];
1530   scale=ExpandAffine(&draw_info->affine);
1531   length=scale*(draw_info->dash_pattern[0]-0.5);
1532   offset=draw_info->dash_offset != 0.0 ? scale*draw_info->dash_offset : 0.0;
1533   j=1;
1534   for (n=0; offset > 0.0; j=0)
1535   {
1536     if (draw_info->dash_pattern[n] <= 0.0)
1537       break;
1538     length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
1539     if (offset > length)
1540       {
1541         offset-=length;
1542         n++;
1543         length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
1544         continue;
1545       }
1546     if (offset < length)
1547       {
1548         length-=offset;
1549         offset=0.0;
1550         break;
1551       }
1552     offset=0.0;
1553     n++;
1554   }
1555   status=MagickTrue;
1556   maximum_length=0.0;
1557   total_length=0.0;
1558   for (i=1; i < (ssize_t) number_vertices; i++)
1559   {
1560     dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
1561     dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
1562     maximum_length=hypot((double) dx,dy);
1563     if (length == 0.0)
1564       {
1565         n++;
1566         if (draw_info->dash_pattern[n] == 0.0)
1567           n=0;
1568         length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
1569       }
1570     for (total_length=0.0; (total_length+length) <= maximum_length; )
1571     {
1572       total_length+=length;
1573       if ((n & 0x01) != 0)
1574         {
1575           dash_polygon[0]=primitive_info[0];
1576           dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
1577             total_length/maximum_length);
1578           dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
1579             total_length/maximum_length);
1580           j=1;
1581         }
1582       else
1583         {
1584           if ((j+1) > (ssize_t) (2*number_vertices))
1585             break;
1586           dash_polygon[j]=primitive_info[i-1];
1587           dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
1588             total_length/maximum_length);
1589           dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
1590             total_length/maximum_length);
1591           dash_polygon[j].coordinates=1;
1592           j++;
1593           dash_polygon[0].coordinates=(size_t) j;
1594           dash_polygon[j].primitive=UndefinedPrimitive;
1595           status|=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
1596         }
1597       n++;
1598       if (draw_info->dash_pattern[n] == 0.0)
1599         n=0;
1600       length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
1601     }
1602     length-=(maximum_length-total_length);
1603     if ((n & 0x01) != 0)
1604       continue;
1605     dash_polygon[j]=primitive_info[i];
1606     dash_polygon[j].coordinates=1;
1607     j++;
1608   }
1609   if ((total_length <= maximum_length) && ((n & 0x01) == 0) && (j > 1))
1610     {
1611       dash_polygon[j]=primitive_info[i-1];
1612       dash_polygon[j].point.x+=MagickEpsilon;
1613       dash_polygon[j].point.y+=MagickEpsilon;
1614       dash_polygon[j].coordinates=1;
1615       j++;
1616       dash_polygon[0].coordinates=(size_t) j;
1617       dash_polygon[j].primitive=UndefinedPrimitive;
1618       status|=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
1619     }
1620   dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
1621   clone_info=DestroyDrawInfo(clone_info);
1622   if (image->debug != MagickFalse)
1623     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end draw-dash");
1624   return(status != 0 ? MagickTrue : MagickFalse);
1625 }
1626 \f
1627 /*
1628 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1629 %                                                                             %
1630 %                                                                             %
1631 %                                                                             %
1632 %   D r a w I m a g e                                                         %
1633 %                                                                             %
1634 %                                                                             %
1635 %                                                                             %
1636 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1637 %
1638 %  DrawImage() draws a graphic primitive on your image.  The primitive
1639 %  may be represented as a string or filename.  Precede the filename with an
1640 %  "at" sign (@) and the contents of the file are drawn on the image.  You
1641 %  can affect how text is drawn by setting one or more members of the draw
1642 %  info structure.
1643 %
1644 %  The format of the DrawImage method is:
1645 %
1646 %      MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
1647 %        ExceptionInfo *exception)
1648 %
1649 %  A description of each parameter follows:
1650 %
1651 %    o image: the image.
1652 %
1653 %    o draw_info: the draw info.
1654 %
1655 %    o exception: return any errors or warnings in this structure.
1656 %
1657 */
1658
1659 static inline MagickBooleanType IsPoint(const char *point)
1660 {
1661   char
1662     *p;
1663
1664   double
1665     value;
1666
1667   value=StringToDouble(point,&p);
1668   return((value == 0.0) && (p == point) ? MagickFalse : MagickTrue);
1669 }
1670
1671 static inline void TracePoint(PrimitiveInfo *primitive_info,
1672   const PointInfo point)
1673 {
1674   primitive_info->coordinates=1;
1675   primitive_info->point=point;
1676 }
1677
1678 MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
1679   ExceptionInfo *exception)
1680 {
1681 #define RenderImageTag  "Render/Image"
1682
1683   AffineMatrix
1684     affine,
1685     current;
1686
1687   char
1688     key[2*MaxTextExtent],
1689     keyword[MaxTextExtent],
1690     geometry[MaxTextExtent],
1691     name[MaxTextExtent],
1692     pattern[MaxTextExtent],
1693     *primitive,
1694     *token;
1695
1696   const char
1697     *q;
1698
1699   DrawInfo
1700     **graphic_context;
1701
1702   MagickBooleanType
1703     proceed,
1704     status;
1705
1706   double
1707     angle,
1708     factor,
1709     primitive_extent;
1710
1711   PointInfo
1712     point;
1713
1714   PixelInfo
1715     start_color;
1716
1717   PrimitiveInfo
1718     *primitive_info;
1719
1720   PrimitiveType
1721     primitive_type;
1722
1723   register const char
1724     *p;
1725
1726   register ssize_t
1727     i,
1728     x;
1729
1730   SegmentInfo
1731     bounds;
1732
1733   size_t
1734     length,
1735     number_points;
1736
1737   ssize_t
1738     j,
1739     k,
1740     n;
1741
1742   /*
1743     Ensure the annotation info is valid.
1744   */
1745   assert(image != (Image *) NULL);
1746   assert(image->signature == MagickSignature);
1747   if (image->debug != MagickFalse)
1748     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1749   assert(draw_info != (DrawInfo *) NULL);
1750   assert(draw_info->signature == MagickSignature);
1751   if (image->debug != MagickFalse)
1752     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
1753   if ((draw_info->primitive == (char *) NULL) ||
1754       (*draw_info->primitive == '\0'))
1755     return(MagickFalse);
1756   if (image->debug != MagickFalse)
1757     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
1758   if (*draw_info->primitive != '@')
1759     primitive=AcquireString(draw_info->primitive);
1760   else
1761     primitive=FileToString(draw_info->primitive+1,~0,exception);
1762   if (primitive == (char *) NULL)
1763     return(MagickFalse);
1764   primitive_extent=(double) strlen(primitive);
1765   (void) SetImageArtifact(image,"MVG",primitive);
1766   n=0;
1767   /*
1768     Allocate primitive info memory.
1769   */
1770   graphic_context=(DrawInfo **) AcquireMagickMemory(
1771     sizeof(*graphic_context));
1772   if (graphic_context == (DrawInfo **) NULL)
1773     {
1774       primitive=DestroyString(primitive);
1775       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1776         image->filename);
1777     }
1778   number_points=2047;
1779   primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
1780     sizeof(*primitive_info));
1781   if (primitive_info == (PrimitiveInfo *) NULL)
1782     {
1783       primitive=DestroyString(primitive);
1784       for ( ; n >= 0; n--)
1785         graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
1786       graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
1787       ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
1788         image->filename);
1789     }
1790   graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
1791   graphic_context[n]->viewbox=image->page;
1792   if ((image->page.width == 0) || (image->page.height == 0))
1793     {
1794       graphic_context[n]->viewbox.width=image->columns;
1795       graphic_context[n]->viewbox.height=image->rows;
1796     }
1797   token=AcquireString(primitive);
1798   (void) QueryColorCompliance("#000000",AllCompliance,&start_color,
1799     exception);
1800   if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
1801     return(MagickFalse);
1802   status=MagickTrue;
1803   for (q=primitive; *q != '\0'; )
1804   {
1805     /*
1806       Interpret graphic primitive.
1807     */
1808     GetMagickToken(q,&q,keyword);
1809     if (*keyword == '\0')
1810       break;
1811     if (*keyword == '#')
1812       {
1813         /*
1814           Comment.
1815         */
1816         while ((*q != '\n') && (*q != '\0'))
1817           q++;
1818         continue;
1819       }
1820     p=q-strlen(keyword)-1;
1821     primitive_type=UndefinedPrimitive;
1822     current=graphic_context[n]->affine;
1823     GetAffineMatrix(&affine);
1824     switch (*keyword)
1825     {
1826       case ';':
1827         break;
1828       case 'a':
1829       case 'A':
1830       {
1831         if (LocaleCompare("affine",keyword) == 0)
1832           {
1833             GetMagickToken(q,&q,token);
1834             affine.sx=StringToDouble(token,(char **) NULL);
1835             GetMagickToken(q,&q,token);
1836             if (*token == ',')
1837               GetMagickToken(q,&q,token);
1838             affine.rx=StringToDouble(token,(char **) NULL);
1839             GetMagickToken(q,&q,token);
1840             if (*token == ',')
1841               GetMagickToken(q,&q,token);
1842             affine.ry=StringToDouble(token,(char **) NULL);
1843             GetMagickToken(q,&q,token);
1844             if (*token == ',')
1845               GetMagickToken(q,&q,token);
1846             affine.sy=StringToDouble(token,(char **) NULL);
1847             GetMagickToken(q,&q,token);
1848             if (*token == ',')
1849               GetMagickToken(q,&q,token);
1850             affine.tx=StringToDouble(token,(char **) NULL);
1851             GetMagickToken(q,&q,token);
1852             if (*token == ',')
1853               GetMagickToken(q,&q,token);
1854             affine.ty=StringToDouble(token,(char **) NULL);
1855             break;
1856           }
1857         if (LocaleCompare("arc",keyword) == 0)
1858           {
1859             primitive_type=ArcPrimitive;
1860             break;
1861           }
1862         status=MagickFalse;
1863         break;
1864       }
1865       case 'b':
1866       case 'B':
1867       {
1868         if (LocaleCompare("bezier",keyword) == 0)
1869           {
1870             primitive_type=BezierPrimitive;
1871             break;
1872           }
1873         if (LocaleCompare("border-color",keyword) == 0)
1874           {
1875             GetMagickToken(q,&q,token);
1876             (void) QueryColorCompliance(token,AllCompliance,
1877               &graphic_context[n]->border_color,exception);
1878             break;
1879           }
1880         status=MagickFalse;
1881         break;
1882       }
1883       case 'c':
1884       case 'C':
1885       {
1886         if (LocaleCompare("clip-path",keyword) == 0)
1887           {
1888             /*
1889               Create clip mask.
1890             */
1891             GetMagickToken(q,&q,token);
1892             (void) CloneString(&graphic_context[n]->clip_mask,token);
1893             (void) DrawClipPath(image,graphic_context[n],
1894               graphic_context[n]->clip_mask,exception);
1895             break;
1896           }
1897         if (LocaleCompare("clip-rule",keyword) == 0)
1898           {
1899             ssize_t
1900               fill_rule;
1901
1902             GetMagickToken(q,&q,token);
1903             fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
1904               token);
1905             if (fill_rule == -1)
1906               status=MagickFalse;
1907             else
1908               graphic_context[n]->fill_rule=(FillRule) fill_rule;
1909             break;
1910           }
1911         if (LocaleCompare("clip-units",keyword) == 0)
1912           {
1913             ssize_t
1914               clip_units;
1915
1916             GetMagickToken(q,&q,token);
1917             clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
1918               token);
1919             if (clip_units == -1)
1920               {
1921                 status=MagickFalse;
1922                 break;
1923               }
1924             graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
1925             if (clip_units == ObjectBoundingBox)
1926               {
1927                 GetAffineMatrix(&current);
1928                 affine.sx=draw_info->bounds.x2;
1929                 affine.sy=draw_info->bounds.y2;
1930                 affine.tx=draw_info->bounds.x1;
1931                 affine.ty=draw_info->bounds.y1;
1932                 break;
1933               }
1934             break;
1935           }
1936         if (LocaleCompare("circle",keyword) == 0)
1937           {
1938             primitive_type=CirclePrimitive;
1939             break;
1940           }
1941         if (LocaleCompare("color",keyword) == 0)
1942           {
1943             primitive_type=ColorPrimitive;
1944             break;
1945           }
1946         status=MagickFalse;
1947         break;
1948       }
1949       case 'd':
1950       case 'D':
1951       {
1952         if (LocaleCompare("decorate",keyword) == 0)
1953           {
1954             ssize_t
1955               decorate;
1956
1957             GetMagickToken(q,&q,token);
1958             decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
1959               token);
1960             if (decorate == -1)
1961               status=MagickFalse;
1962             else
1963               graphic_context[n]->decorate=(DecorationType) decorate;
1964             break;
1965           }
1966         status=MagickFalse;
1967         break;
1968       }
1969       case 'e':
1970       case 'E':
1971       {
1972         if (LocaleCompare("ellipse",keyword) == 0)
1973           {
1974             primitive_type=EllipsePrimitive;
1975             break;
1976           }
1977         if (LocaleCompare("encoding",keyword) == 0)
1978           {
1979             GetMagickToken(q,&q,token);
1980             (void) CloneString(&graphic_context[n]->encoding,token);
1981             break;
1982           }
1983         status=MagickFalse;
1984         break;
1985       }
1986       case 'f':
1987       case 'F':
1988       {
1989         if (LocaleCompare("fill",keyword) == 0)
1990           {
1991             GetMagickToken(q,&q,token);
1992             (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token);
1993             if (GetImageArtifact(image,pattern) != (const char *) NULL)
1994               (void) DrawPatternPath(image,draw_info,token,
1995                 &graphic_context[n]->fill_pattern,exception);
1996             else
1997               {
1998                 status=QueryColorCompliance(token,AllCompliance,
1999                   &graphic_context[n]->fill,exception);
2000                 if (status == MagickFalse)
2001                   {
2002                     ImageInfo
2003                       *pattern_info;
2004
2005                     pattern_info=AcquireImageInfo();
2006                     (void) CopyMagickString(pattern_info->filename,token,
2007                       MaxTextExtent);
2008                     graphic_context[n]->fill_pattern=ReadImage(pattern_info,
2009                       exception);
2010                     CatchException(exception);
2011                     pattern_info=DestroyImageInfo(pattern_info);
2012                   }
2013               }
2014             break;
2015           }
2016         if (LocaleCompare("fill-alpha",keyword) == 0)
2017           {
2018             GetMagickToken(q,&q,token);
2019             factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
2020             graphic_context[n]->fill.alpha=(double) QuantumRange*
2021               factor*StringToDouble(token,(char **) NULL);
2022             break;
2023           }
2024         if (LocaleCompare("fill-rule",keyword) == 0)
2025           {
2026             ssize_t
2027               fill_rule;
2028
2029             GetMagickToken(q,&q,token);
2030             fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
2031               token);
2032             if (fill_rule == -1)
2033               status=MagickFalse;
2034             else
2035               graphic_context[n]->fill_rule=(FillRule) fill_rule;
2036             break;
2037           }
2038         if (LocaleCompare("font",keyword) == 0)
2039           {
2040             GetMagickToken(q,&q,token);
2041             (void) CloneString(&graphic_context[n]->font,token);
2042             if (LocaleCompare("none",token) == 0)
2043               graphic_context[n]->font=(char *)
2044                 RelinquishMagickMemory(graphic_context[n]->font);
2045             break;
2046           }
2047         if (LocaleCompare("font-family",keyword) == 0)
2048           {
2049             GetMagickToken(q,&q,token);
2050             (void) CloneString(&graphic_context[n]->family,token);
2051             break;
2052           }
2053         if (LocaleCompare("font-size",keyword) == 0)
2054           {
2055             GetMagickToken(q,&q,token);
2056             graphic_context[n]->pointsize=StringToDouble(token,(char **) NULL);
2057             break;
2058           }
2059         if (LocaleCompare("font-stretch",keyword) == 0)
2060           {
2061             ssize_t
2062               stretch;
2063
2064             GetMagickToken(q,&q,token);
2065             stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
2066             if (stretch == -1)
2067               status=MagickFalse;
2068             else
2069               graphic_context[n]->stretch=(StretchType) stretch;
2070             break;
2071           }
2072         if (LocaleCompare("font-style",keyword) == 0)
2073           {
2074             ssize_t
2075               style;
2076
2077             GetMagickToken(q,&q,token);
2078             style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
2079             if (style == -1)
2080               status=MagickFalse;
2081             else
2082               graphic_context[n]->style=(StyleType) style;
2083             break;
2084           }
2085         if (LocaleCompare("font-weight",keyword) == 0)
2086           {
2087             GetMagickToken(q,&q,token);
2088             graphic_context[n]->weight=StringToUnsignedLong(token);
2089             if (LocaleCompare(token,"all") == 0)
2090               graphic_context[n]->weight=0;
2091             if (LocaleCompare(token,"bold") == 0)
2092               graphic_context[n]->weight=700;
2093             if (LocaleCompare(token,"bolder") == 0)
2094               if (graphic_context[n]->weight <= 800)
2095                 graphic_context[n]->weight+=100;
2096             if (LocaleCompare(token,"lighter") == 0)
2097               if (graphic_context[n]->weight >= 100)
2098                 graphic_context[n]->weight-=100;
2099             if (LocaleCompare(token,"normal") == 0)
2100               graphic_context[n]->weight=400;
2101             break;
2102           }
2103         status=MagickFalse;
2104         break;
2105       }
2106       case 'g':
2107       case 'G':
2108       {
2109         if (LocaleCompare("gradient-units",keyword) == 0)
2110           {
2111             GetMagickToken(q,&q,token);
2112             break;
2113           }
2114         if (LocaleCompare("gravity",keyword) == 0)
2115           {
2116             ssize_t
2117               gravity;
2118
2119             GetMagickToken(q,&q,token);
2120             gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
2121             if (gravity == -1)
2122               status=MagickFalse;
2123             else
2124               graphic_context[n]->gravity=(GravityType) gravity;
2125             break;
2126           }
2127         status=MagickFalse;
2128         break;
2129       }
2130       case 'i':
2131       case 'I':
2132       {
2133         if (LocaleCompare("image",keyword) == 0)
2134           {
2135             ssize_t
2136               compose;
2137
2138             primitive_type=ImagePrimitive;
2139             GetMagickToken(q,&q,token);
2140             compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
2141             if (compose == -1)
2142               status=MagickFalse;
2143             else
2144               graphic_context[n]->compose=(CompositeOperator) compose;
2145             break;
2146           }
2147         if (LocaleCompare("interline-spacing",keyword) == 0)
2148           {
2149             GetMagickToken(q,&q,token);
2150             graphic_context[n]->interline_spacing=StringToDouble(token,
2151               (char **) NULL);
2152             break;
2153           }
2154         if (LocaleCompare("interword-spacing",keyword) == 0)
2155           {
2156             GetMagickToken(q,&q,token);
2157             graphic_context[n]->interword_spacing=StringToDouble(token,
2158               (char **) NULL);
2159             break;
2160           }
2161         status=MagickFalse;
2162         break;
2163       }
2164       case 'k':
2165       case 'K':
2166       {
2167         if (LocaleCompare("kerning",keyword) == 0)
2168           {
2169             GetMagickToken(q,&q,token);
2170             graphic_context[n]->kerning=StringToDouble(token,(char **) NULL);
2171             break;
2172           }
2173         status=MagickFalse;
2174         break;
2175       }
2176       case 'l':
2177       case 'L':
2178       {
2179         if (LocaleCompare("line",keyword) == 0)
2180           primitive_type=LinePrimitive;
2181         else
2182           status=MagickFalse;
2183         break;
2184       }
2185       case 'm':
2186       case 'M':
2187       {
2188         if (LocaleCompare("matte",keyword) == 0)
2189           primitive_type=MattePrimitive;
2190         else
2191           status=MagickFalse;
2192         break;
2193       }
2194       case 'o':
2195       case 'O':
2196       {
2197         if (LocaleCompare("offset",keyword) == 0)
2198           {
2199             GetMagickToken(q,&q,token);
2200             break;
2201           }
2202         if (LocaleCompare("opacity",keyword) == 0)
2203           {
2204             GetMagickToken(q,&q,token);
2205             factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
2206             graphic_context[n]->alpha=ClampToQuantum(QuantumRange*(1.0-((1.0-
2207               QuantumScale*graphic_context[n]->alpha)*factor*
2208               StringToDouble(token,(char **) NULL))));
2209             graphic_context[n]->fill.alpha=(double) graphic_context[n]->alpha;
2210             graphic_context[n]->stroke.alpha=(double) graphic_context[n]->alpha;
2211             break;
2212           }
2213         status=MagickFalse;
2214         break;
2215       }
2216       case 'p':
2217       case 'P':
2218       {
2219         if (LocaleCompare("path",keyword) == 0)
2220           {
2221             primitive_type=PathPrimitive;
2222             break;
2223           }
2224         if (LocaleCompare("point",keyword) == 0)
2225           {
2226             primitive_type=PointPrimitive;
2227             break;
2228           }
2229         if (LocaleCompare("polyline",keyword) == 0)
2230           {
2231             primitive_type=PolylinePrimitive;
2232             break;
2233           }
2234         if (LocaleCompare("polygon",keyword) == 0)
2235           {
2236             primitive_type=PolygonPrimitive;
2237             break;
2238           }
2239         if (LocaleCompare("pop",keyword) == 0)
2240           {
2241             GetMagickToken(q,&q,token);
2242             if (LocaleCompare("clip-path",token) == 0)
2243               break;
2244             if (LocaleCompare("defs",token) == 0)
2245               break;
2246             if (LocaleCompare("gradient",token) == 0)
2247               break;
2248             if (LocaleCompare("graphic-context",token) == 0)
2249               {
2250                 if (n <= 0)
2251                   {
2252                     (void) ThrowMagickException(exception,GetMagickModule(),
2253                       DrawError,"UnbalancedGraphicContextPushPop","'%s'",token);
2254                     n=0;
2255                     break;
2256                   }
2257                 if (graphic_context[n]->clip_mask != (char *) NULL)
2258                   if (LocaleCompare(graphic_context[n]->clip_mask,
2259                       graphic_context[n-1]->clip_mask) != 0)
2260                     (void) SetImageMask(image,(Image *) NULL,exception);
2261                 graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
2262                 n--;
2263                 break;
2264               }
2265             if (LocaleCompare("pattern",token) == 0)
2266               break;
2267             status=MagickFalse;
2268             break;
2269           }
2270         if (LocaleCompare("push",keyword) == 0)
2271           {
2272             GetMagickToken(q,&q,token);
2273             if (LocaleCompare("clip-path",token) == 0)
2274               {
2275                 char
2276                   name[MaxTextExtent];
2277
2278                 GetMagickToken(q,&q,token);
2279                 (void) FormatLocaleString(name,MaxTextExtent,"%s",token);
2280                 for (p=q; *q != '\0'; )
2281                 {
2282                   GetMagickToken(q,&q,token);
2283                   if (LocaleCompare(token,"pop") != 0)
2284                     continue;
2285                   GetMagickToken(q,(const char **) NULL,token);
2286                   if (LocaleCompare(token,"clip-path") != 0)
2287                     continue;
2288                   break;
2289                 }
2290                 (void) CopyMagickString(token,p,(size_t) (q-p-4+1));
2291                 (void) SetImageArtifact(image,name,token);
2292                 GetMagickToken(q,&q,token);
2293                 break;
2294               }
2295             if (LocaleCompare("gradient",token) == 0)
2296               {
2297                 char
2298                   key[2*MaxTextExtent],
2299                   name[MaxTextExtent],
2300                   type[MaxTextExtent];
2301
2302                 SegmentInfo
2303                   segment;
2304
2305                 GetMagickToken(q,&q,token);
2306                 (void) CopyMagickString(name,token,MaxTextExtent);
2307                 GetMagickToken(q,&q,token);
2308                 (void) CopyMagickString(type,token,MaxTextExtent);
2309                 GetMagickToken(q,&q,token);
2310                 segment.x1=StringToDouble(token,(char **) NULL);
2311                 GetMagickToken(q,&q,token);
2312                 if (*token == ',')
2313                   GetMagickToken(q,&q,token);
2314                 segment.y1=StringToDouble(token,(char **) NULL);
2315                 GetMagickToken(q,&q,token);
2316                 if (*token == ',')
2317                   GetMagickToken(q,&q,token);
2318                 segment.x2=StringToDouble(token,(char **) NULL);
2319                 GetMagickToken(q,&q,token);
2320                 if (*token == ',')
2321                   GetMagickToken(q,&q,token);
2322                 segment.y2=StringToDouble(token,(char **) NULL);
2323                 if (LocaleCompare(type,"radial") == 0)
2324                   {
2325                     GetMagickToken(q,&q,token);
2326                     if (*token == ',')
2327                       GetMagickToken(q,&q,token);
2328                   }
2329                 for (p=q; *q != '\0'; )
2330                 {
2331                   GetMagickToken(q,&q,token);
2332                   if (LocaleCompare(token,"pop") != 0)
2333                     continue;
2334                   GetMagickToken(q,(const char **) NULL,token);
2335                   if (LocaleCompare(token,"gradient") != 0)
2336                     continue;
2337                   break;
2338                 }
2339                 (void) CopyMagickString(token,p,(size_t) (q-p-4+1));
2340                 bounds.x1=graphic_context[n]->affine.sx*segment.x1+
2341                   graphic_context[n]->affine.ry*segment.y1+
2342                   graphic_context[n]->affine.tx;
2343                 bounds.y1=graphic_context[n]->affine.rx*segment.x1+
2344                   graphic_context[n]->affine.sy*segment.y1+
2345                   graphic_context[n]->affine.ty;
2346                 bounds.x2=graphic_context[n]->affine.sx*segment.x2+
2347                   graphic_context[n]->affine.ry*segment.y2+
2348                   graphic_context[n]->affine.tx;
2349                 bounds.y2=graphic_context[n]->affine.rx*segment.x2+
2350                   graphic_context[n]->affine.sy*segment.y2+
2351                   graphic_context[n]->affine.ty;
2352                 (void) FormatLocaleString(key,MaxTextExtent,"%s",name);
2353                 (void) SetImageArtifact(image,key,token);
2354                 (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name);
2355                 (void) FormatLocaleString(geometry,MaxTextExtent,
2356                   "%gx%g%+.15g%+.15g",
2357                   MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
2358                   MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
2359                   bounds.x1,bounds.y1);
2360                 (void) SetImageArtifact(image,key,geometry);
2361                 GetMagickToken(q,&q,token);
2362                 break;
2363               }
2364             if (LocaleCompare("pattern",token) == 0)
2365               {
2366                 RectangleInfo
2367                   bounds;
2368
2369                 GetMagickToken(q,&q,token);
2370                 (void) CopyMagickString(name,token,MaxTextExtent);
2371                 GetMagickToken(q,&q,token);
2372                 bounds.x=(ssize_t) ceil(StringToDouble(token,(char **) NULL)-
2373                   0.5);
2374                 GetMagickToken(q,&q,token);
2375                 if (*token == ',')
2376                   GetMagickToken(q,&q,token);
2377                 bounds.y=(ssize_t) ceil(StringToDouble(token,(char **) NULL)-
2378                   0.5);
2379                 GetMagickToken(q,&q,token);
2380                 if (*token == ',')
2381                   GetMagickToken(q,&q,token);
2382                 bounds.width=(size_t) floor(StringToDouble(token,
2383                   (char **) NULL)+0.5);
2384                 GetMagickToken(q,&q,token);
2385                 if (*token == ',')
2386                   GetMagickToken(q,&q,token);
2387                 bounds.height=(size_t) floor(StringToDouble(token,
2388                   (char **) NULL)+0.5);
2389                 for (p=q; *q != '\0'; )
2390                 {
2391                   GetMagickToken(q,&q,token);
2392                   if (LocaleCompare(token,"pop") != 0)
2393                     continue;
2394                   GetMagickToken(q,(const char **) NULL,token);
2395                   if (LocaleCompare(token,"pattern") != 0)
2396                     continue;
2397                   break;
2398                 }
2399                 (void) CopyMagickString(token,p,(size_t) (q-p-4+1));
2400                 (void) FormatLocaleString(key,MaxTextExtent,"%s",name);
2401                 (void) SetImageArtifact(image,key,token);
2402                 (void) FormatLocaleString(key,MaxTextExtent,"%s-geometry",name);
2403                 (void) FormatLocaleString(geometry,MaxTextExtent,
2404                   "%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double)
2405                   bounds.height,(double) bounds.x,(double) bounds.y);
2406                 (void) SetImageArtifact(image,key,geometry);
2407                 GetMagickToken(q,&q,token);
2408                 break;
2409               }
2410             if (LocaleCompare("graphic-context",token) == 0)
2411               {
2412                 n++;
2413                 graphic_context=(DrawInfo **) ResizeQuantumMemory(
2414                   graphic_context,(size_t) (n+1),sizeof(*graphic_context));
2415                 if (graphic_context == (DrawInfo **) NULL)
2416                   {
2417                     (void) ThrowMagickException(exception,GetMagickModule(),
2418                       ResourceLimitError,"MemoryAllocationFailed","'%s'",
2419                       image->filename);
2420                     break;
2421                   }
2422                 graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
2423                   graphic_context[n-1]);
2424                 break;
2425               }
2426             if (LocaleCompare("defs",token) == 0)
2427               break;
2428             status=MagickFalse;
2429             break;
2430           }
2431         status=MagickFalse;
2432         break;
2433       }
2434       case 'r':
2435       case 'R':
2436       {
2437         if (LocaleCompare("rectangle",keyword) == 0)
2438           {
2439             primitive_type=RectanglePrimitive;
2440             break;
2441           }
2442         if (LocaleCompare("rotate",keyword) == 0)
2443           {
2444             GetMagickToken(q,&q,token);
2445             angle=StringToDouble(token,(char **) NULL);
2446             affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
2447             affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
2448             affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
2449             affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
2450             break;
2451           }
2452         if (LocaleCompare("roundRectangle",keyword) == 0)
2453           {
2454             primitive_type=RoundRectanglePrimitive;
2455             break;
2456           }
2457         status=MagickFalse;
2458         break;
2459       }
2460       case 's':
2461       case 'S':
2462       {
2463         if (LocaleCompare("scale",keyword) == 0)
2464           {
2465             GetMagickToken(q,&q,token);
2466             affine.sx=StringToDouble(token,(char **) NULL);
2467             GetMagickToken(q,&q,token);
2468             if (*token == ',')
2469               GetMagickToken(q,&q,token);
2470             affine.sy=StringToDouble(token,(char **) NULL);
2471             break;
2472           }
2473         if (LocaleCompare("skewX",keyword) == 0)
2474           {
2475             GetMagickToken(q,&q,token);
2476             angle=StringToDouble(token,(char **) NULL);
2477             affine.ry=sin(DegreesToRadians(angle));
2478             break;
2479           }
2480         if (LocaleCompare("skewY",keyword) == 0)
2481           {
2482             GetMagickToken(q,&q,token);
2483             angle=StringToDouble(token,(char **) NULL);
2484             affine.rx=(-tan(DegreesToRadians(angle)/2.0));
2485             break;
2486           }
2487         if (LocaleCompare("stop-color",keyword) == 0)
2488           {
2489             PixelInfo
2490               stop_color;
2491
2492             GetMagickToken(q,&q,token);
2493             (void) QueryColorCompliance(token,AllCompliance,&stop_color,
2494               exception);
2495             (void) GradientImage(image,LinearGradient,ReflectSpread,
2496               &start_color,&stop_color,exception);
2497             start_color=stop_color;
2498             GetMagickToken(q,&q,token);
2499             break;
2500           }
2501         if (LocaleCompare("stroke",keyword) == 0)
2502           {
2503             GetMagickToken(q,&q,token);
2504             (void) FormatLocaleString(pattern,MaxTextExtent,"%s",token);
2505             if (GetImageArtifact(image,pattern) != (const char *) NULL)
2506               (void) DrawPatternPath(image,draw_info,token,
2507                 &graphic_context[n]->stroke_pattern,exception);
2508             else
2509               {
2510                 status=QueryColorCompliance(token,AllCompliance,
2511                   &graphic_context[n]->stroke,exception);
2512                 if (status == MagickFalse)
2513                   {
2514                     ImageInfo
2515                       *pattern_info;
2516
2517                     pattern_info=AcquireImageInfo();
2518                     (void) CopyMagickString(pattern_info->filename,token,
2519                       MaxTextExtent);
2520                     graphic_context[n]->stroke_pattern=ReadImage(pattern_info,
2521                       exception);
2522                     CatchException(exception);
2523                     pattern_info=DestroyImageInfo(pattern_info);
2524                   }
2525               }
2526             break;
2527           }
2528         if (LocaleCompare("stroke-antialias",keyword) == 0)
2529           {
2530             GetMagickToken(q,&q,token);
2531             graphic_context[n]->stroke_antialias=
2532               StringToLong(token) != 0 ? MagickTrue : MagickFalse;
2533             break;
2534           }
2535         if (LocaleCompare("stroke-dasharray",keyword) == 0)
2536           {
2537             if (graphic_context[n]->dash_pattern != (double *) NULL)
2538               graphic_context[n]->dash_pattern=(double *)
2539                 RelinquishMagickMemory(graphic_context[n]->dash_pattern);
2540             if (IsPoint(q) != MagickFalse)
2541               {
2542                 const char
2543                   *p;
2544
2545                 p=q;
2546                 GetMagickToken(p,&p,token);
2547                 if (*token == ',')
2548                   GetMagickToken(p,&p,token);
2549                 for (x=0; IsPoint(token) != MagickFalse; x++)
2550                 {
2551                   GetMagickToken(p,&p,token);
2552                   if (*token == ',')
2553                     GetMagickToken(p,&p,token);
2554                 }
2555                 graphic_context[n]->dash_pattern=(double *)
2556                   AcquireQuantumMemory((size_t) (2UL*x+1UL),
2557                   sizeof(*graphic_context[n]->dash_pattern));
2558                 if (graphic_context[n]->dash_pattern == (double *) NULL)
2559                   {
2560                     (void) ThrowMagickException(exception,GetMagickModule(),
2561                       ResourceLimitError,"MemoryAllocationFailed","'%s'",
2562                       image->filename);
2563                     break;
2564                   }
2565                 for (j=0; j < x; j++)
2566                 {
2567                   GetMagickToken(q,&q,token);
2568                   if (*token == ',')
2569                     GetMagickToken(q,&q,token);
2570                   graphic_context[n]->dash_pattern[j]=StringToDouble(token,
2571                     (char **) NULL);
2572                 }
2573                 if ((x & 0x01) != 0)
2574                   for ( ; j < (2*x); j++)
2575                     graphic_context[n]->dash_pattern[j]=
2576                       graphic_context[n]->dash_pattern[j-x];
2577                 graphic_context[n]->dash_pattern[j]=0.0;
2578                 break;
2579               }
2580             GetMagickToken(q,&q,token);
2581             break;
2582           }
2583         if (LocaleCompare("stroke-dashoffset",keyword) == 0)
2584           {
2585             GetMagickToken(q,&q,token);
2586             graphic_context[n]->dash_offset=StringToDouble(token,
2587               (char **) NULL);
2588             break;
2589           }
2590         if (LocaleCompare("stroke-linecap",keyword) == 0)
2591           {
2592             ssize_t
2593               linecap;
2594
2595             GetMagickToken(q,&q,token);
2596             linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
2597             if (linecap == -1)
2598               status=MagickFalse;
2599             else
2600               graphic_context[n]->linecap=(LineCap) linecap;
2601             break;
2602           }
2603         if (LocaleCompare("stroke-linejoin",keyword) == 0)
2604           {
2605             ssize_t
2606               linejoin;
2607
2608             GetMagickToken(q,&q,token);
2609             linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
2610               token);
2611             if (linejoin == -1)
2612               status=MagickFalse;
2613             else
2614               graphic_context[n]->linejoin=(LineJoin) linejoin;
2615             break;
2616           }
2617         if (LocaleCompare("stroke-miterlimit",keyword) == 0)
2618           {
2619             GetMagickToken(q,&q,token);
2620             graphic_context[n]->miterlimit=StringToUnsignedLong(token);
2621             break;
2622           }
2623         if (LocaleCompare("stroke-opacity",keyword) == 0)
2624           {
2625             GetMagickToken(q,&q,token);
2626             factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
2627             graphic_context[n]->stroke.alpha=(double) QuantumRange*
2628               factor*StringToDouble(token,(char **) NULL);
2629             break;
2630           }
2631         if (LocaleCompare("stroke-width",keyword) == 0)
2632           {
2633             GetMagickToken(q,&q,token);
2634             graphic_context[n]->stroke_width=StringToDouble(token,
2635               (char **) NULL);
2636             break;
2637           }
2638         status=MagickFalse;
2639         break;
2640       }
2641       case 't':
2642       case 'T':
2643       {
2644         if (LocaleCompare("text",keyword) == 0)
2645           {
2646             primitive_type=TextPrimitive;
2647             break;
2648           }
2649         if (LocaleCompare("text-align",keyword) == 0)
2650           {
2651             ssize_t
2652               align;
2653
2654             GetMagickToken(q,&q,token);
2655             align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
2656             if (align == -1)
2657               status=MagickFalse;
2658             else
2659               graphic_context[n]->align=(AlignType) align;
2660             break;
2661           }
2662         if (LocaleCompare("text-anchor",keyword) == 0)
2663           {
2664             ssize_t
2665               align;
2666
2667             GetMagickToken(q,&q,token);
2668             align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
2669             if (align == -1)
2670               status=MagickFalse;
2671             else
2672               graphic_context[n]->align=(AlignType) align;
2673             break;
2674           }
2675         if (LocaleCompare("text-antialias",keyword) == 0)
2676           {
2677             GetMagickToken(q,&q,token);
2678             graphic_context[n]->text_antialias=
2679               StringToLong(token) != 0 ? MagickTrue : MagickFalse;
2680             break;
2681           }
2682         if (LocaleCompare("text-undercolor",keyword) == 0)
2683           {
2684             GetMagickToken(q,&q,token);
2685             (void) QueryColorCompliance(token,AllCompliance,
2686               &graphic_context[n]->undercolor,exception);
2687             break;
2688           }
2689         if (LocaleCompare("translate",keyword) == 0)
2690           {
2691             GetMagickToken(q,&q,token);
2692             affine.tx=StringToDouble(token,(char **) NULL);
2693             GetMagickToken(q,&q,token);
2694             if (*token == ',')
2695               GetMagickToken(q,&q,token);
2696             affine.ty=StringToDouble(token,(char **) NULL);
2697             break;
2698           }
2699         status=MagickFalse;
2700         break;
2701       }
2702       case 'v':
2703       case 'V':
2704       {
2705         if (LocaleCompare("viewbox",keyword) == 0)
2706           {
2707             GetMagickToken(q,&q,token);
2708             graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
2709               (char **) NULL)-0.5);
2710             GetMagickToken(q,&q,token);
2711             if (*token == ',')
2712               GetMagickToken(q,&q,token);
2713             graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
2714               (char **) NULL)-0.5);
2715             GetMagickToken(q,&q,token);
2716             if (*token == ',')
2717               GetMagickToken(q,&q,token);
2718             graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
2719               token,(char **) NULL)+0.5);
2720             GetMagickToken(q,&q,token);
2721             if (*token == ',')
2722               GetMagickToken(q,&q,token);
2723             graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
2724               token,(char **) NULL)+0.5);
2725             break;
2726           }
2727         status=MagickFalse;
2728         break;
2729       }
2730       default:
2731       {
2732         status=MagickFalse;
2733         break;
2734       }
2735     }
2736     if (status == MagickFalse)
2737       break;
2738     if ((affine.sx != 1.0) || (affine.rx != 0.0) || (affine.ry != 0.0) ||
2739         (affine.sy != 1.0) || (affine.tx != 0.0) || (affine.ty != 0.0))
2740       {
2741         graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
2742         graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
2743         graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
2744         graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
2745         graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
2746           current.tx;
2747         graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
2748           current.ty;
2749       }
2750     if (primitive_type == UndefinedPrimitive)
2751       {
2752         if (image->debug != MagickFalse)
2753           (void) LogMagickEvent(DrawEvent,GetMagickModule(),"  %.*s",
2754             (int) (q-p),p);
2755         continue;
2756       }
2757     /*
2758       Parse the primitive attributes.
2759     */
2760     i=0;
2761     j=0;
2762     primitive_info[0].point.x=0.0;
2763     primitive_info[0].point.y=0.0;
2764     for (x=0; *q != '\0'; x++)
2765     {
2766       /*
2767         Define points.
2768       */
2769       if (IsPoint(q) == MagickFalse)
2770         break;
2771       GetMagickToken(q,&q,token);
2772       point.x=StringToDouble(token,(char **) NULL);
2773       GetMagickToken(q,&q,token);
2774       if (*token == ',')
2775         GetMagickToken(q,&q,token);
2776       point.y=StringToDouble(token,(char **) NULL);
2777       GetMagickToken(q,(const char **) NULL,token);
2778       if (*token == ',')
2779         GetMagickToken(q,&q,token);
2780       primitive_info[i].primitive=primitive_type;
2781       primitive_info[i].point=point;
2782       primitive_info[i].coordinates=0;
2783       primitive_info[i].method=FloodfillMethod;
2784       i++;
2785       if (i < (ssize_t) number_points)
2786         continue;
2787       number_points<<=1;
2788       primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
2789         (size_t) number_points,sizeof(*primitive_info));
2790       if (primitive_info == (PrimitiveInfo *) NULL)
2791         {
2792           (void) ThrowMagickException(exception,GetMagickModule(),
2793             ResourceLimitError,"MemoryAllocationFailed","'%s'",image->filename);
2794           break;
2795         }
2796     }
2797     primitive_info[j].primitive=primitive_type;
2798     primitive_info[j].coordinates=(size_t) x;
2799     primitive_info[j].method=FloodfillMethod;
2800     primitive_info[j].text=(char *) NULL;
2801     /*
2802       Circumscribe primitive within a circle.
2803     */
2804     bounds.x1=primitive_info[j].point.x;
2805     bounds.y1=primitive_info[j].point.y;
2806     bounds.x2=primitive_info[j].point.x;
2807     bounds.y2=primitive_info[j].point.y;
2808     for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
2809     {
2810       point=primitive_info[j+k].point;
2811       if (point.x < bounds.x1)
2812         bounds.x1=point.x;
2813       if (point.y < bounds.y1)
2814         bounds.y1=point.y;
2815       if (point.x > bounds.x2)
2816         bounds.x2=point.x;
2817       if (point.y > bounds.y2)
2818         bounds.y2=point.y;
2819     }
2820     /*
2821       Speculate how many points our primitive might consume.
2822     */
2823     length=primitive_info[j].coordinates;
2824     switch (primitive_type)
2825     {
2826       case RectanglePrimitive:
2827       {
2828         length*=5;
2829         break;
2830       }
2831       case RoundRectanglePrimitive:
2832       {
2833         length*=5+8*BezierQuantum;
2834         break;
2835       }
2836       case BezierPrimitive:
2837       {
2838         if (primitive_info[j].coordinates > 107)
2839           (void) ThrowMagickException(exception,GetMagickModule(),DrawError,
2840             "TooManyBezierCoordinates","'%s'",token);
2841         length=BezierQuantum*primitive_info[j].coordinates;
2842         break;
2843       }
2844       case PathPrimitive:
2845       {
2846         char
2847           *s,
2848           *t;
2849
2850         GetMagickToken(q,&q,token);
2851         length=1;
2852         t=token;
2853         for (s=token; *s != '\0'; s=t)
2854         {
2855           double
2856             value;
2857
2858           value=StringToDouble(s,&t);
2859           (void) value;
2860           if (s == t)
2861             {
2862               t++;
2863               continue;
2864             }
2865           length++;
2866         }
2867         length=length*BezierQuantum/2;
2868         break;
2869       }
2870       case CirclePrimitive:
2871       case ArcPrimitive:
2872       case EllipsePrimitive:
2873       {
2874         double
2875           alpha,
2876           beta,
2877           radius;
2878
2879         alpha=bounds.x2-bounds.x1;
2880         beta=bounds.y2-bounds.y1;
2881         radius=hypot((double) alpha,(double) beta);
2882         length=2*((size_t) ceil((double) MagickPI*radius))+6*BezierQuantum+360;
2883         break;
2884       }
2885       default:
2886         break;
2887     }
2888     if ((size_t) (i+length) >= number_points)
2889       {
2890         /*
2891           Resize based on speculative points required by primitive.
2892         */
2893         number_points+=length+1;
2894         primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(primitive_info,
2895           (size_t) number_points,sizeof(*primitive_info));
2896         if (primitive_info == (PrimitiveInfo *) NULL)
2897           {
2898             (void) ThrowMagickException(exception,GetMagickModule(),
2899               ResourceLimitError,"MemoryAllocationFailed","'%s'",
2900               image->filename);
2901             break;
2902           }
2903       }
2904     switch (primitive_type)
2905     {
2906       case PointPrimitive:
2907       default:
2908       {
2909         if (primitive_info[j].coordinates != 1)
2910           {
2911             status=MagickFalse;
2912             break;
2913           }
2914         TracePoint(primitive_info+j,primitive_info[j].point);
2915         i=(ssize_t) (j+primitive_info[j].coordinates);
2916         break;
2917       }
2918       case LinePrimitive:
2919       {
2920         if (primitive_info[j].coordinates != 2)
2921           {
2922             status=MagickFalse;
2923             break;
2924           }
2925         TraceLine(primitive_info+j,primitive_info[j].point,
2926           primitive_info[j+1].point);
2927         i=(ssize_t) (j+primitive_info[j].coordinates);
2928         break;
2929       }
2930       case RectanglePrimitive:
2931       {
2932         if (primitive_info[j].coordinates != 2)
2933           {
2934             status=MagickFalse;
2935             break;
2936           }
2937         TraceRectangle(primitive_info+j,primitive_info[j].point,
2938           primitive_info[j+1].point);
2939         i=(ssize_t) (j+primitive_info[j].coordinates);
2940         break;
2941       }
2942       case RoundRectanglePrimitive:
2943       {
2944         if (primitive_info[j].coordinates != 3)
2945           {
2946             status=MagickFalse;
2947             break;
2948           }
2949         TraceRoundRectangle(primitive_info+j,primitive_info[j].point,
2950           primitive_info[j+1].point,primitive_info[j+2].point);
2951         i=(ssize_t) (j+primitive_info[j].coordinates);
2952         break;
2953       }
2954       case ArcPrimitive:
2955       {
2956         if (primitive_info[j].coordinates != 3)
2957           {
2958             primitive_type=UndefinedPrimitive;
2959             break;
2960           }
2961         TraceArc(primitive_info+j,primitive_info[j].point,
2962           primitive_info[j+1].point,primitive_info[j+2].point);
2963         i=(ssize_t) (j+primitive_info[j].coordinates);
2964         break;
2965       }
2966       case EllipsePrimitive:
2967       {
2968         if (primitive_info[j].coordinates != 3)
2969           {
2970             status=MagickFalse;
2971             break;
2972           }
2973         TraceEllipse(primitive_info+j,primitive_info[j].point,
2974           primitive_info[j+1].point,primitive_info[j+2].point);
2975         i=(ssize_t) (j+primitive_info[j].coordinates);
2976         break;
2977       }
2978       case CirclePrimitive:
2979       {
2980         if (primitive_info[j].coordinates != 2)
2981           {
2982             status=MagickFalse;
2983             break;
2984           }
2985         TraceCircle(primitive_info+j,primitive_info[j].point,
2986           primitive_info[j+1].point);
2987         i=(ssize_t) (j+primitive_info[j].coordinates);
2988         break;
2989       }
2990       case PolylinePrimitive:
2991         break;
2992       case PolygonPrimitive:
2993       {
2994         primitive_info[i]=primitive_info[j];
2995         primitive_info[i].coordinates=0;
2996         primitive_info[j].coordinates++;
2997         i++;
2998         break;
2999       }
3000       case BezierPrimitive:
3001       {
3002         if (primitive_info[j].coordinates < 3)
3003           {
3004             status=MagickFalse;
3005             break;
3006           }
3007         TraceBezier(primitive_info+j,primitive_info[j].coordinates);
3008         i=(ssize_t) (j+primitive_info[j].coordinates);
3009         break;
3010       }
3011       case PathPrimitive:
3012       {
3013         i=(ssize_t) (j+TracePath(primitive_info+j,token));
3014         break;
3015       }
3016       case ColorPrimitive:
3017       case MattePrimitive:
3018       {
3019         ssize_t
3020           method;
3021
3022         if (primitive_info[j].coordinates != 1)
3023           {
3024             status=MagickFalse;
3025             break;
3026           }
3027         GetMagickToken(q,&q,token);
3028         method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
3029         if (method == -1)
3030           status=MagickFalse;
3031         else
3032           primitive_info[j].method=(PaintMethod) method;
3033         break;
3034       }
3035       case TextPrimitive:
3036       {
3037         if (primitive_info[j].coordinates != 1)
3038           {
3039             status=MagickFalse;
3040             break;
3041           }
3042         if (*token != ',')
3043           GetMagickToken(q,&q,token);
3044         primitive_info[j].text=AcquireString(token);
3045         break;
3046       }
3047       case ImagePrimitive:
3048       {
3049         if (primitive_info[j].coordinates != 2)
3050           {
3051             status=MagickFalse;
3052             break;
3053           }
3054         GetMagickToken(q,&q,token);
3055         primitive_info[j].text=AcquireString(token);
3056         break;
3057       }
3058     }
3059     if (primitive_info == (PrimitiveInfo *) NULL)
3060       break;
3061     if (image->debug != MagickFalse)
3062       (void) LogMagickEvent(DrawEvent,GetMagickModule(),"  %.*s",(int) (q-p),p);
3063     if (status == MagickFalse)
3064       break;
3065     primitive_info[i].primitive=UndefinedPrimitive;
3066     if (i == 0)
3067       continue;
3068     /*
3069       Transform points.
3070     */
3071     for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
3072     {
3073       point=primitive_info[i].point;
3074       primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
3075         graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
3076       primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
3077         graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
3078       point=primitive_info[i].point;
3079       if (point.x < graphic_context[n]->bounds.x1)
3080         graphic_context[n]->bounds.x1=point.x;
3081       if (point.y < graphic_context[n]->bounds.y1)
3082         graphic_context[n]->bounds.y1=point.y;
3083       if (point.x > graphic_context[n]->bounds.x2)
3084         graphic_context[n]->bounds.x2=point.x;
3085       if (point.y > graphic_context[n]->bounds.y2)
3086         graphic_context[n]->bounds.y2=point.y;
3087       if (primitive_info[i].primitive == ImagePrimitive)
3088         break;
3089       if (i >= (ssize_t) number_points)
3090         ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
3091     }
3092     if (graphic_context[n]->render != MagickFalse)
3093       {
3094         if ((n != 0) && (graphic_context[n]->clip_mask != (char *) NULL) &&
3095             (LocaleCompare(graphic_context[n]->clip_mask,
3096              graphic_context[n-1]->clip_mask) != 0))
3097           (void) DrawClipPath(image,graphic_context[n],
3098             graphic_context[n]->clip_mask,exception);
3099         (void) DrawPrimitive(image,graphic_context[n],primitive_info,exception);
3100       }
3101     if (primitive_info->text != (char *) NULL)
3102       primitive_info->text=(char *) RelinquishMagickMemory(
3103         primitive_info->text);
3104     proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
3105       primitive_extent);
3106     if (proceed == MagickFalse)
3107       break;
3108   }
3109   if (image->debug != MagickFalse)
3110     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
3111   /*
3112     Relinquish resources.
3113   */
3114   token=DestroyString(token);
3115   if (primitive_info != (PrimitiveInfo *) NULL)
3116     primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
3117   primitive=DestroyString(primitive);
3118   for ( ; n >= 0; n--)
3119     graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
3120   graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
3121   if (status == MagickFalse)
3122     ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
3123       keyword);
3124   return(status);
3125 }
3126 \f
3127 /*
3128 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3129 %                                                                             %
3130 %                                                                             %
3131 %                                                                             %
3132 %     D r a w G r a d i e n t I m a g e                                       %
3133 %                                                                             %
3134 %                                                                             %
3135 %                                                                             %
3136 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3137 %
3138 %  DrawGradientImage() draws a linear gradient on the image.
3139 %
3140 %  The format of the DrawGradientImage method is:
3141 %
3142 %      MagickBooleanType DrawGradientImage(Image *image,
3143 %        const DrawInfo *draw_info,ExceptionInfo *exception)
3144 %
3145 %  A description of each parameter follows:
3146 %
3147 %    o image: the image.
3148 %
3149 %    o draw_info: the draw info.
3150 %
3151 %    o exception: return any errors or warnings in this structure.
3152 %
3153 */
3154
3155 static inline double GetStopColorOffset(const GradientInfo *gradient,
3156   const ssize_t x,const ssize_t y)
3157 {
3158   switch (gradient->type)
3159   {
3160     case UndefinedGradient:
3161     case LinearGradient:
3162     {
3163       double
3164         gamma,
3165         length,
3166         offset,
3167         scale;
3168
3169       PointInfo
3170         p,
3171         q;
3172
3173       const SegmentInfo
3174         *gradient_vector;
3175
3176       gradient_vector=(&gradient->gradient_vector);
3177       p.x=gradient_vector->x2-gradient_vector->x1;
3178       p.y=gradient_vector->y2-gradient_vector->y1;
3179       q.x=(double) x-gradient_vector->x1;
3180       q.y=(double) y-gradient_vector->y1;
3181       length=sqrt(q.x*q.x+q.y*q.y);
3182       gamma=sqrt(p.x*p.x+p.y*p.y)*length;
3183       gamma=MagickEpsilonReciprocal(gamma);
3184       scale=p.x*q.x+p.y*q.y;
3185       offset=gamma*scale*length;
3186       return(offset);
3187     }
3188     case RadialGradient:
3189     {
3190       double
3191         length,
3192         offset;
3193
3194       PointInfo
3195         v;
3196
3197       v.x=(double) x-gradient->center.x;
3198       v.y=(double) y-gradient->center.y;
3199       length=sqrt(v.x*v.x+v.y*v.y);
3200       if (gradient->spread == RepeatSpread)
3201         return(length);
3202       offset=length/gradient->radius;
3203       return(offset);
3204     }
3205   }
3206   return(0.0);
3207 }
3208
3209 MagickExport MagickBooleanType DrawGradientImage(Image *image,
3210   const DrawInfo *draw_info,ExceptionInfo *exception)
3211 {
3212   CacheView
3213     *image_view;
3214
3215   const GradientInfo
3216     *gradient;
3217
3218   const SegmentInfo
3219     *gradient_vector;
3220
3221   MagickBooleanType
3222     status;
3223
3224   PixelInfo
3225     zero;
3226
3227   double
3228     length;
3229
3230   PointInfo
3231     point;
3232
3233   RectangleInfo
3234     bounding_box;
3235
3236   size_t
3237     height,
3238     width;
3239
3240   ssize_t
3241     y;
3242
3243   /*
3244     Draw linear or radial gradient on image.
3245   */
3246   assert(image != (Image *) NULL);
3247   assert(image->signature == MagickSignature);
3248   if (image->debug != MagickFalse)
3249     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3250   assert(draw_info != (const DrawInfo *) NULL);
3251   gradient=(&draw_info->gradient);
3252   gradient_vector=(&gradient->gradient_vector);
3253   point.x=gradient_vector->x2-gradient_vector->x1;
3254   point.y=gradient_vector->y2-gradient_vector->y1;
3255   length=sqrt(point.x*point.x+point.y*point.y);
3256   bounding_box=gradient->bounding_box;
3257   status=MagickTrue;
3258   GetPixelInfo(image,&zero);
3259   height=bounding_box.height-bounding_box.y;
3260   width=bounding_box.width-bounding_box.x;
3261   image_view=AcquireAuthenticCacheView(image,exception);
3262 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3263   #pragma omp parallel for schedule(static) shared(status) \
3264     dynamic_number_threads(image,width,height,1)
3265 #endif
3266   for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
3267   {
3268     PixelInfo
3269       composite,
3270       pixel;
3271
3272     double
3273       alpha,
3274       offset;
3275
3276     register Quantum
3277       *restrict q;
3278
3279     register ssize_t
3280       i,
3281       x;
3282
3283     ssize_t
3284       j;
3285
3286     if (status == MagickFalse)
3287       continue;
3288     q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
3289     if (q == (Quantum *) NULL)
3290       {
3291         status=MagickFalse;
3292         continue;
3293       }
3294     pixel=zero;
3295     composite=zero;
3296     offset=GetStopColorOffset(gradient,0,y);
3297     if (gradient->type != RadialGradient)
3298       offset/=length;
3299     for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
3300     {
3301       GetPixelInfoPixel(image,q,&pixel);
3302       switch (gradient->spread)
3303       {
3304         case UndefinedSpread:
3305         case PadSpread:
3306         {
3307           if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
3308               (y != (ssize_t) ceil(gradient_vector->y1-0.5)))
3309             {
3310               offset=GetStopColorOffset(gradient,x,y);
3311               if (gradient->type != RadialGradient)
3312                 offset/=length;
3313             }
3314           for (i=0; i < (ssize_t) gradient->number_stops; i++)
3315             if (offset < gradient->stops[i].offset)
3316               break;
3317           if ((offset < 0.0) || (i == 0))
3318             composite=gradient->stops[0].color;
3319           else
3320             if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
3321               composite=gradient->stops[gradient->number_stops-1].color;
3322             else
3323               {
3324                 j=i;
3325                 i--;
3326                 alpha=(offset-gradient->stops[i].offset)/
3327                   (gradient->stops[j].offset-gradient->stops[i].offset);
3328                 CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
3329                   &gradient->stops[j].color,alpha,&composite);
3330               }
3331           break;
3332         }
3333         case ReflectSpread:
3334         {
3335           if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
3336               (y != (ssize_t) ceil(gradient_vector->y1-0.5)))
3337             {
3338               offset=GetStopColorOffset(gradient,x,y);
3339               if (gradient->type != RadialGradient)
3340                 offset/=length;
3341             }
3342           if (offset < 0.0)
3343             offset=(-offset);
3344           if ((ssize_t) fmod(offset,2.0) == 0)
3345             offset=fmod(offset,1.0);
3346           else
3347             offset=1.0-fmod(offset,1.0);
3348           for (i=0; i < (ssize_t) gradient->number_stops; i++)
3349             if (offset < gradient->stops[i].offset)
3350               break;
3351           if (i == 0)
3352             composite=gradient->stops[0].color;
3353           else
3354             if (i == (ssize_t) gradient->number_stops)
3355               composite=gradient->stops[gradient->number_stops-1].color;
3356             else
3357               {
3358                 j=i;
3359                 i--;
3360                 alpha=(offset-gradient->stops[i].offset)/
3361                   (gradient->stops[j].offset-gradient->stops[i].offset);
3362                 CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
3363                   &gradient->stops[j].color,alpha,&composite);
3364               }
3365           break;
3366         }
3367         case RepeatSpread:
3368         {
3369           MagickBooleanType
3370             antialias;
3371
3372           double
3373             repeat;
3374
3375           antialias=MagickFalse;
3376           repeat=0.0;
3377           if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
3378               (y != (ssize_t) ceil(gradient_vector->y1-0.5)))
3379             {
3380               offset=GetStopColorOffset(gradient,x,y);
3381               if (gradient->type == LinearGradient)
3382                 {
3383                   repeat=fmod(offset,length);
3384                   if (repeat < 0.0)
3385                     repeat=length-fmod(-repeat,length);
3386                   else
3387                     repeat=fmod(offset,length);
3388                   antialias=(repeat < length) && ((repeat+1.0) > length) ?
3389                     MagickTrue : MagickFalse;
3390                   offset=repeat/length;
3391                 }
3392               else
3393                 {
3394                   repeat=fmod(offset,gradient->radius);
3395                   if (repeat < 0.0)
3396                     repeat=gradient->radius-fmod(-repeat,gradient->radius);
3397                   else
3398                     repeat=fmod(offset,gradient->radius);
3399                   antialias=repeat+1.0 > gradient->radius ? MagickTrue :
3400                     MagickFalse;
3401                   offset=repeat/gradient->radius;
3402                 }
3403             }
3404           for (i=0; i < (ssize_t) gradient->number_stops; i++)
3405             if (offset < gradient->stops[i].offset)
3406               break;
3407           if (i == 0)
3408             composite=gradient->stops[0].color;
3409           else
3410             if (i == (ssize_t) gradient->number_stops)
3411               composite=gradient->stops[gradient->number_stops-1].color;
3412             else
3413               {
3414                 j=i;
3415                 i--;
3416                 alpha=(offset-gradient->stops[i].offset)/
3417                   (gradient->stops[j].offset-gradient->stops[i].offset);
3418                 if (antialias != MagickFalse)
3419                   {
3420                     if (gradient->type == LinearGradient)
3421                       alpha=length-repeat;
3422                     else
3423                       alpha=gradient->radius-repeat;
3424                     i=0;
3425                     j=(ssize_t) gradient->number_stops-1L;
3426                   }
3427                 CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
3428                   &gradient->stops[j].color,alpha,&composite);
3429               }
3430           break;
3431         }
3432       }
3433       CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,
3434         &pixel);
3435       SetPixelInfoPixel(image,&pixel,q);
3436       q+=GetPixelChannels(image);
3437     }
3438     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3439       status=MagickFalse;
3440   }
3441   image_view=DestroyCacheView(image_view);
3442   return(status);
3443 }
3444 \f
3445 /*
3446 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3447 %                                                                             %
3448 %                                                                             %
3449 %                                                                             %
3450 %   D r a w P a t t e r n P a t h                                             %
3451 %                                                                             %
3452 %                                                                             %
3453 %                                                                             %
3454 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3455 %
3456 %  DrawPatternPath() draws a pattern.
3457 %
3458 %  The format of the DrawPatternPath method is:
3459 %
3460 %      MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
3461 %        const char *name,Image **pattern,ExceptionInfo *exception)
3462 %
3463 %  A description of each parameter follows:
3464 %
3465 %    o image: the image.
3466 %
3467 %    o draw_info: the draw info.
3468 %
3469 %    o name: the pattern name.
3470 %
3471 %    o image: the image.
3472 %
3473 %    o exception: return any errors or warnings in this structure.
3474 %
3475 */
3476 MagickExport MagickBooleanType DrawPatternPath(Image *image,
3477   const DrawInfo *draw_info,const char *name,Image **pattern,
3478   ExceptionInfo *exception)
3479 {
3480   char
3481     property[MaxTextExtent];
3482
3483   const char
3484     *geometry,
3485     *path;
3486
3487   DrawInfo
3488     *clone_info;
3489
3490   ImageInfo
3491     *image_info;
3492
3493   MagickBooleanType
3494     status;
3495
3496   assert(image != (Image *) NULL);
3497   assert(image->signature == MagickSignature);
3498   if (image->debug != MagickFalse)
3499     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3500   assert(draw_info != (const DrawInfo *) NULL);
3501   assert(name != (const char *) NULL);
3502   (void) FormatLocaleString(property,MaxTextExtent,"%s",name);
3503   path=GetImageArtifact(image,property);
3504   if (path == (const char *) NULL)
3505     return(MagickFalse);
3506   (void) FormatLocaleString(property,MaxTextExtent,"%s-geometry",name);
3507   geometry=GetImageArtifact(image,property);
3508   if (geometry == (const char *) NULL)
3509     return(MagickFalse);
3510   if ((*pattern) != (Image *) NULL)
3511     *pattern=DestroyImage(*pattern);
3512   image_info=AcquireImageInfo();
3513   image_info->size=AcquireString(geometry);
3514   *pattern=AcquireImage(image_info,exception);
3515   image_info=DestroyImageInfo(image_info);
3516   (void) QueryColorCompliance("#00000000",AllCompliance,
3517     &(*pattern)->background_color,exception);
3518   (void) SetImageBackgroundColor(*pattern,exception);
3519   if (image->debug != MagickFalse)
3520     (void) LogMagickEvent(DrawEvent,GetMagickModule(),
3521       "begin pattern-path %s %s",name,geometry);
3522   clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
3523   clone_info->fill_pattern=NewImageList();
3524   clone_info->stroke_pattern=NewImageList();
3525   (void) CloneString(&clone_info->primitive,path);
3526   status=DrawImage(*pattern,clone_info,exception);
3527   clone_info=DestroyDrawInfo(clone_info);
3528   if (image->debug != MagickFalse)
3529     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
3530   return(status);
3531 }
3532 \f
3533 /*
3534 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3535 %                                                                             %
3536 %                                                                             %
3537 %                                                                             %
3538 +   D r a w P o l y g o n P r i m i t i v e                                   %
3539 %                                                                             %
3540 %                                                                             %
3541 %                                                                             %
3542 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3543 %
3544 %  DrawPolygonPrimitive() draws a polygon on the image.
3545 %
3546 %  The format of the DrawPolygonPrimitive method is:
3547 %
3548 %      MagickBooleanType DrawPolygonPrimitive(Image *image,
3549 %        const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
3550 %        ExceptionInfo *exception)
3551 %
3552 %  A description of each parameter follows:
3553 %
3554 %    o image: the image.
3555 %
3556 %    o draw_info: the draw info.
3557 %
3558 %    o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
3559 %
3560 %    o exception: return any errors or warnings in this structure.
3561 %
3562 */
3563
3564 static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
3565 {
3566   register ssize_t
3567     i;
3568
3569   assert(polygon_info != (PolygonInfo **) NULL);
3570   for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
3571     if (polygon_info[i] != (PolygonInfo *) NULL)
3572       polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
3573   polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
3574   return(polygon_info);
3575 }
3576
3577 static PolygonInfo **AcquirePolygonThreadSet(const DrawInfo *draw_info,
3578   const PrimitiveInfo *primitive_info)
3579 {
3580   PathInfo
3581     *restrict path_info;
3582
3583   PolygonInfo
3584     **polygon_info;
3585
3586   register ssize_t
3587     i;
3588
3589   size_t
3590     number_threads;
3591
3592   number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
3593   polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
3594     sizeof(*polygon_info));
3595   if (polygon_info == (PolygonInfo **) NULL)
3596     return((PolygonInfo **) NULL);
3597   (void) ResetMagickMemory(polygon_info,0,number_threads*sizeof(*polygon_info));
3598   path_info=ConvertPrimitiveToPath(draw_info,primitive_info);
3599   if (path_info == (PathInfo *) NULL)
3600     return(DestroyPolygonThreadSet(polygon_info));
3601   for (i=0; i < (ssize_t) number_threads; i++)
3602   {
3603     polygon_info[i]=ConvertPathToPolygon(draw_info,path_info);
3604     if (polygon_info[i] == (PolygonInfo *) NULL)
3605       return(DestroyPolygonThreadSet(polygon_info));
3606   }
3607   path_info=(PathInfo *) RelinquishMagickMemory(path_info);
3608   return(polygon_info);
3609 }
3610
3611 static double GetFillAlpha(PolygonInfo *polygon_info,
3612   const double mid,const MagickBooleanType fill,
3613   const FillRule fill_rule,const double x,const double y,
3614   double *stroke_alpha)
3615 {
3616   double
3617     alpha,
3618     beta,
3619     distance,
3620     subpath_alpha;
3621
3622   PointInfo
3623     delta;
3624
3625   register EdgeInfo
3626     *p;
3627
3628   register const PointInfo
3629     *q;
3630
3631   register ssize_t
3632     i;
3633
3634   ssize_t
3635     j,
3636     winding_number;
3637
3638   /*
3639     Compute fill & stroke opacity for this (x,y) point.
3640   */
3641   *stroke_alpha=0.0;
3642   subpath_alpha=0.0;
3643   p=polygon_info->edges;
3644   for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
3645   {
3646     if (y <= (p->bounds.y1-mid-0.5))
3647       break;
3648     if (y > (p->bounds.y2+mid+0.5))
3649       {
3650         (void) DestroyEdge(polygon_info,(size_t) j);
3651         continue;
3652       }
3653     if ((x <= (p->bounds.x1-mid-0.5)) || (x > (p->bounds.x2+mid+0.5)))
3654       continue;
3655     i=(ssize_t) MagickMax((double) p->highwater,1.0);
3656     for ( ; i < (ssize_t) p->number_points; i++)
3657     {
3658       if (y <= (p->points[i-1].y-mid-0.5))
3659         break;
3660       if (y > (p->points[i].y+mid+0.5))
3661         continue;
3662       if (p->scanline != y)
3663         {
3664           p->scanline=y;
3665           p->highwater=(size_t) i;
3666         }
3667       /*
3668         Compute distance between a point and an edge.
3669       */
3670       q=p->points+i-1;
3671       delta.x=(q+1)->x-q->x;
3672       delta.y=(q+1)->y-q->y;
3673       beta=delta.x*(x-q->x)+delta.y*(y-q->y);
3674       if (beta < 0.0)
3675         {
3676           delta.x=x-q->x;
3677           delta.y=y-q->y;
3678           distance=delta.x*delta.x+delta.y*delta.y;
3679         }
3680       else
3681         {
3682           alpha=delta.x*delta.x+delta.y*delta.y;
3683           if (beta > alpha)
3684             {
3685               delta.x=x-(q+1)->x;
3686               delta.y=y-(q+1)->y;
3687               distance=delta.x*delta.x+delta.y*delta.y;
3688             }
3689           else
3690             {
3691               alpha=1.0/alpha;
3692               beta=delta.x*(y-q->y)-delta.y*(x-q->x);
3693               distance=alpha*beta*beta;
3694             }
3695         }
3696       /*
3697         Compute stroke & subpath opacity.
3698       */
3699       beta=0.0;
3700       if (p->ghostline == MagickFalse)
3701         {
3702           alpha=mid+0.5;
3703           if ((*stroke_alpha < 1.0) &&
3704               (distance <= ((alpha+0.25)*(alpha+0.25))))
3705             {
3706               alpha=mid-0.5;
3707               if (distance <= ((alpha+0.25)*(alpha+0.25)))
3708                 *stroke_alpha=1.0;
3709               else
3710                 {
3711                   beta=1.0;
3712                   if (distance != 1.0)
3713                     beta=sqrt((double) distance);
3714                   alpha=beta-mid-0.5;
3715                   if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))
3716                     *stroke_alpha=(alpha-0.25)*(alpha-0.25);
3717                 }
3718             }
3719         }
3720       if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))
3721         continue;
3722       if (distance <= 0.0)
3723         {
3724           subpath_alpha=1.0;
3725           continue;
3726         }
3727       if (distance > 1.0)
3728         continue;
3729       if (beta == 0.0)
3730         {
3731           beta=1.0;
3732           if (distance != 1.0)
3733             beta=sqrt(distance);
3734         }
3735       alpha=beta-1.0;
3736       if (subpath_alpha < (alpha*alpha))
3737         subpath_alpha=alpha*alpha;
3738     }
3739   }
3740   /*
3741     Compute fill opacity.
3742   */
3743   if (fill == MagickFalse)
3744     return(0.0);
3745   if (subpath_alpha >= 1.0)
3746     return(1.0);
3747   /*
3748     Determine winding number.
3749   */
3750   winding_number=0;
3751   p=polygon_info->edges;
3752   for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
3753   {
3754     if (y <= p->bounds.y1)
3755       break;
3756     if ((y > p->bounds.y2) || (x <= p->bounds.x1))
3757       continue;
3758     if (x > p->bounds.x2)
3759       {
3760         winding_number+=p->direction ? 1 : -1;
3761         continue;
3762       }
3763     i=(ssize_t) MagickMax((double) p->highwater,1.0);
3764     for ( ; i < (ssize_t) p->number_points; i++)
3765       if (y <= p->points[i].y)
3766         break;
3767     q=p->points+i-1;
3768     if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
3769       winding_number+=p->direction ? 1 : -1;
3770   }
3771   if (fill_rule != NonZeroRule)
3772     {
3773       if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
3774         return(1.0);
3775     }
3776   else
3777     if (MagickAbsoluteValue(winding_number) != 0)
3778       return(1.0);
3779   return(subpath_alpha);
3780 }
3781
3782 static MagickBooleanType DrawPolygonPrimitive(Image *image,
3783   const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
3784   ExceptionInfo *exception)
3785 {
3786   CacheView
3787     *image_view;
3788
3789   MagickBooleanType
3790     fill,
3791     status;
3792
3793   double
3794     mid;
3795
3796   PolygonInfo
3797     **restrict polygon_info;
3798
3799   register EdgeInfo
3800     *p;
3801
3802   register ssize_t
3803     i;
3804
3805   SegmentInfo
3806     bounds;
3807
3808   size_t
3809     height,
3810     width;
3811
3812   ssize_t
3813     start,
3814     stop,
3815     y;
3816
3817   /*
3818     Compute bounding box.
3819   */
3820   assert(image != (Image *) NULL);
3821   assert(image->signature == MagickSignature);
3822   if (image->debug != MagickFalse)
3823     (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
3824   assert(draw_info != (DrawInfo *) NULL);
3825   assert(draw_info->signature == MagickSignature);
3826   assert(primitive_info != (PrimitiveInfo *) NULL);
3827   if (primitive_info->coordinates == 0)
3828     return(MagickTrue);
3829   polygon_info=AcquirePolygonThreadSet(draw_info,primitive_info);
3830   if (polygon_info == (PolygonInfo **) NULL)
3831     return(MagickFalse);
3832   if (0)
3833     DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);
3834   if (image->debug != MagickFalse)
3835     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    begin draw-polygon");
3836   fill=(primitive_info->method == FillToBorderMethod) ||
3837     (primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
3838   mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
3839   bounds=polygon_info[0]->edges[0].bounds;
3840   for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
3841   {
3842     p=polygon_info[0]->edges+i;
3843     if (p->bounds.x1 < bounds.x1)
3844       bounds.x1=p->bounds.x1;
3845     if (p->bounds.y1 < bounds.y1)
3846       bounds.y1=p->bounds.y1;
3847     if (p->bounds.x2 > bounds.x2)
3848       bounds.x2=p->bounds.x2;
3849     if (p->bounds.y2 > bounds.y2)
3850       bounds.y2=p->bounds.y2;
3851   }
3852   bounds.x1-=(mid+1.0);
3853   bounds.x1=bounds.x1 < 0.0 ? 0.0 : (size_t) ceil(bounds.x1-0.5) >=
3854     image->columns ? (double) image->columns-1.0 : bounds.x1;
3855   bounds.y1-=(mid+1.0);
3856   bounds.y1=bounds.y1 < 0.0 ? 0.0 : (size_t) ceil(bounds.y1-0.5) >=
3857     image->rows ? (double) image->rows-1.0 : bounds.y1;
3858   bounds.x2+=(mid+1.0);
3859   bounds.x2=bounds.x2 < 0.0 ? 0.0 : (size_t) floor(bounds.x2+0.5) >=
3860     image->columns ? (double) image->columns-1.0 : bounds.x2;
3861   bounds.y2+=(mid+1.0);
3862   bounds.y2=bounds.y2 < 0.0 ? 0.0 : (size_t) floor(bounds.y2+0.5) >=
3863     image->rows ? (double) image->rows-1.0 : bounds.y2;
3864   status=MagickTrue;
3865   image_view=AcquireAuthenticCacheView(image,exception);
3866   height=(size_t) (floor(bounds.y2+0.5)-ceil(bounds.y1-0.5));
3867   width=(size_t) (floor(bounds.x2+0.5)-ceil(bounds.x1-0.5));
3868   if (primitive_info->coordinates == 1)
3869     {
3870       /*
3871         Draw point.
3872       */
3873       start=(ssize_t) ceil(bounds.y1-0.5);
3874       stop=(ssize_t) floor(bounds.y2+0.5);
3875 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3876       #pragma omp parallel for schedule(static) shared(status) \
3877         dynamic_number_threads(image,width,height,1)
3878 #endif
3879       for (y=start; y <= stop; y++)
3880       {
3881         MagickBooleanType
3882           sync;
3883
3884         PixelInfo
3885           pixel;
3886
3887         register ssize_t
3888           x;
3889
3890         register Quantum
3891           *restrict q;
3892
3893         ssize_t
3894           start,
3895           stop;
3896
3897         if (status == MagickFalse)
3898           continue;
3899         start=(ssize_t) ceil(bounds.x1-0.5);
3900         stop=(ssize_t) floor(bounds.x2+0.5);
3901         x=start;
3902         q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop-x+1),
3903           1,exception);
3904         if (q == (Quantum *) NULL)
3905           {
3906             status=MagickFalse;
3907             continue;
3908           }
3909         GetPixelInfo(image,&pixel);
3910         for ( ; x <= stop; x++)
3911         {
3912           if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
3913               (y == (ssize_t) ceil(primitive_info->point.y-0.5)))
3914             {
3915               (void) GetStrokeColor(draw_info,x,y,&pixel,exception);
3916               SetPixelInfoPixel(image,&pixel,q);
3917             }
3918           q+=GetPixelChannels(image);
3919         }
3920         sync=SyncCacheViewAuthenticPixels(image_view,exception);
3921         if (sync == MagickFalse)
3922           status=MagickFalse;
3923       }
3924       image_view=DestroyCacheView(image_view);
3925       polygon_info=DestroyPolygonThreadSet(polygon_info);
3926       if (image->debug != MagickFalse)
3927         (void) LogMagickEvent(DrawEvent,GetMagickModule(),
3928           "    end draw-polygon");
3929       return(status);
3930     }
3931   /*
3932     Draw polygon or line.
3933   */
3934   if (image->matte == MagickFalse)
3935     (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
3936   start=(ssize_t) ceil(bounds.y1-0.5);
3937   stop=(ssize_t) floor(bounds.y2+0.5);
3938 #if defined(MAGICKCORE_OPENMP_SUPPORT)
3939   #pragma omp parallel for schedule(static) shared(status) \
3940     dynamic_number_threads(image,width,height,1)
3941 #endif
3942   for (y=start; y <= stop; y++)
3943   {
3944     const int
3945       id = GetOpenMPThreadId();
3946
3947     double
3948       fill_alpha,
3949       stroke_alpha;
3950
3951     PixelInfo
3952       fill_color,
3953       stroke_color;
3954
3955     register Quantum
3956       *restrict q;
3957
3958     register ssize_t
3959       x;
3960
3961     ssize_t
3962       start,
3963       stop;
3964
3965     if (status == MagickFalse)
3966       continue;
3967     start=(ssize_t) ceil(bounds.x1-0.5);
3968     stop=(ssize_t) floor(bounds.x2+0.5);
3969     q=GetCacheViewAuthenticPixels(image_view,start,y,(size_t) (stop-start+1),1,
3970       exception);
3971     if (q == (Quantum *) NULL)
3972       {
3973         status=MagickFalse;
3974         continue;
3975       }
3976     for (x=start; x <= stop; x++)
3977     {
3978       /*
3979         Fill and/or stroke.
3980       */
3981       fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,
3982         (double) x,(double) y,&stroke_alpha);
3983       if (draw_info->stroke_antialias == MagickFalse)
3984         {
3985           fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;
3986           stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;
3987         }
3988       (void) GetFillColor(draw_info,x,y,&fill_color,exception);
3989       fill_alpha=fill_alpha*fill_color.alpha;
3990       CompositePixelOver(image,&fill_color,fill_alpha,q,(double)
3991         GetPixelAlpha(image,q),q);
3992       (void) GetStrokeColor(draw_info,x,y,&stroke_color,exception);
3993       stroke_alpha=stroke_alpha*stroke_color.alpha;
3994       CompositePixelOver(image,&stroke_color,stroke_alpha,q,(double)
3995         GetPixelAlpha(image,q),q);
3996       q+=GetPixelChannels(image);
3997     }
3998     if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
3999       status=MagickFalse;
4000   }
4001   image_view=DestroyCacheView(image_view);
4002   polygon_info=DestroyPolygonThreadSet(polygon_info);
4003   if (image->debug != MagickFalse)
4004     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end draw-polygon");
4005   return(status);
4006 }
4007 \f
4008 /*
4009 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4010 %                                                                             %
4011 %                                                                             %
4012 %                                                                             %
4013 %   D r a w P r i m i t i v e                                                 %
4014 %                                                                             %
4015 %                                                                             %
4016 %                                                                             %
4017 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4018 %
4019 %  DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
4020 %
4021 %  The format of the DrawPrimitive method is:
4022 %
4023 %      MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
4024 %        PrimitiveInfo *primitive_info,ExceptionInfo *exception)
4025 %
4026 %  A description of each parameter follows:
4027 %
4028 %    o image: the image.
4029 %
4030 %    o draw_info: the draw info.
4031 %
4032 %    o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
4033 %
4034 %    o exception: return any errors or warnings in this structure.
4035 %
4036 */
4037
4038 static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
4039 {
4040   const char
4041     *methods[] =
4042     {
4043       "point",
4044       "replace",
4045       "floodfill",
4046       "filltoborder",
4047       "reset",
4048       "?"
4049     };
4050
4051   PointInfo
4052     p,
4053     q,
4054     point;
4055
4056   register ssize_t
4057     i,
4058     x;
4059
4060   ssize_t
4061     coordinates,
4062     y;
4063
4064   x=(ssize_t) ceil(primitive_info->point.x-0.5);
4065   y=(ssize_t) ceil(primitive_info->point.y-0.5);
4066   switch (primitive_info->primitive)
4067   {
4068     case PointPrimitive:
4069     {
4070       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4071         "PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
4072         methods[primitive_info->method]);
4073       return;
4074     }
4075     case ColorPrimitive:
4076     {
4077       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4078         "ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
4079         methods[primitive_info->method]);
4080       return;
4081     }
4082     case MattePrimitive:
4083     {
4084       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4085         "MattePrimitive %.20g,%.20g %s",(double) x,(double) y,
4086         methods[primitive_info->method]);
4087       return;
4088     }
4089     case TextPrimitive:
4090     {
4091       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4092         "TextPrimitive %.20g,%.20g",(double) x,(double) y);
4093       return;
4094     }
4095     case ImagePrimitive:
4096     {
4097       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4098         "ImagePrimitive %.20g,%.20g",(double) x,(double) y);
4099       return;
4100     }
4101     default:
4102       break;
4103   }
4104   coordinates=0;
4105   p=primitive_info[0].point;
4106   q.x=(-1.0);
4107   q.y=(-1.0);
4108   for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
4109   {
4110     point=primitive_info[i].point;
4111     if (coordinates <= 0)
4112       {
4113         coordinates=(ssize_t) primitive_info[i].coordinates;
4114         (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4115           "    begin open (%.20g)",(double) coordinates);
4116         p=point;
4117       }
4118     point=primitive_info[i].point;
4119     if ((fabs(q.x-point.x) >= MagickEpsilon) ||
4120         (fabs(q.y-point.y) >= MagickEpsilon))
4121       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4122         "      %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
4123     else
4124       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4125         "      %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
4126     q=point;
4127     coordinates--;
4128     if (coordinates > 0)
4129       continue;
4130     if ((fabs(p.x-point.x) >= MagickEpsilon) ||
4131         (fabs(p.y-point.y) >= MagickEpsilon))
4132       (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end last (%.20g)",
4133         (double) coordinates);
4134     else
4135       (void) LogMagickEvent(DrawEvent,GetMagickModule(),"    end open (%.20g)",
4136         (double) coordinates);
4137   }
4138 }
4139
4140 MagickExport MagickBooleanType DrawPrimitive(Image *image,
4141   const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
4142   ExceptionInfo *exception)
4143 {
4144   CacheView
4145     *image_view;
4146
4147   MagickStatusType
4148     status;
4149
4150   register ssize_t
4151     i,
4152     x;
4153
4154   ssize_t
4155     y;
4156
4157   if (image->debug != MagickFalse)
4158     {
4159       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4160         "  begin draw-primitive");
4161       (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4162         "    affine: %g %g %g %g %g %g",draw_info->affine.sx,
4163         draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
4164         draw_info->affine.tx,draw_info->affine.ty);
4165     }
4166   if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
4167       ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
4168        (IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
4169     (void) SetImageColorspace(image,RGBColorspace,exception);
4170   status=MagickTrue;
4171   x=(ssize_t) ceil(primitive_info->point.x-0.5);
4172   y=(ssize_t) ceil(primitive_info->point.y-0.5);
4173   image_view=AcquireAuthenticCacheView(image,exception);
4174   switch (primitive_info->primitive)
4175   {
4176     case PointPrimitive:
4177     {
4178       PixelInfo
4179         fill_color;
4180
4181       register Quantum
4182         *q;
4183
4184       if ((y < 0) || (y >= (ssize_t) image->rows))
4185         break;
4186       if ((x < 0) || (x >= (ssize_t) image->columns))
4187         break;
4188       q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
4189       if (q == (Quantum *) NULL)
4190         break;
4191       (void) GetFillColor(draw_info,x,y,&fill_color,exception);
4192       CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
4193         (double) GetPixelAlpha(image,q),q);
4194       (void) SyncCacheViewAuthenticPixels(image_view,exception);
4195       break;
4196     }
4197     case ColorPrimitive:
4198     {
4199       switch (primitive_info->method)
4200       {
4201         case PointMethod:
4202         default:
4203         {
4204           PixelInfo
4205             pixel;
4206
4207           register Quantum
4208             *q;
4209
4210           q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
4211           if (q == (Quantum *) NULL)
4212             break;
4213           GetPixelInfo(image,&pixel);
4214           (void) GetFillColor(draw_info,x,y,&pixel,exception);
4215           SetPixelInfoPixel(image,&pixel,q);
4216           (void) SyncCacheViewAuthenticPixels(image_view,exception);
4217           break;
4218         }
4219         case ReplaceMethod:
4220         {
4221           MagickBooleanType
4222             sync;
4223
4224           PixelInfo
4225             pixel,
4226             target;
4227
4228           (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
4229             exception);
4230           for (y=0; y < (ssize_t) image->rows; y++)
4231           {
4232             register Quantum
4233               *restrict q;
4234
4235             q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
4236               exception);
4237             if (q == (Quantum *) NULL)
4238               break;
4239             for (x=0; x < (ssize_t) image->columns; x++)
4240             {
4241               GetPixelInfoPixel(image,q,&pixel);
4242               if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
4243                 {
4244                   q+=GetPixelChannels(image);
4245                   continue;
4246                 }
4247               (void) GetFillColor(draw_info,x,y,&pixel,exception);
4248               SetPixelInfoPixel(image,&pixel,q);
4249               q+=GetPixelChannels(image);
4250             }
4251             sync=SyncCacheViewAuthenticPixels(image_view,exception);
4252             if (sync == MagickFalse)
4253               break;
4254           }
4255           break;
4256         }
4257         case FloodfillMethod:
4258         case FillToBorderMethod:
4259         {
4260           PixelInfo
4261             target;
4262
4263           (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
4264             &target,exception);
4265           if (primitive_info->method == FillToBorderMethod)
4266             {
4267               target.red=(double) draw_info->border_color.red;
4268               target.green=(double) draw_info->border_color.green;
4269               target.blue=(double) draw_info->border_color.blue;
4270             }
4271           (void) FloodfillPaintImage(image,draw_info,&target,x,y,
4272             primitive_info->method == FloodfillMethod ? MagickFalse :
4273             MagickTrue,exception);
4274           break;
4275         }
4276         case ResetMethod:
4277         {
4278           MagickBooleanType
4279             sync;
4280
4281           PixelInfo
4282             pixel;
4283
4284           GetPixelInfo(image,&pixel);
4285           for (y=0; y < (ssize_t) image->rows; y++)
4286           {
4287             register Quantum
4288               *restrict q;
4289
4290             register ssize_t
4291               x;
4292
4293             q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
4294               exception);
4295             if (q == (Quantum *) NULL)
4296               break;
4297             for (x=0; x < (ssize_t) image->columns; x++)
4298             {
4299               (void) GetFillColor(draw_info,x,y,&pixel,exception);
4300               SetPixelInfoPixel(image,&pixel,q);
4301               q+=GetPixelChannels(image);
4302             }
4303             sync=SyncCacheViewAuthenticPixels(image_view,exception);
4304             if (sync == MagickFalse)
4305               break;
4306           }
4307           break;
4308         }
4309       }
4310       break;
4311     }
4312     case MattePrimitive:
4313     {
4314       if (image->matte == MagickFalse)
4315         (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
4316       switch (primitive_info->method)
4317       {
4318         case PointMethod:
4319         default:
4320         {
4321           PixelInfo
4322             pixel;
4323
4324           register Quantum
4325             *q;
4326
4327           q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
4328           if (q == (Quantum *) NULL)
4329             break;
4330           (void) GetFillColor(draw_info,x,y,&pixel,exception);
4331           SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
4332           (void) SyncCacheViewAuthenticPixels(image_view,exception);
4333           break;
4334         }
4335         case ReplaceMethod:
4336         {
4337           MagickBooleanType
4338             sync;
4339
4340           PixelInfo
4341             pixel,
4342             target;
4343
4344           (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
4345             exception);
4346           for (y=0; y < (ssize_t) image->rows; y++)
4347           {
4348             register Quantum
4349               *restrict q;
4350
4351             register ssize_t
4352               x;
4353
4354             q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
4355               exception);
4356             if (q == (Quantum *) NULL)
4357               break;
4358             for (x=0; x < (ssize_t) image->columns; x++)
4359             {
4360               GetPixelInfoPixel(image,q,&pixel);
4361               if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
4362                 {
4363                   q+=GetPixelChannels(image);
4364                   continue;
4365                 }
4366               (void) GetFillColor(draw_info,x,y,&pixel,exception);
4367               SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
4368               q+=GetPixelChannels(image);
4369             }
4370             sync=SyncCacheViewAuthenticPixels(image_view,exception);
4371             if (sync == MagickFalse)
4372               break;
4373           }
4374           break;
4375         }
4376         case FloodfillMethod:
4377         case FillToBorderMethod:
4378         {
4379           ChannelType
4380             channel_mask;
4381
4382           PixelInfo
4383             target;
4384
4385           (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
4386             &target,exception);
4387           if (primitive_info->method == FillToBorderMethod)
4388             {
4389               target.red=(double) draw_info->border_color.red;
4390               target.green=(double) draw_info->border_color.green;
4391               target.blue=(double) draw_info->border_color.blue;
4392             }
4393           channel_mask=SetPixelChannelMask(image,AlphaChannel);
4394           (void) FloodfillPaintImage(image,draw_info,&target,x,y,
4395             primitive_info->method == FloodfillMethod ? MagickFalse :
4396             MagickTrue,exception);
4397           (void) SetPixelChannelMask(image,channel_mask);
4398           break;
4399         }
4400         case ResetMethod:
4401         {
4402           MagickBooleanType
4403             sync;
4404
4405           PixelInfo
4406             pixel;
4407
4408           for (y=0; y < (ssize_t) image->rows; y++)
4409           {
4410             register Quantum
4411               *restrict q;
4412
4413             register ssize_t
4414               x;
4415
4416             q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
4417               exception);
4418             if (q == (Quantum *) NULL)
4419               break;
4420             for (x=0; x < (ssize_t) image->columns; x++)
4421             {
4422               (void) GetFillColor(draw_info,x,y,&pixel,exception);
4423               SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
4424               q+=GetPixelChannels(image);
4425             }
4426             sync=SyncCacheViewAuthenticPixels(image_view,exception);
4427             if (sync == MagickFalse)
4428               break;
4429           }
4430           break;
4431         }
4432       }
4433       break;
4434     }
4435     case TextPrimitive:
4436     {
4437       char
4438         geometry[MaxTextExtent];
4439
4440       DrawInfo
4441         *clone_info;
4442
4443       if (primitive_info->text == (char *) NULL)
4444         break;
4445       clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
4446       (void) CloneString(&clone_info->text,primitive_info->text);
4447       (void) FormatLocaleString(geometry,MaxTextExtent,"%+f%+f",
4448         primitive_info->point.x,primitive_info->point.y);
4449       (void) CloneString(&clone_info->geometry,geometry);
4450       status=AnnotateImage(image,clone_info,exception);
4451       clone_info=DestroyDrawInfo(clone_info);
4452       break;
4453     }
4454     case ImagePrimitive:
4455     {
4456       AffineMatrix
4457         affine;
4458
4459       char
4460         composite_geometry[MaxTextExtent];
4461
4462       Image
4463         *composite_image;
4464
4465       ImageInfo
4466         *clone_info;
4467
4468       RectangleInfo
4469         geometry;
4470
4471       ssize_t
4472         x1,
4473         y1;
4474
4475       if (primitive_info->text == (char *) NULL)
4476         break;
4477       clone_info=AcquireImageInfo();
4478       if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
4479         composite_image=ReadInlineImage(clone_info,primitive_info->text,
4480           exception);
4481       else
4482         {
4483           (void) CopyMagickString(clone_info->filename,primitive_info->text,
4484             MaxTextExtent);
4485           composite_image=ReadImage(clone_info,exception);
4486         }
4487       clone_info=DestroyImageInfo(clone_info);
4488       if (composite_image == (Image *) NULL)
4489         break;
4490       (void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
4491         NULL,(void *) NULL);
4492       x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
4493       y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
4494       if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
4495           ((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
4496         {
4497           char
4498             geometry[MaxTextExtent];
4499
4500           /*
4501             Resize image.
4502           */
4503           (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g!",
4504             primitive_info[1].point.x,primitive_info[1].point.y);
4505           composite_image->filter=image->filter;
4506           (void) TransformImage(&composite_image,(char *) NULL,geometry,
4507             exception);
4508         }
4509       if (composite_image->matte == MagickFalse)
4510         (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
4511           exception);
4512       if (draw_info->alpha != OpaqueAlpha)
4513         (void) SetImageAlpha(composite_image,draw_info->alpha,exception);
4514       SetGeometry(image,&geometry);
4515       image->gravity=draw_info->gravity;
4516       geometry.x=x;
4517       geometry.y=y;
4518       (void) FormatLocaleString(composite_geometry,MaxTextExtent,
4519         "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
4520         composite_image->rows,(double) geometry.x,(double) geometry.y);
4521       (void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
4522       affine=draw_info->affine;
4523       affine.tx=(double) geometry.x;
4524       affine.ty=(double) geometry.y;
4525       composite_image->interpolate=image->interpolate;
4526       if (draw_info->compose == OverCompositeOp)
4527         (void) DrawAffineImage(image,composite_image,&affine,exception);
4528       else
4529         (void) CompositeImage(image,composite_image,draw_info->compose,
4530           MagickTrue,geometry.x,geometry.y,exception);
4531       composite_image=DestroyImage(composite_image);
4532       break;
4533     }
4534     default:
4535     {
4536       double
4537         mid,
4538         scale;
4539
4540       DrawInfo
4541         *clone_info;
4542
4543       if (IsEventLogging() != MagickFalse)
4544         LogPrimitiveInfo(primitive_info);
4545       scale=ExpandAffine(&draw_info->affine);
4546       if ((draw_info->dash_pattern != (double *) NULL) &&
4547           (draw_info->dash_pattern[0] != 0.0) &&
4548           ((scale*draw_info->stroke_width) >= MagickEpsilon) &&
4549           (draw_info->stroke.alpha != (Quantum) TransparentAlpha))
4550         {
4551           /*
4552             Draw dash polygon.
4553           */
4554           clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
4555           clone_info->stroke_width=0.0;
4556           clone_info->stroke.alpha=(Quantum) TransparentAlpha;
4557           status=DrawPolygonPrimitive(image,clone_info,primitive_info,
4558             exception);
4559           clone_info=DestroyDrawInfo(clone_info);
4560           (void) DrawDashPolygon(draw_info,primitive_info,image,exception);
4561           break;
4562         }
4563       mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
4564       if ((mid > 1.0) &&
4565           (draw_info->stroke.alpha != (Quantum) TransparentAlpha))
4566         {
4567           MagickBooleanType
4568             closed_path;
4569
4570           /*
4571             Draw strokes while respecting line cap/join attributes.
4572           */
4573           for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
4574           closed_path=
4575             (primitive_info[i-1].point.x == primitive_info[0].point.x) &&
4576             (primitive_info[i-1].point.y == primitive_info[0].point.y) ?
4577             MagickTrue : MagickFalse;
4578           i=(ssize_t) primitive_info[0].coordinates;
4579           if ((((draw_info->linecap == RoundCap) ||
4580                 (closed_path != MagickFalse)) &&
4581                (draw_info->linejoin == RoundJoin)) ||
4582                (primitive_info[i].primitive != UndefinedPrimitive))
4583             {
4584               (void) DrawPolygonPrimitive(image,draw_info,primitive_info,
4585                 exception);
4586               break;
4587             }
4588           clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
4589           clone_info->stroke_width=0.0;
4590           clone_info->stroke.alpha=(Quantum) TransparentAlpha;
4591           status=DrawPolygonPrimitive(image,clone_info,primitive_info,
4592             exception);
4593           clone_info=DestroyDrawInfo(clone_info);
4594           status|=DrawStrokePolygon(image,draw_info,primitive_info,exception);
4595           break;
4596         }
4597       status=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
4598       break;
4599     }
4600   }
4601   image_view=DestroyCacheView(image_view);
4602   if (image->debug != MagickFalse)
4603     (void) LogMagickEvent(DrawEvent,GetMagickModule(),"  end draw-primitive");
4604   return(status != 0 ? MagickTrue : MagickFalse);
4605 }
4606 \f
4607 /*
4608 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4609 %                                                                             %
4610 %                                                                             %
4611 %                                                                             %
4612 +   D r a w S t r o k e P o l y g o n                                         %
4613 %                                                                             %
4614 %                                                                             %
4615 %                                                                             %
4616 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4617 %
4618 %  DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
4619 %  the image while respecting the line cap and join attributes.
4620 %
4621 %  The format of the DrawStrokePolygon method is:
4622 %
4623 %      MagickBooleanType DrawStrokePolygon(Image *image,
4624 %        const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
4625 %
4626 %  A description of each parameter follows:
4627 %
4628 %    o image: the image.
4629 %
4630 %    o draw_info: the draw info.
4631 %
4632 %    o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
4633 %
4634 %
4635 */
4636
4637 static void DrawRoundLinecap(Image *image,const DrawInfo *draw_info,
4638   const PrimitiveInfo *primitive_info,ExceptionInfo *exception)
4639 {
4640   PrimitiveInfo
4641     linecap[5];
4642
4643   register ssize_t
4644     i;
4645
4646   for (i=0; i < 4; i++)
4647     linecap[i]=(*primitive_info);
4648   linecap[0].coordinates=4;
4649   linecap[1].point.x+=(double) (10.0*MagickEpsilon);
4650   linecap[2].point.x+=(double) (10.0*MagickEpsilon);
4651   linecap[2].point.y+=(double) (10.0*MagickEpsilon);
4652   linecap[3].point.y+=(double) (10.0*MagickEpsilon);
4653   linecap[4].primitive=UndefinedPrimitive;
4654   (void) DrawPolygonPrimitive(image,draw_info,linecap,exception);
4655 }
4656
4657 static MagickBooleanType DrawStrokePolygon(Image *image,
4658   const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
4659   ExceptionInfo *exception)
4660 {
4661   DrawInfo
4662     *clone_info;
4663
4664   MagickBooleanType
4665     closed_path,
4666     status;
4667
4668   PrimitiveInfo
4669     *stroke_polygon;
4670
4671   register const PrimitiveInfo
4672     *p,
4673     *q;
4674
4675   /*
4676     Draw stroked polygon.
4677   */
4678   if (image->debug != MagickFalse)
4679     (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4680       "    begin draw-stroke-polygon");
4681   clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
4682   clone_info->fill=draw_info->stroke;
4683   if (clone_info->fill_pattern != (Image *) NULL)
4684     clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
4685   if (clone_info->stroke_pattern != (Image *) NULL)
4686     clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
4687       MagickTrue,exception);
4688   clone_info->stroke.alpha=(Quantum) TransparentAlpha;
4689   clone_info->stroke_width=0.0;
4690   clone_info->fill_rule=NonZeroRule;
4691   status=MagickTrue;
4692   for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
4693   {
4694     stroke_polygon=TraceStrokePolygon(draw_info,p);
4695     status=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
4696     stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
4697     q=p+p->coordinates-1;
4698     closed_path=(q->point.x == p->point.x) && (q->point.y == p->point.y) ?
4699       MagickTrue : MagickFalse;
4700     if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
4701       {
4702         DrawRoundLinecap(image,draw_info,p,exception);
4703         DrawRoundLinecap(image,draw_info,q,exception);
4704       }
4705   }
4706   clone_info=DestroyDrawInfo(clone_info);
4707   if (image->debug != MagickFalse)
4708     (void) LogMagickEvent(DrawEvent,GetMagickModule(),
4709       "    end draw-stroke-polygon");
4710   return(status);
4711 }
4712 \f
4713 /*
4714 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4715 %                                                                             %
4716 %                                                                             %
4717 %                                                                             %
4718 %   G e t A f f i n e M a t r i x                                             %
4719 %                                                                             %
4720 %                                                                             %
4721 %                                                                             %
4722 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4723 %
4724 %  GetAffineMatrix() returns an AffineMatrix initialized to the identity
4725 %  matrix.
4726 %
4727 %  The format of the GetAffineMatrix method is:
4728 %
4729 %      void GetAffineMatrix(AffineMatrix *affine_matrix)
4730 %
4731 %  A description of each parameter follows:
4732 %
4733 %    o affine_matrix: the affine matrix.
4734 %
4735 */
4736 MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
4737 {
4738   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
4739   assert(affine_matrix != (AffineMatrix *) NULL);
4740   (void) ResetMagickMemory(affine_matrix,0,sizeof(*affine_matrix));
4741   affine_matrix->sx=1.0;
4742   affine_matrix->sy=1.0;
4743 }
4744 \f
4745 /*
4746 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4747 %                                                                             %
4748 %                                                                             %
4749 %                                                                             %
4750 +   G e t D r a w I n f o                                                     %
4751 %                                                                             %
4752 %                                                                             %
4753 %                                                                             %
4754 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4755 %
4756 %  GetDrawInfo() initializes draw_info to default values from image_info.
4757 %
4758 %  The format of the GetDrawInfo method is:
4759 %
4760 %      void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
4761 %
4762 %  A description of each parameter follows:
4763 %
4764 %    o image_info: the image info..
4765 %
4766 %    o draw_info: the draw info.
4767 %
4768 */
4769 MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
4770 {
4771   const char
4772     *option;
4773
4774   ExceptionInfo
4775     *exception;
4776
4777   /*
4778     Initialize draw attributes.
4779   */
4780   (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
4781   assert(draw_info != (DrawInfo *) NULL);
4782   (void) ResetMagickMemory(draw_info,0,sizeof(*draw_info));
4783   GetAffineMatrix(&draw_info->affine);
4784   exception=AcquireExceptionInfo();
4785   (void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
4786     exception);
4787   (void) QueryColorCompliance("#FFF0",AllCompliance,&draw_info->stroke,
4788     exception);
4789   draw_info->stroke_width=1.0;
4790   draw_info->alpha=OpaqueAlpha;
4791   draw_info->fill_rule=EvenOddRule;
4792   draw_info->linecap=ButtCap;
4793   draw_info->linejoin=MiterJoin;
4794   draw_info->miterlimit=10;
4795   draw_info->decorate=NoDecoration;
4796   draw_info->pointsize=12.0;
4797   draw_info->undercolor.alpha=(Quantum) TransparentAlpha;
4798   draw_info->compose=OverCompositeOp;
4799   draw_info->render=MagickTrue;
4800   draw_info->debug=IsEventLogging();
4801   if (image_info != (ImageInfo *) NULL)
4802     {
4803       draw_info->stroke_antialias=image_info->antialias;
4804       if (image_info->font != (char *) NULL)
4805         draw_info->font=AcquireString(image_info->font);
4806       if (image_info->density != (char *) NULL)
4807         draw_info->density=AcquireString(image_info->density);
4808       draw_info->text_antialias=image_info->antialias;
4809       if (image_info->pointsize != 0.0)
4810         draw_info->pointsize=image_info->pointsize;
4811       draw_info->border_color=image_info->border_color;
4812       if (image_info->server_name != (char *) NULL)
4813         draw_info->server_name=AcquireString(image_info->server_name);
4814       option=GetImageOption(image_info,"encoding");
4815       if (option != (const char *) NULL)
4816         (void) CloneString(&draw_info->encoding,option);
4817       option=GetImageOption(image_info,"kerning");
4818       if (option != (const char *) NULL)
4819         draw_info->kerning=StringToDouble(option,(char **) NULL);
4820       option=GetImageOption(image_info,"interline-spacing");
4821       if (option != (const char *) NULL)
4822         draw_info->interline_spacing=StringToDouble(option,(char **) NULL);
4823       option=GetImageOption(image_info,"interword-spacing");
4824       if (option != (const char *) NULL)
4825         draw_info->interword_spacing=StringToDouble(option,(char **) NULL);
4826       option=GetImageOption(image_info,"direction");
4827       if (option != (const char *) NULL)
4828         draw_info->direction=(DirectionType) ParseCommandOption(
4829           MagickDirectionOptions,MagickFalse,option);
4830       else
4831         draw_info->direction=UndefinedDirection;
4832       option=GetImageOption(image_info,"fill");
4833       if (option != (const char *) NULL)
4834         (void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
4835           exception);
4836       option=GetImageOption(image_info,"stroke");
4837       if (option != (const char *) NULL)
4838         (void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
4839           exception);
4840       option=GetImageOption(image_info,"strokewidth");
4841       if (option != (const char *) NULL)
4842         draw_info->stroke_width=StringToDouble(option,(char **) NULL);
4843       option=GetImageOption(image_info,"undercolor");
4844       if (option != (const char *) NULL)
4845         (void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
4846           exception);
4847       option=GetImageOption(image_info,"gravity");
4848       if (option != (const char *) NULL)
4849         draw_info->gravity=(GravityType) ParseCommandOption(
4850           MagickGravityOptions,MagickFalse,option);
4851     }
4852   exception=DestroyExceptionInfo(exception);
4853   draw_info->signature=MagickSignature;
4854 }
4855 \f
4856 /*
4857 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4858 %                                                                             %
4859 %                                                                             %
4860 %                                                                             %
4861 +   P e r m u t a t e                                                         %
4862 %                                                                             %
4863 %                                                                             %
4864 %                                                                             %
4865 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4866 %
4867 %  Permutate() returns the permuation of the (n,k).
4868 %
4869 %  The format of the Permutate method is:
4870 %
4871 %      void Permutate(ssize_t n,ssize_t k)
4872 %
4873 %  A description of each parameter follows:
4874 %
4875 %    o n:
4876 %
4877 %    o k:
4878 %
4879 %
4880 */
4881 static inline double Permutate(const ssize_t n,const ssize_t k)
4882 {
4883   double
4884     r;
4885
4886   register ssize_t
4887     i;
4888
4889   r=1.0;
4890   for (i=k+1; i <= n; i++)
4891     r*=i;
4892   for (i=1; i <= (n-k); i++)
4893     r/=i;
4894   return(r);
4895 }
4896 \f
4897 /*
4898 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4899 %                                                                             %
4900 %                                                                             %
4901 %                                                                             %
4902 +   T r a c e P r i m i t i v e                                               %
4903 %                                                                             %
4904 %                                                                             %
4905 %                                                                             %
4906 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4907 %
4908 %  TracePrimitive is a collection of methods for generating graphic
4909 %  primitives such as arcs, ellipses, paths, etc.
4910 %
4911 */
4912
4913 static void TraceArc(PrimitiveInfo *primitive_info,const PointInfo start,
4914   const PointInfo end,const PointInfo degrees)
4915 {
4916   PointInfo
4917     center,
4918     radii;
4919
4920   center.x=0.5*(end.x+start.x);
4921   center.y=0.5*(end.y+start.y);
4922   radii.x=fabs(center.x-start.x);
4923   radii.y=fabs(center.y-start.y);
4924   TraceEllipse(primitive_info,center,radii,degrees);
4925 }
4926
4927 static void TraceArcPath(PrimitiveInfo *primitive_info,const PointInfo start,
4928   const PointInfo end,const PointInfo arc,const double angle,
4929   const MagickBooleanType large_arc,const MagickBooleanType sweep)
4930 {
4931   double
4932     alpha,
4933     beta,
4934     delta,
4935     factor,
4936     gamma,
4937     theta;
4938
4939   PointInfo
4940     center,
4941     points[3],
4942     radii;
4943
4944   register double
4945     cosine,
4946     sine;
4947
4948   register PrimitiveInfo
4949     *p;
4950
4951   register ssize_t
4952     i;
4953
4954   size_t
4955     arc_segments;
4956
4957   if ((start.x == end.x) && (start.y == end.y))
4958     {
4959       TracePoint(primitive_info,end);
4960       return;
4961     }
4962   radii.x=fabs(arc.x);
4963   radii.y=fabs(arc.y);
4964   if ((radii.x == 0.0) || (radii.y == 0.0))
4965     {
4966       TraceLine(primitive_info,start,end);
4967       return;
4968     }
4969   cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
4970   sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
4971   center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
4972   center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
4973   delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
4974     (radii.y*radii.y);
4975   if (delta < MagickEpsilon)
4976     {
4977       TraceLine(primitive_info,start,end);
4978       return;
4979     }
4980   if (delta > 1.0)
4981     {
4982       radii.x*=sqrt((double) delta);
4983       radii.y*=sqrt((double) delta);
4984     }
4985   points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
4986   points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
4987   points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
4988   points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
4989   alpha=points[1].x-points[0].x;
4990   beta=points[1].y-points[0].y;
4991   factor=MagickEpsilonReciprocal(alpha*alpha+beta*beta)-0.25;
4992   if (factor <= 0.0)
4993     factor=0.0;
4994   else
4995     {
4996       factor=sqrt((double) factor);
4997       if (sweep == large_arc)
4998         factor=(-factor);
4999     }
5000   center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
5001   center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
5002   alpha=atan2(points[0].y-center.y,points[0].x-center.x);
5003   theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
5004   if ((theta < 0.0) && (sweep != MagickFalse))
5005     theta+=(double) (2.0*MagickPI);
5006   else
5007     if ((theta > 0.0) && (sweep == MagickFalse))
5008       theta-=(double) (2.0*MagickPI);
5009   arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
5010     MagickEpsilon))));
5011   p=primitive_info;
5012   for (i=0; i < (ssize_t) arc_segments; i++)
5013   {
5014     beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
5015     gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
5016       sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
5017       sin(fmod((double) beta,DegreesToRadians(360.0)));
5018     points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
5019       arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
5020       (double) i*theta/arc_segments),DegreesToRadians(360.0))));
5021     points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
5022       arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
5023       (double) i*theta/arc_segments),DegreesToRadians(360.0))));
5024     points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
5025       theta/arc_segments),DegreesToRadians(360.0))));
5026     points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
5027       theta/arc_segments),DegreesToRadians(360.0))));
5028     points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
5029       (i+1)*theta/arc_segments),DegreesToRadians(360.0))));
5030     points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
5031       (i+1)*theta/arc_segments),DegreesToRadians(360.0))));
5032     p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
5033     p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
5034     (p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
5035       points[0].y);
5036     (p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
5037       points[0].y);
5038     (p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
5039       points[1].y);
5040     (p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
5041       points[1].y);
5042     (p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
5043       points[2].y);
5044     (p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
5045       points[2].y);
5046     if (i == (ssize_t) (arc_segments-1))
5047       (p+3)->point=end;
5048     TraceBezier(p,4);
5049     p+=p->coordinates;
5050   }
5051   primitive_info->coordinates=(size_t) (p-primitive_info);
5052   for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
5053   {
5054     p->primitive=primitive_info->primitive;
5055     p--;
5056   }
5057 }
5058
5059 static void TraceBezier(PrimitiveInfo *primitive_info,
5060   const size_t number_coordinates)
5061 {
5062   double
5063     alpha,
5064     *coefficients,
5065     weight;
5066
5067   PointInfo
5068     end,
5069     point,
5070     *points;
5071
5072   register PrimitiveInfo
5073     *p;
5074
5075   register ssize_t
5076     i,
5077     j;
5078
5079   size_t
5080     control_points,
5081     quantum;
5082
5083   /*
5084     Allocate coeficients.
5085   */
5086   quantum=number_coordinates;
5087   for (i=0; i < (ssize_t) number_coordinates; i++)
5088   {
5089     for (j=i+1; j < (ssize_t) number_coordinates; j++)
5090     {
5091       alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
5092       if (alpha > (double) quantum)
5093         quantum=(size_t) alpha;
5094       alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
5095       if (alpha > (double) quantum)
5096         quantum=(size_t) alpha;
5097     }
5098   }
5099   quantum=(size_t) MagickMin((double) quantum/number_coordinates,
5100     (double) BezierQuantum);
5101   control_points=quantum*number_coordinates;
5102   coefficients=(double *) AcquireQuantumMemory((size_t)
5103     number_coordinates,sizeof(*coefficients));
5104   points=(PointInfo *) AcquireQuantumMemory((size_t) control_points,
5105     sizeof(*points));
5106   if ((coefficients == (double *) NULL) ||
5107       (points == (PointInfo *) NULL))
5108     ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
5109   /*
5110     Compute bezier points.
5111   */
5112   end=primitive_info[number_coordinates-1].point;
5113   for (i=0; i < (ssize_t) number_coordinates; i++)
5114     coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
5115   weight=0.0;
5116   for (i=0; i < (ssize_t) control_points; i++)
5117   {
5118     p=primitive_info;
5119     point.x=0.0;
5120     point.y=0.0;
5121     alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
5122     for (j=0; j < (ssize_t) number_coordinates; j++)
5123     {
5124       point.x+=alpha*coefficients[j]*p->point.x;
5125       point.y+=alpha*coefficients[j]*p->point.y;
5126       alpha*=weight/(1.0-weight);
5127       p++;
5128     }
5129     points[i]=point;
5130     weight+=1.0/control_points;
5131   }
5132   /*
5133     Bezier curves are just short segmented polys.
5134   */
5135   p=primitive_info;
5136   for (i=0; i < (ssize_t) control_points; i++)
5137   {
5138     TracePoint(p,points[i]);
5139     p+=p->coordinates;
5140   }
5141   TracePoint(p,end);
5142   p+=p->coordinates;
5143   primitive_info->coordinates=(size_t) (p-primitive_info);
5144   for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
5145   {
5146     p->primitive=primitive_info->primitive;
5147     p--;
5148   }
5149   points=(PointInfo *) RelinquishMagickMemory(points);
5150   coefficients=(double *) RelinquishMagickMemory(coefficients);
5151 }
5152
5153 static void TraceCircle(PrimitiveInfo *primitive_info,const PointInfo start,
5154   const PointInfo end)
5155 {
5156   double
5157     alpha,
5158     beta,
5159     radius;
5160
5161   PointInfo
5162     offset,
5163     degrees;
5164
5165   alpha=end.x-start.x;
5166   beta=end.y-start.y;
5167   radius=hypot((double) alpha,(double) beta);
5168   offset.x=(double) radius;
5169   offset.y=(double) radius;
5170   degrees.x=0.0;
5171   degrees.y=360.0;
5172   TraceEllipse(primitive_info,start,offset,degrees);
5173 }
5174
5175 static void TraceEllipse(PrimitiveInfo *primitive_info,const PointInfo start,
5176   const PointInfo stop,const PointInfo degrees)
5177 {
5178   double
5179     delta,
5180     step,
5181     y;
5182
5183   PointInfo
5184     angle,
5185     point;
5186
5187   register PrimitiveInfo
5188     *p;
5189
5190   register ssize_t
5191     i;
5192
5193   /*
5194     Ellipses are just short segmented polys.
5195   */
5196   if ((stop.x == 0.0) && (stop.y == 0.0))
5197     {
5198       TracePoint(primitive_info,start);
5199       return;
5200     }
5201   delta=2.0/MagickMax(stop.x,stop.y);
5202   step=(double) (MagickPI/8.0);
5203   if ((delta >= 0.0) && (delta < (double) (MagickPI/8.0)))
5204     step=(double) (MagickPI/(4*(MagickPI/delta/2+0.5)));
5205   angle.x=DegreesToRadians(degrees.x);
5206   y=degrees.y;
5207   while (y < degrees.x)
5208     y+=360.0;
5209   angle.y=(double) (DegreesToRadians(y)-MagickEpsilon);
5210   for (p=primitive_info; angle.x < angle.y; angle.x+=step)
5211   {
5212     point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*stop.x+start.x;
5213     point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*stop.y+start.y;
5214     TracePoint(p,point);
5215     p+=p->coordinates;
5216   }
5217   point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*stop.x+start.x;
5218   point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*stop.y+start.y;
5219   TracePoint(p,point);
5220   p+=p->coordinates;
5221   primitive_info->coordinates=(size_t) (p-primitive_info);
5222   for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
5223   {
5224     p->primitive=primitive_info->primitive;
5225     p--;
5226   }
5227 }
5228
5229 static void TraceLine(PrimitiveInfo *primitive_info,const PointInfo start,
5230   const PointInfo end)
5231 {
5232   TracePoint(primitive_info,start);
5233   if ((fabs(start.x-end.x) < MagickEpsilon) &&
5234       (fabs(start.y-end.y) < MagickEpsilon))
5235     {
5236       primitive_info->primitive=PointPrimitive;
5237       primitive_info->coordinates=1;
5238       return;
5239     }
5240   TracePoint(primitive_info+1,end);
5241   (primitive_info+1)->primitive=primitive_info->primitive;
5242   primitive_info->coordinates=2;
5243 }
5244
5245 static size_t TracePath(PrimitiveInfo *primitive_info,const char *path)
5246 {
5247   char
5248     token[MaxTextExtent];
5249
5250   const char
5251     *p;
5252
5253   int
5254     attribute,
5255     last_attribute;
5256
5257   double
5258     x,
5259     y;
5260
5261   PointInfo
5262     end,
5263     points[4],
5264     point,
5265     start;
5266
5267   PrimitiveType
5268     primitive_type;
5269
5270   register PrimitiveInfo
5271     *q;
5272
5273   register ssize_t
5274     i;
5275
5276   size_t
5277     number_coordinates,
5278     z_count;
5279
5280   attribute=0;
5281   point.x=0.0;
5282   point.y=0.0;
5283   start.x=0.0;
5284   start.y=0.0;
5285   number_coordinates=0;
5286   z_count=0;
5287   primitive_type=primitive_info->primitive;
5288   q=primitive_info;
5289   for (p=path; *p != '\0'; )
5290   {
5291     while (isspace((int) ((unsigned char) *p)) != 0)
5292       p++;
5293     if (*p == '\0')
5294       break;
5295     last_attribute=attribute;
5296     attribute=(int) (*p++);
5297     switch (attribute)
5298     {
5299       case 'a':
5300       case 'A':
5301       {
5302         MagickBooleanType
5303           large_arc,
5304           sweep;
5305
5306         double
5307           angle;
5308
5309         PointInfo
5310           arc;
5311
5312         /*
5313           Compute arc points.
5314         */
5315         do
5316         {
5317           GetMagickToken(p,&p,token);
5318           if (*token == ',')
5319             GetMagickToken(p,&p,token);
5320           arc.x=StringToDouble(token,(char **) NULL);
5321           GetMagickToken(p,&p,token);
5322           if (*token == ',')
5323             GetMagickToken(p,&p,token);
5324           arc.y=StringToDouble(token,(char **) NULL);
5325           GetMagickToken(p,&p,token);
5326           if (*token == ',')
5327             GetMagickToken(p,&p,token);
5328           angle=StringToDouble(token,(char **) NULL);
5329           GetMagickToken(p,&p,token);
5330           if (*token == ',')
5331             GetMagickToken(p,&p,token);
5332           large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
5333           GetMagickToken(p,&p,token);
5334           if (*token == ',')
5335             GetMagickToken(p,&p,token);
5336           sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
5337           GetMagickToken(p,&p,token);
5338           if (*token == ',')
5339             GetMagickToken(p,&p,token);
5340           x=StringToDouble(token,(char **) NULL);
5341           GetMagickToken(p,&p,token);
5342           if (*token == ',')
5343             GetMagickToken(p,&p,token);
5344           y=StringToDouble(token,(char **) NULL);
5345           end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
5346           end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
5347           TraceArcPath(q,point,end,arc,angle,large_arc,sweep);
5348           q+=q->coordinates;
5349           point=end;
5350           while (isspace((int) ((unsigned char) *p)) != 0)
5351             p++;
5352           if (*p == ',')
5353             p++;
5354         } while (IsPoint(p) != MagickFalse);
5355         break;
5356       }
5357       case 'c':
5358       case 'C':
5359       {
5360         /*
5361           Compute bezier points.
5362         */
5363         do
5364         {
5365           points[0]=point;
5366           for (i=1; i < 4; i++)
5367           {
5368             GetMagickToken(p,&p,token);
5369             if (*token == ',')
5370               GetMagickToken(p,&p,token);
5371             x=StringToDouble(token,(char **) NULL);
5372             GetMagickToken(p,&p,token);
5373             if (*token == ',')
5374               GetMagickToken(p,&p,token);
5375             y=StringToDouble(token,(char **) NULL);
5376             end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
5377             end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
5378             points[i]=end;
5379           }
5380           for (i=0; i < 4; i++)
5381             (q+i)->point=points[i];
5382           TraceBezier(q,4);
5383           q+=q->coordinates;
5384           point=end;
5385         } while (IsPoint(p) != MagickFalse);
5386         break;
5387       }
5388       case 'H':
5389       case 'h':
5390       {
5391         do
5392         {
5393           GetMagickToken(p,&p,token);
5394           if (*token == ',')
5395             GetMagickToken(p,&p,token);
5396           x=StringToDouble(token,(char **) NULL);
5397           point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
5398           TracePoint(q,point);
5399           q+=q->coordinates;
5400         } while (IsPoint(p) != MagickFalse);
5401         break;
5402       }
5403       case 'l':
5404       case 'L':
5405       {
5406         do
5407         {
5408           GetMagickToken(p,&p,token);
5409           if (*token == ',')
5410             GetMagickToken(p,&p,token);
5411           x=StringToDouble(token,(char **) NULL);
5412           GetMagickToken(p,&p,token);
5413           if (*token == ',')
5414             GetMagickToken(p,&p,token);
5415           y=StringToDouble(token,(char **) NULL);
5416           point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
5417           point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
5418           TracePoint(q,point);
5419           q+=q->coordinates;
5420         } while (IsPoint(p) != MagickFalse);
5421         break;
5422       }
5423       case 'M':
5424       case 'm':
5425       {
5426         if (q != primitive_info)
5427           {
5428             primitive_info->coordinates=(size_t) (q-primitive_info);
5429             number_coordinates+=primitive_info->coordinates;
5430             primitive_info=q;
5431           }
5432         i=0;
5433         do
5434         {
5435           GetMagickToken(p,&p,token);
5436           if (*token == ',')
5437             GetMagickToken(p,&p,token);
5438           x=StringToDouble(token,(char **) NULL);
5439           GetMagickToken(p,&p,token);
5440           if (*token == ',')
5441             GetMagickToken(p,&p,token);
5442           y=StringToDouble(token,(char **) NULL);
5443           point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
5444           point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
5445           if (i == 0)
5446             start=point;
5447           i++;
5448           TracePoint(q,point);
5449           q+=q->coordinates;
5450           if ((i != 0) && (attribute == (int) 'M'))
5451             {
5452               TracePoint(q,point);
5453               q+=q->coordinates;
5454             }
5455         } while (IsPoint(p) != MagickFalse);
5456         break;
5457       }
5458       case 'q':
5459       case 'Q':
5460       {
5461         /*
5462           Compute bezier points.
5463         */
5464         do
5465         {
5466           points[0]=point;
5467           for (i=1; i < 3; i++)
5468           {
5469             GetMagickToken(p,&p,token);
5470             if (*token == ',')
5471               GetMagickToken(p,&p,token);
5472             x=StringToDouble(token,(char **) NULL);
5473             GetMagickToken(p,&p,token);
5474             if (*token == ',')
5475               GetMagickToken(p,&p,token);
5476             y=StringToDouble(token,(char **) NULL);
5477             if (*p == ',')
5478               p++;
5479             end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
5480             end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
5481             points[i]=end;
5482           }
5483           for (i=0; i < 3; i++)
5484             (q+i)->point=points[i];
5485           TraceBezier(q,3);
5486           q+=q->coordinates;
5487           point=end;
5488         } while (IsPoint(p) != MagickFalse);
5489         break;
5490       }
5491       case 's':
5492       case 'S':
5493       {
5494         /*
5495           Compute bezier points.
5496         */
5497         do
5498         {
5499           points[0]=points[3];
5500           points[1].x=2.0*points[3].x-points[2].x;
5501           points[1].y=2.0*points[3].y-points[2].y;
5502           for (i=2; i < 4; i++)
5503           {
5504             GetMagickToken(p,&p,token);
5505             if (*token == ',')
5506               GetMagickToken(p,&p,token);
5507             x=StringToDouble(token,(char **) NULL);
5508             GetMagickToken(p,&p,token);
5509             if (*token == ',')
5510               GetMagickToken(p,&p,token);
5511             y=StringToDouble(token,(char **) NULL);
5512             if (*p == ',')
5513               p++;
5514             end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
5515             end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
5516             points[i]=end;
5517           }
5518           if (strchr("CcSs",last_attribute) == (char *) NULL)
5519             {
5520               points[0]=points[2];
5521               points[1]=points[3];
5522             }
5523           for (i=0; i < 4; i++)
5524             (q+i)->point=points[i];
5525           TraceBezier(q,4);
5526           q+=q->coordinates;
5527           point=end;
5528         } while (IsPoint(p) != MagickFalse);
5529         break;
5530       }
5531       case 't':
5532       case 'T':
5533       {
5534         /*
5535           Compute bezier points.
5536         */
5537         do
5538         {
5539           points[0]=points[2];
5540           points[1].x=2.0*points[2].x-points[1].x;
5541           points[1].y=2.0*points[2].y-points[1].y;
5542           for (i=2; i < 3; i++)
5543           {
5544             GetMagickToken(p,&p,token);
5545             if (*token == ',')
5546               GetMagickToken(p,&p,token);
5547             x=StringToDouble(token,(char **) NULL);
5548             GetMagickToken(p,&p,token);
5549             if (*token == ',')
5550               GetMagickToken(p,&p,token);
5551             y=StringToDouble(token,(char **) NULL);
5552             end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
5553             end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
5554             points[i]=end;
5555           }
5556           if (strchr("QqTt",last_attribute) == (char *) NULL)
5557             {
5558               points[0]=points[2];
5559               points[1]=points[3];
5560             }
5561           for (i=0; i < 3; i++)
5562             (q+i)->point=points[i];
5563           TraceBezier(q,3);
5564           q+=q->coordinates;
5565           point=end;
5566         } while (IsPoint(p) != MagickFalse);
5567         break;
5568       }
5569       case 'v':
5570       case 'V':
5571       {
5572         do
5573         {
5574           GetMagickToken(p,&p,token);
5575           if (*token == ',')
5576             GetMagickToken(p,&p,token);
5577           y=StringToDouble(token,(char **) NULL);
5578           point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
5579           TracePoint(q,point);
5580           q+=q->coordinates;
5581         } while (IsPoint(p) != MagickFalse);
5582         break;
5583       }
5584       case 'z':
5585       case 'Z':
5586       {
5587         point=start;
5588         TracePoint(q,point);
5589         q+=q->coordinates;
5590         primitive_info->coordinates=(size_t) (q-primitive_info);
5591         number_coordinates+=primitive_info->coordinates;
5592         primitive_info=q;
5593         z_count++;
5594         break;
5595       }
5596       default:
5597       {
5598         if (isalpha((int) ((unsigned char) attribute)) != 0)
5599           (void) FormatLocaleFile(stderr,"attribute not recognized: %c\n",
5600             attribute);
5601         break;
5602       }
5603     }
5604   }
5605   primitive_info->coordinates=(size_t) (q-primitive_info);
5606   number_coordinates+=primitive_info->coordinates;
5607   for (i=0; i < (ssize_t) number_coordinates; i++)
5608   {
5609     q--;
5610     q->primitive=primitive_type;
5611     if (z_count > 1)
5612       q->method=FillToBorderMethod;
5613   }
5614   q=primitive_info;
5615   return(number_coordinates);
5616 }
5617
5618 static void TraceRectangle(PrimitiveInfo *primitive_info,const PointInfo start,
5619   const PointInfo end)
5620 {
5621   PointInfo
5622     point;
5623
5624   register PrimitiveInfo
5625     *p;
5626
5627   register ssize_t
5628     i;
5629
5630   p=primitive_info;
5631   TracePoint(p,start);
5632   p+=p->coordinates;
5633   point.x=start.x;
5634   point.y=end.y;
5635   TracePoint(p,point);
5636   p+=p->coordinates;
5637   TracePoint(p,end);
5638   p+=p->coordinates;
5639   point.x=end.x;
5640   point.y=start.y;
5641   TracePoint(p,point);
5642   p+=p->coordinates;
5643   TracePoint(p,start);
5644   p+=p->coordinates;
5645   primitive_info->coordinates=(size_t) (p-primitive_info);
5646   for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
5647   {
5648     p->primitive=primitive_info->primitive;
5649     p--;
5650   }
5651 }
5652
5653 static void TraceRoundRectangle(PrimitiveInfo *primitive_info,
5654   const PointInfo start,const PointInfo end,PointInfo arc)
5655 {
5656   PointInfo
5657     degrees,
5658     offset,
5659     point;
5660
5661   register PrimitiveInfo
5662     *p;
5663
5664   register ssize_t
5665     i;
5666
5667   p=primitive_info;
5668   offset.x=fabs(end.x-start.x);
5669   offset.y=fabs(end.y-start.y);
5670   if (arc.x > (0.5*offset.x))
5671     arc.x=0.5*offset.x;
5672   if (arc.y > (0.5*offset.y))
5673     arc.y=0.5*offset.y;
5674   point.x=start.x+offset.x-arc.x;
5675   point.y=start.y+arc.y;
5676   degrees.x=270.0;
5677   degrees.y=360.0;
5678   TraceEllipse(p,point,arc,degrees);
5679   p+=p->coordinates;
5680   point.x=start.x+offset.x-arc.x;
5681   point.y=start.y+offset.y-arc.y;
5682   degrees.x=0.0;
5683   degrees.y=90.0;
5684   TraceEllipse(p,point,arc,degrees);
5685   p+=p->coordinates;
5686   point.x=start.x+arc.x;
5687   point.y=start.y+offset.y-arc.y;
5688   degrees.x=90.0;
5689   degrees.y=180.0;
5690   TraceEllipse(p,point,arc,degrees);
5691   p+=p->coordinates;
5692   point.x=start.x+arc.x;
5693   point.y=start.y+arc.y;
5694   degrees.x=180.0;
5695   degrees.y=270.0;
5696   TraceEllipse(p,point,arc,degrees);
5697   p+=p->coordinates;
5698   TracePoint(p,primitive_info->point);
5699   p+=p->coordinates;
5700   primitive_info->coordinates=(size_t) (p-primitive_info);
5701   for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
5702   {
5703     p->primitive=primitive_info->primitive;
5704     p--;
5705   }
5706 }
5707
5708 static void TraceSquareLinecap(PrimitiveInfo *primitive_info,
5709   const size_t number_vertices,const double offset)
5710 {
5711   double
5712     distance;
5713
5714   register double
5715     dx,
5716     dy;
5717
5718   register ssize_t
5719     i;
5720
5721   ssize_t
5722     j;
5723
5724   dx=0.0;
5725   dy=0.0;
5726   for (i=1; i < (ssize_t) number_vertices; i++)
5727   {
5728     dx=primitive_info[0].point.x-primitive_info[i].point.x;
5729     dy=primitive_info[0].point.y-primitive_info[i].point.y;
5730     if ((fabs((double) dx) >= MagickEpsilon) ||
5731         (fabs((double) dy) >= MagickEpsilon))
5732       break;
5733   }
5734   if (i == (ssize_t) number_vertices)
5735     i=(ssize_t) number_vertices-1L;
5736   distance=hypot((double) dx,(double) dy);
5737   primitive_info[0].point.x=(double) (primitive_info[i].point.x+
5738     dx*(distance+offset)/distance);
5739   primitive_info[0].point.y=(double) (primitive_info[i].point.y+
5740     dy*(distance+offset)/distance);
5741   for (j=(ssize_t) number_vertices-2; j >= 0;  j--)
5742   {
5743     dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
5744     dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
5745     if ((fabs((double) dx) >= MagickEpsilon) ||
5746         (fabs((double) dy) >= MagickEpsilon))
5747       break;
5748   }
5749   distance=hypot((double) dx,(double) dy);
5750   primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
5751     dx*(distance+offset)/distance);
5752   primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
5753     dy*(distance+offset)/distance);
5754 }
5755
5756 static inline double DrawEpsilonReciprocal(const double x)
5757 {
5758 #define DrawEpsilon  ((double) 1.0e-10)
5759
5760   double sign = x < (double) 0.0 ? (double) -1.0 :
5761     (double) 1.0;
5762   return((sign*x) >= DrawEpsilon ? (double) 1.0/x : sign*(
5763     (double) 1.0/DrawEpsilon));
5764 }
5765
5766 static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info,
5767   const PrimitiveInfo *primitive_info)
5768 {
5769   typedef struct _LineSegment
5770   {
5771     double
5772       p,
5773       q;
5774   } LineSegment;
5775
5776   LineSegment
5777     dx,
5778     dy,
5779     inverse_slope,
5780     slope,
5781     theta;
5782
5783   MagickBooleanType
5784     closed_path;
5785
5786   double
5787     delta_theta,
5788     dot_product,
5789     mid,
5790     miterlimit;
5791
5792   PointInfo
5793     box_p[5],
5794     box_q[5],
5795     center,
5796     offset,
5797     *path_p,
5798     *path_q;
5799
5800   PrimitiveInfo
5801     *polygon_primitive,
5802     *stroke_polygon;
5803
5804   register ssize_t
5805     i;
5806
5807   size_t
5808     arc_segments,
5809     max_strokes,
5810     number_vertices;
5811
5812   ssize_t
5813     j,
5814     n,
5815     p,
5816     q;
5817
5818   /*
5819     Allocate paths.
5820   */
5821   number_vertices=primitive_info->coordinates;
5822   max_strokes=2*number_vertices+6*BezierQuantum+360;
5823   path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
5824     sizeof(*path_p));
5825   path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
5826     sizeof(*path_q));
5827   polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
5828     number_vertices+2UL,sizeof(*polygon_primitive));
5829   if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL) ||
5830       (polygon_primitive == (PrimitiveInfo *) NULL))
5831     return((PrimitiveInfo *) NULL);
5832   (void) CopyMagickMemory(polygon_primitive,primitive_info,(size_t)
5833     number_vertices*sizeof(*polygon_primitive));
5834   closed_path=
5835     (primitive_info[number_vertices-1].point.x == primitive_info[0].point.x) &&
5836     (primitive_info[number_vertices-1].point.y == primitive_info[0].point.y) ?
5837     MagickTrue : MagickFalse;
5838   if ((draw_info->linejoin == RoundJoin) ||
5839       ((draw_info->linejoin == MiterJoin) && (closed_path != MagickFalse)))
5840     {
5841       polygon_primitive[number_vertices]=primitive_info[1];
5842       number_vertices++;
5843     }
5844   polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
5845   /*
5846     Compute the slope for the first line segment, p.
5847   */
5848   dx.p=0.0;
5849   dy.p=0.0;
5850   for (n=1; n < (ssize_t) number_vertices; n++)
5851   {
5852     dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
5853     dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
5854     if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))
5855       break;
5856   }
5857   if (n == (ssize_t) number_vertices)
5858     n=(ssize_t) number_vertices-1L;
5859   slope.p=DrawEpsilonReciprocal(dx.p)*dy.p;
5860   inverse_slope.p=(-1.0*DrawEpsilonReciprocal(slope.p));
5861   mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0;
5862   miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*
5863     mid*mid);
5864   if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
5865     TraceSquareLinecap(polygon_primitive,number_vertices,mid);
5866   offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
5867   offset.y=(double) (offset.x*inverse_slope.p);
5868   if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
5869     {
5870       box_p[0].x=polygon_primitive[0].point.x-offset.x;
5871       box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
5872       box_p[1].x=polygon_primitive[n].point.x-offset.x;
5873       box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
5874       box_q[0].x=polygon_primitive[0].point.x+offset.x;
5875       box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
5876       box_q[1].x=polygon_primitive[n].point.x+offset.x;
5877       box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
5878     }
5879   else
5880     {
5881       box_p[0].x=polygon_primitive[0].point.x+offset.x;
5882       box_p[0].y=polygon_primitive[0].point.y+offset.y;
5883       box_p[1].x=polygon_primitive[n].point.x+offset.x;
5884       box_p[1].y=polygon_primitive[n].point.y+offset.y;
5885       box_q[0].x=polygon_primitive[0].point.x-offset.x;
5886       box_q[0].y=polygon_primitive[0].point.y-offset.y;
5887       box_q[1].x=polygon_primitive[n].point.x-offset.x;
5888       box_q[1].y=polygon_primitive[n].point.y-offset.y;
5889     }
5890   /*
5891     Create strokes for the line join attribute: bevel, miter, round.
5892   */
5893   p=0;
5894   q=0;
5895   path_q[p++]=box_q[0];
5896   path_p[q++]=box_p[0];
5897   for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
5898   {
5899     /*
5900       Compute the slope for this line segment, q.
5901     */
5902     dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
5903     dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
5904     dot_product=dx.q*dx.q+dy.q*dy.q;
5905     if (dot_product < 0.25)
5906       continue;
5907     slope.q=DrawEpsilonReciprocal(dx.q)*dy.q;
5908     inverse_slope.q=(-1.0*DrawEpsilonReciprocal(slope.q));
5909     offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
5910     offset.y=(double) (offset.x*inverse_slope.q);
5911     dot_product=dy.q*offset.x-dx.q*offset.y;
5912     if (dot_product > 0.0)
5913       {
5914         box_p[2].x=polygon_primitive[n].point.x-offset.x;
5915         box_p[2].y=polygon_primitive[n].point.y-offset.y;
5916         box_p[3].x=polygon_primitive[i].point.x-offset.x;
5917         box_p[3].y=polygon_primitive[i].point.y-offset.y;
5918         box_q[2].x=polygon_primitive[n].point.x+offset.x;
5919         box_q[2].y=polygon_primitive[n].point.y+offset.y;
5920         box_q[3].x=polygon_primitive[i].point.x+offset.x;
5921         box_q[3].y=polygon_primitive[i].point.y+offset.y;
5922       }
5923     else
5924       {
5925         box_p[2].x=polygon_primitive[n].point.x+offset.x;
5926         box_p[2].y=polygon_primitive[n].point.y+offset.y;
5927         box_p[3].x=polygon_primitive[i].point.x+offset.x;
5928         box_p[3].y=polygon_primitive[i].point.y+offset.y;
5929         box_q[2].x=polygon_primitive[n].point.x-offset.x;
5930         box_q[2].y=polygon_primitive[n].point.y-offset.y;
5931         box_q[3].x=polygon_primitive[i].point.x-offset.x;
5932         box_q[3].y=polygon_primitive[i].point.y-offset.y;
5933       }
5934     if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)
5935       {
5936         box_p[4]=box_p[1];
5937         box_q[4]=box_q[1];
5938       }
5939     else
5940       {
5941         box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
5942           box_p[3].y)/(slope.p-slope.q));
5943         box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
5944         box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
5945           box_q[3].y)/(slope.p-slope.q));
5946         box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
5947       }
5948     if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360))
5949       {
5950          max_strokes+=6*BezierQuantum+360;
5951          path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes,
5952            sizeof(*path_p));
5953          path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes,
5954            sizeof(*path_q));
5955          if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL))
5956            {
5957              polygon_primitive=(PrimitiveInfo *)
5958                RelinquishMagickMemory(polygon_primitive);
5959              return((PrimitiveInfo *) NULL);
5960            }
5961       }
5962     dot_product=dx.q*dy.p-dx.p*dy.q;
5963     if (dot_product <= 0.0)
5964       switch (draw_info->linejoin)
5965       {
5966         case BevelJoin:
5967         {
5968           path_q[q++]=box_q[1];
5969           path_q[q++]=box_q[2];
5970           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
5971             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
5972           if (dot_product <= miterlimit)
5973             path_p[p++]=box_p[4];
5974           else
5975             {
5976               path_p[p++]=box_p[1];
5977               path_p[p++]=box_p[2];
5978             }
5979           break;
5980         }
5981         case MiterJoin:
5982         {
5983           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
5984             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
5985           if (dot_product <= miterlimit)
5986             {
5987               path_q[q++]=box_q[4];
5988               path_p[p++]=box_p[4];
5989             }
5990           else
5991             {
5992               path_q[q++]=box_q[1];
5993               path_q[q++]=box_q[2];
5994               path_p[p++]=box_p[1];
5995               path_p[p++]=box_p[2];
5996             }
5997           break;
5998         }
5999         case RoundJoin:
6000         {
6001           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
6002             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
6003           if (dot_product <= miterlimit)
6004             path_p[p++]=box_p[4];
6005           else
6006             {
6007               path_p[p++]=box_p[1];
6008               path_p[p++]=box_p[2];
6009             }
6010           center=polygon_primitive[n].point;
6011           theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
6012           theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
6013           if (theta.q < theta.p)
6014             theta.q+=(double) (2.0*MagickPI);
6015           arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
6016             (2.0*sqrt((double) (1.0/mid)))));
6017           path_q[q].x=box_q[1].x;
6018           path_q[q].y=box_q[1].y;
6019           q++;
6020           for (j=1; j < (ssize_t) arc_segments; j++)
6021           {
6022             delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
6023             path_q[q].x=(double) (center.x+mid*cos(fmod((double)
6024               (theta.p+delta_theta),DegreesToRadians(360.0))));
6025             path_q[q].y=(double) (center.y+mid*sin(fmod((double)
6026               (theta.p+delta_theta),DegreesToRadians(360.0))));
6027             q++;
6028           }
6029           path_q[q++]=box_q[2];
6030           break;
6031         }
6032         default:
6033           break;
6034       }
6035     else
6036       switch (draw_info->linejoin)
6037       {
6038         case BevelJoin:
6039         {
6040           path_p[p++]=box_p[1];
6041           path_p[p++]=box_p[2];
6042           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
6043             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
6044           if (dot_product <= miterlimit)
6045             path_q[q++]=box_q[4];
6046           else
6047             {
6048               path_q[q++]=box_q[1];
6049               path_q[q++]=box_q[2];
6050             }
6051           break;
6052         }
6053         case MiterJoin:
6054         {
6055           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
6056             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
6057           if (dot_product <= miterlimit)
6058             {
6059               path_q[q++]=box_q[4];
6060               path_p[p++]=box_p[4];
6061             }
6062           else
6063             {
6064               path_q[q++]=box_q[1];
6065               path_q[q++]=box_q[2];
6066               path_p[p++]=box_p[1];
6067               path_p[p++]=box_p[2];
6068             }
6069           break;
6070         }
6071         case RoundJoin:
6072         {
6073           dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
6074             (box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
6075           if (dot_product <= miterlimit)
6076             path_q[q++]=box_q[4];
6077           else
6078             {
6079               path_q[q++]=box_q[1];
6080               path_q[q++]=box_q[2];
6081             }
6082           center=polygon_primitive[n].point;
6083           theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
6084           theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
6085           if (theta.p < theta.q)
6086             theta.p+=(double) (2.0*MagickPI);
6087           arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
6088             (2.0*sqrt((double) (1.0/mid)))));
6089           path_p[p++]=box_p[1];
6090           for (j=1; j < (ssize_t) arc_segments; j++)
6091           {
6092             delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
6093             path_p[p].x=(double) (center.x+mid*cos(fmod((double)
6094               (theta.p+delta_theta),DegreesToRadians(360.0))));
6095             path_p[p].y=(double) (center.y+mid*sin(fmod((double)
6096               (theta.p+delta_theta),DegreesToRadians(360.0))));
6097             p++;
6098           }
6099           path_p[p++]=box_p[2];
6100           break;
6101         }
6102         default:
6103           break;
6104       }
6105     slope.p=slope.q;
6106     inverse_slope.p=inverse_slope.q;
6107     box_p[0]=box_p[2];
6108     box_p[1]=box_p[3];
6109     box_q[0]=box_q[2];
6110     box_q[1]=box_q[3];
6111     dx.p=dx.q;
6112     dy.p=dy.q;
6113     n=i;
6114   }
6115   path_p[p++]=box_p[1];
6116   path_q[q++]=box_q[1];
6117   /*
6118     Trace stroked polygon.
6119   */
6120   stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
6121     (p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
6122   if (stroke_polygon != (PrimitiveInfo *) NULL)
6123     {
6124       for (i=0; i < (ssize_t) p; i++)
6125       {
6126         stroke_polygon[i]=polygon_primitive[0];
6127         stroke_polygon[i].point=path_p[i];
6128       }
6129       if (closed_path != MagickFalse)
6130         {
6131           stroke_polygon[i]=polygon_primitive[0];
6132           stroke_polygon[i].point=stroke_polygon[0].point;
6133           i++;
6134         }
6135       for ( ; i < (ssize_t) (p+q+closed_path); i++)
6136       {
6137         stroke_polygon[i]=polygon_primitive[0];
6138         stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
6139       }
6140       if (closed_path != MagickFalse)
6141         {
6142           stroke_polygon[i]=polygon_primitive[0];
6143           stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
6144           i++;
6145         }
6146       stroke_polygon[i]=polygon_primitive[0];
6147       stroke_polygon[i].point=stroke_polygon[0].point;
6148       i++;
6149       stroke_polygon[i].primitive=UndefinedPrimitive;
6150       stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
6151     }
6152   path_p=(PointInfo *) RelinquishMagickMemory(path_p);
6153   path_q=(PointInfo *) RelinquishMagickMemory(path_q);
6154   polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
6155   return(stroke_polygon);
6156 }