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