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