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