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