]> git.tdb.fi Git - ext/subsurface.git/blob - profile.c
Merge branch 'ui' of git://github.com/dirkhh/subsurface
[ext/subsurface.git] / profile.c
1 /* profile.c */
2 /* creates all the necessary data for drawing the dive profile 
3  * uses cairo to draw it
4  */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <string.h>
9 #include <time.h>
10
11 #include "dive.h"
12 #include "display.h"
13 #include "divelist.h"
14
15 int selected_dive = 0;
16
17 typedef enum { STABLE, SLOW, MODERATE, FAST, CRAZY } velocity_t;
18 /* Plot info with smoothing, velocity indication
19  * and one-, two- and three-minute minimums and maximums */
20 struct plot_info {
21         int nr;
22         int maxtime;
23         int meandepth, maxdepth;
24         int minpressure, maxpressure;
25         int endpressure; /* start pressure better be max pressure */
26         int mintemp, maxtemp;
27         struct plot_data {
28                 unsigned int same_cylinder:1;
29                 unsigned int cylinderindex;
30                 int sec;
31                 /* pressure[0] is sensor pressure
32                  * pressure[1] is interpolated pressure */
33                 int pressure[2];
34                 int temperature;
35                 /* Depth info */
36                 int depth;
37                 int smoothed;
38                 velocity_t velocity;
39                 struct plot_data *min[3];
40                 struct plot_data *max[3];
41                 int avg[3];
42         } entry[];
43 };
44 #define SENSOR_PR 0
45 #define INTERPOLATED_PR 1
46 #define SENSOR_PRESSURE(_entry) (_entry)->pressure[SENSOR_PR]
47 #define INTERPOLATED_PRESSURE(_entry) (_entry)->pressure[INTERPOLATED_PR]
48
49 /* convert velocity to colors */
50 typedef struct { double r, g, b; } rgb_t;
51 static const rgb_t rgb[] = {
52         [STABLE]   = {0.0, 0.4, 0.0},
53         [SLOW]     = {0.4, 0.8, 0.0},
54         [MODERATE] = {0.8, 0.8, 0.0},
55         [FAST]     = {0.8, 0.5, 0.0},
56         [CRAZY]    = {1.0, 0.0, 0.0},
57 };
58
59 #define plot_info_size(nr) (sizeof(struct plot_info) + (nr)*sizeof(struct plot_data))
60
61 /* Scale to 0,0 -> maxx,maxy */
62 #define SCALEX(gc,x)  (((x)-gc->leftx)/(gc->rightx-gc->leftx)*gc->maxx)
63 #define SCALEY(gc,y)  (((y)-gc->topy)/(gc->bottomy-gc->topy)*gc->maxy)
64 #define SCALE(gc,x,y) SCALEX(gc,x),SCALEY(gc,y)
65
66 static void move_to(struct graphics_context *gc, double x, double y)
67 {
68         cairo_move_to(gc->cr, SCALE(gc, x, y));
69 }
70
71 static void line_to(struct graphics_context *gc, double x, double y)
72 {
73         cairo_line_to(gc->cr, SCALE(gc, x, y));
74 }
75
76 static void set_source_rgba(struct graphics_context *gc, double r, double g, double b, double a)
77 {
78         /*
79          * For printers, we still honor 'a', but ignore colors
80          * for now. Black is white and white is black
81          */
82         if (gc->printer) {
83                 double sum = r+g+b;
84                 if (sum > 0.8)
85                         r = g = b = 0;
86                 else
87                         r = g = b = 1;
88         }
89         cairo_set_source_rgba(gc->cr, r, g, b, a);
90 }
91
92 void set_source_rgb(struct graphics_context *gc, double r, double g, double b)
93 {
94         set_source_rgba(gc, r, g, b, 1);
95 }
96
97 #define ROUND_UP(x,y) ((((x)+(y)-1)/(y))*(y))
98
99 /*
100  * When showing dive profiles, we scale things to the
101  * current dive. However, we don't scale past less than
102  * 30 minutes or 90 ft, just so that small dives show
103  * up as such.
104  * we also need to add 180 seconds at the end so the min/max
105  * plots correctly
106  */
107 static int get_maxtime(struct plot_info *pi)
108 {
109         int seconds = pi->maxtime;
110         /* min 30 minutes, rounded up to 5 minutes, with at least 2.5 minutes to spare */
111         return MAX(30*60, ROUND_UP(seconds+150, 60*5));
112 }
113
114 static int get_maxdepth(struct plot_info *pi)
115 {
116         unsigned mm = pi->maxdepth;
117         /* Minimum 30m, rounded up to 10m, with at least 3m to spare */
118         return MAX(30000, ROUND_UP(mm+3000, 10000));
119 }
120
121 typedef struct {
122         int size;
123         double r,g,b;
124         double hpos, vpos;
125 } text_render_options_t;
126
127 #define RIGHT (-1.0)
128 #define CENTER (-0.5)
129 #define LEFT (0.0)
130
131 #define TOP (1)
132 #define MIDDLE (0)
133 #define BOTTOM (-1)
134
135 static void plot_text(struct graphics_context *gc, const text_render_options_t *tro,
136                       double x, double y, const char *fmt, ...)
137 {
138         cairo_t *cr = gc->cr;
139         cairo_font_extents_t fe;
140         cairo_text_extents_t extents;
141         double dx, dy;
142         char buffer[80];
143         va_list args;
144
145         va_start(args, fmt);
146         vsnprintf(buffer, sizeof(buffer), fmt, args);
147         va_end(args);
148
149         cairo_set_font_size(cr, tro->size);
150         cairo_font_extents(cr, &fe);
151         cairo_text_extents(cr, buffer, &extents);
152         dx = tro->hpos * extents.width + extents.x_bearing;
153         dy = tro->vpos * extents.height + fe.descent;
154
155         move_to(gc, x, y);
156         cairo_rel_move_to(cr, dx, dy);
157
158         cairo_text_path(cr, buffer);
159         set_source_rgb(gc, 0, 0, 0);
160         cairo_stroke(cr);
161
162         move_to(gc, x, y);
163         cairo_rel_move_to(cr, dx, dy);
164
165         set_source_rgb(gc, tro->r, tro->g, tro->b);
166         cairo_show_text(cr, buffer);
167 }
168
169 static void plot_one_event(struct graphics_context *gc, struct plot_info *pi, struct event *event, const text_render_options_t *tro)
170 {
171         int i, depth = 0;
172         int x,y;
173
174         for (i = 0; i < pi->nr; i++) {
175                 struct plot_data *data = pi->entry + i;
176                 if (event->time.seconds < data->sec)
177                         break;
178                 depth = data->depth;
179         }
180         /* draw a little tirangular marker and attach tooltip */
181         x = SCALEX(gc, event->time.seconds);
182         y = SCALEY(gc, depth);
183         set_source_rgba(gc, 1.0, 1.0, 0.1, 0.8);
184         cairo_move_to(gc->cr, x-15, y+6);
185         cairo_line_to(gc->cr, x-3  , y+6);
186         cairo_line_to(gc->cr, x-9, y-6);
187         cairo_line_to(gc->cr, x-15, y+6);
188         cairo_stroke_preserve(gc->cr);
189         cairo_fill(gc->cr);
190         set_source_rgba(gc, 0.0, 0.0, 0.0, 0.8);
191         cairo_move_to(gc->cr, x-9, y-3);
192         cairo_line_to(gc->cr, x-9, y+1);
193         cairo_move_to(gc->cr, x-9, y+4);
194         cairo_line_to(gc->cr, x-9, y+4);
195         cairo_stroke(gc->cr);
196         attach_tooltip(x-15, y-6, 12, 12, event->name);
197 }
198
199 static void plot_events(struct graphics_context *gc, struct plot_info *pi, struct dive *dive)
200 {
201         static const text_render_options_t tro = {14, 1.0, 0.2, 0.2, CENTER, TOP};
202         struct event *event = dive->events;
203
204         if (gc->printer)
205                 return;
206
207         while (event) {
208                 plot_one_event(gc, pi, event, &tro);
209                 event = event->next;
210         }
211 }
212
213 static void render_depth_sample(struct graphics_context *gc, struct plot_data *entry, const text_render_options_t *tro)
214 {
215         int sec = entry->sec, decimals;
216         double d;
217
218         d = get_depth_units(entry->depth, &decimals, NULL);
219
220         plot_text(gc, tro, sec, entry->depth, "%.*f", decimals, d);
221 }
222
223 static void plot_text_samples(struct graphics_context *gc, struct plot_info *pi)
224 {
225         static const text_render_options_t deep = {14, 1.0, 0.2, 0.2, CENTER, TOP};
226         static const text_render_options_t shallow = {14, 1.0, 0.2, 0.2, CENTER, BOTTOM};
227         int i;
228
229         for (i = 0; i < pi->nr; i++) {
230                 struct plot_data *entry = pi->entry + i;
231
232                 if (entry->depth < 2000)
233                         continue;
234
235                 if (entry == entry->max[2])
236                         render_depth_sample(gc, entry, &deep);
237
238                 if (entry == entry->min[2])
239                         render_depth_sample(gc, entry, &shallow);
240         }
241 }
242
243 static void plot_depth_text(struct graphics_context *gc, struct plot_info *pi)
244 {
245         int maxtime, maxdepth;
246
247         /* Get plot scaling limits */
248         maxtime = get_maxtime(pi);
249         maxdepth = get_maxdepth(pi);
250
251         gc->leftx = 0; gc->rightx = maxtime;
252         gc->topy = 0; gc->bottomy = maxdepth;
253
254         plot_text_samples(gc, pi);
255 }
256
257 static void plot_smoothed_profile(struct graphics_context *gc, struct plot_info *pi)
258 {
259         int i;
260         struct plot_data *entry = pi->entry;
261
262         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
263         move_to(gc, entry->sec, entry->smoothed);
264         for (i = 1; i < pi->nr; i++) {
265                 entry++;
266                 line_to(gc, entry->sec, entry->smoothed);
267         }
268         cairo_stroke(gc->cr);
269 }
270
271 static void plot_minmax_profile_minute(struct graphics_context *gc, struct plot_info *pi,
272                                 int index, double a)
273 {
274         int i;
275         struct plot_data *entry = pi->entry;
276
277         set_source_rgba(gc, 1, 0.2, 1, a);
278         move_to(gc, entry->sec, entry->min[index]->depth);
279         for (i = 1; i < pi->nr; i++) {
280                 entry++;
281                 line_to(gc, entry->sec, entry->min[index]->depth);
282         }
283         for (i = 1; i < pi->nr; i++) {
284                 line_to(gc, entry->sec, entry->max[index]->depth);
285                 entry--;
286         }
287         cairo_close_path(gc->cr);
288         cairo_fill(gc->cr);
289 }
290
291 static void plot_minmax_profile(struct graphics_context *gc, struct plot_info *pi)
292 {
293         if (gc->printer)
294                 return;
295         plot_minmax_profile_minute(gc, pi, 2, 0.1);
296         plot_minmax_profile_minute(gc, pi, 1, 0.1);
297         plot_minmax_profile_minute(gc, pi, 0, 0.1);
298 }
299
300 static void plot_depth_profile(struct graphics_context *gc, struct plot_info *pi)
301 {
302         int i, incr;
303         cairo_t *cr = gc->cr;
304         int sec, depth;
305         struct plot_data *entry;
306         int maxtime, maxdepth, marker;
307         int increments[4] = { 5*60, 10*60, 15*60, 30*60 };
308
309         /* Get plot scaling limits */
310         maxtime = get_maxtime(pi);
311         maxdepth = get_maxdepth(pi);
312
313         /* Time markers: at most every 5 min, but no more than 12 markers
314          * and for convenience we do 5, 10, 15 or 30 min intervals.
315          * This allows for 6h dives - enough (I hope) for even the craziest
316          * divers - but just in case, for those 8h depth-record-breaking dives,
317          * we double the interval if this still doesn't get us to 12 or fewer
318          * time markers */
319         i = 0;
320         while (maxtime / increments[i] > 12 && i < 4)
321                 i++;
322         incr = increments[i];
323         while (maxtime / incr > 12)
324                 incr *= 2;
325
326         gc->leftx = 0; gc->rightx = maxtime;
327         gc->topy = 0; gc->bottomy = 1.0;
328         set_source_rgba(gc, 1, 1, 1, 0.5);
329         for (i = incr; i < maxtime; i += incr) {
330                 move_to(gc, i, 0);
331                 line_to(gc, i, 1);
332         }
333         cairo_stroke(cr);
334
335         /* now the text on every second time marker */
336         text_render_options_t tro = {10, 0.2, 1.0, 0.2, CENTER, TOP};
337         for (i = incr; i < maxtime; i += 2 * incr)
338                 plot_text(gc, &tro, i, 1, "%d", i/60);
339
340         /* Depth markers: every 30 ft or 10 m*/
341         gc->leftx = 0; gc->rightx = 1.0;
342         gc->topy = 0; gc->bottomy = maxdepth;
343         switch (output_units.length) {
344         case METERS: marker = 10000; break;
345         case FEET: marker = 9144; break;        /* 30 ft */
346         }
347
348         set_source_rgba(gc, 1, 1, 1, 0.5);
349         for (i = marker; i < maxdepth; i += marker) {
350                 move_to(gc, 0, i);
351                 line_to(gc, 1, i);
352         }
353         cairo_stroke(cr);
354
355         /* Show mean depth */
356         if (! gc->printer) {
357                 set_source_rgba(gc, 1, 0.2, 0.2, 0.40);
358                 move_to(gc, 0, pi->meandepth);
359                 line_to(gc, 1, pi->meandepth);
360                 cairo_stroke(cr);
361         }
362
363         gc->leftx = 0; gc->rightx = maxtime;
364
365         /*
366          * These are good for debugging text placement etc,
367          * but not for actual display..
368          */
369         if (0) {
370                 plot_smoothed_profile(gc, pi);
371                 plot_minmax_profile(gc, pi);
372         }
373
374         set_source_rgba(gc, 1, 0.2, 0.2, 0.80);
375
376         /* Do the depth profile for the neat fill */
377         gc->topy = 0; gc->bottomy = maxdepth;
378         set_source_rgba(gc, 1, 0.2, 0.2, 0.20);
379
380         entry = pi->entry;
381         move_to(gc, 0, 0);
382         for (i = 0; i < pi->nr; i++, entry++)
383                 line_to(gc, entry->sec, entry->depth);
384         cairo_close_path(gc->cr);
385         if (gc->printer) {
386                 set_source_rgba(gc, 1, 1, 1, 0.2);
387                 cairo_fill_preserve(cr);
388                 set_source_rgb(gc, 1, 1, 1);
389                 cairo_stroke(cr);
390                 return;
391         }
392         cairo_fill(gc->cr);
393
394         /* Now do it again for the velocity colors */
395         entry = pi->entry;
396         for (i = 1; i < pi->nr; i++) {
397                 entry++;
398                 sec = entry->sec;
399                 /* we want to draw the segments in different colors
400                  * representing the vertical velocity, so we need to
401                  * chop this into short segments */
402                 rgb_t color = rgb[entry->velocity];
403                 depth = entry->depth;
404                 set_source_rgb(gc, color.r, color.g, color.b);
405                 move_to(gc, entry[-1].sec, entry[-1].depth);
406                 line_to(gc, sec, depth);
407                 cairo_stroke(cr);
408         }
409 }
410
411 static int setup_temperature_limits(struct graphics_context *gc, struct plot_info *pi)
412 {
413         int maxtime, mintemp, maxtemp, delta;
414
415         /* Get plot scaling limits */
416         maxtime = get_maxtime(pi);
417         mintemp = pi->mintemp;
418         maxtemp = pi->maxtemp;
419
420         gc->leftx = 0; gc->rightx = maxtime;
421         /* Show temperatures in roughly the lower third, but make sure the scale
422            is at least somewhat reasonable */
423         delta = maxtemp - mintemp;
424         if (delta > 3000) { /* more than 3K in fluctuation */
425                 gc->topy = maxtemp + delta*2;
426                 gc->bottomy = mintemp - delta/2;
427         } else {
428                 gc->topy = maxtemp + 1500 + delta*2;
429                 gc->bottomy = mintemp - delta/2;
430         }
431
432         return maxtemp > mintemp;
433 }
434
435 static void plot_single_temp_text(struct graphics_context *gc, int sec, int mkelvin)
436 {
437         int deg;
438         const char *unit;
439         static const text_render_options_t tro = {12, 0.2, 0.2, 1.0, LEFT, TOP};
440         temperature_t temperature = { mkelvin };
441
442         if (output_units.temperature == FAHRENHEIT) {
443                 deg = to_F(temperature);
444                 unit = UTF8_DEGREE "F";
445         } else {
446                 deg = to_C(temperature);
447                 unit = UTF8_DEGREE "C";
448         }
449         plot_text(gc, &tro, sec, temperature.mkelvin, "%d%s", deg, unit);
450 }
451
452 static void plot_temperature_text(struct graphics_context *gc, struct plot_info *pi)
453 {
454         int i;
455         int last = 0, sec = 0;
456         int last_temperature = 0, last_printed_temp = 0;
457
458         if (!setup_temperature_limits(gc, pi))
459                 return;
460
461         for (i = 0; i < pi->nr; i++) {
462                 struct plot_data *entry = pi->entry+i;
463                 int mkelvin = entry->temperature;
464
465                 if (!mkelvin)
466                         continue;
467                 last_temperature = mkelvin;
468                 sec = entry->sec;
469                 if (sec < last + 300)
470                         continue;
471                 last = sec;
472                 plot_single_temp_text(gc,sec,mkelvin);
473                 last_printed_temp = mkelvin;
474         }
475         /* it would be nice to print the end temperature, if it's different */
476         if (abs(last_temperature - last_printed_temp) > 500)
477                 plot_single_temp_text(gc, sec, last_temperature);
478 }
479
480 static void plot_temperature_profile(struct graphics_context *gc, struct plot_info *pi)
481 {
482         int i;
483         cairo_t *cr = gc->cr;
484         int last = 0;
485
486         if (!setup_temperature_limits(gc, pi))
487                 return;
488
489         set_source_rgba(gc, 0.2, 0.2, 1.0, 0.8);
490         for (i = 0; i < pi->nr; i++) {
491                 struct plot_data *entry = pi->entry + i;
492                 int mkelvin = entry->temperature;
493                 int sec = entry->sec;
494                 if (!mkelvin) {
495                         if (!last)
496                                 continue;
497                         mkelvin = last;
498                 }
499                 if (last)
500                         line_to(gc, sec, mkelvin);
501                 else
502                         move_to(gc, sec, mkelvin);
503                 last = mkelvin;
504         }
505         cairo_stroke(cr);
506 }
507
508 /* gets both the actual start and end pressure as well as the scaling factors */
509 static int get_cylinder_pressure_range(struct graphics_context *gc, struct plot_info *pi)
510 {
511         gc->leftx = 0;
512         gc->rightx = get_maxtime(pi);
513
514         gc->bottomy = 0; gc->topy = pi->maxpressure * 1.5;
515         return pi->maxpressure != 0;
516 }
517
518 static void plot_pressure_helper(struct graphics_context *gc, struct plot_info *pi, int type)
519 {
520         int i;
521         int lift_pen = FALSE;
522
523         for (i = 0; i < pi->nr; i++) {
524                 int mbar;
525                 struct plot_data *entry = pi->entry + i;
526
527                 mbar = entry->pressure[type];
528                 if (!entry->same_cylinder)
529                         lift_pen = TRUE;
530                 if (!mbar) {
531                         lift_pen = TRUE;
532                         continue;
533                 }
534                 if (lift_pen) {
535                         if (i > 0 && entry->same_cylinder) {
536                                 /* if we have a previous event from the same tank,
537                                  * draw at least a short line .
538                                  * This uses the implementation detail that the
539                                  * type is either 0 or 1 */
540                                 int prev_pr;
541                                 prev_pr = (entry-1)->pressure[type] ? : (entry-1)->pressure[1 - type];
542                                 move_to(gc, (entry-1)->sec, prev_pr);
543                                 line_to(gc, entry->sec, mbar);
544                         } else
545                                 move_to(gc, entry->sec, mbar);
546                         lift_pen = FALSE;
547                 }
548                 else
549                         line_to(gc, entry->sec, mbar);
550         }
551         cairo_stroke(gc->cr);
552
553 }
554
555 static void plot_cylinder_pressure(struct graphics_context *gc, struct plot_info *pi)
556 {
557         if (!get_cylinder_pressure_range(gc, pi))
558                 return;
559
560         /* first plot the pressure readings we have from the dive computer */
561         set_source_rgba(gc, 0.2, 1.0, 0.2, 0.80);
562         plot_pressure_helper(gc, pi, SENSOR_PR);
563
564         /* then, in a different color, the interpolated values */
565         set_source_rgba(gc, 1.0, 1.0, 0.2, 0.80);
566         plot_pressure_helper(gc, pi, INTERPOLATED_PR);
567 }
568
569 static int mbar_to_PSI(int mbar)
570 {
571         pressure_t p = {mbar};
572         return to_PSI(p);
573 }
574
575 static void plot_pressure_value(struct graphics_context *gc, int mbar, int sec,
576                                 int xalign, int yalign)
577 {
578         int pressure;
579         const char *unit;
580
581         switch (output_units.pressure) {
582         case PASCAL:
583                 pressure = mbar * 100;
584                 unit = "pascal";
585                 break;
586         case BAR:
587                 pressure = (mbar + 500) / 1000;
588                 unit = "bar";
589                 break;
590         case PSI:
591                 pressure = mbar_to_PSI(mbar);
592                 unit = "psi";
593                 break;
594         }
595         text_render_options_t tro = {10, 0.2, 1.0, 0.2, xalign, yalign};
596         plot_text(gc, &tro, sec, mbar, "%d %s", pressure, unit);
597 }
598
599 static void plot_cylinder_pressure_text(struct graphics_context *gc, struct plot_info *pi)
600 {
601         int i;
602         int mbar, cyl;
603         int seen_cyl[MAX_CYLINDERS] = { FALSE, };
604         int last_pressure[MAX_CYLINDERS] = { 0, };
605         int last_time[MAX_CYLINDERS] = { 0, };
606         struct plot_data *entry;
607
608         if (!get_cylinder_pressure_range(gc, pi))
609                 return;
610
611         /* only loop over the actual events from the dive computer */
612         for (i = 2; i < pi->nr - 2; i++) {
613                 entry = pi->entry + i;
614
615                 if (!entry->same_cylinder) {
616                         cyl = entry->cylinderindex;
617                         if (!seen_cyl[cyl]) {
618                                 mbar = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
619                                 plot_pressure_value(gc, mbar, entry->sec, LEFT, BOTTOM);
620                                 seen_cyl[cyl] = TRUE;
621                         }
622                         if (i > 2) {
623                                 /* remember the last pressure and time of
624                                  * the previous cylinder */
625                                 cyl = (entry - 1)->cylinderindex;
626                                 last_pressure[cyl] =
627                                         SENSOR_PRESSURE(entry - 1) ? : INTERPOLATED_PRESSURE(entry - 1);
628                                 last_time[cyl] = (entry - 1)->sec;
629                         }
630                 }
631         }
632         cyl = entry->cylinderindex;
633         last_pressure[cyl] = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
634         last_time[cyl] = entry->sec;
635
636         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
637                 if (last_time[cyl]) {
638                         plot_pressure_value(gc, last_pressure[cyl], last_time[cyl], CENTER, TOP);
639                 }
640         }
641 }
642
643 static void analyze_plot_info_minmax_minute(struct plot_data *entry, struct plot_data *first, struct plot_data *last, int index)
644 {
645         struct plot_data *p = entry;
646         int time = entry->sec;
647         int seconds = 90*(index+1);
648         struct plot_data *min, *max;
649         int avg, nr;
650
651         /* Go back 'seconds' in time */
652         while (p > first) {
653                 if (p[-1].sec < time - seconds)
654                         break;
655                 p--;
656         }
657
658         /* Then go forward until we hit an entry past the time */
659         min = max = p;
660         avg = p->depth;
661         nr = 1;
662         while (++p < last) {
663                 int depth = p->depth;
664                 if (p->sec > time + seconds)
665                         break;
666                 avg += depth;
667                 nr ++;
668                 if (depth < min->depth)
669                         min = p;
670                 if (depth > max->depth)
671                         max = p;
672         }
673         entry->min[index] = min;
674         entry->max[index] = max;
675         entry->avg[index] = (avg + nr/2) / nr;
676 }
677
678 static void analyze_plot_info_minmax(struct plot_data *entry, struct plot_data *first, struct plot_data *last)
679 {
680         analyze_plot_info_minmax_minute(entry, first, last, 0);
681         analyze_plot_info_minmax_minute(entry, first, last, 1);
682         analyze_plot_info_minmax_minute(entry, first, last, 2);
683 }
684
685 static velocity_t velocity(int speed)
686 {
687         velocity_t v;
688
689         if (speed < -304) /* ascent faster than -60ft/min */
690                 v = CRAZY;
691         else if (speed < -152) /* above -30ft/min */
692                 v = FAST;
693         else if (speed < -76) /* -15ft/min */
694                 v = MODERATE;
695         else if (speed < -25) /* -5ft/min */
696                 v = SLOW;
697         else if (speed < 25) /* very hard to find data, but it appears that the recommendations
698                                 for descent are usually about 2x ascent rate; still, we want 
699                                 stable to mean stable */
700                 v = STABLE;
701         else if (speed < 152) /* between 5 and 30ft/min is considered slow */
702                 v = SLOW;
703         else if (speed < 304) /* up to 60ft/min is moderate */
704                 v = MODERATE;
705         else if (speed < 507) /* up to 100ft/min is fast */
706                 v = FAST;
707         else /* more than that is just crazy - you'll blow your ears out */
708                 v = CRAZY;
709
710         return v;
711 }
712 static struct plot_info *analyze_plot_info(struct plot_info *pi)
713 {
714         int i;
715         int nr = pi->nr;
716
717         /* Do pressure min/max based on the non-surface data */
718         for (i = 0; i < nr; i++) {
719                 struct plot_data *entry = pi->entry+i;
720                 int pressure = SENSOR_PRESSURE(entry) ? : INTERPOLATED_PRESSURE(entry);
721                 int temperature = entry->temperature;
722
723                 if (pressure) {
724                         if (!pi->minpressure || pressure < pi->minpressure)
725                                 pi->minpressure = pressure;
726                         if (pressure > pi->maxpressure)
727                                 pi->maxpressure = pressure;
728                 }
729
730                 if (temperature) {
731                         if (!pi->mintemp || temperature < pi->mintemp)
732                                 pi->mintemp = temperature;
733                         if (temperature > pi->maxtemp)
734                                 pi->maxtemp = temperature;
735                 }
736         }
737
738         /* Smoothing function: 5-point triangular smooth */
739         for (i = 2; i < nr; i++) {
740                 struct plot_data *entry = pi->entry+i;
741                 int depth;
742
743                 if (i < nr-2) {
744                         depth = entry[-2].depth + 2*entry[-1].depth + 3*entry[0].depth + 2*entry[1].depth + entry[2].depth;
745                         entry->smoothed = (depth+4) / 9;
746                 }
747                 /* vertical velocity in mm/sec */
748                 /* Linus wants to smooth this - let's at least look at the samples that aren't FAST or CRAZY */
749                 if (entry[0].sec - entry[-1].sec) {
750                         entry->velocity = velocity((entry[0].depth - entry[-1].depth) / (entry[0].sec - entry[-1].sec));
751                         /* if our samples are short and we aren't too FAST*/
752                         if (entry[0].sec - entry[-1].sec < 15 && entry->velocity < FAST) {
753                                 int past = -2;
754                                 while (i+past > 0 && entry[0].sec - entry[past].sec < 15)
755                                         past--;
756                                 entry->velocity = velocity((entry[0].depth - entry[past].depth) / 
757                                                         (entry[0].sec - entry[past].sec));
758                         }
759                 } else
760                         entry->velocity = STABLE;
761         }
762
763         /* One-, two- and three-minute minmax data */
764         for (i = 0; i < nr; i++) {
765                 struct plot_data *entry = pi->entry +i;
766                 analyze_plot_info_minmax(entry, pi->entry, pi->entry+nr);
767         }
768         
769         return pi;
770 }
771
772 /*
773  * simple structure to track the beginning and end tank pressure as
774  * well as the integral of depth over time spent while we have no
775  * pressure reading from the tank */
776 typedef struct pr_track_struct pr_track_t;
777 struct pr_track_struct {
778         int start;
779         int end;
780         int t_start;
781         int t_end;
782         double pressure_time;
783         pr_track_t *next;
784 };
785
786 static pr_track_t *pr_track_alloc(int start, int t_start) {
787         pr_track_t *pt = malloc(sizeof(pr_track_t));
788         pt->start = start;
789         pt->t_start = t_start;
790         pt->end = 0;
791         pt->t_end = 0;
792         pt->pressure_time = 0.0;
793         pt->next = NULL;
794         return pt;
795 }
796
797 /* poor man's linked list */
798 static pr_track_t *list_last(pr_track_t *list)
799 {
800         pr_track_t *tail = list;
801         if (!tail)
802                 return NULL;
803         while (tail->next) {
804                 tail = tail->next;
805         }
806         return tail;
807 }
808
809 static pr_track_t *list_add(pr_track_t *list, pr_track_t *element)
810 {
811         pr_track_t *tail = list_last(list);
812         if (!tail)
813                 return element;
814         tail->next = element;
815         return list;
816 }
817
818 static void list_free(pr_track_t *list)
819 {
820         if (!list)
821                 return;
822         list_free(list->next);
823         free(list);
824 }
825
826 static void fill_missing_tank_pressures(struct dive *dive, struct plot_info *pi,
827                                         pr_track_t **track_pr)
828 {
829         pr_track_t *list = NULL;
830         pr_track_t *nlist = NULL;
831         double pt, magic;
832         int cyl, i;
833         struct plot_data *entry;
834         int cur_pr[MAX_CYLINDERS];
835
836         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) {
837                 cur_pr[cyl] = track_pr[cyl]->start;
838         }
839         for (i = 0; i < dive->samples; i++) {
840                 entry = pi->entry + i + 2;
841                 if (SENSOR_PRESSURE(entry)) {
842                         cur_pr[entry->cylinderindex] = SENSOR_PRESSURE(entry);
843                 } else {
844                         if(!list || list->t_end < entry->sec) {
845                                 nlist = track_pr[entry->cylinderindex];
846                                 list = NULL;
847                                 while (nlist && nlist->t_start <= entry->sec) {
848                                         list = nlist;
849                                         nlist = list->next;
850                                 }
851                                 /* there may be multiple segments - so
852                                  * let's assemble the length */
853                                 nlist = list;
854                                 pt = list->pressure_time;
855                                 while (!nlist->end) {
856                                         nlist = nlist->next;
857                                         if (!nlist) {
858                                                 /* oops - we have no end pressure,
859                                                  * so this means this is a tank without
860                                                  * gas consumption information */
861                                                 break;
862                                         }
863                                         pt += nlist->pressure_time;
864                                 }
865                                 if (!nlist) {
866                                         /* just continue without calculating
867                                          * interpolated values */
868                                         list = NULL;
869                                         continue;
870                                 }
871                                 magic = (nlist->end - cur_pr[entry->cylinderindex]) / pt;                               }
872                         if (pt != 0.0) {
873                                 double cur_pt = (entry->sec - (entry-1)->sec) *
874                                         (1 + entry->depth / 10000.0);
875                                 INTERPOLATED_PRESSURE(entry) =
876                                         cur_pr[entry->cylinderindex] + cur_pt * magic;
877                                 cur_pr[entry->cylinderindex] = INTERPOLATED_PRESSURE(entry);
878                         }
879                 }
880         }
881 }
882
883 static int get_cylinder_index(struct dive *dive, struct event *ev)
884 {
885         int i;
886
887         /*
888          * Try to find a cylinder that matches the O2 percentage
889          * in the gas change event 'value' field.
890          *
891          * Crazy suunto gas change events. We really should do
892          * this in libdivecomputer or something.
893          */
894         for (i = 0; i < MAX_CYLINDERS; i++) {
895                 cylinder_t *cyl = dive->cylinder+i;
896                 int o2 = (cyl->gasmix.o2.permille + 5) / 10;
897                 if (o2 == ev->value)
898                         return i;
899         }
900
901         return 0;
902 }
903
904 static struct event *get_next_gaschange(struct event *event)
905 {
906         while (event) {
907                 if (!strcmp(event->name, "gaschange"))
908                         return event;
909                 event = event->next;
910         }
911         return event;
912 }
913
914 static int set_cylinder_index(struct plot_info *pi, int i, int cylinderindex, unsigned int end)
915 {
916         while (i < pi->nr) {
917                 struct plot_data *entry = pi->entry+i;
918                 if (entry->sec > end)
919                         break;
920                 if (entry->cylinderindex != cylinderindex) {
921                         entry->cylinderindex = cylinderindex;
922                         entry->pressure[0] = 0;
923                 }
924                 i++;
925         }
926         return i;
927 }
928
929 static void check_gas_change_events(struct dive *dive, struct plot_info *pi)
930 {
931         int i = 0, cylinderindex = 0;
932         struct event *ev = get_next_gaschange(dive->events);
933
934         if (!ev)
935                 return;
936
937         do {
938                 i = set_cylinder_index(pi, i, cylinderindex, ev->time.seconds);
939                 cylinderindex = get_cylinder_index(dive, ev);
940                 ev = get_next_gaschange(ev->next);
941         } while (ev);
942         set_cylinder_index(pi, i, cylinderindex, ~0u);
943 }
944
945 /*
946  * Create a plot-info with smoothing and ranged min/max
947  *
948  * This also makes sure that we have extra empty events on both
949  * sides, so that you can do end-points without having to worry
950  * about it.
951  */
952 static struct plot_info *create_plot_info(struct dive *dive)
953 {
954         int cylinderindex = -1;
955         int lastdepth, lastindex;
956         int i, nr = dive->samples + 4, sec, cyl;
957         size_t alloc_size = plot_info_size(nr);
958         struct plot_info *pi;
959         pr_track_t *track_pr[MAX_CYLINDERS] = {NULL, };
960         pr_track_t *pr_track, *current;
961         gboolean missing_pr = FALSE;
962         struct plot_data *entry;
963
964         pi = malloc(alloc_size);
965         if (!pi)
966                 return pi;
967         memset(pi, 0, alloc_size);
968         pi->nr = nr;
969         sec = 0;
970         lastindex = 0;
971         lastdepth = -1;
972         for (i = 0; i < dive->samples; i++) {
973                 int depth;
974                 struct sample *sample = dive->sample+i;
975
976                 entry = pi->entry + i + 2;
977                 sec = entry->sec = sample->time.seconds;
978                 depth = entry->depth = sample->depth.mm;
979                 entry->cylinderindex = sample->cylinderindex;
980                 SENSOR_PRESSURE(entry) = sample->cylinderpressure.mbar;
981                 entry->temperature = sample->temperature.mkelvin;
982
983                 if (depth || lastdepth)
984                         lastindex = i+2;
985
986                 lastdepth = depth;
987                 if (depth > pi->maxdepth)
988                         pi->maxdepth = depth;
989         }
990
991         check_gas_change_events(dive, pi);
992
993         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) /* initialize the start pressures */
994                 track_pr[cyl] = pr_track_alloc(dive->cylinder[cyl].start.mbar, -1);
995         current = track_pr[dive->sample[0].cylinderindex];
996         for (i = 0; i < dive->samples; i++) {
997                 entry = pi->entry + i + 2;
998
999                 entry->same_cylinder = entry->cylinderindex == cylinderindex;
1000                 cylinderindex = entry->cylinderindex;
1001
1002                 /* track the segments per cylinder and their pressure/time integral */
1003                 if (!entry->same_cylinder) {
1004                         current->end = SENSOR_PRESSURE(entry-1);
1005                         current->t_end = (entry-1)->sec;
1006                         current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1007                         track_pr[cylinderindex] = list_add(track_pr[cylinderindex], current);
1008                 } else { /* same cylinder */
1009                         if ((!SENSOR_PRESSURE(entry) && SENSOR_PRESSURE(entry-1)) ||
1010                                 (SENSOR_PRESSURE(entry) && !SENSOR_PRESSURE(entry-1))) {
1011                                 /* transmitter changed its working status */
1012                                 current->end = SENSOR_PRESSURE(entry-1);
1013                                 current->t_end = (entry-1)->sec;
1014                                 current = pr_track_alloc(SENSOR_PRESSURE(entry), entry->sec);
1015                                 track_pr[cylinderindex] =
1016                                         list_add(track_pr[cylinderindex], current);
1017                         }
1018                 }
1019                 /* finally, do the discrete integration to get the SAC rate equivalent */
1020                 current->pressure_time += (entry->sec - (entry-1)->sec) *
1021                                                 (1 + entry->depth / 10000.0);
1022                 missing_pr |= !SENSOR_PRESSURE(entry);
1023         }
1024
1025         current->t_end = entry->sec;
1026         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++) { /* initialize the end pressures */
1027                 int pr = dive->cylinder[cyl].end.mbar;
1028                 if (pr && track_pr[cyl]) {
1029                         pr_track = list_last(track_pr[cyl]);
1030                         pr_track->end = pr;
1031                 }
1032         }
1033         if (lastdepth)
1034                 lastindex = i + 2;
1035         /* Fill in the last two entries with empty values but valid times */
1036         i = dive->samples + 2;
1037         pi->entry[i].sec = sec + 20;
1038         pi->entry[i+1].sec = sec + 40;
1039         pi->nr = lastindex+1;
1040         pi->maxtime = pi->entry[lastindex].sec;
1041
1042         pi->endpressure = pi->minpressure = dive->cylinder[0].end.mbar;
1043         pi->maxpressure = dive->cylinder[0].start.mbar;
1044
1045         pi->meandepth = dive->meandepth.mm;
1046
1047         if (missing_pr) {
1048                 fill_missing_tank_pressures(dive, pi, track_pr);
1049         }
1050         for (cyl = 0; cyl < MAX_CYLINDERS; cyl++)
1051                 list_free(track_pr[cyl]);
1052         return analyze_plot_info(pi);
1053 }
1054
1055 void plot(struct graphics_context *gc, cairo_rectangle_int_t *drawing_area, struct dive *dive)
1056 {
1057         struct plot_info *pi = create_plot_info(dive);
1058
1059         cairo_translate(gc->cr, drawing_area->x, drawing_area->y);
1060         cairo_set_line_width(gc->cr, 2);
1061         cairo_set_line_cap(gc->cr, CAIRO_LINE_CAP_ROUND);
1062         cairo_set_line_join(gc->cr, CAIRO_LINE_JOIN_ROUND);
1063
1064         /*
1065          * We can use "cairo_translate()" because that doesn't
1066          * scale line width etc. But the actual scaling we need
1067          * do set up ourselves..
1068          *
1069          * Snif. What a pity.
1070          */
1071         gc->maxx = (drawing_area->width - 2*drawing_area->x);
1072         gc->maxy = (drawing_area->height - 2*drawing_area->y);
1073
1074         /* Temperature profile */
1075         plot_temperature_profile(gc, pi);
1076
1077         /* Cylinder pressure plot */
1078         plot_cylinder_pressure(gc, pi);
1079
1080         /* Depth profile */
1081         plot_depth_profile(gc, pi);
1082         plot_events(gc, pi, dive);
1083
1084         /* Text on top of all graphs.. */
1085         plot_temperature_text(gc, pi);
1086         plot_depth_text(gc, pi);
1087         plot_cylinder_pressure_text(gc, pi);
1088
1089         /* Bounding box last */
1090         gc->leftx = 0; gc->rightx = 1.0;
1091         gc->topy = 0; gc->bottomy = 1.0;
1092
1093         set_source_rgb(gc, 1, 1, 1);
1094         move_to(gc, 0, 0);
1095         line_to(gc, 0, 1);
1096         line_to(gc, 1, 1);
1097         line_to(gc, 1, 0);
1098         cairo_close_path(gc->cr);
1099         cairo_stroke(gc->cr);
1100
1101         free(pi);
1102 }