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