Debian Codegraph @

src/AIModel/AIBase.cxx

raw symbols SCIP
1 /*
2 * SPDX-FileName: AIBase.cxx
3 * SPDX-FileComment: abstract base class for AI objects, based on David Luff's FGAIEntity class.
4 * SPDX-FileCopyrightText: Written by David Culp, started Nov 2003 - [email protected]
5 * SPDX-FileContributor: With additions by Mathias Froehlich & Vivian Meazza 2004-2007
6 * SPDX-License-Identifier: GPL-2.0-or-later
7 */
8
9 #include <config.h>
10
11 #include <string.h>
12
13 #include <simgear/compiler.h>
14
15 #include <string>
16
17 #include <osg/ref_ptr>
18 #include <osg/Node>
19 #include <osgDB/FileUtils>
20
21 #include <simgear/debug/ErrorReportingCallback.hxx>
22 #include <simgear/debug/logstream.hxx>
23 #include <simgear/misc/sg_path.hxx>
24 #include <simgear/props/props.hxx>
25 #include <simgear/scene/model/modellib.hxx>
26 #include <simgear/scene/util/SGNodeMasks.hxx>
27
28 #include <Main/ErrorReporter.hxx>
29 #include <Main/fg_props.hxx>
30 #include <Main/globals.hxx>
31 #include <Scenery/scenery.hxx>
32 #include <Scripting/NasalModelData.hxx>
33 #include <Scripting/NasalSys.hxx>
34 #include <Sound/fg_fx.hxx>
35
36 #include "AIFlightPlan.hxx"
37 #include "AIBase.hxx"
38 #include "AIManager.hxx"
39
40 static std::string default_model = "Models/Geometry/glider.ac";
41 const double FGAIBase::e = 2.71828183;
42 const double FGAIBase::lbs_to_slugs = 0.031080950172; //conversion factor
43
44 using std::string;
45 using namespace simgear;
46
47 class FGAIModelData : public simgear::SGModelData {
48 public:
49 explicit FGAIModelData(SGPropertyNode *root = nullptr)
50 : _root (root)
51 {
52 }
53
54
55 ~FGAIModelData() = default;
56
57 FGAIModelData* clone() const override { return new FGAIModelData(); }
58
59 ErrorContext getErrorContext() const override
60 {
61 return _errorContext;
62 }
63
64 void addErrorContext(const std::string& key, const std::string& value)
65 {
66 _errorContext[key] = value;
67 }
68
69 void captureErrorContext(const std::string& key)
70 {
71 const auto v = flightgear::ErrorReporter::threadSpecificContextValue(key);
72 if (!v.empty()) {
73 addErrorContext(key, v);
74 }
75 }
76
77 /** osg callback, thread-safe */
78 void modelLoaded(const std::string& path, SGPropertyNode *prop, osg::Node *n)
79 {
80 // WARNING: Called in a separate OSG thread! Only use thread-safe stuff here...
81 if (_ready && _modelLoaded.count(path) > 0)
82 return;
83
84 _modelLoaded[path] = true;
85
86 if(prop->hasChild("interior-path")){
87 _interiorPath = prop->getStringValue("interior-path");
88 _hasInteriorPath = true;
89 }
90
91 // save radius of loaded model for updating LOD
92 auto bs = n->getBound();
93 if (bs.valid()) {
94 _radius = bs.radius();
95 }
96
97 _fxpath = prop->getStringValue("sound/path");
98 _nasal[path] = std::unique_ptr<FGNasalModelDataProxy>(new FGNasalModelDataProxy(_root));
99 _nasal[path]->modelLoaded(path, prop, n);
100 _ready = true;
101 _initialized = false;
102 }
103
104 /** init hook to be called after model is loaded.
105 * Not thread-safe. Call from main thread only. */
106 void init(void) { _initialized = true; }
107
108 bool needInitialization(void) { return _ready && !_initialized;}
109 bool isInitialized(void) { return _initialized;}
110 inline std::string& get_sound_path() { return _fxpath;}
111
112 void setInteriorLoaded(const bool state) { _interiorLoaded = state;}
113 bool getInteriorLoaded(void) { return _interiorLoaded;}
114 bool hasInteriorPath(void) { return _hasInteriorPath;}
115 inline std::string& getInteriorPath() { return _interiorPath; }
116 inline float getRadius() { return _radius; }
117 private:
118 std::string _fxpath;
119 std::string _interiorPath;
120
121 std::map<string, bool> _modelLoaded;
122 std::map<string, std::unique_ptr<FGNasalModelDataProxy>> _nasal;
123 bool _ready = false;
124 bool _initialized = false;
125 bool _hasInteriorPath = false;
126 bool _interiorLoaded = false;
127 float _radius = -1.0;
128 SGPropertyNode* _root;
129
130 ErrorContext _errorContext;
131 };
132
133 FGAIBase::FGAIBase(object_type ot, bool enableHot) : replay_time(fgGetNode("sim/replay/time", true)),
134 model_removed(fgGetNode("/ai/models/model-removed", true)),
135 pos(SGGeod::fromDeg(0.0, 0.0)),
136 _impact_lat(0),
137 _impact_lon(0),
138 _impact_elev(0),
139 _impact_hdg(0),
140 _impact_pitch(0),
141 _impact_roll(0),
142 _impact_speed(0),
143 _refID(_newAIModelID()),
144 _otype(ot)
145 {
146 tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
147 tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs_fps = pitch = 0.0;
148 bearing = elevation = range = rdot = 0.0;
149 x_shift = y_shift = rotation = 0.0;
150 in_range = false;
151 invisible = false;
152 no_roll = true;
153 life = 900;
154 delete_me = false;
155 _impact_reported = false;
156 _collision_reported = false;
157 _expiry_reported = false;
158
159 _x_offset = 0;
160 _y_offset = 0;
161 _z_offset = 0;
162
163 _pitch_offset = 0;
164 _roll_offset = 0;
165 _yaw_offset = 0;
166
167 speed = 0;
168 altitude_ft = 0;
169 speed_north_deg_sec = 0;
170 speed_east_deg_sec = 0;
171 turn_radius_ft = 0;
172
173 ft_per_deg_lon = 0;
174 ft_per_deg_lat = 0;
175
176 horiz_offset = 0;
177 vert_offset = 0;
178 ht_diff = 0;
179
180 serviceable = false;
181
182 // explicitly disable HOT for (most) AI models
183 if (!enableHot)
184 aip.getSceneGraph()->setNodeMask(~SG_NODEMASK_TERRAIN_BIT);
185 }
186
187 FGAIBase::~FGAIBase() {
188 // Unregister that one at the scenery manager
189 removeModel();
190
191 if (props) {
192 SGPropertyNode* parent = props->getParent();
193
194 if (parent)
195 model_removed->setStringValue(props->getPath());
196 }
197
198 removeSoundFx();
199 }
200
201 /** Cleanly remove the model
202 * and let the scenery database pager do the clean-up work.
203 */
204 void
205 FGAIBase::removeModel()
206 {
207 if (!_model.valid())
208 return;
209
210 FGScenery* pSceneryManager = globals->get_scenery();
211 if (pSceneryManager && pSceneryManager->get_models_branch())
212 {
213 osg::ref_ptr<osg::Object> temp = _model.get();
214 pSceneryManager->get_models_branch()->removeChild(aip.getSceneGraph());
215 // withdraw from SGModelPlacement and drop own reference (unref)
216 aip.clear();
217 _modeldata = nullptr;
218 _model = nullptr;
219 _interior = nullptr;
220 _high_res = nullptr;
221 _low_res = nullptr;
222
223 // pass it on to the pager, to be be deleted in the pager thread
224 pSceneryManager->getPager()->queueDeleteRequest(temp);
225 }
226 else
227 {
228 aip.clear();
229 _model = nullptr;
230 _modeldata = nullptr;
231 }
232 }
233
234 void FGAIBase::setScenarioPath(const std::string& scenarioPath)
235 {
236 _scenarioPath = scenarioPath;
237 }
238
239 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
240 {
241 if (!scFileNode)
242 return;
243
244 setPath(scFileNode->getStringValue("model",
245 fgGetString("/sim/multiplay/default-model", default_model).c_str()).c_str());
246
247 setFallbackModelIndex(scFileNode->getIntValue("fallback-model-index", 0));
248
249 setHeading(scFileNode->getDoubleValue("heading", 0.0));
250 setSpeed(scFileNode->getDoubleValue("speed", 0.0));
251 setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
252 setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
253 setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
254 setBank(scFileNode->getDoubleValue("roll", 0.0));
255 setPitch(scFileNode->getDoubleValue("pitch", 0.0));
256 setCollisionHeight(scFileNode->getDoubleValue("collision-height", 0.0));
257 setCollisionLength(scFileNode->getDoubleValue("collision-length", 0.0));
258
259 SGPropertyNode* submodels = scFileNode->getChild("submodels");
260
261 if (submodels) {
262 setServiceable(submodels->getBoolValue("serviceable", false));
263 setSMPath(submodels->getStringValue("path", ""));
264 }
265
266 string searchOrder = scFileNode->getStringValue("search-order", "");
267 if (!searchOrder.empty()) {
268 if (searchOrder == "DATA_ONLY") {
269 _searchOrder = ModelSearchOrder::DATA_ONLY;
270 } else if (searchOrder == "PREFER_AI") {
271 _searchOrder = ModelSearchOrder::PREFER_AI;
272 } else if (searchOrder == "PREFER_DATA") {
273 _searchOrder = ModelSearchOrder::PREFER_DATA;
274 } else
275 SG_LOG(SG_AI, SG_WARN, "invalid model search order " << searchOrder << ". Use either DATA_ONLY, PREFER_AI or PREFER_DATA");
276 }
277
278 const string modelLowres = scFileNode->getStringValue("model-lowres", "");
279 if (!modelLowres.empty()) {
280 setPathLowres(modelLowres);
281 }
282 }
283
284 void FGAIBase::update(double dt) {
285
286 SG_UNUSED(dt);
287 if (replay_time->getDoubleValue() > 0)
288 return;
289 if (_otype == object_type::otStatic)
290 return;
291
292 ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
293 ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
294
295 if ((_modeldata)&&(_modeldata->needInitialization()))
296 {
297 // process deferred nasal initialization,
298 // which must be done in main thread
299 _modeldata->init();
300
301 // update LOD radius from loaded modeldata
302 auto radius = _modeldata->getRadius();
303 if (radius > 0) {
304 _model->setRadius(radius);
305 _model->dirtyBound();
306 }
307 else {
308 SG_LOG(SG_AI, SG_WARN, "AIBase: model radius not set.");
309 }
310
311 // sound initialization
312 if (fgGetBool("/sim/sound/aimodels/enabled",false))
313 {
314 const string& fxpath = _modeldata->get_sound_path();
315 if (fxpath != "")
316 {
317 removeSoundFx();
318
319 simgear::ErrorReportContext ec("ai-model", _name);
320 if (!_scenarioPath.empty()) {
321 ec.add("scenario-path", _scenarioPath);
322 }
323
324 props->setStringValue("sim/sound/path", fxpath.c_str());
325
326 // initialize the sound configuration
327 std::stringstream name;
328 name << "aifx:";
329 name << _refID;
330 _fx = new FGFX(name.str(), props);
331 _fx->init();
332 }
333 }
334 }
335
336 if ( _fx )
337 {
338 // update model's audio sample values
339 _fx->set_position_geod( pos );
340
341 SGQuatd orient = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
342 _fx->set_orientation( orient );
343
344 SGVec3d velocity;
345 velocity = SGVec3d( speed_north_deg_sec, speed_east_deg_sec,
346 pitch*speed );
347 _fx->set_velocity( velocity );
348 }
349
350 updateInterior();
351 }
352
353 void FGAIBase::updateInterior()
354 {
355 if(!_modeldata || !_modeldata->hasInteriorPath())
356 return;
357
358 if (!_modeldata->getInteriorLoaded()) { // interior is not yet load
359 _interior = SGModelLib::loadPagedModel(_modeldata->getInteriorPath(), props, _modeldata);
360 _group->addChild(_interior);
361 if (_interior.valid()) {
362 bool pixel_mode = !fgGetBool("/sim/rendering/static-lod/aimp-range-mode-distance", false);
363 if (pixel_mode) {
364 _interior->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
365 _interior->setRange(0, _maxRangeInterior, FLT_MAX);
366 }
367 else {
368 _interior->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
369 _interior->setRange(0, 0.0, _maxRangeInterior);
370 }
371 _modeldata->setInteriorLoaded(true);
372 SG_LOG(SG_AI, SG_INFO, "AIBase: Loaded interior model " << _interior->getName());
373 }
374 }
375 }
376
377 /** update LOD properties of the model */
378 void FGAIBase::updateLOD()
379 {
380 double maxRangeDetail = fgGetDouble("/sim/rendering/static-lod/aimp-detailed", 3000.0);
381 double maxRangeBare = fgGetDouble("/sim/rendering/static-lod/aimp-bare", 10000.0);
382 _maxRangeInterior = fgGetDouble("/sim/rendering/static-lod/aimp-interior", 50.0);
383
384 if (_model.valid())
385 {
386 bool pixel_mode = !fgGetBool("/sim/rendering/static-lod/aimp-range-mode-distance", false);
387 if (pixel_mode) {
388 _model->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
389 }
390 else {
391 _model->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
392 }
393
394 if (maxRangeDetail < 0)
395 {
396 // High detail model (only)
397 // - disables the low detail detail model by setting its visibility from 0 to 0
398 if (_high_res.valid()) {
399 _model->setRange(modelHighDetailIndex, 0.0, FLT_MAX); // all ranges.
400 _model->setRange(modelLowDetailIndex, 0.0, 0.0); // turn it off
401 }
402 else {
403 // only having low-res model
404 _model->setRange(modelLowDetailIndex, 0.0, FLT_MAX); // only having low-res model.
405 _model->setRange(modelHighDetailIndex, 0.0, 0.0); // only having low-res model.
406 }
407 }
408 else if ((int)maxRangeBare == (int)maxRangeDetail)
409 {
410 // low detail model (only)
411 if (_low_res.valid()) {
412 _model->setRange(modelHighDetailIndex, 0, 0); // turn it off
413 _model->setRange(modelLowDetailIndex, 0, FLT_MAX);
414 }
415 else {
416 // Only having high_res model
417 _model->setRange(modelHighDetailIndex, 0, FLT_MAX);
418 _model->setRange(modelLowDetailIndex, 0, 0.0);
419 }
420 }
421 else
422 {
423 if(pixel_mode)
424 {
425 /* In pixel size mode, the range sense is reversed, so we want the
426 * detailed model [0] to be displayed when the "range" is really
427 * large (i.e. the object is taking up a large number of pixels on screen),
428 * and the less detailed model [1] to be displayed if the
429 * "range" is between the detailed range and the bare range.
430 * When the "range" is less than the bare value, the aircraft
431 * represents too few pixels to be worth displaying.
432 */
433
434 if (maxRangeBare > maxRangeDetail) {
435 // Sanity check that we have sensible values.
436 maxRangeBare = maxRangeDetail;
437 SG_LOG(SG_AI,
438 SG_WARN,
439 "/sim/rendering/static-lod/aimp-bare greater " <<
440 "than /sim/rendering/static-lod/aimp-detailed when using " <<
441 "/sim/rendering/static-lod/aimp-range-mode-distance=false. Ignoring ai-bare."
442 );
443 }
444
445 if (_low_res.valid() && _high_res.valid()) {
446 /*if (_model->getRadius() < 0)
447 {
448 osg::BoundingSphere bs = _model->computeBound();
449 if (bs.radius() > 0) {
450 _model->setRadius(bs.radius());
451 _model->setCenterMode(osg::LOD::CenterMode::USER_DEFINED_CENTER);
452 }
453 }*/
454 _model->setRange(modelHighDetailIndex , maxRangeDetail, FLT_MAX); // most detailed
455 _model->setRange(modelLowDetailIndex , maxRangeBare, maxRangeDetail); // least detailed
456 } else if (_low_res.valid() && !_high_res.valid()) {
457 // we have only low_res_model model it obviously will have to be displayed from the smallest value
458 _model->setRange(modelLowDetailIndex, std::min(maxRangeBare, maxRangeDetail), FLT_MAX );
459 _model->setRange(modelHighDetailIndex, 0,0);
460 } else if (!_low_res.valid() && _high_res.valid()) {
461 // we have only high_res model it obviously will have to be displayed from the smallest value
462 _model->setRange(modelHighDetailIndex, std::min(maxRangeBare, maxRangeDetail), FLT_MAX );
463 _model->setRange(modelLowDetailIndex, 0,0);
464 }
465 } else {
466 /* In non-pixel range mode we're dealing with straight distance.
467 * We use the detailed model [0] for when we are up to the detailed
468 * range, and the less complex model [1] (if available) for further
469 * away up to the bare range.
470 * - in this case the maxRangeBare is a delta on top of maxRangeDetail.
471 */
472
473 if (maxRangeBare <= 0) {
474 // Sanity check that we have sensible values.
475 maxRangeBare = 1;
476 SG_LOG(SG_AI,
477 SG_ALERT,
478 "/sim/rendering/static-lod/aimp-bare is <= 0. This should be a delta on top of aimp-detailed in meters mode. setting to 1.");
479 }
480
481
482 if (_low_res.valid() && _high_res.valid()) {
483 _model->setRange(modelHighDetailIndex , 0, maxRangeDetail); // most detailed
484 _model->setRange(modelLowDetailIndex , maxRangeDetail, maxRangeDetail+maxRangeBare); // least detailed
485 } else if (_low_res.valid() && !_high_res.valid()) {
486 _model->setRange(modelLowDetailIndex, 0, maxRangeBare + maxRangeDetail); // only low_res, so display from 0 to the highest value in meters
487 _model->setRange(modelHighDetailIndex, 0, 0);
488 } else if (!_low_res.valid() && _high_res.valid()) {
489 _model->setRange(modelHighDetailIndex, 0, maxRangeBare + maxRangeDetail); // only high_res, so display from 0 to the highest value in meters
490 _model->setRange(modelLowDetailIndex, 0, 0);
491 }
492 }
493 }
494 if (_modeldata->getInteriorLoaded() && _interior.valid()) {
495 if (pixel_mode) {
496 _interior->setRangeMode(osg::LOD::PIXEL_SIZE_ON_SCREEN);
497 _interior->setRange(0, _maxRangeInterior, FLT_MAX);
498 }
499 else {
500 _interior->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
501 _interior->setRange(0, 0.0, _maxRangeInterior);
502 }
503 }
504 }
505 }
506
507 void FGAIBase::Transform() {
508
509 if (!invisible) {
510 aip.setVisible(true);
511 aip.setPosition(pos);
512
513 if (no_roll)
514 aip.setOrientation(0.0, pitch, hdg);
515 else
516 aip.setOrientation(roll, pitch, hdg);
517
518 aip.update();
519 } else {
520 aip.setVisible(false);
521 aip.update();
522 }
523
524 }
525
526 /*
527 * Find a set of paths to the model, in order of LOD from most detailed to
528 * least, and accounting for the user preference of detailed models vs. AI
529 * low resolution models.
530 *
531 * This returns a vector of size 1 or 2.
532 */
533 std::vector<std::string> FGAIBase::resolveModelPath(ModelSearchOrder searchOrder)
534 {
535 string_list path_list;
536
537 if (searchOrder == ModelSearchOrder::DATA_ONLY) {
538 SG_LOG(SG_AI, SG_DEBUG, "Resolving model path: DATA only");
539 auto p = simgear::SGModelLib::findDataFile(model_path);
540 if (!p.empty()) {
541 // We've got a model, use it
542 _installed = true;
543 SG_LOG(SG_AI, SG_DEBUG, "Found model " << p);
544 path_list.push_back(p);
545
546 if (!model_path_lowres.empty()) {
547 p = simgear::SGModelLib::findDataFile(model_path_lowres);
548 if (!p.empty()) {
549 //lowres model needs to be the first in the list
550 path_list.insert(path_list.begin(),p);
551 }
552 }
553 } else {
554 // No model, so fall back to the default
555 const SGPath defaultModelPath = SGPath::fromUtf8(fgGetString("/sim/multiplay/default-model", default_model));
556 path_list.push_back(defaultModelPath.utf8Str());
557 }
558 } else {
559 SG_LOG(SG_AI, SG_DEBUG, "Resolving model path: PREFER_AI/PREFER_DATA");
560 // We're either PREFER_AI or PREFER_DATA. Find an AI model first.
561 for (SGPath p : globals->get_data_paths("AI")) {
562 p.append(model_path);
563 if (p.exists()) {
564 SG_LOG(SG_AI, SG_DEBUG, "Found AI model: " << p);
565 path_list.push_back(p.utf8Str());
566 break;
567 }
568 }
569
570 if (path_list.empty()) {
571 // Fall back on the fallback-model-index which is a lookup into
572 // /sim/multiplay/fallback-models/model[]
573 std::string fallback_path;
574 const SGPropertyNode* fallbackNode =
575 globals->get_props()->getNode("/sim/multiplay/fallback-models/model", _getFallbackModelIndex(), false);
576
577 if (fallbackNode != nullptr) {
578 fallback_path = fallbackNode->getStringValue();
579 } else {
580 fallback_path = globals->get_props()->getNode("/sim/multiplay/fallback-models/model", 0, true)->getStringValue();
581 }
582
583 for (SGPath p : globals->get_data_paths()) {
584 p.append(fallback_path);
585 if (p.exists()) {
586 SG_LOG(SG_AI, SG_DEBUG, "Found fallback model path for index " << _fallback_model_index << ": " << p);
587 path_list.push_back(p.utf8Str());
588 break;
589 }
590 }
591 }
592
593 if ((searchOrder == ModelSearchOrder::PREFER_AI) && !path_list.empty()) {
594 // if we prefer AI, and we've got a valid AI path from above, then use it, we're done
595 _installed = true;
596 return path_list;
597 }
598
599 // At this point we're looking for a regular model to display at closer range.
600 // From experimentation it seems to work best if the LODs are in the range list in terms of detail
601 // from lowest to highest - so insert this at the end.
602 auto p = simgear::SGModelLib::findDataFile(model_path);
603 if (!p.empty()) {
604 _installed = true;
605 SG_LOG(SG_AI, SG_DEBUG, "Found DATA model " << p);
606 path_list.insert(path_list.end(), p);
607 }
608 }
609
610 /*
611 * We return either one or two models. LoD logic elsewhere relies on this,
612 * so anything else is a logic error in the above code.
613 */
614 assert(path_list.size() != 0);
615 assert(path_list.size() < 3);
616
617 return path_list;
618 }
619
620 bool FGAIBase::init(ModelSearchOrder searchOrder)
621 {
622 if (_model.valid())
623 {
624 SG_LOG(SG_AI, SG_ALERT, "AIBase: Cannot initialize a model multiple times! " << model_path);
625 return false;
626 }
627
628 props->addChild("type")->setStringValue("AI");
629 _modeldata = new FGAIModelData(props);
630 _modeldata->addErrorContext("ai", _name);
631 _modeldata->captureErrorContext("scenario-path");
632
633 // set by FGAISchedule::createAIAircraft
634 _modeldata->captureErrorContext("traffic-aircraft-callsign");
635
636 if (_otype == object_type::otMultiplayer) {
637 _modeldata->addErrorContext("multiplayer", getCallSign());
638 }
639
640 // Load models
641 _model = new osg::LOD();
642 std::vector<string> model_list = resolveModelPath(searchOrder);
643 if(model_list.size() == 1 && _modeldata && _modeldata->hasInteriorPath()) {
644 // Only one model and interior available (expecting this to be a high_res model)
645 _low_res = new osg::PagedLOD(); // Dummy node to keep LOD node happy
646 _model->addChild(_low_res);
647 _high_res = SGModelLib::loadPagedModel(model_list[0], props, _modeldata);
648 _group = osg::ref_ptr<osg::Group>(new osg::Group());
649 _group->addChild(_high_res);
650 _model->addChild(_group);
651 } else if (model_list.size() == 1) {
652 // low_res model only (as we do not have any interior)
653 _low_res = SGModelLib::loadPagedModel(model_list[0], props, _modeldata);
654 _model->addChild(_low_res);
655 _group = osg::ref_ptr<osg::Group>(new osg::Group()); // Dummy node to keep LOD node happy
656 _model->addChild(_group);
657 } else {
658 // high and low-res model
659 assert(model_list.size() == 2);
660 _low_res = SGModelLib::loadPagedModel(model_list[0], props, _modeldata);
661 _model->addChild(_low_res);
662 _high_res = SGModelLib::loadPagedModel(model_list[1], props, _modeldata);
663 _group = osg::ref_ptr<osg::Group>(new osg::Group());
664 _group->addChild(_high_res);
665 _model->addChild(_group);
666 }
667
668 // Set PagedLODs to MAX Range. The visibility is controlled with the top-level LOD node
669 if(_high_res.valid()) {
670 _high_res->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
671 _high_res->setRange(0, 0, FLT_MAX);
672 }
673 if(_low_res.valid()) {
674 _low_res->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
675 _low_res->setRange(0, 0, FLT_MAX);
676 }
677
678 _model->setName("AI-model range animation node");
679 _model->setRadius(getDefaultModelRadius());
680
681 updateLOD();
682 initModel();
683
684 if (_model.valid() && _initialized == false) {
685 aip.init( _model.get() );
686 aip.setVisible(true);
687 invisible = false;
688
689 auto scenery = globals->get_scenery();
690 if (scenery) {
691 scenery->get_models_branch()->addChild(aip.getSceneGraph());
692 }
693 _initialized = true;
694
695 SG_LOG(SG_AI, SG_DEBUG, "AIBase: Loaded model " << model_path);
696
697 } else if (!model_path.empty()) {
698 SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
699 // not properly installed...
700 _installed = false;
701 }
702
703 setDie(false);
704 return true;
705 }
706
707 void FGAIBase::initModel()
708 {
709 if (_model.valid()) {
710
711 if( _path != ""){
712 props->setStringValue("submodels/path", _path.c_str());
713 SG_LOG(SG_AI, SG_DEBUG, "AIBase: submodels/path " << _path);
714 }
715
716 if( _parent!= ""){
717 props->setStringValue("parent-name", _parent.c_str());
718 }
719
720 fgSetString("/ai/models/model-added", props->getPath().c_str());
721 } else if (!model_path.empty()) {
722 SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
723 }
724
725 setDie(false);
726 }
727
728
729 bool FGAIBase::isa( object_type otype ) {
730 return otype == _otype;
731 }
732
733 void FGAIBase::bind() {
734 _tiedProperties.setRoot(props);
735 tie("id", SGRawValueMethods<FGAIBase,int>(*this,
736 &FGAIBase::getID));
737 tie("velocities/true-airspeed-kt", SGRawValuePointer<double>(&speed));
738 tie("velocities/vertical-speed-fps",
739 SGRawValueMethods<FGAIBase,double>(*this,
740 &FGAIBase::_getVS_fps,
741 &FGAIBase::_setVS_fps));
742
743 tie("position/altitude-ft",
744 SGRawValueMethods<FGAIBase,double>(*this,
745 &FGAIBase::_getAltitude,
746 &FGAIBase::_setAltitude));
747 tie("position/latitude-deg",
748 SGRawValueMethods<FGAIBase,double>(*this,
749 &FGAIBase::_getLatitude,
750 &FGAIBase::_setLatitude));
751 tie("position/longitude-deg",
752 SGRawValueMethods<FGAIBase,double>(*this,
753 &FGAIBase::_getLongitude,
754 &FGAIBase::_setLongitude));
755
756 tie("position/global-x",
757 SGRawValueMethods<FGAIBase,double>(*this,
758 &FGAIBase::_getCartPosX,
759 nullptr));
760 tie("position/global-y",
761 SGRawValueMethods<FGAIBase,double>(*this,
762 &FGAIBase::_getCartPosY,
763 nullptr));
764 tie("position/global-z",
765 SGRawValueMethods<FGAIBase,double>(*this,
766 &FGAIBase::_getCartPosZ,
767 nullptr));
768 tie("callsign",
769 SGRawValueMethods<FGAIBase,const char*>(*this,
770 &FGAIBase::_getCallsign,
771 nullptr));
772 // 2018.2 - to ensure consistent properties also tie the callsign to where it would be in a local model.
773 tie("sim/multiplay/callsign",
774 SGRawValueMethods<FGAIBase, const char*>(*this, &FGAIBase::_getCallsign, nullptr));
775
776 tie("orientation/pitch-deg", SGRawValuePointer<double>(&pitch));
777 tie("orientation/roll-deg", SGRawValuePointer<double>(&roll));
778 tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
779
780 tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
781 tie("radar/bearing-deg", SGRawValuePointer<double>(&bearing));
782 tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
783 tie("radar/range-nm", SGRawValuePointer<double>(&range));
784 tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
785 tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
786 tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
787 tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
788 tie("radar/rotation", SGRawValuePointer<double>(&rotation));
789 tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
790 tie("subID", SGRawValuePointer<int>(&_subID));
791
792 props->setStringValue("sim/model/path", model_path);
793
794 // note: AIAircraft creates real SGPropertyNodes for these, we don't do
795 // that here because it would bloat AIBase slightly
796 props->setBoolValue("controls/glide-path", true);
797
798 props->setStringValue("controls/flight/lateral-mode", "roll");
799 props->setDoubleValue("controls/flight/target-hdg", hdg);
800 props->setDoubleValue("controls/flight/target-roll", roll);
801
802 props->setStringValue("controls/flight/vertical-mode", "alt");
803
804 // The property above was incorrectly labelled 'longitude-mode' up until
805 // FG 2018.4, so create an alias in case anyone is relying on the old name
806 auto node = props->getNode("controls/flight/longitude-mode", true);
807 node->alias(props->getNode("controls/flight/vertical-mode"), false);
808
809 props->setDoubleValue("controls/flight/target-alt", altitude_ft);
810 props->setDoubleValue("controls/flight/target-pitch", pitch);
811
812 props->setDoubleValue("controls/flight/target-spd", speed);
813
814 props->setBoolValue("sim/sound/avionics/enabled", false);
815 props->setDoubleValue("sim/sound/avionics/volume", 0.0);
816 props->setBoolValue("sim/sound/avionics/external-view", false);
817 props->setBoolValue("sim/current-view/internal", false);
818 }
819
820 void FGAIBase::unbind() {
821 _tiedProperties.Untie();
822
823 props->setBoolValue("/sim/controls/radar", true);
824
825 removeSoundFx();
826 }
827
828 void FGAIBase::removeSoundFx()
829 {
830 if (_fx) {
831 _fx->shutdown();
832 _fx.clear();
833 }
834 }
835
836 double FGAIBase::UpdateRadar(FGAIManager* manager)
837 {
838 if (!manager->isRadarEnabled())
839 return 0.0;
840
841 const double radar_range_m = manager->radarRangeM() * 1.1; // + 10%
842 bool force_on = manager->enableRadarDebug();
843 double d = dist(SGVec3d::fromGeod(pos), globals->get_aircraft_position_cart());
844 double dFt = d * SG_METER_TO_FEET;
845 in_range = (d < radar_range_m);
846
847 if (!force_on && !in_range) {
848 return dFt * dFt;
849 }
850
851 // copy values from the AIManager
852 double user_heading = manager->get_user_heading();
853 double user_pitch = manager->get_user_pitch();
854
855 range = d * SG_METER_TO_NM;
856 // calculate bearing to target
857 bearing = SGGeodesy::courseDeg(globals->get_aircraft_position(), pos);
858
859 // calculate look left/right to target, without yaw correction
860 horiz_offset = bearing - user_heading;
861 SG_NORMALIZE_RANGE(horiz_offset, -180.0, 180.0);
862
863 // calculate elevation to target
864 ht_diff = altitude_ft - globals->get_aircraft_position().getElevationFt();
865 elevation = atan2( ht_diff, dFt ) * SG_RADIANS_TO_DEGREES;
866
867 // calculate look up/down to target
868 vert_offset = elevation - user_pitch;
869
870 /* this calculation needs to be fixed, but it isn't important anyway
871 // calculate range rate
872 double recip_bearing = bearing + 180.0;
873 if (recip_bearing > 360.0) recip_bearing -= 360.0;
874 double my_horiz_offset = recip_bearing - hdg;
875 if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
876 if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
877 rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
878 +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
879 */
880
881 // now correct look left/right for yaw
882 // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
883
884 // calculate values for radar display
885 y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
886 x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
887
888 rotation = hdg - user_heading;
889 SG_NORMALIZE_RANGE(rotation, 0.0, 360.0);
890
891 return dFt * dFt;
892 }
893
894 /*
895 * Getters and Setters
896 */
897
898 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
899 // Transform that one to the horizontal local coordinate system.
900 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
901
902 // and postrotate the orientation of the AIModel wrt the horizontal
903 // local frame
904 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
905
906 // The offset converted to the usual body fixed coordinate system
907 // rotated to the earth fixed coordinates axis
908 SGVec3d off = hlTrans.backTransform(_off);
909
910 // Add the position offset of the AIModel to gain the earth centered position
911 SGVec3d cartPos = SGVec3d::fromGeod(pos);
912
913 return cartPos + off;
914 }
915
916 SGVec3d FGAIBase::getCartPos() const {
917 SGVec3d cartPos = SGVec3d::fromGeod(pos);
918 return cartPos;
919 }
920
921 bool FGAIBase::getGroundElevationM(const SGGeod& pos, double& elev,
922 const simgear::BVHMaterial** material) const {
923 return globals->get_scenery()->get_elevation_m(pos, elev, material,
924 _model.get());
925 }
926
927 SGPropertyNode* FGAIBase::getPositionFromNode(SGPropertyNode* scFileNode, const std::string &key, SGVec3d &position) {
928 SGPropertyNode* positionNode = scFileNode->getChild(key);
929 if (positionNode) {
930 // Transform to the right coordinate frame, configuration is done in
931 // the usual x-back, y-right, z-up coordinates, computations
932 // in the simulation usual body x-forward, y-right, z-down coordinates
933 position(0) = -positionNode->getDoubleValue("x-offset-m", 0);
934 position(1) = positionNode->getDoubleValue("y-offset-m", 0);
935 position(2) = -positionNode->getDoubleValue("z-offset-m", 0);
936 return positionNode;
937 }
938 else
939 position = SGVec3d::zeros();
940 return nullptr;
941 }
942
943 double FGAIBase::_getCartPosX() const {
944 SGVec3d cartPos = getCartPos();
945 return cartPos.x();
946 }
947
948 double FGAIBase::_getCartPosY() const {
949 SGVec3d cartPos = getCartPos();
950 return cartPos.y();
951 }
952
953 double FGAIBase::_getCartPosZ() const {
954 SGVec3d cartPos = getCartPos();
955 return cartPos.z();
956 }
957
958 void FGAIBase::_setLongitude( double longitude ) {
959 pos.setLongitudeDeg(longitude);
960 }
961
962 void FGAIBase::_setLatitude ( double latitude ) {
963 pos.setLatitudeDeg(latitude);
964 }
965
966 void FGAIBase::_setSubID( int s ) {
967 _subID = s;
968 }
969
970 bool FGAIBase::setParentNode() {
971 if (_parent == ""){
972 SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name << " parent not set ");
973 return false;
974 }
975
976 const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
977
978 for (int i = ai->nChildren() - 1; i >= -1; i--) {
979 SGPropertyNode_ptr model;
980
981 if (i < 0) { // last iteration: selected model
982 model = _selected_ac;
983 } else {
984 model = ai->getChild(i);
985 const string name = model->getStringValue("name");
986
987 if (!model->nChildren()){
988 continue;
989 }
990
991 if (name == _parent) {
992 _selected_ac = model; // save selected model for last iteration
993 break;
994 }
995 }
996
997 if (!model)
998 continue;
999 }// end for loop
1000
1001 if (_selected_ac != 0){
1002 // DEADCODE: const string name = _selected_ac->getStringValue("name");
1003 return true;
1004 } else {
1005 SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name << " parent not found: dying ");
1006 setDie(true);
1007 return false;
1008 }
1009 }
1010
1011 double FGAIBase::_getLongitude() const {
1012 return pos.getLongitudeDeg();
1013 }
1014
1015 double FGAIBase::_getLatitude() const {
1016 return pos.getLatitudeDeg();
1017 }
1018
1019 double FGAIBase::_getElevationFt() const {
1020 return pos.getElevationFt();
1021 }
1022
1023 double FGAIBase::_getRdot() const {
1024 return rdot;
1025 }
1026
1027 double FGAIBase::_getVS_fps() const {
1028 return vs_fps;
1029 }
1030
1031 double FGAIBase::_get_speed_east_fps() const {
1032 return speed_east_deg_sec * ft_per_deg_lon;
1033 }
1034
1035 double FGAIBase::_get_speed_north_fps() const {
1036 return speed_north_deg_sec * ft_per_deg_lat;
1037 }
1038
1039 void FGAIBase::_setVS_fps( double _vs ) {
1040 vs_fps = _vs;
1041 }
1042
1043 double FGAIBase::_getAltitude() const {
1044 return altitude_ft;
1045 }
1046
1047 double FGAIBase::_getAltitudeAGL(SGGeod inpos, double start){
1048 getGroundElevationM(SGGeod::fromGeodM(inpos, start),
1049 _elevation_m, NULL);
1050 return inpos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
1051 }
1052
1053 bool FGAIBase::_getServiceable() const {
1054 return serviceable;
1055 }
1056
1057 SGPropertyNode* FGAIBase::_getProps() const {
1058 return props;
1059 }
1060
1061 void FGAIBase::_setAltitude( double _alt ) {
1062 setAltitude( _alt );
1063 }
1064
1065 bool FGAIBase::_isNight() {
1066 return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
1067 }
1068
1069 bool FGAIBase::_getCollisionData() {
1070 return _collision_reported;
1071 }
1072
1073 bool FGAIBase::_getExpiryData() {
1074 return _expiry_reported;
1075 }
1076
1077 bool FGAIBase::_getImpactData() {
1078 return _impact_reported;
1079 }
1080
1081 double FGAIBase::_getImpactLat() const {
1082 return _impact_lat;
1083 }
1084
1085 double FGAIBase::_getImpactLon() const {
1086 return _impact_lon;
1087 }
1088
1089 double FGAIBase::_getImpactElevFt() const {
1090 return _impact_elev * SG_METER_TO_FEET;
1091 }
1092
1093 double FGAIBase::_getImpactPitch() const {
1094 return _impact_pitch;
1095 }
1096
1097 double FGAIBase::_getImpactRoll() const {
1098 return _impact_roll;
1099 }
1100
1101 double FGAIBase::_getImpactHdg() const {
1102 return _impact_hdg;
1103 }
1104
1105 double FGAIBase::_getImpactSpeed() const {
1106 return _impact_speed;
1107 }
1108
1109 int FGAIBase::getID() const {
1110 return _refID;
1111 }
1112
1113 int FGAIBase::_getSubID() const {
1114 return _subID;
1115 }
1116
1117 double FGAIBase::_getSpeed() const {
1118 return speed;
1119 }
1120
1121 double FGAIBase::_getRoll() const {
1122 return roll;
1123 }
1124
1125 double FGAIBase::_getPitch() const {
1126 return pitch;
1127 }
1128
1129 double FGAIBase::_getHeading() const {
1130 return hdg;
1131 }
1132
1133 double FGAIBase::_getXOffset() const {
1134 return _x_offset;
1135 }
1136
1137 double FGAIBase::_getYOffset() const {
1138 return _y_offset;
1139 }
1140
1141 double FGAIBase::_getZOffset() const {
1142 return _z_offset;
1143 }
1144
1145 const char* FGAIBase::_getPath() const {
1146 return model_path.c_str();
1147 }
1148
1149 const char* FGAIBase::_getSMPath() const {
1150 return _path.c_str();
1151 }
1152
1153 const char* FGAIBase::_getName() const {
1154 return _name.c_str();
1155 }
1156
1157 const char* FGAIBase::_getCallsign() const {
1158 return _callsign.c_str();
1159 }
1160
1161 const char* FGAIBase::_getSubmodel() const {
1162 return _submodel.c_str();
1163 }
1164
1165 int FGAIBase::_getFallbackModelIndex() const {
1166 return _fallback_model_index;
1167 }
1168
1169 int FGAIBase::_newAIModelID() {
1170 static int id = 0;
1171
1172 if (!++id)
1173 id++; // id = 0 is not allowed.
1174
1175 return id;
1176 }
1177
1178 void FGAIBase::setFlightPlan(std::unique_ptr<FGAIFlightPlan> f)
1179 {
1180 fp = std::move(f);
1181 }
1182
1183 bool FGAIBase::isValid() const
1184 {
1185 //Either no flightplan or it is valid
1186 return !fp || fp->isValidPlan();
1187 }
1188
1189 osg::LOD* FGAIBase::getSceneBranch() const
1190 {
1191 return _model;
1192 }
1193
1194 bool FGAIBase::modelLoaded() const
1195 {
1196 if(_low_res.valid())
1197 return _low_res->getNumChildren() >= 1;
1198 else if (_high_res.valid())
1199 return _high_res->getNumChildren() >= 1;
1200 return false;
1201 }
1202
1203 SGGeod FGAIBase::getGeodPos() const
1204 {
1205 return pos;
1206 }
1207
1208 void FGAIBase::setGeodPos(const SGGeod& geod)
1209 {
1210 pos = geod;
1211 }