Debian Codegraph @

texk/web2c/mplibdir/pngout.w

raw
1 % Copyright 2012 Taco Hoekwater.
2 %
3 % This program is free software: you can redistribute it and/or modify
4 % it under the terms of the GNU Lesser General Public License as published by
5 % the Free Software Foundation, either version 3 of the License, or
6 % (at your option) any later version.
7 %
8 % This program is distributed in the hope that it will be useful,
9 % but WITHOUT ANY WARRANTY; without even the implied warranty of
10 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 % GNU Lesser General Public License for more details.
12 %
13 % You should have received a copy of the GNU Lesser General Public License
14 % along with this program. If not, see <http://www.gnu.org/licenses/>.
15 %
16 % TeX is a trademark of the American Mathematical Society.
17 % METAFONT is a trademark of Addison-Wesley Publishing Company.
18 % PostScript is a trademark of Adobe Systems Incorporated.
19
20 % Here is TeX material that gets inserted after \input webmac
21
22 \font\tenlogo=logo10 % font used for the METAFONT logo
23 \font\logos=logosl10
24 \def\MF{{\tenlogo META}\-{\tenlogo FONT}}
25 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
26 \def\<#1>{$\langle#1\rangle$}
27 \def\section{\mathhexbox278}
28 \def\[#1]{} % from pascal web
29 \def\(#1){} % this is used to make section names sort themselves better
30 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
31
32 \def\title{MetaPost PNG output}
33 \def\topofcontents{\hsize 5.5in
34 \vglue -30pt plus 1fil minus 1.5in
35 \def\?##1]{\hbox to 1in{\hfil##1.\ }}
36 }
37 \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
38 \pdfoutput=1
39 \pageno=3
40
41 @
42 @d zero_t ((math_data *)mp->math)->zero_t
43 @d number_zero(A) (((math_data *)(mp->math))->equal)(A,zero_t)
44 @d number_greater(A,B) (((math_data *)(mp->math))->greater)(A,B)
45 @d number_positive(A) number_greater(A, zero_t)
46 @d number_to_scaled(A) (((math_data *)(mp->math))->to_scaled)(A)
47 @d round_unscaled(A) (((math_data *)(mp->math))->round_unscaled)(A)
48 @d True 1
49 @d False 0
50 @d null_font 0
51 @d null 0
52 @d unity 1.0
53 @d incr(A) (A)=(A)+1 /* increase a variable by unity */
54 @d decr(A) (A)=(A)-1 /* decrease a variable by unity */
55 @d negate(A) (A)=-(A) /* change the sign of a variable */
56
57 @c
58 #include "mpconfig.h"
59 #include <w2c/config.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <math.h>
64 #include "mplib.h"
65 #include "mplibps.h" /* external header */
66 #include "mplibpng.h" /* external header */
67 #include "mpmp.h" /* internal header */
68 #include "mppsout.h" /* internal header */
69 #include "mppngout.h" /* internal header */
70 #include "mpmath.h" /* internal header */
71 @h
72 @<Types in the outer block@>
73 @<Declarations@>
74
75 @ There is a small bit of code from the backend that bleads through
76 to the frontend because I do not know how to set up the includes
77 properly. That is |typedef struct pngout_data_struct * pngout_data|.
78
79 @ @(mppngout.h@>=
80 #ifndef MPPNGOUT_H
81 #define MPPNGOUT_H 1
82 #include "cairo.h"
83 const char *COMPILED_CAIRO_VERSION_STRING = CAIRO_VERSION_STRING;
84 #include "pixman.h"
85 const char *COMPILED_PIXMAN_VERSION_STRING = PIXMAN_VERSION_STRING;
86 #define PNG_SKIP_SETJMP_CHECK 1
87 #include "png.h"
88 #include "mplib.h"
89 #include "mpmp.h"
90 #include "mplibps.h"
91 typedef struct pngout_data_struct {
92 @<Globals@>
93 } pngout_data_struct ;
94 @<Exported function headers@>
95 #endif
96
97 @ @<Exported function headers@>=
98 void mp_png_backend_initialize (MP mp) ;
99 void mp_png_backend_free (MP mp) ;
100
101 @ @c
102 void mp_png_backend_initialize (MP mp) {
103 mp->png = mp_xmalloc(mp,1,sizeof(pngout_data_struct));
104 memset(mp->png,0,sizeof(pngout_data_struct));
105 }
106 void mp_png_backend_free (MP mp) {
107 mp_xfree(mp->png);
108 mp->png = NULL;
109 }
110
111 @ Writing to PNG files
112
113 @<Globals@>=
114 cairo_surface_t *surface;
115 cairo_t *cr;
116
117 @ We often need to print a pair of coordinates, and these need to
118 offset so that all coordinates are positive.
119
120 @<Globals@>=
121 integer dx;
122 integer dy;
123
124 @
125 @<Declarations@>=
126 static void mp_png_start(MP mp,mp_edge_object *hh, double hppp, double vppp, int colormodel, int antialias);
127
128 @
129 @c
130 void mp_png_start(MP mp,mp_edge_object *hh, double hppp, double vppp, int colormodel, int antialias) {
131 double w, h;
132 if ( hh->minx>hh->maxx) {
133 w = 1;
134 h = 1;
135 mp->png->dx = 0;
136 mp->png->dy = 0;
137 } else {
138 w = (ceil(hh->maxx) - floor(hh->minx)) / hppp;
139 h = (ceil(hh->maxy) - floor(hh->miny)) / vppp;
140 mp->png->dx = -floor(hh->minx);
141 mp->png->dy = -floor(hh->miny);
142 }
143 mp->png->surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
144 mp->png->cr = cairo_create (mp->png->surface);
145 /* if there is no alpha channel, a white background is needed */
146 if (colormodel == PNG_COLOR_TYPE_RGB ||
147 colormodel == PNG_COLOR_TYPE_GRAY) {
148 cairo_save(mp->png->cr);
149 cairo_set_source_rgb(mp->png->cr, 1.0, 1.0, 1.0);
150 cairo_rectangle(mp->png->cr, 0, 0, w, h);
151 cairo_fill(mp->png->cr);
152 cairo_restore(mp->png->cr);
153 }
154 cairo_scale(mp->png->cr, 1/hppp, -1/vppp);
155 cairo_translate(mp->png->cr, 0, -(h*vppp));
156 cairo_translate(mp->png->cr, mp->png->dx, mp->png->dy);
157 cairo_set_antialias(mp->png->cr, antialias);
158 }
159
160 @ Outputting a color specification.
161
162 @d set_color_objects(pq)
163 object_color_model = pq->color_model;
164 object_color_a = pq->color.a_val;
165 object_color_b = pq->color.b_val;
166 object_color_c = pq->color.c_val;
167 object_color_d = pq->color.d_val;
168
169 @c
170 static void mp_png_color_out (MP mp, mp_graphic_object *p) {
171 int object_color_model;
172 double object_color_a, object_color_b, object_color_c, object_color_d ;
173 if (gr_type(p) == mp_fill_code) {
174 mp_fill_object *pq = (mp_fill_object *)p;
175 set_color_objects(pq);
176 } else if (gr_type(p) == mp_stroked_code) {
177 mp_stroked_object *pq = (mp_stroked_object *)p;
178 set_color_objects(pq);
179 } else {
180 mp_text_object *pq = (mp_text_object *)p;
181 set_color_objects(pq);
182 }
183 if ( object_color_model==mp_no_model ) {
184 cairo_set_source_rgb (mp->png->cr, 0, 0, 0);
185 } else {
186 if ( object_color_model==mp_grey_model ) {
187 object_color_b = object_color_a;
188 object_color_c = object_color_a;
189 } else if ( object_color_model==mp_cmyk_model) {
190 int c,m,y,k;
191 c = object_color_a;
192 m = object_color_b;
193 y = object_color_c;
194 k = object_color_d;
195 object_color_a = unity - (c+k>unity ? unity : c+k);
196 object_color_b = unity - (m+k>unity ? unity : m+k);
197 object_color_c = unity - (y+k>unity ? unity : y+k);
198 }
199 cairo_set_source_rgb (mp->png->cr, object_color_a, object_color_b, object_color_c);
200 }
201 }
202
203 @ @<Declarations@>=
204 static void mp_png_color_out (MP mp, mp_graphic_object *p);
205
206 @ This is the information that comes from a pen
207
208 @<Types...@>=
209 typedef struct mp_pen_info {
210 double tx, ty;
211 double sx, rx, ry, sy;
212 double ww;
213 } mp_pen_info;
214
215
216 @ (Re)discover the characteristics of an elliptical pen
217
218 @<Declarations@>=
219 mp_pen_info *mp_png_pen_info(MP mp, mp_gr_knot pp, mp_gr_knot p);
220
221 @ The next two constants come from the original web source.
222 Together with the two helper functions, they will tell whether
223 the |x| or the |y| direction of the path is the most important
224
225 @d aspect_bound (10/65536.0)
226 @d aspect_default 1
227
228 @c
229 static double coord_range_x (mp_gr_knot h, double dz) {
230 double z;
231 double zlo = 0, zhi = 0;
232 mp_gr_knot f = h;
233 while (h != NULL) {
234 z = gr_x_coord(h);
235 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
236 z = gr_right_x(h);
237 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
238 z = gr_left_x(h);
239 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
240 h = gr_next_knot(h);
241 if (h==f)
242 break;
243 }
244 return (zhi - zlo <= dz ? aspect_bound : aspect_default);
245 }
246 static double coord_range_y (mp_gr_knot h, double dz) {
247 double z;
248 double zlo = 0, zhi = 0;
249 mp_gr_knot f = h;
250 while (h != NULL) {
251 z = gr_y_coord(h);
252 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
253 z = gr_right_y(h);
254 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
255 z = gr_left_y(h);
256 if (z < zlo) zlo = z; else if (z > zhi) zhi = z;
257 h = gr_next_knot(h);
258 if (h==f)
259 break;
260 }
261 return (zhi - zlo <= dz ? aspect_bound : aspect_default);
262 }
263
264 @
265 @c
266 mp_pen_info *mp_png_pen_info(MP mp, mp_gr_knot pp, mp_gr_knot p) {
267 double wx, wy; /* temporary pen widths, in either direction */
268 struct mp_pen_info *pen; /* return structure */
269 if (p == NULL)
270 return NULL;
271 pen = mp_xmalloc(mp, 1, sizeof(mp_pen_info));
272 pen->rx = unity;
273 pen->ry = unity;
274 pen->ww = unity;
275 if ((gr_right_x(p) == gr_x_coord(p))
276 &&
277 (gr_left_y(p) == gr_y_coord(p))) {
278 wx = fabs(gr_left_x(p) - gr_x_coord(p));
279 wy = fabs(gr_right_y(p) - gr_y_coord(p));
280 } else {
281 double arg1, arg2;
282 arg1 = gr_left_x(p)-gr_x_coord(p);
283 arg2 = gr_right_x(p)-gr_x_coord(p);
284 wx = sqrt(arg1*arg1 + arg2*arg2);
285 arg1 = gr_left_y(p)-gr_y_coord(p);
286 arg2 = gr_right_y(p)-gr_y_coord(p);
287 wy = sqrt(arg1*arg1 + arg2*arg2);
288 }
289 if ((wy/coord_range_x(pp, wx)) >= (wx/coord_range_y(pp, wy)))
290 pen->ww = wy;
291 else
292 pen->ww = wx;
293 pen->tx = gr_x_coord(p);
294 pen->ty = gr_y_coord(p);
295 pen->sx = gr_left_x(p) - pen->tx;
296 pen->rx = gr_left_y(p) - pen->ty;
297 pen->ry = gr_right_x(p) - pen->tx;
298 pen->sy = gr_right_y(p) - pen->ty;
299 if (pen->ww != unity) {
300 if (pen->ww == 0) {
301 pen->sx = unity;
302 pen->sy = unity;
303 } else {
304 pen->rx = pen->rx / pen->ww;
305 pen->ry = pen->ry / pen->ww;
306 pen->sx = pen->sx / pen->ww;
307 pen->sy = pen->sy / pen->ww;
308 }
309 }
310 return pen;
311 }
312
313 @ Two types of straight lines come up often in \MP\ paths:
314 cubics with zero initial and final velocity as created by |make_path| or
315 |make_envelope|, and cubics with control points uniformly spaced on a line
316 as created by |make_choices|.
317
318 @<Declarations@>=
319 static boolean mp_is_curved(mp_gr_knot p, mp_gr_knot q) ;
320
321
322 @
323 @d bend_tolerance (131/65536.0) /* allow rounding error of $2\cdot10^{-3}$ */
324
325 @c
326 boolean mp_is_curved(mp_gr_knot p, mp_gr_knot q) {
327 double d; /* a temporary value */
328 if ( gr_right_x(p)==gr_x_coord(p) )
329 if ( gr_right_y(p)==gr_y_coord(p) )
330 if ( gr_left_x(q)==gr_x_coord(q) )
331 if ( gr_left_y(q)==gr_y_coord(q) )
332 return False;
333 d=gr_left_x(q)-gr_right_x(p);
334 if ( fabs(gr_right_x(p)-gr_x_coord(p)-d)<=bend_tolerance )
335 if ( fabs(gr_x_coord(q)-gr_left_x(q)-d)<=bend_tolerance ) {
336 d=gr_left_y(q)-gr_right_y(p);
337 if ( fabs(gr_right_y(p)-gr_y_coord(p)-d)<=bend_tolerance )
338 if ( fabs(gr_y_coord(q)-gr_left_y(q)-d)<=bend_tolerance )
339 return False;
340 }
341 return True;
342 }
343
344
345 @ Cairo does not want to draw a path that consists of only a moveto,
346 so make sure there is some kind of line even for single-pair paths.
347 @c
348 static void mp_png_path_out (MP mp, mp_gr_knot h) {
349 mp_gr_knot p, q; /* for scanning the path */
350 int steps = 0;
351 cairo_move_to (mp->png->cr, gr_x_coord(h),gr_y_coord(h));
352 p=h;
353 do {
354 if ( gr_right_type(p)==mp_endpoint ) {
355 if (steps==0) {
356 cairo_line_to (mp->png->cr, gr_x_coord(p),gr_y_coord(p));
357 }
358 return;
359 }
360 q=gr_next_knot(p);
361 if (mp_is_curved(p, q)){
362 cairo_curve_to (mp->png->cr, gr_right_x(p),gr_right_y(p),
363 gr_left_x(q),gr_left_y(q),
364 gr_x_coord(q),gr_y_coord(q));
365 } else {
366 cairo_line_to (mp->png->cr, gr_x_coord(q),gr_y_coord(q));
367 }
368 p=q;
369 steps++;
370 } while (p!=h);
371 if ((gr_x_coord(p) == gr_x_coord(h)) && (gr_y_coord(p) == gr_y_coord(h)) &&
372 gr_right_type(p)!=mp_endpoint) {
373 cairo_close_path(mp->png->cr);
374 }
375 }
376
377 @ Now for outputting the actual graphic objects.
378
379 @<Declarations@>=
380 static double mp_png_choose_scale (MP mp, mp_graphic_object *p) ;
381
382 @ @c double mp_png_choose_scale (MP mp, mp_graphic_object *p) {
383 /* |p| should point to a text node */
384 double a,b,c,d,ad,bc; /* temporary values */
385 double ret1, ret2;
386 a=gr_txx_val(p);
387 b=gr_txy_val(p);
388 c=gr_tyx_val(p);
389 d=gr_tyy_val(p);
390 if ( a<0 ) negate(a);
391 if ( b<0 ) negate(b);
392 if ( c<0 ) negate(c);
393 if ( d<0 ) negate(d);
394 ad=(a-d)/2.0;
395 bc=(b-c)/2.0;
396 ret1 = sqrt((d+ad)*(d+ad) + ad*ad);
397 ret2 = sqrt((c+bc)*(c+bc) + bc*bc);
398 return sqrt(ret1*ret1 + ret2*ret2);
399 }
400
401 @
402 @d xrealloc(P,A,B) mp_xrealloc(mp,P,(size_t)A,B)
403 @d XREALLOC(a,b,c) a = xrealloc(a,(b+1),sizeof(c));
404
405 @c
406 void mp_reallocate_psfonts (MP mp, int l) {
407 if (l>=mp->png->font_max) {
408 int f;
409 mp->png->last_fnum = mp->png->font_max;
410 XREALLOC (mp->png->psfonts, l, mp_edge_object *);
411 for (f = (mp->png->last_fnum + 1); f <= l; f++) {
412 mp->png->psfonts[f] = NULL;
413 }
414 mp->png->font_max = l;
415 }
416 }
417
418 @ @<Declarations@>=
419 void mp_reallocate_psfonts (MP mp, int l);
420
421 @ @<Globals@>=
422 mp_edge_object **psfonts;
423 int font_max;
424 int last_fnum;
425
426 @ @<Declarations@>=
427 static void mp_png_text_out (MP mp, mp_text_object *p) ;
428
429 @ @c
430 void mp_png_text_out (MP mp, mp_text_object *p) {
431 double ds; /* design size and scale factor for a text node */
432 unsigned char *s = (unsigned char *)gr_text_p(p);
433 size_t l = gr_text_l(p); /* string length */
434 boolean transformed= (gr_txx_val(p)!=unity)||(gr_tyy_val(p)!=unity)||
435 (gr_txy_val(p)!=0)||(gr_tyx_val(p)!=0);
436 int fn = gr_font_n(p);
437 mp_ps_font *f;
438 double scf;
439 ds =(mp->font_dsize[fn]+8) / (16*65536.0);
440 scf = mp_png_choose_scale (mp,(mp_graphic_object *)p);
441 cairo_save(mp->png->cr);
442 if ( transformed ) {
443 cairo_matrix_t matrix = {0,0,0,0,0,0};
444 cairo_matrix_init(&matrix, (gr_txx_val(p)/scf), (gr_tyx_val(p)/scf),
445 (gr_txy_val(p)/scf), (gr_tyy_val(p)/scf),
446 gr_tx_val(p),gr_ty_val(p));
447 cairo_transform (mp->png->cr, &matrix);
448 cairo_move_to(mp->png->cr, 0, 0);
449 } else {
450 cairo_translate (mp->png->cr,gr_tx_val(p),gr_ty_val(p));
451 }
452 cairo_scale(mp->png->cr, ((ds/1000.0)*scf), ((ds/1000.0)*scf));
453 mp_png_color_out(mp,(mp_graphic_object *)p);
454 while (l-->0) {
455 mp_edge_object *ch;
456 int k = (int)*s++;
457 double wd = 0.0; /* this is in PS design units */
458 mp_reallocate_psfonts(mp, ((fn+1) * 256));
459 ch = mp->png->psfonts[(fn*256)+k];
460 if (ch == NULL) {
461 f = mp_ps_font_parse(mp, fn);
462 if (f == NULL) return;
463 ch = mp_ps_font_charstring(mp,f,k);
464 mp->png->psfonts[(fn*256)+k] = ch;
465 }
466 if (ch != NULL) {
467 mp_graphic_object *pp = ch->body;
468 while (pp!=NULL) {
469 mp_png_path_out(mp, gr_path_p((mp_fill_object *)pp));
470 pp=pp->next;
471 }
472 cairo_fill(mp->png->cr);
473 }
474 wd = mp_get_char_dimension (mp, mp->font_name[fn], k, 'w');
475 /* $wd/100$ is the size in PS point , i.e, $wd =100\cdot real\_wd$
476 but without considering scaling.
477 We have a scale factor of
478 $(ds/1000.0)\cdot scf$
479 so to match the scale wd should be
480 $1000\cdot real_wd\cdot scf /(ds\cdot scf)$
481 i.e. $wd = 10\cdot wd/ds$.
482 */
483 wd *= 10.0/ds;
484 cairo_translate(mp->png->cr,wd,0);
485 }
486 cairo_restore(mp->png->cr);
487 }
488
489 @ When stroking a path with an elliptical pen, it is necessary to transform
490 the coordinate system so that a unit circular pen will have the desired shape.
491 To keep this transformation local, we enclose it in a $$\&{\<g>}\ldots\&{\</g>}$$
492 block. Any translation component must be applied to the path being stroked
493 while the rest of the transformation must apply only to the pen.
494 If |fill_also=True|, the path is to be filled as well as stroked so we must
495 insert commands to do this after giving the path.
496
497 @<Declarations@>=
498 static void mp_png_stroke_out (MP mp, mp_graphic_object *h,
499 mp_pen_info *pen, boolean fill_also) ;
500
501
502 @ @c
503 void mp_png_stroke_out (MP mp, mp_graphic_object *h,
504 mp_pen_info *pen, boolean fill_also) {
505 boolean transformed = False;
506 if (fill_also) {
507 cairo_save(mp->png->cr);
508 mp_png_path_out(mp, gr_path_p((mp_stroked_object *)h));
509 cairo_close_path (mp->png->cr);
510 cairo_fill (mp->png->cr);
511 cairo_restore(mp->png->cr);
512 }
513 cairo_save(mp->png->cr);
514 if (pen != NULL) {
515 transformed = True;
516 if ((pen->sx==unity) &&
517 (pen->rx==0) &&
518 (pen->ry==0) &&
519 (pen->sy==unity) &&
520 (pen->tx==0) &&
521 (pen->ty==0)) {
522 transformed = False;
523 }
524 }
525 if (pen != NULL) {
526 cairo_set_line_width(mp->png->cr, pen->ww);
527 } else {
528 cairo_set_line_width(mp->png->cr, 0);
529 }
530 if (gr_lcap_val(h)!=0) {
531 switch (gr_lcap_val(h)) {
532 case 1: cairo_set_line_cap(mp->png->cr,CAIRO_LINE_CAP_ROUND); break;
533 case 2: cairo_set_line_cap(mp->png->cr,CAIRO_LINE_CAP_SQUARE); break;
534 default:cairo_set_line_cap(mp->png->cr,CAIRO_LINE_CAP_BUTT); break;
535 }
536 }
537 if (gr_type(h)!=mp_fill_code) {
538 mp_dash_object *hh= gr_dash_p(h);
539 if (hh != NULL && hh->array != NULL) {
540 int i;
541 for (i=0; *(hh->array+i) != -1;i++)
542 ;
543 cairo_set_dash (mp->png->cr, hh->array, i, hh->offset);
544 }
545 }
546 if (gr_ljoin_val((mp_stroked_object *)h)!=0) {
547 switch (gr_ljoin_val((mp_stroked_object *)h)) {
548 case 1: cairo_set_line_join(mp->png->cr,CAIRO_LINE_JOIN_ROUND); break;
549 case 2: cairo_set_line_join(mp->png->cr,CAIRO_LINE_JOIN_BEVEL); break;
550 default: cairo_set_line_join(mp->png->cr,CAIRO_LINE_JOIN_MITER); break;
551 }
552 }
553 cairo_set_miter_limit(mp->png->cr,gr_miterlim_val((mp_stroked_object *)h));
554 mp_png_path_out(mp, gr_path_p((mp_stroked_object *)h));
555 if (transformed) {
556 cairo_matrix_t matrix = {0,0,0,0,0,0};
557 cairo_save(mp->png->cr);
558 cairo_matrix_init(&matrix, pen->sx, pen->rx, pen->ry, pen->sy, pen->tx, pen->ty);
559 cairo_transform (mp->png->cr, &matrix);
560 cairo_stroke (mp->png->cr);
561 cairo_restore(mp->png->cr);
562 } else {
563 cairo_stroke (mp->png->cr);
564 }
565 cairo_restore(mp->png->cr);
566 }
567
568 @ Here is a simple routine that just fills a cycle.
569
570 @<Declarations@>=
571 static void mp_png_fill_out (MP mp, mp_gr_knot p, mp_graphic_object *h);
572
573 @ @c
574 void mp_png_fill_out (MP mp, mp_gr_knot p, mp_graphic_object *h) {
575 cairo_save(mp->png->cr);
576 mp_png_path_out(mp, p);
577 cairo_close_path (mp->png->cr);
578 cairo_fill (mp->png->cr);
579 cairo_restore(mp->png->cr);
580 }
581
582 @ The main output function
583
584 @d pen_is_elliptical(A) ((A)==gr_next_knot((A)))
585 @d gr_has_color(A) (gr_type((A))<mp_start_clip_code)
586
587 @<Exported function ...@>=
588 int mp_png_gr_ship_out (mp_edge_object *hh, const char *options, int standalone) ;
589
590 @ This is a structure to ship data from cairo to our png writer. |width| and
591 |height| could have been stored in our private |mp| instance, but this is just
592 as easy.
593
594 @<Types...@>=
595 typedef struct {
596 unsigned char * data;
597 int height;
598 int width;
599 } bitmap_t;
600
601 @ This is a small structure that is needed so that the png writer callbacks
602 can actually access the |mp| object instance.
603
604 @<Types...@>=
605 typedef struct {
606 void *fp;
607 MP mp;
608 } mp_png_io;
609
610 @ Output a png chunk: the libpng callbacks
611 @c
612 static void mp_write_png_data(png_structp png_ptr, png_bytep data, png_size_t length)
613 {
614 mp_png_io *ioptr = (mp_png_io *)png_get_io_ptr(png_ptr);
615 MP mp = ioptr->mp;
616 (mp->write_binary_file)(mp,ioptr->fp, (void *)data, (size_t)length);
617 }
618 static void mp_write_png_flush(png_structp png_ptr)
619 {
620 /* nothing to do */
621 }
622
623
624 @ Write |bitmap| to a PNG file specified by |path|; returns 0 on
625 success, non-zero on error. The original of this function was
626 borrowed from an internet post, and extended as needed.
627
628 @<Declarations@>=
629 int mp_png_save_to_file (MP mp, const bitmap_t * bitmap, const char *path, int colormodel);
630
631 @ @c
632 int mp_png_save_to_file (MP mp, const bitmap_t * bitmap, const char *path, int colormodel)
633 {
634 mp_png_io io;
635 png_structp png_ptr = NULL;
636 png_infop info_ptr = NULL;
637 size_t y;
638 png_byte ** row_pointers = NULL;
639 int status = -1;
640 int depth = 8;
641 int dpi = 72;
642 int ppm_x;
643 int ppm_y; /* pixels per metre */
644
645 io.mp = mp;
646 io.fp = (mp->open_file)(mp, path, "wb", mp_filetype_bitmap);
647 if (!io.fp) {
648 goto fopen_failed;
649 }
650
651 png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
652 if (png_ptr == NULL) {
653 goto png_create_write_struct_failed;
654 }
655
656 info_ptr = png_create_info_struct (png_ptr);
657 if (info_ptr == NULL) {
658 goto png_create_info_struct_failed;
659 }
660
661 /* Set up error handling. */
662
663 if (setjmp (png_jmpbuf (png_ptr))) {
664 goto png_failure;
665 }
666
667 /* Set image attributes. */
668
669 png_set_IHDR (png_ptr,
670 info_ptr,
671 bitmap->width,
672 bitmap->height,
673 depth,
674 colormodel,
675 PNG_INTERLACE_NONE,
676 PNG_COMPRESSION_TYPE_DEFAULT,
677 PNG_FILTER_TYPE_DEFAULT);
678
679 /* Compression level |3| appears the best tradeoff between
680 disk size and compression speed */
681 png_set_compression_level(png_ptr, 3);
682 png_set_filter(png_ptr,0,PNG_FILTER_NONE);
683 /* setup some information */
684 if (1) {
685 png_text text[2];
686 char *a, *b, *c, *d; /* to get rid of a typecast warning */
687 a = xstrdup("Title");
688 b = xstrdup(path);
689 c = xstrdup("Software");
690 d = xstrdup("Generated by Metapost version " metapost_version);
691
692 text[0].compression = PNG_TEXT_COMPRESSION_NONE;
693 text[0].key = a;
694 text[0].text = b;
695 text[1].compression = PNG_TEXT_COMPRESSION_NONE;
696 text[1].key = c;
697 text[1].text = d;
698 png_set_text(png_ptr, info_ptr, text, 2);
699
700 free(a);
701 free(b);
702 free(c);
703 free(d);
704 }
705
706 /* The original plan was to add |hppp| and |vppp| values in here,
707 but that seems to have negative effects on various bits of
708 software. Better keep the DPI at 72 */
709 ppm_x = dpi / 0.0254;
710 ppm_y = dpi / 0.0254;
711 png_set_pHYs(png_ptr, info_ptr, ppm_x, ppm_y, PNG_RESOLUTION_METER);
712
713 /* Initialize rows of PNG. */
714
715 row_pointers = malloc (bitmap->height * sizeof (png_byte *));
716 for (y = 0; y < bitmap->height; ++y) {
717 if (colormodel == PNG_COLOR_TYPE_GRAY) {
718 row_pointers[y] = bitmap->data + bitmap->width * y;
719 } else if (colormodel == PNG_COLOR_TYPE_GRAY_ALPHA) {
720 row_pointers[y] = bitmap->data + bitmap->width * 2 * y;
721 } else {
722 row_pointers[y] = bitmap->data + bitmap->width * 4 * y;
723 }
724 }
725
726 /* Write the image data to |io| */
727 png_set_write_fn(png_ptr, &io, mp_write_png_data, mp_write_png_flush);
728
729 png_set_rows (png_ptr, info_ptr, row_pointers);
730 if (colormodel == PNG_COLOR_TYPE_RGB) {
731 /* Unfortunately, |png_write_png| does not have enough |PNG_TRANSFORM| options
732 to do this properly, so we have to modify the bitmap data */
733 int i;
734 for (i = 0; i < bitmap->width*bitmap->height*4; i+=4) {
735 unsigned char b = bitmap->data[i];
736 unsigned char g = bitmap->data[i+1];
737 bitmap->data[i] = bitmap->data[i+3];
738 bitmap->data[i+1] = bitmap->data[i+2];
739 bitmap->data[i+2] = g;
740 bitmap->data[i+3] = b;
741 }
742 png_write_png (png_ptr, info_ptr, PNG_TRANSFORM_STRIP_FILLER, NULL);
743 } else if (colormodel == PNG_COLOR_TYPE_RGB_ALPHA) {
744 png_write_png (png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL);
745 } else if (colormodel == PNG_COLOR_TYPE_GRAY ||
746 colormodel == PNG_COLOR_TYPE_GRAY_ALPHA) {
747 int i, j;
748 j = 0;
749 for (i = 0; i < bitmap->width*bitmap->height*4; i+=4) {
750 unsigned char b = bitmap->data[i];
751 unsigned char g = bitmap->data[i+1];
752 unsigned char r = bitmap->data[i+2];
753 bitmap->data[j++] = ((r==g && r==b) ? r : 0.2126*r + 0.7152*g + 0.0722*b);
754 if (colormodel == PNG_COLOR_TYPE_GRAY_ALPHA)
755 bitmap->data[j++] = bitmap->data[i+3];
756 }
757 png_write_png (png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
758 }
759 status = 0;
760
761 free (row_pointers);
762
763 png_failure:
764 png_create_info_struct_failed:
765 png_destroy_write_struct (&png_ptr, &info_ptr);
766 png_create_write_struct_failed:
767 (mp->close_file)(mp, io.fp);
768 fopen_failed:
769 return status;
770 }
771
772
773 @
774 @d number_to_double(A) (((math_data *)(mp->math))->to_double)(A)
775
776 @c
777 int mp_png_gr_ship_out (mp_edge_object *hh, const char *options, int standalone) {
778 char *ss;
779 mp_graphic_object *p;
780 mp_pen_info *pen = NULL;
781 MP mp = hh->parent;
782 bitmap_t bitmap;
783 const char *currentoption = options;
784 int colormodel = PNG_COLOR_TYPE_RGB_ALPHA;
785 int antialias = CAIRO_ANTIALIAS_FAST;
786 int c;
787 while (currentoption && *currentoption) {
788 if (strncmp(currentoption,"format=",7)==0) {
789 currentoption += 7;
790 if (strncmp(currentoption,"rgba",4)==0) {
791 colormodel = PNG_COLOR_TYPE_RGB_ALPHA;
792 currentoption += 4;
793 } else if (strncmp(currentoption,"rgb",3)==0) {
794 colormodel = PNG_COLOR_TYPE_RGB;
795 currentoption += 3;
796 } else if (strncmp(currentoption,"graya",5)==0) {
797 colormodel = PNG_COLOR_TYPE_GRAY_ALPHA;
798 currentoption += 5;
799 } else if (strncmp(currentoption,"gray",4)==0) {
800 colormodel = PNG_COLOR_TYPE_GRAY;
801 currentoption += 4;
802 }
803 } else if (strncmp(currentoption,"antialias=",10)==0) {
804 currentoption += 10;
805 if (strncmp(currentoption,"none",4)==0) {
806 antialias = CAIRO_ANTIALIAS_NONE;
807 currentoption += 4;
808 } else if (strncmp(currentoption,"fast",4)==0) {
809 antialias = CAIRO_ANTIALIAS_FAST;
810 currentoption += 4;
811 } else if (strncmp(currentoption,"good",4)==0) {
812 antialias = CAIRO_ANTIALIAS_GOOD;
813 currentoption += 4;
814 } else if (strncmp(currentoption,"best",4)==0) {
815 antialias = CAIRO_ANTIALIAS_BEST;
816 currentoption += 4;
817 }
818 }
819 currentoption = strchr(currentoption,' ');
820 if (currentoption) {
821 while (*currentoption == ' ')
822 currentoption++;
823 }
824 }
825 c = round_unscaled(internal_value (mp_char_code));
826 if (standalone) {
827 mp->jump_buf = malloc(sizeof(jmp_buf));
828 if (mp->jump_buf == NULL || setjmp(*(mp->jump_buf)))
829 return 0;
830 }
831 if (mp->history >= mp_fatal_error_stop ) return 1;
832 mp_png_start(mp, hh, number_to_double(internal_value(mp_hppp)), number_to_double(internal_value(mp_vppp)),
833 colormodel, antialias);
834 p = hh->body;
835 while ( p!=NULL ) {
836 if (gr_has_color (p))
837 mp_png_color_out (mp, p);
838 switch (gr_type(p)) {
839 case mp_fill_code:
840 {
841 mp_fill_object *ph = (mp_fill_object *)p;
842 if ( gr_pen_p(ph)==NULL ) {
843 mp_png_fill_out(mp, gr_path_p(ph), p);
844 } else if ( pen_is_elliptical(gr_pen_p(ph)) ) {
845 pen = mp_png_pen_info(mp, gr_path_p(ph), gr_pen_p(ph));
846 mp_png_stroke_out(mp, p, pen, True);
847 mp_xfree(pen);
848 } else {
849 mp_png_fill_out(mp, gr_path_p(ph), p);
850 mp_png_fill_out(mp, gr_htap_p(ph), p);
851 }
852 }
853 break;
854 case mp_stroked_code:
855 {
856 mp_stroked_object *ph = (mp_stroked_object *)p;
857 if ( pen_is_elliptical(gr_pen_p(ph))) {
858 pen = mp_png_pen_info(mp, gr_path_p(ph), gr_pen_p(ph));
859 mp_png_stroke_out(mp, p, pen, False);
860 mp_xfree(pen);
861 } else {
862 mp_png_fill_out(mp, gr_path_p(ph), p);
863 }
864 }
865 break;
866 case mp_text_code:
867 if ( (gr_font_n(p)!=null_font) && (gr_text_l(p)>0) ) {
868 mp_png_text_out(mp, (mp_text_object *)p);
869 }
870 break;
871 case mp_start_clip_code:
872 cairo_save(mp->png->cr);
873 mp_png_path_out(mp, gr_path_p((mp_clip_object *)p));
874 cairo_clip(mp->png->cr);
875 cairo_new_path(mp->png->cr);
876 break;
877 case mp_stop_clip_code:
878 cairo_restore(mp->png->cr);
879 break;
880 case mp_start_bounds_code:
881 case mp_stop_bounds_code:
882 break;
883 case mp_special_code:
884 break;
885 } /* all cases are enumerated */
886 p=gr_link(p);
887 }
888 (void)mp_set_output_file_name (mp, c);
889 mp_store_true_output_filename (mp, c);
890 ss = xstrdup(mp->name_of_file);
891 cairo_surface_flush (mp->png->surface);
892 cairo_destroy (mp->png->cr);
893 bitmap.data = cairo_image_surface_get_data (mp->png->surface);
894 bitmap.width = cairo_image_surface_get_width (mp->png->surface);
895 bitmap.height = cairo_image_surface_get_height (mp->png->surface);
896 mp_png_save_to_file (mp, &bitmap, ss, colormodel);
897 cairo_surface_destroy (mp->png->surface);
898 free(ss);
899 return 1;
900 }
901
902 @ @(mplibpng.h@>=
903 #ifndef MPLIBPNG_H
904 #define MPLIBPNG_H 1
905 int mp_png_ship_out (mp_edge_object *hh, const char *options) ;
906 #endif
907
908 @ @c
909 int mp_png_ship_out (mp_edge_object *hh, const char *options) {
910 return mp_png_gr_ship_out (hh, options, (int)True);
911 }
912