]> git.imager.perl.org - imager.git/blob - polygon.c
fix a format string error introduced in the XS re-work
[imager.git] / polygon.c
1 #include "imager.h"
2 #include "draw.h"
3 #include "log.h"
4 #include "imrender.h"
5 #include "imageri.h"
6
7 #define IMTRUNC(x) ((int)((x)*16))
8
9 #define coarse(x) ((x)/16)
10 #define fine(x)   ((x)%16)
11
12 /*#define DEBUG_POLY*/
13 #ifdef DEBUG_POLY
14 #define POLY_DEB(x) x
15 #else
16 #define POLY_DEB(x)
17 #endif
18
19
20 typedef i_img_dim pcord;
21
22 typedef struct {
23   int n;
24   pcord x,y;
25 } p_point;
26
27 typedef struct {
28   int n;
29   pcord x1,y1;
30   pcord x2,y2;
31   pcord miny,maxy;
32   pcord minx,maxx;
33   int updown; /* -1 means down, 0 vertical, 1 up */
34 } p_line;
35
36 typedef struct {
37   int n;
38   double x;
39 } p_slice;
40
41 typedef struct {
42   int *line;            /* temporary buffer for scanline */
43   i_img_dim linelen;    /* length of scanline */
44 } ss_scanline;
45
46 static
47 int
48 p_compy(const p_point *p1, const p_point *p2) {
49   if (p1->y > p2->y) return 1;
50   if (p1->y < p2->y) return -1;
51   return 0;
52 }
53
54 static
55 int
56 p_compx(const p_slice *p1, const p_slice *p2) {
57   if (p1->x > p2->x) return 1;
58   if (p1->x < p2->x) return -1;
59   return 0;
60 }
61
62 /* Change this to int? and round right goddamn it! */
63
64 static
65 double
66 p_eval_aty(p_line *l, pcord y) {
67   int t;
68   t=l->y2-l->y1;
69   if (t) return ( (y-l->y1)*l->x2 + (l->y2-y)*l->x1 )/t;
70   return (l->x1+l->x2)/2.0;
71 }
72
73 static
74 double
75 p_eval_atx(p_line *l, pcord x) {
76   int t;
77   t = l->x2-l->x1;
78   if (t) return ( (x-l->x1)*l->y2 + (l->x2-x)*l->y1 )/t;
79   return (l->y1+l->y2)/2.0;
80 }
81
82 static
83 p_line *
84 line_set_new(const double *x, const double *y, int l) {
85   int i;
86   p_line *lset = mymalloc(sizeof(p_line) * l);
87
88   for(i=0; i<l; i++) {
89     lset[i].n=i;
90     lset[i].x1 = IMTRUNC(x[i]);
91     lset[i].y1 = IMTRUNC(y[i]);
92     lset[i].x2 = IMTRUNC(x[(i+1)%l]);
93     lset[i].y2 = IMTRUNC(y[(i+1)%l]);
94     lset[i].miny=i_min(lset[i].y1,lset[i].y2);
95     lset[i].maxy=i_max(lset[i].y1,lset[i].y2);
96     lset[i].minx=i_min(lset[i].x1,lset[i].x2);
97     lset[i].maxx=i_max(lset[i].x1,lset[i].x2);
98   }
99   return lset;
100 }
101
102 static
103 p_point *
104 point_set_new(const double *x, const double *y, int l) {
105   int i;
106   p_point *pset = mymalloc(sizeof(p_point) * l);
107   
108   for(i=0; i<l; i++) {
109     pset[i].n=i;
110     pset[i].x=IMTRUNC(x[i]);
111     pset[i].y=IMTRUNC(y[i]);
112   }
113   return pset;
114 }
115
116 static
117 void
118 ss_scanline_reset(ss_scanline *ss) {
119   memset(ss->line, 0, sizeof(int) * ss->linelen);
120 }
121
122 static
123 void
124 ss_scanline_init(ss_scanline *ss, i_img_dim linelen, int linepairs) {
125   ss->line    = mymalloc( sizeof(int) * linelen );
126   ss->linelen = linelen;
127   ss_scanline_reset(ss);
128 }
129
130 static
131 void
132 ss_scanline_exorcise(ss_scanline *ss) {
133   myfree(ss->line);
134 }
135   
136                      
137
138
139 /* returns the number of matches */
140
141 static
142 int
143 lines_in_interval(p_line *lset, int l, p_slice *tllist, pcord minc, pcord maxc) {
144   int k;
145   int count = 0;
146   for(k=0; k<l; k++) {
147     if (lset[k].maxy > minc && lset[k].miny < maxc) {
148       if (lset[k].miny == lset[k].maxy) {
149         POLY_DEB( printf(" HORIZONTAL - skipped\n") );
150       } else {
151         tllist[count].x=p_eval_aty(&lset[k],(minc+maxc)/2.0 );
152         tllist[count].n=k;
153         count++;
154       }
155     }
156   }
157   return count;
158 }
159
160 /* marks the up variable for all lines in a slice */
161
162 static
163 void
164 mark_updown_slices(p_line *lset, p_slice *tllist, int count) {
165   p_line *l, *r;
166   int k;
167   for(k=0; k<count; k+=2) {
168     l = lset + tllist[k].n;
169
170     if (l->y1 == l->y2) {
171       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
172       exit(3);
173     }
174
175     l->updown = (l->x1 == l->x2) ?
176       0 :
177       (l->x1 > l->x2)
178       ? 
179       (l->y1 > l->y2) ? -1 : 1
180       : 
181       (l->y1 > l->y2) ? 1 : -1;
182
183     POLY_DEB( printf("marking left line %d as %s(%d)\n", l->n,
184                      l->updown ?  l->updown == 1 ? "up" : "down" : "vert", l->updown, l->updown)
185               );
186
187     if (k+1 >= count) {
188       mm_log((1, "Invalid polygon spec, odd number of line crossings.\n"));
189       return;
190     }
191
192     r = lset + tllist[k+1].n;
193     if (r->y1 == r->y2) {
194       mm_log((1, "mark_updown_slices: horizontal line being marked: internal error!\n"));
195       exit(3);
196     }
197
198     r->updown = (r->x1 == r->x2) ?
199       0 :
200       (r->x1 > r->x2)
201       ? 
202       (r->y1 > r->y2) ? -1 : 1
203       : 
204       (r->y1 > r->y2) ? 1 : -1;
205     
206     POLY_DEB( printf("marking right line %d as %s(%d)\n", r->n,
207                      r->updown ?  r->updown == 1 ? "up" : "down" : "vert", r->updown, r->updown)
208               );
209   }
210 }
211
212
213
214 static
215 unsigned char
216 saturate(int in) {
217   if (in>255) { return 255; }
218   else if (in>0) return in;
219   return 0;
220 }
221
222 typedef void (*scanline_flusher)(i_img *im, ss_scanline *ss, int y, void *ctx);
223
224 /* This function must be modified later to do proper blending */
225
226 static void
227 scanline_flush(i_img *im, ss_scanline *ss, int y, void *ctx) {
228   int x, ch, tv;
229   i_color t;
230   i_color *val = (i_color *)ctx;
231   POLY_DEB( printf("Flushing line %d\n", y) );
232   for(x=0; x<im->xsize; x++) {
233     tv = saturate(ss->line[x]);
234     i_gpix(im, x, y, &t);
235     for(ch=0; ch<im->channels; ch++) 
236       t.channel[ch] = tv/255.0 * val->channel[ch] + (1.0-tv/255.0) * t.channel[ch];
237     i_ppix(im, x, y, &t);
238   }
239 }
240
241
242
243 static
244 int
245 trap_square(pcord xlen, pcord ylen, double xl, double yl) {
246   POLY_DEB( printf("trap_square: %d %d %.2f %.2f\n", xlen, ylen, xl, yl) );
247   return xlen*ylen-(xl*yl)/2.0;
248 }
249
250
251 /* 
252    pixel_coverage calculates the 'left side' pixel coverage of a pixel that is
253    within the min/max ranges.  The shape always corresponds to a square with some
254    sort of a triangle cut from it (which can also yield a triangle).
255 */
256
257
258 static
259 int 
260 pixel_coverage(p_line *line, pcord minx, pcord maxx, pcord  miny, pcord maxy) {
261   double lycross, rycross;
262   int l, r;
263
264   POLY_DEB
265     (
266      printf("    pixel_coverage(..., minx %g, maxx%g, miny %g, maxy %g)\n", 
267             minx/16.0, maxx/16.0, miny/16.0, maxy/16.0)
268      );
269
270   if (!line->updown) {
271     l = r = 0;
272   } else {
273     lycross = p_eval_atx(line, minx);
274     rycross = p_eval_atx(line, maxx);
275     l = lycross <= maxy && lycross >= miny; /* true if it enters through left side */
276     r = rycross <= maxy && rycross >= miny; /* true if it enters through left side */
277   }
278   POLY_DEB(
279            printf("    %4s(%+d): ", line->updown ?  line->updown == 1 ? "up" : "down" : "vert", line->updown);
280            printf(" (%2d,%2d) [%3d-%3d, %3d-%3d] lycross=%.2f rycross=%.2f", coarse(minx), coarse(miny), minx, maxx, miny, maxy, lycross, rycross);
281            printf(" l=%d r=%d\n", l, r)
282            );
283   
284   if (l && r) 
285     return line->updown == 1 ? 
286       (double)(maxx-minx) * (2.0*maxy-lycross-rycross)/2.0  /* up case */
287       :
288       (double)(maxx-minx) * (lycross+rycross-2*miny)/2.0;  /* down case */
289   
290   if (!l && !r) return (maxy-miny)*(maxx*2-p_eval_aty(line, miny)-p_eval_aty(line, maxy))/2.0;
291
292   if (l && !r)
293     return line->updown == 1 ?
294       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, miny)-minx, p_eval_atx(line, minx)-miny) : 
295       trap_square(maxx-minx, maxy-miny, p_eval_aty(line, maxy)-minx, maxy-p_eval_atx(line, minx));
296   
297
298   if (!l && r) {
299     int r = line->updown == 1 ?
300       (maxx-p_eval_aty(line, maxy))*(maxy-p_eval_atx(line, maxx))/2.0 : 
301       (maxx-p_eval_aty(line, miny))*(p_eval_atx(line, maxx)-miny)/2.0;
302     return r;
303   }
304
305   return 0; /* silence compiler warning */
306 }
307
308
309
310
311
312 /* 
313    handle the scanline slice in three steps 
314    
315    1.  Where only the left edge is inside a pixel
316    2a. Where both left and right edge are inside a pixel
317    2b. Where neither left or right edge are inside a pixel
318    3.  Where only the right edge is inside a pixel
319 */
320
321 static
322 void
323 render_slice_scanline(ss_scanline *ss, int y, p_line *l, p_line *r, pcord miny, pcord maxy) {
324   
325   pcord lminx, lmaxx;   /* left line min/max within y bounds in fine coords */
326   pcord rminx, rmaxx;   /* right line min/max within y bounds in fine coords */
327   i_img_dim cpix;       /* x-coordinate of current pixel */
328   i_img_dim startpix;   /* temporary variable for "start of this interval" */
329   i_img_dim stoppix;    /* temporary variable for "end of this interval" */
330
331   /* Find the y bounds of scanline_slice */
332
333   POLY_DEB
334     (
335      printf("render_slice_scanline(..., y=%d)\n");
336      printf("  left  n=%d p1(%.2g, %.2g) p2(%.2g,%.2g) min(%.2g, %.2g) max(%.2g,%.2g) updown(%d)\n",
337             l->n, l->x1/16.0, l->y1/16.0, l->x2/16.0, l->y2/16.0, 
338             l->minx/16.0, l->miny/16.0, l->maxx/16.0, l->maxy/16.0,
339             l->updown);
340      printf("  right n=%d p1(%.2g, %.2g) p2(%.2g,%.2g) min(%.2g, %.2g) max(%.2g,%.2g) updown(%d)\n",
341             r->n, r->x1/16.0, r->y1/16.0, r->x2/16.0, r->y2/16.0, 
342             r->minx/16.0, r->miny/16.0, r->maxx/16.0, r->maxy/16.0,
343             r->updown);
344      );
345   
346   lminx = i_min( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
347   lmaxx = i_max( p_eval_aty(l, maxy), p_eval_aty(l, miny) );
348
349   rminx = i_min( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
350   rmaxx = i_max( p_eval_aty(r, maxy), p_eval_aty(r, miny) );
351
352   startpix = i_max( coarse(lminx), 0 );
353   stoppix  = i_min( coarse(rmaxx-1), ss->linelen-1 );
354
355   POLY_DEB(  printf("  miny=%g maxy=%g\n", miny/16.0, maxy/16.0)  );
356   
357   for(cpix=startpix; cpix<=stoppix; cpix++) {
358     int lt = coarse(lmaxx-1) >= cpix;
359     int rt = coarse(rminx) <= cpix;
360     
361     int A, B, C;
362     
363     POLY_DEB( printf("  (%d,%d) lt=%d rt=%d\n", cpix, y, lt, rt) );
364
365     A = lt ? pixel_coverage(l, cpix*16, cpix*16+16, miny, maxy) : 0;
366     B = lt ? 0 : 16*(maxy-miny);
367     C = rt ? pixel_coverage(r, cpix*16, cpix*16+16, miny, maxy) : 0;
368
369     POLY_DEB( printf("  A=%d B=%d C=%d\n", A, B, C) );
370
371     ss->line[cpix] += A+B-C;
372
373   }
374   POLY_DEB( printf("end render_slice_scanline()\n") );
375 }
376
377 /* Antialiasing polygon algorithm 
378    specs:
379    1. only nice polygons - no crossovers
380    2. 1/16 pixel resolution
381    3. full antialiasing ( complete spectrum of blends )
382    4. uses hardly any memory
383    5. no subsampling phase
384    
385
386    Algorithm outline:
387    1. Split into vertical intervals.
388    2. handle each interval 
389
390    For each interval we must: 
391    1. find which lines are in it
392    2. order the lines from in increasing x order.
393       since we are assuming no crossovers it is sufficent
394       to check a single point on each line.
395 */
396
397 /*
398   Definitions:
399   
400   1. Interval:  A vertical segment in which no lines cross nor end.
401   2. Scanline:  A physical line, contains 16 subpixels in the horizontal direction
402   3. Slice:     A start stop line pair.
403   
404  */
405
406
407 static void
408 i_poly_aa_low(i_img *im, int l, const double *x, const double *y, void *ctx, scanline_flusher flusher) {
409   int i ,k;                     /* Index variables */
410   i_img_dim clc;                /* Lines inside current interval */
411   /* initialize to avoid compiler warnings */
412   pcord tempy = 0;
413   i_img_dim cscl = 0;                   /* Current scanline */
414
415   ss_scanline templine;         /* scanline accumulator */
416   p_point *pset;                /* List of points in polygon */
417   p_line  *lset;                /* List of lines in polygon */
418   p_slice *tllist;              /* List of slices */
419
420   mm_log((1, "i_poly_aa(im %p, l %d, x %p, y %p, ctx %p, flusher %p)\n", im, l, x, y, ctx, flusher));
421
422   for(i=0; i<l; i++) {
423     mm_log((2, "(%.2f, %.2f)\n", x[i], y[i]));
424   }
425
426
427   POLY_DEB(
428            fflush(stdout);
429            setbuf(stdout, NULL);
430            );
431
432   tllist   = mymalloc(sizeof(p_slice)*l);
433   
434   ss_scanline_init(&templine, im->xsize, l);
435
436   pset     = point_set_new(x, y, l);
437   lset     = line_set_new(x, y, l);
438
439
440   qsort(pset, l, sizeof(p_point), (int(*)(const void *,const void *))p_compy);
441   
442   POLY_DEB(
443            for(i=0;i<l;i++) {
444              printf("%d [ %d ] (%d , %d) -> (%d , %d) yspan ( %d , %d )\n",
445                     i, lset[i].n, lset[i].x1, lset[i].y1, lset[i].x2, lset[i].y2, lset[i].miny, lset[i].maxy);
446            }
447            printf("MAIN LOOP\n\n");
448            );
449   
450
451   /* loop on intervals */
452   for(i=0; i<l-1; i++) {
453     i_img_dim startscan = i_max( coarse(pset[i].y), 0);
454     i_img_dim stopscan = i_min( coarse(pset[i+1].y+15), im->ysize);
455     pcord miny, maxy;   /* y bounds in fine coordinates */
456
457     POLY_DEB( pcord cc = (pset[i].y + pset[i+1].y)/2 );
458
459     POLY_DEB(
460              printf("current slice is %d: %d to %d ( cpoint %d ) scanlines %d to %d\n", 
461                     i, pset[i].y, pset[i+1].y, cc, startscan, stopscan)
462              );
463     
464     if (pset[i].y == pset[i+1].y) {
465       POLY_DEB( printf("current slice thickness = 0 => skipping\n") );
466       continue;
467     }
468
469     clc = lines_in_interval(lset, l, tllist, pset[i].y, pset[i+1].y);
470     qsort(tllist, clc, sizeof(p_slice), (int(*)(const void *,const void *))p_compx);
471
472     mark_updown_slices(lset, tllist, clc);
473
474     POLY_DEB
475       (
476        printf("Interval contains %d lines\n", clc);
477        for(k=0; k<clc; k++) {
478          int lno = tllist[k].n;
479          p_line *ln = lset+lno;
480          printf("%d:  line #%2d: (%2d, %2d)->(%2d, %2d) (%2d/%2d, %2d/%2d) -> (%2d/%2d, %2d/%2d) alignment=%s\n",
481                 k, lno, ln->x1, ln->y1, ln->x2, ln->y2, 
482                 coarse(ln->x1), fine(ln->x1), 
483                 coarse(ln->y1), fine(ln->y1), 
484                 coarse(ln->x2), fine(ln->x2), 
485                 coarse(ln->y2), fine(ln->y2),
486                 ln->updown == 0 ? "vert" : ln->updown == 1 ? "up" : "down");
487            
488        }
489        );
490     maxy = im->ysize * 16;
491     miny = 0;
492     for (k = 0; k < clc; ++k) {
493       p_line const * line = lset + tllist[k].n;
494       if (line->miny > miny)
495         miny = line->miny;
496       if (line->maxy < maxy)
497         maxy = line->maxy;
498       POLY_DEB( printf(" line miny %g maxy %g\n", line->miny/16.0, line->maxy/16.0) );
499     }
500     POLY_DEB( printf("miny %g maxy %g\n", miny/16.0, maxy/16.0) );
501
502     for(cscl=startscan; cscl<stopscan; cscl++) {
503       pcord scan_miny = i_max(miny, cscl * 16);
504       pcord scan_maxy = i_min(maxy, (cscl + 1 ) * 16);
505       
506       tempy = i_min(cscl*16+16, pset[i+1].y);
507       POLY_DEB( printf("evaluating scan line %d \n", cscl) );
508       for(k=0; k<clc-1; k+=2) {
509         POLY_DEB( printf("evaluating slice %d\n", k) );
510         render_slice_scanline(&templine, cscl, lset+tllist[k].n, lset+tllist[k+1].n, scan_miny, scan_maxy);
511       }
512       if (16*coarse(tempy) == tempy) {
513         POLY_DEB( printf("flushing scan line %d\n", cscl) );
514         flusher(im, &templine, cscl, ctx);
515         ss_scanline_reset(&templine);
516       }
517       /*
518         else {
519         scanline_flush(im, &templine, cscl, val);
520         ss_scanline_reset(&templine);
521         return 0;
522         }
523       */
524     }
525   } /* Intervals */
526   if (16*coarse(tempy) != tempy) 
527     flusher(im, &templine, cscl-1, ctx);
528
529   ss_scanline_exorcise(&templine);
530   myfree(pset);
531   myfree(lset);
532   myfree(tllist);
533   
534 } /* Function */
535
536 int
537 i_poly_aa(i_img *im, int l, const double *x, const double *y, const i_color *val) {
538   i_color c = *val;
539   i_poly_aa_low(im, l, x, y, &c, scanline_flush);
540   return 1;
541 }
542
543 struct poly_render_state {
544   i_render render;
545   i_fill_t *fill;
546   unsigned char *cover;
547 };
548
549 static void
550 scanline_flush_render(i_img *im, ss_scanline *ss, int y, void *ctx) {
551   i_img_dim x;
552   i_img_dim left, right;
553   struct poly_render_state *state = (struct poly_render_state *)ctx;
554
555   left = 0;
556   while (left < im->xsize && ss->line[left] <= 0)
557     ++left;
558   if (left < im->xsize) {
559     right = im->xsize;
560     /* since going from the left found something, moving from the 
561        right should */
562     while (/* right > left && */ ss->line[right-1] <= 0) 
563       --right;
564     
565     /* convert to the format the render interface wants */
566     for (x = left; x < right; ++x) {
567       state->cover[x-left] = saturate(ss->line[x]);
568     }
569     i_render_fill(&state->render, left, y, right-left, state->cover, 
570                   state->fill);
571   }
572 }
573
574 int
575 i_poly_aa_cfill(i_img *im, int l, const double *x, const double *y, 
576                 i_fill_t *fill) {
577   struct poly_render_state ctx;
578
579   i_render_init(&ctx.render, im, im->xsize);
580   ctx.fill = fill;
581   ctx.cover = mymalloc(im->xsize);
582   i_poly_aa_low(im, l, x, y, &ctx, scanline_flush_render);
583   myfree(ctx.cover);
584   i_render_done(&ctx.render);
585   return 1;
586 }