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