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>
32 #include <simgear/math/SGMath.hxx>
34 #include <Main/fg_props.hxx>
35 #include <Main/globals.hxx>
36 #include <Time/sunsolver.hxx>
40 static bool do_timeofday (const SGPropertyNode * arg)
42 const string &offset_type = arg->getStringValue("timeofday", "noon");
43 int offset = arg->getIntValue("offset", 0);
44 TimeManager* self = (TimeManager*) globals->get_subsystem("time");
45 if (offset_type == "real") {
46 // without this, setting 'real' time is a no-op, since the current
47 // wrap value (orig_warp) is retained in setTimeOffset. Ick.
48 fgSetInt("/sim/time/warp", 0);
51 self->setTimeOffset(offset_type, offset);
55 TimeManager::TimeManager() :
59 globals->get_commands()->addCommand("timeofday", do_timeofday);
62 TimeManager::~TimeManager()
64 globals->get_commands()->removeCommand("timeofday");
67 void TimeManager::init()
70 // time manager has to be initialised early, so needs to be defensive
71 // about multiple initialisation
78 _adjustWarpOnUnfreeze = false;
80 _maxDtPerFrame = fgGetNode("/sim/max-simtime-per-frame", true);
81 _clockFreeze = fgGetNode("/sim/freeze/clock", true);
82 _timeOverride = fgGetNode("/sim/time/cur-time-override", true);
83 _warp = fgGetNode("/sim/time/warp", true);
84 _warp->addChangeListener(this);
86 _warpDelta = fgGetNode("/sim/time/warp-delta", true);
88 SGPath zone(globals->get_fg_root());
89 zone.append("Timezone");
91 _impl = new SGTime(globals->get_aircraft_position(), zone, _timeOverride->getLongValue());
93 _warpDelta->setIntValue(0);
95 globals->get_event_mgr()->addTask("updateLocalTime", this,
96 &TimeManager::updateLocalTime, 30*60 );
99 _impl->update(globals->get_aircraft_position(), _timeOverride->getLongValue(),
100 _warp->getIntValue());
101 globals->set_time_params(_impl);
103 // frame-rate / worst-case latency / update-rate counters
104 _frameRate = fgGetNode("/sim/frame-rate", true);
105 _frameLatency = fgGetNode("/sim/frame-latency-max-ms", true);
106 _frameRateWorst = fgGetNode("/sim/frame-rate-worst", true);
108 _frameLatencyMax = 0.0;
111 _sceneryLoaded = fgGetNode("sim/sceneryloaded", true);
112 _modelHz = fgGetNode("sim/model-hz", true);
113 _timeDelta = fgGetNode("sim/time/delta-realtime-sec", true);
114 _simTimeDelta = fgGetNode("sim/time/delta-sec", true);
117 void TimeManager::unbind()
119 _maxDtPerFrame.clear();
120 _clockFreeze.clear();
121 _timeOverride.clear();
125 _frameLatency.clear();
126 _frameRateWorst.clear();
128 _sceneryLoaded.clear();
131 _simTimeDelta.clear();
134 void TimeManager::postinit()
139 void TimeManager::reinit()
146 void TimeManager::shutdown()
148 _warp->removeChangeListener(this);
150 globals->set_time_params(NULL);
154 globals->get_event_mgr()->removeTask("updateLocalTime");
157 void TimeManager::valueChanged(SGPropertyNode* aProp)
159 if (aProp == _warp) {
160 if (_clockFreeze->getBoolValue()) {
161 // if the warp is changed manually while frozen, don't modify it when
162 // un-freezing - the user wants to unfreeze with exactly the warp
164 _adjustWarpOnUnfreeze = false;
167 _impl->update(globals->get_aircraft_position(),
168 _timeOverride->getLongValue(),
169 _warp->getIntValue());
173 void TimeManager::computeTimeDeltas(double& simDt, double& realDt)
175 // Update the elapsed time.
178 _firstUpdate = false;
179 _lastClockFreeze = _clockFreeze->getBoolValue();
182 bool wait_for_scenery = !_sceneryLoaded->getBoolValue();
183 if (!wait_for_scenery) {
184 throttleUpdateRate();
188 // suppress framerate while initial scenery isn't loaded yet (splash screen still active)
193 SGTimeStamp currentStamp;
194 currentStamp.stamp();
195 double dt = (currentStamp - _lastStamp).toSecs();
196 if (dt > _frameLatencyMax)
197 _frameLatencyMax = dt;
199 // Limit the time we need to spend in simulation loops
200 // That means, if the /sim/max-simtime-per-frame value is strictly positive
201 // you can limit the maximum amount of time you will do simulations for
202 // one frame to display. The cpu time spent in simulations code is roughly
203 // at least O(real_delta_time_sec). If this is (due to running debug
204 // builds or valgrind or something different blowing up execution times)
205 // larger than the real time you will no longer get any response
206 // from flightgear. This limits that effect. Just set to property from
207 // your .fgfsrc or commandline ...
208 double dtMax = _maxDtPerFrame->getDoubleValue();
209 if (0 < dtMax && dtMax < dt) {
213 SGSubsystemGroup* fdmGroup =
214 globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
215 double modelHz = _modelHz->getDoubleValue();
216 fdmGroup->set_fixed_update_time(1.0 / modelHz);
218 // round the real time down to a multiple of 1/model-hz.
219 // this way all systems are updated the _same_ amount of dt.
221 int multiLoop = long(floor(dt * modelHz));
222 multiLoop = SGMisc<long>::max(0, multiLoop);
223 _dtRemainder = dt - double(multiLoop)/modelHz;
224 dt = double(multiLoop)/modelHz;
227 if (_clockFreeze->getBoolValue() || wait_for_scenery) {
233 _lastStamp = currentStamp;
234 globals->inc_sim_time_sec(simDt);
236 // These are useful, especially for Nasal scripts.
237 _timeDelta->setDoubleValue(realDt);
238 _simTimeDelta->setDoubleValue(simDt);
241 void TimeManager::update(double dt)
243 bool freeze = _clockFreeze->getBoolValue();
244 time_t now = time(NULL);
247 // clock freeze requested
248 if (_timeOverride->getLongValue() == 0) {
249 _timeOverride->setLongValue(now);
250 _adjustWarpOnUnfreeze = true;
253 // no clock freeze requested
254 if (_lastClockFreeze) {
255 if (_adjustWarpOnUnfreeze) {
256 // clock just unfroze, let's set warp as the difference
257 // between frozen time and current time so we don't get a
258 // time jump (and corresponding sky object and lighting
260 int adjust = _timeOverride->getLongValue() - now;
261 SG_LOG(SG_GENERAL, SG_DEBUG, "adjusting on un-freeze:" << adjust);
262 _warp->setIntValue(_warp->getIntValue() + adjust);
264 _timeOverride->setLongValue(0);
267 int warpDelta = _warpDelta->getIntValue();
268 if (warpDelta != 0) {
269 _warp->setIntValue(_warp->getIntValue() + warpDelta);
273 _lastClockFreeze = freeze;
274 _impl->update(globals->get_aircraft_position(),
275 _timeOverride->getLongValue(),
276 _warp->getIntValue());
281 void TimeManager::computeFrameRate()
283 // Calculate frame rate average
284 if ((_impl->get_cur_time() != _lastFrameTime)) {
285 _frameRate->setIntValue(_frameCount);
286 _frameLatency->setDoubleValue(_frameLatencyMax*1000);
287 if (_frameLatencyMax>0)
288 _frameRateWorst->setIntValue(1/_frameLatencyMax);
290 _frameLatencyMax = 0.0;
293 _lastFrameTime = _impl->get_cur_time();
297 void TimeManager::throttleUpdateRate()
299 // common case, no throttle requested
300 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
301 if (throttle_hz <= 0)
304 // sleep for exactly 1/hz seconds relative to the past valid timestamp
305 SGTimeStamp::sleepUntil(_lastStamp + SGTimeStamp::fromSec(1/throttle_hz));
308 // periodic time updater wrapper
309 void TimeManager::updateLocalTime()
311 SGPath zone(globals->get_fg_root());
312 zone.append("Timezone");
313 _impl->updateLocal(globals->get_aircraft_position(), zone.str());
316 void TimeManager::initTimeOffset()
319 long int offset = fgGetLong("/sim/startup/time-offset");
320 string offset_type = fgGetString("/sim/startup/time-offset-type");
321 setTimeOffset(offset_type, offset);
324 void TimeManager::setTimeOffset(const std::string& offset_type, long int offset)
326 // Handle potential user specified time offsets
327 int orig_warp = _warp->getIntValue();
328 time_t cur_time = _impl->get_cur_time();
329 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
330 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
331 time_t aircraftLocalTime =
332 sgTimeGetGMT( fgLocaltime(&cur_time, _impl->get_zonename() ) );
334 // Okay, we now have several possible scenarios
335 SGGeod loc = globals->get_aircraft_position();
338 if ( offset_type == "real" ) {
340 } else if ( offset_type == "dawn" ) {
341 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 90.0, true );
342 } else if ( offset_type == "morning" ) {
343 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 75.0, true );
344 } else if ( offset_type == "noon" ) {
345 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 0.0, true );
346 } else if ( offset_type == "afternoon" ) {
347 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 75.0, false );
348 } else if ( offset_type == "dusk" ) {
349 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 90.0, false );
350 } else if ( offset_type == "evening" ) {
351 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 100.0, false );
352 } else if ( offset_type == "midnight" ) {
353 warp = fgTimeSecondsUntilSunAngle( cur_time, loc, 180.0, false );
354 } else if ( offset_type == "system-offset" ) {
357 } else if ( offset_type == "gmt-offset" ) {
358 warp = offset - (currGMT - systemLocalTime);
360 } else if ( offset_type == "latitude-offset" ) {
361 warp = offset - (aircraftLocalTime - systemLocalTime);
363 } else if ( offset_type == "system" ) {
364 warp = offset - (systemLocalTime - currGMT) - cur_time;
365 } else if ( offset_type == "gmt" ) {
366 warp = offset - cur_time;
367 } else if ( offset_type == "latitude" ) {
368 warp = offset - (aircraftLocalTime - currGMT)- cur_time;
370 SG_LOG( SG_GENERAL, SG_ALERT,
371 "TimeManager::setTimeOffset: unsupported offset: " << offset_type );
375 if( fgGetBool("/sim/time/warp-easing", false) ) {
376 double duration = fgGetDouble("/sim/time/warp-easing-duration-secs", 5.0 );
377 const string easing = fgGetString("/sim/time/warp-easing-method", "swing" );
379 n.setDoubleValue( orig_warp + warp );
380 _warp->interpolate( "numeric", n, duration, easing );
382 _warp->setIntValue( orig_warp + warp );
385 SG_LOG( SG_GENERAL, SG_INFO, "After TimeManager::setTimeOffset(): warp = "
386 << _warp->getIntValue() );