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