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