]> git.mxchange.org Git - flightgear.git/blob - src/Time/TimeManager.cxx
Create TimeManager subsystem, and collect the time related code out of main.cxx and...
[flightgear.git] / src / Time / TimeManager.cxx
1 // TimeManager.cxx -- simulation-wide time management
2 //
3 // Written by James Turner, started July 2010.
4 //
5 // Copyright (C) 2010  Curtis L. Olson  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 # include "config.h"
23 #endif
24
25 #include "TimeManager.hxx"
26
27 #ifdef _WIN32
28 #  define WIN32_LEAN_AND_MEAN
29 #  include <windows.h> // for Sleep()
30 #else
31 #  include <unistd.h> // for usleep()
32 #endif
33
34 #include <simgear/timing/sg_time.hxx>
35 #include <simgear/structure/event_mgr.hxx>
36 #include <simgear/misc/sg_path.hxx>
37 #include <simgear/timing/lowleveltime.h>
38
39 #include <Main/fg_props.hxx>
40 #include <Main/globals.hxx>
41 #include <Time/sunsolver.hxx>
42
43 TimeManager::TimeManager() :
44   _inited(false),
45   _impl(NULL)
46 {
47   
48 }
49
50 void TimeManager::init()
51 {
52   if (_inited) {
53     // time manager has to be initialised early, so needs to be defensive
54     // about multiple initialisation 
55     return; 
56   }
57   
58   _firstUpdate = true;
59   _inited = true;
60   _dtRemainder = 0.0;
61   
62   _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
63   _clockFreeze = fgGetNode("/sim/freeze/clock", true);
64   _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
65   
66   _longitudeDeg = fgGetNode("/position/longitude-deg", true);
67   _latitudeDeg = fgGetNode("/position/latitude-deg", true);
68   
69   SGPath zone(globals->get_fg_root());
70   zone.append("Timezone");
71   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
72   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
73   _impl = new SGTime(lon, lat, zone.str(), _timeOverride->getLongValue());
74   
75   globals->set_warp_delta(0);
76   
77   globals->get_event_mgr()->addTask("updateLocalTime", this,
78                             &TimeManager::updateLocalTime, 30*60 );
79   updateLocalTime();
80   
81   _impl->update(lon, lat, _timeOverride->getLongValue(),
82                globals->get_warp());
83   globals->set_time_params(_impl);
84   
85   initTimeOffset();
86   
87 // frame/update-rate counters
88   _frameRate = fgGetNode("/sim/frame-rate", true);
89   _lastFrameTime = _impl->get_cur_time();
90   _frameCount = 0;
91 }
92
93 void TimeManager::postinit()
94 {
95   initTimeOffset();
96 }
97
98 void TimeManager::reinit()
99 {
100   globals->set_time_params(NULL);
101   delete _impl;
102   _inited = false;
103   globals->get_event_mgr()->removeTask("updateLocalTime");
104   
105   init();
106   postinit();
107 }
108
109 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
110 {
111   // Update the elapsed time.
112   if (_firstUpdate) {
113     _lastStamp.stamp();
114     _firstUpdate = false;
115     _lastClockFreeze = _clockFreeze->getBoolValue();
116   }
117
118   bool scenery_loaded = fgGetBool("sim/sceneryloaded");
119   bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
120   
121   if (!wait_for_scenery) {
122     throttleUpdateRate();
123   }
124   
125   SGTimeStamp currentStamp;
126   currentStamp.stamp();
127   double dt = (currentStamp - _lastStamp).toSecs();
128   
129 // Limit the time we need to spend in simulation loops
130 // That means, if the /sim/max-simtime-per-frame value is strictly positive
131 // you can limit the maximum amount of time you will do simulations for
132 // one frame to display. The cpu time spent in simulations code is roughly
133 // at least O(real_delta_time_sec). If this is (due to running debug
134 // builds or valgrind or something different blowing up execution times)
135 // larger than the real time you will no longer get any response
136 // from flightgear. This limits that effect. Just set to property from
137 // your .fgfsrc or commandline ...
138   double dtMax = _maxDtPerFrame->getDoubleValue();
139   if (0 < dtMax && dtMax < dt) {
140     dt = dtMax;
141   }
142   
143   int model_hz = fgGetInt("/sim/model-hz");
144   
145   SGSubsystemGroup* fdmGroup = 
146     globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
147   fdmGroup->set_fixed_update_time(1.0 / model_hz);
148   
149 // round the real time down to a multiple of 1/model-hz.
150 // this way all systems are updated the _same_ amount of dt.
151   dt += _dtRemainder;
152   int multiLoop = long(floor(dt * model_hz));
153   multiLoop = SGMisc<long>::max(0, multiLoop);
154   _dtRemainder = dt - double(multiLoop)/double(model_hz);
155   dt = double(multiLoop)/double(model_hz);
156
157   realDt = dt;
158   if (_clockFreeze->getBoolValue() || wait_for_scenery) {
159     simDt = 0;
160   } else {
161     simDt = dt;
162   }
163   
164   _lastStamp = currentStamp;
165   globals->inc_sim_time_sec(simDt);
166
167 // These are useful, especially for Nasal scripts.
168   fgSetDouble("/sim/time/delta-realtime-sec", realDt);
169   fgSetDouble("/sim/time/delta-sec", simDt);
170 }
171
172 void TimeManager::update(double dt)
173 {
174   bool freeze = _clockFreeze->getBoolValue();
175   if (freeze) {
176     // clock freeze requested
177     if (_timeOverride->getLongValue() == 0) {
178       fgSetLong( "/sim/time/cur-time-override", _impl->get_cur_time());
179       globals->set_warp(0);
180     }
181   } else {
182     // no clock freeze requested
183     if (_lastClockFreeze) {
184     // clock just unfroze, let's set warp as the difference
185     // between frozen time and current time so we don't get a
186     // time jump (and corresponding sky object and lighting
187     // jump.)
188       globals->set_warp(_timeOverride->getLongValue() - time(NULL));
189       fgSetLong( "/sim/time/cur-time-override", 0 );
190     }
191     
192     if ( globals->get_warp_delta() != 0 ) {
193       globals->inc_warp( globals->get_warp_delta() );
194     }
195   }
196
197   _lastClockFreeze = freeze;
198   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
199   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
200   _impl->update(lon, lat,
201                _timeOverride->getLongValue(),
202                globals->get_warp());
203
204   computeFrameRate();
205 }
206
207 void TimeManager::computeFrameRate()
208 {
209   // Calculate frame rate average
210   if ((_impl->get_cur_time() != _lastFrameTime) && (_lastFrameTime > 0)) {
211     _frameRate->setIntValue(_frameCount);
212     _frameCount = 0;
213   }
214   
215   _lastFrameTime = _impl->get_cur_time();
216   ++_frameCount;
217 }
218
219 void TimeManager::throttleUpdateRate()
220 {
221   double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
222   SGTimeStamp currentStamp;
223   
224   // common case, no throttle requested
225   if (throttle_hz <= 0.0) {
226     return; // no-op
227   }
228   
229   double frame_us = 1000000.0 / throttle_hz;
230 #define FG_SLEEP_BASED_TIMING 1
231 #if defined(FG_SLEEP_BASED_TIMING)
232   // sleep based timing loop.
233   //
234   // Calling sleep, even usleep() on linux is less accurate than
235   // we like, but it does free up the cpu for other tasks during
236   // the sleep so it is desirable.  Because of the way sleep()
237   // is implemented in consumer operating systems like windows
238   // and linux, you almost always sleep a little longer than the
239   // requested amount.
240   //
241   // To combat the problem of sleeping too long, we calculate the
242   // desired wait time and shorten it by 2000us (2ms) to avoid
243   // [hopefully] over-sleep'ing.  The 2ms value was arrived at
244   // via experimentation.  We follow this up at the end with a
245   // simple busy-wait loop to get the final pause timing exactly
246   // right.
247   //
248   // Assuming we don't oversleep by more than 2000us, this
249   // should be a reasonable compromise between sleep based
250   // waiting, and busy waiting.
251
252   // sleep() will always overshoot by a bit so undersleep by
253   // 2000us in the hopes of never oversleeping.
254   frame_us -= 2000.0;
255   if ( frame_us < 0.0 ) {
256       frame_us = 0.0;
257   }
258   
259   currentStamp.stamp();
260
261   double elapsed_us = (currentStamp - _lastStamp).toUSecs();
262   if ( elapsed_us < frame_us ) {
263     double requested_us = frame_us - elapsed_us;
264  
265 #ifdef _WIN32
266     Sleep ((int)(requested_us / 1000.0)) ;
267 #else
268     usleep(requested_us) ;
269 #endif
270   }
271 #endif
272
273   // busy wait timing loop.
274   //
275   // This yields the most accurate timing.  If the previous
276   // ulMilliSecondSleep() call is omitted this will peg the cpu
277   // (which is just fine if FG is the only app you care about.)
278   currentStamp.stamp();
279   SGTimeStamp next_time_stamp = _lastStamp;
280   next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
281   while ( currentStamp < next_time_stamp ) {
282       currentStamp.stamp();
283   }
284 }
285
286 // periodic time updater wrapper
287 void TimeManager::updateLocalTime() 
288 {
289   SGPath zone(globals->get_fg_root());
290   zone.append("Timezone");
291   
292   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
293   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
294   
295   SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
296   _impl->updateLocal(lon, lat, zone.str());
297 }
298
299 void TimeManager::initTimeOffset()
300 {
301   // Handle potential user specified time offsets
302   int orig_warp = globals->get_warp();
303   time_t cur_time = _impl->get_cur_time();
304   time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
305   time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
306   time_t aircraftLocalTime = 
307       sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
308     
309   // Okay, we now have several possible scenarios
310   int offset = fgGetInt("/sim/startup/time-offset");
311   string offset_type = fgGetString("/sim/startup/time-offset-type");
312   double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
313   double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
314   int warp = 0;
315   
316   if ( offset_type == "real" ) {
317       warp = 0;
318   } else if ( offset_type == "dawn" ) {
319       warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true ); 
320   } else if ( offset_type == "morning" ) {
321      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true ); 
322   } else if ( offset_type == "noon" ) {
323      warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true ); 
324   } else if ( offset_type == "afternoon" ) {
325     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 60.0, false );  
326   } else if ( offset_type == "dusk" ) {
327     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
328   } else if ( offset_type == "evening" ) {
329     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
330   } else if ( offset_type == "midnight" ) {
331     warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
332   } else if ( offset_type == "system-offset" ) {
333     warp = offset;
334     orig_warp = 0;
335   } else if ( offset_type == "gmt-offset" ) {
336     warp = offset - (currGMT - systemLocalTime);
337     orig_warp = 0;
338   } else if ( offset_type == "latitude-offset" ) {
339     warp = offset - (aircraftLocalTime - systemLocalTime);
340     orig_warp = 0;
341   } else if ( offset_type == "system" ) {
342     warp = offset - (systemLocalTime - currGMT) - cur_time;
343   } else if ( offset_type == "gmt" ) {
344       warp = offset - cur_time;
345   } else if ( offset_type == "latitude" ) {
346       warp = offset - (aircraftLocalTime - currGMT)- cur_time; 
347   } else {
348     SG_LOG( SG_GENERAL, SG_ALERT,
349           "TimeManager::initTimeOffset: unsupported offset: " << offset_type );
350      warp = 0;
351   }
352   
353   globals->set_warp( orig_warp + warp );
354   _impl->update(lon, lat, _timeOverride->getLongValue(),
355                globals->get_warp() );
356
357   SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = " 
358             << globals->get_warp() );
359 }