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) :
69 _roll_constant(0.001),
71 _roll_factor(-0.0083335),
78 FGAIShip::~FGAIShip() {
81 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
86 FGAIBase::readFromScenario(scFileNode);
88 setRudder(scFileNode->getFloatValue("rudder", 0.0));
89 setName(scFileNode->getStringValue("name", "Titanic"));
90 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
91 std::string flightplan = scFileNode->getStringValue("flightplan");
92 setRepeat(scFileNode->getBoolValue("repeat", false));
93 setRestart(scFileNode->getBoolValue("restart", false));
94 setStartTime(scFileNode->getStringValue("time", ""));
95 setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
96 setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
97 setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
98 setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
99 setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
100 setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
102 if (!flightplan.empty()) {
103 SG_LOG(SG_GENERAL, SG_ALERT, "getting flightplan: " << _name );
105 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
111 bool FGAIShip::init(bool search_in_AI_path) {
112 prev = 0; // the one behind you
113 curr = 0; // the one ahead
114 next = 0; // the next plus 1
116 props->setStringValue("name", _name.c_str());
117 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
118 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
119 props->setStringValue("waypoint/name-next", _next_name.c_str());
120 props->setStringValue("submodels/path", _path.c_str());
121 props->setStringValue("waypoint/start-time", _start_time.c_str());
122 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
128 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
131 _fp_init = initFlightPlan();
133 return FGAIBase::init(search_in_AI_path);
136 void FGAIShip::bind() {
139 props->tie("surface-positions/rudder-pos-deg",
140 SGRawValuePointer<float>(&_rudder));
141 props->tie("controls/heading-lock",
142 SGRawValuePointer<bool>(&_hdg_lock));
143 props->tie("controls/tgt-speed-kts",
144 SGRawValuePointer<double>(&tgt_speed));
145 props->tie("controls/tgt-heading-degs",
146 SGRawValuePointer<double>(&tgt_heading));
147 props->tie("controls/constants/rudder",
148 SGRawValuePointer<double>(&_rudder_constant));
149 props->tie("controls/constants/roll-factor",
150 SGRawValuePointer<double>(&_roll_factor));
151 props->tie("controls/constants/roll",
152 SGRawValuePointer<double>(&_roll_constant));
153 props->tie("controls/constants/rudder",
154 SGRawValuePointer<double>(&_rudder_constant));
155 props->tie("controls/constants/speed",
156 SGRawValuePointer<double>(&_speed_constant));
157 props->tie("waypoint/range-nm",
158 SGRawValuePointer<double>(&_wp_range));
159 props->tie("waypoint/brg-deg",
160 SGRawValuePointer<double>(&_course));
161 props->tie("waypoint/rangerate-nm-sec",
162 SGRawValuePointer<double>(&_range_rate));
163 props->tie("waypoint/new",
164 SGRawValuePointer<bool>(&_new_waypoint));
165 props->tie("waypoint/missed",
166 SGRawValuePointer<bool>(&_missed));
167 props->tie("waypoint/missed-count-sec",
168 SGRawValuePointer<double>(&_missed_count));
169 props->tie("waypoint/missed-range-nm",
170 SGRawValuePointer<double>(&_missed_range));
171 props->tie("waypoint/missed-time-sec",
172 SGRawValuePointer<double>(&_missed_time_sec));
173 props->tie("waypoint/wait-count-sec",
174 SGRawValuePointer<double>(&_wait_count));
175 props->tie("waypoint/xtrack-error-ft",
176 SGRawValuePointer<double>(&_xtrack_error));
177 props->tie("waypoint/waiting",
178 SGRawValuePointer<bool>(&_waiting));
179 props->tie("waypoint/lead-angle-deg",
180 SGRawValuePointer<double>(&_lead_angle));
181 props->tie("waypoint/tunnel",
182 SGRawValuePointer<bool>(&_tunnel));
183 props->tie("waypoint/alt-curr-m",
184 SGRawValuePointer<double>(&_curr_alt));
185 props->tie("waypoint/alt-prev-m",
186 SGRawValuePointer<double>(&_prev_alt));
187 props->tie("submodels/serviceable",
188 SGRawValuePointer<bool>(&_serviceable));
189 props->tie("controls/turn-radius-ft",
190 SGRawValuePointer<double>(&turn_radius_ft));
191 props->tie("controls/turn-radius-corrected-ft",
192 SGRawValuePointer<double>(&_rd_turn_radius_ft));
193 props->tie("controls/constants/lead-angle/gain",
194 SGRawValuePointer<double>(&_lead_angle_gain));
195 props->tie("controls/constants/lead-angle/limit-deg",
196 SGRawValuePointer<double>(&_lead_angle_limit));
197 props->tie("controls/constants/lead-angle/proportion",
198 SGRawValuePointer<double>(&_proportion));
199 props->tie("controls/fixed-turn-radius-ft",
200 SGRawValuePointer<double>(&_fixed_turn_radius));
201 props->tie("controls/restart",
202 SGRawValuePointer<bool>(&_restart));
203 props->tie("velocities/speed-kts",
204 SGRawValuePointer<double>(&speed));
207 void FGAIShip::unbind() {
209 props->untie("surface-positions/rudder-pos-deg");
210 props->untie("controls/heading-lock");
211 props->untie("controls/tgt-speed-kts");
212 props->untie("controls/tgt-heading-degs");
213 props->untie("controls/constants/roll");
214 props->untie("controls/constants/rudder");
215 props->untie("controls/constants/roll-factor");
216 props->untie("controls/constants/speed");
217 props->untie("waypoint/range-nm");
218 props->untie("waypoint/range-brg-deg");
219 props->untie("waypoint/rangerate-nm-sec");
220 props->untie("waypoint/new");
221 props->untie("waypoint/missed");
222 props->untie("waypoint/missed-count-sec");
223 props->untie("waypoint/missed-time-sec");
224 props->untie("waypoint/missed-range");
225 props->untie("waypoint/wait-count-sec");
226 props->untie("waypoint/lead-angle-deg");
227 props->untie("waypoint/xtrack-error-ft");
228 props->untie("waypoint/waiting");
229 props->untie("waypoint/tunnel");
230 props->untie("waypoint/alt-curr-m");
231 props->untie("waypoint/alt-prev-m");
232 props->untie("submodels/serviceable");
233 props->untie("controls/turn-radius-ft");
234 props->untie("controls/turn-radius-corrected-ft");
235 props->untie("controls/constants/lead-angle/gain");
236 props->untie("controls/constants/lead-angle/limit-deg");
237 props->untie("controls/constants/lead-angle/proportion");
238 props->untie("controls/fixed-turn-radius-ft");
239 props->untie("controls/constants/speed");
240 props->untie("controls/restart");
241 props->untie("velocities/speed-kts");
244 void FGAIShip::update(double dt) {
245 //SG_LOG(SG_GENERAL, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
246 // For computation of rotation speeds we just use finite differences here.
247 // That is perfectly valid since this thing is not driven by accelerations
248 // but by just apply discrete changes at its velocity variables.
249 // Update the velocity information stored in those nodes.
250 // Transform that one to the horizontal local coordinate system.
251 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
252 // The orientation of the carrier wrt the horizontal local frame
253 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
254 // and postrotate the orientation of the AIModel wrt the horizontal
256 SGQuatd ec2body = ec2hl*hl2body;
257 // The cartesian position of the carrier in the wgs84 world
258 SGVec3d cartPos = SGVec3d::fromGeod(pos);
260 // The simulation time this transform is meant for
261 aip.setReferenceTime(globals->get_sim_time_sec());
263 // Compute the velocity in m/s in the body frame
264 aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
266 FGAIBase::update(dt);
272 // Only change these values if we are able to compute them safely
273 if (SGLimits<double>::min() < dt) {
274 // Now here is the finite difference ...
276 // Transform that one to the horizontal local coordinate system.
277 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
278 // compute the new orientation
279 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
280 // The rotation difference
281 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
282 SGVec3d dOrAngleAxis;
283 dOr.getAngleAxis(dOrAngleAxis);
284 // divided by the time difference provides a rotation speed vector
287 aip.setBodyAngularVelocity(dOrAngleAxis);
291 void FGAIShip::Run(double dt) {
293 ProcessFlightPlan(dt);
295 string type = getTypeString();
302 double speed_diff = tgt_speed - speed;
304 if (fabs(speed_diff) > 0.1) {
306 if (speed_diff > 0.0)
307 speed += _speed_constant * dt;
309 if (speed_diff < 0.0)
310 speed -= _speed_constant * dt;
314 // do not allow unreasonable speeds
315 SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
317 // convert speed to degrees per second
318 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
319 * speed * 1.686 / ft_per_deg_lat;
320 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
321 * speed * 1.686 / ft_per_deg_lon;
324 //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
325 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
326 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
327 pos.setElevationFt(tgt_altitude_ft);
330 // adjust heading based on current _rudder angle
331 if (turn_radius_ft <= 0)
332 turn_radius_ft = 0; // don't allow nonsense values
341 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
342 if(type == "ship" || type == "carrier" || type == "escort"){
345 _sp_turn_radius_ft = _fixed_turn_radius;
347 // adjust turn radius for speed. The equation is very approximate.
348 // we need to allow for negative speeds
349 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
354 if (fabs(speed) <= 40)
355 _sp_turn_radius_ft = _fixed_turn_radius;
357 // adjust turn radius for speed.
358 _sp_turn_radius_ft = turn_radius_ft;
363 if (_rudder <= -0.25 || _rudder >= 0.25) {
364 // adjust turn radius for _rudder angle. The equation is even more approximate.
369 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
371 // calculate the angle, alpha, subtended by the arc traversed in time dt
372 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
373 //cout << _name << " alpha " << alpha << endl;
374 // make sure that alpha is applied in the right direction
375 hdg += alpha * sign(_rudder);
377 SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
379 //adjust roll for rudder angle and speed. Another bit of voodoo
380 raw_roll = _roll_factor * speed * _rudder;
382 // _rudder angle is 0
390 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
392 // adjust target _rudder angle if heading lock engaged
393 double rudder_diff = 0.0;
395 double rudder_sense = 0.0;
396 double diff = fabs(hdg - tgt_heading);
397 //cout << "_rudder diff" << diff << endl;
399 diff = fabs(diff - 360);
401 double sum = hdg + diff;
406 if (fabs(sum - tgt_heading)< 1.0)
412 rudder_sense = -rudder_sense;
415 _tgt_rudder = diff * rudder_sense;
417 _tgt_rudder = 45 * rudder_sense;
419 rudder_diff = _tgt_rudder - _rudder;
422 // set the _rudder limit by speed
423 if (type == "ship" || type == "carrier" || type == "escort"){
426 rudder_limit = (-0.825 * speed) + 35;
433 if (fabs(rudder_diff)> 0.1) { // apply dead zone
435 if (rudder_diff > 0.0) {
436 _rudder += _rudder_constant * dt;
438 if (_rudder > rudder_limit) // apply the _rudder limit
439 _rudder = rudder_limit;
441 } else if (rudder_diff < 0.0) {
442 _rudder -= _rudder_constant * dt;
444 if (_rudder < -rudder_limit)
445 _rudder = -rudder_limit;
449 // do calculations for radar
450 UpdateRadar(manager);
454 void FGAIShip::AccelTo(double speed) {
458 void FGAIShip::PitchTo(double angle) {
462 void FGAIShip::RollTo(double angle) {
466 void FGAIShip::YawTo(double angle) {
469 void FGAIShip::ClimbTo(double altitude) {
470 tgt_altitude_ft = altitude;
471 _setAltitude(altitude);
474 void FGAIShip::TurnTo(double heading) {
475 tgt_heading = heading - _lead_angle + _tow_angle;
476 SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
480 double FGAIShip::sign(double x) {
487 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
491 void FGAIShip::setName(const string& n) {
495 void FGAIShip::setStartTime(const string& st) {
499 void FGAIShip::setUntilTime(const string& ut) {
501 props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
504 void FGAIShip::setCurrName(const string& c) {
506 props->setStringValue("waypoint/name-curr", _curr_name.c_str());
509 void FGAIShip::setNextName(const string& n) {
511 props->setStringValue("waypoint/name-next", _next_name.c_str());
514 void FGAIShip::setPrevName(const string& p) {
516 props->setStringValue("waypoint/name-prev", _prev_name.c_str());
519 void FGAIShip::setRepeat(bool r) {
523 void FGAIShip::setRestart(bool r) {
527 void FGAIShip::setMissed(bool m) {
529 props->setBoolValue("waypoint/missed", _missed);
532 void FGAIShip::setRudder(float r) {
536 void FGAIShip::setRoll(double rl) {
540 void FGAIShip::setLeadAngleGain(double g) {
541 _lead_angle_gain = g;
544 void FGAIShip::setLeadAngleLimit(double l) {
545 _lead_angle_limit = l;
548 void FGAIShip::setLeadAngleProp(double p) {
552 void FGAIShip::setRudderConstant(double rc) {
553 _rudder_constant = rc;
556 void FGAIShip::setSpeedConstant(double sc) {
557 _speed_constant = sc;
560 void FGAIShip::setFixedTurnRadius(double ftr) {
561 _fixed_turn_radius = ftr;
564 void FGAIShip::setInitialTunnel(bool t) {
566 setTunnel(_initial_tunnel);
569 void FGAIShip::setTunnel(bool t) {
573 void FGAIShip::setWPNames() {
576 setPrevName(prev->name);
581 setCurrName(curr->name);
584 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: current wp name error" );
588 setNextName(next->name);
592 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
593 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
594 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
598 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
600 double course, distance, az2;
602 //calculate the bearing and range of the second pos from the first
603 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
604 distance *= SG_METER_TO_NM;
608 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
610 double course, distance, recip;
612 //calculate the bearing and range of the second pos from the first
613 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
614 if (tgt_speed >= 0) {
616 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: course " << course);
619 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: recip " << recip);
623 void FGAIShip::ProcessFlightPlan(double dt) {
625 double time_sec = getDaySeconds();
629 ///////////////////////////////////////////////////////////////////////////
630 // Check Execution time (currently once every 1 sec)
631 // Add a bit of randomization to prevent the execution of all flight plans
632 // in synchrony, which can add significant periodic framerate flutter.
633 ///////////////////////////////////////////////////////////////////////////
635 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
636 if (_dt_count < _next_run && _start_sec < time_sec)
639 _next_run = 0.05 + (0.025 * sg_random());
641 double until_time_sec = 0;
644 // check to see if we've reached the point for our next turn
645 // if the range to the waypoint is less than the calculated turn
646 // radius we can start the turn to the next leg
647 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
648 _range_rate = (_wp_range - _old_range) / _dt_count;
649 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
650 // we need to try to identify a _missed waypoint
652 // calculate the time needed to turn through an arc of 90 degrees,
653 // and allow a time error
655 _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
657 _missed_time_sec = 10;
659 _missed_range = 4 * sp_turn_radius_nm;
661 //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
662 //if ((_range_rate > 0) && !_new_waypoint){
663 if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
664 _missed_count += _dt_count;
667 if (_missed_count >= 120)
669 else if (_missed_count >= _missed_time_sec)
674 _old_range = _wp_range;
677 if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
679 if (_next_name == "TUNNEL"){
682 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " " << sp_turn_radius_nm );
684 fp->IncrementWaypoint(false);
685 next = fp->getNextWaypoint();
687 if (next->name == "WAITUNTIL" || next->name == "WAIT"
688 || next->name == "END" || next->name == "TUNNEL")
692 fp->IncrementWaypoint(false);
693 curr = fp->getCurrentWaypoint();
694 next = fp->getNextWaypoint();
696 }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
699 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: "<< _name << " Flightplan repeating ");
702 curr = fp->getCurrentWaypoint();
703 next = fp->getNextWaypoint();
705 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
706 _old_range = _wp_range;
708 _new_waypoint = true;
711 AccelTo(prev->speed);
712 } else if (_restart){
713 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " Flightplan restarting ");
717 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
723 } else if (_next_name == "WAIT") {
725 if (_wait_count < next->time_sec) {
726 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
729 _wait_count += _dt_count;
734 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
735 << " wait done: getting new waypoints ");
738 fp->IncrementWaypoint(false);
739 next = fp->getNextWaypoint();
741 if (next->name == "WAITUNTIL" || next->name == "WAIT"
742 || next->name == "END" || next->name == "TUNNEL")
746 fp->IncrementWaypoint(false);
747 curr = fp->getCurrentWaypoint();
748 next = fp->getNextWaypoint();
751 } else if (_next_name == "WAITUNTIL") {
752 time_sec = getDaySeconds();
753 until_time_sec = processTimeString(next->time);
754 _until_time = next->time;
755 setUntilTime(next->time);
756 if (until_time_sec > time_sec) {
757 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " "
758 << curr->name << " waiting until: "
759 << _until_time << " " << until_time_sec << " now " << time_sec );
765 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
766 << _name << " wait until done: getting new waypoints ");
768 fp->IncrementWaypoint(false);
770 while (next->name == "WAITUNTIL") {
771 fp->IncrementWaypoint(false);
772 next = fp->getNextWaypoint();
775 if (next->name == "WAIT")
779 fp->IncrementWaypoint(false);
780 curr = fp->getCurrentWaypoint();
781 next = fp->getNextWaypoint();
786 //now reorganise the waypoints, so that next becomes current and so on
787 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
788 fp->IncrementWaypoint(false);
789 prev = fp->getPreviousWaypoint(); //first waypoint
790 curr = fp->getCurrentWaypoint(); //second waypoint
791 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
795 _new_waypoint = true;
799 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
800 _old_range = _wp_range;
802 object_type type = getType();
805 AccelTo(prev->speed);
807 _curr_alt = curr->altitude;
808 _prev_alt = prev->altitude;
811 _new_waypoint = false;
814 // now revise the required course for the next way point
815 _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
820 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
823 } // end Processing FlightPlan
825 bool FGAIShip::initFlightPlan() {
827 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
831 _tunnel = _initial_tunnel;
834 fp->IncrementWaypoint(false);
836 prev = fp->getPreviousWaypoint(); //first waypoint
837 curr = fp->getCurrentWaypoint(); //second waypoint
838 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
840 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
841 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
842 fp->IncrementWaypoint(false);
843 curr = fp->getCurrentWaypoint();
844 next = fp->getNextWaypoint();
847 if (!_start_time.empty()){
848 _start_sec = processTimeString(_start_time);
849 double day_sec = getDaySeconds();
851 if (_start_sec < day_sec){
852 //cout << "flight plan has already started " << _start_time << endl;
853 init = advanceFlightPlan(_start_sec, day_sec);
855 } else if (_start_sec > day_sec && _repeat) {
856 //cout << "flight plan has not started, " << _start_time;
857 //cout << "offsetting start time by -24 hrs" << endl;
859 init = advanceFlightPlan(_start_sec, day_sec);
863 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
866 fp->IncrementWaypoint(false);
867 prev = fp->getPreviousWaypoint();
868 curr = fp->getCurrentWaypoint();
869 next = fp->getNextWaypoint();
874 setLatitude(prev->latitude);
875 setLongitude(prev->longitude);
876 setSpeed(prev->speed);
880 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
881 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
882 _old_range = _wp_range;
887 _new_waypoint = true;
889 SG_LOG(SG_GENERAL, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
898 } // end of initialization
901 double FGAIShip::processTimeString(const string& theTime) {
907 // first split theTime string into
908 // hour, minute, second and convert to int;
909 Hour = atoi(theTime.substr(0,2).c_str());
910 Minute = atoi(theTime.substr(3,5).c_str());
911 Second = atoi(theTime.substr(6,8).c_str());
913 // offset by a day-sec to allow for starting a day earlier
914 double time_seconds = Hour * 3600
921 double FGAIShip::getDaySeconds () {
923 struct tm *t = globals->get_time_params()->getGmt();
925 double day_seconds = t->tm_hour * 3600
932 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
934 double elapsed_sec = start_sec;
935 double distance_nm = 0;
937 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
939 while ( elapsed_sec < day_sec ) {
941 if (next->name == "END" || fp->getNextWaypoint() == 0) {
944 //cout << _name << ": " << "restarting flightplan" << endl;
946 curr = fp->getCurrentWaypoint();
947 next = fp->getNextWaypoint();
949 //cout << _name << ": " << "ending flightplan" << endl;
954 } else if (next->name == "WAIT") {
955 //cout << _name << ": begin WAIT: " << prev->name << " ";
956 //cout << curr->name << " " << next->name << endl;
958 elapsed_sec += next->time_sec;
960 if ( elapsed_sec >= day_sec)
963 fp->IncrementWaypoint(false);
964 next = fp->getNextWaypoint();
966 if (next->name != "WAITUNTIL" && next->name != "WAIT"
967 && next->name != "END") {
969 fp->IncrementWaypoint(false);
970 curr = fp->getCurrentWaypoint();
971 next = fp->getNextWaypoint();
974 } else if (next->name == "WAITUNTIL") {
975 double until_sec = processTimeString(next->time);
977 if (until_sec > _start_sec && start_sec < 0)
980 if (elapsed_sec < until_sec)
981 elapsed_sec = until_sec;
983 if (elapsed_sec >= day_sec )
986 fp->IncrementWaypoint(false);
987 next = fp->getNextWaypoint();
989 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
991 fp->IncrementWaypoint(false);
992 curr = fp->getCurrentWaypoint();
993 next = fp->getNextWaypoint();
996 //cout << _name << ": end WAITUNTIL: ";
997 //cout << prev->name << " " << curr->name << " " << next->name << endl;
1000 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
1001 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
1003 if (elapsed_sec >= day_sec)
1006 fp->IncrementWaypoint(false);
1007 prev = fp->getPreviousWaypoint();
1008 curr = fp->getCurrentWaypoint();
1009 next = fp->getNextWaypoint();
1014 // the required position lies between the previous and current waypoints
1015 // so we will calculate the distance back up the track from the current waypoint
1016 // then calculate the lat and lon.
1018 //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
1019 // << " " << day_sec << endl;
1021 double time_diff = elapsed_sec - day_sec;
1022 double lat, lon, recip;
1024 //cout << " time diff " << time_diff << endl;
1026 if (next->name == "WAIT" ){
1028 lat = curr->latitude;
1029 lon = curr->longitude;
1030 _wait_count= time_diff;
1032 } else if (next->name == "WAITUNTIL") {
1034 lat = curr->latitude;
1035 lon = curr->longitude;
1038 setSpeed(prev->speed);
1039 distance_nm = speed * time_diff / (60 * 60);
1040 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
1042 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1043 // << " lat " << curr->latitude << " lon " << curr->longitude
1044 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1046 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1047 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1048 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1049 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1050 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
1051 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1060 void FGAIShip::setWPPos() {
1062 if (curr->name == "END" || curr->name == "WAIT"
1063 || curr->name == "WAITUNTIL" || curr->name == "TUNNEL"){
1064 //cout << curr->name << " returning" << endl;
1068 double elevation_m = 0;
1069 wppos.setLatitudeDeg(curr->latitude);
1070 wppos.setLongitudeDeg(curr->longitude);
1071 wppos.setElevationM(0);
1073 if (curr->on_ground){
1075 if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1076 elevation_m, &_material, 0)){
1077 wppos.setElevationM(elevation_m);
1080 //cout << curr->name << " setting measured elev " << elevation_m << endl;
1083 wppos.setElevationM(curr->altitude);
1084 //cout << curr->name << " setting FP elev " << elevation_m << endl;
1087 curr->altitude = wppos.getElevationM();
1091 void FGAIShip::setXTrackError() {
1093 double course = getCourse(prev->latitude, prev->longitude,
1094 curr->latitude, curr->longitude);
1095 double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1096 curr->latitude, curr->longitude);
1097 double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1098 double factor = -0.0045 * speed + 1;
1099 double limit = _lead_angle_limit * factor;
1102 _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1106 _lead_angle *= _lead_angle_gain * factor;
1107 _xtrack_error = xtrack_error_nm * 6076.1155;
1109 SG_CLAMP_RANGE(_lead_angle, -limit, limit);