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