]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBallistic.cxx
Interim windows build fix
[flightgear.git] / src / AIModel / AIBallistic.cxx
1 // FGAIBallistic - FGAIBase-derived class creates a ballistic object
2 //
3 // Written by David Culp, started November 2003.
4 // - davidculp2@comcast.net
5 //
6 // With major additions by Mathias Froehlich & Vivian Meazza 2004-2008
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include <simgear/math/sg_random.h>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/scene/model/modellib.hxx>
29
30 #include <Scenery/scenery.hxx>
31
32 #include "AIBallistic.hxx"
33
34 #include <Main/util.hxx>
35 #include <Environment/gravity.hxx>
36 #include <Main/fg_props.hxx>
37
38 using namespace simgear;
39 using std::string;
40
41 const double FGAIBallistic::slugs_to_kgs = 14.5939029372;
42 const double FGAIBallistic::slugs_to_lbs = 32.1740485564;
43
44 FGAIBallistic::FGAIBallistic(object_type ot) :
45 FGAIBase(ot, false),
46 _height(0.0),
47 _speed(0),
48 _ht_agl_ft(0.0),
49 _azimuth(0.0),
50 _elevation(0.0),
51 _rotation(0.0),
52 hs(0),
53 _elapsed_time(0),
54 _az_random_error(0.0),
55 _el_random_error(0.0),
56 _aero_stabilised(false),
57 _drag_area(0.007),
58 _cd(0.029),
59 _init_cd(0.029),
60 _cd_randomness(0.0),
61 _buoyancy(0),
62 _life_timer(0.0),
63 _wind(true),
64 _mass(0),
65 _random(false),
66 _life_randomness(0.0),
67 _load_resistance(0),
68 _solid(false),
69 _force_stabilised(false),
70 _slave_to_ac(false),
71 _slave_load_to_ac(false),
72 _contents_lb(0),
73 _report_collision(false),
74 _report_impact(false),
75 _external_force(false),
76 _report_expiry(false),
77 _impact_report_node(fgGetNode("/ai/models/model-impact", true))
78
79 {
80     no_roll = false;
81 }
82
83 FGAIBallistic::~FGAIBallistic() {
84 }
85
86 void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) {
87     if (!scFileNode){
88         return;
89     }
90
91     FGAIBase::readFromScenario(scFileNode);
92
93     //setPath(scFileNode->getStringValue("model", "Models/Geometry/rocket.ac")); 
94     setRandom(scFileNode->getBoolValue("random", false));
95     setAzimuth(scFileNode->getDoubleValue("azimuth", 0.0));
96     setElevation(scFileNode->getDoubleValue("elevation", 0));
97     setDragArea(scFileNode->getDoubleValue("eda", 0.007));
98     setLife(scFileNode->getDoubleValue("life", 900.0));
99     setBuoyancy(scFileNode->getDoubleValue("buoyancy", 0));
100     //setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
101     //setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
102     setWind(scFileNode->getBoolValue("wind", false));
103     setRoll(scFileNode->getDoubleValue("roll", 0.0));
104     setCd(scFileNode->getDoubleValue("cd", 0.029));
105     //setMass(scFileNode->getDoubleValue("mass", 0.007));
106     setWeight(scFileNode->getDoubleValue("weight", 0.25));
107     setStabilisation(scFileNode->getBoolValue("aero-stabilised", false));
108     setNoRoll(scFileNode->getBoolValue("no-roll", false));
109     setImpact(scFileNode->getBoolValue("impact", false));
110     setExpiry(scFileNode->getBoolValue("expiry", false));
111     setCollision(scFileNode->getBoolValue("collision", false));
112     setImpactReportNode(scFileNode->getStringValue("impact-reports"));
113     setName(scFileNode->getStringValue("name", "Rocket"));
114     setFuseRange(scFileNode->getDoubleValue("fuse-range", 0.0));
115     setSMPath(scFileNode->getStringValue("submodel-path", ""));
116     setSubID(scFileNode->getIntValue("SubID", 0));
117     setExternalForce(scFileNode->getBoolValue("external-force", false));
118     setForcePath(scFileNode->getStringValue("force-path", ""));
119     setForceStabilisation(scFileNode->getBoolValue("force-stabilised", false));
120     setXoffset(scFileNode->getDoubleValue("x-offset", 0.0));
121     setYoffset(scFileNode->getDoubleValue("y-offset", 0.0));
122     setZoffset(scFileNode->getDoubleValue("z-offset", 0.0));
123     setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
124     setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
125     setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
126     setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
127     setLoadOffset(scFileNode->getDoubleValue("load-offset", 0.0));
128     setSlaved(scFileNode->getBoolValue("slaved", false));
129     setSlavedLoad(scFileNode->getBoolValue("slaved-load", false));
130     setContentsPath(scFileNode->getStringValue("contents"));
131     setParentName(scFileNode->getStringValue("parent"));
132 }
133
134 bool FGAIBallistic::init(bool search_in_AI_path) {
135     FGAIBase::init(search_in_AI_path);
136     reinit();
137     return true;
138 }
139
140 void FGAIBallistic::reinit() {
141     _impact_reported = false;
142     _collision_reported = false;
143     _expiry_reported = false;
144
145     _impact_lat = 0;
146     _impact_lon = 0;
147     _impact_elev = 0;
148     _impact_hdg = 0;
149     _impact_pitch = 0;
150     _impact_roll = 0;
151     _impact_speed = 0;
152
153     invisible = false;
154
155     _elapsed_time += (sg_random() * 100);
156
157     _life_timer = 0;
158
159     props->setStringValue("material/name", "");
160     props->setStringValue("name", _name.c_str());
161     props->setStringValue("submodels/path", _path.c_str());
162
163     if (_slave_to_ac) {
164         props->setStringValue("force/path", _force_path.c_str());
165         props->setStringValue("contents/path", _contents_path.c_str());
166     }
167
168     //cout << "init: name " << _name.c_str() << " _life_timer " << _life_timer 
169     //    << endl;
170
171     //if(_parent != ""){
172     //    setParentNode();
173     //}
174
175     //setParentNodes(_selected_ac);
176
177     //props->setStringValue("vector/path", _vector_path.c_str());
178
179     // start with high value so that animations don't trigger yet
180     _ht_agl_ft = 1e10;
181     hdg = _azimuth;
182     pitch = _elevation;
183     roll = _rotation;
184
185     Transform();
186
187     if (_parent != "") {
188         setParentNode();
189     }
190
191     setParentNodes(_selected_ac);
192
193     FGAIBase::reinit();
194 }
195
196 void FGAIBallistic::bind() {
197     //    FGAIBase::bind();
198
199     _tiedProperties.setRoot(props);
200     tie("sim/time/elapsed-sec",
201         SGRawValueMethods<FGAIBallistic,double>(*this,
202         &FGAIBallistic::_getTime, &FGAIBallistic::setTime));
203     //tie("mass-slug",
204     //    SGRawValueMethods<FGAIBallistic,double>(*this,
205     //    &FGAIBallistic::getMass));
206
207     tie("material/solid",
208         SGRawValuePointer<bool>(&_solid));
209     tie("altitude-agl-ft",
210         SGRawValuePointer<double>(&_ht_agl_ft));
211     tie("controls/slave-to-ac",
212         SGRawValueMethods<FGAIBallistic,bool>
213         (*this, &FGAIBallistic::getSlaved, &FGAIBallistic::setSlaved));
214     tie("controls/invisible",
215         SGRawValuePointer<bool>(&invisible));
216
217     if (_external_force || _slave_to_ac) {
218         tie("controls/force_stabilized",
219             SGRawValuePointer<bool>(&_force_stabilised));
220         tie("position/global-x",
221             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosX, 0));
222         tie("position/global-y",
223             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosY, 0));
224         tie("position/global-z",
225             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosZ, 0));
226         tie("velocities/vertical-speed-fps",
227             SGRawValuePointer<double>(&vs));
228         tie("velocities/true-airspeed-kt",
229             SGRawValuePointer<double>(&speed));
230         tie("velocities/horizontal-speed-fps",
231             SGRawValuePointer<double>(&hs));
232         tie("position/altitude-ft",
233             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getElevationFt, &FGAIBase::_setAltitude));
234         tie("position/latitude-deg",
235             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLatitude, &FGAIBase::_setLatitude));
236         tie("position/longitude-deg",
237             SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLongitude, &FGAIBase::_setLongitude));
238         tie("orientation/hdg-deg",
239             SGRawValuePointer<double>(&hdg));
240         tie("orientation/pitch-deg",
241             SGRawValuePointer<double>(&pitch));
242         tie("orientation/roll-deg",
243             SGRawValuePointer<double>(&roll));
244         tie("controls/slave-load-to-ac",
245             SGRawValueMethods<FGAIBallistic,bool>
246             (*this, &FGAIBallistic::getSlavedLoad, &FGAIBallistic::setSlavedLoad));
247         tie("position/load-offset",
248             SGRawValueMethods<FGAIBallistic,double>
249             (*this, &FGAIBallistic::getLoadOffset, &FGAIBallistic::setLoadOffset));
250         tie("load/distance-to-hitch-ft",
251             SGRawValueMethods<FGAIBallistic,double>
252             (*this, &FGAIBallistic::getDistanceToHitch));
253         tie("load/elevation-to-hitch-deg",
254             SGRawValueMethods<FGAIBallistic,double>
255             (*this, &FGAIBallistic::getElevToHitch));
256         tie("load/bearing-to-hitch-deg",
257             SGRawValueMethods<FGAIBallistic,double>
258             (*this, &FGAIBallistic::getBearingToHitch));
259         tie("material/load-resistance",
260         SGRawValuePointer<double>(&_load_resistance));
261     }
262 }
263
264 void FGAIBallistic::update(double dt)
265 {
266     FGAIBase::update(dt);
267
268     if (_slave_to_ac) {
269         slaveToAC(dt);
270         Transform();
271     }
272     else if (!invisible) {
273         Run(dt);
274         Transform();
275     }
276
277 }
278
279 void FGAIBallistic::setAzimuth(double az) {
280     if (_random)
281         hdg = _azimuth = az - _az_random_error + 2 * _az_random_error * sg_random();
282     else 
283         hdg = _azimuth = az;
284 }
285
286 void FGAIBallistic::setAzimuthRandomError(double error) {
287     _az_random_error = error;
288 }
289
290 void FGAIBallistic::setElevationRandomError(double error) {
291     _el_random_error = error;
292 }
293
294 void FGAIBallistic::setElevation(double el) {
295     if (_random)
296         pitch = _elevation = el - _el_random_error + 2 * _el_random_error * sg_random();
297     else
298         pitch = _elevation = el;
299 }
300
301 void FGAIBallistic::setRoll(double rl) {
302     roll = _rotation = rl;
303 }
304
305 void FGAIBallistic::setStabilisation(bool val) {
306     _aero_stabilised = val;
307 }
308
309 void FGAIBallistic::setForceStabilisation(bool val) {
310     _force_stabilised = val;
311 }
312
313 void FGAIBallistic::setNoRoll(bool nr) {
314     no_roll = nr;
315 }
316
317 void FGAIBallistic::setDragArea(double a) {
318     _drag_area = a;
319 }
320
321 void FGAIBallistic::setLife(double seconds) {
322     if (_random)
323         life = seconds * _life_randomness + (seconds * (1 -_life_randomness) * sg_random());
324     else
325         life = seconds;
326 }
327
328 void FGAIBallistic::setBuoyancy(double fpss) {
329     _buoyancy = fpss;
330 }
331
332 void FGAIBallistic::setWind_from_east(double fps) {
333     _wind_from_east = fps;
334 }
335
336 void FGAIBallistic::setWind_from_north(double fps) {
337     _wind_from_north = fps;
338 }
339
340 void FGAIBallistic::setWind(bool val) {
341     _wind = val;
342 }
343
344 void FGAIBallistic::setCd(double cd) {
345     _cd = cd;
346     _init_cd = cd;
347 }
348
349 void FGAIBallistic::setCdRandomness(double randomness) {
350     _cd_randomness = randomness;
351 }
352
353 void FGAIBallistic::setMass(double m) {
354     _mass = m;
355 }
356
357 void FGAIBallistic::setWeight(double w) {
358     _weight_lb = w;
359 }
360
361 void FGAIBallistic::setLifeRandomness(double randomness) {
362     _life_randomness = randomness;
363 }
364
365 void FGAIBallistic::setRandom(bool r) {
366     _random = r;
367 }
368
369 void FGAIBallistic::setImpact(bool i) {
370     _report_impact = i;
371 }
372
373 void FGAIBallistic::setCollision(bool c) {
374     _report_collision = c;
375 }
376
377 void FGAIBallistic::setExpiry(bool e) {
378     _report_expiry = e;
379 }
380
381 void FGAIBallistic::setExternalForce(bool f) {
382     _external_force = f;
383 }
384
385 void FGAIBallistic::setImpactReportNode(const string& path) {
386     if (!path.empty())
387         _impact_report_node = fgGetNode(path.c_str(), true);
388 }
389
390 void FGAIBallistic::setSMPath(const string& s) {
391     _path = s;
392     //cout << "submodel path " << _path << endl;
393 }
394
395 void FGAIBallistic::setFuseRange(double f) {
396     _fuse_range = f;
397 }
398
399 void FGAIBallistic::setSubID(int i) {
400     _subID = i;
401 }
402
403 void FGAIBallistic::setSubmodel(const string& s) {
404     _submodel = s;
405 }
406
407 void FGAIBallistic::setGroundOffset(double g) {
408     _ground_offset = g;
409 }
410
411 void FGAIBallistic::setLoadOffset(double l) {
412     _load_offset = l;
413 }
414
415 double FGAIBallistic::getLoadOffset() const {
416     return _load_offset;
417 }
418
419 void FGAIBallistic::setSlaved(bool s) {
420     _slave_to_ac = s;
421 }
422
423 void FGAIBallistic::setContentsPath(const string& path) {
424     _contents_path = path;
425
426     if (!path.empty()) {
427         _contents_node = fgGetNode(path.c_str(), true);
428     }
429 }
430
431 void FGAIBallistic::setContentsNode(SGPropertyNode_ptr node) {
432     if (node != 0) {
433         _contents_node = node;
434         _contents_path = _contents_node->getDisplayName();
435     }
436 }
437
438 void FGAIBallistic::setParentNodes(SGPropertyNode_ptr node) {
439     if (node != 0) {
440         _pnode = node;
441         _p_pos_node = _pnode->getChild("position", 0, true);
442         _p_lat_node = _p_pos_node->getChild("latitude-deg", 0, true);
443         _p_lon_node = _p_pos_node->getChild("longitude-deg", 0, true);
444         _p_alt_node = _p_pos_node->getChild("altitude-ft", 0, true);
445         _p_agl_node = _p_pos_node->getChild("altitude-agl-ft", 0, true);
446
447
448         _p_ori_node = _pnode->getChild("orientation", 0, true);
449         _p_pch_node = _p_ori_node->getChild("pitch-deg", 0, true);
450         _p_rll_node = _p_ori_node->getChild("roll-deg", 0, true);
451         _p_hdg_node = _p_ori_node->getChild("true-heading-deg",0, true);
452
453         _p_vel_node = _pnode->getChild("velocities", 0, true);
454         _p_spd_node = _p_vel_node->getChild("true-airspeed-kt", 0, true);
455     }
456 }
457
458 void FGAIBallistic::setParentPos() {
459     if (_pnode != 0) { 
460         double lat = _p_lat_node->getDoubleValue();
461         double lon = _p_lon_node->getDoubleValue();
462         double alt = _p_alt_node->getDoubleValue();
463
464         _parentpos.setLongitudeDeg(lon);
465         _parentpos.setLatitudeDeg(lat);
466         _parentpos.setElevationFt(alt);
467     }
468 }
469
470 bool FGAIBallistic::getSlaved() const {
471     return _slave_to_ac;
472 }
473
474 double FGAIBallistic::getMass() const {
475     return _mass;
476 }
477
478 double FGAIBallistic::getContents() {
479     if (_contents_node) {
480         _contents_lb = _contents_node->getChild("level-lbs", 0, 1)->getDoubleValue();
481     }
482     return _contents_lb;
483 }
484
485 void FGAIBallistic::setContents(double c) {
486     if (_contents_node)
487         _contents_lb = _contents_node->getChild("level-gal_us", 0, 1)->setDoubleValue(c);
488 }
489
490 void FGAIBallistic::setSlavedLoad(bool l) {
491     _slave_load_to_ac = l;
492 }
493
494 bool FGAIBallistic::getSlavedLoad() const {
495     return _slave_load_to_ac;
496 }
497
498 void FGAIBallistic::setForcePath(const string& p) {
499     _force_path = p;
500     if (!_force_path.empty()) {
501         SGPropertyNode *fnode = fgGetNode(_force_path.c_str(), 0, true );
502         _force_node = fnode->getChild("force-lb", 0, true);
503         _force_azimuth_node = fnode->getChild("force-azimuth-deg", 0, true);
504         _force_elevation_node = fnode->getChild("force-elevation-deg", 0, true);
505     }
506 }
507
508 bool FGAIBallistic::getHtAGL(double start) {
509     const simgear::BVHMaterial* mat = 0;
510     if (getGroundElevationM(SGGeod::fromGeodM(pos, start),
511         _elevation_m, &mat)) {
512             const SGMaterial* material = dynamic_cast<const SGMaterial*>(mat);
513             _ht_agl_ft = pos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
514
515             if (material) {
516                 const std::vector<string>& names = material->get_names();
517                 _solid = material->get_solid();
518                 _load_resistance = material->get_load_resistance();
519                 _frictionFactor = material->get_friction_factor();
520
521                 if (!names.empty())
522                     props->setStringValue("material/name", names[0].c_str());
523                 else
524                     props->setStringValue("material/name", "");
525
526                 _mat_name = names[0];
527
528                 //cout << "material " << _mat_name 
529                 //<< " solid " << _solid 
530                 //<< " load " << _load_resistance
531                 //<< " frictionFactor " << _frictionFactor
532                 //<< endl;
533             }
534
535             return true;
536     }
537     else {
538         return false;
539     }
540 }
541
542 double FGAIBallistic::getRecip(double az) {
543     // calculate the reciprocal of the input azimuth 
544     if (az - 180 < 0) {
545         return az + 180;
546     }
547     else {
548         return az - 180; 
549     }
550 }
551
552 void FGAIBallistic::setPch(double e, double dt, double coeff) {
553     double c = dt / (coeff + dt);
554     pitch = (e * c) + (pitch * (1 - c));
555 }
556
557 void FGAIBallistic::setBnk(double r, double dt, double coeff) {
558     double c = dt / (coeff + dt);
559     roll = (r * c) + (roll * (1 - c));
560 }
561
562 void FGAIBallistic::setSpd(double s, double dt, double coeff) {
563     double c = dt / (coeff + dt);
564     _speed = (s * c) + (_speed * (1 - c));
565 }
566
567 void FGAIBallistic::setHt(double h, double dt, double coeff) {
568     double c = dt / (coeff + dt);
569     _height = (h * c) + (_height * (1 - c));
570 }
571
572 int FGAIBallistic::setHdg(double tgt_hdg, double dt, double coeff) {
573     double recip = getRecip(hdg);
574     double c = dt / (coeff + dt);
575     //cout << "set heading " << tgt_hdg << endl;
576     //we need to ensure that we turn the short way to the new hdg
577     if (tgt_hdg < recip && tgt_hdg < hdg && hdg > 180) {
578         hdg = ((tgt_hdg + 360) * c) + (hdg * (1 - c));
579 //        cout << "case 1: right turn" << endl;
580     } else if (tgt_hdg > recip && tgt_hdg > hdg && hdg <= 180){
581         hdg = ((tgt_hdg - 360) * c) + (hdg * (1 - c));
582 //        cout << "case 2: left turn" << endl;
583     } else {
584         hdg = (tgt_hdg * c) + (hdg * (1 - c));
585 //        cout << "case 4: left turn" << endl;
586     }
587     return -1;
588 }
589
590 double  FGAIBallistic::getTgtXOffset() const {
591     return _tgt_x_offset;
592 }
593
594 double  FGAIBallistic::getTgtYOffset() const {
595     return _tgt_y_offset;
596
597
598 double  FGAIBallistic::getTgtZOffset() const {
599     return _tgt_z_offset;
600 }
601
602 void FGAIBallistic::setTgtXOffset(double x) {
603     _tgt_x_offset = x;
604 }
605
606 void FGAIBallistic::setTgtYOffset(double y) {
607     _tgt_y_offset = y;
608 }
609
610 void FGAIBallistic::setTgtZOffset(double z) {
611     _tgt_z_offset = z;
612 }
613
614 void FGAIBallistic::slaveToAC(double dt) {
615     if (invisible)
616         return;
617
618     double hdg, pch, rll;//, agl = 0;
619
620     if (_pnode != 0) {
621         setParentPos();
622         hdg = _p_hdg_node->getDoubleValue();
623         pch = _p_pch_node->getDoubleValue();
624         rll = _p_rll_node->getDoubleValue();
625 //        agl = _p_agl_node->getDoubleValue();
626         setOffsetPos(_parentpos, hdg, pch, rll);
627         setSpeed(_p_spd_node->getDoubleValue());
628     }
629     else {
630         hdg = manager->get_user_heading();
631         pch = manager->get_user_pitch();
632         rll = manager->get_user_roll();
633 //        agl = manager->get_user_agl();
634         setOffsetPos(globals->get_aircraft_position(), hdg, pch, rll);
635         setSpeed(manager->get_user_speed());
636     }
637
638     pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
639     pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
640     pos.setElevationFt(_offsetpos.getElevationFt());
641     setHeading(hdg);
642     setPitch(pch + _pitch_offset);
643     setBank(rll + _roll_offset);
644     setOffsetVelocity(dt, pos);
645     setTime(0);
646
647     //update the mass (slugs)
648     _mass = (_weight_lb + getContents()) / slugs_to_lbs;
649
650     _impact_reported = false;
651
652     //cout << _name << " _mass "<<_mass <<" " << getContents() 
653     //<< " " << getContents() / slugs_to_lbs << " weight " << _weight_lb << endl;
654     //    cout << _name << " update hs " << hs << " vs " << vs << endl;
655 }
656
657 void FGAIBallistic::Run(double dt) {
658     _life_timer += dt;
659     
660     //_pass += 1;
661     //cout<<"AIBallistic run: name " << _name.c_str() 
662     //    << " dt " << dt <<  " _life_timer " << _life_timer << " pass " << _pass << endl;
663
664     // if life = -1 the object does not die
665     if (_life_timer > life && life != -1) {
666         if (_report_expiry && !_expiry_reported && !_impact_reported && !_collision_reported) {
667             //cout<<"AIBallistic run: name " << _name.c_str() << " expiry " 
668                 //<< " _life_timer " << _life_timer<< endl;
669             handle_expiry();
670         }
671         else {
672             //cout<<"AIBallistic run: name " << _name.c_str() 
673             //    << " die " <<  " _life_timer " << _life_timer << endl;
674             setDie(true);
675         }
676
677         setTime(0);
678     }
679
680     // Set the contents in the appropriate tank or other property in the parent to zero
681     setContents(0);
682
683     if (_random) {
684         // Keep the new Cd within +- 10% of the current Cd to avoid a fluctuating value
685         double cd_min = _cd * 0.9;
686         double cd_max = _cd * 1.1;
687
688         // Randomize Cd by +- a certain percentage of the initial Cd
689         _cd = _init_cd * (1 - _cd_randomness + 2 * _cd_randomness * sg_random());
690
691         if (_cd < cd_min) _cd = cd_min;
692         if (_cd > cd_max) _cd = cd_max;
693     }
694
695     // Adjust Cd by Mach number. The equations are based on curves
696     // for a conventional shell/bullet (no boat-tail).
697     double Cdm;
698
699     if (Mach < 0.7)
700         Cdm = 0.0125 * Mach + _cd;
701     else if (Mach < 1.2)
702         Cdm = 0.3742 * pow(Mach, 2) - 0.252 * Mach + 0.0021 + _cd;
703     else
704         Cdm = 0.2965 * pow(Mach, -1.1506) + _cd;
705
706     //cout <<_name << " Mach " << Mach << " Cdm " << Cdm 
707     //    << " ballistic speed kts "<< speed <<  endl;
708
709     // drag = Cd * 0.5 * rho * speed * speed * drag_area;
710     // rho is adjusted for altitude in void FGAIBase::update,
711     // using Standard Atmosphere (sealevel temperature 15C)
712     // acceleration = drag/mass;
713     // adjust speed by drag
714     speed -= (Cdm * 0.5 * rho * speed * speed * _drag_area/_mass) * dt;
715
716     // don't let speed become negative
717     if (speed < 0.0)
718         speed = 0.0;
719
720 //    double speed_fps = speed * SG_KT_TO_FPS;
721
722     // calculate vertical and horizontal speed components
723     calcVSHS();
724
725     //resolve horizontal speed into north and east components:
726     //and convert horizontal speed (fps) to degrees per second
727     calcNE();
728
729     // If wind not required, set to zero
730     if (!_wind) {
731         _wind_from_north = 0;
732         _wind_from_east = 0;
733     }
734     else {
735         _wind_from_north = manager->get_wind_from_north();
736         _wind_from_east = manager->get_wind_from_east();
737     }
738
739     // Calculate velocity due to external force
740     double force_speed_north_deg_sec = 0;
741     double force_speed_east_deg_sec = 0;
742     double hs_force_fps = 0;
743     double v_force_acc_fpss = 0;
744     double force_speed_north_fps = 0;
745     double force_speed_east_fps = 0;
746     double h_force_lbs = 0;
747     double normal_force_lbs = 0;
748     double normal_force_fpss = 0;
749     double static_friction_force_lbs = 0;
750     double dynamic_friction_force_lbs = 0;
751     double friction_force_speed_north_fps = 0;
752     double friction_force_speed_east_fps = 0;
753     double friction_force_speed_north_deg_sec = 0;
754     double friction_force_speed_east_deg_sec = 0;
755     double force_elevation_deg = 0;
756     double force_azimuth_deg  = 0;
757     double force_lbs = 0;
758
759     if (_external_force) {
760         //cout << _name << " external force " <<  hdg << " az " << _azimuth << endl;
761
762         SGPropertyNode *n = fgGetNode(_force_path.c_str(), true);
763         force_lbs            = n->getChild("force-lb", 0, true)->getDoubleValue();
764         force_elevation_deg  = n->getChild("force-elevation-deg", 0, true)->getDoubleValue();
765         force_azimuth_deg    = n->getChild("force-azimuth-deg", 0, true)->getDoubleValue();
766         
767         // Resolve force into vertical and horizontal components:
768         double v_force_lbs = force_lbs * sin( force_elevation_deg * SG_DEGREES_TO_RADIANS );
769         h_force_lbs = force_lbs * cos( force_elevation_deg * SG_DEGREES_TO_RADIANS );
770
771         // Perform ground interaction if impacts are not calculated
772         if (!_report_impact && getHtAGL(10000)) {
773             double deadzone = 0.1;
774
775             if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid) {
776                 normal_force_lbs = (_mass * slugs_to_lbs) - v_force_lbs;
777
778                 if (normal_force_lbs < 0)
779                     normal_force_lbs = 0;
780
781                 pos.setElevationFt(0 + _ground_offset);
782                 if (vs < 0)
783                     vs = -vs * 0.5;
784
785                 // Calculate friction. We assume a static coefficient of
786                 // friction (mu) of 0.62 (wood on concrete)
787                 double mu = 0.62;
788
789                 static_friction_force_lbs = mu * normal_force_lbs * _frictionFactor;
790
791                 // Adjust horizontal force. We assume that a speed of <= 5 fps is static
792                 if (h_force_lbs <= static_friction_force_lbs && hs <= 5) {
793                     h_force_lbs = hs = 0;
794                     _speed_north_fps = _speed_east_fps = 0;
795                 }
796                 else
797                     dynamic_friction_force_lbs = (static_friction_force_lbs * 0.95);
798
799                 // Ignore wind when on the ground for now
800                 //TODO fix this
801                 _wind_from_north = 0;
802                 _wind_from_east = 0;
803             }
804         }
805
806         //acceleration = (force(lbsf)/mass(slugs))
807         v_force_acc_fpss = v_force_lbs / _mass;
808         normal_force_fpss = normal_force_lbs / _mass;
809         double h_force_acc_fpss = h_force_lbs / _mass;
810         double dynamic_friction_acc_fpss = dynamic_friction_force_lbs / _mass;
811
812         // velocity = acceleration * dt
813         hs_force_fps = h_force_acc_fpss * dt;
814         double friction_force_fps = dynamic_friction_acc_fpss * dt;
815
816         //resolve horizontal speeds into north and east components:
817         force_speed_north_fps   = cos(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
818         force_speed_east_fps    = sin(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
819
820         friction_force_speed_north_fps = cos(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
821         friction_force_speed_east_fps  = sin(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
822
823         // convert horizontal speed (fps) to degrees per second
824         force_speed_north_deg_sec = force_speed_north_fps / ft_per_deg_lat;
825         force_speed_east_deg_sec  = force_speed_east_fps / ft_per_deg_lon;
826
827         friction_force_speed_north_deg_sec = friction_force_speed_north_fps / ft_per_deg_lat;
828         friction_force_speed_east_deg_sec  = friction_force_speed_east_fps / ft_per_deg_lon;
829     }
830
831     // convert wind speed (fps) to degrees lat/lon per second
832     double wind_speed_from_north_deg_sec = _wind_from_north / ft_per_deg_lat;
833     double wind_speed_from_east_deg_sec  = _wind_from_east / ft_per_deg_lon;
834
835     //recombine the horizontal velocity components
836     hs = sqrt(((_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps) 
837         * (_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
838         + ((_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps) 
839         * (_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps)));
840
841     if (hs <= 0.00001)
842         hs = 0;
843
844     // adjust vertical speed for acceleration of gravity, buoyancy, and vertical force
845     double gravity = SG_METER_TO_FEET * (Environment::Gravity::instance()->getGravity(pos));
846     vs -= (gravity - _buoyancy - v_force_acc_fpss - normal_force_fpss) * dt;
847
848     if (vs <= 0.00001 && vs >= -0.00001)
849         vs = 0;
850
851     // set new position
852     if (_slave_load_to_ac) {
853         setOffsetPos(pos, 
854             manager->get_user_heading(),
855             manager->get_user_pitch(), 
856             manager->get_user_roll()
857             );
858         pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
859         pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
860         pos.setElevationFt(_offsetpos.getElevationFt());
861
862         if (getHtAGL(10000)) {
863             double deadzone = 0.1;
864
865             if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid) {
866                 pos.setElevationFt(0 + _ground_offset);
867             }
868             else {
869                 pos.setElevationFt(_offsetpos.getElevationFt() + _load_offset);
870             }
871         }
872     }
873     else {
874         pos.setLatitudeDeg( pos.getLatitudeDeg()
875             + (speed_north_deg_sec - wind_speed_from_north_deg_sec 
876             + force_speed_north_deg_sec + friction_force_speed_north_deg_sec) * dt );
877         pos.setLongitudeDeg( pos.getLongitudeDeg()
878             + (speed_east_deg_sec - wind_speed_from_east_deg_sec 
879             + force_speed_east_deg_sec + friction_force_speed_east_deg_sec) * dt );
880         pos.setElevationFt(pos.getElevationFt() + vs * dt);
881     }
882
883 //    cout << _name << " run hs " << hs << " vs " << vs << endl;
884
885     // recalculate total speed
886     if ( vs == 0 && hs == 0)
887         speed = 0;
888     else
889         speed = sqrt( vs * vs + hs * hs) / SG_KT_TO_FPS;
890
891     // recalculate elevation and azimuth (velocity vectors)
892     _elevation = atan2( vs, hs ) * SG_RADIANS_TO_DEGREES;
893     _azimuth =  atan2((_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps), 
894         (_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
895         * SG_RADIANS_TO_DEGREES;
896
897     // rationalise azimuth
898     if (_azimuth < 0)
899         _azimuth += 360;
900
901     if (_aero_stabilised) { // we simulate rotational moment of inertia by using a filter
902         //cout<< "_aero_stabilised " << hdg << " az " << _azimuth << endl;
903         const double coeff = 0.9;
904
905         // we assume a symetrical MI about the pitch and yaw axis
906         setPch(_elevation, dt, coeff);
907         setHdg(_azimuth, dt, coeff);
908     }
909     else if (_force_stabilised) { // we simulate rotational moment of inertia by using a filter
910         //cout<< "_force_stabilised "<< endl;
911         
912         const double coeff = 0.9;
913         double ratio = h_force_lbs/(_mass * slugs_to_lbs);
914
915         if (ratio >  1) ratio =  1;
916         if (ratio < -1) ratio = -1;
917
918         double force_pitch = acos(ratio) * SG_RADIANS_TO_DEGREES;
919
920         if (force_pitch <= force_elevation_deg)
921             force_pitch = force_elevation_deg;
922
923         // we assume a symetrical MI about the pitch and yaw axis
924         setPch(force_pitch,dt, coeff);
925         setHdg(_azimuth, dt, coeff);
926     }
927
928     // Do impacts and collisions
929     if (_report_impact && !_impact_reported)
930         handle_impact();
931
932     if (_report_collision && !_collision_reported)
933         handle_collision();
934
935     // Set destruction flag if altitude less than sea level -1000
936     if (altitude_ft < -1000.0 && life != -1)
937         setDie(true);
938 }
939
940 double FGAIBallistic::_getTime() const {
941     return _life_timer;
942 }
943
944 void FGAIBallistic::setTime(double s) {
945     _life_timer = s;
946 }
947
948 void FGAIBallistic::handleEndOfLife(double elevation) {
949     report_impact(elevation);
950
951     // Make the submodel invisible if the submodel is immortal, otherwise kill it if it has no subsubmodels
952     if (life == -1) {
953         invisible = true;
954     }
955     else if (_subID == 0) {
956         // Kill the AIObject if there is no subsubmodel
957         setDie(true);
958     }
959 }
960
961 void FGAIBallistic::handle_impact() {
962     // Try terrain intersection
963     double start = pos.getElevationM() + 100;
964
965     if (!getHtAGL(start))
966         return;
967
968     if (_ht_agl_ft <= 0) {
969         SG_LOG(SG_AI, SG_DEBUG, "AIBallistic: terrain impact material" << _mat_name);
970         _impact_reported = true;
971         handleEndOfLife(_elevation_m);
972     } 
973 }
974
975 void FGAIBallistic::handle_expiry() {
976     _expiry_reported = true;
977     handleEndOfLife(pos.getElevationM());
978 }
979
980 void FGAIBallistic::handle_collision()
981 {
982     const FGAIBase *object = manager->calcCollision(pos.getElevationFt(),
983         pos.getLatitudeDeg(),pos.getLongitudeDeg(), _fuse_range);
984
985     if (object) {
986         report_impact(pos.getElevationM(), object);
987         _collision_reported = true;
988     }
989 }
990
991 void FGAIBallistic::report_impact(double elevation, const FGAIBase *object)
992 {
993     _impact_lat    = pos.getLatitudeDeg();
994     _impact_lon    = pos.getLongitudeDeg();
995     _impact_elev   = elevation;
996     _impact_speed  = speed * SG_KT_TO_MPS;
997     _impact_hdg    = hdg;
998     _impact_pitch  = pitch;
999     _impact_roll   = roll;
1000
1001     SGPropertyNode *n = props->getNode("impact", true);
1002
1003     if (object)
1004         n->setStringValue("type", object->getTypeString());
1005     else
1006         n->setStringValue("type", "terrain");
1007
1008     SG_LOG(SG_AI, SG_DEBUG, "AIBallistic: object impact " << _name 
1009         << " lon " <<_impact_lon << " lat " <<_impact_lat << " sec " << _life_timer);
1010
1011     n->setDoubleValue("longitude-deg", _impact_lon);
1012     n->setDoubleValue("latitude-deg", _impact_lat);
1013     n->setDoubleValue("elevation-m", _impact_elev);
1014     n->setDoubleValue("heading-deg", _impact_hdg);
1015     n->setDoubleValue("pitch-deg", _impact_pitch);
1016     n->setDoubleValue("roll-deg", _impact_roll);
1017     n->setDoubleValue("speed-mps", _impact_speed);
1018
1019     _impact_report_node->setStringValue(props->getPath());
1020 }
1021
1022 SGVec3d FGAIBallistic::getCartHitchPos() const {
1023     // convert geodetic positions to geocentered
1024     SGVec3d cartuserPos = globals->get_aircraft_position_cart();
1025     
1026     //SGVec3d cartPos = getCartPos();
1027
1028     // Transform to the right coordinate frame, configuration is done in
1029     // the x-forward, y-right, z-up coordinates (feet), computation
1030     // in the simulation usual body x-forward, y-right, z-down coordinates
1031     // (meters) )
1032     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1033             _y_offset * SG_FEET_TO_METER,
1034             -_z_offset * SG_FEET_TO_METER);
1035
1036     // Transform the user position to the horizontal local coordinate system.
1037     SGQuatd hlTrans = SGQuatd::fromLonLat(globals->get_aircraft_position());
1038
1039     // and postrotate the orientation of the user model wrt the horizontal
1040     // local frame
1041     hlTrans *= SGQuatd::fromYawPitchRollDeg(
1042         manager->get_user_heading(),
1043         manager->get_user_pitch(),
1044         manager->get_user_roll());
1045
1046     // The offset converted to the usual body fixed coordinate system
1047     // rotated to the earth-fixed coordinates axis
1048     SGVec3d off = hlTrans.backTransform(_off);
1049
1050     // Add the position offset of the user model to get the geocentered position
1051     SGVec3d offsetPos = cartuserPos + off;
1052     return offsetPos;
1053 }
1054
1055 void FGAIBallistic::setOffsetPos(SGGeod inpos, double heading, double pitch, double roll) {
1056     // Convert the hitch geocentered position to geodetic
1057     SGVec3d cartoffsetPos = getCartOffsetPos(inpos, heading, pitch, roll);
1058     SGGeodesy::SGCartToGeod(cartoffsetPos, _offsetpos);
1059 }
1060
1061 double FGAIBallistic::getDistanceToHitch() const {
1062     //calculate the distance load to hitch 
1063     SGVec3d carthitchPos = getCartHitchPos();
1064     SGVec3d cartPos = getCartPos();
1065
1066     SGVec3d diff = carthitchPos - cartPos;
1067     double distance = norm(diff);
1068     return distance * SG_METER_TO_FEET;
1069 }
1070
1071 double FGAIBallistic::getElevToHitch() const {
1072     // now the angle, positive angles are upwards
1073     double distance = getDistanceToHitch() * SG_FEET_TO_METER;
1074     double angle = 0;
1075     double daltM = _offsetpos.getElevationM() - pos.getElevationM();
1076
1077     if (fabs(distance) < SGLimits<float>::min()) {
1078         angle = 0;
1079     } else {
1080         double sAngle = daltM/distance;
1081         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1082         angle = SGMiscd::rad2deg(asin(sAngle));
1083     }
1084
1085     return angle;
1086 }
1087
1088 double FGAIBallistic::getBearingToHitch() const {
1089     //calculate the bearing and range of the second pos from the first
1090     double distance = getDistanceToHitch() * SG_FEET_TO_METER;
1091     double az1, az2;
1092
1093     geo_inverse_wgs_84(pos, _offsetpos, &az1, &az2, &distance);
1094
1095     return az1;
1096 }
1097
1098 double FGAIBallistic::getRelBrgHitchToUser() const {
1099     //calculate the relative bearing 
1100     double az1, az2, distance;
1101
1102     geo_inverse_wgs_84(_offsetpos, globals->get_aircraft_position(), &az1, &az2, &distance);
1103
1104     double rel_brg = az1 - hdg;
1105
1106     SG_NORMALIZE_RANGE(rel_brg, -180.0, 180.0);
1107
1108     return rel_brg;
1109 }
1110
1111 double FGAIBallistic::getElevHitchToUser() const {
1112     // Calculate the distance from the user position
1113     SGVec3d carthitchPos = getCartHitchPos();
1114     SGVec3d cartuserPos = globals->get_aircraft_position_cart();
1115
1116     SGVec3d diff = cartuserPos - carthitchPos;
1117
1118     double distance = norm(diff);
1119     double angle = 0;
1120
1121     double daltM = globals->get_aircraft_position().getElevationM() - _offsetpos.getElevationM();
1122
1123     // Now the angle, positive angles are upwards
1124     if (fabs(distance) < SGLimits<float>::min()) {
1125         angle = 0;
1126     }
1127     else {
1128         double sAngle = daltM/distance;
1129         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1130         angle = SGMiscd::rad2deg(asin(sAngle));
1131     }
1132
1133     return angle;
1134 }
1135
1136 void FGAIBallistic::setTgtOffsets(double dt, double coeff) {
1137     double c = dt / (coeff + dt);
1138
1139     _x_offset = (_tgt_x_offset * c) + (_x_offset * (1 - c));
1140     _y_offset = (_tgt_y_offset * c) + (_y_offset * (1 - c));
1141     _z_offset = (_tgt_z_offset * c) + (_z_offset * (1 - c));
1142 }
1143
1144 void FGAIBallistic::calcVSHS() {
1145     // Calculate vertical and horizontal speed components
1146     double speed_fps = speed * SG_KT_TO_FPS;
1147
1148     if (speed == 0.0) {
1149         hs = vs = 0.0;
1150     }
1151     else {
1152         vs = sin( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1153         hs = cos( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1154     }
1155 }
1156
1157 void FGAIBallistic::calcNE() {
1158     // Resolve horizontal speed into north and east components:
1159     _speed_north_fps = cos(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1160     _speed_east_fps = sin(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1161
1162     // Convert horizontal speed (fps) to degrees per second
1163     speed_north_deg_sec = _speed_north_fps / ft_per_deg_lat;
1164     speed_east_deg_sec  = _speed_east_fps / ft_per_deg_lon;
1165 }
1166
1167 SGVec3d FGAIBallistic::getCartOffsetPos(SGGeod inpos, double user_heading, 
1168                                         double user_pitch, double user_roll
1169                                         ) const {
1170     // Convert geodetic positions to geocentered
1171     SGVec3d cartuserPos = SGVec3d::fromGeod(inpos);
1172
1173     // Transform to the right coordinate frame, configuration is done in
1174     // the x-forward, y-right, z-up coordinates (feet), computation
1175     // in the simulation usual body x-forward, y-right, z-down coordinates
1176     // (meters) )
1177     SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1178             _y_offset * SG_FEET_TO_METER,
1179             -_z_offset * SG_FEET_TO_METER);
1180
1181     // Transform the user position to the horizontal local coordinate system.
1182     SGQuatd hlTrans = SGQuatd::fromLonLat(inpos);
1183
1184     // And postrotate the orientation of the user model wrt the horizontal
1185     // local frame
1186     hlTrans *= SGQuatd::fromYawPitchRollDeg(
1187         user_heading,
1188         user_pitch,
1189         user_roll);
1190
1191     // The offset converted to the usual body fixed coordinate system
1192     // rotated to the earth-fixed coordinates axis
1193     SGVec3d off = hlTrans.backTransform(_off);
1194
1195     // Add the position offset of the user model to get the geocentered position
1196     SGVec3d offsetPos = cartuserPos + off;
1197
1198     return offsetPos;
1199 }
1200
1201 void FGAIBallistic::setOffsetVelocity(double dt, SGGeod offsetpos) {
1202     // Calculate the distance from the previous offset position
1203     SGVec3d cartoffsetPos = SGVec3d::fromGeod(offsetpos);
1204     SGVec3d diff = cartoffsetPos - _oldcartoffsetPos;
1205
1206     double distance = norm(diff);
1207     // Calculate speed knots
1208     speed = (distance / dt) * SG_MPS_TO_KT;
1209
1210     // Now calulate the angle between the old and current postion positions (degrees)
1211     double angle = 0;
1212     double daltM = offsetpos.getElevationM() - _oldoffsetpos.getElevationM();
1213
1214     if (fabs(distance) < SGLimits<float>::min()) {
1215         angle = 0;
1216     }
1217     else {
1218         double sAngle = daltM / distance;
1219         sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1220         angle = SGMiscd::rad2deg(asin(sAngle));
1221     }
1222
1223     _elevation = angle;
1224
1225     // Calculate vertical and horizontal speed components
1226     calcVSHS();
1227
1228     // Calculate the bearing of the new offset position from the old
1229     // Don't do this if speed is low
1230     //cout << "speed " << speed << endl;
1231     if (speed > 0.1) {
1232         double az1, az2, dist;
1233         geo_inverse_wgs_84(_oldoffsetpos, offsetpos, &az1, &az2, &dist);
1234         _azimuth = az1;
1235         //cout << "offset az " << _azimuth << endl;
1236     }
1237     else {
1238         _azimuth = hdg;
1239         //cout << " slow offset az " << _azimuth << endl;
1240     }
1241
1242     // Resolve horizontal speed into north and east components
1243     calcNE();
1244
1245     // And finally store the new values
1246     _oldcartoffsetPos = cartoffsetPos;
1247     _oldoffsetpos = offsetpos;
1248 }