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