1 // FGAIShip - FGAIBase-derived class creates an AI ship
3 // Written by David Culp, started October 2003.
4 // with major amendments and additions by Vivian Meazza, 2004 - 2007
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License as
8 // published by the Free Software Foundation; either version 2 of the
9 // License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
28 double fgIsFinite(double x) { return _finite(x); }
30 double fgIsFinite(double x) { return std::isfinite(x); }
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/timing/sg_time.hxx>
36 #include <simgear/math/sg_random.h>
38 #include <simgear/scene/util/SGNodeMasks.hxx>
39 #include <Scenery/scenery.hxx>
45 FGAIShip::FGAIShip(object_type ot) :
46 // allow HOT to be enabled
53 _initial_tunnel(false),
64 _roll_constant(0.001),
65 _roll_factor(-0.0083335),
81 FGAIShip::~FGAIShip() {
84 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
89 FGAIBase::readFromScenario(scFileNode);
91 setRudder(scFileNode->getFloatValue("rudder", 0.0));
92 setName(scFileNode->getStringValue("name", "Titanic"));
93 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
94 const std::string& flightplan = scFileNode->getStringValue("flightplan");
95 setRepeat(scFileNode->getBoolValue("repeat", false));
96 setRestart(scFileNode->getBoolValue("restart", false));
97 setStartTime(scFileNode->getStringValue("time", ""));
98 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
99 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
100 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
101 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
102 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
103 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
104 setSMPath(scFileNode->getStringValue("submodel-path", ""));
105 setRollFactor(scFileNode->getDoubleValue("roll-factor", 1));
107 if (!flightplan.empty()) {
108 SG_LOG(SG_AI, SG_ALERT, "getting flightplan: " << _name );
110 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
116 bool FGAIShip::init(bool search_in_AI_path) {
118 return FGAIBase::init(search_in_AI_path);
121 void FGAIShip::reinit()
123 prev = 0; // the one behind you
124 curr = 0; // the one ahead
125 next = 0; // the next plus 1
127 props->setStringValue("name", _name.c_str());
128 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
129 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
130 props->setStringValue("waypoint/name-next", _next_name.c_str());
131 props->setStringValue("submodels/path", _path.c_str());
132 props->setStringValue("waypoint/start-time", _start_time.c_str());
133 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
139 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
142 _fp_init = initFlightPlan();
147 void FGAIShip::bind() {
150 tie("surface-positions/rudder-pos-deg",
151 SGRawValuePointer<float>(&_rudder));
152 tie("controls/heading-lock",
153 SGRawValuePointer<bool>(&_hdg_lock));
154 tie("controls/tgt-speed-kts",
155 SGRawValuePointer<double>(&tgt_speed));
156 tie("controls/tgt-heading-degs",
157 SGRawValuePointer<double>(&tgt_heading));
158 tie("controls/constants/rudder",
159 SGRawValuePointer<double>(&_rudder_constant));
160 tie("controls/constants/roll-factor",
161 SGRawValuePointer<double>(&_roll_factor));
162 tie("controls/constants/roll",
163 SGRawValuePointer<double>(&_roll_constant));
164 tie("controls/constants/rudder",
165 SGRawValuePointer<double>(&_rudder_constant));
166 tie("controls/constants/speed",
167 SGRawValuePointer<double>(&_speed_constant));
168 tie("waypoint/range-nm",
169 SGRawValuePointer<double>(&_wp_range));
170 tie("waypoint/brg-deg",
171 SGRawValuePointer<double>(&_course));
172 tie("waypoint/rangerate-nm-sec",
173 SGRawValuePointer<double>(&_range_rate));
175 SGRawValuePointer<bool>(&_new_waypoint));
176 tie("waypoint/missed",
177 SGRawValuePointer<bool>(&_missed));
178 tie("waypoint/missed-count-sec",
179 SGRawValuePointer<double>(&_missed_count));
180 tie("waypoint/missed-range-nm",
181 SGRawValuePointer<double>(&_missed_range));
182 tie("waypoint/missed-time-sec",
183 SGRawValuePointer<double>(&_missed_time_sec));
184 tie("waypoint/wait-count-sec",
185 SGRawValuePointer<double>(&_wait_count));
186 tie("waypoint/xtrack-error-ft",
187 SGRawValuePointer<double>(&_xtrack_error));
188 tie("waypoint/waiting",
189 SGRawValuePointer<bool>(&_waiting));
190 tie("waypoint/lead-angle-deg",
191 SGRawValuePointer<double>(&_lead_angle));
192 tie("waypoint/tunnel",
193 SGRawValuePointer<bool>(&_tunnel));
194 tie("waypoint/alt-curr-m",
195 SGRawValuePointer<double>(&_curr_alt));
196 tie("waypoint/alt-prev-m",
197 SGRawValuePointer<double>(&_prev_alt));
198 tie("submodels/serviceable",
199 SGRawValuePointer<bool>(&_serviceable));
200 tie("controls/turn-radius-ft",
201 SGRawValuePointer<double>(&turn_radius_ft));
202 tie("controls/turn-radius-corrected-ft",
203 SGRawValuePointer<double>(&_rd_turn_radius_ft));
204 tie("controls/constants/lead-angle/gain",
205 SGRawValuePointer<double>(&_lead_angle_gain));
206 tie("controls/constants/lead-angle/limit-deg",
207 SGRawValuePointer<double>(&_lead_angle_limit));
208 tie("controls/constants/lead-angle/proportion",
209 SGRawValuePointer<double>(&_proportion));
210 tie("controls/fixed-turn-radius-ft",
211 SGRawValuePointer<double>(&_fixed_turn_radius));
212 tie("controls/restart",
213 SGRawValuePointer<bool>(&_restart));
214 tie("velocities/speed-kts",
215 SGRawValuePointer<double>(&speed));
218 void FGAIShip::update(double dt) {
219 //SG_LOG(SG_AI, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
220 // For computation of rotation speeds we just use finite differences here.
221 // That is perfectly valid since this thing is not driven by accelerations
222 // but by just apply discrete changes at its velocity variables.
223 // Update the velocity information stored in those nodes.
224 // Transform that one to the horizontal local coordinate system.
225 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
226 // The orientation of the ship wrt the horizontal local frame
227 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
228 // and postrotate the orientation of the AIModel wrt the horizontal
230 SGQuatd ec2body = ec2hl*hl2body;
231 // The cartesian position of the ship in the wgs84 world
232 //SGVec3d cartPos = SGVec3d::fromGeod(pos);
234 // The simulation time this transform is meant for
235 aip.setReferenceTime(globals->get_sim_time_sec());
237 // Compute the velocity in m/s in the body frame
238 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
240 FGAIBase::update(dt);
246 // Only change these values if we are able to compute them safely
247 if (SGLimits<double>::min() < dt) {
248 // Now here is the finite difference ...
250 // Transform that one to the horizontal local coordinate system.
251 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
252 // compute the new orientation
253 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
254 // The rotation difference
255 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
256 SGVec3d dOrAngleAxis;
257 dOr.getAngleAxis(dOrAngleAxis);
258 // divided by the time difference provides a rotation speed vector
261 aip.setBodyAngularVelocity(dOrAngleAxis);
265 void FGAIShip::Run(double dt) {
267 ProcessFlightPlan(dt);
269 const string& type = getTypeString();
276 double speed_diff = tgt_speed - speed;
278 if (fabs(speed_diff) > 0.1) {
280 if (speed_diff > 0.0)
281 speed += _speed_constant * dt;
283 if (speed_diff < 0.0)
284 speed -= _speed_constant * dt;
288 // do not allow unreasonable speeds
289 SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
291 // convert speed to degrees per second
292 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
293 * speed * 1.686 / ft_per_deg_lat;
294 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
295 * speed * 1.686 / ft_per_deg_lon;
298 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
299 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
300 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
301 pos.setElevationFt(tgt_altitude_ft);
304 // adjust heading based on current _rudder angle
305 if (turn_radius_ft <= 0)
306 turn_radius_ft = 0; // don't allow nonsense values
315 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
316 if(type == "ship" || type == "carrier" || type == "escort"){
319 _sp_turn_radius_ft = _fixed_turn_radius;
321 // adjust turn radius for speed. The equation is very approximate.
322 // we need to allow for negative speeds
323 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
328 if (fabs(speed) <= 40)
329 _sp_turn_radius_ft = _fixed_turn_radius;
331 // adjust turn radius for speed.
332 _sp_turn_radius_ft = turn_radius_ft;
337 if (_rudder <= -0.25 || _rudder >= 0.25) {
338 // adjust turn radius for _rudder angle. The equation is even more approximate.
343 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
345 // calculate the angle, alpha, subtended by the arc traversed in time dt
346 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
347 //cout << _name << " alpha " << alpha << endl;
348 // make sure that alpha is applied in the right direction
349 hdg += alpha * sign(_rudder);
351 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
353 //adjust roll for rudder angle and speed. Another bit of voodoo
354 raw_roll = _roll_factor * speed * _rudder;
356 // _rudder angle is 0
364 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
366 // adjust target _rudder angle if heading lock engaged
367 double rudder_diff = 0.0;
369 double rudder_sense = 0.0;
370 double diff = fabs(hdg - tgt_heading);
371 //cout << "_rudder diff" << diff << endl;
373 diff = fabs(diff - 360);
375 double sum = hdg + diff;
380 if (fabs(sum - tgt_heading)< 1.0)
386 rudder_sense = -rudder_sense;
389 _tgt_rudder = diff * rudder_sense;
391 _tgt_rudder = 45 * rudder_sense;
393 rudder_diff = _tgt_rudder - _rudder;
396 // set the _rudder limit by speed
397 if (type == "ship" || type == "carrier" || type == "escort"){
400 rudder_limit = (-0.825 * speed) + 35;
407 if (fabs(rudder_diff)> 0.1) { // apply dead zone
409 if (rudder_diff > 0.0) {
410 _rudder += _rudder_constant * dt;
412 if (_rudder > rudder_limit) // apply the _rudder limit
413 _rudder = rudder_limit;
415 } else if (rudder_diff < 0.0) {
416 _rudder -= _rudder_constant * dt;
418 if (_rudder < -rudder_limit)
419 _rudder = -rudder_limit;
423 // do calculations for radar
424 UpdateRadar(manager);
428 void FGAIShip::AccelTo(double speed) {
432 void FGAIShip::PitchTo(double angle) {
436 void FGAIShip::RollTo(double angle) {
440 void FGAIShip::YawTo(double angle) {
443 void FGAIShip::ClimbTo(double altitude) {
444 tgt_altitude_ft = altitude;
445 _setAltitude(altitude);
448 void FGAIShip::TurnTo(double heading) {
449 tgt_heading = heading - _lead_angle + _tow_angle;
450 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
454 double FGAIShip::sign(double x) {
461 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
465 void FGAIShip::setStartTime(const string& st) {
469 void FGAIShip::setUntilTime(const string& ut) {
471 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
474 void FGAIShip::setCurrName(const string& c) {
476 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
479 void FGAIShip::setNextName(const string& n) {
481 props->setStringValue("waypoint/name-next", _next_name.c_str());
484 void FGAIShip::setPrevName(const string& p) {
486 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
489 void FGAIShip::setRepeat(bool r) {
493 void FGAIShip::setRestart(bool r) {
497 void FGAIShip::setMissed(bool m) {
499 props->setBoolValue("waypoint/missed", _missed);
502 void FGAIShip::setRudder(float r) {
506 void FGAIShip::setRoll(double rl) {
510 void FGAIShip::setLeadAngleGain(double g) {
511 _lead_angle_gain = g;
514 void FGAIShip::setLeadAngleLimit(double l) {
515 _lead_angle_limit = l;
518 void FGAIShip::setLeadAngleProp(double p) {
522 void FGAIShip::setRudderConstant(double rc) {
523 _rudder_constant = rc;
526 void FGAIShip::setSpeedConstant(double sc) {
527 _speed_constant = sc;
530 void FGAIShip::setFixedTurnRadius(double ftr) {
531 _fixed_turn_radius = ftr;
534 void FGAIShip::setRollFactor(double rf) {
535 _roll_factor = rf * -0.0083335;
538 void FGAIShip::setInitialTunnel(bool t) {
540 setTunnel(_initial_tunnel);
543 void FGAIShip::setTunnel(bool t) {
547 void FGAIShip::setWPNames() {
550 setPrevName(prev->getName());
555 setCurrName(curr->getName());
558 SG_LOG(SG_AI, SG_ALERT, "AIShip: current wp name error" );
562 setNextName(next->getName());
566 SG_LOG(SG_AI, SG_DEBUG, "AIShip: prev wp name " << prev->getName());
567 SG_LOG(SG_AI, SG_DEBUG, "AIShip: current wp name " << curr->getName());
568 SG_LOG(SG_AI, SG_DEBUG, "AIShip: next wp name " << next->getName());
572 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
574 double course, distance, az2;
576 //calculate the bearing and range of the second pos from the first
577 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
578 distance *= SG_METER_TO_NM;
582 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
584 double course, distance, recip;
586 //calculate the bearing and range of the second pos from the first
587 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
588 if (tgt_speed >= 0) {
590 SG_LOG(SG_AI, SG_DEBUG, "AIShip: course " << course);
593 SG_LOG(SG_AI, SG_DEBUG, "AIShip: recip " << recip);
597 void FGAIShip::ProcessFlightPlan(double dt) {
599 if ( dt < 0.00001 ) {
603 double time_sec = getDaySeconds();
607 ///////////////////////////////////////////////////////////////////////////
608 // Check Execution time (currently once every 1 sec)
609 // Add a bit of randomization to prevent the execution of all flight plans
610 // in synchrony, which can add significant periodic framerate flutter.
611 ///////////////////////////////////////////////////////////////////////////
613 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
614 if (_dt_count < _next_run && _start_sec < time_sec)
617 _next_run = 0.05 + (0.025 * sg_random());
619 double until_time_sec = 0;
622 // check to see if we've reached the point for our next turn
623 // if the range to the waypoint is less than the calculated turn
624 // radius we can start the turn to the next leg
625 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
626 _range_rate = (_wp_range - _old_range) / _dt_count;
627 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
628 // we need to try to identify a _missed waypoint
630 // calculate the time needed to turn through an arc of 90 degrees,
631 // and allow a time error
633 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
635 _missed_time_sec = 10;
637 _missed_range = 4 * sp_turn_radius_nm;
639 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
640 //if ((_range_rate > 0) && !_new_waypoint){
641 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
642 _missed_count += _dt_count;
645 if (_missed_count >= 120)
647 else if (_missed_count >= _missed_time_sec)
652 _old_range = _wp_range;
655 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
657 if (_next_name == "TUNNEL"){
660 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " " << sp_turn_radius_nm );
662 fp->IncrementWaypoint(false);
663 next = fp->getNextWaypoint();
665 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
666 || next->getName() == "END" || next->getName() == "TUNNEL")
670 fp->IncrementWaypoint(false);
671 curr = fp->getCurrentWaypoint();
672 next = fp->getNextWaypoint();
674 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
677 SG_LOG(SG_AI, SG_INFO, "AIShip: "<< _name << " Flightplan repeating ");
680 curr = fp->getCurrentWaypoint();
681 next = fp->getNextWaypoint();
683 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
684 _old_range = _wp_range;
686 _new_waypoint = true;
689 AccelTo(prev->getSpeed());
690 } else if (_restart){
691 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " Flightplan restarting ");
695 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
701 } else if (_next_name == "WAIT") {
703 if (_wait_count < next->getTime_sec()) {
704 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " waiting ");
707 _wait_count += _dt_count;
712 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name
713 << " wait done: getting new waypoints ");
716 fp->IncrementWaypoint(false);
717 next = fp->getNextWaypoint();
719 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
720 || next->getName() == "END" || next->getName() == "TUNNEL")
724 fp->IncrementWaypoint(false);
725 curr = fp->getCurrentWaypoint();
726 next = fp->getNextWaypoint();
729 } else if (_next_name == "WAITUNTIL") {
730 time_sec = getDaySeconds();
731 until_time_sec = processTimeString(next->getTime());
732 _until_time = next->getTime();
733 setUntilTime(next->getTime());
734 if (until_time_sec > time_sec) {
735 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " "
736 << curr->getName() << " waiting until: "
737 << _until_time << " " << until_time_sec << " now " << time_sec );
743 SG_LOG(SG_AI, SG_INFO, "AIShip: "
744 << _name << " wait until done: getting new waypoints ");
746 fp->IncrementWaypoint(false);
748 while (next->getName() == "WAITUNTIL") {
749 fp->IncrementWaypoint(false);
750 next = fp->getNextWaypoint();
753 if (next->getName() == "WAIT")
757 fp->IncrementWaypoint(false);
758 curr = fp->getCurrentWaypoint();
759 next = fp->getNextWaypoint();
764 //now reorganise the waypoints, so that next becomes current and so on
765 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
766 fp->IncrementWaypoint(false);
767 prev = fp->getPreviousWaypoint(); //first waypoint
768 curr = fp->getCurrentWaypoint(); //second waypoint
769 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
773 _new_waypoint = true;
777 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
778 _old_range = _wp_range;
780 object_type type = getType();
783 AccelTo(prev->getSpeed());
785 _curr_alt = curr->getAltitude();
786 _prev_alt = prev->getAltitude();
789 _new_waypoint = false;
792 // now revise the required course for the next way point
793 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
795 if (fgIsFinite(_course))
798 SG_LOG(SG_AI, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
801 } // end Processing FlightPlan
803 bool FGAIShip::initFlightPlan() {
805 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
809 _tunnel = _initial_tunnel;
812 fp->IncrementWaypoint(false);
814 prev = fp->getPreviousWaypoint(); //first waypoint
815 curr = fp->getCurrentWaypoint(); //second waypoint
816 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
818 while (curr->getName() == "WAIT" || curr->getName() == "WAITUNTIL") { // don't wait when initialising
819 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
820 fp->IncrementWaypoint(false);
821 curr = fp->getCurrentWaypoint();
822 next = fp->getNextWaypoint();
825 if (!_start_time.empty()){
826 _start_sec = processTimeString(_start_time);
827 double day_sec = getDaySeconds();
829 if (_start_sec < day_sec){
830 //cout << "flight plan has already started " << _start_time << endl;
831 init = advanceFlightPlan(_start_sec, day_sec);
833 } else if (_start_sec > day_sec && _repeat) {
834 //cout << "flight plan has not started, " << _start_time;
835 //cout << "offsetting start time by -24 hrs" << endl;
837 init = advanceFlightPlan(_start_sec, day_sec);
841 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
844 fp->IncrementWaypoint(false);
845 prev = fp->getPreviousWaypoint();
846 curr = fp->getCurrentWaypoint();
847 next = fp->getNextWaypoint();
852 setLatitude(prev->getLatitude());
853 setLongitude(prev->getLongitude());
854 setSpeed(prev->getSpeed());
858 setHeading(getCourse(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude()));
859 _wp_range = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
860 _old_range = _wp_range;
865 _new_waypoint = true;
867 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
876 } // end of initialization
879 double FGAIShip::processTimeString(const string& theTime) {
885 // first split theTime string into
886 // hour, minute, second and convert to int;
887 Hour = atoi(theTime.substr(0,2).c_str());
888 Minute = atoi(theTime.substr(3,5).c_str());
889 Second = atoi(theTime.substr(6,8).c_str());
891 // offset by a day-sec to allow for starting a day earlier
892 double time_seconds = Hour * 3600
899 double FGAIShip::getDaySeconds () {
901 struct tm *t = globals->get_time_params()->getGmt();
903 double day_seconds = t->tm_hour * 3600
910 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
912 double elapsed_sec = start_sec;
913 double distance_nm = 0;
915 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
917 while ( elapsed_sec < day_sec ) {
919 if (next->getName() == "END" || fp->getNextWaypoint() == 0) {
922 //cout << _name << ": " << "restarting flightplan" << endl;
924 curr = fp->getCurrentWaypoint();
925 next = fp->getNextWaypoint();
927 //cout << _name << ": " << "ending flightplan" << endl;
932 } else if (next->getName() == "WAIT") {
933 //cout << _name << ": begin WAIT: " << prev->name << " ";
934 //cout << curr->name << " " << next->name << endl;
936 elapsed_sec += next->getTime_sec();
938 if ( elapsed_sec >= day_sec)
941 fp->IncrementWaypoint(false);
942 next = fp->getNextWaypoint();
944 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT"
945 && next->getName() != "END") {
947 fp->IncrementWaypoint(false);
948 curr = fp->getCurrentWaypoint();
949 next = fp->getNextWaypoint();
952 } else if (next->getName() == "WAITUNTIL") {
953 double until_sec = processTimeString(next->getTime());
955 if (until_sec > _start_sec && start_sec < 0)
958 if (elapsed_sec < until_sec)
959 elapsed_sec = until_sec;
961 if (elapsed_sec >= day_sec )
964 fp->IncrementWaypoint(false);
965 next = fp->getNextWaypoint();
967 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT") {
969 fp->IncrementWaypoint(false);
970 curr = fp->getCurrentWaypoint();
971 next = fp->getNextWaypoint();
974 //cout << _name << ": end WAITUNTIL: ";
975 //cout << prev->name << " " << curr->name << " " << next->name << endl;
978 distance_nm = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
979 elapsed_sec += distance_nm * 60 * 60 / prev->getSpeed();
981 if (elapsed_sec >= day_sec)
984 fp->IncrementWaypoint(false);
985 prev = fp->getPreviousWaypoint();
986 curr = fp->getCurrentWaypoint();
987 next = fp->getNextWaypoint();
992 // the required position lies between the previous and current waypoints
993 // so we will calculate the distance back up the track from the current waypoint
994 // then calculate the lat and lon.
996 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
997 // << " " << day_sec << endl;
999 double time_diff = elapsed_sec - day_sec;
1000 double lat, lon, recip;
1002 //cout << " time diff " << time_diff << endl;
1004 if (next->getName() == "WAIT" ){
1006 lat = curr->getLatitude();
1007 lon = curr->getLongitude();
1008 _wait_count= time_diff;
1010 } else if (next->getName() == "WAITUNTIL") {
1012 lat = curr->getLatitude();
1013 lon = curr->getLongitude();
1016 setSpeed(prev->getSpeed());
1017 distance_nm = speed * time_diff / (60 * 60);
1018 double brg = getCourse(curr->getLatitude(), curr->getLongitude(), prev->getLatitude(), prev->getLongitude());
1020 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1021 // << " lat " << curr->latitude << " lon " << curr->longitude
1022 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1024 lat = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1025 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1026 lon = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1027 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1028 recip = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1029 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1038 void FGAIShip::setWPPos() {
1040 if (curr->getName() == "END" || curr->getName() == "WAIT"
1041 || curr->getName() == "WAITUNTIL" || curr->getName() == "TUNNEL"){
1042 //cout << curr->name << " returning" << endl;
1046 double elevation_m = 0;
1047 wppos.setLatitudeDeg(curr->getLatitude());
1048 wppos.setLongitudeDeg(curr->getLongitude());
1049 wppos.setElevationM(0);
1051 if (curr->getOn_ground()){
1053 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1054 elevation_m, NULL, 0)){
1055 wppos.setElevationM(elevation_m);
1058 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1061 wppos.setElevationM(curr->getAltitude());
1062 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1065 curr->setAltitude(wppos.getElevationM());
1069 void FGAIShip::setXTrackError() {
1071 double course = getCourse(prev->getLatitude(), prev->getLongitude(),
1072 curr->getLatitude(), curr->getLongitude());
1073 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1074 curr->getLatitude(), curr->getLongitude());
1075 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1076 double factor = -0.0045 * speed + 1;
1077 double limit = _lead_angle_limit * factor;
1080 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1084 _lead_angle *= _lead_angle_gain * factor;
1085 _xtrack_error = xtrack_error_nm * 6076.1155;
1087 SG_CLAMP_RANGE(_lead_angle, -limit, limit);