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