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