]> git.tdb.fi Git - ext/subsurface.git/blob - dive.c
Merge branch 'change_quit2' of http://ambre.pingoured.fr/cgit/subsurface
[ext/subsurface.git] / dive.c
1 /* dive.c */
2 /* maintains the internal dive list structure */
3 #include <string.h>
4 #include <stdio.h>
5
6 #include "dive.h"
7
8 void add_event(struct dive *dive, int time, int type, int flags, int value, const char *name)
9 {
10         struct event *ev, **p;
11         unsigned int size, len = strlen(name);
12
13         size = sizeof(*ev) + len + 1;
14         ev = malloc(size);
15         if (!ev)
16                 return;
17         memset(ev, 0, size);
18         memcpy(ev->name, name, len);
19         ev->time.seconds = time;
20         ev->type = type;
21         ev->flags = flags;
22         ev->value = value;
23         ev->next = NULL;
24
25         p = &dive->events;
26         while (*p)
27                 p = &(*p)->next;
28         *p = ev;
29         remember_event(name);
30 }
31
32 int get_pressure_units(unsigned int mb, const char **units)
33 {
34         int pressure;
35         const char* unit;
36
37         switch (output_units.pressure) {
38         case PASCAL:
39                 pressure = mb * 100;
40                 unit = "pascal";
41                 break;
42         case BAR:
43                 pressure = (mb + 500) / 1000;
44                 unit = "bar";
45                 break;
46         case PSI:
47                 pressure = mbar_to_PSI(mb);
48                 unit = "psi";
49                 break;
50         }
51         if (units)
52                 *units = unit;
53         return pressure;
54 }
55
56 double get_temp_units(unsigned int mk, const char **units)
57 {
58         double deg;
59         const char *unit;
60
61         if (output_units.temperature == FAHRENHEIT) {
62                 deg = mkelvin_to_F(mk);
63                 unit = UTF8_DEGREE "F";
64         } else {
65                 deg = mkelvin_to_C(mk);
66                 unit = UTF8_DEGREE "C";
67         }
68         if (units)
69                 *units = unit;
70         return deg;
71 }
72
73 double get_volume_units(unsigned int ml, int *frac, const char **units)
74 {
75         int decimals;
76         double vol;
77         const char *unit;
78
79         switch (output_units.volume) {
80         case LITER:
81                 vol = ml / 1000.0;
82                 unit = "l";
83                 decimals = 1;
84                 break;
85         case CUFT:
86                 vol = ml_to_cuft(ml);
87                 unit = "cuft";
88                 decimals = 2;
89                 break;
90         }
91         if (frac)
92                 *frac = decimals;
93         if (units)
94                 *units = unit;
95         return vol;
96 }
97
98 double get_depth_units(unsigned int mm, int *frac, const char **units)
99 {
100         int decimals;
101         double d;
102         const char *unit;
103
104         switch (output_units.length) {
105         case METERS:
106                 d = mm / 1000.0;
107                 unit = "m";
108                 decimals = d < 20;
109                 break;
110         case FEET:
111                 d = mm_to_feet(mm);
112                 unit = "ft";
113                 decimals = 0;
114                 break;
115         }
116         if (frac)
117                 *frac = decimals;
118         if (units)
119                 *units = unit;
120         return d;
121 }
122
123 double get_weight_units(unsigned int grams, int *frac, const char **units)
124 {
125         int decimals;
126         double value;
127         const char* unit;
128
129         if (output_units.weight == LBS) {
130                 value = grams_to_lbs(grams);
131                 unit = "lbs";
132                 decimals = 0;
133         } else {
134                 value = grams / 1000.0;
135                 unit = "kg";
136                 decimals = 1;
137         }
138         if (frac)
139                 *frac = decimals;
140         if (units)
141                 *units = unit;
142         return value;
143 }
144
145 struct dive *alloc_dive(void)
146 {
147         const int initial_samples = 5;
148         unsigned int size;
149         struct dive *dive;
150
151         size = dive_size(initial_samples);
152         dive = malloc(size);
153         if (!dive)
154                 exit(1);
155         memset(dive, 0, size);
156         dive->alloc_samples = initial_samples;
157         return dive;
158 }
159
160 struct sample *prepare_sample(struct dive **divep)
161 {
162         struct dive *dive = *divep;
163         if (dive) {
164                 int nr = dive->samples;
165                 int alloc_samples = dive->alloc_samples;
166                 struct sample *sample;
167                 if (nr >= alloc_samples) {
168                         unsigned int size;
169
170                         alloc_samples = (alloc_samples * 3)/2 + 10;
171                         size = dive_size(alloc_samples);
172                         dive = realloc(dive, size);
173                         if (!dive)
174                                 return NULL;
175                         dive->alloc_samples = alloc_samples;
176                         *divep = dive;
177                 }
178                 sample = dive->sample + nr;
179                 memset(sample, 0, sizeof(*sample));
180                 return sample;
181         }
182         return NULL;
183 }
184
185 void finish_sample(struct dive *dive)
186 {
187         dive->samples++;
188 }
189
190 /*
191  * So when we re-calculate maxdepth and meandepth, we will
192  * not override the old numbers if they are close to the
193  * new ones.
194  *
195  * Why? Because a dive computer may well actually track the
196  * max depth and mean depth at finer granularity than the
197  * samples it stores. So it's possible that the max and mean
198  * have been reported more correctly originally.
199  *
200  * Only if the values calculated from the samples are clearly
201  * different do we override the normal depth values.
202  *
203  * This considers 1m to be "clearly different". That's
204  * a totally random number.
205  */
206 static void update_depth(depth_t *depth, int new)
207 {
208         if (new) {
209                 int old = depth->mm;
210
211                 if (abs(old - new) > 1000)
212                         depth->mm = new;
213         }
214 }
215
216 static void update_duration(duration_t *duration, int new)
217 {
218         if (new)
219                 duration->seconds = new;
220 }
221
222 static void update_temperature(temperature_t *temperature, int new)
223 {
224         if (new) {
225                 int old = temperature->mkelvin;
226
227                 if (abs(old - new) > 1000)
228                         temperature->mkelvin = new;
229         }
230 }
231
232 static void fixup_pressure(struct dive *dive, struct sample *sample)
233 {
234         unsigned int pressure, index;
235         cylinder_t *cyl;
236
237         pressure = sample->cylinderpressure.mbar;
238         if (!pressure)
239                 return;
240         index = sample->cylinderindex;
241         if (index >= MAX_CYLINDERS)
242                 return;
243         cyl = dive->cylinder + index;
244         if (!cyl->sample_start.mbar)
245                 cyl->sample_start.mbar = pressure;
246         cyl->sample_end.mbar = pressure;
247 }
248
249 /*
250  * If the cylinder tank pressures are within half a bar
251  * (about 8 PSI) of the sample pressures, we consider it
252  * to be a rounding error, and throw them away as redundant.
253  */
254 static int same_rounded_pressure(pressure_t a, pressure_t b)
255 {
256         return abs(a.mbar - b.mbar) <= 500;
257 }
258
259 static void sanitize_gasmix(struct gasmix *mix)
260 {
261         unsigned int o2, he;
262
263         o2 = mix->o2.permille;
264         he = mix->he.permille;
265
266         /* Regular air: leave empty */
267         if (!he) {
268                 if (!o2)
269                         return;
270                 /* 20.9% or 21% O2 is just air */
271                 if (o2 >= 209 && o2 <= 210) {
272                         mix->o2.permille = 0;
273                         return;
274                 }
275         }
276
277         /* Sane mix? */
278         if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
279                 return;
280         fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
281         memset(mix, 0, sizeof(*mix));
282 }
283
284 /*
285  * See if the size/workingpressure looks like some standard cylinder
286  * size, eg "AL80".
287  */
288 static void match_standard_cylinder(cylinder_type_t *type)
289 {
290         double cuft;
291         int psi, len;
292         const char *fmt;
293         char buffer[20], *p;
294
295         /* Do we already have a cylinder description? */
296         if (type->description)
297                 return;
298
299         cuft = ml_to_cuft(type->size.mliter);
300         cuft *= to_ATM(type->workingpressure);
301         psi = to_PSI(type->workingpressure);
302
303         switch (psi) {
304         case 2300 ... 2500:     /* 2400 psi: LP tank */
305                 fmt = "LP%d";
306                 break;
307         case 2600 ... 2700:     /* 2640 psi: LP+10% */
308                 fmt = "LP%d";
309                 break;
310         case 2900 ... 3100:     /* 3000 psi: ALx tank */
311                 fmt = "AL%d";
312                 break;
313         case 3400 ... 3500:     /* 3442 psi: HP tank */
314                 fmt = "HP%d";
315                 break;
316         case 3700 ... 3850:     /* HP+10% */
317                 fmt = "HP%d+";
318                 break;
319         default:
320                 return;
321         }
322         len = snprintf(buffer, sizeof(buffer), fmt, (int) (cuft+0.5));
323         p = malloc(len+1);
324         if (!p)
325                 return;
326         memcpy(p, buffer, len+1);
327         type->description = p;
328 }
329
330
331 /*
332  * There are two ways to give cylinder size information:
333  *  - total amount of gas in cuft (depends on working pressure and physical size)
334  *  - physical size
335  *
336  * where "physical size" is the one that actually matters and is sane.
337  *
338  * We internally use physical size only. But we save the workingpressure
339  * so that we can do the conversion if required.
340  */
341 static void sanitize_cylinder_type(cylinder_type_t *type)
342 {
343         double volume_of_air, atm, volume;
344
345         /* If we have no working pressure, it had *better* be just a physical size! */
346         if (!type->workingpressure.mbar)
347                 return;
348
349         /* No size either? Nothing to go on */
350         if (!type->size.mliter)
351                 return;
352
353         if (input_units.volume == CUFT) {
354                 /* confusing - we don't really start from ml but millicuft !*/
355                 volume_of_air = cuft_to_l(type->size.mliter);
356                 atm = to_ATM(type->workingpressure);            /* working pressure in atm */
357                 volume = volume_of_air / atm;                   /* milliliters at 1 atm: "true size" */
358                 type->size.mliter = volume + 0.5;
359         }
360
361         /* Ok, we have both size and pressure: try to match a description */
362         match_standard_cylinder(type);
363 }
364
365 static void sanitize_cylinder_info(struct dive *dive)
366 {
367         int i;
368
369         for (i = 0; i < MAX_CYLINDERS; i++) {
370                 sanitize_gasmix(&dive->cylinder[i].gasmix);
371                 sanitize_cylinder_type(&dive->cylinder[i].type);
372         }
373 }
374
375 struct dive *fixup_dive(struct dive *dive)
376 {
377         int i,j;
378         double depthtime = 0;
379         int lasttime = 0;
380         int lastindex = -1;
381         int start = -1, end = -1;
382         int maxdepth = 0, mintemp = 0;
383         int lastdepth = 0;
384         int lasttemp = 0, lastpressure = 0;
385         int pressure_delta[MAX_CYLINDERS] = {INT_MAX, };
386
387         sanitize_cylinder_info(dive);
388         for (i = 0; i < dive->samples; i++) {
389                 struct sample *sample = dive->sample + i;
390                 int time = sample->time.seconds;
391                 int depth = sample->depth.mm;
392                 int temp = sample->temperature.mkelvin;
393                 int pressure = sample->cylinderpressure.mbar;
394                 int index = sample->cylinderindex;
395
396                 if (index == lastindex) {
397                         /* Remove duplicate redundant pressure information */
398                         if (pressure == lastpressure)
399                                 sample->cylinderpressure.mbar = 0;
400                         /* check for simply linear data in the samples
401                            +INT_MAX means uninitialized, -INT_MAX means not linear */
402                         if (pressure_delta[index] != -INT_MAX && lastpressure) {
403                                 if (pressure_delta[index] == INT_MAX) {
404                                         pressure_delta[index] = abs(pressure - lastpressure);
405                                 } else {
406                                         int cur_delta = abs(pressure - lastpressure);
407                                         if (cur_delta && abs(cur_delta - pressure_delta[index]) > 150) {
408                                                 /* ok the samples aren't just a linearisation
409                                                  * between start and end */
410                                                 pressure_delta[index] = -INT_MAX;
411                                         }
412                                 }
413                         }
414                 }
415                 lastindex = index;
416                 lastpressure = pressure;
417
418                 if (lastdepth)
419                         end = time;
420
421                 if (depth) {
422                         if (start < 0)
423                                 start = lasttime;
424                         if (depth > maxdepth)
425                                 maxdepth = depth;
426                 }
427
428                 fixup_pressure(dive, sample);
429
430                 if (temp) {
431                         /*
432                          * If we have consecutive identical
433                          * temperature readings, throw away
434                          * the redundant ones.
435                          */
436                         if (lasttemp == temp)
437                                 sample->temperature.mkelvin = 0;
438                         else
439                                 lasttemp = temp;
440
441                         if (!mintemp || temp < mintemp)
442                                 mintemp = temp;
443                 }
444                 depthtime += (time - lasttime) * (lastdepth + depth) / 2;
445                 lastdepth = depth;
446                 lasttime = time;
447         }
448         /* if all the samples for a cylinder have pressure data that
449          * is basically equidistant throw out the sample cylinder pressure
450          * information but make sure we still have a valid start and end
451          * pressure
452          * this happens when DivingLog decides to linearalize the
453          * pressure between beginning and end and for strange reasons
454          * decides to put that in the sample data as if it came from
455          * the dive computer; we don't want that (we'll visualize with
456          * constant SAC rate instead)
457          * WARNING WARNING - I have only seen this in single tank dives
458          * --- maybe I should try to create a multi tank dive and see what
459          * --- divinglog does there - but the code right now is only tested
460          * --- for the single tank case */
461         for (j = 0; j < MAX_CYLINDERS; j++) {
462                 if (abs(pressure_delta[j]) != INT_MAX) {
463                         cylinder_t *cyl = dive->cylinder + j;
464                         for (i = 0; i < dive->samples; i++)
465                                 if (dive->sample[i].cylinderindex == j)
466                                         dive->sample[i].cylinderpressure.mbar = 0;
467                         if (! cyl->start.mbar)
468                                 cyl->start.mbar = cyl->sample_start.mbar;
469                         if (! cyl->end.mbar)
470                                 cyl->end.mbar = cyl->sample_end.mbar;
471                         cyl->sample_start.mbar = 0;
472                         cyl->sample_end.mbar = 0;
473                 }
474         }
475         if (end < 0)
476                 return dive;
477
478         update_duration(&dive->duration, end - start);
479         if (start != end)
480                 depthtime /= (end - start);
481
482         update_depth(&dive->meandepth, depthtime);
483         update_temperature(&dive->watertemp, mintemp);
484         update_depth(&dive->maxdepth, maxdepth);
485
486         add_people(dive->buddy);
487         add_people(dive->divemaster);
488         add_location(dive->location);
489         add_suit(dive->suit);
490         for (i = 0; i < MAX_CYLINDERS; i++) {
491                 cylinder_t *cyl = dive->cylinder + i;
492                 add_cylinder_description(&cyl->type);
493                 if (same_rounded_pressure(cyl->sample_start, cyl->start))
494                         cyl->start.mbar = 0;
495                 if (same_rounded_pressure(cyl->sample_end, cyl->end))
496                         cyl->end.mbar = 0;
497         }
498         for (i = 0; i < MAX_WEIGHTSYSTEMS; i++) {
499                 weightsystem_t *ws = dive->weightsystem + i;
500                 add_weightsystem_description(ws);
501         }
502
503         return dive;
504 }
505
506 /* Don't pick a zero for MERGE_MIN() */
507 #define MERGE_MAX(res, a, b, n) res->n = MAX(a->n, b->n)
508 #define MERGE_MIN(res, a, b, n) res->n = (a->n)?(b->n)?MIN(a->n, b->n):(a->n):(b->n)
509 #define MERGE_TXT(res, a, b, n) res->n = merge_text(a->n, b->n)
510 #define MERGE_NONZERO(res, a, b, n) res->n = a->n ? a->n : b->n
511
512 static struct dive *add_sample(struct sample *sample, int time, struct dive *dive)
513 {
514         struct sample *p = prepare_sample(&dive);
515
516         if (!p)
517                 return NULL;
518         *p = *sample;
519         p->time.seconds = time;
520         finish_sample(dive);
521         return dive;
522 }
523
524 /*
525  * Merge samples. Dive 'a' is "offset" seconds before Dive 'b'
526  */
527 static struct dive *merge_samples(struct dive *res, struct dive *a, struct dive *b, int offset)
528 {
529         int asamples = a->samples;
530         int bsamples = b->samples;
531         struct sample *as = a->sample;
532         struct sample *bs = b->sample;
533
534         for (;;) {
535                 int at, bt;
536                 struct sample sample;
537
538                 if (!res)
539                         return NULL;
540
541                 at = asamples ? as->time.seconds : -1;
542                 bt = bsamples ? bs->time.seconds + offset : -1;
543
544                 /* No samples? All done! */
545                 if (at < 0 && bt < 0)
546                         return fixup_dive(res);
547
548                 /* Only samples from a? */
549                 if (bt < 0) {
550 add_sample_a:
551                         res = add_sample(as, at, res);
552                         as++;
553                         asamples--;
554                         continue;
555                 }
556
557                 /* Only samples from b? */
558                 if (at < 0) {
559 add_sample_b:
560                         res = add_sample(bs, bt, res);
561                         bs++;
562                         bsamples--;
563                         continue;
564                 }
565
566                 if (at < bt)
567                         goto add_sample_a;
568                 if (at > bt)
569                         goto add_sample_b;
570
571                 /* same-time sample: add a merged sample. Take the non-zero ones */
572                 sample = *bs;
573                 if (as->depth.mm)
574                         sample.depth = as->depth;
575                 if (as->temperature.mkelvin)
576                         sample.temperature = as->temperature;
577                 if (as->cylinderpressure.mbar)
578                         sample.cylinderpressure = as->cylinderpressure;
579                 if (as->cylinderindex)
580                         sample.cylinderindex = as->cylinderindex;
581
582                 res = add_sample(&sample, at, res);
583
584                 as++;
585                 bs++;
586                 asamples--;
587                 bsamples--;
588         }
589 }
590
591 static char *merge_text(const char *a, const char *b)
592 {
593         char *res;
594
595         if (!a || !*a)
596                 return (char *)b;
597         if (!b || !*b)
598                 return (char *)a;
599         if (!strcmp(a,b))
600                 return (char *)a;
601         res = malloc(strlen(a) + strlen(b) + 9);
602         if (!res)
603                 return (char *)a;
604         sprintf(res, "(%s) or (%s)", a, b);
605         return res;
606 }
607
608 #define SORT(a,b,field) \
609         if (a->field != b->field) return a->field < b->field ? -1 : 1
610
611 static int sort_event(struct event *a, struct event *b)
612 {
613         SORT(a,b,time.seconds);
614         SORT(a,b,type);
615         SORT(a,b,flags);
616         SORT(a,b,value);
617         return strcmp(a->name, b->name);
618 }
619
620 static void merge_events(struct dive *res, struct dive *src1, struct dive *src2, int offset)
621 {
622         struct event *a, *b;
623         struct event **p = &res->events;
624
625         a = src1->events;
626         b = src2->events;
627         while (b) {
628                 b->time.seconds += offset;
629                 b = b->next;
630         }
631         b = src2->events;
632
633         while (a || b) {
634                 int s;
635                 if (!b) {
636                         *p = a;
637                         break;
638                 }
639                 if (!a) {
640                         *p = b;
641                         break;
642                 }
643                 s = sort_event(a, b);
644                 /* Pick b */
645                 if (s > 0) {
646                         *p = b;
647                         p = &b->next;
648                         b = b->next;
649                         continue;
650                 }
651                 /* Pick 'a' or neither */
652                 if (s < 0) {
653                         *p = a;
654                         p = &a->next;
655                 }
656                 a = a->next;
657                 continue;
658         }
659 }
660
661 /* Pick whichever has any info (if either). Prefer 'a' */
662 static void merge_cylinder_type(cylinder_type_t *res, cylinder_type_t *a, cylinder_type_t *b)
663 {
664         if (a->size.mliter)
665                 b = a;
666         *res = *b;
667 }
668
669 static void merge_cylinder_mix(struct gasmix *res, struct gasmix *a, struct gasmix *b)
670 {
671         if (a->o2.permille)
672                 b = a;
673         *res = *b;
674 }
675
676 static void merge_cylinder_info(cylinder_t *res, cylinder_t *a, cylinder_t *b)
677 {
678         merge_cylinder_type(&res->type, &a->type, &b->type);
679         merge_cylinder_mix(&res->gasmix, &a->gasmix, &b->gasmix);
680         MERGE_MAX(res, a, b, start.mbar);
681         MERGE_MIN(res, a, b, end.mbar);
682 }
683
684 /*
685  * This could do a lot more merging. Right now it really only
686  * merges almost exact duplicates - something that happens easily
687  * with overlapping dive downloads.
688  */
689 struct dive *try_to_merge(struct dive *a, struct dive *b)
690 {
691         int i;
692         struct dive *res;
693
694         if ((a->when >= b->when + 60) || (a->when <= b->when - 60))
695                 return NULL;
696
697         res = alloc_dive();
698
699         res->when = a->when;
700         MERGE_NONZERO(res, a, b, latitude);
701         MERGE_NONZERO(res, a, b, longitude);
702         MERGE_TXT(res, a, b, location);
703         MERGE_TXT(res, a, b, notes);
704         MERGE_TXT(res, a, b, buddy);
705         MERGE_TXT(res, a, b, divemaster);
706         MERGE_MAX(res, a, b, rating);
707         MERGE_TXT(res, a, b, suit);
708         MERGE_MAX(res, a, b, number);
709         MERGE_MAX(res, a, b, maxdepth.mm);
710         res->meandepth.mm = 0;
711         MERGE_MAX(res, a, b, duration.seconds);
712         MERGE_MAX(res, a, b, surfacetime.seconds);
713         MERGE_MAX(res, a, b, airtemp.mkelvin);
714         MERGE_MIN(res, a, b, watertemp.mkelvin);
715         for (i = 0; i < MAX_CYLINDERS; i++)
716                 merge_cylinder_info(res->cylinder+i, a->cylinder + i, b->cylinder + i);
717         merge_events(res, a, b, 0);
718         return merge_samples(res, a, b, 0);
719 }