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