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