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"
27 #include <simgear/timing/sg_time.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29 #include <simgear/misc/sg_path.hxx>
30 #include <simgear/timing/lowleveltime.h>
31 #include <simgear/structure/commands.hxx>
33 #include <Main/fg_props.hxx>
34 #include <Main/globals.hxx>
35 #include <Time/sunsolver.hxx>
39 static bool do_timeofday (const SGPropertyNode * arg)
41 const string &offset_type = arg->getStringValue("timeofday", "noon");
42 int offset = arg->getIntValue("offset", 0);
43 TimeManager* self = (TimeManager*) globals->get_subsystem("time");
44 if (offset_type == "real") {
45 // without this, setting 'real' time is a no-op, since the current
46 // wrap value (orig_warp) is retained in setTimeOffset. Ick.
47 fgSetInt("/sim/time/warp", 0);
50 self->setTimeOffset(offset_type, offset);
54 TimeManager::TimeManager() :
57 _sceneryLoaded("sim/sceneryloaded"),
58 _sceneryLoadOverride("sim/sceneryloaded-override"),
59 _modelHz("sim/model-hz"),
60 _timeDelta("sim/time/delta-realtime-sec"),
61 _simTimeDelta("sim/time/delta-sec")
63 SGCommandMgr::instance()->addCommand("timeofday", do_timeofday);
66 void TimeManager::init()
69 // time manager has to be initialised early, so needs to be defensive
70 // about multiple initialisation
77 _adjustWarpOnUnfreeze = false;
79 _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
80 _clockFreeze = fgGetNode("/sim/freeze/clock", true);
81 _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
82 _warp = fgGetNode("/sim/time/warp", true);
83 _warp->addChangeListener(this);
85 _warpDelta = fgGetNode("/sim/time/warp-delta", true);
87 _longitudeDeg = fgGetNode("/position/longitude-deg", true);
88 _latitudeDeg = fgGetNode("/position/latitude-deg", true);
90 SGPath zone(globals->get_fg_root());
91 zone.append("Timezone");
92 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
93 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
95 _impl = new SGTime(lon, lat, zone.str(), _timeOverride->getLongValue());
97 _warpDelta->setIntValue(0);
99 globals->get_event_mgr()->addTask("updateLocalTime", this,
100 &TimeManager::updateLocalTime, 30*60 );
103 _impl->update(lon, lat, _timeOverride->getLongValue(),
104 _warp->getIntValue());
105 globals->set_time_params(_impl);
107 // frame-rate / worst-case latency / update-rate counters
108 _frameRate = fgGetNode("/sim/frame-rate", true);
109 _frameLatency = fgGetNode("/sim/frame-latency-max-ms", true);
110 _frameRateWorst = fgGetNode("/sim/frame-rate-worst", true);
112 _frameLatencyMax = 0.0;
116 void TimeManager::postinit()
121 void TimeManager::reinit()
128 void TimeManager::shutdown()
130 _warp->removeChangeListener(this);
132 globals->set_time_params(NULL);
136 globals->get_event_mgr()->removeTask("updateLocalTime");
139 void TimeManager::valueChanged(SGPropertyNode* aProp)
141 if (aProp == _warp) {
142 if (_clockFreeze->getBoolValue()) {
143 // if the warp is changed manually while frozen, don't modify it when
144 // un-freezing - the user wants to unfreeze with exactly the warp
146 _adjustWarpOnUnfreeze = false;
149 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
150 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
151 _impl->update(lon, lat,
152 _timeOverride->getLongValue(),
153 _warp->getIntValue());
157 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
159 // Update the elapsed time.
162 _firstUpdate = false;
163 _lastClockFreeze = _clockFreeze->getBoolValue();
166 bool wait_for_scenery = !(_sceneryLoaded || _sceneryLoadOverride);
167 if (!wait_for_scenery) {
168 throttleUpdateRate();
172 // suppress framerate while initial scenery isn't loaded yet (splash screen still active)
177 SGTimeStamp currentStamp;
178 currentStamp.stamp();
179 double dt = (currentStamp - _lastStamp).toSecs();
180 if (dt > _frameLatencyMax)
181 _frameLatencyMax = dt;
183 // Limit the time we need to spend in simulation loops
184 // That means, if the /sim/max-simtime-per-frame value is strictly positive
185 // you can limit the maximum amount of time you will do simulations for
186 // one frame to display. The cpu time spent in simulations code is roughly
187 // at least O(real_delta_time_sec). If this is (due to running debug
188 // builds or valgrind or something different blowing up execution times)
189 // larger than the real time you will no longer get any response
190 // from flightgear. This limits that effect. Just set to property from
191 // your .fgfsrc or commandline ...
192 double dtMax = _maxDtPerFrame->getDoubleValue();
193 if (0 < dtMax && dtMax < dt) {
197 SGSubsystemGroup* fdmGroup =
198 globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
199 fdmGroup->set_fixed_update_time(1.0 / _modelHz);
201 // round the real time down to a multiple of 1/model-hz.
202 // this way all systems are updated the _same_ amount of dt.
204 int multiLoop = long(floor(dt * _modelHz));
205 multiLoop = SGMisc<long>::max(0, multiLoop);
206 _dtRemainder = dt - double(multiLoop)/double(_modelHz);
207 dt = double(multiLoop)/double(_modelHz);
210 if (_clockFreeze->getBoolValue() || wait_for_scenery) {
216 _lastStamp = currentStamp;
217 globals->inc_sim_time_sec(simDt);
219 // These are useful, especially for Nasal scripts.
221 _simTimeDelta = simDt;
224 void TimeManager::update(double dt)
226 bool freeze = _clockFreeze->getBoolValue();
227 time_t now = time(NULL);
230 // clock freeze requested
231 if (_timeOverride->getLongValue() == 0) {
232 _timeOverride->setLongValue(now);
233 _adjustWarpOnUnfreeze = true;
236 // no clock freeze requested
237 if (_lastClockFreeze) {
238 if (_adjustWarpOnUnfreeze) {
239 // clock just unfroze, let's set warp as the difference
240 // between frozen time and current time so we don't get a
241 // time jump (and corresponding sky object and lighting
243 int adjust = _timeOverride->getLongValue() - now;
244 SG_LOG(SG_GENERAL, SG_INFO, "adjusting on un-freeze:" << adjust);
245 _warp->setIntValue(_warp->getIntValue() + adjust);
247 _timeOverride->setLongValue(0);
250 int warpDelta = _warpDelta->getIntValue();
251 if (warpDelta != 0) {
252 _warp->setIntValue(_warp->getIntValue() + warpDelta);
256 _lastClockFreeze = freeze;
257 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
258 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
259 _impl->update(lon, lat,
260 _timeOverride->getLongValue(),
261 _warp->getIntValue());
266 void TimeManager::computeFrameRate()
268 // Calculate frame rate average
269 if ((_impl->get_cur_time() != _lastFrameTime)) {
270 _frameRate->setIntValue(_frameCount);
271 _frameLatency->setDoubleValue(_frameLatencyMax*1000);
272 if (_frameLatencyMax>0)
273 _frameRateWorst->setIntValue(1/_frameLatencyMax);
275 _frameLatencyMax = 0.0;
278 _lastFrameTime = _impl->get_cur_time();
282 void TimeManager::throttleUpdateRate()
284 // common case, no throttle requested
285 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
286 if (throttle_hz <= 0)
289 // sleep for exactly 1/hz seconds relative to the past valid timestamp
290 SGTimeStamp::sleepUntil(_lastStamp + SGTimeStamp::fromSec(1/throttle_hz));
293 // periodic time updater wrapper
294 void TimeManager::updateLocalTime()
296 SGPath zone(globals->get_fg_root());
297 zone.append("Timezone");
299 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
300 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
302 SG_LOG(SG_GENERAL, SG_INFO, "updateLocal(" << lon << ", " << lat << ", " << zone.str() << ")");
303 _impl->updateLocal(lon, lat, zone.str());
306 void TimeManager::initTimeOffset()
309 long int offset = fgGetLong("/sim/startup/time-offset");
310 string offset_type = fgGetString("/sim/startup/time-offset-type");
311 setTimeOffset(offset_type, offset);
314 void TimeManager::setTimeOffset(const std::string& offset_type, long int offset)
316 // Handle potential user specified time offsets
317 int orig_warp = _warp->getIntValue();
318 time_t cur_time = _impl->get_cur_time();
319 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
320 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
321 time_t aircraftLocalTime =
322 sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
324 // Okay, we now have several possible scenarios
325 double lon = _longitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
326 double lat = _latitudeDeg->getDoubleValue() * SG_DEGREES_TO_RADIANS;
329 if ( offset_type == "real" ) {
331 } else if ( offset_type == "dawn" ) {
332 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, true );
333 } else if ( offset_type == "morning" ) {
334 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, true );
335 } else if ( offset_type == "noon" ) {
336 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 0.0, true );
337 } else if ( offset_type == "afternoon" ) {
338 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 75.0, false );
339 } else if ( offset_type == "dusk" ) {
340 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 90.0, false );
341 } else if ( offset_type == "evening" ) {
342 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 100.0, false );
343 } else if ( offset_type == "midnight" ) {
344 warp = fgTimeSecondsUntilSunAngle( cur_time, lon, lat, 180.0, false );
345 } else if ( offset_type == "system-offset" ) {
348 } else if ( offset_type == "gmt-offset" ) {
349 warp = offset - (currGMT - systemLocalTime);
351 } else if ( offset_type == "latitude-offset" ) {
352 warp = offset - (aircraftLocalTime - systemLocalTime);
354 } else if ( offset_type == "system" ) {
355 warp = offset - (systemLocalTime - currGMT) - cur_time;
356 } else if ( offset_type == "gmt" ) {
357 warp = offset - cur_time;
358 } else if ( offset_type == "latitude" ) {
359 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
361 SG_LOG( SG_GENERAL, SG_ALERT,
362 "TimeManager::setTimeOffset: unsupported offset: " << offset_type );
366 _warp->setIntValue( orig_warp + warp );
368 SG_LOG( SG_GENERAL, SG_INFO, "After TimeManager::setTimeOffset(): warp = "
369 << _warp->getIntValue() );