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.
26 # define finite _finite
27 #elif defined(__sun) || defined(sgi)
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>
44 FGAIShip::FGAIShip(object_type ot) :
45 // allow HOT to be enabled
52 _initial_tunnel(false),
63 _roll_constant(0.001),
64 _roll_factor(-0.0083335),
80 FGAIShip::~FGAIShip() {
83 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
88 FGAIBase::readFromScenario(scFileNode);
90 setRudder(scFileNode->getFloatValue("rudder", 0.0));
91 setName(scFileNode->getStringValue("name", "Titanic"));
92 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
93 std::string flightplan = scFileNode->getStringValue("flightplan");
94 setRepeat(scFileNode->getBoolValue("repeat", false));
95 setRestart(scFileNode->getBoolValue("restart", false));
96 setStartTime(scFileNode->getStringValue("time", ""));
97 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
98 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
99 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
100 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
101 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
102 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
103 setSMPath(scFileNode->getStringValue("submodel-path", ""));
105 if (!flightplan.empty()) {
106 SG_LOG(SG_GENERAL, SG_ALERT, "getting flightplan: " << _name );
108 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
114 bool FGAIShip::init(bool search_in_AI_path) {
115 prev = 0; // the one behind you
116 curr = 0; // the one ahead
117 next = 0; // the next plus 1
119 props->setStringValue("name", _name.c_str());
120 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
121 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
122 props->setStringValue("waypoint/name-next", _next_name.c_str());
123 props->setStringValue("submodels/path", _path.c_str());
124 props->setStringValue("waypoint/start-time", _start_time.c_str());
125 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
131 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
134 _fp_init = initFlightPlan();
136 return FGAIBase::init(search_in_AI_path);
139 void FGAIShip::bind() {
142 props->tie("surface-positions/rudder-pos-deg",
143 SGRawValuePointer<float>(&_rudder));
144 props->tie("controls/heading-lock",
145 SGRawValuePointer<bool>(&_hdg_lock));
146 props->tie("controls/tgt-speed-kts",
147 SGRawValuePointer<double>(&tgt_speed));
148 props->tie("controls/tgt-heading-degs",
149 SGRawValuePointer<double>(&tgt_heading));
150 props->tie("controls/constants/rudder",
151 SGRawValuePointer<double>(&_rudder_constant));
152 props->tie("controls/constants/roll-factor",
153 SGRawValuePointer<double>(&_roll_factor));
154 props->tie("controls/constants/roll",
155 SGRawValuePointer<double>(&_roll_constant));
156 props->tie("controls/constants/rudder",
157 SGRawValuePointer<double>(&_rudder_constant));
158 props->tie("controls/constants/speed",
159 SGRawValuePointer<double>(&_speed_constant));
160 props->tie("waypoint/range-nm",
161 SGRawValuePointer<double>(&_wp_range));
162 props->tie("waypoint/brg-deg",
163 SGRawValuePointer<double>(&_course));
164 props->tie("waypoint/rangerate-nm-sec",
165 SGRawValuePointer<double>(&_range_rate));
166 props->tie("waypoint/new",
167 SGRawValuePointer<bool>(&_new_waypoint));
168 props->tie("waypoint/missed",
169 SGRawValuePointer<bool>(&_missed));
170 props->tie("waypoint/missed-count-sec",
171 SGRawValuePointer<double>(&_missed_count));
172 props->tie("waypoint/missed-range-nm",
173 SGRawValuePointer<double>(&_missed_range));
174 props->tie("waypoint/missed-time-sec",
175 SGRawValuePointer<double>(&_missed_time_sec));
176 props->tie("waypoint/wait-count-sec",
177 SGRawValuePointer<double>(&_wait_count));
178 props->tie("waypoint/xtrack-error-ft",
179 SGRawValuePointer<double>(&_xtrack_error));
180 props->tie("waypoint/waiting",
181 SGRawValuePointer<bool>(&_waiting));
182 props->tie("waypoint/lead-angle-deg",
183 SGRawValuePointer<double>(&_lead_angle));
184 props->tie("waypoint/tunnel",
185 SGRawValuePointer<bool>(&_tunnel));
186 props->tie("waypoint/alt-curr-m",
187 SGRawValuePointer<double>(&_curr_alt));
188 props->tie("waypoint/alt-prev-m",
189 SGRawValuePointer<double>(&_prev_alt));
190 props->tie("submodels/serviceable",
191 SGRawValuePointer<bool>(&_serviceable));
192 props->tie("controls/turn-radius-ft",
193 SGRawValuePointer<double>(&turn_radius_ft));
194 props->tie("controls/turn-radius-corrected-ft",
195 SGRawValuePointer<double>(&_rd_turn_radius_ft));
196 props->tie("controls/constants/lead-angle/gain",
197 SGRawValuePointer<double>(&_lead_angle_gain));
198 props->tie("controls/constants/lead-angle/limit-deg",
199 SGRawValuePointer<double>(&_lead_angle_limit));
200 props->tie("controls/constants/lead-angle/proportion",
201 SGRawValuePointer<double>(&_proportion));
202 props->tie("controls/fixed-turn-radius-ft",
203 SGRawValuePointer<double>(&_fixed_turn_radius));
204 props->tie("controls/restart",
205 SGRawValuePointer<bool>(&_restart));
206 props->tie("velocities/speed-kts",
207 SGRawValuePointer<double>(&speed));
210 void FGAIShip::unbind() {
212 props->untie("surface-positions/rudder-pos-deg");
213 props->untie("controls/heading-lock");
214 props->untie("controls/tgt-speed-kts");
215 props->untie("controls/tgt-heading-degs");
216 props->untie("controls/constants/roll");
217 props->untie("controls/constants/rudder");
218 props->untie("controls/constants/roll-factor");
219 props->untie("controls/constants/speed");
220 props->untie("waypoint/range-nm");
221 props->untie("waypoint/range-brg-deg");
222 props->untie("waypoint/rangerate-nm-sec");
223 props->untie("waypoint/new");
224 props->untie("waypoint/missed");
225 props->untie("waypoint/missed-count-sec");
226 props->untie("waypoint/missed-time-sec");
227 props->untie("waypoint/missed-range");
228 props->untie("waypoint/wait-count-sec");
229 props->untie("waypoint/lead-angle-deg");
230 props->untie("waypoint/xtrack-error-ft");
231 props->untie("waypoint/waiting");
232 props->untie("waypoint/tunnel");
233 props->untie("waypoint/alt-curr-m");
234 props->untie("waypoint/alt-prev-m");
235 props->untie("submodels/serviceable");
236 props->untie("controls/turn-radius-ft");
237 props->untie("controls/turn-radius-corrected-ft");
238 props->untie("controls/constants/lead-angle/gain");
239 props->untie("controls/constants/lead-angle/limit-deg");
240 props->untie("controls/constants/lead-angle/proportion");
241 props->untie("controls/fixed-turn-radius-ft");
242 props->untie("controls/constants/speed");
243 props->untie("controls/restart");
244 props->untie("velocities/speed-kts");
247 void FGAIShip::update(double dt) {
248 //SG_LOG(SG_GENERAL, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
249 // For computation of rotation speeds we just use finite differences here.
250 // That is perfectly valid since this thing is not driven by accelerations
251 // but by just apply discrete changes at its velocity variables.
252 // Update the velocity information stored in those nodes.
253 // Transform that one to the horizontal local coordinate system.
254 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
255 // The orientation of the ship wrt the horizontal local frame
256 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
257 // and postrotate the orientation of the AIModel wrt the horizontal
259 SGQuatd ec2body = ec2hl*hl2body;
260 // The cartesian position of the ship in the wgs84 world
261 SGVec3d cartPos = SGVec3d::fromGeod(pos);
263 // The simulation time this transform is meant for
264 aip.setReferenceTime(globals->get_sim_time_sec());
266 // Compute the velocity in m/s in the body frame
267 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
269 FGAIBase::update(dt);
275 // Only change these values if we are able to compute them safely
276 if (SGLimits<double>::min() < dt) {
277 // Now here is the finite difference ...
279 // Transform that one to the horizontal local coordinate system.
280 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
281 // compute the new orientation
282 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
283 // The rotation difference
284 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
285 SGVec3d dOrAngleAxis;
286 dOr.getAngleAxis(dOrAngleAxis);
287 // divided by the time difference provides a rotation speed vector
290 aip.setBodyAngularVelocity(dOrAngleAxis);
294 void FGAIShip::Run(double dt) {
296 ProcessFlightPlan(dt);
298 string type = getTypeString();
305 double speed_diff = tgt_speed - speed;
307 if (fabs(speed_diff) > 0.1) {
309 if (speed_diff > 0.0)
310 speed += _speed_constant * dt;
312 if (speed_diff < 0.0)
313 speed -= _speed_constant * dt;
317 // do not allow unreasonable speeds
318 SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
320 // convert speed to degrees per second
321 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
322 * speed * 1.686 / ft_per_deg_lat;
323 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
324 * speed * 1.686 / ft_per_deg_lon;
327 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
328 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
329 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
330 pos.setElevationFt(tgt_altitude_ft);
333 // adjust heading based on current _rudder angle
334 if (turn_radius_ft <= 0)
335 turn_radius_ft = 0; // don't allow nonsense values
344 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
345 if(type == "ship" || type == "carrier" || type == "escort"){
348 _sp_turn_radius_ft = _fixed_turn_radius;
350 // adjust turn radius for speed. The equation is very approximate.
351 // we need to allow for negative speeds
352 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
357 if (fabs(speed) <= 40)
358 _sp_turn_radius_ft = _fixed_turn_radius;
360 // adjust turn radius for speed.
361 _sp_turn_radius_ft = turn_radius_ft;
366 if (_rudder <= -0.25 || _rudder >= 0.25) {
367 // adjust turn radius for _rudder angle. The equation is even more approximate.
372 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
374 // calculate the angle, alpha, subtended by the arc traversed in time dt
375 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
376 //cout << _name << " alpha " << alpha << endl;
377 // make sure that alpha is applied in the right direction
378 hdg += alpha * sign(_rudder);
380 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
382 //adjust roll for rudder angle and speed. Another bit of voodoo
383 raw_roll = _roll_factor * speed * _rudder;
385 // _rudder angle is 0
393 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
395 // adjust target _rudder angle if heading lock engaged
396 double rudder_diff = 0.0;
398 double rudder_sense = 0.0;
399 double diff = fabs(hdg - tgt_heading);
400 //cout << "_rudder diff" << diff << endl;
402 diff = fabs(diff - 360);
404 double sum = hdg + diff;
409 if (fabs(sum - tgt_heading)< 1.0)
415 rudder_sense = -rudder_sense;
418 _tgt_rudder = diff * rudder_sense;
420 _tgt_rudder = 45 * rudder_sense;
422 rudder_diff = _tgt_rudder - _rudder;
425 // set the _rudder limit by speed
426 if (type == "ship" || type == "carrier" || type == "escort"){
429 rudder_limit = (-0.825 * speed) + 35;
436 if (fabs(rudder_diff)> 0.1) { // apply dead zone
438 if (rudder_diff > 0.0) {
439 _rudder += _rudder_constant * dt;
441 if (_rudder > rudder_limit) // apply the _rudder limit
442 _rudder = rudder_limit;
444 } else if (rudder_diff < 0.0) {
445 _rudder -= _rudder_constant * dt;
447 if (_rudder < -rudder_limit)
448 _rudder = -rudder_limit;
452 // do calculations for radar
453 UpdateRadar(manager);
457 void FGAIShip::AccelTo(double speed) {
461 void FGAIShip::PitchTo(double angle) {
465 void FGAIShip::RollTo(double angle) {
469 void FGAIShip::YawTo(double angle) {
472 void FGAIShip::ClimbTo(double altitude) {
473 tgt_altitude_ft = altitude;
474 _setAltitude(altitude);
477 void FGAIShip::TurnTo(double heading) {
478 tgt_heading = heading - _lead_angle + _tow_angle;
479 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
483 double FGAIShip::sign(double x) {
490 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
494 void FGAIShip::setStartTime(const string& st) {
498 void FGAIShip::setUntilTime(const string& ut) {
500 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
503 void FGAIShip::setCurrName(const string& c) {
505 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
508 void FGAIShip::setNextName(const string& n) {
510 props->setStringValue("waypoint/name-next", _next_name.c_str());
513 void FGAIShip::setPrevName(const string& p) {
515 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
518 void FGAIShip::setRepeat(bool r) {
522 void FGAIShip::setRestart(bool r) {
526 void FGAIShip::setMissed(bool m) {
528 props->setBoolValue("waypoint/missed", _missed);
531 void FGAIShip::setRudder(float r) {
535 void FGAIShip::setRoll(double rl) {
539 void FGAIShip::setLeadAngleGain(double g) {
540 _lead_angle_gain = g;
543 void FGAIShip::setLeadAngleLimit(double l) {
544 _lead_angle_limit = l;
547 void FGAIShip::setLeadAngleProp(double p) {
551 void FGAIShip::setRudderConstant(double rc) {
552 _rudder_constant = rc;
555 void FGAIShip::setSpeedConstant(double sc) {
556 _speed_constant = sc;
559 void FGAIShip::setFixedTurnRadius(double ftr) {
560 _fixed_turn_radius = ftr;
563 void FGAIShip::setInitialTunnel(bool t) {
565 setTunnel(_initial_tunnel);
568 void FGAIShip::setTunnel(bool t) {
572 void FGAIShip::setWPNames() {
575 setPrevName(prev->getName());
580 setCurrName(curr->getName());
583 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: current wp name error" );
587 setNextName(next->getName());
591 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->getName());
592 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->getName());
593 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->getName());
597 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
599 double course, distance, az2;
601 //calculate the bearing and range of the second pos from the first
602 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
603 distance *= SG_METER_TO_NM;
607 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
609 double course, distance, recip;
611 //calculate the bearing and range of the second pos from the first
612 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
613 if (tgt_speed >= 0) {
615 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: course " << course);
618 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: recip " << recip);
622 void FGAIShip::ProcessFlightPlan(double dt) {
624 if ( dt < 0.00001 ) {
628 double time_sec = getDaySeconds();
632 ///////////////////////////////////////////////////////////////////////////
633 // Check Execution time (currently once every 1 sec)
634 // Add a bit of randomization to prevent the execution of all flight plans
635 // in synchrony, which can add significant periodic framerate flutter.
636 ///////////////////////////////////////////////////////////////////////////
638 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
639 if (_dt_count < _next_run && _start_sec < time_sec)
642 _next_run = 0.05 + (0.025 * sg_random());
644 double until_time_sec = 0;
647 // check to see if we've reached the point for our next turn
648 // if the range to the waypoint is less than the calculated turn
649 // radius we can start the turn to the next leg
650 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
651 _range_rate = (_wp_range - _old_range) / _dt_count;
652 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
653 // we need to try to identify a _missed waypoint
655 // calculate the time needed to turn through an arc of 90 degrees,
656 // and allow a time error
658 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
660 _missed_time_sec = 10;
662 _missed_range = 4 * sp_turn_radius_nm;
664 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
665 //if ((_range_rate > 0) && !_new_waypoint){
666 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
667 _missed_count += _dt_count;
670 if (_missed_count >= 120)
672 else if (_missed_count >= _missed_time_sec)
677 _old_range = _wp_range;
680 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
682 if (_next_name == "TUNNEL"){
685 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " " << sp_turn_radius_nm );
687 fp->IncrementWaypoint(false);
688 next = fp->getNextWaypoint();
690 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
691 || next->getName() == "END" || next->getName() == "TUNNEL")
695 fp->IncrementWaypoint(false);
696 curr = fp->getCurrentWaypoint();
697 next = fp->getNextWaypoint();
699 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
702 SG_LOG(SG_GENERAL, SG_INFO, "AIShip: "<< _name << " Flightplan repeating ");
705 curr = fp->getCurrentWaypoint();
706 next = fp->getNextWaypoint();
708 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
709 _old_range = _wp_range;
711 _new_waypoint = true;
714 AccelTo(prev->getSpeed());
715 } else if (_restart){
716 SG_LOG(SG_GENERAL, SG_INFO, "AIShip: " << _name << " Flightplan restarting ");
720 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
726 } else if (_next_name == "WAIT") {
728 if (_wait_count < next->getTime_sec()) {
729 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
732 _wait_count += _dt_count;
737 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
738 << " wait done: getting new waypoints ");
741 fp->IncrementWaypoint(false);
742 next = fp->getNextWaypoint();
744 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
745 || next->getName() == "END" || next->getName() == "TUNNEL")
749 fp->IncrementWaypoint(false);
750 curr = fp->getCurrentWaypoint();
751 next = fp->getNextWaypoint();
754 } else if (_next_name == "WAITUNTIL") {
755 time_sec = getDaySeconds();
756 until_time_sec = processTimeString(next->getTime());
757 _until_time = next->getTime();
758 setUntilTime(next->getTime());
759 if (until_time_sec > time_sec) {
760 SG_LOG(SG_GENERAL, SG_INFO, "AIShip: " << _name << " "
761 << curr->getName() << " waiting until: "
762 << _until_time << " " << until_time_sec << " now " << time_sec );
768 SG_LOG(SG_GENERAL, SG_INFO, "AIShip: "
769 << _name << " wait until done: getting new waypoints ");
771 fp->IncrementWaypoint(false);
773 while (next->getName() == "WAITUNTIL") {
774 fp->IncrementWaypoint(false);
775 next = fp->getNextWaypoint();
778 if (next->getName() == "WAIT")
782 fp->IncrementWaypoint(false);
783 curr = fp->getCurrentWaypoint();
784 next = fp->getNextWaypoint();
789 //now reorganise the waypoints, so that next becomes current and so on
790 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
791 fp->IncrementWaypoint(false);
792 prev = fp->getPreviousWaypoint(); //first waypoint
793 curr = fp->getCurrentWaypoint(); //second waypoint
794 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
798 _new_waypoint = true;
802 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
803 _old_range = _wp_range;
805 object_type type = getType();
808 AccelTo(prev->getSpeed());
810 _curr_alt = curr->getAltitude();
811 _prev_alt = prev->getAltitude();
814 _new_waypoint = false;
817 // now revise the required course for the next way point
818 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
823 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
826 } // end Processing FlightPlan
828 bool FGAIShip::initFlightPlan() {
830 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
834 _tunnel = _initial_tunnel;
837 fp->IncrementWaypoint(false);
839 prev = fp->getPreviousWaypoint(); //first waypoint
840 curr = fp->getCurrentWaypoint(); //second waypoint
841 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
843 while (curr->getName() == "WAIT" || curr->getName() == "WAITUNTIL") { // don't wait when initialising
844 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
845 fp->IncrementWaypoint(false);
846 curr = fp->getCurrentWaypoint();
847 next = fp->getNextWaypoint();
850 if (!_start_time.empty()){
851 _start_sec = processTimeString(_start_time);
852 double day_sec = getDaySeconds();
854 if (_start_sec < day_sec){
855 //cout << "flight plan has already started " << _start_time << endl;
856 init = advanceFlightPlan(_start_sec, day_sec);
858 } else if (_start_sec > day_sec && _repeat) {
859 //cout << "flight plan has not started, " << _start_time;
860 //cout << "offsetting start time by -24 hrs" << endl;
862 init = advanceFlightPlan(_start_sec, day_sec);
866 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
869 fp->IncrementWaypoint(false);
870 prev = fp->getPreviousWaypoint();
871 curr = fp->getCurrentWaypoint();
872 next = fp->getNextWaypoint();
877 setLatitude(prev->getLatitude());
878 setLongitude(prev->getLongitude());
879 setSpeed(prev->getSpeed());
883 setHeading(getCourse(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude()));
884 _wp_range = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
885 _old_range = _wp_range;
890 _new_waypoint = true;
892 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
901 } // end of initialization
904 double FGAIShip::processTimeString(const string& theTime) {
910 // first split theTime string into
911 // hour, minute, second and convert to int;
912 Hour = atoi(theTime.substr(0,2).c_str());
913 Minute = atoi(theTime.substr(3,5).c_str());
914 Second = atoi(theTime.substr(6,8).c_str());
916 // offset by a day-sec to allow for starting a day earlier
917 double time_seconds = Hour * 3600
924 double FGAIShip::getDaySeconds () {
926 struct tm *t = globals->get_time_params()->getGmt();
928 double day_seconds = t->tm_hour * 3600
935 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
937 double elapsed_sec = start_sec;
938 double distance_nm = 0;
940 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
942 while ( elapsed_sec < day_sec ) {
944 if (next->getName() == "END" || fp->getNextWaypoint() == 0) {
947 //cout << _name << ": " << "restarting flightplan" << endl;
949 curr = fp->getCurrentWaypoint();
950 next = fp->getNextWaypoint();
952 //cout << _name << ": " << "ending flightplan" << endl;
957 } else if (next->getName() == "WAIT") {
958 //cout << _name << ": begin WAIT: " << prev->name << " ";
959 //cout << curr->name << " " << next->name << endl;
961 elapsed_sec += next->getTime_sec();
963 if ( elapsed_sec >= day_sec)
966 fp->IncrementWaypoint(false);
967 next = fp->getNextWaypoint();
969 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT"
970 && next->getName() != "END") {
972 fp->IncrementWaypoint(false);
973 curr = fp->getCurrentWaypoint();
974 next = fp->getNextWaypoint();
977 } else if (next->getName() == "WAITUNTIL") {
978 double until_sec = processTimeString(next->getTime());
980 if (until_sec > _start_sec && start_sec < 0)
983 if (elapsed_sec < until_sec)
984 elapsed_sec = until_sec;
986 if (elapsed_sec >= day_sec )
989 fp->IncrementWaypoint(false);
990 next = fp->getNextWaypoint();
992 if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT") {
994 fp->IncrementWaypoint(false);
995 curr = fp->getCurrentWaypoint();
996 next = fp->getNextWaypoint();
999 //cout << _name << ": end WAITUNTIL: ";
1000 //cout << prev->name << " " << curr->name << " " << next->name << endl;
1003 distance_nm = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
1004 elapsed_sec += distance_nm * 60 * 60 / prev->getSpeed();
1006 if (elapsed_sec >= day_sec)
1009 fp->IncrementWaypoint(false);
1010 prev = fp->getPreviousWaypoint();
1011 curr = fp->getCurrentWaypoint();
1012 next = fp->getNextWaypoint();
1017 // the required position lies between the previous and current waypoints
1018 // so we will calculate the distance back up the track from the current waypoint
1019 // then calculate the lat and lon.
1021 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
1022 // << " " << day_sec << endl;
1024 double time_diff = elapsed_sec - day_sec;
1025 double lat, lon, recip;
1027 //cout << " time diff " << time_diff << endl;
1029 if (next->getName() == "WAIT" ){
1031 lat = curr->getLatitude();
1032 lon = curr->getLongitude();
1033 _wait_count= time_diff;
1035 } else if (next->getName() == "WAITUNTIL") {
1037 lat = curr->getLatitude();
1038 lon = curr->getLongitude();
1041 setSpeed(prev->getSpeed());
1042 distance_nm = speed * time_diff / (60 * 60);
1043 double brg = getCourse(curr->getLatitude(), curr->getLongitude(), prev->getLatitude(), prev->getLongitude());
1045 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1046 // << " lat " << curr->latitude << " lon " << curr->longitude
1047 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1049 lat = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1050 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1051 lon = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1052 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1053 recip = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1054 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1063 void FGAIShip::setWPPos() {
1065 if (curr->getName() == "END" || curr->getName() == "WAIT"
1066 || curr->getName() == "WAITUNTIL" || curr->getName() == "TUNNEL"){
1067 //cout << curr->name << " returning" << endl;
1071 double elevation_m = 0;
1072 wppos.setLatitudeDeg(curr->getLatitude());
1073 wppos.setLongitudeDeg(curr->getLongitude());
1074 wppos.setElevationM(0);
1076 if (curr->getOn_ground()){
1078 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1079 elevation_m, &_material, 0)){
1080 wppos.setElevationM(elevation_m);
1083 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1086 wppos.setElevationM(curr->getAltitude());
1087 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1090 curr->setAltitude(wppos.getElevationM());
1094 void FGAIShip::setXTrackError() {
1096 double course = getCourse(prev->getLatitude(), prev->getLongitude(),
1097 curr->getLatitude(), curr->getLongitude());
1098 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1099 curr->getLatitude(), curr->getLongitude());
1100 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1101 double factor = -0.0045 * speed + 1;
1102 double limit = _lead_angle_limit * factor;
1105 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1109 _lead_angle *= _lead_angle_gain * factor;
1110 _xtrack_error = xtrack_error_nm * 6076.1155;
1112 SG_CLAMP_RANGE(_lead_angle, -limit, limit);