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