1 // FGAIBallistic - FGAIBase-derived class creates a ballistic object
3 // Written by David Culp, started November 2003.
4 // - davidculp2@comcast.net
6 // With major additions by Mathias Froehlich & Vivian Meazza 2004-2008
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.
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.
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.
26 #include <simgear/math/sg_random.h>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/scene/model/modellib.hxx>
30 #include <Scenery/scenery.hxx>
32 #include "AIBallistic.hxx"
34 #include <Main/util.hxx>
35 #include <Environment/gravity.hxx>
36 #include <Main/fg_props.hxx>
38 using namespace simgear;
41 const double FGAIBallistic::slugs_to_kgs = 14.5939029372;
42 const double FGAIBallistic::slugs_to_lbs = 32.1740485564;
44 FGAIBallistic::FGAIBallistic(object_type ot) :
54 _az_random_error(0.0),
55 _el_random_error(0.0),
56 _aero_stabilised(false),
66 _life_randomness(0.0),
69 _force_stabilised(false),
71 _slave_load_to_ac(false),
73 _report_collision(false),
74 _report_impact(false),
75 _external_force(false),
76 _report_expiry(false),
77 _impact_report_node(fgGetNode("/ai/models/model-impact", true))
83 FGAIBallistic::~FGAIBallistic() {
86 void FGAIBallistic::readFromScenario(SGPropertyNode* scFileNode) {
91 FGAIBase::readFromScenario(scFileNode);
93 //setPath(scFileNode->getStringValue("model", "Models/Geometry/rocket.ac"));
94 setRandom(scFileNode->getBoolValue("random", false));
95 setAzimuth(scFileNode->getDoubleValue("azimuth", 0.0));
96 setElevation(scFileNode->getDoubleValue("elevation", 0));
97 setDragArea(scFileNode->getDoubleValue("eda", 0.007));
98 setLife(scFileNode->getDoubleValue("life", 900.0));
99 setBuoyancy(scFileNode->getDoubleValue("buoyancy", 0));
100 //setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
101 //setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
102 setWind(scFileNode->getBoolValue("wind", false));
103 setRoll(scFileNode->getDoubleValue("roll", 0.0));
104 setCd(scFileNode->getDoubleValue("cd", 0.029));
105 //setMass(scFileNode->getDoubleValue("mass", 0.007));
106 setWeight(scFileNode->getDoubleValue("weight", 0.25));
107 setStabilisation(scFileNode->getBoolValue("aero-stabilised", false));
108 setNoRoll(scFileNode->getBoolValue("no-roll", false));
109 setImpact(scFileNode->getBoolValue("impact", false));
110 setExpiry(scFileNode->getBoolValue("expiry", false));
111 setCollision(scFileNode->getBoolValue("collision", false));
112 setImpactReportNode(scFileNode->getStringValue("impact-reports"));
113 setName(scFileNode->getStringValue("name", "Rocket"));
114 setFuseRange(scFileNode->getDoubleValue("fuse-range", 0.0));
115 setSMPath(scFileNode->getStringValue("submodel-path", ""));
116 setSubID(scFileNode->getIntValue("SubID", 0));
117 setExternalForce(scFileNode->getBoolValue("external-force", false));
118 setForcePath(scFileNode->getStringValue("force-path", ""));
119 setForceStabilisation(scFileNode->getBoolValue("force-stabilised", false));
120 setXoffset(scFileNode->getDoubleValue("x-offset", 0.0));
121 setYoffset(scFileNode->getDoubleValue("y-offset", 0.0));
122 setZoffset(scFileNode->getDoubleValue("z-offset", 0.0));
123 setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
124 setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
125 setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
126 setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
127 setLoadOffset(scFileNode->getDoubleValue("load-offset", 0.0));
128 setSlaved(scFileNode->getBoolValue("slaved", false));
129 setSlavedLoad(scFileNode->getBoolValue("slaved-load", false));
130 setContentsPath(scFileNode->getStringValue("contents"));
131 setParentName(scFileNode->getStringValue("parent"));
134 bool FGAIBallistic::init(bool search_in_AI_path) {
135 FGAIBase::init(search_in_AI_path);
140 void FGAIBallistic::reinit() {
141 _impact_reported = false;
142 _collision_reported = false;
143 _expiry_reported = false;
155 _elapsed_time += (sg_random() * 100);
159 props->setStringValue("material/name", "");
160 props->setStringValue("name", _name.c_str());
161 props->setStringValue("submodels/path", _path.c_str());
164 props->setStringValue("force/path", _force_path.c_str());
165 props->setStringValue("contents/path", _contents_path.c_str());
168 //cout << "init: name " << _name.c_str() << " _life_timer " << _life_timer
175 //setParentNodes(_selected_ac);
177 //props->setStringValue("vector/path", _vector_path.c_str());
179 // start with high value so that animations don't trigger yet
191 setParentNodes(_selected_ac);
196 void FGAIBallistic::bind() {
199 _tiedProperties.setRoot(props);
200 tie("sim/time/elapsed-sec",
201 SGRawValueMethods<FGAIBallistic,double>(*this,
202 &FGAIBallistic::_getTime, &FGAIBallistic::setTime));
204 // SGRawValueMethods<FGAIBallistic,double>(*this,
205 // &FGAIBallistic::getMass));
207 tie("material/solid",
208 SGRawValuePointer<bool>(&_solid));
209 tie("altitude-agl-ft",
210 SGRawValuePointer<double>(&_ht_agl_ft));
211 tie("controls/slave-to-ac",
212 SGRawValueMethods<FGAIBallistic,bool>
213 (*this, &FGAIBallistic::getSlaved, &FGAIBallistic::setSlaved));
214 tie("controls/invisible",
215 SGRawValuePointer<bool>(&invisible));
217 if (_external_force || _slave_to_ac) {
218 tie("controls/force_stabilized",
219 SGRawValuePointer<bool>(&_force_stabilised));
220 tie("position/global-x",
221 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosX, 0));
222 tie("position/global-y",
223 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosY, 0));
224 tie("position/global-z",
225 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getCartPosZ, 0));
226 tie("velocities/vertical-speed-fps",
227 SGRawValuePointer<double>(&vs));
228 tie("velocities/true-airspeed-kt",
229 SGRawValuePointer<double>(&speed));
230 tie("velocities/horizontal-speed-fps",
231 SGRawValuePointer<double>(&hs));
232 tie("position/altitude-ft",
233 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getElevationFt, &FGAIBase::_setAltitude));
234 tie("position/latitude-deg",
235 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLatitude, &FGAIBase::_setLatitude));
236 tie("position/longitude-deg",
237 SGRawValueMethods<FGAIBase,double>(*this, &FGAIBase::_getLongitude, &FGAIBase::_setLongitude));
238 tie("orientation/hdg-deg",
239 SGRawValuePointer<double>(&hdg));
240 tie("orientation/pitch-deg",
241 SGRawValuePointer<double>(&pitch));
242 tie("orientation/roll-deg",
243 SGRawValuePointer<double>(&roll));
244 tie("controls/slave-load-to-ac",
245 SGRawValueMethods<FGAIBallistic,bool>
246 (*this, &FGAIBallistic::getSlavedLoad, &FGAIBallistic::setSlavedLoad));
247 tie("position/load-offset",
248 SGRawValueMethods<FGAIBallistic,double>
249 (*this, &FGAIBallistic::getLoadOffset, &FGAIBallistic::setLoadOffset));
250 tie("load/distance-to-hitch-ft",
251 SGRawValueMethods<FGAIBallistic,double>
252 (*this, &FGAIBallistic::getDistanceToHitch));
253 tie("load/elevation-to-hitch-deg",
254 SGRawValueMethods<FGAIBallistic,double>
255 (*this, &FGAIBallistic::getElevToHitch));
256 tie("load/bearing-to-hitch-deg",
257 SGRawValueMethods<FGAIBallistic,double>
258 (*this, &FGAIBallistic::getBearingToHitch));
259 tie("material/load-resistance",
260 SGRawValuePointer<double>(&_load_resistance));
264 void FGAIBallistic::update(double dt)
266 FGAIBase::update(dt);
272 else if (!invisible) {
279 void FGAIBallistic::setAzimuth(double az) {
281 hdg = _azimuth = az - _az_random_error + 2 * _az_random_error * sg_random();
286 void FGAIBallistic::setAzimuthRandomError(double error) {
287 _az_random_error = error;
290 void FGAIBallistic::setElevationRandomError(double error) {
291 _el_random_error = error;
294 void FGAIBallistic::setElevation(double el) {
296 pitch = _elevation = el - _el_random_error + 2 * _el_random_error * sg_random();
298 pitch = _elevation = el;
301 void FGAIBallistic::setRoll(double rl) {
302 roll = _rotation = rl;
305 void FGAIBallistic::setStabilisation(bool val) {
306 _aero_stabilised = val;
309 void FGAIBallistic::setForceStabilisation(bool val) {
310 _force_stabilised = val;
313 void FGAIBallistic::setNoRoll(bool nr) {
317 void FGAIBallistic::setDragArea(double a) {
321 void FGAIBallistic::setLife(double seconds) {
323 life = seconds * _life_randomness + (seconds * (1 -_life_randomness) * sg_random());
328 void FGAIBallistic::setBuoyancy(double fpss) {
332 void FGAIBallistic::setWind_from_east(double fps) {
333 _wind_from_east = fps;
336 void FGAIBallistic::setWind_from_north(double fps) {
337 _wind_from_north = fps;
340 void FGAIBallistic::setWind(bool val) {
344 void FGAIBallistic::setCd(double cd) {
349 void FGAIBallistic::setCdRandomness(double randomness) {
350 _cd_randomness = randomness;
353 void FGAIBallistic::setMass(double m) {
357 void FGAIBallistic::setWeight(double w) {
361 void FGAIBallistic::setLifeRandomness(double randomness) {
362 _life_randomness = randomness;
365 void FGAIBallistic::setRandom(bool r) {
369 void FGAIBallistic::setImpact(bool i) {
373 void FGAIBallistic::setCollision(bool c) {
374 _report_collision = c;
377 void FGAIBallistic::setExpiry(bool e) {
381 void FGAIBallistic::setExternalForce(bool f) {
385 void FGAIBallistic::setImpactReportNode(const string& path) {
387 _impact_report_node = fgGetNode(path.c_str(), true);
390 void FGAIBallistic::setSMPath(const string& s) {
392 //cout << "submodel path " << _path << endl;
395 void FGAIBallistic::setFuseRange(double f) {
399 void FGAIBallistic::setSubID(int i) {
403 void FGAIBallistic::setSubmodel(const string& s) {
407 void FGAIBallistic::setGroundOffset(double g) {
411 void FGAIBallistic::setLoadOffset(double l) {
415 double FGAIBallistic::getLoadOffset() const {
419 void FGAIBallistic::setSlaved(bool s) {
423 void FGAIBallistic::setContentsPath(const string& path) {
424 _contents_path = path;
427 _contents_node = fgGetNode(path.c_str(), true);
431 void FGAIBallistic::setContentsNode(SGPropertyNode_ptr node) {
433 _contents_node = node;
434 _contents_path = _contents_node->getDisplayName();
438 void FGAIBallistic::setParentNodes(SGPropertyNode_ptr node) {
441 _p_pos_node = _pnode->getChild("position", 0, true);
442 _p_lat_node = _p_pos_node->getChild("latitude-deg", 0, true);
443 _p_lon_node = _p_pos_node->getChild("longitude-deg", 0, true);
444 _p_alt_node = _p_pos_node->getChild("altitude-ft", 0, true);
445 _p_agl_node = _p_pos_node->getChild("altitude-agl-ft", 0, true);
448 _p_ori_node = _pnode->getChild("orientation", 0, true);
449 _p_pch_node = _p_ori_node->getChild("pitch-deg", 0, true);
450 _p_rll_node = _p_ori_node->getChild("roll-deg", 0, true);
451 _p_hdg_node = _p_ori_node->getChild("true-heading-deg",0, true);
453 _p_vel_node = _pnode->getChild("velocities", 0, true);
454 _p_spd_node = _p_vel_node->getChild("true-airspeed-kt", 0, true);
458 void FGAIBallistic::setParentPos() {
460 double lat = _p_lat_node->getDoubleValue();
461 double lon = _p_lon_node->getDoubleValue();
462 double alt = _p_alt_node->getDoubleValue();
464 _parentpos.setLongitudeDeg(lon);
465 _parentpos.setLatitudeDeg(lat);
466 _parentpos.setElevationFt(alt);
470 bool FGAIBallistic::getSlaved() const {
474 double FGAIBallistic::getMass() const {
478 double FGAIBallistic::getContents() {
479 if (_contents_node) {
480 _contents_lb = _contents_node->getChild("level-lbs", 0, 1)->getDoubleValue();
485 void FGAIBallistic::setContents(double c) {
487 _contents_lb = _contents_node->getChild("level-gal_us", 0, 1)->setDoubleValue(c);
490 void FGAIBallistic::setSlavedLoad(bool l) {
491 _slave_load_to_ac = l;
494 bool FGAIBallistic::getSlavedLoad() const {
495 return _slave_load_to_ac;
498 void FGAIBallistic::setForcePath(const string& p) {
500 if (!_force_path.empty()) {
501 SGPropertyNode *fnode = fgGetNode(_force_path.c_str(), 0, true );
502 _force_node = fnode->getChild("force-lb", 0, true);
503 _force_azimuth_node = fnode->getChild("force-azimuth-deg", 0, true);
504 _force_elevation_node = fnode->getChild("force-elevation-deg", 0, true);
508 bool FGAIBallistic::getHtAGL(double start) {
509 const simgear::BVHMaterial* mat = 0;
510 if (getGroundElevationM(SGGeod::fromGeodM(pos, start),
511 _elevation_m, &mat)) {
512 const SGMaterial* material = dynamic_cast<const SGMaterial*>(mat);
513 _ht_agl_ft = pos.getElevationFt() - _elevation_m * SG_METER_TO_FEET;
516 const std::vector<string>& names = material->get_names();
517 _solid = material->get_solid();
518 _load_resistance = material->get_load_resistance();
519 _frictionFactor = material->get_friction_factor();
522 props->setStringValue("material/name", names[0].c_str());
524 props->setStringValue("material/name", "");
526 _mat_name = names[0];
528 //cout << "material " << _mat_name
529 //<< " solid " << _solid
530 //<< " load " << _load_resistance
531 //<< " frictionFactor " << _frictionFactor
542 double FGAIBallistic::getRecip(double az) {
543 // calculate the reciprocal of the input azimuth
552 void FGAIBallistic::setPch(double e, double dt, double coeff) {
553 double c = dt / (coeff + dt);
554 pitch = (e * c) + (pitch * (1 - c));
557 void FGAIBallistic::setBnk(double r, double dt, double coeff) {
558 double c = dt / (coeff + dt);
559 roll = (r * c) + (roll * (1 - c));
562 void FGAIBallistic::setSpd(double s, double dt, double coeff) {
563 double c = dt / (coeff + dt);
564 _speed = (s * c) + (_speed * (1 - c));
567 void FGAIBallistic::setHt(double h, double dt, double coeff) {
568 double c = dt / (coeff + dt);
569 _height = (h * c) + (_height * (1 - c));
572 int FGAIBallistic::setHdg(double tgt_hdg, double dt, double coeff) {
573 double recip = getRecip(hdg);
574 double c = dt / (coeff + dt);
575 //cout << "set heading " << tgt_hdg << endl;
576 //we need to ensure that we turn the short way to the new hdg
577 if (tgt_hdg < recip && tgt_hdg < hdg && hdg > 180) {
578 hdg = ((tgt_hdg + 360) * c) + (hdg * (1 - c));
579 // cout << "case 1: right turn" << endl;
580 } else if (tgt_hdg > recip && tgt_hdg > hdg && hdg <= 180){
581 hdg = ((tgt_hdg - 360) * c) + (hdg * (1 - c));
582 // cout << "case 2: left turn" << endl;
584 hdg = (tgt_hdg * c) + (hdg * (1 - c));
585 // cout << "case 4: left turn" << endl;
590 double FGAIBallistic::getTgtXOffset() const {
591 return _tgt_x_offset;
594 double FGAIBallistic::getTgtYOffset() const {
595 return _tgt_y_offset;
598 double FGAIBallistic::getTgtZOffset() const {
599 return _tgt_z_offset;
602 void FGAIBallistic::setTgtXOffset(double x) {
606 void FGAIBallistic::setTgtYOffset(double y) {
610 void FGAIBallistic::setTgtZOffset(double z) {
614 void FGAIBallistic::slaveToAC(double dt) {
618 double hdg, pch, rll;//, agl = 0;
622 hdg = _p_hdg_node->getDoubleValue();
623 pch = _p_pch_node->getDoubleValue();
624 rll = _p_rll_node->getDoubleValue();
625 // agl = _p_agl_node->getDoubleValue();
626 setOffsetPos(_parentpos, hdg, pch, rll);
627 setSpeed(_p_spd_node->getDoubleValue());
630 hdg = manager->get_user_heading();
631 pch = manager->get_user_pitch();
632 rll = manager->get_user_roll();
633 // agl = manager->get_user_agl();
634 setOffsetPos(globals->get_aircraft_position(), hdg, pch, rll);
635 setSpeed(manager->get_user_speed());
638 pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
639 pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
640 pos.setElevationFt(_offsetpos.getElevationFt());
642 setPitch(pch + _pitch_offset);
643 setBank(rll + _roll_offset);
644 setOffsetVelocity(dt, pos);
647 //update the mass (slugs)
648 _mass = (_weight_lb + getContents()) / slugs_to_lbs;
650 _impact_reported = false;
652 //cout << _name << " _mass "<<_mass <<" " << getContents()
653 //<< " " << getContents() / slugs_to_lbs << " weight " << _weight_lb << endl;
654 // cout << _name << " update hs " << hs << " vs " << vs << endl;
657 void FGAIBallistic::Run(double dt) {
661 //cout<<"AIBallistic run: name " << _name.c_str()
662 // << " dt " << dt << " _life_timer " << _life_timer << " pass " << _pass << endl;
664 // if life = -1 the object does not die
665 if (_life_timer > life && life != -1) {
666 if (_report_expiry && !_expiry_reported && !_impact_reported && !_collision_reported) {
667 //cout<<"AIBallistic run: name " << _name.c_str() << " expiry "
668 //<< " _life_timer " << _life_timer<< endl;
672 //cout<<"AIBallistic run: name " << _name.c_str()
673 // << " die " << " _life_timer " << _life_timer << endl;
680 // Set the contents in the appropriate tank or other property in the parent to zero
684 // Keep the new Cd within +- 10% of the current Cd to avoid a fluctuating value
685 double cd_min = _cd * 0.9;
686 double cd_max = _cd * 1.1;
688 // Randomize Cd by +- a certain percentage of the initial Cd
689 _cd = _init_cd * (1 - _cd_randomness + 2 * _cd_randomness * sg_random());
691 if (_cd < cd_min) _cd = cd_min;
692 if (_cd > cd_max) _cd = cd_max;
695 // Adjust Cd by Mach number. The equations are based on curves
696 // for a conventional shell/bullet (no boat-tail).
700 Cdm = 0.0125 * Mach + _cd;
702 Cdm = 0.3742 * pow(Mach, 2) - 0.252 * Mach + 0.0021 + _cd;
704 Cdm = 0.2965 * pow(Mach, -1.1506) + _cd;
706 //cout <<_name << " Mach " << Mach << " Cdm " << Cdm
707 // << " ballistic speed kts "<< speed << endl;
709 // drag = Cd * 0.5 * rho * speed * speed * drag_area;
710 // rho is adjusted for altitude in void FGAIBase::update,
711 // using Standard Atmosphere (sealevel temperature 15C)
712 // acceleration = drag/mass;
713 // adjust speed by drag
714 speed -= (Cdm * 0.5 * rho * speed * speed * _drag_area/_mass) * dt;
716 // don't let speed become negative
720 // double speed_fps = speed * SG_KT_TO_FPS;
722 // calculate vertical and horizontal speed components
725 //resolve horizontal speed into north and east components:
726 //and convert horizontal speed (fps) to degrees per second
729 // If wind not required, set to zero
731 _wind_from_north = 0;
735 _wind_from_north = manager->get_wind_from_north();
736 _wind_from_east = manager->get_wind_from_east();
739 // Calculate velocity due to external force
740 double force_speed_north_deg_sec = 0;
741 double force_speed_east_deg_sec = 0;
742 double hs_force_fps = 0;
743 double v_force_acc_fpss = 0;
744 double force_speed_north_fps = 0;
745 double force_speed_east_fps = 0;
746 double h_force_lbs = 0;
747 double normal_force_lbs = 0;
748 double normal_force_fpss = 0;
749 double static_friction_force_lbs = 0;
750 double dynamic_friction_force_lbs = 0;
751 double friction_force_speed_north_fps = 0;
752 double friction_force_speed_east_fps = 0;
753 double friction_force_speed_north_deg_sec = 0;
754 double friction_force_speed_east_deg_sec = 0;
755 double force_elevation_deg = 0;
756 double force_azimuth_deg = 0;
757 double force_lbs = 0;
759 if (_external_force) {
760 //cout << _name << " external force " << hdg << " az " << _azimuth << endl;
762 SGPropertyNode *n = fgGetNode(_force_path.c_str(), true);
763 force_lbs = n->getChild("force-lb", 0, true)->getDoubleValue();
764 force_elevation_deg = n->getChild("force-elevation-deg", 0, true)->getDoubleValue();
765 force_azimuth_deg = n->getChild("force-azimuth-deg", 0, true)->getDoubleValue();
767 // Resolve force into vertical and horizontal components:
768 double v_force_lbs = force_lbs * sin( force_elevation_deg * SG_DEGREES_TO_RADIANS );
769 h_force_lbs = force_lbs * cos( force_elevation_deg * SG_DEGREES_TO_RADIANS );
771 // Perform ground interaction if impacts are not calculated
772 if (!_report_impact && getHtAGL(10000)) {
773 double deadzone = 0.1;
775 if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid) {
776 normal_force_lbs = (_mass * slugs_to_lbs) - v_force_lbs;
778 if (normal_force_lbs < 0)
779 normal_force_lbs = 0;
781 pos.setElevationFt(0 + _ground_offset);
785 // Calculate friction. We assume a static coefficient of
786 // friction (mu) of 0.62 (wood on concrete)
789 static_friction_force_lbs = mu * normal_force_lbs * _frictionFactor;
791 // Adjust horizontal force. We assume that a speed of <= 5 fps is static
792 if (h_force_lbs <= static_friction_force_lbs && hs <= 5) {
793 h_force_lbs = hs = 0;
794 _speed_north_fps = _speed_east_fps = 0;
797 dynamic_friction_force_lbs = (static_friction_force_lbs * 0.95);
799 // Ignore wind when on the ground for now
801 _wind_from_north = 0;
806 //acceleration = (force(lbsf)/mass(slugs))
807 v_force_acc_fpss = v_force_lbs / _mass;
808 normal_force_fpss = normal_force_lbs / _mass;
809 double h_force_acc_fpss = h_force_lbs / _mass;
810 double dynamic_friction_acc_fpss = dynamic_friction_force_lbs / _mass;
812 // velocity = acceleration * dt
813 hs_force_fps = h_force_acc_fpss * dt;
814 double friction_force_fps = dynamic_friction_acc_fpss * dt;
816 //resolve horizontal speeds into north and east components:
817 force_speed_north_fps = cos(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
818 force_speed_east_fps = sin(force_azimuth_deg * SG_DEGREES_TO_RADIANS) * hs_force_fps;
820 friction_force_speed_north_fps = cos(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
821 friction_force_speed_east_fps = sin(getRecip(hdg) * SG_DEGREES_TO_RADIANS) * friction_force_fps;
823 // convert horizontal speed (fps) to degrees per second
824 force_speed_north_deg_sec = force_speed_north_fps / ft_per_deg_lat;
825 force_speed_east_deg_sec = force_speed_east_fps / ft_per_deg_lon;
827 friction_force_speed_north_deg_sec = friction_force_speed_north_fps / ft_per_deg_lat;
828 friction_force_speed_east_deg_sec = friction_force_speed_east_fps / ft_per_deg_lon;
831 // convert wind speed (fps) to degrees lat/lon per second
832 double wind_speed_from_north_deg_sec = _wind_from_north / ft_per_deg_lat;
833 double wind_speed_from_east_deg_sec = _wind_from_east / ft_per_deg_lon;
835 //recombine the horizontal velocity components
836 hs = sqrt(((_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps)
837 * (_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
838 + ((_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps)
839 * (_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps)));
844 // adjust vertical speed for acceleration of gravity, buoyancy, and vertical force
845 double gravity = SG_METER_TO_FEET * (Environment::Gravity::instance()->getGravity(pos));
846 vs -= (gravity - _buoyancy - v_force_acc_fpss - normal_force_fpss) * dt;
848 if (vs <= 0.00001 && vs >= -0.00001)
852 if (_slave_load_to_ac) {
854 manager->get_user_heading(),
855 manager->get_user_pitch(),
856 manager->get_user_roll()
858 pos.setLatitudeDeg(_offsetpos.getLatitudeDeg());
859 pos.setLongitudeDeg(_offsetpos.getLongitudeDeg());
860 pos.setElevationFt(_offsetpos.getElevationFt());
862 if (getHtAGL(10000)) {
863 double deadzone = 0.1;
865 if (_ht_agl_ft <= (0 + _ground_offset + deadzone) && _solid) {
866 pos.setElevationFt(0 + _ground_offset);
869 pos.setElevationFt(_offsetpos.getElevationFt() + _load_offset);
874 pos.setLatitudeDeg( pos.getLatitudeDeg()
875 + (speed_north_deg_sec - wind_speed_from_north_deg_sec
876 + force_speed_north_deg_sec + friction_force_speed_north_deg_sec) * dt );
877 pos.setLongitudeDeg( pos.getLongitudeDeg()
878 + (speed_east_deg_sec - wind_speed_from_east_deg_sec
879 + force_speed_east_deg_sec + friction_force_speed_east_deg_sec) * dt );
880 pos.setElevationFt(pos.getElevationFt() + vs * dt);
883 // cout << _name << " run hs " << hs << " vs " << vs << endl;
885 // recalculate total speed
886 if ( vs == 0 && hs == 0)
889 speed = sqrt( vs * vs + hs * hs) / SG_KT_TO_FPS;
891 // recalculate elevation and azimuth (velocity vectors)
892 _elevation = atan2( vs, hs ) * SG_RADIANS_TO_DEGREES;
893 _azimuth = atan2((_speed_east_fps + force_speed_east_fps + friction_force_speed_east_fps),
894 (_speed_north_fps + force_speed_north_fps + friction_force_speed_north_fps))
895 * SG_RADIANS_TO_DEGREES;
897 // rationalise azimuth
901 if (_aero_stabilised) { // we simulate rotational moment of inertia by using a filter
902 //cout<< "_aero_stabilised " << hdg << " az " << _azimuth << endl;
903 const double coeff = 0.9;
905 // we assume a symetrical MI about the pitch and yaw axis
906 setPch(_elevation, dt, coeff);
907 setHdg(_azimuth, dt, coeff);
909 else if (_force_stabilised) { // we simulate rotational moment of inertia by using a filter
910 //cout<< "_force_stabilised "<< endl;
912 const double coeff = 0.9;
913 double ratio = h_force_lbs/(_mass * slugs_to_lbs);
915 if (ratio > 1) ratio = 1;
916 if (ratio < -1) ratio = -1;
918 double force_pitch = acos(ratio) * SG_RADIANS_TO_DEGREES;
920 if (force_pitch <= force_elevation_deg)
921 force_pitch = force_elevation_deg;
923 // we assume a symetrical MI about the pitch and yaw axis
924 setPch(force_pitch,dt, coeff);
925 setHdg(_azimuth, dt, coeff);
928 // Do impacts and collisions
929 if (_report_impact && !_impact_reported)
932 if (_report_collision && !_collision_reported)
935 // Set destruction flag if altitude less than sea level -1000
936 if (altitude_ft < -1000.0 && life != -1)
940 double FGAIBallistic::_getTime() const {
944 void FGAIBallistic::setTime(double s) {
948 void FGAIBallistic::handleEndOfLife(double elevation) {
949 report_impact(elevation);
951 // Make the submodel invisible if the submodel is immortal, otherwise kill it if it has no subsubmodels
955 else if (_subID == 0) {
956 // Kill the AIObject if there is no subsubmodel
961 void FGAIBallistic::handle_impact() {
962 // Try terrain intersection
963 double start = pos.getElevationM() + 100;
965 if (!getHtAGL(start))
968 if (_ht_agl_ft <= 0) {
969 SG_LOG(SG_AI, SG_DEBUG, "AIBallistic: terrain impact material" << _mat_name);
970 _impact_reported = true;
971 handleEndOfLife(_elevation_m);
975 void FGAIBallistic::handle_expiry() {
976 _expiry_reported = true;
977 handleEndOfLife(pos.getElevationM());
980 void FGAIBallistic::handle_collision()
982 const FGAIBase *object = manager->calcCollision(pos.getElevationFt(),
983 pos.getLatitudeDeg(),pos.getLongitudeDeg(), _fuse_range);
986 report_impact(pos.getElevationM(), object);
987 _collision_reported = true;
991 void FGAIBallistic::report_impact(double elevation, const FGAIBase *object)
993 _impact_lat = pos.getLatitudeDeg();
994 _impact_lon = pos.getLongitudeDeg();
995 _impact_elev = elevation;
996 _impact_speed = speed * SG_KT_TO_MPS;
998 _impact_pitch = pitch;
1001 SGPropertyNode *n = props->getNode("impact", true);
1004 n->setStringValue("type", object->getTypeString());
1006 n->setStringValue("type", "terrain");
1008 SG_LOG(SG_AI, SG_DEBUG, "AIBallistic: object impact " << _name
1009 << " lon " <<_impact_lon << " lat " <<_impact_lat << " sec " << _life_timer);
1011 n->setDoubleValue("longitude-deg", _impact_lon);
1012 n->setDoubleValue("latitude-deg", _impact_lat);
1013 n->setDoubleValue("elevation-m", _impact_elev);
1014 n->setDoubleValue("heading-deg", _impact_hdg);
1015 n->setDoubleValue("pitch-deg", _impact_pitch);
1016 n->setDoubleValue("roll-deg", _impact_roll);
1017 n->setDoubleValue("speed-mps", _impact_speed);
1019 _impact_report_node->setStringValue(props->getPath());
1022 SGVec3d FGAIBallistic::getCartHitchPos() const {
1023 // convert geodetic positions to geocentered
1024 SGVec3d cartuserPos = globals->get_aircraft_position_cart();
1026 //SGVec3d cartPos = getCartPos();
1028 // Transform to the right coordinate frame, configuration is done in
1029 // the x-forward, y-right, z-up coordinates (feet), computation
1030 // in the simulation usual body x-forward, y-right, z-down coordinates
1032 SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1033 _y_offset * SG_FEET_TO_METER,
1034 -_z_offset * SG_FEET_TO_METER);
1036 // Transform the user position to the horizontal local coordinate system.
1037 SGQuatd hlTrans = SGQuatd::fromLonLat(globals->get_aircraft_position());
1039 // and postrotate the orientation of the user model wrt the horizontal
1041 hlTrans *= SGQuatd::fromYawPitchRollDeg(
1042 manager->get_user_heading(),
1043 manager->get_user_pitch(),
1044 manager->get_user_roll());
1046 // The offset converted to the usual body fixed coordinate system
1047 // rotated to the earth-fixed coordinates axis
1048 SGVec3d off = hlTrans.backTransform(_off);
1050 // Add the position offset of the user model to get the geocentered position
1051 SGVec3d offsetPos = cartuserPos + off;
1055 void FGAIBallistic::setOffsetPos(SGGeod inpos, double heading, double pitch, double roll) {
1056 // Convert the hitch geocentered position to geodetic
1057 SGVec3d cartoffsetPos = getCartOffsetPos(inpos, heading, pitch, roll);
1058 SGGeodesy::SGCartToGeod(cartoffsetPos, _offsetpos);
1061 double FGAIBallistic::getDistanceToHitch() const {
1062 //calculate the distance load to hitch
1063 SGVec3d carthitchPos = getCartHitchPos();
1064 SGVec3d cartPos = getCartPos();
1066 SGVec3d diff = carthitchPos - cartPos;
1067 double distance = norm(diff);
1068 return distance * SG_METER_TO_FEET;
1071 double FGAIBallistic::getElevToHitch() const {
1072 // now the angle, positive angles are upwards
1073 double distance = getDistanceToHitch() * SG_FEET_TO_METER;
1075 double daltM = _offsetpos.getElevationM() - pos.getElevationM();
1077 if (fabs(distance) < SGLimits<float>::min()) {
1080 double sAngle = daltM/distance;
1081 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1082 angle = SGMiscd::rad2deg(asin(sAngle));
1088 double FGAIBallistic::getBearingToHitch() const {
1089 //calculate the bearing and range of the second pos from the first
1090 double distance = getDistanceToHitch() * SG_FEET_TO_METER;
1093 geo_inverse_wgs_84(pos, _offsetpos, &az1, &az2, &distance);
1098 double FGAIBallistic::getRelBrgHitchToUser() const {
1099 //calculate the relative bearing
1100 double az1, az2, distance;
1102 geo_inverse_wgs_84(_offsetpos, globals->get_aircraft_position(), &az1, &az2, &distance);
1104 double rel_brg = az1 - hdg;
1106 SG_NORMALIZE_RANGE(rel_brg, -180.0, 180.0);
1111 double FGAIBallistic::getElevHitchToUser() const {
1112 // Calculate the distance from the user position
1113 SGVec3d carthitchPos = getCartHitchPos();
1114 SGVec3d cartuserPos = globals->get_aircraft_position_cart();
1116 SGVec3d diff = cartuserPos - carthitchPos;
1118 double distance = norm(diff);
1121 double daltM = globals->get_aircraft_position().getElevationM() - _offsetpos.getElevationM();
1123 // Now the angle, positive angles are upwards
1124 if (fabs(distance) < SGLimits<float>::min()) {
1128 double sAngle = daltM/distance;
1129 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1130 angle = SGMiscd::rad2deg(asin(sAngle));
1136 void FGAIBallistic::setTgtOffsets(double dt, double coeff) {
1137 double c = dt / (coeff + dt);
1139 _x_offset = (_tgt_x_offset * c) + (_x_offset * (1 - c));
1140 _y_offset = (_tgt_y_offset * c) + (_y_offset * (1 - c));
1141 _z_offset = (_tgt_z_offset * c) + (_z_offset * (1 - c));
1144 void FGAIBallistic::calcVSHS() {
1145 // Calculate vertical and horizontal speed components
1146 double speed_fps = speed * SG_KT_TO_FPS;
1152 vs = sin( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1153 hs = cos( _elevation * SG_DEGREES_TO_RADIANS ) * speed_fps;
1157 void FGAIBallistic::calcNE() {
1158 // Resolve horizontal speed into north and east components:
1159 _speed_north_fps = cos(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1160 _speed_east_fps = sin(_azimuth / SG_RADIANS_TO_DEGREES) * hs;
1162 // Convert horizontal speed (fps) to degrees per second
1163 speed_north_deg_sec = _speed_north_fps / ft_per_deg_lat;
1164 speed_east_deg_sec = _speed_east_fps / ft_per_deg_lon;
1167 SGVec3d FGAIBallistic::getCartOffsetPos(SGGeod inpos, double user_heading,
1168 double user_pitch, double user_roll
1170 // Convert geodetic positions to geocentered
1171 SGVec3d cartuserPos = SGVec3d::fromGeod(inpos);
1173 // Transform to the right coordinate frame, configuration is done in
1174 // the x-forward, y-right, z-up coordinates (feet), computation
1175 // in the simulation usual body x-forward, y-right, z-down coordinates
1177 SGVec3d _off(_x_offset * SG_FEET_TO_METER,
1178 _y_offset * SG_FEET_TO_METER,
1179 -_z_offset * SG_FEET_TO_METER);
1181 // Transform the user position to the horizontal local coordinate system.
1182 SGQuatd hlTrans = SGQuatd::fromLonLat(inpos);
1184 // And postrotate the orientation of the user model wrt the horizontal
1186 hlTrans *= SGQuatd::fromYawPitchRollDeg(
1191 // The offset converted to the usual body fixed coordinate system
1192 // rotated to the earth-fixed coordinates axis
1193 SGVec3d off = hlTrans.backTransform(_off);
1195 // Add the position offset of the user model to get the geocentered position
1196 SGVec3d offsetPos = cartuserPos + off;
1201 void FGAIBallistic::setOffsetVelocity(double dt, SGGeod offsetpos) {
1202 // Calculate the distance from the previous offset position
1203 SGVec3d cartoffsetPos = SGVec3d::fromGeod(offsetpos);
1204 SGVec3d diff = cartoffsetPos - _oldcartoffsetPos;
1206 double distance = norm(diff);
1207 // Calculate speed knots
1208 speed = (distance / dt) * SG_MPS_TO_KT;
1210 // Now calulate the angle between the old and current postion positions (degrees)
1212 double daltM = offsetpos.getElevationM() - _oldoffsetpos.getElevationM();
1214 if (fabs(distance) < SGLimits<float>::min()) {
1218 double sAngle = daltM / distance;
1219 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
1220 angle = SGMiscd::rad2deg(asin(sAngle));
1225 // Calculate vertical and horizontal speed components
1228 // Calculate the bearing of the new offset position from the old
1229 // Don't do this if speed is low
1230 //cout << "speed " << speed << endl;
1232 double az1, az2, dist;
1233 geo_inverse_wgs_84(_oldoffsetpos, offsetpos, &az1, &az2, &dist);
1235 //cout << "offset az " << _azimuth << endl;
1239 //cout << " slow offset az " << _azimuth << endl;
1242 // Resolve horizontal speed into north and east components
1245 // And finally store the new values
1246 _oldcartoffsetPos = cartoffsetPos;
1247 _oldoffsetpos = offsetpos;