]> git.mxchange.org Git - simgear.git/blob - simgear/timing/sg_time.cxx
Make sky dome scaling values sensible (i.e. the sky dome will now fill up
[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 <cstdio>
35 #  include <cstdlib>
36 #  include <ctime>
37 #else
38 #  include <math.h>
39 #  include <stdio.h>
40 #  include <stdlib.h>
41 #endif
42
43 #include <string>
44
45 #ifdef HAVE_SYS_TIME_H
46 #  include <sys/time.h>  // for get/setitimer, gettimeofday, struct timeval
47 #endif
48 #ifdef HAVE_SYS_TIMEB_H
49 #  include <sys/timeb.h> // for ftime() and struct timeb
50 #endif
51 #ifdef HAVE_UNISTD_H
52 #  include <unistd.h>    // for gettimeofday()
53 #endif
54
55 #include <math.h>        // for NAN
56
57 #include <simgear/constants.h>
58 #include <simgear/debug/logstream.hxx>
59 #include <simgear/misc/sg_path.hxx>
60
61 #include "sg_time.hxx"
62 #include "timezone.h"
63 #include "lowleveltime.h"
64
65 #define DEGHR(x)        ((x)/15.)
66 #define RADHR(x)        DEGHR(x*SGD_RADIANS_TO_DEGREES)
67
68
69 static const double MJD0    = 2415020.0;
70 static const double J2000   = 2451545.0 - MJD0;
71 static const double SIDRATE = 0.9972695677;
72
73
74 void SGTime::init( double lon_rad, double lat_rad,
75                    const string& root, time_t init_time )
76 {
77     SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
78
79     gst_diff = -9999.0;
80
81     if ( init_time ) {
82         cur_time = init_time;
83     } else {
84         cur_time = time(NULL); 
85     }
86
87     SG_LOG( SG_EVENT, SG_INFO,
88                 "Current greenwich mean time = " << asctime(gmtime(&cur_time)));
89     SG_LOG( SG_EVENT, SG_INFO,
90              "Current local time          = " << asctime(localtime(&cur_time)));
91
92     if ( !root.empty()) {
93         SGPath zone( root );
94         zone.append( "zone.tab" );
95         SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
96                 << zone.str() );
97         tzContainer = new SGTimeZoneContainer( zone.c_str() );
98
99         SGGeoCoord location( SGD_RADIANS_TO_DEGREES * lat_rad, SGD_RADIANS_TO_DEGREES * lon_rad );
100         SGGeoCoord* nearestTz = tzContainer->getNearest(location);
101
102         SGPath name( root );
103         name.append( nearestTz->getDescription() );
104         zonename = name.str();
105         SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
106     } else {
107         SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
108         tzContainer = NULL;
109         zonename.erase();
110     }
111 }
112
113 SGTime::SGTime( double lon_rad, double lat_rad, const string& root,
114                 time_t init_time )
115 {
116     init( lon_rad, lat_rad, root, init_time );
117 }
118
119
120 SGTime::SGTime( const string& root ) {
121     init( 0.0, 0.0, root, 0 );
122 }
123
124
125 SGTime::SGTime() {
126     init( 0.0, 0.0, "", 0 );
127 }
128
129
130 SGTime::~SGTime()
131 {
132     if ( tzContainer != NULL ) {
133         SGTimeZoneContainer *tmp = tzContainer;
134         tzContainer = NULL;
135         delete tmp;
136     }
137 }
138
139
140 // given Julian Date and Longitude (decimal degrees West) compute
141 // Local Sidereal Time, in decimal hours.
142 //
143 // Provided courtesy of ecdowney@noao.edu (Elwood Downey) 
144 static double sidereal_precise( double mjd, double lng )
145 {
146     /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ", 
147        mjd + MJD0, lng); */
148
149     // convert to required internal units
150     lng *= SGD_DEGREES_TO_RADIANS;
151
152     // compute LST and print
153     double gst = sgTimeCalcGST( mjd );
154     double lst = gst - RADHR( lng );
155     lst -= 24.0 * floor( lst / 24.0 );
156     // printf ("%7.4f\n", lstTmp);
157
158     return lst;
159 }
160
161
162 // return a courser but cheaper estimate of sidereal time
163 static double sidereal_course( time_t cur_time, const struct tm *gmt, double lng )
164 {
165     time_t start_gmt, now;
166     double diff, part, days, hours, lstTmp;
167     char tbuf[64];
168   
169     now = cur_time;
170     start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
171   
172     SG_LOG( SG_EVENT, SG_DEBUG, "  COURSE: GMT = "
173             << sgTimeFormatTime(gmt, tbuf) );
174     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (GMT) = " << start_gmt );
175   
176     diff = (now - start_gmt) / (3600.0 * 24.0);
177   
178     SG_LOG( SG_EVENT, SG_DEBUG, 
179             "  Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
180   
181     part = fmod(diff, 1.0);
182     days = diff - part;
183     hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
184   
185     lstTmp = (days - lng)/15.0 + hours - 12;
186   
187     while ( lstTmp < 0.0 ) {
188         lstTmp += 24.0;
189     }
190   
191     SG_LOG( SG_EVENT, SG_DEBUG,
192             "  days = " << days << "  hours = " << hours << "  lon = " 
193             << lng << "  lst = " << lstTmp );
194   
195     return lstTmp;
196 }
197
198
199 // Update the time related variables
200 void SGTime::update( double lon_rad, double lat_rad,
201                      time_t ct, long int warp )
202 {
203     double gst_precise, gst_course;
204
205 #if defined(_MSC_VER) || defined(__MINGW32__)
206     tm * gmt = &m_gmt;
207 #endif
208
209     SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
210
211     // get current Unix calendar time (in seconds)
212     // warp += warp_delta;
213     if ( ct ) {
214         cur_time = ct + warp;
215     } else {
216         cur_time = time(NULL) + warp;
217     }
218     SG_LOG( SG_EVENT, SG_DEBUG, 
219             "  Current Unix calendar time = " << cur_time 
220             << "  warp = " << warp );
221
222     // get GMT break down for current time
223 #if defined(_MSC_VER) || defined(__MINGW32__)
224     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
225 #else
226     gmt = gmtime(&cur_time);
227 #endif
228     SG_LOG( SG_EVENT, SG_DEBUG, 
229             "  Current GMT = " << gmt->tm_mon+1 << "/" 
230             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
231             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
232             << gmt->tm_sec );
233
234     // calculate modified Julian date starting with current
235     mjd = sgTimeCurrentMJD( ct, warp );
236
237     // add in partial day
238     mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
239         (gmt->tm_sec / (24.0 * 60.0 * 60.0));
240
241     // convert "back" to Julian date + partial day (as a fraction of one)
242     jd = mjd + MJD0;
243     SG_LOG( SG_EVENT, SG_DEBUG, "  Current Julian Date = " << jd );
244
245     // printf("  Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
246
247     // Calculate local side real time
248     if ( gst_diff < -100.0 ) {
249         // first time through do the expensive calculation & cheap
250         // calculation to get the difference.
251         SG_LOG( SG_EVENT, SG_INFO, "  First time, doing precise gst" );
252         gst_precise = gst = sidereal_precise( mjd, 0.00 );
253         gst_course = sidereal_course( cur_time, gmt, 0.00 );
254       
255         gst_diff = gst_precise - gst_course;
256
257         lst = sidereal_course( cur_time, gmt,
258                                -(lon_rad * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
259     } else {
260         // course + difference should drift off very slowly
261         gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
262         lst = sidereal_course( cur_time, gmt,
263                                -(lon_rad * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
264     }
265
266     SG_LOG( SG_EVENT, SG_DEBUG,
267             "  Current lon=0.00 Sidereal Time = " << gst );
268     SG_LOG( SG_EVENT, SG_DEBUG,
269             "  Current LOCAL Sidereal Time = " << lst << " (" 
270             << sidereal_precise( mjd, -(lon_rad * SGD_RADIANS_TO_DEGREES) ) 
271             << ") (diff = " << gst_diff << ")" );
272 }
273
274
275 // Given lon/lat, update timezone information and local_offset
276 void SGTime::updateLocal( double lon_rad, double lat_rad, const string& root ) {
277     // sanity checking
278     if ( lon_rad < -SGD_PI || lon_rad> SGD_PI ) {
279         // not within -180 ... 180
280         lon_rad = 0.0;
281     }
282     if ( lat_rad < -SGD_PI * 0.5 || lat_rad > SGD_PI * 0.5 ) {
283         // not within -90 ... 90
284         lat_rad = 0.0;
285     }
286     if ( lon_rad != lon_rad ) {
287         // only true if lon_rad == nan
288         SG_LOG( SG_EVENT, SG_ALERT,
289                 "  Detected lon_rad == nan, resetting to 0.0" );
290         lon_rad = 0.0;
291     }
292     if ( lat_rad != lat_rad ) {
293         // only true if lat_rad == nan
294         SG_LOG( SG_EVENT, SG_ALERT,
295                 "  Detected lat_rad == nan, resetting to 0.0" );
296         lat_rad = 0.0;
297     }
298     time_t currGMT;
299     time_t aircraftLocalTime;
300     SGGeoCoord location( SGD_RADIANS_TO_DEGREES * lat_rad,
301                          SGD_RADIANS_TO_DEGREES * lon_rad );
302     SGGeoCoord* nearestTz = tzContainer->getNearest(location);
303     SGPath zone( root );
304     zone.append ( nearestTz->getDescription() );
305     zonename = zone.str();
306
307     //Avoid troubles when zone.tab hasn't got the right line endings
308     if (zonename[zonename.size()-1] == '\r')
309     {
310       zonename[zonename.size()-1]=0;
311       zone.set( zonename );
312     }
313
314     currGMT = sgTimeGetGMT( gmtime(&cur_time) );
315     aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
316     local_offset = aircraftLocalTime - currGMT;
317     // cout << "Using " << local_offset << " as local time offset Timezone is " 
318     //      << zonename << endl;
319 }
320
321
322 // given a date in months, mn, days, dy, years, yr, return the
323 // modified Julian date (number of days elapsed since 1900 jan 0.5),
324 // mjd.  Adapted from Xephem.
325 double sgTimeCalcMJD(int mn, double dy, int yr) {
326     double mjd;
327
328     // internal book keeping data
329     static double last_mjd, last_dy;
330     static int last_mn, last_yr;
331
332     int b, d, m, y;
333     long c;
334   
335     if (mn == last_mn && yr == last_yr && dy == last_dy) {
336         mjd = last_mjd;
337     }
338   
339     m = mn;
340     y = (yr < 0) ? yr + 1 : yr;
341     if (mn < 3) {
342         m += 12;
343         y -= 1;
344     }
345   
346     if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
347         b = 0;
348     } else {
349         int a;
350         a = y/100;
351         b = 2 - a + a/4;
352     }
353   
354     if (y < 0) {
355         c = (long)((365.25*y) - 0.75) - 694025L;
356     } else {
357         c = (long)(365.25*y) - 694025L;
358     }
359   
360     d = (int)(30.6001*(m+1));
361   
362     mjd = b + c + d + dy - 0.5;
363   
364     last_mn = mn;
365     last_dy = dy;
366     last_yr = yr;
367     last_mjd = mjd;
368
369     return mjd;
370 }
371
372
373 // return the current modified Julian date (number of days elapsed
374 // since 1900 jan 0.5), mjd.
375 double sgTimeCurrentMJD( time_t ct, long int warp ) {
376
377 #if defined(_MSC_VER) || defined(__MINGW32__)
378     struct tm m_gmt;    // copy of system gmtime(&time_t) structure
379     struct tm *gmt = &m_gmt;
380 #else
381     struct tm *gmt;
382 #endif
383
384     // get current Unix calendar time (in seconds)
385     // warp += warp_delta;
386     time_t cur_time;
387     if ( ct ) {
388         cur_time = ct + warp;
389     } else {
390         cur_time = time(NULL) + warp;
391     }
392     SG_LOG( SG_EVENT, SG_DEBUG, 
393             "  Current Unix calendar time = " << cur_time 
394             << "  warp = " << warp );
395
396     // get GMT break down for current time
397 #if defined(_MSC_VER) || defined(__MINGW32__)
398     memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
399 #else
400     gmt = gmtime(&cur_time);
401 #endif
402     SG_LOG( SG_EVENT, SG_DEBUG, 
403             "  Current GMT = " << gmt->tm_mon+1 << "/" 
404             << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
405             << gmt->tm_hour << ":" << gmt->tm_min << ":" 
406             << gmt->tm_sec );
407
408     // calculate modified Julian date
409     // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday, 
410     //     (int)(t->gmt->tm_year + 1900));
411     double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday, 
412                                 (int)(gmt->tm_year + 1900) );
413
414     return mjd;
415 }
416
417
418 // given an mjd, calculate greenwich mean sidereal time, gst
419 double sgTimeCalcGST( double mjd ) {
420     double gst;
421
422     double day = floor(mjd-0.5)+0.5;
423     double hr = (mjd-day)*24.0;
424     double T, x;
425
426     T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
427     x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
428     x /= 3600.0;
429     gst = (1.0/SIDRATE)*hr + x;
430
431     SG_LOG( SG_EVENT, SG_DEBUG, "  gst => " << gst );
432
433     return gst;
434 }
435
436
437 #if defined( HAVE_TIMEGM ) 
438     // ignore this function
439 #elif defined( MK_TIME_IS_GMT )
440     // ignore this function
441 #else // ! defined ( MK_TIME_IS_GMT )
442
443     // Fix up timezone if using ftime()
444     static long int fix_up_timezone( long int timezone_orig ) {
445 #   if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
446         // ftime() needs a little extra help finding the current timezone
447         struct timeb current;
448         ftime(&current);
449         return( current.timezone * 60 );
450 #   else
451         return( timezone_orig );
452 #   endif
453     }
454 #endif
455
456
457 /******************************************************************
458  * The following are some functions that were included as SGTime
459  * members, although they currently don't make use of any of the
460  * class's variables. Maybe this'll change in the future
461  *****************************************************************/
462
463 // Return time_t for Sat Mar 21 12:00:00 GMT
464 //
465 // On many systems it is ambiguous if mktime() assumes the input is in
466 // GMT, or local timezone.  To address this, a new function called
467 // timegm() is appearing.  It works exactly like mktime() but
468 // explicitely interprets the input as GMT.
469 //
470 // timegm() is available and documented under FreeBSD.  It is
471 // available, but completely undocumented on my current Debian 2.1
472 // distribution.
473 //
474 // In the absence of timegm() we have to guess what mktime() might do.
475 //
476 // Many older BSD style systems have a mktime() that assumes the input
477 // time in GMT.  But FreeBSD explicitly states that mktime() assumes
478 // local time zone
479 //
480 // The mktime() on many SYSV style systems (such as Linux) usually
481 // returns its result assuming you have specified the input time in
482 // your local timezone.  Therefore, in the absence if timegm() you
483 // have to go to extra trouble to convert back to GMT.
484 //
485 // If you are having problems with incorrectly positioned astronomical
486 // bodies, this is a really good place to start looking.
487
488 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
489 {
490     struct tm mt;
491
492     mt.tm_mon = month;
493     mt.tm_mday = day;
494     mt.tm_year = year;
495     mt.tm_hour = hour;
496     mt.tm_min = min;
497     mt.tm_sec = sec;
498     mt.tm_isdst = -1; // let the system determine the proper time zone
499
500     // For now we assume that if daylight is not defined in
501     // /usr/include/time.h that we have a machine with a mktime() that
502     // assumes input is in GMT ... this only matters if we are
503     // building on a system that does not have timegm()
504 #if !defined(HAVE_DAYLIGHT)
505 #  define MK_TIME_IS_GMT 1
506 #endif
507
508 #if defined( HAVE_TIMEGM )
509     return ( timegm(&mt) );
510 #elif defined( MK_TIME_IS_GMT )
511     time_t ret = mktime(&mt);
512
513 #ifdef __CYGWIN__
514         ret -= _timezone;
515 #endif
516
517     // This is necessary as some mktime() calls may
518     // try to access the system timezone files
519     // if this open fails errno is set to 2
520     // CYGWIN for one does this
521     // if ( errno ) {
522     //     perror( "sgTimeGetGMT()" );
523     //     errno = 0;
524     // }
525
526     // reset errno in any event.
527     errno = 0;
528
529     return ret;
530 #else // ! defined ( MK_TIME_IS_GMT )
531
532     // timezone seems to work as a proper offset for Linux & Solaris
533 #   if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
534 #       define TIMEZONE_OFFSET_WORKS 1
535 #   endif
536
537 #if defined(__CYGWIN__)
538 #define TIMEZONE _timezone
539 #else
540 #define TIMEZONE timezone
541 #endif
542         
543     time_t start = mktime(&mt);
544
545     SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
546     // the ctime() call can screw up time progression on some versions
547     // of Linux
548     // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
549     SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
550
551     TIMEZONE = fix_up_timezone( TIMEZONE );
552
553 #  if defined( TIMEZONE_OFFSET_WORKS )
554     SG_LOG( SG_EVENT, SG_DEBUG,
555             "start = " << start << ", timezone = " << TIMEZONE );
556     return( start - TIMEZONE );
557 #  else // ! defined( TIMEZONE_OFFSET_WORKS )
558
559     daylight = mt.tm_isdst;
560     if ( daylight > 0 ) {
561         daylight = 1;
562     } else if ( daylight < 0 ) {
563         SG_LOG( SG_EVENT, FG_WARN, 
564                 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
565     }
566
567     long int offset = -(TIMEZONE / 3600 - daylight);
568
569     SG_LOG( SG_EVENT, SG_DEBUG, "  Raw time zone offset = " << TIMEZONE );
570     SG_LOG( SG_EVENT, SG_DEBUG, "  Daylight Savings = " << daylight );
571     SG_LOG( SG_EVENT, SG_DEBUG, "  Local hours from GMT = " << offset );
572     
573     long int start_gmt = start - TIMEZONE + (daylight * 3600);
574     
575     SG_LOG( SG_EVENT, SG_DEBUG, "  March 21 noon (CST) = " << start );
576
577     return ( start_gmt );
578 #  endif // ! defined( TIMEZONE_OFFSET_WORKS )
579 #endif // ! defined ( MK_TIME_IS_GMT )
580 }
581
582
583 // format time
584 char* sgTimeFormatTime( const struct tm* p, char* buf )
585 {
586     sprintf( buf, "%d/%d/%2d %d:%02d:%02d", 
587              p->tm_mon, p->tm_mday, p->tm_year,
588              p->tm_hour, p->tm_min, p->tm_sec);
589     return buf;
590 }