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