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