Debian Codegraph @

src/FDM/fdm_shell.cxx

raw symbols SCIP
1 // fdm_shell.cxx -- encapsulate FDM implementations as well-behaved subsystems
2 //
3 // Written by James Turner, started June 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 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 #include <cassert>
28 #include <simgear/structure/exception.hxx>
29 #include <simgear/props/props_io.hxx>
30
31 #include <FDM/fdm_shell.hxx>
32 #include <FDM/flight.hxx>
33 #include <Aircraft/replay.hxx>
34 #include <Main/globals.hxx>
35 #include <Main/fg_props.hxx>
36 #include <Scenery/scenery.hxx>
37 #include "AIModel/AIManager.hxx"
38 #include "AIModel/AIAircraft.hxx"
39
40 // all the FDMs, since we are the factory method
41 #ifdef ENABLE_SP_FDM
42 #include <FDM/SP/ADA.hxx>
43 #include <FDM/SP/ACMS.hxx>
44 #include <FDM/SP/MagicCarpet.hxx>
45 #include <FDM/SP/Balloon.h>
46 #include <FDM/SP/AISim.hpp>
47 #endif
48 #include <FDM/ExternalNet/ExternalNet.hxx>
49 #include <FDM/ExternalPipe/ExternalPipe.hxx>
50
51 #ifdef ENABLE_JSBSIM
52 #include <FDM/JSBSim/JSBSim.hxx>
53 #endif
54
55 #ifdef ENABLE_LARCSIM
56 #include <FDM/LaRCsim/LaRCsim.hxx>
57 #endif
58
59 #include <FDM/UFO.hxx>
60 #include <FDM/NullFDM.hxx>
61
62 #ifdef ENABLE_YASIM
63 #include <FDM/YASim/YASim.hxx>
64 #endif
65
66 #include <GUI/MessageBox.hxx>
67 #include <Main/sentryIntegration.hxx>
68
69 using std::string;
70
71 FDMShell::FDMShell() : _tankProperties(fgGetNode("/consumables/fuel", true))
72 {
73 }
74
75 FDMShell::~FDMShell()
76 {
77 }
78
79 void FDMShell::init()
80 {
81 _props = globals->get_props();
82 fgSetBool("/sim/fdm-initialized", false);
83
84 _wind_north = _props->getNode("environment/wind-from-north-fps", true);
85 _wind_east = _props->getNode("environment/wind-from-east-fps", true);
86 _wind_down = _props->getNode("environment/wind-from-down-fps", true);
87 _control_fdm_atmo = _props->getNode("environment/params/control-fdm-atmosphere", true);
88 _temp_degc = _props->getNode("environment/temperature-degc", true);
89 _pressure_inhg = _props->getNode("environment/pressure-inhg", true);
90 _density_slugft = _props->getNode("environment/density-slugft3", true);
91 _data_logging = _props->getNode("/sim/temp/fdm-data-logging", true);
92 _replay_master = _props->getNode("/sim/freeze/replay-state", true);
93
94 // AI aerodynamic wake interaction
95 _max_radius_nm = _props->getNode("fdm/ai-wake/max-radius-nm", true);
96 _ai_wake_enabled = _props->getNode("fdm/ai-wake/enabled", true);
97
98 _nanCheckFailed = false;
99 fgSetBool("/sim/fdm-nan-failure", false);
100 _lastValidPos = SGGeod::invalid();
101
102 createImplementation();
103 }
104
105 void FDMShell::postinit()
106 {
107 _initialFdmProperties = new SGPropertyNode;
108
109 if (!copyProperties(_props->getNode("fdm", true),
110 _initialFdmProperties))
111 {
112 SG_LOG(SG_FLIGHT, SG_ALERT, "Failed to save initial FDM property state");
113 }
114
115 _ai_mgr = globals->get_subsystem<FGAIManager>();
116 if (!_ai_mgr) {
117 SG_LOG(SG_FLIGHT, SG_DEV_ALERT, "FDM connection to the AI manager: FAILED");
118 }
119 }
120
121 void FDMShell::shutdown()
122 {
123 if (_impl) {
124 fgSetBool("/sim/fdm-initialized", false);
125 _impl->unbind();
126 _impl.clear();
127 }
128
129 _props.clear();
130 _wind_north.clear();
131 _wind_east.clear();
132 _wind_down.clear();
133 _control_fdm_atmo.clear();
134 _temp_degc.clear();
135 _pressure_inhg.clear();
136 _density_slugft .clear();
137 _data_logging.clear();
138 _replay_master.clear();
139 }
140
141 void FDMShell::reinit()
142 {
143 shutdown();
144
145 if ( copyProperties(_initialFdmProperties, fgGetNode("/fdm", true)) ) {
146 SG_LOG( SG_FLIGHT, SG_INFO, "Preserved state restored successfully" );
147 } else {
148 SG_LOG( SG_FLIGHT, SG_WARN,
149 "FDM: Some errors restoring preserved state" );
150 }
151
152
153 init();
154 }
155
156 void FDMShell::bind()
157 {
158 _tankProperties.bind();
159 if (_impl && _impl->get_inited()) {
160 if (_impl->get_bound()) {
161 throw sg_exception("FDMShell::bind of bound FGInterface impl");
162 }
163 _impl->bind();
164 }
165 }
166
167 void FDMShell::unbind()
168 {
169 if( _impl ) _impl->unbind();
170 _tankProperties.unbind();
171 }
172
173 void FDMShell::doInitAndBind()
174 {
175 SG_LOG(SG_FLIGHT, SG_INFO, "Scenery loaded, will init FDM");
176 try {
177 _impl->init();
178 if (_impl->get_bound()) {
179 _impl->unbind();
180 }
181 _impl->bind();
182
183 fgSetBool("/sim/fdm-initialized", true);
184 fgSetBool("/sim/signals/fdm-initialized", true);
185 } catch (std::exception& e) {
186 flightgear::fatalMessageBoxThenExit("Aircraft FDM initialization error",
187 string{"The aircraft flight dynamics model contains errors and cannot be used. ("} + e.what() + ")");
188 }
189
190 if (!copyProperties(_props->getNode("fdm", true),
191 _initialFdmProperties)) {
192 SG_LOG(SG_FLIGHT, SG_ALERT, "Failed to save initial FDM property state");
193 }
194 }
195
196 void FDMShell::update(double dt)
197 {
198 if (!_impl) {
199 return;
200 }
201
202 if (_nanCheckFailed) {
203 return;
204 }
205
206 if (!_impl->get_inited()) {
207 // Check for scenery around the aircraft.
208 double lon = fgGetDouble("/sim/presets/longitude-deg");
209 double lat = fgGetDouble("/sim/presets/latitude-deg");
210
211 double range = 1000.0; // in meters
212 SGGeod geod = SGGeod::fromDeg(lon, lat);
213 const auto startUpPositionFialized = fgGetBool("/sim/position-finalized", false);
214 if (startUpPositionFialized && globals->get_scenery()->scenery_available(geod, range)) {
215 doInitAndBind();
216 }
217 }
218
219 if (!_impl->get_inited()) {
220 return; // still waiting
221 }
222
223 // AI aerodynamic wake interaction
224 if (_ai_wake_enabled->getBoolValue()) {
225 for (FGAIBase* base : _ai_mgr->get_ai_list()) {
226 try {
227 if (base->isa(FGAIBase::object_type::otAircraft) ) {
228 SGVec3d pos = _impl->getCartPosition();
229 const SGSharedPtr<FGAIAircraft> aircraft = dynamic_cast<FGAIAircraft*>(base);
230 double range = _ai_mgr->calcRangeFt(pos, aircraft)*SG_FEET_TO_METER;
231
232 if (!aircraft->onGround() && aircraft->getSpeed() > 0.0
233 && range < _max_radius_nm->getDoubleValue()*SG_NM_TO_METER) {
234 _impl->add_ai_wake(aircraft);
235 }
236 }
237 } catch (sg_exception& e) {
238 SG_LOG(SG_FLIGHT, SG_WARN, "caught exception updating AI model:"
239 << base->_getName()<< ", which will be killed."
240 "\n\tError:" << e.getFormattedMessage());
241 base->setDie(true);
242 }
243 }
244 }
245
246 // pull environmental data in, since the FDMs are lazy
247 _impl->set_Velocities_Local_Airmass(
248 _wind_north->getDoubleValue(),
249 _wind_east->getDoubleValue(),
250 _wind_down->getDoubleValue());
251
252 if (_control_fdm_atmo->getBoolValue()) {
253 // convert from Rankine to Celsius
254 double tempDegC = _temp_degc->getDoubleValue();
255 _impl->set_Static_temperature((9.0/5.0) * (tempDegC + 273.15));
256
257 // convert from inHG to PSF
258 double pressureInHg = _pressure_inhg->getDoubleValue();
259 _impl->set_Static_pressure(pressureInHg * 70.726566);
260 // keep in slugs/ft^3
261 _impl->set_Density(_density_slugft->getDoubleValue());
262 }
263
264 bool doLog = _data_logging->getBoolValue();
265 if (doLog != _dataLogging) {
266 _dataLogging = doLog;
267 _impl->ToggleDataLogging(doLog);
268 }
269
270 switch(_replay_master->getIntValue())
271 {
272 case 0:
273 // normal FDM operation
274 _impl->update(dt);
275 break;
276 case 3:
277 // resume FDM operation at current replay position
278 _impl->reinit();
279 break;
280 default:
281 // replay is active
282 break;
283 }
284
285 validateOutputProperties();
286 }
287
288 FGInterface* FDMShell::getInterface() const
289 {
290 return _impl;
291 }
292
293 void FDMShell::createImplementation()
294 {
295 assert(!_impl);
296
297 double dt = 1.0 / fgGetInt("/sim/model-hz");
298 string model = fgGetString("/sim/flight-model");
299
300 bool fdmUnavailable = false;
301
302 if ( model == "ufo" ) {
303 _impl = new FGUFO( dt );
304 } else if ( model == "external" ) {
305 // external is a synonym for "--fdm=null" and is
306 // maintained here for backwards compatibility
307 _impl = new FGNullFDM( dt );
308 } else if ( model.find("network") == 0 ) {
309 string host = "localhost";
310 int port1 = 5501;
311 int port2 = 5502;
312 int port3 = 5503;
313 string net_options = model.substr(8);
314 string::size_type begin, end;
315 begin = 0;
316 // host
317 end = net_options.find( ",", begin );
318 if ( end != string::npos ) {
319 host = net_options.substr(begin, end - begin);
320 begin = end + 1;
321 }
322 // port1
323 end = net_options.find( ",", begin );
324 if ( end != string::npos ) {
325 port1 = atoi( net_options.substr(begin, end - begin).c_str() );
326 begin = end + 1;
327 }
328 // port2
329 end = net_options.find( ",", begin );
330 if ( end != string::npos ) {
331 port2 = atoi( net_options.substr(begin, end - begin).c_str() );
332 begin = end + 1;
333 }
334 // port3
335 end = net_options.find( ",", begin );
336 if ( end != string::npos ) {
337 port3 = atoi( net_options.substr(begin, end - begin).c_str() );
338 begin = end + 1;
339 }
340 _impl = new FGExternalNet( dt, host, port1, port2, port3 );
341 } else if ( model.find("pipe") == 0 ) {
342 // /* old */ string pipe_path = model.substr(5);
343 // /* old */ _impl = new FGExternalPipe( dt, pipe_path );
344 string pipe_path = "";
345 string pipe_protocol = "";
346 string pipe_options = model.substr(5);
347 string::size_type begin, end;
348 begin = 0;
349 // pipe file path
350 end = pipe_options.find( ",", begin );
351 if ( end != string::npos ) {
352 pipe_path = pipe_options.substr(begin, end - begin);
353 begin = end + 1;
354 }
355 // protocol (last option)
356 pipe_protocol = pipe_options.substr(begin);
357 _impl = new FGExternalPipe( dt, pipe_path, pipe_protocol );
358 } else if ( model == "null" ) {
359 _impl = new FGNullFDM( dt );
360 }
361 else if ( model == "larcsim" ) {
362 #ifdef ENABLE_LARCSIM
363 _impl = new FGLaRCsim( dt );
364 #else
365 fdmUnavailable = true;
366 #endif
367 }
368 else if ( model == "jsb" ) {
369 #ifdef ENABLE_JSBSIM
370 _impl = new FGJSBsim( dt );
371 #else
372 fdmUnavailable = true;
373 #endif
374 }
375 #ifdef ENABLE_SP_FDM
376 else if ( model == "ada" ) {
377 _impl = new FGADA( dt );
378 } else if ( model == "acms" ) {
379 _impl = new FGACMS( dt );
380 } else if ( model == "balloon" ) {
381 _impl = new FGBalloonSim( dt );
382 } else if ( model == "magic" ) {
383 _impl = new FGMagicCarpet( dt );
384 } else if ( model == "aisim" ) {
385 _impl = new FGAISim( dt );
386 }
387 #else
388 else if (( model == "ada" )||(model == "acms")||( model == "balloon" )||( model == "magic" )||( model == "aisim" ))
389 {
390 fdmUnavailable = true;
391 }
392 #endif
393 else if ( model == "yasim" ) {
394 #ifdef ENABLE_YASIM
395 _impl = new YASim( dt );
396 #else
397 fdmUnavailable = true;
398 #endif
399 } else {
400 throw sg_exception(string("Unrecognized flight model '") + model
401 + "', cannot init flight dynamics model.");
402 }
403
404 if (fdmUnavailable)
405 {
406 // FDM type is known, but its support was disabled at compile-time.
407 flightgear::fatalMessageBoxThenExit(
408 "Deprecated Flight Model",
409 std::string("Support for flight model '") + model +
410 "' is not available with this binary (deprecated/disabled).\n"
411 "If you still need it, please rebuild FlightGear and enable its support.\n\n"
412 "Important: The LaRCsim and UIUC flight models will be completely removed in a future major release.",
413 "Please consider migrating to a supported flight model."
414 );
415 }
416 }
417
418 void FDMShell::validateOutputProperties()
419 {
420 if (_nanCheckFailed)
421 return;
422
423 const auto p = globals->get_aircraft_position();
424 if (SGMisc<double>::isNaN(p.getLatitudeDeg()) ||
425 SGMisc<double>::isNaN(p.getLongitudeDeg()) ||
426 SGMisc<double>::isNaN(p.getElevationFt())) {
427 SG_LOG(SG_FLIGHT, SG_ALERT, "FDM position became invalid. Last valid position was:" << _lastValidPos);
428 _nanCheckFailed = true;
429 } else {
430 _lastValidPos = p;
431 }
432
433 if (SGMisc<double>::isNaN(_impl->get_V_true_kts())) {
434 SG_LOG(SG_FLIGHT, SG_ALERT, "FDM velocity became invalid");
435 _nanCheckFailed = true;
436 }
437
438 if (_nanCheckFailed) {
439 flightgear::sentryReportException("FDM NaN check failed");
440
441 flightgear::modalMessageBox("Flight dynamics error",
442 "The flight dynamics model (FDM) has become invalid. The simulation will be stopped, so you can restart at a new location.");
443 fgSetBool("/sim/fdm-nan-failure", true);
444 fgSetBool("/sim/freeze/master", true);
445 fgSetBool("/sim/freeze/clock", true);
446 }
447 }
448
449 // Register the subsystem.
450 SGSubsystemMgr::Registrant<FDMShell> registrantFDMShell(
451 SGSubsystemMgr::FDM);