]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
Merge branch 'next' of git://gitorious.org/fg/flightgear into next
[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->get_fg_root());
519     config.append(path);
520     SG_LOG(SG_GENERAL, SG_DEBUG, "setData: path " << path);
521     try {
522         SG_LOG(SG_GENERAL, SG_DEBUG,
523                 "Submodels: Trying to read AI submodels file: " << config.str());
524         readProperties(config.str(), &root);
525     } catch (const sg_exception &) {
526         SG_LOG(SG_GENERAL, SG_ALERT,
527                 "Submodels: Unable to read AI submodels file: " << config.str());
528         return;
529     }
530
531     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
532     vector<SGPropertyNode_ptr>::iterator it = children.begin();
533     vector<SGPropertyNode_ptr>::iterator end = children.end();
534
535     for (int i = 0; it != end; ++it, i++) {
536         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
537         submodel* sm = new submodel;
538         SGPropertyNode * entry_node = *it;
539         sm->name            = entry_node->getStringValue("name", "none_defined");
540         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
541         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
542         sm->repeat          = entry_node->getBoolValue("repeat", false);
543         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
544         sm->count           = entry_node->getIntValue("count", 1);
545         sm->slaved          = entry_node->getBoolValue("slaved", false);
546         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
547         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
548         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
549         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
550         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
551         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
552         sm->life            = entry_node->getDoubleValue("life", 900.0);
553         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
554         sm->wind            = entry_node->getBoolValue("wind", false);
555         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
556         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
557         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
558         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
559         sm->collision       = entry_node->getBoolValue("collision", false);
560         sm->expiry                      = entry_node->getBoolValue("expiry", false);
561         sm->impact          = entry_node->getBoolValue("impact", false);
562         sm->impact_report   = entry_node->getStringValue("impact-reports");
563         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
564         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
565         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
566         sm->submodel        = entry_node->getStringValue("submodel-path", "");
567         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
568         sm->ext_force       = entry_node->getBoolValue("external-force", false);
569         sm->force_path      = entry_node->getStringValue("force-path", "");
570         sm->random                      = entry_node->getBoolValue("random", false);
571         sm->randomness          = entry_node->getDoubleValue("randomness", 0.5);
572
573         if (sm->contents_node != 0)
574             sm->contents = sm->contents_node->getDoubleValue();
575
576         const char *trigger_path = entry_node->getStringValue("trigger", 0);
577         if (trigger_path) {
578             sm->trigger_node = fgGetNode(trigger_path, true);
579             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
580         } else {
581             sm->trigger_node = 0;
582         }
583
584         if (sm->speed_node != 0)
585             sm->speed = sm->speed_node->getDoubleValue();
586
587         sm->timer = sm->delay;
588         sm->id = id;
589         sm->first_time = false;
590         sm->serviceable = serviceable;
591         sm->sub_id = 0;
592
593         sm->prop = fgGetNode("/ai/submodels/submodel", index, true);
594         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
595         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
596         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
597         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
598         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
599         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
600         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
601         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
602         string name = sm->name;
603         sm->prop->setStringValue("name", name.c_str());
604
605         string submodel = sm->submodel;
606         sm->prop->setStringValue("submodel", submodel.c_str());
607
608         string force_path = sm->force_path;
609         sm->prop->setStringValue("force_path", force_path.c_str());
610         //cout << "set force_path Sub " << force_path << endl;
611
612         if (sm->contents_node != 0)
613             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
614
615         index++;
616         submodels.push_back(sm);
617     }
618 }
619
620 void FGSubmodelMgr::setSubData(int id, string& path, bool serviceable)
621 {
622     SGPropertyNode root;
623
624     SGPath config(globals->get_fg_root());
625     config.append(path);
626     SG_LOG(SG_GENERAL, SG_DEBUG, "setSubData: path " << path);
627
628     try {
629         SG_LOG(SG_GENERAL, SG_DEBUG,
630                 "Submodels: Trying to read AI submodels file: " << config.str());
631         readProperties(config.str(), &root);
632
633     } catch (const sg_exception &) {
634         SG_LOG(SG_GENERAL, SG_ALERT,
635                 "Submodels: Unable to read AI submodels file: " << config.str());
636         return;
637     }
638
639     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
640     vector<SGPropertyNode_ptr>::iterator it = children.begin();
641     vector<SGPropertyNode_ptr>::iterator end = children.end();
642
643     for (int i = 0; it != end; ++it, i++) {
644         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
645         submodel* sm = new submodel;
646         SGPropertyNode * entry_node = *it;
647         sm->name            = entry_node->getStringValue("name", "none_defined");
648         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
649         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
650         sm->repeat          = entry_node->getBoolValue("repeat", false);
651         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
652         sm->count           = entry_node->getIntValue("count", 1);
653         sm->slaved          = entry_node->getBoolValue("slaved", false);
654         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
655         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
656         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
657         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
658         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
659         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
660         sm->life            = entry_node->getDoubleValue("life", 900.0);
661         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
662         sm->wind            = entry_node->getBoolValue("wind", false);
663         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
664         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
665         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
666         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
667         sm->collision       = entry_node->getBoolValue("collision", false);
668         sm->expiry          = entry_node->getBoolValue("expiry", false);
669         sm->impact          = entry_node->getBoolValue("impact", false);
670         sm->impact_report   = entry_node->getStringValue("impact-reports");
671         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
672         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
673         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
674         sm->submodel        = entry_node->getStringValue("submodel-path", "");
675         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
676         sm->ext_force       = entry_node->getBoolValue("external-force", false);
677         sm->force_path      = entry_node->getStringValue("force-path", "");
678         sm->random          = entry_node->getBoolValue("random", false);
679         sm->randomness      = entry_node->getDoubleValue("randomness", 0.5);
680
681         if (sm->contents_node != 0)
682             sm->contents = sm->contents_node->getDoubleValue();
683
684         const char *trigger_path = entry_node->getStringValue("trigger", 0);
685         if (trigger_path) {
686             sm->trigger_node = fgGetNode(trigger_path, true);
687             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
688         } else {
689             sm->trigger_node = 0;
690         }
691
692         if (sm->speed_node != 0)
693             sm->speed = sm->speed_node->getDoubleValue();
694
695         sm->timer = sm->delay;
696         sm->id = index;
697         sm->first_time = false;
698         sm->serviceable = serviceable;
699         sm->sub_id = 0;
700
701         sm->prop = fgGetNode("/ai/submodels/subsubmodel", index, true);
702         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
703         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
704         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
705         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
706         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
707         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
708         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
709
710         string name = sm->name;
711         sm->prop->setStringValue("name", name.c_str());
712
713         string submodel = sm->submodel;
714         sm->prop->setStringValue("submodel-path", submodel.c_str());
715         // cout << " set submodel path AI" << submodel<< endl;
716
717         string force_path = sm->force_path;
718         sm->prop->setStringValue("force_path", force_path.c_str());
719         //cout << "set force_path  AI" << force_path << endl;
720
721         if (sm->contents_node != 0)
722             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
723
724         index++;
725         subsubmodels.push_back(sm);
726     }
727 }
728
729 void FGSubmodelMgr::loadSubmodels()
730 {
731     SG_LOG(SG_GENERAL, SG_DEBUG, "Submodels: Loading sub submodels");
732
733     _found_sub = false;
734
735     submodel_iterator = submodels.begin();
736
737     while (submodel_iterator != submodels.end()) {
738         string submodel  = (*submodel_iterator)->submodel;
739         if (!submodel.empty()) {
740             //int id = (*submodel_iterator)->id;
741             bool serviceable = true;
742             SG_LOG(SG_GENERAL, SG_DEBUG, "found path sub sub "
743                     << submodel
744                     << " index " << index
745                     << " name " << (*submodel_iterator)->name);
746
747             if ((*submodel_iterator)->sub_id == 0){
748                 (*submodel_iterator)->sub_id = index;
749                 _found_sub = true;
750                 setSubData(index, submodel, serviceable);
751             }
752         }
753
754         ++submodel_iterator;
755     } // end while
756
757     subsubmodel_iterator = subsubmodels.begin();
758
759     while (subsubmodel_iterator != subsubmodels.end()) {
760
761         submodels.push_back(*subsubmodel_iterator);
762         ++subsubmodel_iterator;
763     } // end while
764
765     subsubmodels.clear();
766
767     //submodel_iterator = submodels.begin();
768
769     //int subcount = 0;
770
771     //while (submodel_iterator != submodels.end()) {
772     //    int id = (*submodel_iterator)->id;
773     //    subcount++;
774
775     //    SG_LOG(SG_GENERAL, SG_ALERT,"after pushback "
776     //            << " parent id " << id
777     //            << " name " << (*submodel_iterator)->name
778     //            << " sub id " << (*submodel_iterator)->sub_id
779     //            << " subcount "<< subcount);
780
781     //    ++submodel_iterator;
782     //}
783 }
784
785 SGVec3d FGSubmodelMgr::getCartOffsetPos() const{
786
787     // convert geodetic positions to geocentered
788     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
789     // Transform to the right coordinate frame, configuration is done in
790     // the x-forward, y-right, z-up coordinates (feet), computation
791     // in the simulation usual body x-forward, y-right, z-down coordinates
792     // (meters) )
793
794     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
795         _y_offset * SG_FEET_TO_METER,
796         -_z_offset * SG_FEET_TO_METER);
797
798     // Transform the user position to the horizontal local coordinate system.
799     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
800
801     // and postrotate the orientation of the user model wrt the horizontal
802     // local frame
803     hlTrans *= SGQuatd::fromYawPitchRollDeg(
804        IC.azimuth,            
805        IC.elevation,
806        IC.roll);
807
808     // The offset converted to the usual body fixed coordinate system
809     // rotated to the earth-fixed coordinates axis
810     SGVec3d off = hlTrans.backTransform(_off);
811
812     // Add the position offset of the user model to get the geocentered position
813     SGVec3d offsetPos = cartuserPos + off;
814     return offsetPos;
815 }
816
817 void FGSubmodelMgr::setOffsetPos(){
818     // convert the offset geocentered position to geodetic
819     SGVec3d cartoffsetPos = getCartOffsetPos();
820
821     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
822
823     //cout << "OFFSET POS" << offsetpos.getElevationFt();
824
825 }
826
827 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
828 {
829 //    cout << "LISTENER: " << endl;
830
831     const char* _model_added = _model_added_node->getStringValue();
832
833     basic_string <char>::size_type indexCh2b;
834
835     string str2 = _model_added;
836     const char *cstr2b = "ballistic";
837     indexCh2b = str2.find( cstr2b, 0 );
838
839 //    cout << "model added - " << str2 <<" now do something "<< endl;
840
841     if (indexCh2b != string::npos ){        // we will ignore Ballistic Objects - there are potentially too many 
842         return;
843     } else {
844        
845         SGPropertyNode *a_node = fgGetNode(_model_added, true );
846         SGPropertyNode *sub_node = a_node->getChild("submodels", 0, true);
847         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
848
849         string path = path_node->getStringValue();
850
851         if (path.empty()){
852             // nothing to do - return
853             //cout << "subpath empty - return"  << endl << endl;
854             return;
855         } else {
856             //cout << "subpath found - loading"  << endl << endl;
857             SGPropertyNode_ptr ident_node = a_node->getChild("id", 0, true);
858             int id = ident_node->getIntValue();
859
860             setData(id, path, true);
861
862             _found_sub = true;
863
864             while (_found_sub)
865                 loadSubmodels();
866
867         }
868
869     }
870
871 }
872
873 void FGSubmodelMgr::setParentNode(int id) {
874
875     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
876
877     for (int i = ai->nChildren() - 1; i >= -1; i--) {
878         SGPropertyNode_ptr model;
879
880         if (i < 0) { // last iteration: selected model
881             model = _selected_ac;
882         } else {
883             model = ai->getChild(i);
884             string path = ai->getPath();
885             const string name = model->getStringValue("name");
886             int parent_id = model->getIntValue("id");
887             if (!model->nChildren()){
888                 continue;
889             }
890             if (parent_id == id) {
891                 _selected_ac = model;  // save selected model for last iteration
892                 break;
893             }
894
895         }
896         if (!model)
897             continue;
898
899     }// end for loop 
900
901     if (_selected_ac != 0){
902
903         //cout << " parent node found"<< endl;
904
905         const string name  = _selected_ac->getStringValue("name");
906         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
907         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
908         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
909         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
910         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
911         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
912         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
913         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
914         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
915         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
916
917         //cout << name << " IC.speed " << IC.speed << endl;
918
919     } else {
920         SG_LOG(SG_GENERAL, SG_ALERT, "AISubmodel: parent node not found ");
921     }
922
923 }
924 // end of submodel.cxx