]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
a0353d4ec2ca142e36009c4e12a5ae5e1ac1237d
[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 program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // 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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #ifdef FG_HAVE_STD_INCLUDES
31 #  include <cmath>
32 #  include <cstdio>
33 #  include <cstdlib>
34 #  include <ctime>
35 #else
36 #  include <math.h>
37 #  include <stdio.h>
38 #  include <stdlib.h>
39 #  include <time.h>
40 #endif
41
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 #ifdef HAVE_SYS_TIME_H
49 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
50 #endif
51
52 #include <simgear/constants.h>
53 #include <simgear/debug/logstream.hxx>
54 #include <simgear/misc/fgpath.hxx>
55
56 #include "sg_time.hxx"
57 #include "timezone.h"
58 #include "lowleveltime.h"
59
60
61 #define DEGHR(x)        ((x)/15.)
62 #define RADHR(x)        DEGHR(x*RAD_TO_DEG)
63
64
65 SGTime::SGTime( const string& root )
66 {
67     FGPath zone( root );
68     zone.append( "zone.tab" );
69
70     FG_LOG( FG_EVENT, FG_DEBUG, "Reading timezone info from: " << zone.str() );
71     tzContainer = new TimezoneContainer( zone.c_str() );
72
73     zonename = NULL;
74 }
75
76
77 SGTime::~SGTime()
78 {
79     delete tzContainer;
80
81     if ( zonename != NULL ) {
82         delete zonename;
83     }
84 }
85
86
87 // Initialize the time related variables
88 void SGTime::init( double lon, double lat, const string& root )
89 {
90     FG_LOG( FG_EVENT, FG_INFO, "Initializing Time" );
91     gst_diff = -9999.0;
92
93     // time_t currGMT;
94     // time_t systemLocalTime;
95     // time_t aircraftLocalTime;
96
97     // would it be better to put these sanity checks in the options
98     // parsing code? (CLO)
99
100     cur_time = time(NULL); 
101
102     // printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
103     // printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
104     // time_t tmp = cur_time;
105     GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
106
107     GeoCoord* nearestTz = tzContainer->getNearest(location);
108
109     FGPath zone( root );
110     zone.append( nearestTz->getDescription() );
111
112     // cout << "Using " << zone.str() << " for timezone information" << endl;
113     zonename = strdup( zone.c_str() );
114     // cout << "zonename = " << zonename << endl;
115     //show( buffer.c_str(), cur_time, 1); 
116     //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
117     //printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
118     // currGMT = get_gmt( gmtime(&cur_time) );
119     // cout << "currGMT = " << currGMT << endl;
120
121     // systemLocalTime = get_gmt( localtime(&cur_time) );
122     // cout << "systemLocalTime = " << systemLocalTime << endl;
123
124     // aircraftLocalTime = get_gmt( fgLocaltime(&cur_time, zone.c_str()) ); 
125     //printf ("Current greenwich mean time = %24s", asctime(gmtime(&cur_time)));
126     //printf ("Current local time          = %24s", asctime(localtime(&cur_time)));
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 *= DEG_TO_RAD;
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, 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     FG_LOG( FG_EVENT, FG_DEBUG, "  COURSE: GMT = "
163             << sgTimeFormatTime(gmt, tbuf) );
164     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
165   
166     diff = (now - start_gmt) / (3600.0 * 24.0);
167   
168     FG_LOG( FG_EVENT, FG_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     FG_LOG( FG_EVENT, FG_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, double lat, long int warp ) {
191     double gst_precise, gst_course;
192
193     FG_LOG( FG_EVENT, FG_DEBUG, "Updating time" );
194
195     // get current Unix calendar time (in seconds)
196     // warp += warp_delta;
197     cur_time = time(NULL) + warp;
198     FG_LOG( FG_EVENT, FG_DEBUG, 
199             "  Current Unix calendar time = " << cur_time 
200             << "  warp = " << warp );
201
202     // get GMT break down for current time
203     gmt = gmtime(&cur_time);
204     FG_LOG( FG_EVENT, FG_DEBUG, 
205             "  Current GMT = " << gmt->tm_mon+1 << "/" 
206             << gmt->tm_mday << "/" << gmt->tm_year << " "
207             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
208             << gmt->tm_sec );
209
210     // calculate modified Julian date
211     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
212     //     (int)(t->gmt->tm_year + 1900));
213     mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
214                          (int)(gmt->tm_year + 1900) );
215
216     // add in partial day
217     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
218         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
219
220     // convert "back" to Julian date + partial day (as a fraction of one)
221     jd = mjd + MJD0;
222     FG_LOG( FG_EVENT, FG_DEBUG, "  Current Julian Date = " << jd );
223
224     // printf("  Current Longitude = %.3f\n", FG_Longitude * RAD_TO_DEG);
225
226     // Calculate local side real time
227     if ( gst_diff < -100.0 ) {
228         // first time through do the expensive calculation & cheap
229         // calculation to get the difference.
230         FG_LOG( FG_EVENT, FG_INFO, "  First time, doing precise gst" );
231         gst_precise = gst = sidereal_precise( mjd, 0.00 );
232         gst_course = sidereal_course( cur_time, gmt, 0.00 );
233       
234         gst_diff = gst_precise - gst_course;
235
236         lst = sidereal_course( cur_time, gmt, -(lon * RAD_TO_DEG) ) + gst_diff;
237     } else {
238         // course + difference should drift off very slowly
239         gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
240         lst = sidereal_course( cur_time, gmt, -(lon * RAD_TO_DEG) ) + gst_diff;
241     }
242
243     FG_LOG( FG_EVENT, FG_DEBUG,
244             "  Current lon=0.00 Sidereal Time = " << gst );
245     FG_LOG( FG_EVENT, FG_DEBUG,
246             "  Current LOCAL Sidereal Time = " << lst << " (" 
247             << sidereal_precise( mjd, -(lon * RAD_TO_DEG) ) 
248             << ") (diff = " << gst_diff << ")" );
249 }
250
251
252 // Given lon/lat, update timezone information and local_offset
253 void SGTime::updateLocal( double lon, double lat, const string& root )
254 {
255   time_t currGMT;
256   time_t aircraftLocalTime;
257   GeoCoord location( RAD_TO_DEG * lat, RAD_TO_DEG * lon );
258   GeoCoord* nearestTz = tzContainer->getNearest(location);
259   FGPath zone( root );
260   zone.append ( nearestTz->getDescription() );
261   if ( zonename ) {
262       delete zonename;
263   }
264   zonename = strdup( zone.c_str() );
265   currGMT = sgTimeGetGMT( gmtime(&cur_time) );
266   aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
267   local_offset = aircraftLocalTime - currGMT;
268   // cout << "Using " << local_offset << " as local time offset Timezone is " 
269   //      << zonename << endl;
270 }
271
272
273 // given a date in months, mn, days, dy, years, yr, return the
274 // modified Julian date (number of days elapsed since 1900 jan 0.5),
275 // mjd.  Adapted from Xephem.
276 double sgTimeCalcMJD(int mn, double dy, int yr) {
277     double mjd;
278
279     // internal book keeping data
280     static double last_mjd, last_dy;
281     static int last_mn, last_yr;
282
283     int b, d, m, y;
284     long c;
285   
286     if (mn == last_mn && yr == last_yr && dy == last_dy) {
287         mjd = last_mjd;
288     }
289   
290     m = mn;
291     y = (yr < 0) ? yr + 1 : yr;
292     if (mn < 3) {
293         m += 12;
294         y -= 1;
295     }
296   
297     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
298         b = 0;
299     } else {
300         int a;
301         a = y/100;
302         b = 2 - a + a/4;
303     }
304   
305     if (y < 0) {
306         c = (long)((365.25*y) - 0.75) - 694025L;
307     } else {
308         c = (long)(365.25*y) - 694025L;
309     }
310   
311     d = (int)(30.6001*(m+1));
312   
313     mjd = b + c + d + dy - 0.5;
314   
315     last_mn = mn;
316     last_dy = dy;
317     last_yr = yr;
318     last_mjd = mjd;
319
320     return mjd;
321 }
322
323
324 // given an mjd, calculate greenwich mean sidereal time, gst
325 double sgTimeCalcGST( double mjd ) {
326     double gst;
327
328     double day = floor(mjd-0.5)+0.5;
329     double hr = (mjd-day)*24.0;
330     double T, x;
331
332     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
333     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
334     x /= 3600.0;
335     gst = (1.0/SIDRATE)*hr + x;
336
337     FG_LOG( FG_EVENT, FG_DEBUG, "  gst => " << gst );
338
339     return gst;
340 }
341
342
343 #if defined( HAVE_TIMEGM ) 
344     // ignore this function
345 #elif defined( MK_TIME_IS_GMT )
346     // ignore this function
347 #else // ! defined ( MK_TIME_IS_GMT )
348
349     // Fix up timezone if using ftime()
350     static long int fix_up_timezone( long int timezone_orig ) {
351 #   if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
352         // ftime() needs a little extra help finding the current timezone
353         struct timeb current;
354         ftime(&current);
355         return( current.timezone * 60 );
356 #   else
357         return( timezone_orig );
358 #   endif
359     }
360 #endif
361
362
363 /******************************************************************
364  * The following are some functions that were included as SGTime
365  * members, although they currently don't make use of any of the
366  * class's variables. Maybe this'll change in the future
367  *****************************************************************/
368
369 // Return time_t for Sat Mar 21 12:00:00 GMT
370 //
371 // On many systems it is ambiguous if mktime() assumes the input is in
372 // GMT, or local timezone.  To address this, a new function called
373 // timegm() is appearing.  It works exactly like mktime() but
374 // explicitely interprets the input as GMT.
375 //
376 // timegm() is available and documented under FreeBSD.  It is
377 // available, but completely undocumented on my current Debian 2.1
378 // distribution.
379 //
380 // In the absence of timegm() we have to guess what mktime() might do.
381 //
382 // Many older BSD style systems have a mktime() that assumes the input
383 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
384 // local time zone
385 //
386 // The mktime() on many SYSV style systems (such as Linux) usually
387 // returns its result assuming you have specified the input time in
388 // your local timezone.  Therefore, in the absence if timegm() you
389 // have to go to extra trouble to convert back to GMT.
390 //
391 // If you are having problems with incorrectly positioned astronomical
392 // bodies, this is a really good place to start looking.
393
394 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
395 {
396     struct tm mt;
397
398     mt.tm_mon = month;
399     mt.tm_mday = day;
400     mt.tm_year = year;
401     mt.tm_hour = hour;
402     mt.tm_min = min;
403     mt.tm_sec = sec;
404     mt.tm_isdst = -1; // let the system determine the proper time zone
405
406     // For now we assume that if daylight is not defined in
407     // /usr/include/time.h that we have a machine with a mktime() that
408     // assumes input is in GMT ... this only matters if we are
409     // building on a system that does not have timegm()
410 #if !defined(HAVE_DAYLIGHT)
411 #  define MK_TIME_IS_GMT 1
412 #endif
413
414 #if defined( HAVE_TIMEGM ) 
415     return ( timegm(&mt) );
416 #elif defined( MK_TIME_IS_GMT )
417     return ( mktime(&mt) );
418 #else // ! defined ( MK_TIME_IS_GMT )
419
420     // timezone seems to work as a proper offset for Linux & Solaris
421 #   if defined( __linux__ ) || defined( __sun__ ) 
422 #       define TIMEZONE_OFFSET_WORKS 1
423 #   endif
424
425     long int start = mktime(&mt);
426
427     FG_LOG( FG_EVENT, FG_DEBUG, "start1 = " << start );
428     // the ctime() call can screw up time progression on some versions
429     // of Linux
430     // fgPrintf( FG_EVENT, FG_DEBUG, "start2 = %s", ctime(&start));
431     FG_LOG( FG_EVENT, FG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
432
433     timezone = fix_up_timezone( timezone );
434
435 #  if defined( TIMEZONE_OFFSET_WORKS )
436     FG_LOG( FG_EVENT, FG_DEBUG, 
437             "start = " << start << ", timezone = " << timezone );
438     return( start - timezone );
439 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
440
441     daylight = mt.tm_isdst;
442     if ( daylight > 0 ) {
443         daylight = 1;
444     } else if ( daylight < 0 ) {
445         FG_LOG( FG_EVENT, FG_WARN, 
446                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
447     }
448
449     long int offset = -(timezone / 3600 - daylight);
450
451     FG_LOG( FG_EVENT, FG_DEBUG, "  Raw time zone offset = " << timezone );
452     FG_LOG( FG_EVENT, FG_DEBUG, "  Daylight Savings = " << daylight );
453     FG_LOG( FG_EVENT, FG_DEBUG, "  Local hours from GMT = " << offset );
454     
455     long int start_gmt = start - timezone + (daylight * 3600);
456     
457     FG_LOG( FG_EVENT, FG_DEBUG, "  March 21 noon (CST) = " << start );
458
459     return ( start_gmt );
460 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
461 #endif // ! defined ( MK_TIME_IS_GMT )
462 }
463
464
465 // format time
466 char* sgTimeFormatTime( const struct tm* p, char* buf )
467 {
468     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
469              p->tm_mon, p->tm_mday, p->tm_year,
470              p->tm_hour, p->tm_min, p->tm_sec);
471     return buf;
472 }