1 // TimeManager.cxx -- simulation-wide time management
3 // Written by James Turner, started July 2010.
5 // Copyright (C) 2010 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
25 #include "TimeManager.hxx"
28 # define WIN32_LEAN_AND_MEAN
29 # include <windows.h> // for Sleep()
31 # include <unistd.h> // for usleep()
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>
39 #include <Main/fg_props.hxx>
40 #include <Main/globals.hxx>
41 #include <Time/sunsolver.hxx>
43 TimeManager::TimeManager() :
50 void TimeManager::init()
53 // time manager has to be initialised early, so needs to be defensive
54 // about multiple initialisation
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);
66 _longitudeDeg = fgGetNode("/position/longitude-deg", true);
67 _latitudeDeg = fgGetNode("/position/latitude-deg", true);
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());
75 globals->set_warp_delta(0);
77 globals->get_event_mgr()->addTask("updateLocalTime", this,
78 &TimeManager::updateLocalTime, 30*60 );
81 _impl->update(lon, lat, _timeOverride->getLongValue(),
83 globals->set_time_params(_impl);
85 // frame/update-rate counters
86 _frameRate = fgGetNode("/sim/frame-rate", true);
87 _lastFrameTime = _impl->get_cur_time();
91 void TimeManager::postinit()
96 void TimeManager::reinit()
98 globals->set_time_params(NULL);
101 globals->get_event_mgr()->removeTask("updateLocalTime");
107 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
109 // Update the elapsed time.
112 _firstUpdate = false;
113 _lastClockFreeze = _clockFreeze->getBoolValue();
116 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
117 bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
119 if (!wait_for_scenery) {
120 throttleUpdateRate();
123 SGTimeStamp currentStamp;
124 currentStamp.stamp();
125 double dt = (currentStamp - _lastStamp).toSecs();
127 // Limit the time we need to spend in simulation loops
128 // That means, if the /sim/max-simtime-per-frame value is strictly positive
129 // you can limit the maximum amount of time you will do simulations for
130 // one frame to display. The cpu time spent in simulations code is roughly
131 // at least O(real_delta_time_sec). If this is (due to running debug
132 // builds or valgrind or something different blowing up execution times)
133 // larger than the real time you will no longer get any response
134 // from flightgear. This limits that effect. Just set to property from
135 // your .fgfsrc or commandline ...
136 double dtMax = _maxDtPerFrame->getDoubleValue();
137 if (0 < dtMax && dtMax < dt) {
141 int model_hz = fgGetInt("/sim/model-hz");
143 SGSubsystemGroup* fdmGroup =
144 globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
145 fdmGroup->set_fixed_update_time(1.0 / model_hz);
147 // round the real time down to a multiple of 1/model-hz.
148 // this way all systems are updated the _same_ amount of dt.
150 int multiLoop = long(floor(dt * model_hz));
151 multiLoop = SGMisc<long>::max(0, multiLoop);
152 _dtRemainder = dt - double(multiLoop)/double(model_hz);
153 dt = double(multiLoop)/double(model_hz);
156 if (_clockFreeze->getBoolValue() || wait_for_scenery) {
162 _lastStamp = currentStamp;
163 globals->inc_sim_time_sec(simDt);
165 // These are useful, especially for Nasal scripts.
166 fgSetDouble("/sim/time/delta-realtime-sec", realDt);
167 fgSetDouble("/sim/time/delta-sec", simDt);
170 void TimeManager::update(double dt)
172 bool freeze = _clockFreeze->getBoolValue();
174 // clock freeze requested
175 if (_timeOverride->getLongValue() == 0) {
176 fgSetLong( "/sim/time/cur-time-override", _impl->get_cur_time());
177 globals->set_warp(0);
180 // no clock freeze requested
181 if (_lastClockFreeze) {
182 // clock just unfroze, let's set warp as the difference
183 // between frozen time and current time so we don't get a
184 // time jump (and corresponding sky object and lighting
186 globals->set_warp(_timeOverride->getLongValue() - time(NULL));
187 fgSetLong( "/sim/time/cur-time-override", 0 );
190 if ( globals->get_warp_delta() != 0 ) {
191 globals->inc_warp( globals->get_warp_delta() );
195 _lastClockFreeze = freeze;
196 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
197 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
198 _impl->update(lon, lat,
199 _timeOverride->getLongValue(),
200 globals->get_warp());
205 void TimeManager::computeFrameRate()
207 // Calculate frame rate average
208 if ((_impl->get_cur_time() != _lastFrameTime) && (_lastFrameTime > 0)) {
209 _frameRate->setIntValue(_frameCount);
213 _lastFrameTime = _impl->get_cur_time();
217 void TimeManager::throttleUpdateRate()
219 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
220 SGTimeStamp currentStamp;
222 // common case, no throttle requested
223 if (throttle_hz <= 0.0) {
227 double frame_us = 1000000.0 / throttle_hz;
228 #define FG_SLEEP_BASED_TIMING 1
229 #if defined(FG_SLEEP_BASED_TIMING)
230 // sleep based timing loop.
232 // Calling sleep, even usleep() on linux is less accurate than
233 // we like, but it does free up the cpu for other tasks during
234 // the sleep so it is desirable. Because of the way sleep()
235 // is implemented in consumer operating systems like windows
236 // and linux, you almost always sleep a little longer than the
239 // To combat the problem of sleeping too long, we calculate the
240 // desired wait time and shorten it by 2000us (2ms) to avoid
241 // [hopefully] over-sleep'ing. The 2ms value was arrived at
242 // via experimentation. We follow this up at the end with a
243 // simple busy-wait loop to get the final pause timing exactly
246 // Assuming we don't oversleep by more than 2000us, this
247 // should be a reasonable compromise between sleep based
248 // waiting, and busy waiting.
250 // sleep() will always overshoot by a bit so undersleep by
251 // 2000us in the hopes of never oversleeping.
253 if ( frame_us < 0.0 ) {
257 currentStamp.stamp();
259 double elapsed_us = (currentStamp - _lastStamp).toUSecs();
260 if ( elapsed_us < frame_us ) {
261 double requested_us = frame_us - elapsed_us;
264 Sleep ((int)(requested_us / 1000.0)) ;
266 usleep(requested_us) ;
271 // busy wait timing loop.
273 // This yields the most accurate timing. If the previous
274 // ulMilliSecondSleep() call is omitted this will peg the cpu
275 // (which is just fine if FG is the only app you care about.)
276 currentStamp.stamp();
277 SGTimeStamp next_time_stamp = _lastStamp;
278 next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
279 while ( currentStamp < next_time_stamp ) {
280 currentStamp.stamp();
284 // periodic time updater wrapper
285 void TimeManager::updateLocalTime()
287 SGPath zone(globals->get_fg_root());
288 zone.append("Timezone");
290 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
291 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
293 SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
294 _impl->updateLocal(lon, lat, zone.str());
297 void TimeManager::initTimeOffset()
299 // Handle potential user specified time offsets
300 int orig_warp = globals->get_warp();
301 time_t cur_time = _impl->get_cur_time();
302 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
303 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
304 time_t aircraftLocalTime =
305 sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
307 // Okay, we now have several possible scenarios
308 int offset = fgGetInt("/sim/startup/time-offset");
309 string offset_type = fgGetString("/sim/startup/time-offset-type");
310 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
311 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
314 if ( offset_type == "real" ) {
316 } else if ( offset_type == "dawn" ) {
317 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true );
318 } else if ( offset_type == "morning" ) {
319 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true );
320 } else if ( offset_type == "noon" ) {
321 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true );
322 } else if ( offset_type == "afternoon" ) {
323 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 60.0, false );
324 } else if ( offset_type == "dusk" ) {
325 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
326 } else if ( offset_type == "evening" ) {
327 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
328 } else if ( offset_type == "midnight" ) {
329 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
330 } else if ( offset_type == "system-offset" ) {
333 } else if ( offset_type == "gmt-offset" ) {
334 warp = offset - (currGMT - systemLocalTime);
336 } else if ( offset_type == "latitude-offset" ) {
337 warp = offset - (aircraftLocalTime - systemLocalTime);
339 } else if ( offset_type == "system" ) {
340 warp = offset - (systemLocalTime - currGMT) - cur_time;
341 } else if ( offset_type == "gmt" ) {
342 warp = offset - cur_time;
343 } else if ( offset_type == "latitude" ) {
344 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
346 SG_LOG( SG_GENERAL, SG_ALERT,
347 "TimeManager::initTimeOffset: unsupported offset: " << offset_type );
351 globals->set_warp( orig_warp + warp );
352 _impl->update(lon, lat, _timeOverride->getLongValue(),
353 globals->get_warp() );
355 SG_LOG( SG_GENERAL, SG_INFO, "After fgInitTimeOffset(): warp = "
356 << globals->get_warp() );