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