]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
Improve <usage> tag feature
[flightgear.git] / src / AIModel / AIBase.cxx
1 // FGAIBase - abstract base class for AI objects
2 // Written by David Culp, started Nov 2003, based on
3 // David Luff's FGAIEntity class.
4 // - davidculp2@comcast.net
5 //
6 // With additions by Mathias Froehlich & Vivian Meazza 2004 -2007
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <string.h>
28
29 #include <simgear/compiler.h>
30
31 #include <boost/foreach.hpp>
32 #include <string>
33
34 #include <osg/ref_ptr>
35 #include <osg/Node>
36 #include <osgDB/FileUtils>
37
38 #include <simgear/misc/sg_path.hxx>
39 #include <simgear/scene/model/modellib.hxx>
40 #include <simgear/scene/util/SGNodeMasks.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
43
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <Scripting/NasalSys.hxx>
47 #include <Scripting/NasalModelData.hxx>
48 #include <Sound/fg_fx.hxx>
49
50 #include "AIBase.hxx"
51 #include "AIManager.hxx"
52
53 const char *default_model = "Models/Geometry/glider.ac";
54 const double FGAIBase::e = 2.71828183;
55 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
56
57 using std::string;
58 using namespace simgear;
59
60 class FGAIModelData : public simgear::SGModelData {
61 public:
62     FGAIModelData(SGPropertyNode *root = NULL)
63         : _nasal( new FGNasalModelDataProxy(root) ),
64         _ready(false),
65         _initialized(false),
66         _hasInteriorPath(false),
67         _interiorLoaded(false)
68     {
69     }
70
71     
72     ~FGAIModelData()
73     {
74     }
75     
76     virtual FGAIModelData* clone() const { return new FGAIModelData(); }
77
78     /** osg callback, thread-safe */
79     void modelLoaded(const std::string& path, SGPropertyNode *prop, osg::Node *n)
80     {
81         // WARNING: Called in a separate OSG thread! Only use thread-safe stuff here...
82         if (_ready)
83             return;
84         
85         if(prop->hasChild("interior-path")){
86             _interiorPath = prop->getStringValue("interior-path");
87             _hasInteriorPath = true;
88         }
89
90         _fxpath = prop->getStringValue("sound/path");
91         _nasal->modelLoaded(path, prop, n);
92         
93         _ready = true;
94
95     }
96     
97     /** init hook to be called after model is loaded.
98      * Not thread-safe. Call from main thread only. */
99     void init(void) { _initialized = true; }
100     
101     bool needInitilization(void) { return _ready && !_initialized;}
102     bool isInitialized(void) { return _initialized;}
103     inline std::string& get_sound_path() { return _fxpath;}
104
105     void setInteriorLoaded(const bool state) { _interiorLoaded = state;}
106     bool getInteriorLoaded(void) { return _interiorLoaded;}
107     bool hasInteriorPath(void) { return _hasInteriorPath;}
108     inline std::string& getInteriorPath() { return _interiorPath; }
109     
110 private:
111     std::auto_ptr<FGNasalModelDataProxy> _nasal;
112     std::string _fxpath;
113     bool _ready;
114     bool _initialized;
115
116     std::string _interiorPath;
117     bool _hasInteriorPath;
118     bool _interiorLoaded;
119 };
120
121 FGAIBase::FGAIBase(object_type ot, bool enableHot) :
122     _max_speed(300),
123     _name(""),
124     _parent(""),
125     props( NULL ),
126     model_removed( fgGetNode("/ai/models/model-removed", true) ),
127     manager( NULL ),
128     _installed(false),
129     fp( NULL ),
130     _impact_lat(0),
131     _impact_lon(0),
132     _impact_elev(0),
133     _impact_hdg(0),
134     _impact_pitch(0),
135     _impact_roll(0),
136     _impact_speed(0),
137     _refID( _newAIModelID() ),
138     _otype(ot),
139     _initialized(false),
140     _modeldata(0),
141     _fx(0)
142 {
143     tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
144     tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
145     bearing = elevation = range = rdot = 0.0;
146     x_shift = y_shift = rotation = 0.0;
147     in_range = false;
148     invisible = false;
149     no_roll = true;
150     life = 900;
151     delete_me = false;
152     _impact_reported = false;
153     _collision_reported = false;
154     _expiry_reported = false;
155
156     _subID = 0;
157
158     _x_offset = 0;
159     _y_offset = 0;
160     _z_offset = 0;
161
162     _pitch_offset = 0;
163     _roll_offset = 0;
164     _yaw_offset = 0;
165
166     pos = SGGeod::fromDeg(0, 0);
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     fp = 0;
183
184     rho = 1;
185     T = 280;
186     p = 1e5;
187     a = 340;
188     Mach = 0;
189
190     // explicitly disable HOT for (most) AI models
191     if (!enableHot)
192         aip.getSceneGraph()->setNodeMask(~SG_NODEMASK_TERRAIN_BIT);
193 }
194
195 FGAIBase::~FGAIBase() {
196     // Unregister that one at the scenery manager
197     removeModel();
198
199     if (props) {
200         SGPropertyNode* parent = props->getParent();
201
202         if (parent)
203             model_removed->setStringValue(props->getPath());
204     }
205
206     removeSoundFx();
207
208     if (fp)
209         delete fp;
210     fp = 0;
211 }
212
213 /** Cleanly remove the model
214  * and let the scenery database pager do the clean-up work.
215  */
216 void
217 FGAIBase::removeModel()
218 {
219     if (!_model.valid())
220         return;
221
222     FGScenery* pSceneryManager = globals->get_scenery();
223     if (pSceneryManager)
224     {
225         osg::ref_ptr<osg::Object> temp = _model.get();
226         pSceneryManager->get_models_branch()->removeChild(aip.getSceneGraph());
227         // withdraw from SGModelPlacement and drop own reference (unref)
228         aip.clear();
229         _modeldata = 0;
230         _model = 0;
231         
232         // pass it on to the pager, to be be deleted in the pager thread
233         pSceneryManager->getPager()->queueDeleteRequest(temp);
234     }
235     else
236     {
237         SG_LOG(SG_AI, SG_ALERT, "AIBase: Could not unload model. Missing scenery manager!");
238     }
239 }
240
241 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
242 {
243     if (!scFileNode)
244         return;
245
246     setPath(scFileNode->getStringValue("model",
247             fgGetString("/sim/multiplay/default-model", default_model)));
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
256     SGPropertyNode* submodels = scFileNode->getChild("submodels");
257
258     if (submodels) {
259         setServiceable(submodels->getBoolValue("serviceable", false));
260         setSMPath(submodels->getStringValue("path", ""));
261     }
262
263 }
264
265 void FGAIBase::update(double dt) {
266
267     if (_otype == otStatic)
268         return;
269
270     if (_otype == otBallistic)
271         CalculateMach();
272
273     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
274     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
275
276     if ( _fx )
277     {
278         // update model's audio sample values
279         _fx->set_position_geod( pos );
280
281         SGQuatd orient = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
282         _fx->set_orientation( orient );
283
284         SGVec3d velocity;
285         velocity = SGVec3d( speed_north_deg_sec, speed_east_deg_sec,
286                             pitch*speed );
287         _fx->set_velocity( velocity );
288     }
289     else if ((_modeldata)&&(_modeldata->needInitilization()))
290     {
291         // process deferred nasal initialization,
292         // which must be done in main thread
293         _modeldata->init();
294
295         // sound initialization
296         if (fgGetBool("/sim/sound/aimodels/enabled",false))
297         {
298             const string& fxpath = _modeldata->get_sound_path();
299             if (fxpath != "")
300             {
301                 props->setStringValue("sim/sound/path", fxpath.c_str());
302
303                 // initialize the sound configuration
304                 std::stringstream name;
305                 name <<  "aifx:";
306                 name << _refID;
307                 _fx = new FGFX(name.str(), props);
308                 _fx->init();
309             }
310         }
311     }
312
313     updateInterior();
314 }
315
316 void FGAIBase::updateInterior()
317 {
318     if(!_modeldata || !_modeldata->hasInteriorPath())
319         return;
320
321     if(!_modeldata->getInteriorLoaded()){ // interior is not yet load
322         double d2 = dist(SGVec3d::fromGeod(pos), globals->get_aircraft_position_cart());
323         if(d2 <= _maxRangeInterior){ // if the AI is in-range we load the interior
324             _interior = SGModelLib::loadPagedModel(_modeldata->getInteriorPath(), props, _modeldata);
325             if(_interior.valid()){
326                 _interior->setRange(0, 0.0, _maxRangeInterior);
327                 aip.add(_interior.get());
328                 _modeldata->setInteriorLoaded(true);
329                 SG_LOG(SG_AI, SG_INFO, "AIBase: Loaded interior model " << _interior->getName());
330             }
331         }
332     }
333 }
334
335 /** update LOD properties of the model */
336 void FGAIBase::updateLOD()
337 {
338     double maxRangeDetail = fgGetDouble("/sim/rendering/static-lod/ai-detailed", 10000.0);
339     double maxRangeBare   = fgGetDouble("/sim/rendering/static-lod/ai-bare", 20000.0);
340     _maxRangeInterior     = fgGetDouble("/sim/rendering/static-lod/ai-interior", 50.0);
341     if (_model.valid())
342     {
343         if( maxRangeDetail == 0.0 )
344         {
345             // disable LOD
346             _model->setRange(0, 0.0,     FLT_MAX);
347             _model->setRange(1, FLT_MAX, FLT_MAX);
348         }
349         else
350         {
351             _model->setRange(0, 0.0, maxRangeDetail);
352             _model->setRange(1, maxRangeDetail,maxRangeBare);
353         }
354     }
355 }
356
357 void FGAIBase::Transform() {
358
359     if (!invisible) {
360         aip.setVisible(true);
361         aip.setPosition(pos);
362
363         if (no_roll)
364             aip.setOrientation(0.0, pitch, hdg);
365         else
366             aip.setOrientation(roll, pitch, hdg);
367
368         aip.update();
369     } else {
370         aip.setVisible(false);
371         aip.update();
372     }
373
374 }
375
376 bool FGAIBase::init(bool search_in_AI_path)
377 {
378     if (_model.valid())
379     {
380         SG_LOG(SG_AI, SG_ALERT, "AIBase: Cannot initialize a model multiple times! " << model_path);
381         return false;
382     }
383
384     string f;
385     if(search_in_AI_path)
386     {
387         BOOST_FOREACH(SGPath p, globals->get_data_paths("AI")) {
388             p.append(model_path);
389             if (p.exists()) {
390                 f = p.str();
391                 break;
392             }
393         } // of AI data paths iteration
394     } // of search in AI path
395
396     if (f.empty()) {
397         f = simgear::SGModelLib::findDataFile(model_path);
398     }
399     
400     if(f.empty())
401         f = fgGetString("/sim/multiplay/default-model", default_model);
402     else
403         _installed = true;
404
405     props->addChild("type")->setStringValue("AI");
406     _modeldata = new FGAIModelData(props);
407     _model= SGModelLib::loadPagedModel(f, props, _modeldata);
408
409     _model->setName("AI-model range animation node");
410
411   //  _model->setCenterMode(osg::LOD::USE_BOUNDING_SPHERE_CENTER);
412   //  _model->setRangeMode(osg::LOD::DISTANCE_FROM_EYE_POINT);
413   
414 //    We really need low-resolution versions of AI/MP aircraft.
415 //    Or at least dummy "stubs" with some default silhouette.
416 //        _model->addChild( SGModelLib::loadPagedModel(fgGetString("/sim/multiplay/default-model", default_model),
417 //                                                    props, new FGNasalModelData(props)), FLT_MAX, FLT_MAX);
418     updateLOD();
419     initModel();
420   
421     if (_model.valid() && _initialized == false) {
422         aip.init( _model.get() );
423         aip.setVisible(true);
424         invisible = false;
425         globals->get_scenery()->get_models_branch()->addChild(aip.getSceneGraph());
426         _initialized = true;
427
428         SG_LOG(SG_AI, SG_DEBUG, "AIBase: Loaded model " << model_path);
429
430     } else if (!model_path.empty()) {
431         SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
432         // not properly installed...
433         _installed = false;
434     }
435
436     setDie(false);
437     return true;
438 }
439
440 void FGAIBase::initModel()
441 {
442     if (_model.valid()) { 
443
444         if( _path != ""){
445             props->setStringValue("submodels/path", _path.c_str());
446             SG_LOG(SG_AI, SG_DEBUG, "AIBase: submodels/path " << _path);
447         }
448
449         if( _parent!= ""){
450             props->setStringValue("parent-name", _parent.c_str());
451         }
452
453         fgSetString("/ai/models/model-added", props->getPath().c_str());
454     } else if (!model_path.empty()) {
455         SG_LOG(SG_AI, SG_WARN, "AIBase: Could not load model " << model_path);
456     }
457
458     setDie(false);
459 }
460
461
462 bool FGAIBase::isa( object_type otype ) {
463     return otype == _otype;
464 }
465
466
467 void FGAIBase::bind() {
468     _tiedProperties.setRoot(props);
469     tie("id", SGRawValueMethods<FGAIBase,int>(*this,
470         &FGAIBase::getID));
471     tie("velocities/true-airspeed-kt",  SGRawValuePointer<double>(&speed));
472     tie("velocities/vertical-speed-fps",
473         SGRawValueMethods<FGAIBase,double>(*this,
474         &FGAIBase::_getVS_fps,
475         &FGAIBase::_setVS_fps));
476
477     tie("position/altitude-ft",
478         SGRawValueMethods<FGAIBase,double>(*this,
479         &FGAIBase::_getAltitude,
480         &FGAIBase::_setAltitude));
481     tie("position/latitude-deg",
482         SGRawValueMethods<FGAIBase,double>(*this,
483         &FGAIBase::_getLatitude,
484         &FGAIBase::_setLatitude));
485     tie("position/longitude-deg",
486         SGRawValueMethods<FGAIBase,double>(*this,
487         &FGAIBase::_getLongitude,
488         &FGAIBase::_setLongitude));
489
490     tie("position/global-x",
491         SGRawValueMethods<FGAIBase,double>(*this,
492         &FGAIBase::_getCartPosX,
493         0));
494     tie("position/global-y",
495         SGRawValueMethods<FGAIBase,double>(*this,
496         &FGAIBase::_getCartPosY,
497         0));
498     tie("position/global-z",
499         SGRawValueMethods<FGAIBase,double>(*this,
500         &FGAIBase::_getCartPosZ,
501         0));
502     tie("callsign",
503         SGRawValueMethods<FGAIBase,const char*>(*this,
504         &FGAIBase::_getCallsign,
505         0));
506
507     tie("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
508     tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
509     tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
510
511     tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
512     tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
513     tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
514     tie("radar/range-nm", SGRawValuePointer<double>(&range));
515     tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
516     tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
517     tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
518     tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
519     tie("radar/rotation", SGRawValuePointer<double>(&rotation));
520     tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
521     tie("subID", SGRawValuePointer<int>(&_subID));
522     tie("controls/lighting/nav-lights", SGRawValueFunctions<bool>(_isNight));
523
524     props->setBoolValue("controls/lighting/beacon", true);
525     props->setBoolValue("controls/lighting/strobe", true);
526     props->setBoolValue("controls/glide-path", true);
527
528     props->setStringValue("controls/flight/lateral-mode", "roll");
529     props->setDoubleValue("controls/flight/target-hdg", hdg);
530     props->setDoubleValue("controls/flight/target-roll", roll);
531
532     props->setStringValue("controls/flight/longitude-mode", "alt");
533     props->setDoubleValue("controls/flight/target-alt", altitude_ft);
534     props->setDoubleValue("controls/flight/target-pitch", pitch);
535
536     props->setDoubleValue("controls/flight/target-spd", speed);
537
538     props->setBoolValue("sim/sound/avionics/enabled", false);
539     props->setDoubleValue("sim/sound/avionics/volume", 0.0);
540     props->setBoolValue("sim/sound/avionics/external-view", false);
541     props->setBoolValue("sim/current-view/internal", false);
542 }
543
544 void FGAIBase::unbind() {
545     _tiedProperties.Untie();
546
547     props->setBoolValue("/sim/controls/radar", true);
548
549     removeSoundFx();
550 }
551
552 void FGAIBase::removeSoundFx() {
553     // drop reference to sound effects now
554     if (_fx)
555     {
556         // must remove explicitly - since the sound manager also keeps a reference
557         _fx->unbind();
558         // now drop last reference - kill the object
559         _fx = 0;
560     }
561 }
562
563 double FGAIBase::UpdateRadar(FGAIManager* manager)
564 {
565     bool control = fgGetBool("/sim/controls/radar", true);
566
567     if(!control) return 0;
568
569     double radar_range_m = fgGetDouble("/instrumentation/radar/range");
570     bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
571     radar_range_m *= SG_NM_TO_METER  * 1.1; // + 10%
572     radar_range_m *= radar_range_m; // squared
573     
574     double d2 = distSqr(SGVec3d::fromGeod(pos), globals->get_aircraft_position_cart());
575     double range_ft = sqrt(d2) * SG_METER_TO_FEET;
576     
577     if (!force_on && (d2 > radar_range_m)) {
578         return range_ft * range_ft;
579     }
580     
581     props->setBoolValue("radar/in-range", true);
582
583     // copy values from the AIManager
584     double user_heading   = manager->get_user_heading();
585     double user_pitch     = manager->get_user_pitch();
586   
587     range = range_ft * SG_FEET_TO_METER * SG_METER_TO_NM;
588
589     // calculate bearing to target
590     bearing = SGGeodesy::courseDeg(globals->get_aircraft_position(), pos);
591
592     // calculate look left/right to target, without yaw correction
593     horiz_offset = bearing - user_heading;
594     SG_NORMALIZE_RANGE(horiz_offset, -180.0, 180.0);
595    
596     // calculate elevation to target
597     ht_diff = altitude_ft - globals->get_aircraft_position().getElevationFt();
598     elevation = atan2( ht_diff, range_ft ) * SG_RADIANS_TO_DEGREES;
599
600     // calculate look up/down to target
601     vert_offset = elevation - user_pitch;
602
603     /* this calculation needs to be fixed, but it isn't important anyway
604     // calculate range rate
605     double recip_bearing = bearing + 180.0;
606     if (recip_bearing > 360.0) recip_bearing -= 360.0;
607     double my_horiz_offset = recip_bearing - hdg;
608     if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
609     if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
610     rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
611     +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
612     */
613
614     // now correct look left/right for yaw
615     // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
616
617     // calculate values for radar display
618     y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
619     x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
620     
621     rotation = hdg - user_heading;
622     SG_NORMALIZE_RANGE(rotation, 0.0, 360.0);
623
624     return range_ft * range_ft;
625 }
626
627 /*
628 * Getters and Setters
629 */
630
631 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
632     // Transform that one to the horizontal local coordinate system.
633     SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
634
635     // and postrotate the orientation of the AIModel wrt the horizontal
636     // local frame
637     hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
638
639     // The offset converted to the usual body fixed coordinate system
640     // rotated to the earth fixed coordinates axis
641     SGVec3d off = hlTrans.backTransform(_off);
642
643     // Add the position offset of the AIModel to gain the earth centered position
644     SGVec3d cartPos = SGVec3d::fromGeod(pos);
645
646     return cartPos + off;
647 }
648
649 SGVec3d FGAIBase::getCartPos() const {
650     SGVec3d cartPos = SGVec3d::fromGeod(pos);
651     return cartPos;
652 }
653
654 bool FGAIBase::getGroundElevationM(const SGGeod& pos, double& elev,
655                                    const simgear::BVHMaterial** material) const {
656     return globals->get_scenery()->get_elevation_m(pos, elev, material,
657                                                    _model.get());
658 }
659
660 double FGAIBase::_getCartPosX() const {
661     SGVec3d cartPos = getCartPos();
662     return cartPos.x();
663 }
664
665 double FGAIBase::_getCartPosY() const {
666     SGVec3d cartPos = getCartPos();
667     return cartPos.y();
668 }
669
670 double FGAIBase::_getCartPosZ() const {
671     SGVec3d cartPos = getCartPos();
672     return cartPos.z();
673 }
674
675 void FGAIBase::_setLongitude( double longitude ) {
676     pos.setLongitudeDeg(longitude);
677 }
678
679 void FGAIBase::_setLatitude ( double latitude )  {
680     pos.setLatitudeDeg(latitude);
681 }
682
683 void FGAIBase::_setSubID( int s ) {
684     _subID = s;
685 }
686
687 bool FGAIBase::setParentNode() {
688
689     if (_parent == ""){
690        SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
691             << " parent not set ");
692        return false;
693     }
694
695     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
696
697     for (int i = ai->nChildren() - 1; i >= -1; i--) {
698         SGPropertyNode_ptr model;
699
700         if (i < 0) { // last iteration: selected model
701             model = _selected_ac;
702         } else {
703             model = ai->getChild(i);
704             //const string& path = ai->getPath();
705             const string name = model->getStringValue("name");
706
707             if (!model->nChildren()){
708                 continue;
709             }
710             if (name == _parent) {
711                 _selected_ac = model;  // save selected model for last iteration
712                 break;
713             }
714
715         }
716         if (!model)
717             continue;
718
719     }// end for loop
720
721     if (_selected_ac != 0){
722         const string name = _selected_ac->getStringValue("name");
723         return true;
724     } else {
725         SG_LOG(SG_AI, SG_ALERT, "AIBase: " << _name
726             << " parent not found: dying ");
727         setDie(true);
728         return false;
729     }
730
731 }
732
733 double FGAIBase::_getLongitude() const {
734     return pos.getLongitudeDeg();
735 }
736
737 double FGAIBase::_getLatitude() const {
738     return pos.getLatitudeDeg();
739 }
740
741 double FGAIBase::_getElevationFt() const {
742     return pos.getElevationFt();
743 }
744
745 double FGAIBase::_getRdot() const {
746     return rdot;
747 }
748
749 double FGAIBase::_getVS_fps() const {
750     return vs/60.0;
751 }
752
753 double FGAIBase::_get_speed_east_fps() const {
754     return speed_east_deg_sec * ft_per_deg_lon;
755 }
756
757 double FGAIBase::_get_speed_north_fps() const {
758     return speed_north_deg_sec * ft_per_deg_lat;
759 }
760
761 void FGAIBase::_setVS_fps( double _vs ) {
762     vs = _vs*60.0;
763 }
764
765 double FGAIBase::_getAltitude() const {
766     return altitude_ft;
767 }
768
769 double FGAIBase::_getAltitudeAGL(SGGeod inpos, double start){
770     getGroundElevationM(SGGeod::fromGeodM(inpos, start),
771         _elevation_m, NULL);
772     return inpos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
773 }
774
775 bool FGAIBase::_getServiceable() const {
776     return serviceable;
777 }
778
779 SGPropertyNode* FGAIBase::_getProps() const {
780     return props;
781 }
782
783 void FGAIBase::_setAltitude( double _alt ) {
784     setAltitude( _alt );
785 }
786
787 bool FGAIBase::_isNight() {
788     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
789 }
790
791 bool FGAIBase::_getCollisionData() {
792     return _collision_reported;
793 }
794
795 bool FGAIBase::_getExpiryData() {
796     return _expiry_reported;
797 }
798
799 bool FGAIBase::_getImpactData() {
800     return _impact_reported;
801 }
802
803 double FGAIBase::_getImpactLat() const {
804     return _impact_lat;
805 }
806
807 double FGAIBase::_getImpactLon() const {
808     return _impact_lon;
809 }
810
811 double FGAIBase::_getImpactElevFt() const {
812     return _impact_elev * SG_METER_TO_FEET;
813 }
814
815 double FGAIBase::_getImpactPitch() const {
816     return _impact_pitch;
817 }
818
819 double FGAIBase::_getImpactRoll() const {
820     return _impact_roll;
821 }
822
823 double FGAIBase::_getImpactHdg() const {
824     return _impact_hdg;
825 }
826
827 double FGAIBase::_getImpactSpeed() const {
828     return _impact_speed;
829 }
830
831 int FGAIBase::getID() const {
832     return  _refID;
833 }
834
835 int FGAIBase::_getSubID() const {
836     return  _subID;
837 }
838
839 double FGAIBase::_getSpeed() const {
840     return speed;
841 }
842
843 double FGAIBase::_getRoll() const {
844     return roll;
845 }
846
847 double FGAIBase::_getPitch() const {
848     return pitch;
849 }
850
851 double FGAIBase::_getHeading() const {
852     return hdg;
853 }
854
855 double  FGAIBase::_getXOffset() const {
856     return _x_offset;
857 }
858
859 double  FGAIBase::_getYOffset() const {
860     return _y_offset;
861 }
862
863 double  FGAIBase::_getZOffset() const {
864     return _z_offset;
865 }
866
867 const char* FGAIBase::_getPath() const {
868     return model_path.c_str();
869 }
870
871 const char* FGAIBase::_getSMPath() const {
872     return _path.c_str();
873 }
874
875 const char* FGAIBase::_getName() const {
876     return _name.c_str();
877 }
878
879 const char* FGAIBase::_getCallsign() const {
880     return _callsign.c_str();
881 }
882
883 const char* FGAIBase::_getSubmodel() const {
884     return _submodel.c_str();
885 }
886
887 void FGAIBase::CalculateMach() {
888     // Calculate rho at altitude, using standard atmosphere
889     // For the temperature T and the pressure p,
890     double altitude = altitude_ft;
891
892     if (altitude < 36152) {             // curve fits for the troposphere
893         T = 59 - 0.00356 * altitude;
894         p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
895     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
896         T = -70;
897         p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
898     } else {                                    //  upper stratosphere
899         T = -205.05 + (0.00164 * altitude);
900         p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
901     }
902
903     rho = p / (1718 * (T + 459.7));
904
905     // calculate the speed of sound at altitude
906     // a = sqrt ( g * R * (T + 459.7))
907     // where:
908     // a = speed of sound [ft/s]
909     // g = specific heat ratio, which is usually equal to 1.4
910     // R = specific gas constant, which equals 1716 ft-lb/slug/R
911     a = sqrt ( 1.4 * 1716 * (T + 459.7));
912
913     // calculate Mach number
914     Mach = speed/a;
915
916     // cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
917 }
918
919 int FGAIBase::_newAIModelID() {
920     static int id = 0;
921
922     if (!++id)
923         id++;   // id = 0 is not allowed.
924
925     return id;
926 }
927
928
929