]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
- added sg_xml_exception class
[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 <cmath>
35 #  include <cstdio>
36 #  include <cstdlib>
37 #  include <ctime>
38 #else
39 #  include <math.h>
40 #  include <stdio.h>
41 #  include <stdlib.h>
42 #  include <time.h>
43 #endif
44
45 #ifdef HAVE_SYS_TIMEB_H
46 #  include <sys/timeb.h> // for ftime() and struct timeb
47 #endif
48 #ifdef HAVE_UNISTD_H
49 #  include <unistd.h>    // for gettimeofday()
50 #endif
51 #ifdef HAVE_SYS_TIME_H
52 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
53 #endif
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 SGTime::SGTime( double lon, double lat, const string& root )
74 {
75     SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
76
77     gst_diff = -9999.0;
78
79     cur_time = time(NULL); 
80     cout << "Current greenwich mean time = " << asctime(gmtime(&cur_time))
81          << endl;
82     cout << "Current local time          = " 
83          << asctime(localtime(&cur_time)) << endl;
84
85     if ( root != (string)"" ) {
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 TimezoneContainer( zone.c_str() );
91
92         GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
93         GeoCoord* nearestTz = tzContainer->getNearest(location);
94
95         SGPath name( root );
96         name.append( nearestTz->getDescription() );
97         zonename = strdup( name.c_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 = NULL;
103     }
104 }
105
106
107 SGTime::SGTime( const string& root ) {
108     SGTime( 0.0, 0.0, root );
109 }
110
111
112 SGTime::SGTime() {
113     SGTime( 0.0, 0.0, "" );
114 }
115
116
117 SGTime::~SGTime()
118 {
119     if ( tzContainer != NULL ) {
120         TimezoneContainer *tmp = tzContainer;
121         tzContainer = NULL;
122         delete tmp;
123     }
124
125     if ( zonename != NULL ) {
126         char *tmp = zonename;
127         zonename = 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, 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, double lat, long int warp ) {
194     double gst_precise, gst_course;
195
196 #ifdef _MSC_VER
197     tm * gmt = &m_gmt;
198 #endif
199
200     SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
201
202     // get current Unix calendar time (in seconds)
203     // warp += warp_delta;
204     cur_time = time(NULL) + warp;
205     SG_LOG( SG_EVENT, SG_DEBUG, 
206             "  Current Unix calendar time = " << cur_time 
207             << "  warp = " << warp );
208
209     // get GMT break down for current time
210 #ifdef _MSC_VER
211     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
212 #else
213     gmt = gmtime(&cur_time);
214 #endif
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( 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, -(lon * 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, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
249     }
250
251     SG_LOG( SG_EVENT, SG_DEBUG,
252             "  Current lon=0.00 Sidereal Time = " << gst );
253     SG_LOG( SG_EVENT, SG_DEBUG,
254             "  Current LOCAL Sidereal Time = " << lst << " (" 
255             << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) ) 
256             << ") (diff = " << gst_diff << ")" );
257 }
258
259
260 // Given lon/lat, update timezone information and local_offset
261 void SGTime::updateLocal( double lon, double lat, const string& root ) {
262     time_t currGMT;
263     time_t aircraftLocalTime;
264     GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
265     GeoCoord* nearestTz = tzContainer->getNearest(location);
266     SGPath zone( root );
267     zone.append ( nearestTz->getDescription() );
268     if ( zonename ) {
269         char *ptr = zonename;
270         zonename = NULL;
271         delete ptr;
272     }
273     zonename = strdup( zone.c_str() );
274     currGMT = sgTimeGetGMT( gmtime(&cur_time) );
275     aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
276     local_offset = aircraftLocalTime - currGMT;
277     // cout << "Using " << local_offset << " as local time offset Timezone is " 
278     //      << zonename << endl;
279 }
280
281
282 // given a date in months, mn, days, dy, years, yr, return the
283 // modified Julian date (number of days elapsed since 1900 jan 0.5),
284 // mjd.  Adapted from Xephem.
285 double sgTimeCalcMJD(int mn, double dy, int yr) {
286     double mjd;
287
288     // internal book keeping data
289     static double last_mjd, last_dy;
290     static int last_mn, last_yr;
291
292     int b, d, m, y;
293     long c;
294   
295     if (mn == last_mn && yr == last_yr && dy == last_dy) {
296         mjd = last_mjd;
297     }
298   
299     m = mn;
300     y = (yr < 0) ? yr + 1 : yr;
301     if (mn < 3) {
302         m += 12;
303         y -= 1;
304     }
305   
306     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
307         b = 0;
308     } else {
309         int a;
310         a = y/100;
311         b = 2 - a + a/4;
312     }
313   
314     if (y < 0) {
315         c = (long)((365.25*y) - 0.75) - 694025L;
316     } else {
317         c = (long)(365.25*y) - 694025L;
318     }
319   
320     d = (int)(30.6001*(m+1));
321   
322     mjd = b + c + d + dy - 0.5;
323   
324     last_mn = mn;
325     last_dy = dy;
326     last_yr = yr;
327     last_mjd = mjd;
328
329     return mjd;
330 }
331
332
333 // return the current modified Julian date (number of days elapsed
334 // since 1900 jan 0.5), mjd.
335 double sgTimeCurrentMJD( long int warp ) {
336 #ifdef _MSC_VER
337     struct tm m_gmt;    // copy of system gmtime(&time_t) structure
338 #else
339     struct tm *gmt;
340 #endif
341
342 #ifdef _MSC_VER
343     tm * gmt = &m_gmt;
344 #endif
345
346     // get current Unix calendar time (in seconds)
347     // warp += warp_delta;
348     time_t cur_time = time(NULL) + warp;
349     SG_LOG( SG_EVENT, SG_DEBUG, 
350             "  Current Unix calendar time = " << cur_time 
351             << "  warp = " << warp );
352
353     // get GMT break down for current time
354 #ifdef _MSC_VER
355     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
356 #else
357     gmt = gmtime(&cur_time);
358 #endif
359     SG_LOG( SG_EVENT, SG_DEBUG, 
360             "  Current GMT = " << gmt->tm_mon+1 << "/" 
361             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
362             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
363             << gmt->tm_sec );
364
365     // calculate modified Julian date
366     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
367     //     (int)(t->gmt->tm_year + 1900));
368     double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
369                                 (int)(gmt->tm_year + 1900) );
370
371     return mjd;
372 }
373
374
375 // given an mjd, calculate greenwich mean sidereal time, gst
376 double sgTimeCalcGST( double mjd ) {
377     double gst;
378
379     double day = floor(mjd-0.5)+0.5;
380     double hr = (mjd-day)*24.0;
381     double T, x;
382
383     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
384     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
385     x /= 3600.0;
386     gst = (1.0/SIDRATE)*hr + x;
387
388     SG_LOG( SG_EVENT, SG_DEBUG, "  gst => " << gst );
389
390     return gst;
391 }
392
393
394 #if defined( HAVE_TIMEGM ) 
395     // ignore this function
396 #elif defined( MK_TIME_IS_GMT )
397     // ignore this function
398 #else // ! defined ( MK_TIME_IS_GMT )
399
400     // Fix up timezone if using ftime()
401     static long int fix_up_timezone( long int timezone_orig ) {
402 #   if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
403         // ftime() needs a little extra help finding the current timezone
404         struct timeb current;
405         ftime(&current);
406         return( current.timezone * 60 );
407 #   else
408         return( timezone_orig );
409 #   endif
410     }
411 #endif
412
413
414 /******************************************************************
415  * The following are some functions that were included as SGTime
416  * members, although they currently don't make use of any of the
417  * class's variables. Maybe this'll change in the future
418  *****************************************************************/
419
420 // Return time_t for Sat Mar 21 12:00:00 GMT
421 //
422 // On many systems it is ambiguous if mktime() assumes the input is in
423 // GMT, or local timezone.  To address this, a new function called
424 // timegm() is appearing.  It works exactly like mktime() but
425 // explicitely interprets the input as GMT.
426 //
427 // timegm() is available and documented under FreeBSD.  It is
428 // available, but completely undocumented on my current Debian 2.1
429 // distribution.
430 //
431 // In the absence of timegm() we have to guess what mktime() might do.
432 //
433 // Many older BSD style systems have a mktime() that assumes the input
434 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
435 // local time zone
436 //
437 // The mktime() on many SYSV style systems (such as Linux) usually
438 // returns its result assuming you have specified the input time in
439 // your local timezone.  Therefore, in the absence if timegm() you
440 // have to go to extra trouble to convert back to GMT.
441 //
442 // If you are having problems with incorrectly positioned astronomical
443 // bodies, this is a really good place to start looking.
444
445 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
446 {
447     struct tm mt;
448
449     mt.tm_mon = month;
450     mt.tm_mday = day;
451     mt.tm_year = year;
452     mt.tm_hour = hour;
453     mt.tm_min = min;
454     mt.tm_sec = sec;
455     mt.tm_isdst = -1; // let the system determine the proper time zone
456
457     // For now we assume that if daylight is not defined in
458     // /usr/include/time.h that we have a machine with a mktime() that
459     // assumes input is in GMT ... this only matters if we are
460     // building on a system that does not have timegm()
461 #if !defined(HAVE_DAYLIGHT)
462 #  define MK_TIME_IS_GMT 1
463 #endif
464
465 #if defined( HAVE_TIMEGM )
466     return ( timegm(&mt) );
467 #elif defined( MK_TIME_IS_GMT )
468     time_t ret = mktime(&mt);
469
470 #ifdef __CYGWIN__
471         ret -= _timezone;
472 #endif
473
474     // This is necessary as some mktime() calls may
475     // try to access the system timezone files
476     // if this open fails errno is set to 2
477     // CYGWIN for one does this
478     // if ( errno ) {
479     //     perror( "sgTimeGetGMT()" );
480     //     errno = 0;
481     // }
482
483     // reset errno in any event.
484     errno = 0;
485
486     return ret;
487 #else // ! defined ( MK_TIME_IS_GMT )
488
489     // timezone seems to work as a proper offset for Linux & Solaris
490 #   if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
491 #       define TIMEZONE_OFFSET_WORKS 1
492 #   endif
493
494 #if defined(__CYGWIN__)
495 #define TIMEZONE _timezone
496 #else
497 #define TIMEZONE timezone
498 #endif
499         
500     time_t start = mktime(&mt);
501
502     SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
503     // the ctime() call can screw up time progression on some versions
504     // of Linux
505     // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
506     SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
507
508     TIMEZONE = fix_up_timezone( TIMEZONE );
509
510 #  if defined( TIMEZONE_OFFSET_WORKS )
511     SG_LOG( SG_EVENT, SG_DEBUG,
512             "start = " << start << ", timezone = " << TIMEZONE );
513     return( start - TIMEZONE );
514 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
515
516     daylight = mt.tm_isdst;
517     if ( daylight > 0 ) {
518         daylight = 1;
519     } else if ( daylight < 0 ) {
520         SG_LOG( SG_EVENT, FG_WARN, 
521                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
522     }
523
524     long int offset = -(TIMEZONE / 3600 - daylight);
525
526     SG_LOG( SG_EVENT, SG_DEBUG, "  Raw time zone offset = " << TIMEZONE );
527     SG_LOG( SG_EVENT, SG_DEBUG, "  Daylight Savings = " << daylight );
528     SG_LOG( SG_EVENT, SG_DEBUG, "  Local hours from GMT = " << offset );
529     
530     long int start_gmt = start - TIMEZONE + (daylight * 3600);
531     
532     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (CST) = " << start );
533
534     return ( start_gmt );
535 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
536 #endif // ! defined ( MK_TIME_IS_GMT )
537 }
538
539
540 // format time
541 char* sgTimeFormatTime( const struct tm* p, char* buf )
542 {
543     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
544              p->tm_mon, p->tm_mday, p->tm_year,
545              p->tm_hour, p->tm_min, p->tm_sec);
546     return buf;
547 }