]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
Be a bit more descriptive on "PT_vs_hpt: ran out of layers"
[flightgear.git] / src / AIModel / submodel.cxx
1 //// submodel.cxx - models a releasable submodel.
2 // Written by Dave Culp, started Aug 2004
3 // With major additions by Vivian Meaaza 2004 - 2007
4 //
5 // This file is in the Public Domain and comes with no warranty.
6
7 #ifdef HAVE_CONFIG_H
8 #  include "config.h"
9 #endif
10
11 #include "submodel.hxx"
12
13 #include <simgear/structure/exception.hxx>
14 #include <simgear/misc/sg_path.hxx>
15 #include <simgear/math/sg_geodesy.hxx>
16 #include <simgear/props/props_io.hxx>
17
18 #include <Main/fg_props.hxx>
19 #include <Main/util.hxx>
20
21
22 #include "AIBase.hxx"
23 #include "AIManager.hxx"
24 #include "AIBallistic.hxx"
25
26
27 const double FGSubmodelMgr::lbs_to_slugs = 0.031080950172;
28
29 FGSubmodelMgr::FGSubmodelMgr()
30 {
31     x_offset = y_offset = z_offset = 0.0;
32     pitch_offset = 0.0;
33     yaw_offset = 0.0;
34
35     //out[0] = out[1] = out[2] = 0;
36     string contents_node;
37     contrail_altitude = 30000;
38     _count = 0;
39     _found_sub = true;
40 }
41
42 FGSubmodelMgr::~FGSubmodelMgr()
43 {
44 }
45
46 void FGSubmodelMgr::init()
47 {
48     index = 0;
49
50     _serviceable_node = fgGetNode("/sim/submodels/serviceable", true);
51     _serviceable_node->setBoolValue(true);
52
53     _user_lat_node = fgGetNode("/position/latitude-deg", true);
54     _user_lon_node = fgGetNode("/position/longitude-deg", true);
55     _user_alt_node = fgGetNode("/position/altitude-ft", true);
56
57     _user_heading_node = fgGetNode("/orientation/heading-deg", true);
58     _user_pitch_node =   fgGetNode("/orientation/pitch-deg", true);
59     _user_roll_node =    fgGetNode("/orientation/roll-deg", true);
60     _user_yaw_node =     fgGetNode("/orientation/yaw-deg", true);
61     _user_alpha_node =   fgGetNode("/orientation/alpha-deg", true);
62
63     _user_speed_node = fgGetNode("/velocities/uBody-fps", true);
64
65     _user_wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps", true);
66     _user_wind_from_north_node = fgGetNode("/environment/wind-from-north-fps", true);
67
68     _user_speed_down_fps_node   = fgGetNode("/velocities/speed-down-fps", true);
69     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
70     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
71
72     _contrail_altitude_node = fgGetNode("/environment/params/contrail-altitude", true);
73     contrail_altitude       = _contrail_altitude_node->getDoubleValue();
74     _contrail_trigger       = fgGetNode("ai/submodels/contrails", true);
75     _contrail_trigger->setBoolValue(false);
76
77     ai = (FGAIManager*)globals->get_subsystem("ai_model");
78
79     load();
80
81     //_model_added_node = fgGetNode("ai/models/model-added", true);
82     //_model_added_node->addChangeListener(this, false);
83
84 }
85
86 void FGSubmodelMgr::postinit() {
87     // postinit, so that the AI list is populated
88
89         loadAI();
90
91     while (_found_sub)
92         loadSubmodels();
93
94     //TODO reload submodels if an MP ac joins
95
96     //_model_added_node = fgGetNode("ai/models/model-added", true);
97     //_model_added_node->addChangeListener(this, false);
98 }
99
100 void FGSubmodelMgr::bind()
101 {}
102
103 void FGSubmodelMgr::unbind()
104 {
105     submodel_iterator = submodels.begin();
106     while (submodel_iterator != submodels.end()) {
107         (*submodel_iterator)->prop->untie("count");
108         ++submodel_iterator;
109     }
110 }
111
112 void FGSubmodelMgr::update(double dt)
113 {
114     if (!_serviceable_node->getBoolValue())
115         return;
116
117     _impact = false;
118     _hit = false;
119     _expiry = false;
120
121     // check if the submodel hit an object or terrain
122     sm_list = ai->get_ai_list();
123     sm_list_iterator sm_list_itr = sm_list.begin();
124     sm_list_iterator end = sm_list.end();
125
126     for (; sm_list_itr != end; ++sm_list_itr) {
127         FGAIBase::object_type object_type =(*sm_list_itr)->getType();
128
129         if (object_type != FGAIBase::otBallistic){// only work on ballistic objects
130             continue; // so continue 
131         }
132
133         int parent_subID = (*sm_list_itr)->_getSubID();
134         int id = (*sm_list_itr)->getID();
135
136         if ( parent_subID == 0 || id == -1) // this entry in the list has no associated submodel
137             continue;                       // or is invalid so we can continue
138
139         //SG_LOG(SG_GENERAL, SG_DEBUG, "Submodel: Impact " << _impact << " hit! "
140         //        << _hit <<" parent_subID " << parent_subID);
141
142         _hit = (*sm_list_itr)->_getCollisionData();
143         _impact = (*sm_list_itr)->_getImpactData();
144         _expiry = (*sm_list_itr)->_getExpiryData();
145
146         //SG_LOG(SG_GENERAL, SG_ALERT, "Submodel: " << (*sm_list_itr)->_getName()
147         //    << " Impact " << _impact << " hit! " << _hit
148         //    << " exipiry :-( " << _expiry );
149
150         if (_impact || _hit || _expiry) {
151     //        SG_LOG(SG_GENERAL, SG_ALERT, "Submodel: Impact " << _impact << " hit! " << _hit 
152                 //<< " exipiry :-( " << _expiry );
153
154             submodel_iterator = submodels.begin();
155
156             while (submodel_iterator != submodels.end()) {
157                 int child_ID = (*submodel_iterator)->id;
158                 //cout << "Impact: parent SubID " << parent_subID << " child_ID " << child_ID << endl;
159
160                 if ( parent_subID == child_ID ) {
161                     _parent_lat = (*sm_list_itr)->_getImpactLat();
162                     _parent_lon = (*sm_list_itr)->_getImpactLon();
163                     _parent_elev = (*sm_list_itr)->_getImpactElevFt();
164                     _parent_hdg = (*sm_list_itr)->_getImpactHdg();
165                     _parent_pitch = (*sm_list_itr)->_getImpactPitch();
166                     _parent_roll = (*sm_list_itr)->_getImpactRoll();
167                     _parent_speed = (*sm_list_itr)->_getImpactSpeed();
168                     (*submodel_iterator)->first_time = true;
169                     //cout << "Impact: parent SubID = child_ID elev " << _parent_elev << endl;
170
171                     if (release(*submodel_iterator, dt)){
172                         (*sm_list_itr)->setDie(true);
173                         //cout << "Impact: set die" << (*sm_list_itr)->_getName() << endl;
174                     }
175
176                 }
177
178                 ++submodel_iterator;
179             }
180         }
181     }
182
183     _contrail_trigger->setBoolValue(_user_alt_node->getDoubleValue() > contrail_altitude);
184
185
186 //    bool in_range = true;
187     bool trigger = false;
188     int i = -1;
189
190     submodel_iterator = submodels.begin();
191     while (submodel_iterator != submodels.end())  {
192         i++;
193
194         /*SG_LOG(SG_GENERAL, SG_DEBUG,
195                 "Submodels:  " << (*submodel_iterator)->id
196                 << " name " << (*submodel_iterator)->name
197                 );*/
198
199         if ((*submodel_iterator)->trigger_node != 0) {
200             _trigger_node = (*submodel_iterator)->trigger_node;
201             trigger = _trigger_node->getBoolValue();
202             //cout << (*submodel_iterator)->name << "trigger node found " <<  trigger << endl;
203         } else {
204             trigger = false;
205             //cout << (*submodel_iterator)->name << " trigger node not found " << trigger << endl;
206         }
207
208         if (trigger && (*submodel_iterator)->count != 0) {
209
210             int id = (*submodel_iterator)->id;
211             string name = (*submodel_iterator)->name;
212             
213             SG_LOG(SG_GENERAL, SG_DEBUG,
214             "Submodels release:  " << (*submodel_iterator)->id
215             << " name " << (*submodel_iterator)->name
216             << " count " << (*submodel_iterator)->count
217             << " slaved " << (*submodel_iterator)->slaved
218             );
219
220             release(*submodel_iterator, dt);
221         } else
222             (*submodel_iterator)->first_time = true;
223
224         ++submodel_iterator;
225     } // end while
226 }
227
228 bool FGSubmodelMgr::release(submodel *sm, double dt)
229 {
230     //cout << "release id " << sm->id 
231     //    << " name " << sm->name
232     //    << " first time " << sm->first_time
233     //    << " repeat " << sm->repeat
234     //    << " slaved " << sm->slaved
235     //    << endl;
236
237     // only run if first time or repeat is set to true
238     if (!sm->first_time && !sm->repeat) {
239         //cout<< "returning: "<< sm->name 
240         //    << " not first time " << sm->first_time 
241         //    << " repeat " << sm->repeat
242         //    << " slaved " << sm->slaved
243         //    << endl;
244         return false;
245     }
246
247     sm->timer += dt;
248
249     if (sm->timer < sm->delay) {
250         //cout << "not yet: timer " << sm->timer << " delay " << sm->delay << endl;
251         return false;
252     }
253     
254     //cout << "released timer: " << sm->timer << " delay " << sm->delay << endl;
255
256     sm->timer = 0.0;
257
258     if (sm->first_time) {
259         dt = 0.0;
260         sm->first_time = false;
261     }
262
263     transform(sm);  // calculate submodel's initial conditions in world-coordinates
264
265     FGAIBallistic* ballist = new FGAIBallistic;
266     ballist->setPath(sm->model.c_str());
267     ballist->setName(sm->name);
268     ballist->setSlaved(sm->slaved);
269     ballist->setRandom(sm->random);
270     ballist->setRandomness(sm->randomness);
271     ballist->setLatitude(offsetpos.getLatitudeDeg());
272     ballist->setLongitude(offsetpos.getLongitudeDeg());
273     ballist->setAltitude(offsetpos.getElevationFt());
274     ballist->setAzimuth(IC.azimuth);
275     ballist->setElevation(IC.elevation);
276     ballist->setRoll(IC.roll);
277     ballist->setSpeed(IC.speed / SG_KT_TO_FPS);
278     ballist->setWind_from_east(IC.wind_from_east);
279     ballist->setWind_from_north(IC.wind_from_north);
280     ballist->setMass(IC.mass);
281     ballist->setDragArea(sm->drag_area);
282     ballist->setLife(sm->life);
283     ballist->setBuoyancy(sm->buoyancy);
284     ballist->setWind(sm->wind);
285     ballist->setCd(sm->cd);
286     ballist->setStabilisation(sm->aero_stabilised);
287     ballist->setNoRoll(sm->no_roll);
288     ballist->setCollision(sm->collision);
289     ballist->setExpiry(sm->expiry);
290     ballist->setImpact(sm->impact);
291     ballist->setImpactReportNode(sm->impact_report);
292     ballist->setFuseRange(sm->fuse_range);
293     ballist->setSubmodel(sm->submodel.c_str());
294     ballist->setSubID(sm->sub_id);
295     ballist->setForceStabilisation(sm->force_stabilised);
296     ballist->setExternalForce(sm->ext_force);
297     ballist->setForcePath(sm->force_path.c_str());
298     ballist->setXoffset(sm->x_offset);
299     ballist->setYoffset(sm->y_offset);
300     ballist->setZoffset(sm->z_offset);
301     ballist->setPitchoffset(sm->pitch_offset);
302     ballist->setYawoffset(sm->yaw_offset);
303     ballist->setParentNode(_selected_ac);
304     ballist->setContentsNode(sm->contents_node);
305     ballist->setWeight(sm->weight);
306     ai->attach(ballist);
307
308     if (sm->count > 0)
309         sm->count--;
310     return true;
311 }
312
313 void FGSubmodelMgr::load()
314 {
315     SGPropertyNode *path = fgGetNode("/sim/submodels/path");
316
317     if (path) {
318         const int id = 0;
319         string Path = path->getStringValue();
320         bool Seviceable =_serviceable_node->getBoolValue();
321         setData(id, Path, Seviceable);
322     }
323 }
324
325 void FGSubmodelMgr::transform(submodel *sm)
326 {
327     // set initial conditions
328     if (sm->contents_node != 0 && !sm->slaved) {
329         // get the weight of the contents (lbs) and convert to mass (slugs)
330         sm->contents = sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue();
331         //cout << "transform: contents " << sm->contents << endl;
332         IC.mass = (sm->weight + sm->contents) * lbs_to_slugs;
333         //cout << "mass inc contents"  << IC.mass << endl;
334
335         // set contents to 0 in the parent
336         sm->contents_node->getChild("level-gal_us",0,1)->setDoubleValue(0);
337         /*cout << "contents " << sm->contents_node->getChild("level-gal_us")->getDoubleValue()
338         << " " << sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue()
339         << endl;*/
340     } else
341         IC.mass = sm->weight * lbs_to_slugs;
342
343     int id = sm->id;
344     int sub_id = sm->sub_id;
345     string name = sm->name;
346
347
348     if (sm->speed_node != 0)
349         sm->speed = sm->speed_node->getDoubleValue();
350
351
352     //cout << " name " << name << " id " << id << " sub id" << sub_id << endl;
353
354     // set the Initial Conditions for the types of submodel parent 
355
356     if (_impact || _hit || _expiry) {
357         // set the data for a submodel tied to a submodel
358
359         _count++;
360
361         IC.lat             = _parent_lat;
362         IC.lon             = _parent_lon;
363         IC.alt             = _parent_elev;
364         IC.roll            = _parent_roll;    // rotation about x axis
365         IC.elevation       = _parent_pitch;   // rotation about y axis
366         IC.azimuth         = _parent_hdg;     // rotation about z axis
367         IC.speed           = _parent_speed;
368         IC.speed_down_fps  = 0;
369         IC.speed_east_fps  = 0;
370         IC.speed_north_fps = 0;
371
372     } else if (id == 0) {
373         //set the data for a submodel tied to the main model
374
375         IC.lat             = _user_lat_node->getDoubleValue();
376         IC.lon             = _user_lon_node->getDoubleValue();
377         IC.alt             = _user_alt_node->getDoubleValue();
378         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
379         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
380         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
381         IC.speed           = _user_speed_node->getDoubleValue();
382         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
383         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
384         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
385
386     } else {
387         // set the data for a submodel tied to an AI Object
388         //cout << " set the data for a submodel tied to an AI Object " << id << endl;
389         sm_list_iterator sm_list_itr = sm_list.begin();
390         sm_list_iterator end = sm_list.end();
391         setParentNode(id);
392     }
393
394     //cout << "Submodel: setting IC "<< name << endl;
395     //cout << "heading " << IC.azimuth << endl ;
396     //cout << "speed down " << IC.speed_down_fps << endl ;
397     //cout << "speed east " << IC.speed_east_fps << endl ;
398     //cout << "speed north " << IC.speed_north_fps << endl ;
399     //cout << "parent speed fps in " << IC.speed << "sm speed in " << sm->speed << endl ;
400     //cout << "lat " << IC.lat;
401     //cout << "alt " << IC.alt <<  endl ;
402
403
404     // Set the Initial Conditions that are common to all types of parent
405     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
406     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
407
408 //cout << "wind e " << IC.wind_from_east << " n " << IC.wind_from_north << endl;
409
410     userpos.setLatitudeDeg(IC.lat);
411     userpos.setLongitudeDeg(IC.lon);
412     userpos.setElevationFt(IC.alt);
413
414     _x_offset = sm->x_offset;
415     _y_offset = sm->y_offset;
416     _z_offset = sm->z_offset;
417
418     setOffsetPos();
419
420     //IC.elevation += sm->pitch_offset;
421     //IC.azimuth   += sm->yaw_offset ;
422
423     // pre-process the trig functions
424     cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS);
425     sinRx = sin(-IC.roll * SG_DEGREES_TO_RADIANS);
426     cosRy = cos(-IC.elevation * SG_DEGREES_TO_RADIANS);
427     sinRy = sin(-IC.elevation * SG_DEGREES_TO_RADIANS);
428     cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS);
429     sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS);
430
431
432     // Get submodel initial velocity vector angles in XZ and XY planes.
433     // This vector should be added to aircraft's vector.
434     IC.elevation += (sm->yaw_offset * sinRx) + (sm->pitch_offset * cosRx);
435     IC.azimuth   += (sm->yaw_offset * cosRx) - (sm->pitch_offset * sinRx);
436
437     // calculate the total speed north
438     IC.total_speed_north = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
439             * cos(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_north_fps;
440
441     // calculate the total speed east
442     IC.total_speed_east = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
443             * sin(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_east_fps;
444
445     // calculate the total speed down
446     IC.total_speed_down = sm->speed * -sin(IC.elevation * SG_DEGREES_TO_RADIANS)
447             + IC.speed_down_fps;
448
449     // re-calculate speed, elevation and azimuth
450     IC.speed = sqrt(IC.total_speed_north * IC.total_speed_north
451             + IC.total_speed_east * IC.total_speed_east
452             + IC.total_speed_down * IC.total_speed_down);
453
454     // if speeds are low this calculation can become unreliable
455     if (IC.speed > 1) {
456         IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES;
457         //        cout << "azimuth1 " << IC.azimuth<<endl;
458
459         // rationalise the output
460         if (IC.azimuth < 0)
461             IC.azimuth += 360;
462         else if (IC.azimuth >= 360)
463             IC.azimuth -= 360;
464         // cout << "azimuth2 " << IC.azimuth<<endl;
465
466         IC.elevation = -atan(IC.total_speed_down / sqrt(IC.total_speed_north
467             * IC.total_speed_north + IC.total_speed_east * IC.total_speed_east))
468             * SG_RADIANS_TO_DEGREES;
469     }
470     //cout << "IC.speed " << IC.speed / SG_KT_TO_FPS << endl;
471 }
472
473 void FGSubmodelMgr::updatelat(double lat)
474 {
475     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
476     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
477 }
478
479 void FGSubmodelMgr::loadAI()
480 {
481     SG_LOG(SG_GENERAL, SG_DEBUG, "Submodels: Loading AI submodels ");
482
483     sm_list = ai->get_ai_list();
484
485     if (sm_list.empty()) {
486         SG_LOG(SG_GENERAL, SG_ALERT, "Submodels: Unable to read AI submodel list");
487         return;
488     }
489
490     sm_list_iterator sm_list_itr = sm_list.begin();
491     sm_list_iterator end = sm_list.end();
492
493     while (sm_list_itr != end) {
494         string path = (*sm_list_itr)->_getSMPath();
495
496         if (path.empty()) {
497             ++sm_list_itr;
498             continue;
499         }
500
501         int id = (*sm_list_itr)->getID();
502         string type = (*sm_list_itr)->getTypeString();
503         bool serviceable = (*sm_list_itr)->_getServiceable();
504
505         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
506
507         setData(id, path, serviceable);
508         ++sm_list_itr;
509     }
510 }
511
512
513
514 void FGSubmodelMgr::setData(int id, string& path, bool serviceable)
515 {
516     SGPropertyNode root;
517
518     SGPath config = globals->resolve_aircraft_path(path);
519     try {
520         SG_LOG(SG_GENERAL, SG_DEBUG,
521                 "Submodels: Trying to read AI submodels file: " << config.str());
522         readProperties(config.str(), &root);
523     } catch (const sg_exception &) {
524         SG_LOG(SG_GENERAL, SG_ALERT,
525                 "Submodels: Unable to read AI submodels file: " << config.str());
526         return;
527     }
528
529     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
530     vector<SGPropertyNode_ptr>::iterator it = children.begin();
531     vector<SGPropertyNode_ptr>::iterator end = children.end();
532
533     for (int i = 0; it != end; ++it, i++) {
534         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
535         submodel* sm = new submodel;
536         SGPropertyNode * entry_node = *it;
537         sm->name            = entry_node->getStringValue("name", "none_defined");
538         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
539         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
540         sm->repeat          = entry_node->getBoolValue("repeat", false);
541         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
542         sm->count           = entry_node->getIntValue("count", 1);
543         sm->slaved          = entry_node->getBoolValue("slaved", false);
544         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
545         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
546         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
547         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
548         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
549         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
550         sm->life            = entry_node->getDoubleValue("life", 900.0);
551         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
552         sm->wind            = entry_node->getBoolValue("wind", false);
553         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
554         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
555         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
556         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
557         sm->collision       = entry_node->getBoolValue("collision", false);
558         sm->expiry                      = entry_node->getBoolValue("expiry", false);
559         sm->impact          = entry_node->getBoolValue("impact", false);
560         sm->impact_report   = entry_node->getStringValue("impact-reports");
561         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
562         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
563         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
564         sm->submodel        = entry_node->getStringValue("submodel-path", "");
565         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
566         sm->ext_force       = entry_node->getBoolValue("external-force", false);
567         sm->force_path      = entry_node->getStringValue("force-path", "");
568         sm->random                      = entry_node->getBoolValue("random", false);
569         sm->randomness          = entry_node->getDoubleValue("randomness", 0.5);
570
571         if (sm->contents_node != 0)
572             sm->contents = sm->contents_node->getDoubleValue();
573
574         const char *trigger_path = entry_node->getStringValue("trigger", 0);
575         if (trigger_path) {
576             sm->trigger_node = fgGetNode(trigger_path, true);
577             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
578         } else {
579             sm->trigger_node = 0;
580         }
581
582         if (sm->speed_node != 0)
583             sm->speed = sm->speed_node->getDoubleValue();
584
585         sm->timer = sm->delay;
586         sm->id = id;
587         sm->first_time = false;
588         sm->serviceable = serviceable;
589         sm->sub_id = 0;
590
591         sm->prop = fgGetNode("/ai/submodels/submodel", index, true);
592         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
593         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
594         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
595         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
596         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
597         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
598         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
599         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
600         string name = sm->name;
601         sm->prop->setStringValue("name", name.c_str());
602
603         string submodel = sm->submodel;
604         sm->prop->setStringValue("submodel", submodel.c_str());
605
606         string force_path = sm->force_path;
607         sm->prop->setStringValue("force_path", force_path.c_str());
608         //cout << "set force_path Sub " << force_path << endl;
609
610         if (sm->contents_node != 0)
611             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
612
613         index++;
614         submodels.push_back(sm);
615     }
616 }
617
618 void FGSubmodelMgr::setSubData(int id, string& path, bool serviceable)
619 {
620     SGPropertyNode root;
621     SGPath config = globals->resolve_aircraft_path(path);
622
623     try {
624         SG_LOG(SG_GENERAL, SG_DEBUG,
625                 "Submodels: Trying to read AI submodels file: " << config.str());
626         readProperties(config.str(), &root);
627
628     } catch (const sg_exception &) {
629         SG_LOG(SG_GENERAL, SG_ALERT,
630                 "Submodels: Unable to read AI submodels file: " << config.str());
631         return;
632     }
633
634     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
635     vector<SGPropertyNode_ptr>::iterator it = children.begin();
636     vector<SGPropertyNode_ptr>::iterator end = children.end();
637
638     for (int i = 0; it != end; ++it, i++) {
639         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
640         submodel* sm = new submodel;
641         SGPropertyNode * entry_node = *it;
642         sm->name            = entry_node->getStringValue("name", "none_defined");
643         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
644         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
645         sm->repeat          = entry_node->getBoolValue("repeat", false);
646         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
647         sm->count           = entry_node->getIntValue("count", 1);
648         sm->slaved          = entry_node->getBoolValue("slaved", false);
649         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
650         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
651         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
652         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
653         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
654         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
655         sm->life            = entry_node->getDoubleValue("life", 900.0);
656         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
657         sm->wind            = entry_node->getBoolValue("wind", false);
658         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
659         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
660         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
661         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
662         sm->collision       = entry_node->getBoolValue("collision", false);
663         sm->expiry          = entry_node->getBoolValue("expiry", false);
664         sm->impact          = entry_node->getBoolValue("impact", false);
665         sm->impact_report   = entry_node->getStringValue("impact-reports");
666         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
667         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
668         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
669         sm->submodel        = entry_node->getStringValue("submodel-path", "");
670         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
671         sm->ext_force       = entry_node->getBoolValue("external-force", false);
672         sm->force_path      = entry_node->getStringValue("force-path", "");
673         sm->random          = entry_node->getBoolValue("random", false);
674         sm->randomness      = entry_node->getDoubleValue("randomness", 0.5);
675
676         if (sm->contents_node != 0)
677             sm->contents = sm->contents_node->getDoubleValue();
678
679         const char *trigger_path = entry_node->getStringValue("trigger", 0);
680         if (trigger_path) {
681             sm->trigger_node = fgGetNode(trigger_path, true);
682             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
683         } else {
684             sm->trigger_node = 0;
685         }
686
687         if (sm->speed_node != 0)
688             sm->speed = sm->speed_node->getDoubleValue();
689
690         sm->timer = sm->delay;
691         sm->id = index;
692         sm->first_time = false;
693         sm->serviceable = serviceable;
694         sm->sub_id = 0;
695
696         sm->prop = fgGetNode("/ai/submodels/subsubmodel", index, true);
697         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
698         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
699         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
700         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
701         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
702         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
703         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
704
705         string name = sm->name;
706         sm->prop->setStringValue("name", name.c_str());
707
708         string submodel = sm->submodel;
709         sm->prop->setStringValue("submodel-path", submodel.c_str());
710         // cout << " set submodel path AI" << submodel<< endl;
711
712         string force_path = sm->force_path;
713         sm->prop->setStringValue("force_path", force_path.c_str());
714         //cout << "set force_path  AI" << force_path << endl;
715
716         if (sm->contents_node != 0)
717             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
718
719         index++;
720         subsubmodels.push_back(sm);
721     }
722 }
723
724 void FGSubmodelMgr::loadSubmodels()
725 {
726     SG_LOG(SG_GENERAL, SG_DEBUG, "Submodels: Loading sub submodels");
727
728     _found_sub = false;
729
730     submodel_iterator = submodels.begin();
731
732     while (submodel_iterator != submodels.end()) {
733         string submodel  = (*submodel_iterator)->submodel;
734         if (!submodel.empty()) {
735             //int id = (*submodel_iterator)->id;
736             bool serviceable = true;
737             SG_LOG(SG_GENERAL, SG_DEBUG, "found path sub sub "
738                     << submodel
739                     << " index " << index
740                     << " name " << (*submodel_iterator)->name);
741
742             if ((*submodel_iterator)->sub_id == 0){
743                 (*submodel_iterator)->sub_id = index;
744                 _found_sub = true;
745                 setSubData(index, submodel, serviceable);
746             }
747         }
748
749         ++submodel_iterator;
750     } // end while
751
752     subsubmodel_iterator = subsubmodels.begin();
753
754     while (subsubmodel_iterator != subsubmodels.end()) {
755
756         submodels.push_back(*subsubmodel_iterator);
757         ++subsubmodel_iterator;
758     } // end while
759
760     subsubmodels.clear();
761
762     //submodel_iterator = submodels.begin();
763
764     //int subcount = 0;
765
766     //while (submodel_iterator != submodels.end()) {
767     //    int id = (*submodel_iterator)->id;
768     //    subcount++;
769
770     //    SG_LOG(SG_GENERAL, SG_ALERT,"after pushback "
771     //            << " parent id " << id
772     //            << " name " << (*submodel_iterator)->name
773     //            << " sub id " << (*submodel_iterator)->sub_id
774     //            << " subcount "<< subcount);
775
776     //    ++submodel_iterator;
777     //}
778 }
779
780 SGVec3d FGSubmodelMgr::getCartOffsetPos() const{
781
782     // convert geodetic positions to geocentered
783     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
784     // Transform to the right coordinate frame, configuration is done in
785     // the x-forward, y-right, z-up coordinates (feet), computation
786     // in the simulation usual body x-forward, y-right, z-down coordinates
787     // (meters) )
788
789     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
790         _y_offset * SG_FEET_TO_METER,
791         -_z_offset * SG_FEET_TO_METER);
792
793     // Transform the user position to the horizontal local coordinate system.
794     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
795
796     // and postrotate the orientation of the user model wrt the horizontal
797     // local frame
798     hlTrans *= SGQuatd::fromYawPitchRollDeg(
799        IC.azimuth,            
800        IC.elevation,
801        IC.roll);
802
803     // The offset converted to the usual body fixed coordinate system
804     // rotated to the earth-fixed coordinates axis
805     SGVec3d off = hlTrans.backTransform(_off);
806
807     // Add the position offset of the user model to get the geocentered position
808     SGVec3d offsetPos = cartuserPos + off;
809     return offsetPos;
810 }
811
812 void FGSubmodelMgr::setOffsetPos(){
813     // convert the offset geocentered position to geodetic
814     SGVec3d cartoffsetPos = getCartOffsetPos();
815
816     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
817
818     //cout << "OFFSET POS" << offsetpos.getElevationFt();
819
820 }
821
822 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
823 {
824 //    cout << "LISTENER: " << endl;
825
826     const char* _model_added = _model_added_node->getStringValue();
827
828     basic_string <char>::size_type indexCh2b;
829
830     string str2 = _model_added;
831     const char *cstr2b = "ballistic";
832     indexCh2b = str2.find( cstr2b, 0 );
833
834 //    cout << "model added - " << str2 <<" now do something "<< endl;
835
836     if (indexCh2b != string::npos ){        // we will ignore Ballistic Objects - there are potentially too many 
837         return;
838     } else {
839        
840         SGPropertyNode *a_node = fgGetNode(_model_added, true );
841         SGPropertyNode *sub_node = a_node->getChild("submodels", 0, true);
842         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
843
844         string path = path_node->getStringValue();
845
846         if (path.empty()){
847             // nothing to do - return
848             //cout << "subpath empty - return"  << endl << endl;
849             return;
850         } else {
851             //cout << "subpath found - loading"  << endl << endl;
852             SGPropertyNode_ptr ident_node = a_node->getChild("id", 0, true);
853             int id = ident_node->getIntValue();
854
855             setData(id, path, true);
856
857             _found_sub = true;
858
859             while (_found_sub)
860                 loadSubmodels();
861
862         }
863
864     }
865
866 }
867
868 void FGSubmodelMgr::setParentNode(int id) {
869
870     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
871
872     for (int i = ai->nChildren() - 1; i >= -1; i--) {
873         SGPropertyNode_ptr model;
874
875         if (i < 0) { // last iteration: selected model
876             model = _selected_ac;
877         } else {
878             model = ai->getChild(i);
879             string path = ai->getPath();
880             const string name = model->getStringValue("name");
881             int parent_id = model->getIntValue("id");
882             if (!model->nChildren()){
883                 continue;
884             }
885             if (parent_id == id) {
886                 _selected_ac = model;  // save selected model for last iteration
887                 break;
888             }
889
890         }
891         if (!model)
892             continue;
893
894     }// end for loop 
895
896     if (_selected_ac != 0){
897
898         //cout << " parent node found"<< endl;
899
900         const string name  = _selected_ac->getStringValue("name");
901         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
902         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
903         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
904         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
905         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
906         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
907         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
908         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
909         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
910         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
911
912         //cout << name << " IC.speed " << IC.speed << endl;
913
914     } else {
915         SG_LOG(SG_GENERAL, SG_ALERT, "AISubmodel: parent node not found ");
916     }
917
918 }
919 // end of submodel.cxx