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