more bugfixes in stroke code
[swftools.git] / lib / gfxtools.c
1 /* gfxtools.c
2
3    Various utility functions for dealing with gfxdevices.
4
5    Part of the swftools package.
6
7    Copyright (c) 2005 Matthias Kramm <kramm@quiss.org>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <memory.h>
26 #include <math.h>
27 #include <string.h>
28 #include <assert.h>
29 #include "gfxtools.h"
30 #include "gfxfont.h"
31
32 typedef struct _linedraw_internal
33 {
34     gfxline_t*start;
35     gfxline_t*next;
36     gfxcoord_t x0,y0;
37 } linedraw_internal_t;
38
39 static void linedraw_moveTo(gfxdrawer_t*d, gfxcoord_t x, gfxcoord_t y)
40 {
41     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
42     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
43     l->type = gfx_moveTo;
44     if((int)((d->x * 5120) == (int)(x * 5120)) &&
45        (int)((d->y * 5120) == (int)(y * 5120))) {
46         /* never mind- we're already there */
47         return;
48
49     }
50     i->x0 = x;
51     i->y0 = y;
52     l->sx = l->sy = 0;
53     d->x = l->x = x;
54     d->y = l->y = y;
55     l->next = 0;
56     if(i->next)
57         i->next->next = l;
58     i->next = l;
59     if(!i->start)
60         i->start = l;
61 }
62 static void linedraw_lineTo(gfxdrawer_t*d, gfxcoord_t x, gfxcoord_t y)
63 {
64     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
65     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
66
67     if(!i->start) {
68         /* starts with a line, not with a moveto. As this is the first
69            entry in the list, this is probably *meant* to be a moveto */
70         linedraw_moveTo(d, x, y);
71         return;
72     }
73
74     l->type = gfx_lineTo;
75     d->x = l->x = x;
76     d->y = l->y = y;
77
78     l->next = 0;
79     if(i->next)
80         i->next->next = l;
81     i->next = l;
82     if(!i->start)
83         i->start = l;
84 }
85 static void linedraw_splineTo(gfxdrawer_t*d, gfxcoord_t sx, gfxcoord_t sy, gfxcoord_t x, gfxcoord_t y)
86 {
87     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
88     gfxline_t*l = (gfxline_t*)rfx_alloc(sizeof(gfxline_t));
89
90     if(!i->start) {
91         fprintf(stderr, "Error: drawing startpoint is a spline\n");
92         linedraw_moveTo(d, x, y);
93         return;
94     }
95
96     l->type = gfx_splineTo;
97     d->x = l->x = x;
98     d->y = l->y = y;
99     l->sx = sx;
100     l->sy = sy;
101     l->next = 0;
102     if(i->next)
103         i->next->next = l;
104     i->next = l;
105     if(!i->start)
106         i->start = l;
107 }
108 static void* linedraw_close(gfxdrawer_t*d)
109 {
110     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
111     linedraw_lineTo(d, i->x0, i->y0);
112 }
113 static void* linedraw_result(gfxdrawer_t*d)
114 {
115     linedraw_internal_t*i = (linedraw_internal_t*)d->internal;
116     void*result = (void*)i->start;
117     rfx_free(i);
118     memset(d, 0, sizeof(gfxdrawer_t));
119     return result;
120 }
121
122 void gfxdrawer_target_gfxline(gfxdrawer_t*d)
123 {
124     linedraw_internal_t*i = (linedraw_internal_t*)rfx_calloc(sizeof(linedraw_internal_t));
125     d->x = 0x7fffffff;
126     d->y = 0x7fffffff;
127     d->internal = i;
128     d->moveTo = linedraw_moveTo;
129     d->lineTo = linedraw_lineTo;
130     d->splineTo = linedraw_splineTo;
131     d->close = linedraw_close;
132     d->result = linedraw_result;
133 }
134
135 typedef struct _qspline_abc
136 {
137     double ax,bx,cx;
138     double ay,by,cy;
139 } qspline_abc_t;
140
141 typedef struct qspline_t
142 {
143     gfxpoint_t start;
144     gfxpoint_t control;
145     gfxpoint_t end;
146 } qspline_t;
147
148 typedef struct cspline_t
149 {
150     gfxpoint_t start;
151     gfxpoint_t control1;
152     gfxpoint_t control2;
153     gfxpoint_t end;
154 } cspline_t;
155
156 static void mkspline(qspline_abc_t*s, double x, double y, gfxline_t*l)
157 {
158     /*
159        Form 1: x = t*t*l->x + 2*t*(1-t)*l->sx + (1-t)*(1-t)*x;
160        Form 2: x = a*t*t + b*t + c
161     */
162     s->cx = x; s->bx = 2*l->sx - 2*x; s->ax = l->x - 2*l->sx + x;
163     s->cy = y; s->by = 2*l->sy - 2*y; s->ay = l->y - 2*l->sy + y;
164 }
165
166 static void spline_get_controlpoint(qspline_abc_t*q, double t1, double t2, double*dx, double*dy)
167 {
168     double dt = t2-t1;
169     double nax = q->ax*dt*dt;
170     double nay = q->ay*dt*dt;
171     double nbx = 2*q->ax*dt*t1 + q->bx*dt;
172     double nby = 2*q->ay*dt*t1 + q->by*dt;
173     double ncx = q->ax*t1*t1 + q->bx*t1 + q->cx;
174     double ncy = q->ay*t1*t1 + q->by*t1 + q->cy;
175     *dx = ncx + nbx/2;
176     *dy = ncy + nby/2;
177 }
178
179 static double get_spline_len(qspline_abc_t*s)
180 {
181     int parts = (int)(sqrt(fabs(s->ax) + fabs(s->ay))*3);
182     int i;
183     double len = 0;
184     double r;
185     double r2;
186     if(parts < 3) parts = 3;
187     r = 1.0/parts;
188     r2 = 1.0/(parts*parts);
189     for(i=0;i<parts;i++)
190     {
191         double dx = s->ax*(2*i+1)*r2 + s->bx*r;
192         double dy = s->ay*(2*i+1)*r2 + s->by*r;
193         len += sqrt(dx*dx+dy*dy);
194     }
195     /*printf("Spline from %f,%f to %f,%f has len %f (%f)\n", s->cx, s->cy,
196             s->cx + s->bx + s->ax,
197             s->cy + s->by + s->ay, len,
198             sqrt((s->bx + s->ax)*(s->bx + s->ax) + (s->by + s->ay)*(s->by + s->ay))
199             );
200     assert(len+0.5 >= sqrt((s->bx + s->ax)*(s->bx + s->ax) + (s->by + s->ay)*(s->by + s->ay)));
201      */
202     return len;
203 }
204
205 void gfxtool_draw_dashed_line(gfxdrawer_t*d, gfxline_t*line, float*r, float phase)
206 {
207     double x=0,y=0;
208     double linepos,nextpos;
209     char on;
210     int apos=0;
211
212     if(line && line->type != gfx_moveTo) {
213         fprintf(stderr, "gfxtool: outline doesn't start with a moveTo");
214         return;
215     }
216     
217     int i;
218     double dashlen=0;
219     for(i=0;r[i]>=0;i++) {
220         dashlen+=r[i];
221     }
222     if(!r || (r[0]<=0 && r[0]>-0.01) || dashlen<0.001) {
223         // no dashing. just draw the thing
224         while(line) {
225             if(line->type == gfx_moveTo) {
226                 d->moveTo(d, line->x, line->y);
227             } else if(line->type == gfx_lineTo) {
228                 d->lineTo(d, line->x, line->y);
229             } else if(line->type == gfx_splineTo) {
230                 d->splineTo(d, line->sx, line->sy, line->x, line->y);
231             }
232             line = line->next;
233         }
234         return;
235     }
236     if(r[0]<0 || phase<0) {
237         fprintf(stderr, "gfxtool: invalid (negative) dashes: %f, phase=%f", r[0], phase);
238         return;
239     }
240
241     for(;line;line=line->next) {
242         if(line->type == gfx_moveTo) {
243             d->moveTo(d, line->x, line->y);
244             on = 1; nextpos = r[0]; apos = 0; linepos = 0;
245             x = line->x; y = line->y;
246             while(linepos < phase) {
247                 //printf("[+] linepos: %f, phase: %f, on:%d, apos:%d nextpos:%f\n", linepos, phase, on, apos, nextpos);
248                 linepos += r[apos];
249                 if(linepos < phase) {
250                     on ^= 1;
251                     if(r[++apos]<0)
252                         apos = 0;
253                     nextpos += r[apos];
254                 }
255             }
256             linepos = phase;
257             //printf("[k] linepos: %f, phase: %f, on:%d, apos:%d nextpos:%f \n", linepos, phase, on, apos, nextpos);
258         } else if(line->type == gfx_lineTo) {
259             double dx = line->x - x;
260             double dy = line->y - y;
261             double len = sqrt(dx*dx+dy*dy);
262             double vx;
263             double vy;
264             double lineend = linepos+len;
265             if(len==0)
266                 continue;
267             vx = dx/len;
268             vy = dy/len;
269             assert(nextpos>=linepos);
270             //printf("(line) on:%d apos: %d nextpos: %f, line pos: %f, line end: %f\n", on, apos, nextpos, linepos, linepos+len);
271             while(nextpos<lineend) {
272                 double nx = x + vx*(nextpos-linepos);
273                 double ny = y + vy*(nextpos-linepos);
274                 if(on) {d->lineTo(d, nx,ny);/*printf("lineTo %f\n", nextpos);*/}
275                 else   {d->moveTo(d, nx,ny);/*printf("moveTo %f\n", nextpos);*/}
276                 on^=1;
277                 if(r[++apos]<0)
278                     apos = 0;
279                 nextpos+=r[apos];
280             }
281             linepos = lineend;
282             if(on) {
283                 //printf("lineTo %f\n", 1.0);
284                 d->lineTo(d, line->x,line->y);
285             }
286             x = line->x; y = line->y;
287         } else if(line->type == gfx_splineTo) {
288             qspline_abc_t q;
289             double len, lineend,lastt;
290             mkspline(&q, x, y, line);
291
292             len = get_spline_len(&q);
293             //printf("%f %f -> %f %f, len: %f\n", x, y, line->x, line->y, len);
294             if(len==0)
295                 continue;
296             lineend = linepos+len;
297             lastt = 0;
298             if(nextpos<linepos)
299                 printf("%f !< %f\n", nextpos, linepos);
300             assert(nextpos>=linepos);
301             //printf("(spline) on:%d apos: %d nextpos: %f, line pos: %f, line end: %f\n", on, apos, nextpos, linepos, linepos+len);
302             while(nextpos<lineend) {
303                 double t = (nextpos-linepos)/len;
304                 //printf("%f (%f-%f) apos=%d r[apos]=%f\n", t, nextpos, linepos, apos, r[apos]);
305                 double nx = q.ax*t*t+q.bx*t+q.cx;
306                 double ny = q.ay*t*t+q.by*t+q.cy;
307                 if(on) {
308                     double sx,sy;
309                     spline_get_controlpoint(&q, lastt, t, &sx, &sy);
310                     d->splineTo(d, sx, sy, nx,ny);
311                     //printf("splineTo %f\n", nextpos);
312                 } else  {
313                     d->moveTo(d, nx,ny);
314                     //printf("moveTo %f\n", nextpos);
315                 }
316                 lastt =  t;
317                 on^=1;
318                 if(r[++apos]<0)
319                     apos = 0;
320                 nextpos+=r[apos];
321             }
322             linepos = lineend;
323             if(on) {
324                 double sx,sy;
325                 spline_get_controlpoint(&q, lastt, 1, &sx, &sy);
326                 d->splineTo(d, sx, sy, line->x,line->y);
327                 //printf("splineTo %f\n", 1.0);
328             }
329             x = line->x; y = line->y;
330         }
331     }
332 }
333
334 gfxline_t * gfxline_clone(gfxline_t*line)
335 {
336     gfxline_t*dest = 0;
337     gfxline_t*pos = 0;
338     while(line) {
339         gfxline_t*n = (gfxline_t*)rfx_calloc(sizeof(gfxline_t));
340         *n = *line;
341         n->next = 0;
342         if(!pos) {
343             dest = pos = n;
344         } else {
345             pos->next = n;
346             pos = n;
347         }
348         line = line->next;
349     }
350     return dest;
351 }
352
353 static char splineIsStraight(double x, double y, gfxline_t*l)
354 {
355     if(l->type == gfx_moveTo)
356         return 0;
357     if(l->type == gfx_lineTo)
358         return 1;
359     double dx = l->x-x;
360     double dy = l->y-y;
361     double sx = l->sx-x;
362     double sy = l->sy-y;
363     if(fabs(dx*sy - dy*sx) < 0.000001 && (dx*sx + dy*sy) >= 0) {
364         return 1;
365     }
366     return 0;
367 }
368
369 void gfxline_optimize(gfxline_t*line)
370 {
371     gfxline_t*l = line;
372     /* step 1: convert splines to lines, where possible */
373     double x=0,y=0;
374     while(l) {
375         if(l->type == gfx_splineTo && splineIsStraight(x,y,l)) {
376             l->type = gfx_lineTo;
377         }
378         x = l->x;
379         y = l->y;
380         l = l->next;
381     }
382     /* step 2: combine adjacent lines and splines, where possible */
383     l = line;
384     while(l && l->next) {
385         gfxline_t*next = l->next;
386         char combine = 0;
387         double sx=0,sy=0;
388         if(l->type == gfx_lineTo && next->type == gfx_lineTo) {
389             double dx = l->x-x;
390             double dy = l->y-y;
391             double nx = next->x-l->x;
392             double ny = next->y-l->y;
393             if(fabs(dx*ny - dy*nx) < 0.000001 && (dx*nx + dy*ny) >= 0) {
394                 combine = 1;
395             }
396         } else if(l->type == gfx_splineTo && next->type == gfx_splineTo) {
397             /* TODO */
398         }
399         if(combine) {
400             l->next = next->next;
401             next->next = 0;
402             l->x = next->x;
403             l->y = next->y;
404             l->sx = sx;
405             l->sy = sy;
406             rfx_free(next);
407         } else {
408             x = l->x;
409             y = l->y;
410             l = l->next;
411         }
412     }
413 }
414
415 gfxline_t* gfxtool_dash_line(gfxline_t*line, float*dashes, float phase)
416 {
417     gfxdrawer_t d;
418     gfxline_t*result;
419     gfxdrawer_target_gfxline(&d);
420     gfxtool_draw_dashed_line(&d, line, dashes, phase);
421     result= (gfxline_t*)d.result(&d);
422     return result;
423 }
424
425 void gfxline_show(gfxline_t*l, FILE*fi)
426 {
427     while(l) {
428         if(l->type == gfx_moveTo) {
429             fprintf(fi, "moveTo %.2f,%.2f\n", l->x, l->y);
430         }
431         if(l->type == gfx_lineTo) {
432             fprintf(fi, "lineTo %.2f,%.2f\n", l->x, l->y);
433         }
434         if(l->type == gfx_splineTo) {
435             fprintf(fi, "splineTo %.2f,%.2f %.2f,%.2f\n", l->sx, l->sy, l->x, l->y);
436         }
437         l = l->next;
438     }
439 }
440
441 void gfxline_free(gfxline_t*l)
442 {
443     if(l && (l+1) == l->next) {
444         /* flattened */
445         rfx_free(l);
446     } else {
447         gfxline_t*next;
448         while(l) {
449             next = l->next;
450             l->next = 0;
451             rfx_free(l);
452             l = next;
453         }
454     }
455 }
456
457 static inline gfxpoint_t cspline_getpoint(const struct cspline_t*s, double t)
458 {
459     gfxpoint_t p;
460     double tt = t*t;
461     double ttt = tt*t;
462     double mt = (1-t);
463     double mtmt = mt*(1-t);
464     double mtmtmt = mtmt*(1-t);
465     p.x= s->end.x*ttt + 3*s->control2.x*tt*mt
466             + 3*s->control1.x*t*mtmt + s->start.x*mtmtmt;
467     p.y= s->end.y*ttt + 3*s->control2.y*tt*mt
468             + 3*s->control1.y*t*mtmt + s->start.y*mtmtmt;
469     return p;
470 }
471 static gfxpoint_t qspline_getpoint(const qspline_t*s, double t)
472 {
473     gfxpoint_t p;
474     p.x= s->end.x*t*t + 2*s->control.x*t*(1-t) + s->start.x*(1-t)*(1-t);
475     p.y= s->end.y*t*t + 2*s->control.y*t*(1-t) + s->start.y*(1-t)*(1-t);
476     return p;
477 }
478
479 static int approximate3(const cspline_t*s, qspline_t*q, int size, double quality2)
480 {
481     unsigned int gran = 0;
482     unsigned int istep = 0x80000000;
483     unsigned int istart = 0;
484     int num = 0;
485     int level = 0;
486
487     while(istart<0x80000000)
488     {
489         unsigned int iend = istart + istep;
490         double start = istart/(double)0x80000000;
491         double end = iend/(double)0x80000000;
492         qspline_t test;
493         double pos,qpos;
494         char left = 0,recurse=0;
495         int t;
496         int probes = 15;
497         double dx,dy;
498
499         /* create simple approximation: a qspline_t which run's through the
500            qspline_t point at 0.5 */
501         test.start = cspline_getpoint(s, start);
502         test.control = cspline_getpoint(s, (start+end)/2);
503         test.end = cspline_getpoint(s, end);
504         /* fix the control point:
505            move it so that the new spline does runs through it */
506         test.control.x = -(test.end.x + test.start.x)/2 + 2*(test.control.x);
507         test.control.y = -(test.end.y + test.start.y)/2 + 2*(test.control.y);
508
509         /* depending on where we are in the spline, we either try to match
510            the left or right tangent */
511         if(start<0.5)
512             left=1;
513         /* get derivative */
514         pos = left?start:end;
515         qpos = pos*pos;
516         test.control.x = s->end.x*(3*qpos) + 3*s->control2.x*(2*pos-3*qpos) +
517                     3*s->control1.x*(1-4*pos+3*qpos) + s->start.x*(-3+6*pos-3*qpos);
518         test.control.y = s->end.y*(3*qpos) + 3*s->control2.y*(2*pos-3*qpos) +
519                     3*s->control1.y*(1-4*pos+3*qpos) + s->start.y*(-3+6*pos-3*qpos);
520         if(left) {
521             test.control.x *= (end-start)/2;
522             test.control.y *= (end-start)/2;
523             test.control.x += test.start.x;
524             test.control.y += test.start.y;
525         } else {
526             test.control.x *= -(end-start)/2;
527             test.control.y *= -(end-start)/2;
528             test.control.x += test.end.x;
529             test.control.y += test.end.y;
530         }
531
532 //#define PROBES
533 #ifdef PROBES
534         /* measure the spline's accurancy, by taking a number of probes */
535         for(t=0;t<probes;t++) {
536             gfxpoint_t qr1,qr2,cr1,cr2;
537             double pos = 0.5/(probes*2)*(t*2+1);
538             double dx,dy;
539             double dist1,dist2;
540             qr1 = qspline_getpoint(&test, pos);
541             cr1 = cspline_getpoint(s, start+pos*(end-start));
542
543             dx = qr1.x - cr1.x;
544             dy = qr1.y - cr1.y;
545             dist1 = dx*dx+dy*dy;
546
547             if(dist1>quality2) {
548                 recurse=1;break;
549             }
550             qr2 = qspline_getpoint(&test, (1-pos));
551             cr2 = cspline_getpoint(s, start+(1-pos)*(end-start));
552
553             dx = qr2.x - cr2.x;
554             dy = qr2.y - cr2.y;
555             dist2 = dx*dx+dy*dy;
556
557             if(dist2>quality2) {
558                 recurse=1;break;
559             }
560         }
561 #else // quadratic error: *much* faster!
562
563         /* convert control point representation to
564            d*x^3 + c*x^2 + b*x + a */
565         dx= s->end.x  - s->control2.x*3 + s->control1.x*3 - s->start.x;
566         dy= s->end.y  - s->control2.y*3 + s->control1.y*3 - s->start.y;
567
568         /* we need to do this for the subspline between [start,end], not [0,1]
569            as a transformation of t->a*t+b does nothing to highest coefficient
570            of the spline except multiply it with a^3, we just need to modify
571            d here. */
572         {double m = end-start;
573          dx*=m*m*m;
574          dy*=m*m*m;
575         }
576
577         /* use the integral over (f(x)-g(x))^2 between 0 and 1
578            to measure the approximation quality.
579            (it boils down to const*d^2) */
580         recurse = (dx*dx + dy*dy > quality2);
581 #endif
582
583         if(recurse && istep>1 && size-level > num) {
584             istep >>= 1;
585             level++;
586         } else {
587             *q++ = test;
588             num++;
589             istart += istep;
590             while(!(istart & istep)) {
591                 level--;
592                 istep <<= 1;
593             }
594         }
595     }
596     return num;
597 }
598
599 void gfxdraw_conicTo(gfxdrawer_t*draw, double cx, double cy, double tox, double toy, double quality)
600 {
601     double c1x = (draw->x + 2 * cx) / 3;
602     double c1y = (draw->y + 2 * cy) / 3;
603     double c2x = (2 * cx + tox) / 3;
604     double c2y = (2 * cy + toy) / 3;
605     gfxdraw_cubicTo(draw, c1x, c1y, c2x, c2y, tox, toy, quality);
606 }
607
608
609 void gfxdraw_cubicTo(gfxdrawer_t*draw, double c1x, double c1y, double c2x, double c2y, double x, double y, double quality)
610 {
611     qspline_t q[128];
612     cspline_t c;
613     double maxerror = quality>0 ? quality : 1.0;
614     int t,num;
615
616     c.start.x = draw->x;
617     c.start.y = draw->y;
618     c.control1.x = c1x;
619     c.control1.y = c1y;
620     c.control2.x = c2x;
621     c.control2.y = c2y;
622     c.end.x = x;
623     c.end.y = y;
624
625     num = approximate3(&c, q, 128, maxerror);
626
627     for(t=0;t<num;t++) {
628         gfxpoint_t mid;
629         gfxpoint_t to;
630         mid.x = q[t].control.x;
631         mid.y = q[t].control.y;
632         to.x = q[t].end.x;
633         to.y = q[t].end.y;
634         draw->splineTo(draw, mid.x, mid.y, to.x, to.y);
635     }
636 }
637
638 gfxbbox_t gfxbbox_expand_to_point(gfxbbox_t box, gfxcoord_t x, gfxcoord_t y)
639 {
640     if(box.xmin==0 && box.ymin==0 && box.xmax==0 && box.ymax==0) {
641         box.xmin = x;
642         box.ymin = y;
643         box.xmax = x;
644         box.ymax = y;
645         if(x==0 && y==0) box.xmax = 0.0000001;
646         return box;
647     }
648     if(x < box.xmin)
649         box.xmin = x;
650     if(x > box.xmax)
651         box.xmax = x;
652     if(y < box.ymin)
653         box.ymin = y;
654     if(y > box.ymax)
655         box.ymax = y;
656     return box;
657 }
658
659 void gfxbbox_intersect(gfxbbox_t*box1, gfxbbox_t*box2)
660 {
661     if(box2->xmin > box1->xmin)
662         box1->xmin = box2->xmin;
663     if(box2->ymin > box1->ymin)
664         box1->ymin = box2->ymin;
665     if(box2->xmax < box1->xmax)
666         box1->xmax = box2->xmax;
667     if(box2->ymax > box1->ymax)
668         box1->ymax = box2->ymax;
669     if(box1->xmin > box1->xmax)
670         box1->xmax = box1->xmin;
671     if(box1->ymin > box1->ymax)
672         box1->ymax = box1->ymin;
673 }
674
675 gfxbbox_t gfxline_getbbox(gfxline_t*line)
676 {
677     gfxcoord_t x=0,y=0;
678     gfxbbox_t bbox = {0,0,0,0};
679     char last = 0;
680     while(line) {
681         if(line->type == gfx_moveTo) {
682             last = 1;
683         } else if(line->type == gfx_lineTo) {
684             if(last) bbox = gfxbbox_expand_to_point(bbox, x, y);
685             bbox = gfxbbox_expand_to_point(bbox, line->x, line->y);
686             last = 0;
687         } else if(line->type == gfx_splineTo) {
688             if(last) bbox = gfxbbox_expand_to_point(bbox, x, y);
689             bbox = gfxbbox_expand_to_point(bbox, line->sx, line->sy);
690             bbox = gfxbbox_expand_to_point(bbox, line->x, line->y);
691             last = 0;
692         }
693         x = line->x;
694         y = line->y;
695         line = line->next;
696     }
697     return bbox;
698 }
699
700 gfxline_t* gfxline_append(gfxline_t*line1, gfxline_t*line2)
701 {
702     gfxline_t*l = line1;;
703     if(!l)
704         return line2;
705     while(l->next) {
706         l = l->next;
707     }
708     l->next = line2;
709     return line1;
710 }
711
712 void gfxline_transform(gfxline_t*line, gfxmatrix_t*matrix)
713 {
714     while(line) {
715         double x = matrix->m00*line->x + matrix->m10*line->y + matrix->tx;
716         double y = matrix->m01*line->x + matrix->m11*line->y + matrix->ty;
717         line->x = x;
718         line->y = y;
719         if(line->type == gfx_splineTo) {
720             double sx = matrix->m00*line->sx + matrix->m10*line->sy + matrix->tx;
721             double sy = matrix->m01*line->sx + matrix->m11*line->sy + matrix->ty;
722             line->sx = sx;
723             line->sy = sy;
724         }
725         line = line->next;
726     }
727 }
728
729 void gfxmatrix_dump(gfxmatrix_t*m, FILE*fi, char*prefix)
730 {
731     fprintf(fi, "%f %f | %f\n", m->m00, m->m10, m->tx);
732     fprintf(fi, "%f %f | %f\n", m->m01, m->m11, m->ty);
733 }
734
735 void gfxmatrix_transform(gfxmatrix_t*m, double* v, double*dest)
736 {
737     dest[0] = m->m00*v[0] + m->m10*v[1] + m->tx;
738     dest[1] = m->m01*v[0] + m->m11*v[1] + m->ty;
739 }
740 void gfxmatrix_invert(gfxmatrix_t*m, gfxmatrix_t*dest)
741 {
742     double det = m->m00 * m->m11 - m->m10 * m->m01;
743     if(!det) {
744         memset(dest, 0, sizeof(gfxmatrix_t));
745         return;
746     }
747     det = 1/det;
748     dest->m00 = m->m11 * det;
749     dest->m01 = -m->m01 * det;
750     dest->m10 = -m->m10 * det;
751     dest->m11 = m->m00 * det;
752     dest->tx = -(dest->m00 * m->tx + dest->m10 * m->ty);
753     dest->ty = -(dest->m01 * m->tx + dest->m11 * m->ty);
754 }
755 void gfxmatrix_unit(gfxmatrix_t*m)
756 {
757     memset(m, 0, sizeof(gfxmatrix_t));
758     m->m00 = 1.0;
759     m->m11 = 1.0;
760 }
761 void gfxmatrix_multiply(gfxmatrix_t*m1, gfxmatrix_t*m2, gfxmatrix_t*dest)
762 {
763     dest->m00 = m1->m00*m2->m00 + m1->m10*m2->m01;
764     dest->m01 = m1->m01*m2->m00 + m1->m11*m2->m01;
765     dest->m10 = m1->m00*m2->m10 + m1->m10*m2->m11;
766     dest->m11 = m1->m01*m2->m10 + m1->m11*m2->m11;
767     dest->tx = m1->m00*m2->tx + m1->m10*m2->ty + m1->tx;
768     dest->ty = m1->m01*m2->tx + m1->m11*m2->ty + m1->ty;
769 }
770
771 gfxfontlist_t* gfxfontlist_create()
772 {
773     /* Initial list ist empty */
774     return 0;
775 }
776
777 gfxfont_t*gfxfontlist_findfont(gfxfontlist_t*list, char*id)
778 {
779     gfxfontlist_t*l = list;
780     while(l) {
781         if(!strcmp((char*)l->font->id, id)) {
782             return l->font;
783         }
784         l = l->next;
785     }
786     return 0;
787 }
788 char gfxfontlist_hasfont(gfxfontlist_t*list, gfxfont_t*font)
789 {
790     gfxfontlist_t*l = list;
791     while(l) {
792         if(!strcmp((char*)l->font->id, font->id)) {
793             return 1;
794         }
795         l = l->next;
796     }
797     return 0;
798 }
799 gfxfontlist_t*gfxfontlist_addfont(gfxfontlist_t*list, gfxfont_t*font)
800 {
801     gfxfontlist_t*last=0,*l = list;
802     while(l) {
803         last = l;
804         if(l->font == font) {
805             return list; // we already know this font
806         }
807         l = l->next;
808     }
809     if(!font) {
810         fprintf(stderr, "Tried to add zero font\n");
811     }
812     l = (gfxfontlist_t*)rfx_calloc(sizeof(gfxfontlist_t));
813     l->font = font;
814     l->next = 0;
815     if(last) {
816         last->next = l;
817         return list;
818     } else {
819         return l;
820     }
821 }
822 void gfxfontlist_free(gfxfontlist_t*list, char deletefonts)
823 {
824     gfxfontlist_t*l = list;
825     while(l) {
826         gfxfontlist_t*next = l->next;
827         if(deletefonts && l->font) {
828             gfxfont_free(l->font);l->font=0;
829         }
830         l->next = 0;
831         free(l);
832         l = next;
833     }
834 }
835
836 gfxline_t*gfxline_makerectangle(int x1,int y1,int x2, int y2)
837 {
838     gfxline_t* line = (gfxline_t*)rfx_calloc(sizeof(gfxline_t)*5);
839     line[0].x = x1;line[0].y = y1;line[0].type = gfx_moveTo;line[0].next = &line[1];
840     line[1].x = x2;line[1].y = y1;line[1].type = gfx_lineTo;line[1].next = &line[2];
841     line[2].x = x2;line[2].y = y2;line[2].type = gfx_lineTo;line[2].next = &line[3];
842     line[3].x = x1;line[3].y = y2;line[3].type = gfx_lineTo;line[3].next = &line[4];
843     line[4].x = x1;line[4].y = y1;line[4].type = gfx_lineTo;
844     return line;
845 }
846
847 gfxline_t*gfxline_makecircle(double x,double y,double rx, double ry)
848 {
849     double C1 = 0.2930;    
850     double C2 = 0.4140;   
851     double begin = 0.7070; 
852     gfxline_t** line = (gfxline_t**)rfx_calloc(sizeof(gfxline_t*)*9);
853     int t;
854     for(t=0;t<9;t++) {
855         line[t] = rfx_calloc(sizeof(gfxline_t));
856     }
857     line[0]->type = gfx_moveTo;
858     line[0]->x = x+begin*rx;
859     line[0]->y = y+begin*ry;
860     for(t=1;t<9;t++) {
861         line[t-1]->next = line[t];
862         line[t]->type = gfx_splineTo;
863     }
864     line[8]->next = 0;
865 #define R(nr,cx,cy,mx,my) \
866     line[nr]->sx = line[nr-1]->x + (cx); \
867     line[nr]->sy = line[nr-1]->y + (cy); \
868     line[nr]->x = line[nr]->sx + (mx); \
869     line[nr]->y = line[nr]->sy + (my);
870     R(1, -C1*rx,  C1*ry, -C2*rx,      0);
871     R(2, -C2*rx,      0, -C1*rx, -C1*ry);
872     R(3, -C1*rx, -C1*ry,      0, -C2*ry);
873     R(4,      0, -C2*ry,  C1*rx, -C1*ry);
874     R(5,  C1*rx, -C1*ry,  C2*rx,      0);
875     R(6,  C2*rx,      0,  C1*rx,  C1*ry);
876     R(7,  C1*rx,  C1*ry,      0,  C2*ry);
877     R(8,      0,  C2*ry, -C1*rx,  C1*ry);
878     gfxline_t*l = line[0];
879     free(line);
880     return l;
881 }
882
883 gfxbbox_t* gfxline_isrectangle(gfxline_t*_l)
884 {
885     if(!_l)
886         return 0;
887
888     gfxline_t*l = gfxline_clone(_l);
889     gfxline_optimize(l);
890
891     double x1,x2,y1,y2;
892     int xc=0,yc=0;
893     char corners=0;
894
895     char prev=0;
896     char fail=0;
897     for(;l; l=l->next) {
898         double x = l->x;
899         double y = l->y;
900
901         char top=0,left=0;
902
903         if(xc==2 && x!=x1 && x!=x2) {fail=1;break;}
904         else if(xc>=1 && x==x1) {left=0;}
905         else if(xc==2 && x==x2) {left=1;}
906         else if(xc==1 && x!=x1) {x2 = x; xc=2; left=1;}
907         else if(xc==0) {x1 = x; xc=1;left=0;}
908         else {fprintf(stderr, "Internal error in rectangle detection\n");}
909
910         if(yc==2 && y!=y1 && y!=y2) {fail=1;break;}
911         else if(yc>=1 && y==y1) {top=0;}
912         else if(yc==2 && y==y2) {top=1;}
913         else if(yc==1 && y!=y1) {y2 = y; yc=2; top=1;}
914         else if(yc==0) {y1 = y; yc=1;top=0;}
915         else {fprintf(stderr, "Internal error in rectangle detection\n");}
916
917         char pos=top<<1|left;
918
919         if((pos^prev)==3) {
920             /* diagonal lines not allowed */
921             fail=1;break;
922         }
923         prev = pos;
924
925         /* no corner except the first one may be touched twice */
926         if(pos && (corners & 1<<pos)) {
927             fail=1;break;
928         }
929         /* mark which corners have been touched so far */
930         corners |= 1<<pos;
931     }
932     if(fail) {
933         gfxline_free(l);
934         return 0;
935     }
936
937     if(corners!=0x0f) return 0; // not all 4 corners reached
938
939     if(x2<x1) {double x = x2;x2=x1;x1=x;}
940     if(y2<y1) {double y = y2;y2=y1;y1=y;}
941
942     gfxbbox_t*r = malloc(sizeof(gfxbbox_t));
943     r->xmin = x1; r->ymin = y1;
944     r->xmax = x2; r->ymax = y2;
945     return r;
946 }
947
948 void gfximage_transform(gfximage_t*img, gfxcxform_t*cxform)
949 {
950     int t;
951     int size = img->width*img->height;
952
953     int rr,rg,rb,ra, tr;
954     int gr,gg,gb,ga, tg;
955     int br,bg,bb,ba, tb;
956     int ar,ag,ab,aa, ta;
957     rr = (int)(cxform->rr*256);gr = (int)(cxform->gr*256);
958     rg = (int)(cxform->rg*256);gg = (int)(cxform->gg*256);
959     rb = (int)(cxform->rb*256);gb = (int)(cxform->gb*256);
960     ra = (int)(cxform->ra*256);ga = (int)(cxform->ga*256);
961     br = (int)(cxform->br*256);ar = (int)(cxform->ar*256);tr = (int)(cxform->tr*256);
962     bg = (int)(cxform->bg*256);ag = (int)(cxform->ag*256);tg = (int)(cxform->tg*256);
963     bb = (int)(cxform->bb*256);ab = (int)(cxform->ab*256);tb = (int)(cxform->tb*256);
964     ba = (int)(cxform->ba*256);aa = (int)(cxform->aa*256);ta = (int)(cxform->ta*256);
965
966     for(t=0;t<size;t++) {
967         gfxcolor_t*pixel = &img->data[t];
968         unsigned char r = (pixel->r * rr + pixel->g * rg + pixel->b * rb + pixel->a * ra + tr) / 256;
969         unsigned char g = (pixel->r * gr + pixel->g * gg + pixel->b * gb + pixel->a * ga + tg) / 256;
970         unsigned char b = (pixel->r * br + pixel->g * bg + pixel->b * bb + pixel->a * ba + tb) / 256;
971         unsigned char a = (pixel->r * ar + pixel->g * ag + pixel->b * ab + pixel->a * aa + ta) / 256;
972         pixel->r = r;
973         pixel->g = g;
974         pixel->b = b;
975         pixel->a = a;
976     }
977 }
978 void gfxline_dump(gfxline_t*line, FILE*fi, char*prefix)
979 {
980     while(line) {
981         if(line->type == gfx_moveTo) {
982             fprintf(fi, "%smoveTo %.2f %.2f\n", prefix, line->x, line->y);
983         } else if(line->type == gfx_lineTo) {
984             fprintf(fi, "%slineTo %.2f %.2f\n", prefix, line->x, line->y);
985         } else if(line->type == gfx_splineTo) {
986             fprintf(fi, "%ssplineTo (%.2f %.2f) %.2f %.2f\n", prefix, line->sx, line->sy, line->x, line->y);
987         }
988         line = line->next;
989     }
990 }
991