Changed the way circle sections are drawn.
[rrdtool.git] / src / rrd_gfx.c
1 /****************************************************************************
2  * RRDtool 1.1.x  Copyright Tobias Oetiker, 1997 - 2002
3  ****************************************************************************
4  * rrd_gfx.c  graphics wrapper for rrdtool
5   **************************************************************************/
6
7 /* #define DEBUG */
8
9 #ifdef DEBUG
10 # define DPRINT(x)    (void)(printf x, printf("\n"))
11 #else
12 # define DPRINT(x)
13 #endif
14
15 #include <png.h>
16 #include <ft2build.h>
17 #include FT_FREETYPE_H
18 #include <math.h>
19
20 #include "rrd_gfx.h"
21
22 /* lines are better drawn on the pixle than between pixles */
23 #define LINEOFFSET 0.5
24
25 static
26 gfx_node_t *gfx_new_node( gfx_canvas_t *canvas,enum gfx_en type){
27   gfx_node_t *node = art_new(gfx_node_t,1);
28   if (node == NULL) return NULL;
29   node->type = type;
30   node->color = 0x0;        /* color of element  0xRRGGBBAA  alpha 0xff is solid*/
31   node->size =0.0;         /* font size, line width */
32   node->path = NULL;        /* path */
33   node->points = 0;
34   node->points_max =0;
35   node->svp = NULL;         /* svp */
36   node->filename = NULL;             /* font or image filename */
37   node->text = NULL;
38   node->x = 0.0;
39   node->y = 0.0;          /* position */
40   node->halign = GFX_H_NULL; /* text alignement */
41   node->valign = GFX_V_NULL; /* text alignement */
42   node->tabwidth = 0.0; 
43   node->next = NULL; 
44   if (canvas->lastnode != NULL){
45       canvas->lastnode->next = node;
46   }
47   if (canvas->firstnode == NULL){
48       canvas->firstnode = node;
49   }  
50   canvas->lastnode = node;
51   return node;
52 }
53
54 gfx_canvas_t *gfx_new_canvas (void) {
55     gfx_canvas_t *canvas = art_new(gfx_canvas_t,1);
56     canvas->firstnode = NULL;
57     canvas->lastnode = NULL;
58     return canvas;    
59 }
60
61 /* create a new line */
62 gfx_node_t  *gfx_new_line(gfx_canvas_t *canvas, 
63                            double x0, double y0, 
64                            double x1, double y1,
65                            double width, gfx_color_t color){
66
67   gfx_node_t *node;
68   ArtVpath *vec;
69   node = gfx_new_node(canvas,GFX_LINE);
70   if (node == NULL) return NULL;
71   vec = art_new(ArtVpath, 3);
72   if (vec == NULL) return NULL;
73   vec[0].code = ART_MOVETO_OPEN; vec[0].x=x0+LINEOFFSET; vec[0].y=y0+LINEOFFSET;
74   vec[1].code = ART_LINETO; vec[1].x=x1+LINEOFFSET; vec[1].y=y1+LINEOFFSET;
75   vec[2].code = ART_END;
76   
77   node->points = 3;
78   node->points_max = 3;
79   node->color = color;
80   node->size  = width;
81   node->path  = vec;
82   return node;
83 }
84
85 /* create a new area */
86 gfx_node_t   *gfx_new_area   (gfx_canvas_t *canvas, 
87                               double x0, double y0,
88                               double x1, double y1,
89                               double x2, double y2,
90                               gfx_color_t color) {
91
92   gfx_node_t *node;
93   ArtVpath *vec;
94   node = gfx_new_node(canvas,GFX_AREA);
95   if (node == NULL) return NULL;
96   vec = art_new(ArtVpath, 5);
97   if (vec == NULL) return NULL;
98   vec[0].code = ART_MOVETO; vec[0].x=x0; vec[0].y=y0;
99   vec[1].code = ART_LINETO; vec[1].x=x1; vec[1].y=y1;
100   vec[2].code = ART_LINETO; vec[2].x=x2; vec[2].y=y2;
101   vec[3].code = ART_LINETO; vec[3].x=x0; vec[3].y=y0;
102   vec[4].code = ART_END;
103   
104   node->points = 5;
105   node->points_max = 5;
106   node->color = color;
107   node->path  = vec;
108
109   return node;
110 }
111
112 /* add a point to a line or to an area */
113 int           gfx_add_point  (gfx_node_t *node, 
114                               double x, double y){
115   if (node == NULL) return 1;
116   if (node->type == GFX_AREA) {
117     double x0 = node->path[0].x;
118     double y0 = node->path[0].y;
119     node->points -= 2;
120     art_vpath_add_point (&(node->path),
121                          &(node->points),
122                          &(node->points_max),
123                          ART_LINETO,
124                          x,y);
125     art_vpath_add_point (&(node->path),
126                          &(node->points),
127                          &(node->points_max),
128                          ART_LINETO,
129                          x0,y0);
130     art_vpath_add_point (&(node->path),
131                          &(node->points),
132                          &(node->points_max),
133                          ART_END,
134                          0,0);
135   } else if (node->type == GFX_LINE) {
136     node->points -= 1;
137     art_vpath_add_point (&(node->path),
138                          &(node->points),
139                          &(node->points_max),
140                          ART_LINETO,
141                          x+LINEOFFSET,y+LINEOFFSET);
142     art_vpath_add_point (&(node->path),
143                          &(node->points),
144                          &(node->points_max),
145                          ART_END,
146                          0,0);
147     
148   } else {
149     /* can only add point to areas and lines */
150     return 1;
151   }
152   return 0;
153 }
154
155
156
157 /* create a text node */
158 gfx_node_t   *gfx_new_text   (gfx_canvas_t *canvas,  
159                               double x, double y, gfx_color_t color,
160                               char* font, double size,                        
161                               double tabwidth, double angle,
162                               enum gfx_h_align_en h_align,
163                               enum gfx_v_align_en v_align,
164                               char* text){
165    gfx_node_t *node = gfx_new_node(canvas,GFX_TEXT);
166    if (angle != 0.0){
167        /* currently we only support 0 and 270 */
168        angle = 270.0;
169    }
170    
171    node->text = strdup(text);
172    node->size = size;
173    node->filename = strdup(font);
174    node->x = x;
175    node->y = y;
176    node->color = color;
177    node->tabwidth = tabwidth;
178    node->halign = h_align;
179    node->valign = v_align;
180    return node;
181 }
182
183 double gfx_get_text_width ( double start, char* font, double size,                            
184                             double tabwidth, char* text){
185
186   FT_GlyphSlot  slot;
187   FT_UInt       previous=0;
188   FT_UInt       glyph_index=0;
189   FT_Bool       use_kerning;
190   int           error;
191   FT_Face       face;
192   FT_Library    library=NULL;  
193   double        text_width=0;
194   FT_Init_FreeType( &library );
195   error = FT_New_Face( library, font, 0, &face );
196   if ( error ) return -1;
197   error = FT_Set_Char_Size(face,  size*64,size*64,  100,100);
198   if ( error ) return -1;
199
200   use_kerning = FT_HAS_KERNING(face);
201   slot = face->glyph;
202   for(;*text;text++) {  
203     previous = glyph_index;
204     glyph_index = FT_Get_Char_Index( face, *text);
205     
206     if (use_kerning && previous && glyph_index){
207       FT_Vector  delta;
208       FT_Get_Kerning( face, previous, glyph_index,
209                       0, &delta );
210       text_width += (double)delta.x / 64.0;
211       
212     }
213     error = FT_Load_Glyph( face, glyph_index, 0 );
214     if ( error ) {
215       FT_Done_FreeType(library);
216       return -1;
217     }
218     if (! previous) {
219       text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */        
220     }
221     text_width += (double)slot->metrics.horiAdvance / 64.0;
222   }
223   text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
224   text_width += (double)slot->metrics.width / 64.0; /* add just char width */
225   text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
226   FT_Done_FreeType(library);
227   return text_width;
228 }
229  
230
231
232
233 static int gfx_save_png (art_u8 *buffer, FILE *fp,
234                      long width, long height, long bytes_per_pixel);
235 /* render grafics into png image */
236 int           gfx_render_png (gfx_canvas_t *canvas, 
237                               art_u32 width, art_u32 height, 
238                               double zoom, 
239                               gfx_color_t background, FILE *fp){
240     
241     
242     FT_Library    library;
243     gfx_node_t *node = canvas->firstnode;    
244     art_u8 red = background >> 24, green = (background >> 16) & 0xff;
245     art_u8 blue = (background >> 8) & 0xff, alpha = ( background & 0xff );
246     unsigned long pys_width = width * zoom;
247     unsigned long pys_height = height * zoom;
248     const int bytes_per_pixel = 3;
249     unsigned long rowstride = pys_width*bytes_per_pixel; /* bytes per pixel */
250     art_u8 *buffer = art_new (art_u8, rowstride*pys_height);
251     art_rgb_run_alpha (buffer, red, green, blue, alpha, pys_width*pys_height);
252     FT_Init_FreeType( &library );
253     while(node){
254         switch (node->type) {
255         case GFX_LINE:
256         case GFX_AREA: {   
257             ArtVpath *vec;
258             double dst[6];     
259             ArtSVP *svp;
260             art_affine_scale(dst,zoom,zoom);
261             vec = art_vpath_affine_transform(node->path,dst);
262             if(node->type == GFX_LINE){
263                 svp = art_svp_vpath_stroke ( vec, ART_PATH_STROKE_JOIN_ROUND,
264                                              ART_PATH_STROKE_CAP_ROUND,
265                                              node->size*zoom,1,1);
266             } else {
267                 svp = art_svp_from_vpath ( vec );
268             }
269             art_free(vec);
270             art_rgb_svp_alpha (svp ,0,0, pys_width, pys_height,
271                                node->color, buffer, rowstride, NULL);
272             art_free(svp);
273             break;
274         }
275         case GFX_TEXT: {
276             int  error;
277             float text_width=0.0, text_height = 0.0;
278             unsigned char *text;
279             art_u8 fcolor[3],falpha;
280             FT_Face       face;
281             FT_GlyphSlot  slot;
282             FT_UInt       previous=0;
283             FT_UInt       glyph_index=0;
284             FT_Bool       use_kerning;
285
286             float pen_x = 0.0 , pen_y = 0.0;
287             /* double x,y; */
288             long   ix,iy,iz;
289             
290             fcolor[0] = node->color >> 24;
291             fcolor[1] = (node->color >> 16) & 0xff;
292             fcolor[2] = (node->color >> 8) & 0xff;
293             falpha = node->color & 0xff;
294             error = FT_New_Face( library,
295                                  (char *)node->filename,
296                                  0,
297                                  &face );
298             if ( error ) break;
299             use_kerning = FT_HAS_KERNING(face);
300
301             error = FT_Set_Char_Size(face,   /* handle to face object            */
302                                      (long)(node->size*64),
303                                      (long)(node->size*64),
304                                      (long)(100*zoom),
305                                      (long)(100*zoom));
306             if ( error ) break;
307             pen_x = node->x * zoom;
308             pen_y = node->y * zoom;
309             slot = face->glyph;
310
311             for(text=(unsigned char *)node->text;*text;text++) {        
312                 previous = glyph_index;
313                 glyph_index = FT_Get_Char_Index( face, *text);
314                 
315                 if (use_kerning && previous && glyph_index){
316                     FT_Vector  delta;
317                     FT_Get_Kerning( face, previous, glyph_index,
318                                     0, &delta );
319                     text_width += (double)delta.x / 64.0;
320                     
321                 }
322                 error = FT_Load_Glyph( face, glyph_index, 0 );
323                 if ( error ) break;
324                 if (previous == 0){
325                   pen_x -= (double)slot->metrics.horiBearingX / 64.0; /* adjust pos for first char */   
326                   text_width -= (double)slot->metrics.horiBearingX / 64.0; /* add just char width */    
327                 }
328                 if ( text_height < (double)slot->metrics.horiBearingY / 64.0 ) {
329                   text_height = (double)slot->metrics.horiBearingY / 64.0;
330                 }
331                 text_width += (double)slot->metrics.horiAdvance / 64.0;
332             }
333             text_width -= (double)slot->metrics.horiAdvance / 64.0; /* remove last step */
334             text_width += (double)slot->metrics.width / 64.0; /* add just char width */
335             text_width += (double)slot->metrics.horiBearingX / 64.0; /* add just char width */
336             
337             switch(node->halign){
338             case GFX_H_RIGHT:  pen_x -= text_width; break;
339             case GFX_H_CENTER: pen_x -= text_width / 2.0; break;          
340             case GFX_H_LEFT: break;          
341             }
342
343             switch(node->valign){
344             case GFX_V_TOP:    pen_y += text_height; break;
345             case GFX_V_CENTER: pen_y += text_height / 2.0; break;          
346             case GFX_V_BOTTOM: break;          
347             }
348
349             glyph_index=0;
350             for(text=(unsigned char *)node->text;*text;text++) {
351                 int gr;          
352                 previous = glyph_index;
353                 glyph_index = FT_Get_Char_Index( face, *text);
354                 
355                 if (use_kerning && previous && glyph_index){
356                     FT_Vector  delta;
357                     FT_Get_Kerning( face, previous, glyph_index,
358                                     0, &delta );
359                     pen_x += (double)delta.x / 64.0;
360                     
361                 }
362                 error = FT_Load_Glyph( face, glyph_index, FT_LOAD_RENDER );
363                 if ( error ) break;
364                 gr = slot->bitmap.num_grays -1;
365                 for (iy=0; iy < slot->bitmap.rows; iy++){
366                     long buf_y = iy+(pen_y+0.5)-slot->bitmap_top;
367                     if (buf_y < 0 || buf_y >= pys_height) continue;
368                     buf_y *= rowstride;
369                     for (ix=0;ix < slot->bitmap.width;ix++){
370                         long buf_x = ix + (pen_x + 0.5) + (double)slot->bitmap_left ;
371                         art_u8 font_alpha;
372                         
373                         if (buf_x < 0 || buf_x >= pys_width) continue;
374                         buf_x *=  bytes_per_pixel ;
375                         font_alpha =  *(slot->bitmap.buffer + iy * slot->bitmap.width + ix);
376                         font_alpha =  (art_u8)((double)font_alpha / gr * falpha);
377                         for (iz = 0; iz < 3; iz++){
378                             art_u8 *orig = buffer + buf_y + buf_x + iz;
379                             *orig =  (art_u8)((double)*orig / gr * ( gr - font_alpha) +
380                                               (double)fcolor[iz] / gr * (font_alpha));
381                         }
382                     }
383                 }
384                 pen_x += (double)slot->metrics.horiAdvance / 64.0;
385             }
386         }
387         }
388         node = node->next;
389     }  
390     gfx_save_png(buffer,fp , pys_width,pys_height,bytes_per_pixel);
391     art_free(buffer);
392     FT_Done_FreeType( library );
393     return 0;    
394 }
395
396 /* free memory used by nodes this will also remove memory required for
397    associated paths and svcs ... but not for text strings */
398 int
399 gfx_destroy    (gfx_canvas_t *canvas){  
400   gfx_node_t *next,*node = canvas->firstnode;
401   while(node){
402     next = node->next;
403     art_free(node->path);
404     art_free(node->svp);
405     free(node->text);
406     free(node->filename);
407     art_free(node);
408     node = next;
409   }
410   return 0;
411 }
412  
413 static int gfx_save_png (art_u8 *buffer, FILE *fp,  long width, long height, long bytes_per_pixel){
414   png_structp png_ptr = NULL;
415   png_infop   info_ptr = NULL;
416   int i;
417   png_bytep *row_pointers;
418   int rowstride = width * bytes_per_pixel;
419   png_text text[2];
420   
421   if (fp == NULL)
422     return (1);
423
424   png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,NULL,NULL,NULL);
425   if (png_ptr == NULL)
426    {
427       return (1);
428    }
429    row_pointers = (png_bytepp)png_malloc(png_ptr,
430                                      height*sizeof(png_bytep));
431
432   info_ptr = png_create_info_struct(png_ptr);
433
434   if (info_ptr == NULL)
435     {
436       png_destroy_write_struct(&png_ptr,  (png_infopp)NULL);
437       return (1);
438     }
439
440   if (setjmp(png_jmpbuf(png_ptr)))
441     {
442       /* If we get here, we had a problem writing the file */
443       png_destroy_write_struct(&png_ptr, &info_ptr);
444       return (1);
445     }
446
447   png_init_io(png_ptr, fp);
448   png_set_IHDR (png_ptr, info_ptr,width, height,
449                 8, PNG_COLOR_TYPE_RGB,
450                 PNG_INTERLACE_NONE,
451                 PNG_COMPRESSION_TYPE_DEFAULT,
452                 PNG_FILTER_TYPE_DEFAULT);
453
454   text[0].key = "Software";
455   text[0].text = "RRDtool, Tobias Oetiker <tobi@oetike.ch>, http://tobi.oetiker.ch";
456   text[0].compression = PNG_TEXT_COMPRESSION_NONE;
457   png_set_text (png_ptr, info_ptr, text, 1);
458
459   /* Write header data */
460   png_write_info (png_ptr, info_ptr);
461
462   for (i = 0; i < height; i++)
463     row_pointers[i] = (png_bytep) (buffer + i*rowstride);
464
465   png_write_image(png_ptr, row_pointers);
466   png_write_end(png_ptr, info_ptr);
467   png_destroy_write_struct(&png_ptr, &info_ptr);
468   return 1;
469 }