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