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