]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
Tidy up the autoconf/automake configuration a bit.
[simgear.git] / simgear / timing / sg_time.cxx
1 // sg_time.cxx -- data structures and routines for managing time related stuff.
2 //
3 // Written by Curtis Olson, started August 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
6 //
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // Library General Public License for more details.
16 //
17 // You should have received a copy of the GNU Library General Public
18 // License along with this library; if not, write to the
19 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 // Boston, MA  02111-1307, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #include <errno.h>              // for errno
32
33 #ifdef SG_HAVE_STD_INCLUDES
34 #  include <cstdio>
35 #  include <cstdlib>
36 #  include <ctime>
37 #else
38 #  include <math.h>
39 #  include <stdio.h>
40 #  include <stdlib.h>
41 #endif
42
43 #ifdef HAVE_SYS_TIME_H
44 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
45 #endif
46 #ifdef HAVE_SYS_TIMEB_H
47 #  include <sys/timeb.h> // for ftime() and struct timeb
48 #endif
49 #ifdef HAVE_UNISTD_H
50 #  include <unistd.h>    // for gettimeofday()
51 #endif
52
53 #include <math.h>        // for NAN
54
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/misc/sg_path.hxx>
58
59 #include "sg_time.hxx"
60 #include "timezone.h"
61 #include "lowleveltime.h"
62
63
64 #define DEGHR(x)        ((x)/15.)
65 #define RADHR(x)        DEGHR(x*SGD_RADIANS_TO_DEGREES)
66
67
68 static const double MJD0    = 2415020.0;
69 static const double J2000   = 2451545.0 - MJD0;
70 static const double SIDRATE = 0.9972695677;
71
72
73 void SGTime::init( double lon, double lat,
74                    const string& root, time_t init_time )
75 {
76     SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
77
78     gst_diff = -9999.0;
79
80     if ( init_time ) {
81         cur_time = init_time;
82     } else {
83         cur_time = time(NULL); 
84     }
85
86     cout << "Current greenwich mean time = " << asctime(gmtime(&cur_time))
87          << endl;
88     cout << "Current local time          = " 
89          << asctime(localtime(&cur_time)) << endl;
90
91     if ( !root.empty()) {
92         SGPath zone( root );
93         zone.append( "zone.tab" );
94         SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
95                 << zone.str() );
96         tzContainer = new TimezoneContainer( zone.c_str() );
97
98         GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
99         GeoCoord* nearestTz = tzContainer->getNearest(location);
100
101         SGPath name( root );
102         name.append( nearestTz->getDescription() );
103         zonename = strdup( name.c_str() );
104         SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
105     } else {
106         SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
107         tzContainer = NULL;
108         zonename = NULL;
109     }
110 }
111
112 SGTime::SGTime( double lon, double lat, const string& root, time_t init_time )
113 {
114     init( lon, lat, root, init_time );
115 }
116
117
118 SGTime::SGTime( const string& root ) {
119     init( 0.0, 0.0, root, 0 );
120 }
121
122
123 SGTime::SGTime() {
124     init( 0.0, 0.0, "", 0 );
125 }
126
127
128 SGTime::~SGTime()
129 {
130     if ( tzContainer != NULL ) {
131         TimezoneContainer *tmp = tzContainer;
132         tzContainer = NULL;
133         delete tmp;
134     }
135
136     if ( zonename != NULL ) {
137         char *tmp = zonename;
138         zonename = NULL;
139         free(tmp);
140     }
141 }
142
143
144 // given Julian Date and Longitude (decimal degrees West) compute
145 // Local Sidereal Time, in decimal hours.
146 //
147 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
148 static double sidereal_precise( double mjd, double lng )
149 {
150     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
151        mjd + MJD0, lng); */
152
153     // convert to required internal units
154     lng *= SGD_DEGREES_TO_RADIANS;
155
156     // compute LST and print
157     double gst = sgTimeCalcGST( mjd );
158     double lst = gst - RADHR( lng );
159     lst -= 24.0 * floor( lst / 24.0 );
160     // printf ("%7.4f\n", lstTmp);
161
162     return lst;
163 }
164
165
166 // return a courser but cheaper estimate of sidereal time
167 static double sidereal_course( time_t cur_time, const struct tm *gmt, double lng )
168 {
169     time_t start_gmt, now;
170     double diff, part, days, hours, lstTmp;
171     char tbuf[64];
172   
173     now = cur_time;
174     start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
175   
176     SG_LOG( SG_EVENT, SG_DEBUG, "  COURSE: GMT = "
177             << sgTimeFormatTime(gmt, tbuf) );
178     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
179   
180     diff = (now - start_gmt) / (3600.0 * 24.0);
181   
182     SG_LOG( SG_EVENT, SG_DEBUG, 
183             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
184   
185     part = fmod(diff, 1.0);
186     days = diff - part;
187     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
188   
189     lstTmp = (days - lng)/15.0 + hours - 12;
190   
191     while ( lstTmp < 0.0 ) {
192         lstTmp += 24.0;
193     }
194   
195     SG_LOG( SG_EVENT, SG_DEBUG,
196             "  days = " << days << "  hours = " << hours << "  lon = " 
197             << lng << "  lst = " << lstTmp );
198   
199     return lstTmp;
200 }
201
202
203 // Update the time related variables
204 void SGTime::update( double lon, double lat, time_t ct, long int warp ) {
205     double gst_precise, gst_course;
206
207 #if defined(_MSC_VER) || defined(__MINGW32__)
208     tm * gmt = &m_gmt;
209 #endif
210
211     SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
212
213     // get current Unix calendar time (in seconds)
214     // warp += warp_delta;
215     if ( ct ) {
216         cur_time = ct + warp;
217     } else {
218         cur_time = time(NULL) + warp;
219     }
220     SG_LOG( SG_EVENT, SG_DEBUG, 
221             "  Current Unix calendar time = " << cur_time 
222             << "  warp = " << warp );
223
224     // get GMT break down for current time
225 #if defined(_MSC_VER) || defined(__MINGW32__)
226     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
227 #else
228     gmt = gmtime(&cur_time);
229 #endif
230     SG_LOG( SG_EVENT, SG_DEBUG, 
231             "  Current GMT = " << gmt->tm_mon+1 << "/" 
232             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
233             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
234             << gmt->tm_sec );
235
236     // calculate modified Julian date starting with current
237     mjd = sgTimeCurrentMJD( ct, warp );
238
239     // add in partial day
240     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
241         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
242
243     // convert "back" to Julian date + partial day (as a fraction of one)
244     jd = mjd + MJD0;
245     SG_LOG( SG_EVENT, SG_DEBUG, "  Current Julian Date = " << jd );
246
247     // printf("  Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
248
249     // Calculate local side real time
250     if ( gst_diff < -100.0 ) {
251         // first time through do the expensive calculation & cheap
252         // calculation to get the difference.
253         SG_LOG( SG_EVENT, SG_INFO, "  First time, doing precise gst" );
254         gst_precise = gst = sidereal_precise( mjd, 0.00 );
255         gst_course = sidereal_course( cur_time, gmt, 0.00 );
256       
257         gst_diff = gst_precise - gst_course;
258
259         lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
260     } else {
261         // course + difference should drift off very slowly
262         gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
263         lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
264     }
265
266     SG_LOG( SG_EVENT, SG_DEBUG,
267             "  Current lon=0.00 Sidereal Time = " << gst );
268     SG_LOG( SG_EVENT, SG_DEBUG,
269             "  Current LOCAL Sidereal Time = " << lst << " (" 
270             << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) ) 
271             << ") (diff = " << gst_diff << ")" );
272 }
273
274
275 // Given lon/lat, update timezone information and local_offset
276 void SGTime::updateLocal( double lon, double lat, const string& root ) {
277     // sanity checking
278     if ( lon < -SGD_PI || lon > SGD_PI ) {
279         // not within -180 ... 180
280         lon = 0.0;
281     }
282     if ( lat < -SGD_PI * 0.5 || lat > SGD_PI * 0.5 ) {
283         // not within -90 ... 90
284         lat = 0.0;
285     }
286     if ( lon != lon ) {
287         // only true if lon == nan
288         SG_LOG( SG_EVENT, SG_ALERT, "  Detected lon == nan, resetting to 0.0" );
289         lon = 0.0;
290     }
291     if ( lat != lat ) {
292         // only true if lat == nan
293         SG_LOG( SG_EVENT, SG_ALERT, "  Detected lat == nan, resetting to 0.0" );
294         lat = 0.0;
295     }
296     time_t currGMT;
297     time_t aircraftLocalTime;
298     GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
299     GeoCoord* nearestTz = tzContainer->getNearest(location);
300     SGPath zone( root );
301     zone.append ( nearestTz->getDescription() );
302     if ( zonename ) {
303         char *ptr = zonename;
304         zonename = NULL;
305         free(ptr);
306     }
307     zonename = strdup( zone.c_str() );
308
309     //Avoid troubles when zone.tab hasn't got the right line endings
310     if (zonename[strlen(zonename)-1] == '\r')
311     {
312       zonename[strlen(zonename)-1]=0;
313       zone.set( zonename );
314     }
315
316     currGMT = sgTimeGetGMT( gmtime(&cur_time) );
317     aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
318     local_offset = aircraftLocalTime - currGMT;
319     // cout << "Using " << local_offset << " as local time offset Timezone is " 
320     //      << zonename << endl;
321 }
322
323
324 // given a date in months, mn, days, dy, years, yr, return the
325 // modified Julian date (number of days elapsed since 1900 jan 0.5),
326 // mjd.  Adapted from Xephem.
327 double sgTimeCalcMJD(int mn, double dy, int yr) {
328     double mjd;
329
330     // internal book keeping data
331     static double last_mjd, last_dy;
332     static int last_mn, last_yr;
333
334     int b, d, m, y;
335     long c;
336   
337     if (mn == last_mn && yr == last_yr && dy == last_dy) {
338         mjd = last_mjd;
339     }
340   
341     m = mn;
342     y = (yr < 0) ? yr + 1 : yr;
343     if (mn < 3) {
344         m += 12;
345         y -= 1;
346     }
347   
348     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
349         b = 0;
350     } else {
351         int a;
352         a = y/100;
353         b = 2 - a + a/4;
354     }
355   
356     if (y < 0) {
357         c = (long)((365.25*y) - 0.75) - 694025L;
358     } else {
359         c = (long)(365.25*y) - 694025L;
360     }
361   
362     d = (int)(30.6001*(m+1));
363   
364     mjd = b + c + d + dy - 0.5;
365   
366     last_mn = mn;
367     last_dy = dy;
368     last_yr = yr;
369     last_mjd = mjd;
370
371     return mjd;
372 }
373
374
375 // return the current modified Julian date (number of days elapsed
376 // since 1900 jan 0.5), mjd.
377 double sgTimeCurrentMJD( time_t ct, long int warp ) {
378
379 #if defined(_MSC_VER) || defined(__MINGW32__)
380     struct tm m_gmt;    // copy of system gmtime(&time_t) structure
381     struct tm *gmt = &m_gmt;
382 #else
383     struct tm *gmt;
384 #endif
385
386     // get current Unix calendar time (in seconds)
387     // warp += warp_delta;
388     time_t cur_time;
389     if ( ct ) {
390         cur_time = ct + warp;
391     } else {
392         cur_time = time(NULL) + warp;
393     }
394     SG_LOG( SG_EVENT, SG_DEBUG, 
395             "  Current Unix calendar time = " << cur_time 
396             << "  warp = " << warp );
397
398     // get GMT break down for current time
399 #if defined(_MSC_VER) || defined(__MINGW32__)
400     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
401 #else
402     gmt = gmtime(&cur_time);
403 #endif
404     SG_LOG( SG_EVENT, SG_DEBUG, 
405             "  Current GMT = " << gmt->tm_mon+1 << "/" 
406             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
407             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
408             << gmt->tm_sec );
409
410     // calculate modified Julian date
411     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
412     //     (int)(t->gmt->tm_year + 1900));
413     double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
414                                 (int)(gmt->tm_year + 1900) );
415
416     return mjd;
417 }
418
419
420 // given an mjd, calculate greenwich mean sidereal time, gst
421 double sgTimeCalcGST( double mjd ) {
422     double gst;
423
424     double day = floor(mjd-0.5)+0.5;
425     double hr = (mjd-day)*24.0;
426     double T, x;
427
428     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
429     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
430     x /= 3600.0;
431     gst = (1.0/SIDRATE)*hr + x;
432
433     SG_LOG( SG_EVENT, SG_DEBUG, "  gst => " << gst );
434
435     return gst;
436 }
437
438
439 #if defined( HAVE_TIMEGM ) 
440     // ignore this function
441 #elif defined( MK_TIME_IS_GMT )
442     // ignore this function
443 #else // ! defined ( MK_TIME_IS_GMT )
444
445     // Fix up timezone if using ftime()
446     static long int fix_up_timezone( long int timezone_orig ) {
447 #   if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
448         // ftime() needs a little extra help finding the current timezone
449         struct timeb current;
450         ftime(&current);
451         return( current.timezone * 60 );
452 #   else
453         return( timezone_orig );
454 #   endif
455     }
456 #endif
457
458
459 /******************************************************************
460  * The following are some functions that were included as SGTime
461  * members, although they currently don't make use of any of the
462  * class's variables. Maybe this'll change in the future
463  *****************************************************************/
464
465 // Return time_t for Sat Mar 21 12:00:00 GMT
466 //
467 // On many systems it is ambiguous if mktime() assumes the input is in
468 // GMT, or local timezone.  To address this, a new function called
469 // timegm() is appearing.  It works exactly like mktime() but
470 // explicitely interprets the input as GMT.
471 //
472 // timegm() is available and documented under FreeBSD.  It is
473 // available, but completely undocumented on my current Debian 2.1
474 // distribution.
475 //
476 // In the absence of timegm() we have to guess what mktime() might do.
477 //
478 // Many older BSD style systems have a mktime() that assumes the input
479 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
480 // local time zone
481 //
482 // The mktime() on many SYSV style systems (such as Linux) usually
483 // returns its result assuming you have specified the input time in
484 // your local timezone.  Therefore, in the absence if timegm() you
485 // have to go to extra trouble to convert back to GMT.
486 //
487 // If you are having problems with incorrectly positioned astronomical
488 // bodies, this is a really good place to start looking.
489
490 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
491 {
492     struct tm mt;
493
494     mt.tm_mon = month;
495     mt.tm_mday = day;
496     mt.tm_year = year;
497     mt.tm_hour = hour;
498     mt.tm_min = min;
499     mt.tm_sec = sec;
500     mt.tm_isdst = -1; // let the system determine the proper time zone
501
502     // For now we assume that if daylight is not defined in
503     // /usr/include/time.h that we have a machine with a mktime() that
504     // assumes input is in GMT ... this only matters if we are
505     // building on a system that does not have timegm()
506 #if !defined(HAVE_DAYLIGHT)
507 #  define MK_TIME_IS_GMT 1
508 #endif
509
510 #if defined( HAVE_TIMEGM )
511     return ( timegm(&mt) );
512 #elif defined( MK_TIME_IS_GMT )
513     time_t ret = mktime(&mt);
514
515 #ifdef __CYGWIN__
516         ret -= _timezone;
517 #endif
518
519     // This is necessary as some mktime() calls may
520     // try to access the system timezone files
521     // if this open fails errno is set to 2
522     // CYGWIN for one does this
523     // if ( errno ) {
524     //     perror( "sgTimeGetGMT()" );
525     //     errno = 0;
526     // }
527
528     // reset errno in any event.
529     errno = 0;
530
531     return ret;
532 #else // ! defined ( MK_TIME_IS_GMT )
533
534     // timezone seems to work as a proper offset for Linux & Solaris
535 #   if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
536 #       define TIMEZONE_OFFSET_WORKS 1
537 #   endif
538
539 #if defined(__CYGWIN__)
540 #define TIMEZONE _timezone
541 #else
542 #define TIMEZONE timezone
543 #endif
544         
545     time_t start = mktime(&mt);
546
547     SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
548     // the ctime() call can screw up time progression on some versions
549     // of Linux
550     // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
551     SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
552
553     TIMEZONE = fix_up_timezone( TIMEZONE );
554
555 #  if defined( TIMEZONE_OFFSET_WORKS )
556     SG_LOG( SG_EVENT, SG_DEBUG,
557             "start = " << start << ", timezone = " << TIMEZONE );
558     return( start - TIMEZONE );
559 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
560
561     daylight = mt.tm_isdst;
562     if ( daylight > 0 ) {
563         daylight = 1;
564     } else if ( daylight < 0 ) {
565         SG_LOG( SG_EVENT, FG_WARN, 
566                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
567     }
568
569     long int offset = -(TIMEZONE / 3600 - daylight);
570
571     SG_LOG( SG_EVENT, SG_DEBUG, "  Raw time zone offset = " << TIMEZONE );
572     SG_LOG( SG_EVENT, SG_DEBUG, "  Daylight Savings = " << daylight );
573     SG_LOG( SG_EVENT, SG_DEBUG, "  Local hours from GMT = " << offset );
574     
575     long int start_gmt = start - TIMEZONE + (daylight * 3600);
576     
577     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (CST) = " << start );
578
579     return ( start_gmt );
580 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
581 #endif // ! defined ( MK_TIME_IS_GMT )
582 }
583
584
585 // format time
586 char* sgTimeFormatTime( const struct tm* p, char* buf )
587 {
588     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
589              p->tm_mon, p->tm_mday, p->tm_year,
590              p->tm_hour, p->tm_min, p->tm_sec);
591     return buf;
592 }