]> git.cworth.org Git - acre/blob - acre.c
Fix pixel snapping for minor ticks
[acre] / acre.c
1 /* acre - A cairo-based library for creating plots and charts.
2  *
3  * Copyright © 2009 Carl Worth <cworth@cworth.org>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18  */
19
20 #define _ISOC99_SOURCE /* for round() */
21 #define _XOPEN_SOURCE 500
22 #define _GNU_SOURCE /* for asprintf() */
23
24 #include "acre.h"
25 #include "xmalloc.h"
26
27 #include <string.h>
28 #include <stdarg.h>
29 #include <math.h>
30
31 typedef struct _acre_data_point_2d {
32     double x;
33     double y;
34 } acre_data_point_2d_t;
35
36 struct _acre_data {
37     char *name;
38
39     acre_data_point_2d_t *points;
40     unsigned int points_size;
41     unsigned int num_points;
42 };
43
44 typedef struct _acre_axis {
45     char *label;
46     double min;
47     double max;
48 } acre_axis_t;
49
50 struct _acre {
51     char *title;
52     acre_axis_t x_axis;
53     acre_axis_t y_axis;
54
55     acre_data_t **data;
56     unsigned int data_size;
57     unsigned int num_data;
58
59     /* Data for drawing. */
60     cairo_t *cr;
61     PangoFontDescription *font;
62
63     /* Total size including labels. */
64     int width;
65     int height;
66
67     /* Position and size of chart alone. */
68     PangoRectangle chart;
69 };
70
71 /* Create a new, empty plot. */
72 acre_t *
73 acre_create (void)
74 {
75     acre_t *acre;
76
77     acre = xmalloc (sizeof (acre_t));
78
79     acre->title = NULL;
80
81     acre->x_axis.label = NULL;
82     acre->x_axis.min = 0.0;
83     acre->x_axis.max = 0.0;
84
85     acre->y_axis.label = NULL;
86     acre->y_axis.min = 0.0;
87     acre->y_axis.max = 0.0;
88
89     acre->data = NULL;
90     acre->data_size = 0;
91     acre->num_data = 0;
92
93     acre->chart.x = 0;
94     acre->chart.y = 0;
95     acre->chart.width = 0;
96     acre->chart.height = 0;
97
98     return acre;
99 }
100
101 /* Destroy a plot. */
102 void
103 acre_destroy (acre_t *acre)
104 {
105     unsigned int i;
106
107     free (acre->title);
108     free (acre->x_axis.label);
109     free (acre->y_axis.label);
110
111     for (i = 0; i < acre->num_data; i++)
112         acre_data_destroy (acre->data[i]);
113
114     free (acre->data);
115
116     free (acre);
117 }
118
119 void
120 acre_set_title (acre_t *acre, const char *title)
121 {
122     free (acre->title);
123
124     acre->title = strdup (title);
125 }
126
127 void
128 acre_set_x_axis_label (acre_t *acre, const char *label)
129 {
130     free (acre->x_axis.label);
131
132     acre->x_axis.label = strdup (label);
133 }
134
135 void
136 acre_set_y_axis_label (acre_t *acre, const char *label)
137 {
138     free (acre->y_axis.label);
139
140     acre->y_axis.label = strdup (label);
141 }
142
143 /* Add a dataset to the plot. The plot assumes ownership of the
144  * dataset so it is not necessary to call acre_data_destroy on it. */
145 void
146 acre_add_data (acre_t *acre, acre_data_t *data)
147 {
148     if (acre->num_data >= acre->data_size) {
149         acre->data_size *= 2;
150         if (acre->data_size == 0)
151             acre->data_size = 1;
152         acre->data = xrealloc_ab (acre->data,
153                                   acre->data_size,
154                                   sizeof (acre_data_t *));
155     }
156
157     acre->data[acre->num_data] = data;
158     acre->num_data++;
159 }
160
161 #define ACRE_FONT_FAMILY "sans"
162 #define ACRE_FONT_SIZE 12
163 #define ACRE_TITLE_FONT_SIZE 32
164 #define ACRE_PAD (ACRE_FONT_SIZE)
165 #define ACRE_TICK_MAJOR_SIZE 6
166 #define ACRE_TICK_MINOR_SIZE 3
167 #define ACRE_TICK_MINOR_DIVISIONS 5
168 #define ACRE_X_TICK_VALUE_PAD 2
169 #define ACRE_Y_TICK_VALUE_PAD 4
170
171 static PangoLayout *
172 _create_layout (acre_t *acre, const char *text)
173 {
174     PangoLayout *layout;
175
176     layout = pango_cairo_create_layout (acre->cr);
177     pango_layout_set_font_description (layout, acre->font);
178     pango_layout_set_text (layout, text, -1);
179     pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);
180
181     return layout;
182 }
183
184 #define PRINTF_FORMAT(fmt_index, va_index) __attribute__ ((__format__(__printf__, fmt_index, va_index)))
185
186 static PangoLayout *
187 _create_layout_vprintf (acre_t *acre, const char *fmt, va_list ap)
188 {
189     PangoLayout *layout;
190     char *text;
191
192     vasprintf (&text, fmt, ap);
193
194     layout = _create_layout (acre, text);
195
196     free (text);
197
198     return layout;
199 }
200
201 static PangoLayout *
202 _create_layout_printf (acre_t *acre, const char *fmt, ...)
203     PRINTF_FORMAT (2, 3);
204
205 static PangoLayout *
206 _create_layout_printf (acre_t *acre, const char *fmt, ...)
207 {
208     va_list ap;
209     PangoLayout *layout;
210
211     va_start (ap, fmt);
212
213     layout = _create_layout_vprintf (acre, fmt, ap);
214
215     va_end (ap);
216
217     return layout;
218 }
219
220 static void
221 _destroy_layout (PangoLayout *layout)
222 {
223     g_object_unref (layout);
224 }
225
226 static void
227 _show_layout (cairo_t *cr, PangoLayout *layout)
228 {
229     pango_cairo_show_layout (cr, layout);
230
231     _destroy_layout (layout);
232 }
233
234 static void
235 _draw_title_and_labels (acre_t *acre)
236 {
237     cairo_t *cr = acre->cr;
238     PangoFontDescription *title_font;
239     PangoLayout *title_layout, *x_axis_layout, *y_axis_layout;
240     PangoLayout *min_y, *max_y;
241     int min_y_width, max_y_width, y_axis_value_width;
242     int title_width, title_height;
243     int x_axis_width, x_axis_height;
244     int y_axis_width, y_axis_height;
245     PangoRectangle new_chart;
246
247     cairo_save (cr);
248
249     acre->font = pango_font_description_new ();
250     pango_font_description_set_family (acre->font, ACRE_FONT_FAMILY);
251     pango_font_description_set_absolute_size (acre->font,
252                                               ACRE_FONT_SIZE * PANGO_SCALE);
253
254     title_font = pango_font_description_new ();
255     pango_font_description_set_family (title_font, ACRE_FONT_FAMILY);
256     pango_font_description_set_absolute_size (title_font,
257                                               ACRE_TITLE_FONT_SIZE * PANGO_SCALE);
258
259     title_layout = _create_layout (acre, acre->title);
260     pango_layout_set_font_description (title_layout, title_font);
261
262     x_axis_layout = _create_layout (acre, acre->x_axis.label);
263     y_axis_layout = _create_layout (acre, acre->y_axis.label);
264
265     min_y = _create_layout_printf (acre, "%g",
266                                    round (acre->y_axis.min));
267     max_y = _create_layout_printf (acre, "%g",
268                                    round (acre->y_axis.max));
269
270     pango_layout_get_pixel_size (min_y, &min_y_width, NULL);
271     pango_layout_get_pixel_size (max_y, &max_y_width, NULL);
272     y_axis_value_width = MAX (min_y_width, max_y_width);
273
274     _destroy_layout (min_y);
275     _destroy_layout (max_y);
276
277     /* Iterate with the layout of the title and axis labels until they
278      * are stable, (this requires iteration since we don't know what
279      * to set their widths to in advance due to the wrapping of the
280      * other elements). */
281     while (1) {
282         pango_layout_set_width (title_layout, acre->chart.width * PANGO_SCALE);
283         pango_layout_set_width (x_axis_layout, acre->chart.width * PANGO_SCALE);
284         pango_layout_set_width (y_axis_layout, acre->chart.height * PANGO_SCALE);
285
286         pango_layout_get_pixel_size (title_layout, &title_width, &title_height);
287         pango_layout_get_pixel_size (x_axis_layout, &x_axis_width, &x_axis_height);
288         pango_layout_get_pixel_size (y_axis_layout, &y_axis_width, &y_axis_height);
289
290         new_chart.x = ACRE_PAD + y_axis_height +
291             ACRE_PAD + y_axis_value_width + ACRE_Y_TICK_VALUE_PAD;
292         new_chart.width = acre->width - acre->chart.x - ACRE_PAD;
293
294         new_chart.y = ACRE_PAD + title_height + ACRE_PAD;
295         new_chart.height = acre->height - acre->chart.y - 
296             (ACRE_X_TICK_VALUE_PAD + ACRE_FONT_SIZE +
297              ACRE_PAD + x_axis_height + ACRE_PAD);
298
299         if (new_chart.x == acre->chart.x &&
300             new_chart.y == acre->chart.y &&
301             new_chart.width == acre->chart.width &&
302             new_chart.height == acre->chart.height)
303         {
304             break;
305         }
306
307         acre->chart.x = new_chart.x;
308         acre->chart.y = new_chart.y;
309         acre->chart.width = new_chart.width;
310         acre->chart.height = new_chart.height;
311     }
312
313     cairo_set_source_rgb (cr, 0, 0, 0);
314
315     cairo_move_to (cr, acre->chart.x, ACRE_PAD);
316     _show_layout (cr, title_layout);
317
318     cairo_save (cr);
319     {
320         cairo_translate (cr, ACRE_PAD, acre->chart.y + acre->chart.height);
321         cairo_rotate (cr, - M_PI / 2.0);
322         cairo_move_to (cr, 0, 0);
323         _show_layout (cr, y_axis_layout);
324     }
325     cairo_restore (cr);
326
327     cairo_move_to (cr, acre->chart.x,
328                    acre->chart.y + acre->chart.height +
329                    ACRE_FONT_SIZE + ACRE_PAD);
330     _show_layout (cr, x_axis_layout);
331
332     cairo_restore (cr);
333 }
334
335 /* For a given axis range, compute a step size (in data space) to
336  * generate a suitable number of ticks (5 or so). */
337 static double
338 _step_for_range (double range)
339 {
340     double step, scale_factor;
341
342     /* We want roughly 5 major ticks for the chart. */
343     step = range / 5;
344
345     /* Normalize the step so we can easily snap it to a desirable
346      * value. */
347     scale_factor = pow (10.0, floor (log10 (step)));
348     step /= scale_factor;
349
350     /* We want increments of 1, 2.5, 5, or 10 (times some power of
351      * 10). The threshold values between these are computed
352      * logarithmically. */
353     if (step < 3.535533905932738) {
354         if (step < 1.58113883008419)
355             step = 1.0;
356         else
357             step = 2.5;
358     } else {
359         if (step < 7.071067811865475)
360             step = 5.0;
361         else
362             step = 10.0;
363     }
364
365     /* Un-normalize and we now have the data value that we want to
366      * step at. */
367     return step * scale_factor;
368 }
369
370 /* Given an axis range, we can compute a desired data-space step
371  * amount for the major ticks (see _step_for_range). To get
372  * nice-looking pixel-snapped ticks we want to expand the range
373  * slightly. */
374 static void
375 _expand_range_for_width (double *axis_min, double *axis_max, int pixel_size)
376 {
377     double range, new_range, step, pixel_step;
378
379     range = *axis_max - *axis_min;
380
381     step = _step_for_range (range);
382     pixel_step = step * pixel_size / range / ACRE_TICK_MINOR_DIVISIONS;
383
384     /* We expand the range by the ratio of the pixel step to the floor
385      * of the pixel_step.
386      */
387     new_range = range * pixel_step / floor (pixel_step);
388
389     /* And spread the increase out on either side of the range. */
390     *axis_min -= (new_range - range) / 2.0;
391     *axis_max += (new_range - range) / 2.0;
392 }
393
394 /* Setup a transformation in acre->cr such that data values plotted
395  * will appear where they should within the chart.
396  */
397 static void
398 _set_transform_to_data_space (acre_t *acre)
399 {
400     cairo_t *cr = acre->cr;
401
402     cairo_translate (cr,
403                      acre->chart.x,
404                      acre->chart.y + acre->chart.height);
405     cairo_scale (cr,
406                  acre->chart.width / (acre->x_axis.max - acre->x_axis.min),
407                  - acre->chart.height /(acre->y_axis.max - acre->y_axis.min));
408     cairo_translate (cr, -acre->x_axis.min, -acre->y_axis.min);
409 }
410
411 static void
412 _compute_axis_ranges (acre_t *acre)
413 {
414     unsigned int d, i;
415     acre_data_t *data;
416     double x_adjust, y_adjust;
417     cairo_t *cr = acre->cr;
418
419     acre->x_axis.min = acre->data[0]->points[0].x;
420     acre->x_axis.max = acre->data[0]->points[0].x;
421     acre->y_axis.min = acre->data[0]->points[0].y;
422     acre->y_axis.min = acre->data[0]->points[0].y;
423
424     /* First, simply find the extrema of the data. */
425     for (d = 0; d < acre->num_data; d++) {
426         data = acre->data[d];
427         for (i = 0; i < data->num_points; i++) {
428             if (data->points[i].x < acre->x_axis.min)
429                 acre->x_axis.min = data->points[i].x;
430             if (data->points[i].x > acre->x_axis.max)
431                 acre->x_axis.max = data->points[i].x;
432
433             if (data->points[i].y < acre->y_axis.min)
434                 acre->y_axis.min = data->points[i].y;
435             if (data->points[i].y > acre->y_axis.max)
436                 acre->y_axis.max = data->points[i].y;
437         }
438     }
439
440     /* Next, increase the axis ranges just enough so that the step
441      * sizes for the ticks will be integers.
442      */
443     _expand_range_for_width (&acre->x_axis.min,
444                              &acre->x_axis.max,
445                              acre->chart.width);
446
447     _expand_range_for_width (&acre->y_axis.min,
448                              &acre->y_axis.max,
449                              acre->chart.height);
450
451     /* Finally, we also translate the axis ranges slightly so that the
452      * ticks land on half-integer device-pixel positions.
453      */
454     cairo_save (cr);
455     {
456         _set_transform_to_data_space (acre);
457
458         x_adjust = 0.0;
459         y_adjust = 0.0;
460         cairo_user_to_device (cr, &x_adjust, &y_adjust);
461         x_adjust = (round (x_adjust + 0.5) - 0.5) - x_adjust;
462         y_adjust = (round (y_adjust + 0.5) - 0.5) - y_adjust;
463         cairo_device_to_user_distance (cr, &x_adjust, &y_adjust);
464
465         acre->x_axis.min -= x_adjust;
466         acre->x_axis.max -= x_adjust;
467
468         acre->y_axis.min -= y_adjust;
469         acre->y_axis.max -= y_adjust;
470     }
471     cairo_restore (cr);
472 }
473
474 static void
475 _draw_data (acre_t *acre)
476 {
477     cairo_t *cr = acre->cr;
478     unsigned int d, i;
479     acre_data_t *data;
480
481     cairo_save (cr);
482
483     cairo_set_source_rgb (cr, 0, 0, 0);
484
485     _set_transform_to_data_space (acre);
486
487     for (d = 0; d < acre->num_data; d++) {
488         data = acre->data[d];
489         cairo_new_path (cr);
490         for (i = 0; i < data->num_points; i++) {
491             cairo_line_to (cr,
492                            data->points[i].x,
493                            data->points[i].y);
494         }
495         cairo_save (cr);
496         {
497             cairo_identity_matrix (cr);
498             cairo_set_line_width (cr, 1.0);
499             cairo_stroke (cr);
500         }
501         cairo_restore (cr);
502     }
503
504     cairo_restore (cr);
505 }
506
507 typedef enum _ticks { ACRE_TICKS_X, ACRE_TICKS_Y } acre_ticks_t;
508
509 static void
510 _draw_ticks (acre_t *acre,
511              double axis_min, double axis_max,
512              acre_ticks_t ticks)
513 {
514     cairo_t *cr = acre->cr;
515     double t, step, sub_step;
516
517     cairo_save (cr);
518
519     _set_transform_to_data_space (acre);
520
521     step = _step_for_range (axis_max - axis_min);
522     sub_step = step / ACRE_TICK_MINOR_DIVISIONS;
523
524     for (t = (floor (axis_min / sub_step) + 1) * sub_step;
525          t <= axis_max;
526          t += sub_step)
527     {
528         int tick_size;
529         if (fabs((t / step) - (int) (t / step)) < 0.5 * (sub_step / step))
530             tick_size = ACRE_TICK_MAJOR_SIZE;
531         else
532             tick_size = ACRE_TICK_MINOR_SIZE;
533
534         /* tick */
535         cairo_save (cr);
536         {
537             if (ticks == ACRE_TICKS_X)
538                 cairo_move_to (cr, t, acre->y_axis.min);
539             else
540                 cairo_move_to (cr, acre->x_axis.min, t);
541
542             cairo_identity_matrix (cr);
543
544             if (ticks == ACRE_TICKS_X) {
545                 cairo_rel_line_to (cr, 0, 0.5);
546                 cairo_rel_line_to (cr, 0, -tick_size - 0.5);
547             } else {
548                 cairo_rel_line_to (cr, -0.5, 0);
549                 cairo_rel_line_to (cr, tick_size + 0.5, 0);
550             }
551
552             cairo_set_line_width (cr, 1.0);
553             cairo_stroke (cr);
554         }
555         cairo_restore (cr);
556
557         /* label */
558         if (tick_size == ACRE_TICK_MAJOR_SIZE)
559         {
560             PangoLayout *layout;
561             int width, height;
562
563             cairo_save (cr);
564
565             layout = _create_layout_printf (acre, "%g", t);
566
567             if (ticks == ACRE_TICKS_X)
568                 cairo_move_to (cr, t, acre->y_axis.min);
569             else
570                 cairo_move_to (cr, acre->x_axis.min, t);
571
572             cairo_identity_matrix (cr);
573             pango_layout_get_pixel_size (layout, &width, &height);
574
575             if (ticks == ACRE_TICKS_X)
576                 cairo_rel_move_to (cr, -width / 2, ACRE_X_TICK_VALUE_PAD);
577             else
578                 cairo_rel_move_to (cr, -width - ACRE_Y_TICK_VALUE_PAD,
579                                    -height/2);
580
581             _show_layout (cr, layout);
582
583             cairo_restore (cr);
584         }
585     }
586
587     cairo_restore (cr);
588 }
589
590 static void
591 _draw_frame_and_ticks (acre_t *acre)
592 {
593     cairo_t *cr = acre->cr;
594
595     cairo_save (cr);
596
597     cairo_set_source_rgb (cr, 0, 0, 0); /* black */
598
599     /* ticks */
600     _draw_ticks (acre, acre->x_axis.min, acre->x_axis.max, ACRE_TICKS_X);
601     _draw_ticks (acre, acre->y_axis.min, acre->y_axis.max, ACRE_TICKS_Y);
602
603     /* frame */
604     cairo_rectangle (cr,
605                      acre->chart.x - 0.5, acre->chart.y - 0.5,
606                      acre->chart.width + 1.0, acre->chart.height + 1.0);
607     cairo_set_line_width (cr, 1.0);
608     cairo_stroke (cr);
609
610     cairo_restore (cr);
611 }
612
613 /* Draw the plot to the given cairo context within a user-space
614  * rectangle from (0, 0) to (width, height). This size includes all
615  * space for extra-plot elements (such as the title, the axis labels,
616  * etc.)
617  */
618 void
619 acre_draw (acre_t *acre, cairo_t *cr, int width, int height)
620 {
621     acre->cr = cr;
622
623     acre->width = width;
624     acre->height = height;
625
626     acre->chart.width = width;
627     acre->chart.height = height;
628
629     cairo_save (cr);
630
631     cairo_set_source_rgb (cr, 1, 1, 1);
632
633     /* We compute the axis ranges before doing label layout so that we
634      * can account for the width of the y-axis value labels. */
635     _compute_axis_ranges (acre);
636
637     _draw_title_and_labels (acre);
638
639     /* And we recompute the axis ranges now that the title and axis
640      * label space is all measured and accounted for. */
641     _compute_axis_ranges (acre);
642
643     _draw_data (acre);
644
645     _draw_frame_and_ticks (acre);
646 }
647
648 /* Create a new dataset---a collection of (x, y) datapoints. A single
649  * plot can contain multiple datasets, (see acre_add_data). */
650 acre_data_t *
651 acre_data_create (void)
652 {
653     acre_data_t *data;
654
655     data = xmalloc (sizeof (acre_data_t));
656
657     data->name = NULL;
658
659     data->points = NULL;
660     data->points_size = 0;
661     data->num_points = 0;
662
663     return data;
664 }
665
666 /* Destroy an acre dataset. Do not call this function if the dataset
667  * has been added to an acre_t plot with acre_add_data. */
668 void
669 acre_data_destroy (acre_data_t *data)
670 {
671     free (data->points);
672
673     free (data);
674 }
675
676 /* Set the label for this dataset (to appear in the plot's key). */
677 void
678 acre_data_set_name (acre_data_t *data, const char *name)
679 {
680     free (data->name);
681
682     data->name = strdup (name);
683 }
684
685 /* Add a datapoint to the given dataset. */
686 void
687 acre_data_add_point_2d (acre_data_t *data, double x, double y)
688 {
689     if (data->num_points >= data->points_size) {
690         data->points_size *= 2;
691         if (data->points_size == 0)
692             data->points_size = 16;
693         data->points = xrealloc_ab (data->points,
694                                     data->points_size,
695                                     sizeof (acre_data_point_2d_t));
696     }
697
698     data->points[data->num_points].x = x;
699     data->points[data->num_points].y = y;
700     data->num_points++;
701 }