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