]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/submodel.cxx
comment out unused variables and function and properly initialize variables
[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 FGAIManager* FGSubmodelMgr::aiManager()
47 {
48    return (FGAIManager*)globals->get_subsystem("ai-model");
49 }
50
51 void FGSubmodelMgr::init()
52 {
53     index = 0;
54
55     _serviceable_node = fgGetNode("/sim/submodels/serviceable", true);
56     _serviceable_node->setBoolValue(true);
57
58     _user_lat_node = fgGetNode("/position/latitude-deg", true);
59     _user_lon_node = fgGetNode("/position/longitude-deg", true);
60     _user_alt_node = fgGetNode("/position/altitude-ft", true);
61
62     _user_heading_node = fgGetNode("/orientation/heading-deg", true);
63     _user_pitch_node =   fgGetNode("/orientation/pitch-deg", true);
64     _user_roll_node =    fgGetNode("/orientation/roll-deg", true);
65     _user_yaw_node =     fgGetNode("/orientation/yaw-deg", true);
66     _user_alpha_node =   fgGetNode("/orientation/alpha-deg", true);
67
68     _user_speed_node = fgGetNode("/velocities/uBody-fps", true);
69
70     _user_wind_from_east_node  = fgGetNode("/environment/wind-from-east-fps", true);
71     _user_wind_from_north_node = fgGetNode("/environment/wind-from-north-fps", true);
72
73     _user_speed_down_fps_node   = fgGetNode("/velocities/speed-down-fps", true);
74     _user_speed_east_fps_node   = fgGetNode("/velocities/speed-east-fps", true);
75     _user_speed_north_fps_node  = fgGetNode("/velocities/speed-north-fps", true);
76
77     _contrail_altitude_node = fgGetNode("/environment/params/contrail-altitude", true);
78     contrail_altitude       = _contrail_altitude_node->getDoubleValue();
79     _contrail_trigger       = fgGetNode("ai/submodels/contrails", true);
80     _contrail_trigger->setBoolValue(false);
81
82     load();
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     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
123     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin(),
124       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_AI, 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_AI, 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_AI, 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_AI, 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_AI, 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->setParentNodes(_selected_ac);
304     ballist->setContentsNode(sm->contents_node);
305     ballist->setWeight(sm->weight);
306     
307     aiManager()->attach(ballist);
308
309     if (sm->count > 0)
310         sm->count--;
311     return true;
312 }
313
314 void FGSubmodelMgr::load()
315 {
316     SGPropertyNode *path = fgGetNode("/sim/submodels/path");
317
318     if (path) {
319         const int id = 0;
320         string Path = path->getStringValue();
321         bool Seviceable =_serviceable_node->getBoolValue();
322         setData(id, Path, Seviceable);
323     }
324 }
325
326 void FGSubmodelMgr::transform(submodel *sm)
327 {
328     // set initial conditions
329     if (sm->contents_node != 0 && !sm->slaved) {
330         // get the weight of the contents (lbs) and convert to mass (slugs)
331         sm->contents = sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue();
332         //cout << "transform: contents " << sm->contents << endl;
333         IC.mass = (sm->weight + sm->contents) * lbs_to_slugs;
334         //cout << "mass inc contents"  << IC.mass << endl;
335
336         // set contents to 0 in the parent
337         sm->contents_node->getChild("level-gal_us",0,1)->setDoubleValue(0);
338         /*cout << "contents " << sm->contents_node->getChild("level-gal_us")->getDoubleValue()
339         << " " << sm->contents_node->getChild("level-lbs",0,1)->getDoubleValue()
340         << endl;*/
341     } else
342         IC.mass = sm->weight * lbs_to_slugs;
343
344     int id = sm->id;
345     //int sub_id = sm->sub_id;
346     string name = sm->name;
347
348
349     if (sm->speed_node != 0)
350         sm->speed = sm->speed_node->getDoubleValue();
351
352
353     //cout << " name " << name << " id " << id << " sub id" << sub_id << endl;
354
355     // set the Initial Conditions for the types of submodel parent 
356
357     if (_impact || _hit || _expiry) {
358         // set the data for a submodel tied to a submodel
359
360         _count++;
361
362         IC.lat             = _parent_lat;
363         IC.lon             = _parent_lon;
364         IC.alt             = _parent_elev;
365         IC.roll            = _parent_roll;    // rotation about x axis
366         IC.elevation       = _parent_pitch;   // rotation about y axis
367         IC.azimuth         = _parent_hdg;     // rotation about z axis
368         IC.speed           = _parent_speed;
369         IC.speed_down_fps  = 0;
370         IC.speed_east_fps  = 0;
371         IC.speed_north_fps = 0;
372
373     } else if (id == 0) {
374         //set the data for a submodel tied to the main model
375
376         IC.lat             = _user_lat_node->getDoubleValue();
377         IC.lon             = _user_lon_node->getDoubleValue();
378         IC.alt             = _user_alt_node->getDoubleValue();
379         IC.roll            = _user_roll_node->getDoubleValue();    // rotation about x axis
380         IC.elevation       = _user_pitch_node->getDoubleValue();   // rotation about y axis
381         IC.azimuth         = _user_heading_node->getDoubleValue(); // rotation about z axis
382         IC.speed           = _user_speed_node->getDoubleValue();
383         IC.speed_down_fps  = _user_speed_down_fps_node->getDoubleValue();
384         IC.speed_east_fps  = _user_speed_east_fps_node->getDoubleValue();
385         IC.speed_north_fps = _user_speed_north_fps_node->getDoubleValue();
386
387     } else {
388         // set the data for a submodel tied to an AI Object
389         //cout << " set the data for a submodel tied to an AI Object " << id << endl;
390         setParentNode(id);
391     }
392
393     //cout << "Submodel: setting IC "<< name << endl;
394     //cout << "heading " << IC.azimuth << endl ;
395     //cout << "speed down " << IC.speed_down_fps << endl ;
396     //cout << "speed east " << IC.speed_east_fps << endl ;
397     //cout << "speed north " << IC.speed_north_fps << endl ;
398     //cout << "parent speed fps in " << IC.speed << "sm speed in " << sm->speed << endl ;
399     //cout << "lat " << IC.lat;
400     //cout << "alt " << IC.alt <<  endl ;
401
402
403     // Set the Initial Conditions that are common to all types of parent
404     IC.wind_from_east =  _user_wind_from_east_node->getDoubleValue();
405     IC.wind_from_north = _user_wind_from_north_node->getDoubleValue();
406
407 //cout << "wind e " << IC.wind_from_east << " n " << IC.wind_from_north << endl;
408
409     userpos.setLatitudeDeg(IC.lat);
410     userpos.setLongitudeDeg(IC.lon);
411     userpos.setElevationFt(IC.alt);
412
413     _x_offset = sm->x_offset;
414     _y_offset = sm->y_offset;
415     _z_offset = sm->z_offset;
416
417     setOffsetPos();
418
419     //IC.elevation += sm->pitch_offset;
420     //IC.azimuth   += sm->yaw_offset ;
421
422     // pre-process the trig functions
423     cosRx = cos(-IC.roll * SG_DEGREES_TO_RADIANS);
424     sinRx = sin(-IC.roll * SG_DEGREES_TO_RADIANS);
425     cosRy = cos(-IC.elevation * SG_DEGREES_TO_RADIANS);
426     sinRy = sin(-IC.elevation * SG_DEGREES_TO_RADIANS);
427     cosRz = cos(IC.azimuth * SG_DEGREES_TO_RADIANS);
428     sinRz = sin(IC.azimuth * SG_DEGREES_TO_RADIANS);
429
430
431     // Get submodel initial velocity vector angles in XZ and XY planes.
432     // This vector should be added to aircraft's vector.
433     IC.elevation += (sm->yaw_offset * sinRx) + (sm->pitch_offset * cosRx);
434     IC.azimuth   += (sm->yaw_offset * cosRx) - (sm->pitch_offset * sinRx);
435
436     // calculate the total speed north
437     IC.total_speed_north = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
438             * cos(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_north_fps;
439
440     // calculate the total speed east
441     IC.total_speed_east = sm->speed * cos(IC.elevation * SG_DEGREES_TO_RADIANS)
442             * sin(IC.azimuth * SG_DEGREES_TO_RADIANS) + IC.speed_east_fps;
443
444     // calculate the total speed down
445     IC.total_speed_down = sm->speed * -sin(IC.elevation * SG_DEGREES_TO_RADIANS)
446             + IC.speed_down_fps;
447
448     // re-calculate speed, elevation and azimuth
449     IC.speed = sqrt(IC.total_speed_north * IC.total_speed_north
450             + IC.total_speed_east * IC.total_speed_east
451             + IC.total_speed_down * IC.total_speed_down);
452
453     // if speeds are low this calculation can become unreliable
454     if (IC.speed > 1) {
455         IC.azimuth = atan2(IC.total_speed_east, IC.total_speed_north) * SG_RADIANS_TO_DEGREES;
456         //        cout << "azimuth1 " << IC.azimuth<<endl;
457
458         // rationalise the output
459         if (IC.azimuth < 0)
460             IC.azimuth += 360;
461         else if (IC.azimuth >= 360)
462             IC.azimuth -= 360;
463         // cout << "azimuth2 " << IC.azimuth<<endl;
464
465         IC.elevation = -atan(IC.total_speed_down / sqrt(IC.total_speed_north
466             * IC.total_speed_north + IC.total_speed_east * IC.total_speed_east))
467             * SG_RADIANS_TO_DEGREES;
468     }
469     //cout << "IC.speed " << IC.speed / SG_KT_TO_FPS << endl;
470 }
471
472 void FGSubmodelMgr::updatelat(double lat)
473 {
474     ft_per_deg_latitude = 366468.96 - 3717.12 * cos(lat / SG_RADIANS_TO_DEGREES);
475     ft_per_deg_longitude = 365228.16 * cos(lat / SG_RADIANS_TO_DEGREES);
476 }
477
478 void FGSubmodelMgr::loadAI()
479 {
480     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading AI submodels ");
481
482     FGAIManager::ai_list_type sm_list(aiManager()->get_ai_list());
483
484     if (sm_list.empty()) {
485         SG_LOG(SG_AI, SG_ALERT, "Submodels: Unable to read AI submodel list");
486         return;
487     }
488
489     FGAIManager::ai_list_iterator sm_list_itr = sm_list.begin(),
490       end = sm_list.end();
491
492     while (sm_list_itr != end) {
493         string path = (*sm_list_itr)->_getSMPath();
494
495         if (path.empty()) {
496             ++sm_list_itr;
497             continue;
498         }
499
500         int id = (*sm_list_itr)->getID();
501         string type = (*sm_list_itr)->getTypeString();
502         bool serviceable = (*sm_list_itr)->_getServiceable();
503
504         //cout << "loadAI: type " << type << " path "<< path << " serviceable " << serviceable << endl;
505
506         setData(id, path, serviceable);
507         ++sm_list_itr;
508     }
509 }
510
511
512
513 void FGSubmodelMgr::setData(int id, string& path, bool serviceable)
514 {
515     SGPropertyNode root;
516
517     SGPath config = globals->resolve_aircraft_path(path);
518     try {
519         SG_LOG(SG_AI, SG_DEBUG,
520                 "Submodels: Trying to read AI submodels file: " << config.str());
521         readProperties(config.str(), &root);
522     } catch (const sg_exception &) {
523         SG_LOG(SG_AI, SG_ALERT,
524                 "Submodels: Unable to read AI submodels file: " << config.str());
525         return;
526     }
527
528     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
529     vector<SGPropertyNode_ptr>::iterator it = children.begin();
530     vector<SGPropertyNode_ptr>::iterator end = children.end();
531
532     for (int i = 0; it != end; ++it, i++) {
533         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
534         submodel* sm = new submodel;
535         SGPropertyNode * entry_node = *it;
536         sm->name            = entry_node->getStringValue("name", "none_defined");
537         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
538         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
539         sm->repeat          = entry_node->getBoolValue("repeat", false);
540         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
541         sm->count           = entry_node->getIntValue("count", 1);
542         sm->slaved          = entry_node->getBoolValue("slaved", false);
543         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
544         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
545         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
546         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
547         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
548         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
549         sm->life            = entry_node->getDoubleValue("life", 900.0);
550         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
551         sm->wind            = entry_node->getBoolValue("wind", false);
552         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
553         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
554         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
555         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
556         sm->collision       = entry_node->getBoolValue("collision", false);
557         sm->expiry                      = entry_node->getBoolValue("expiry", false);
558         sm->impact          = entry_node->getBoolValue("impact", false);
559         sm->impact_report   = entry_node->getStringValue("impact-reports");
560         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
561         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
562         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
563         sm->submodel        = entry_node->getStringValue("submodel-path", "");
564         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
565         sm->ext_force       = entry_node->getBoolValue("external-force", false);
566         sm->force_path      = entry_node->getStringValue("force-path", "");
567         sm->random                      = entry_node->getBoolValue("random", false);
568         sm->randomness          = entry_node->getDoubleValue("randomness", 0.5);
569
570         if (sm->contents_node != 0)
571             sm->contents = sm->contents_node->getDoubleValue();
572
573         const char *trigger_path = entry_node->getStringValue("trigger", 0);
574         if (trigger_path) {
575             sm->trigger_node = fgGetNode(trigger_path, true);
576             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
577         } else {
578             sm->trigger_node = 0;
579         }
580
581         if (sm->speed_node != 0)
582             sm->speed = sm->speed_node->getDoubleValue();
583
584         sm->timer = sm->delay;
585         sm->id = id;
586         sm->first_time = false;
587         sm->serviceable = serviceable;
588         sm->sub_id = 0;
589
590         sm->prop = fgGetNode("/ai/submodels/submodel", index, true);
591         sm->prop->tie("delay", SGRawValuePointer<double>(&(sm->delay)));
592         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
593         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
594         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
595         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
596         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
597         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
598         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
599         string name = sm->name;
600         sm->prop->setStringValue("name", name.c_str());
601
602         string submodel = sm->submodel;
603         sm->prop->setStringValue("submodel", submodel.c_str());
604
605         string force_path = sm->force_path;
606         sm->prop->setStringValue("force_path", force_path.c_str());
607         //cout << "set force_path Sub " << force_path << endl;
608
609         if (sm->contents_node != 0)
610             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
611
612         index++;
613         submodels.push_back(sm);
614     }
615 }
616
617 void FGSubmodelMgr::setSubData(int id, string& path, bool serviceable)
618 {
619     SGPropertyNode root;
620     SGPath config = globals->resolve_aircraft_path(path);
621
622     try {
623         SG_LOG(SG_AI, SG_DEBUG,
624                 "Submodels: Trying to read AI submodels file: " << config.str());
625         readProperties(config.str(), &root);
626
627     } catch (const sg_exception &) {
628         SG_LOG(SG_AI, SG_ALERT,
629                 "Submodels: Unable to read AI submodels file: " << config.str());
630         return;
631     }
632
633     vector<SGPropertyNode_ptr> children = root.getChildren("submodel");
634     vector<SGPropertyNode_ptr>::iterator it = children.begin();
635     vector<SGPropertyNode_ptr>::iterator end = children.end();
636
637     for (int i = 0; it != end; ++it, i++) {
638         //cout << "Reading AI submodel " << (*it)->getPath() << endl;
639         submodel* sm = new submodel;
640         SGPropertyNode * entry_node = *it;
641         sm->name            = entry_node->getStringValue("name", "none_defined");
642         sm->model           = entry_node->getStringValue("model", "Models/Geometry/rocket.ac");
643         sm->speed           = entry_node->getDoubleValue("speed", 2329.4);
644         sm->repeat          = entry_node->getBoolValue("repeat", false);
645         sm->delay           = entry_node->getDoubleValue("delay", 0.25);
646         sm->count           = entry_node->getIntValue("count", 1);
647         sm->slaved          = entry_node->getBoolValue("slaved", false);
648         sm->x_offset        = entry_node->getDoubleValue("x-offset", 0.0);
649         sm->y_offset        = entry_node->getDoubleValue("y-offset", 0.0);
650         sm->z_offset        = entry_node->getDoubleValue("z-offset", 0.0);
651         sm->yaw_offset      = entry_node->getDoubleValue("yaw-offset", 0.0);
652         sm->pitch_offset    = entry_node->getDoubleValue("pitch-offset", 0.0);
653         sm->drag_area       = entry_node->getDoubleValue("eda", 0.034);
654         sm->life            = entry_node->getDoubleValue("life", 900.0);
655         sm->buoyancy        = entry_node->getDoubleValue("buoyancy", 0);
656         sm->wind            = entry_node->getBoolValue("wind", false);
657         sm->cd              = entry_node->getDoubleValue("cd", 0.193);
658         sm->weight          = entry_node->getDoubleValue("weight", 0.25);
659         sm->aero_stabilised = entry_node->getBoolValue("aero-stabilised", true);
660         sm->no_roll         = entry_node->getBoolValue("no-roll", false);
661         sm->collision       = entry_node->getBoolValue("collision", false);
662         sm->expiry          = entry_node->getBoolValue("expiry", false);
663         sm->impact          = entry_node->getBoolValue("impact", false);
664         sm->impact_report   = entry_node->getStringValue("impact-reports");
665         sm->fuse_range      = entry_node->getDoubleValue("fuse-range", 0.0);
666         sm->contents_node   = fgGetNode(entry_node->getStringValue("contents", "none"), false);
667         sm->speed_node      = fgGetNode(entry_node->getStringValue("speed-prop", "none"), false);
668         sm->submodel        = entry_node->getStringValue("submodel-path", "");
669         sm->force_stabilised= entry_node->getBoolValue("force-stabilised", false);
670         sm->ext_force       = entry_node->getBoolValue("external-force", false);
671         sm->force_path      = entry_node->getStringValue("force-path", "");
672         sm->random          = entry_node->getBoolValue("random", false);
673         sm->randomness      = entry_node->getDoubleValue("randomness", 0.5);
674
675         if (sm->contents_node != 0)
676             sm->contents = sm->contents_node->getDoubleValue();
677
678         const char *trigger_path = entry_node->getStringValue("trigger", 0);
679         if (trigger_path) {
680             sm->trigger_node = fgGetNode(trigger_path, true);
681             sm->trigger_node->setBoolValue(sm->trigger_node->getBoolValue());
682         } else {
683             sm->trigger_node = 0;
684         }
685
686         if (sm->speed_node != 0)
687             sm->speed = sm->speed_node->getDoubleValue();
688
689         sm->timer = sm->delay;
690         sm->id = index;
691         sm->first_time = false;
692         sm->serviceable = serviceable;
693         sm->sub_id = 0;
694
695         sm->prop = fgGetNode("/ai/submodels/subsubmodel", index, true);
696         sm->prop->tie("count", SGRawValuePointer<int>(&(sm->count)));
697         sm->prop->tie("repeat", SGRawValuePointer<bool>(&(sm->repeat)));
698         sm->prop->tie("id", SGRawValuePointer<int>(&(sm->id)));
699         sm->prop->tie("sub-id", SGRawValuePointer<int>(&(sm->sub_id)));
700         sm->prop->tie("serviceable", SGRawValuePointer<bool>(&(sm->serviceable)));
701         sm->prop->tie("random", SGRawValuePointer<bool>(&(sm->random)));
702         sm->prop->tie("slaved", SGRawValuePointer<bool>(&(sm->slaved)));
703
704         string name = sm->name;
705         sm->prop->setStringValue("name", name.c_str());
706
707         string submodel = sm->submodel;
708         sm->prop->setStringValue("submodel-path", submodel.c_str());
709         // cout << " set submodel path AI" << submodel<< endl;
710
711         string force_path = sm->force_path;
712         sm->prop->setStringValue("force_path", force_path.c_str());
713         //cout << "set force_path  AI" << force_path << endl;
714
715         if (sm->contents_node != 0)
716             sm->prop->tie("contents-lbs", SGRawValuePointer<double>(&(sm->contents)));
717
718         index++;
719         subsubmodels.push_back(sm);
720     }
721 }
722
723 void FGSubmodelMgr::loadSubmodels()
724 {
725     SG_LOG(SG_AI, SG_DEBUG, "Submodels: Loading sub submodels");
726
727     _found_sub = false;
728
729     submodel_iterator = submodels.begin();
730
731     while (submodel_iterator != submodels.end()) {
732         string submodel  = (*submodel_iterator)->submodel;
733         if (!submodel.empty()) {
734             //int id = (*submodel_iterator)->id;
735             bool serviceable = true;
736             SG_LOG(SG_AI, SG_DEBUG, "found path sub sub "
737                     << submodel
738                     << " index " << index
739                     << " name " << (*submodel_iterator)->name);
740
741             if ((*submodel_iterator)->sub_id == 0){
742                 (*submodel_iterator)->sub_id = index;
743                 _found_sub = true;
744                 setSubData(index, submodel, serviceable);
745             }
746         }
747
748         ++submodel_iterator;
749     } // end while
750
751     subsubmodel_iterator = subsubmodels.begin();
752
753     while (subsubmodel_iterator != subsubmodels.end()) {
754
755         submodels.push_back(*subsubmodel_iterator);
756         ++subsubmodel_iterator;
757     } // end while
758
759     subsubmodels.clear();
760
761     //submodel_iterator = submodels.begin();
762
763     //int subcount = 0;
764
765     //while (submodel_iterator != submodels.end()) {
766     //    int id = (*submodel_iterator)->id;
767     //    subcount++;
768
769     //    SG_LOG(SG_AI, SG_ALERT,"after pushback "
770     //            << " parent id " << id
771     //            << " name " << (*submodel_iterator)->name
772     //            << " sub id " << (*submodel_iterator)->sub_id
773     //            << " subcount "<< subcount);
774
775     //    ++submodel_iterator;
776     //}
777 }
778
779 SGVec3d FGSubmodelMgr::getCartOffsetPos() const{
780
781     // convert geodetic positions to geocentered
782     SGVec3d cartuserPos = SGVec3d::fromGeod(userpos);
783     // Transform to the right coordinate frame, configuration is done in
784     // the x-forward, y-right, z-up coordinates (feet), computation
785     // in the simulation usual body x-forward, y-right, z-down coordinates
786     // (meters) )
787
788     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
789         _y_offset * SG_FEET_TO_METER,
790         -_z_offset * SG_FEET_TO_METER);
791
792     // Transform the user position to the horizontal local coordinate system.
793     SGQuatd hlTrans = SGQuatd::fromLonLat(userpos);
794
795     // and postrotate the orientation of the user model wrt the horizontal
796     // local frame
797     hlTrans *= SGQuatd::fromYawPitchRollDeg(
798        IC.azimuth,            
799        IC.elevation,
800        IC.roll);
801
802     // The offset converted to the usual body fixed coordinate system
803     // rotated to the earth-fixed coordinates axis
804     SGVec3d off = hlTrans.backTransform(_off);
805
806     // Add the position offset of the user model to get the geocentered position
807     SGVec3d offsetPos = cartuserPos + off;
808     return offsetPos;
809 }
810
811 void FGSubmodelMgr::setOffsetPos(){
812     // convert the offset geocentered position to geodetic
813     SGVec3d cartoffsetPos = getCartOffsetPos();
814
815     SGGeodesy::SGCartToGeod(cartoffsetPos, offsetpos);
816
817     //cout << "OFFSET POS" << offsetpos.getElevationFt();
818
819 }
820
821 void FGSubmodelMgr::valueChanged(SGPropertyNode *prop)
822 {
823     return; // this isn't working atm
824
825     const char* _model_added = _model_added_node->getStringValue();
826
827     basic_string <char>::size_type indexCh2b;
828
829     string str2 = _model_added;
830     const char *cstr2b = "multiplayer";
831     indexCh2b = str2.find( cstr2b, 0 );
832
833     if (indexCh2b != string::npos ){        // we will ignore Ballistic Objects - there are potentially too many 
834
835         //cout << "Submodels: model added - " << str2 <<" read path "<< endl;
836         //return;
837         SGPropertyNode *a_node = fgGetNode(_model_added, true);
838         SGPropertyNode *sub_node = a_node->getChild("sim", 0, true);
839         SGPropertyNode_ptr path_node = sub_node->getChild("path", 0, true);
840         SGPropertyNode_ptr callsign_node = a_node->getChild("callsign", 0, true);
841
842         string callsign = callsign_node->getStringValue();
843
844         //cout << "Submodels: model added - " << callsign <<" read callsign "<< endl;
845             return;
846
847         } else {
848             cout << "model added - " << str2 <<" returning "<< endl;
849         return;
850         }
851
852 }
853
854 void FGSubmodelMgr::setParentNode(int id) {
855
856     const SGPropertyNode_ptr ai = fgGetNode("/ai/models", true);
857
858     for (int i = ai->nChildren() - 1; i >= -1; i--) {
859         SGPropertyNode_ptr model;
860
861         if (i < 0) { // last iteration: selected model
862             model = _selected_ac;
863         } else {
864             model = ai->getChild(i);
865             string path = ai->getPath();
866             const string name = model->getStringValue("name");
867             int parent_id = model->getIntValue("id");
868             if (!model->nChildren()){
869                 continue;
870             }
871             if (parent_id == id) {
872                 _selected_ac = model;  // save selected model for last iteration
873                 break;
874             }
875
876         }
877         if (!model)
878             continue;
879
880     }// end for loop 
881
882     if (_selected_ac != 0){
883
884         //cout << " parent node found"<< endl;
885
886         const string name  = _selected_ac->getStringValue("name");
887         IC.lat             = _selected_ac->getDoubleValue("position/latitude-deg");
888         IC.lon             = _selected_ac->getDoubleValue("position/longitude-deg");
889         IC.alt             = _selected_ac->getDoubleValue("position/altitude-ft");
890         IC.roll            = _selected_ac->getDoubleValue("orientation/roll-deg");
891         IC.elevation       = _selected_ac->getDoubleValue("orientation/pitch-deg");
892         IC.azimuth         = _selected_ac->getDoubleValue("orientation/true-heading-deg");
893         IC.speed           = _selected_ac->getDoubleValue("velocities/true-airspeed-kt") * SG_KT_TO_FPS;
894         IC.speed_down_fps  = -_selected_ac->getDoubleValue("velocities/vertical-speed-fps");
895         IC.speed_east_fps  = _selected_ac->getDoubleValue("velocities/speed-east-fps");
896         IC.speed_north_fps = _selected_ac->getDoubleValue("velocities/speed-north-fps");
897
898         //cout << name << " IC.speed " << IC.speed << endl;
899
900     } else {
901         SG_LOG(SG_AI, SG_ALERT, "AISubmodel: parent node not found ");
902     }
903
904 }
905 // end of submodel.cxx