]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
MSVC++ 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 <simgear_config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #include <errno.h>              // for errno
32
33 #ifdef SG_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/sg_path.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*SGD_RADIANS_TO_DEGREES)
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     SG_LOG( SG_EVENT, SG_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         SGPath zone( root );
87         zone.append( "zone.tab" );
88         SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
89                 << zone.str() );
90         tzContainer = new TimezoneContainer( zone.c_str() );
91
92         GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
93         GeoCoord* nearestTz = tzContainer->getNearest(location);
94
95         SGPath name( root );
96         name.append( nearestTz->getDescription() );
97         zonename = strdup( name.c_str() );
98         SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
99     } else {
100         SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
101         tzContainer = NULL;
102         zonename = NULL;
103     }
104 }
105
106
107 SGTime::SGTime( const string& root ) {
108     SGTime( 0.0, 0.0, root );
109 }
110
111
112 SGTime::SGTime() {
113     SGTime( 0.0, 0.0, "" );
114 }
115
116
117 SGTime::~SGTime()
118 {
119     if ( tzContainer != NULL ) {
120         delete tzContainer;
121     }
122
123     if ( zonename != NULL ) {
124         delete zonename;
125     }
126 }
127
128
129 // given Julian Date and Longitude (decimal degrees West) compute
130 // Local Sidereal Time, in decimal hours.
131 //
132 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
133 static double sidereal_precise( double mjd, double lng )
134 {
135     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
136        mjd + MJD0, lng); */
137
138     // convert to required internal units
139     lng *= SGD_DEGREES_TO_RADIANS;
140
141     // compute LST and print
142     double gst = sgTimeCalcGST( mjd );
143     double lst = gst - RADHR( lng );
144     lst -= 24.0 * floor( lst / 24.0 );
145     // printf ("%7.4f\n", lstTmp);
146
147     return lst;
148 }
149
150
151 // return a courser but cheaper estimate of sidereal time
152 static double sidereal_course( time_t cur_time, struct tm *gmt, double lng )
153 {
154     time_t start_gmt, now;
155     double diff, part, days, hours, lstTmp;
156     char tbuf[64];
157   
158     now = cur_time;
159     start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
160   
161     SG_LOG( SG_EVENT, SG_DEBUG, "  COURSE: GMT = "
162             << sgTimeFormatTime(gmt, tbuf) );
163     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
164   
165     diff = (now - start_gmt) / (3600.0 * 24.0);
166   
167     SG_LOG( SG_EVENT, SG_DEBUG, 
168             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
169   
170     part = fmod(diff, 1.0);
171     days = diff - part;
172     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
173   
174     lstTmp = (days - lng)/15.0 + hours - 12;
175   
176     while ( lstTmp < 0.0 ) {
177         lstTmp += 24.0;
178     }
179   
180     SG_LOG( SG_EVENT, SG_DEBUG,
181             "  days = " << days << "  hours = " << hours << "  lon = " 
182             << lng << "  lst = " << lstTmp );
183   
184     return lstTmp;
185 }
186
187
188 // Update the time related variables
189 void SGTime::update( double lon, double lat, long int warp ) {
190     double gst_precise, gst_course;
191 #ifdef _MSC_VER
192     tm * gmt = &m_gmt;
193 #endif
194
195     SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
196
197     // get current Unix calendar time (in seconds)
198     // warp += warp_delta;
199     cur_time = time(NULL) + warp;
200     SG_LOG( SG_EVENT, SG_DEBUG, 
201             "  Current Unix calendar time = " << cur_time 
202             << "  warp = " << warp );
203
204     // get GMT break down for current time
205 #ifdef _MSC_VER
206     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
207 #else
208     gmt = gmtime(&cur_time);
209 #endif
210     SG_LOG( SG_EVENT, SG_DEBUG, 
211             "  Current GMT = " << gmt->tm_mon+1 << "/" 
212             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
213             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
214             << gmt->tm_sec );
215
216     // calculate modified Julian date
217     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
218     //     (int)(t->gmt->tm_year + 1900));
219     mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
220                          (int)(gmt->tm_year + 1900) );
221
222     // add in partial day
223     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
224         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
225
226     // convert "back" to Julian date + partial day (as a fraction of one)
227     jd = mjd + MJD0;
228     SG_LOG( SG_EVENT, SG_DEBUG, "  Current Julian Date = " << jd );
229
230     // printf("  Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
231
232     // Calculate local side real time
233     if ( gst_diff < -100.0 ) {
234         // first time through do the expensive calculation & cheap
235         // calculation to get the difference.
236         SG_LOG( SG_EVENT, SG_INFO, "  First time, doing precise gst" );
237         gst_precise = gst = sidereal_precise( mjd, 0.00 );
238         gst_course = sidereal_course( cur_time, gmt, 0.00 );
239       
240         gst_diff = gst_precise - gst_course;
241
242         lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
243     } else {
244         // course + difference should drift off very slowly
245         gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
246         lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
247     }
248
249     SG_LOG( SG_EVENT, SG_DEBUG,
250             "  Current lon=0.00 Sidereal Time = " << gst );
251     SG_LOG( SG_EVENT, SG_DEBUG,
252             "  Current LOCAL Sidereal Time = " << lst << " (" 
253             << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) ) 
254             << ") (diff = " << gst_diff << ")" );
255 }
256
257
258 // Given lon/lat, update timezone information and local_offset
259 void SGTime::updateLocal( double lon, double lat, const string& root )
260 {
261   time_t currGMT;
262   time_t aircraftLocalTime;
263   GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
264   GeoCoord* nearestTz = tzContainer->getNearest(location);
265   SGPath zone( root );
266   zone.append ( nearestTz->getDescription() );
267   if ( zonename ) {
268       delete zonename;
269   }
270   zonename = strdup( zone.c_str() );
271   currGMT = sgTimeGetGMT( gmtime(&cur_time) );
272   aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
273   local_offset = aircraftLocalTime - currGMT;
274   // cout << "Using " << local_offset << " as local time offset Timezone is " 
275   //      << zonename << endl;
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     SG_LOG( SG_EVENT, SG_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 sgTimeGetGMT(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     time_t ret = mktime(&mt);
424
425 #ifdef __CYGWIN__
426         ret -= _timezone;
427 #endif
428
429     // This is necessary as some mktime() calls may
430     // try to access the system timezone files
431     // if this open fails errno is set to 2
432     // CYGWIN for one does this
433     // if ( errno ) {
434     //     perror( "sgTimeGetGMT()" );
435     //     errno = 0;
436     // }
437
438     // reset errno in any event.
439     errno = 0;
440
441     return ret;
442 #else // ! defined ( MK_TIME_IS_GMT )
443
444     // timezone seems to work as a proper offset for Linux & Solaris
445 #   if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
446 #       define TIMEZONE_OFFSET_WORKS 1
447 #   endif
448
449 #if defined(__CYGWIN__)
450 #define TIMEZONE _timezone
451 #else
452 #define TIMEZONE timezone
453 #endif
454         
455     time_t start = mktime(&mt);
456
457     SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
458     // the ctime() call can screw up time progression on some versions
459     // of Linux
460     // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
461     SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
462
463     TIMEZONE = fix_up_timezone( TIMEZONE );
464
465 #  if defined( TIMEZONE_OFFSET_WORKS )
466     SG_LOG( SG_EVENT, SG_DEBUG,
467             "start = " << start << ", timezone = " << TIMEZONE );
468     return( start - TIMEZONE );
469 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
470
471     daylight = mt.tm_isdst;
472     if ( daylight > 0 ) {
473         daylight = 1;
474     } else if ( daylight < 0 ) {
475         SG_LOG( SG_EVENT, FG_WARN, 
476                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
477     }
478
479     long int offset = -(TIMEZONE / 3600 - daylight);
480
481     SG_LOG( SG_EVENT, SG_DEBUG, "  Raw time zone offset = " << TIMEZONE );
482     SG_LOG( SG_EVENT, SG_DEBUG, "  Daylight Savings = " << daylight );
483     SG_LOG( SG_EVENT, SG_DEBUG, "  Local hours from GMT = " << offset );
484     
485     long int start_gmt = start - TIMEZONE + (daylight * 3600);
486     
487     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (CST) = " << start );
488
489     return ( start_gmt );
490 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
491 #endif // ! defined ( MK_TIME_IS_GMT )
492 }
493
494
495 // format time
496 char* sgTimeFormatTime( const struct tm* p, char* buf )
497 {
498     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
499              p->tm_mon, p->tm_mday, p->tm_year,
500              p->tm_hour, p->tm_min, p->tm_sec);
501     return buf;
502 }