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)
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/math/sg_random.h>
39 FGAIShip::FGAIShip(object_type ot) :
46 FGAIShip::~FGAIShip() {
49 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
54 FGAIBase::readFromScenario(scFileNode);
56 setRudder(scFileNode->getFloatValue("rudder", 0.0));
57 setName(scFileNode->getStringValue("name", "Titanic"));
58 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
59 std::string flightplan = scFileNode->getStringValue("flightplan");
60 setRepeat(scFileNode->getBoolValue("repeat", false));
61 setStartTime(scFileNode->getStringValue("time", ""));
63 if (!flightplan.empty()) {
64 FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
70 bool FGAIShip::init(bool search_in_AI_path) {
71 prev = 0; // the one behind you
72 curr = 0; // the one ahead
73 next = 0; // the next plus 1
77 props->setStringValue("name", _name.c_str());
78 props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
79 props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
80 props->setStringValue("position/waypoint-name-next", _next_name.c_str());
81 props->setStringValue("submodels/path", _path.c_str());
82 props->setStringValue("position/waypoint-start-time", _start_time.c_str());
83 props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
89 _rudder_constant = 0.5;
90 _roll_constant = 0.001;
91 _speed_constant = 0.05;
93 _roll_factor = -0.0083335;
95 _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
100 _new_waypoint = true;
104 _missed_time_sec = 30;
109 _wp_range = _old_range = 0;
113 _fp_init = initFlightPlan();
115 return FGAIBase::init(search_in_AI_path);
119 void FGAIShip::bind() {
122 props->tie("surface-positions/rudder-pos-deg",
123 SGRawValuePointer<float>(&_rudder));
124 props->tie("controls/heading-lock",
125 SGRawValuePointer<bool>(&_hdg_lock));
126 props->tie("controls/tgt-speed-kts",
127 SGRawValuePointer<double>(&tgt_speed));
128 props->tie("controls/tgt-heading-degs",
129 SGRawValuePointer<double>(&tgt_heading));
130 props->tie("controls/constants/rudder",
131 SGRawValuePointer<double>(&_rudder_constant));
132 props->tie("controls/constants/roll-factor",
133 SGRawValuePointer<double>(&_roll_factor));
134 props->tie("controls/constants/roll",
135 SGRawValuePointer<double>(&_roll_constant));
136 props->tie("controls/constants/rudder",
137 SGRawValuePointer<double>(&_rudder_constant));
138 props->tie("controls/constants/speed",
139 SGRawValuePointer<double>(&_speed_constant));
140 props->tie("position/waypoint-range-nm",
141 SGRawValuePointer<double>(&_wp_range));
142 props->tie("position/waypoint-range-old-nm",
143 SGRawValuePointer<double>(&_old_range));
144 props->tie("position/waypoint-range-rate-nm-sec",
145 SGRawValuePointer<double>(&_range_rate));
146 props->tie("position/waypoint-new",
147 SGRawValuePointer<bool>(&_new_waypoint));
148 props->tie("position/waypoint-missed",
149 SGRawValuePointer<bool>(&_missed));
150 props->tie("position/waypoint-missed-count",
151 SGRawValuePointer<double>(&_missed_count));
152 props->tie("position/waypoint-missed-time-sec",
153 SGRawValuePointer<double>(&_missed_time_sec));
154 props->tie("position/waypoint-wait-count",
155 SGRawValuePointer<double>(&_wait_count));
156 props->tie("position/waypoint-waiting",
157 SGRawValuePointer<bool>(&_waiting));
158 props->tie("submodels/serviceable",
159 SGRawValuePointer<bool>(&_serviceable));
162 void FGAIShip::unbind() {
164 props->untie("surface-positions/rudder-pos-deg");
165 props->untie("controls/heading-lock");
166 props->untie("controls/tgt-speed-kts");
167 props->untie("controls/tgt-heading-degs");
168 props->untie("controls/constants/roll");
169 props->untie("controls/constants/rudder");
170 props->untie("controls/constants/roll-factor");
171 props->untie("controls/constants/speed");
172 props->untie("position/waypoint-range-nm");
173 props->untie("position/waypoint-range-old-nm");
174 props->untie("position/waypoint-range-rate-nm-sec");
175 props->untie("position/waypoint-new");
176 props->untie("position/waypoint-missed");
177 props->untie("position/waypoint-wait-count");
178 props->untie("position/waypoint-waiting");
179 props->untie("position/waypoint-missed-time-sec");
180 props->untie("submodels/serviceable");
183 void FGAIShip::update(double dt) {
184 FGAIBase::update(dt);
189 void FGAIShip::Run(double dt) {
190 //cout << _name << " init: " << _fp_init << endl;
192 ProcessFlightPlan(dt);
194 // double speed_north_deg_sec;
195 // double speed_east_deg_sec;
201 double speed_diff = tgt_speed - speed;
203 if (fabs(speed_diff) > 0.1) {
205 if (speed_diff > 0.0)
206 speed += _speed_constant * dt;
208 if (speed_diff < 0.0)
209 speed -= _speed_constant * dt;
213 // do not allow unreasonable ship speeds
217 // convert speed to degrees per second
218 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
219 * speed * 1.686 / ft_per_deg_lat;
220 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
221 * speed * 1.686 / ft_per_deg_lon;
224 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
225 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
227 // adjust heading based on current _rudder angle
229 //cout << "turn_radius_ft " << turn_radius_ft ;
231 if (turn_radius_ft <= 0)
232 turn_radius_ft = 0; // don't allow nonsense values
240 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
242 _sp_turn_radius_ft = 500;
244 // adjust turn radius for speed. The equation is very approximate.
245 // we need to allow for negative speeds
246 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
248 //cout << " speed turn radius " << _sp_turn_radius_ft ;
250 if (_rudder <= -0.25 || _rudder >= 0.25) {
251 // adjust turn radius for _rudder angle. The equation is even more approximate.
256 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
258 //cout <<" _rudder turn radius " << _rd_turn_radius_ft << endl;
260 // calculate the angle, alpha, subtended by the arc traversed in time dt
261 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
263 // make sure that alpha is applied in the right direction
264 hdg += alpha * sign(_rudder);
272 //adjust roll for rudder angle and speed. Another bit of voodoo
273 raw_roll = _roll_factor * speed * _rudder;
275 // _rudder angle is 0
283 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
285 // adjust target _rudder angle if heading lock engaged
287 double rudder_sense = 0.0;
288 double diff = fabs(hdg - tgt_heading);
289 //cout << "_rudder diff" << diff << endl;
291 diff = fabs(diff - 360);
293 double sum = hdg + diff;
298 if (fabs(sum - tgt_heading)< 1.0)
304 rudder_sense = -rudder_sense;
307 _tgt_rudder = diff * rudder_sense;
309 _tgt_rudder = 45 * rudder_sense;
312 // adjust _rudder angle
313 double rudder_diff = _tgt_rudder - _rudder;
315 // set the _rudder limit by speed
317 rudder_limit = (-0.825 * speed) + 35;
321 if (fabs(rudder_diff)> 0.1) { // apply dead zone
323 if (rudder_diff > 0.0) {
324 _rudder += _rudder_constant * dt;
326 if (_rudder > rudder_limit) // apply the _rudder limit
327 _rudder = rudder_limit;
329 } else if (rudder_diff < 0.0) {
330 _rudder -= _rudder_constant * dt;
332 if (_rudder < -rudder_limit)
333 _rudder = -rudder_limit;
337 // do calculations for radar
338 UpdateRadar(manager);
342 void FGAIShip::AccelTo(double speed) {
346 void FGAIShip::PitchTo(double angle) {
350 void FGAIShip::RollTo(double angle) {
354 void FGAIShip::YawTo(double angle) {
357 void FGAIShip::ClimbTo(double altitude) {
361 void FGAIShip::TurnTo(double heading) {
362 tgt_heading = heading;
366 double FGAIShip::sign(double x) {
373 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
377 void FGAIShip::setName(const string& n) {
381 void FGAIShip::setStartTime(const string& st) {
385 void FGAIShip::setUntilTime(const string& ut) {
387 props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
390 void FGAIShip::setCurrName(const string& c) {
392 props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
395 void FGAIShip::setNextName(const string& n) {
397 props->setStringValue("position/waypoint-name-next", _next_name.c_str());
400 void FGAIShip::setPrevName(const string& p) {
402 props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
405 void FGAIShip::setRepeat(bool r) {
409 void FGAIShip::setMissed(bool m) {
411 props->setBoolValue("position/waypoint-missed", _missed);
414 void FGAIShip::setRudder(float r) {
418 void FGAIShip::setRoll(double rl) {
422 void FGAIShip::setWPNames() {
425 setPrevName(prev->name);
429 setCurrName(curr->name);
432 setNextName(next->name);
436 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
437 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
438 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
442 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
444 double course, distance, az2;
446 //calculate the bearing and range of the second pos from the first
447 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
448 distance *= SG_METER_TO_NM;
452 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
454 double course, distance, recip;
456 //calculate the bearing and range of the second pos from the first
457 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
458 if (tgt_speed >= 0) {
465 void FGAIShip::ProcessFlightPlan(double dt) {
467 double time_sec = getDaySeconds();
468 double until_time_sec = 0;
473 ///////////////////////////////////////////////////////////////////////////
474 // Check Execution time (currently once every 1 sec)
475 // Add a bit of randomization to prevent the execution of all flight plans
476 // in synchrony, which can add significant periodic framerate flutter.
477 ///////////////////////////////////////////////////////////////////////////
479 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
480 if (_dt_count < _next_run && _start_sec < time_sec)
483 _next_run = 1.0 + (0.5 * sg_random());
485 // check to see if we've reached the point for our next turn
486 // if the range to the waypoint is less than the calculated turn
487 // radius we can start the turn to the next leg
488 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
489 _range_rate = (_wp_range - _old_range) / _dt_count;
490 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
492 // we need to try to identify a _missed waypoint
494 // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
496 _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
498 _missed_time_sec = 30;
500 if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
501 _missed_count += _dt_count;
503 if (_missed_count >= _missed_time_sec) {
509 _old_range = _wp_range;
512 if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
514 if (_next_name == "END") {
517 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
520 curr = fp->getCurrentWaypoint();
521 next = fp->getNextWaypoint();
523 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
524 _old_range = _wp_range;
526 _new_waypoint = true;
528 AccelTo(prev->speed);
530 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
536 } else if (_next_name == "WAIT") {
538 if (_wait_count < next->time_sec) {
539 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
542 _wait_count += _dt_count;
546 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
547 << " wait done: getting new waypoints ");
550 fp->IncrementWaypoint(false);
551 next = fp->getNextWaypoint();
553 if (next->name == "WAITUNTIL" || next->name == "WAIT"
554 || next->name == "END")
558 fp->IncrementWaypoint(false);
559 curr = fp->getCurrentWaypoint();
560 next = fp->getNextWaypoint();
563 } else if (_next_name == "WAITUNTIL") {
564 time_sec = getDaySeconds();
565 until_time_sec = processTimeString(next->time);
566 _until_time = next->time;
567 setUntilTime(next->time);
568 if (until_time_sec > time_sec) {
569 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
570 << _until_time << " " << until_time_sec << " now " << time_sec );
575 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
576 << _name << " wait until done: getting new waypoints ");
578 fp->IncrementWaypoint(false);
580 while (next->name == "WAITUNTIL") {
581 fp->IncrementWaypoint(false);
582 next = fp->getNextWaypoint();
585 if (next->name == "WAIT")
589 fp->IncrementWaypoint(false);
590 curr = fp->getCurrentWaypoint();
591 next = fp->getNextWaypoint();
596 //now reorganise the waypoints, so that next becomes current and so on
597 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
598 fp->IncrementWaypoint(false);
599 prev = fp->getPreviousWaypoint(); //first waypoint
600 curr = fp->getCurrentWaypoint(); //second waypoint
601 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
605 _new_waypoint = true;
608 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
609 _old_range = _wp_range;
610 AccelTo(prev->speed);
612 _new_waypoint = false;
615 // now revise the required course for the next way point
616 double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
621 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
624 } // end Processing FlightPlan
626 bool FGAIShip::initFlightPlan() {
628 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
635 fp->IncrementWaypoint(false);
637 prev = fp->getPreviousWaypoint(); //first waypoint
638 curr = fp->getCurrentWaypoint(); //second waypoint
639 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
641 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
642 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
643 fp->IncrementWaypoint(false);
644 curr = fp->getCurrentWaypoint();
645 next = fp->getNextWaypoint();
648 if (!_start_time.empty()){
649 _start_sec = processTimeString(_start_time);
650 double day_sec = getDaySeconds();
652 if (_start_sec < day_sec){
653 //cout << "flight plan has already started " << _start_time << endl;
654 init = advanceFlightPlan(_start_sec, day_sec);
656 } else if (_start_sec > day_sec && _repeat) {
657 //cout << "flight plan has not started, " << _start_time;
658 //cout << "offsetting start time by -24 hrs" << endl;
660 init = advanceFlightPlan(_start_sec, day_sec);
664 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
667 fp->IncrementWaypoint(false);
668 prev = fp->getPreviousWaypoint();
669 curr = fp->getCurrentWaypoint();
670 next = fp->getNextWaypoint();
675 setLatitude(prev->latitude);
676 setLongitude(prev->longitude);
677 setSpeed(prev->speed);
681 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
682 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
683 _old_range = _wp_range;
688 _new_waypoint = true;
690 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
699 } // end of initialization
702 double FGAIShip::processTimeString(const string& theTime) {
708 // first split theTime string into
709 // hour, minute, second and convert to int;
710 Hour = atoi(theTime.substr(0,2).c_str());
711 Minute = atoi(theTime.substr(3,5).c_str());
712 Second = atoi(theTime.substr(6,8).c_str());
714 // offset by a day-sec to allow for starting a day earlier
715 double time_seconds = Hour * 3600
722 double FGAIShip::getDaySeconds () {
724 struct tm *t = globals->get_time_params()->getGmt();
726 double day_seconds = t->tm_hour * 3600
733 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
735 double elapsed_sec = start_sec;
736 double distance_nm = 0;
738 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
740 while ( elapsed_sec < day_sec ) {
742 if (next->name == "END") {
745 //cout << _name << ": " << "restarting flightplan" << endl;
747 curr = fp->getCurrentWaypoint();
748 next = fp->getNextWaypoint();
750 //cout << _name << ": " << "ending flightplan" << endl;
755 } else if (next->name == "WAIT") {
756 //cout << _name << ": begin WAIT: " << prev->name << " ";
757 //cout << curr->name << " " << next->name << endl;
759 elapsed_sec += next->time_sec;
761 if ( elapsed_sec >= day_sec)
764 fp->IncrementWaypoint(false);
765 next = fp->getNextWaypoint();
767 if (next->name != "WAITUNTIL" && next->name != "WAIT"
768 && next->name != "END") {
770 fp->IncrementWaypoint(false);
771 curr = fp->getCurrentWaypoint();
772 next = fp->getNextWaypoint();
775 } else if (next->name == "WAITUNTIL") {
776 double until_sec = processTimeString(next->time);
778 if (until_sec > _start_sec && start_sec < 0)
781 if (elapsed_sec < until_sec)
782 elapsed_sec = until_sec;
784 if (elapsed_sec >= day_sec )
787 fp->IncrementWaypoint(false);
788 next = fp->getNextWaypoint();
790 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
792 fp->IncrementWaypoint(false);
793 curr = fp->getCurrentWaypoint();
794 next = fp->getNextWaypoint();
797 //cout << _name << ": end WAITUNTIL: ";
798 //cout << prev->name << " " << curr->name << " " << next->name << endl;
801 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
802 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
804 if (elapsed_sec >= day_sec)
807 fp->IncrementWaypoint(false);
808 prev = fp->getPreviousWaypoint();
809 curr = fp->getCurrentWaypoint();
810 next = fp->getNextWaypoint();
815 // the required position lies between the previous and current waypoints
816 // so we will calculate the distance back up the track from the current waypoint
817 // then calculate the lat and lon.
818 /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
819 << " " << day_sec << endl;*/
821 double time_diff = elapsed_sec - day_sec;
822 double lat, lon, recip;
824 //cout << " time diff " << time_diff << endl;
826 if (next->name == "WAIT" ){
828 lat = curr->latitude;
829 lon = curr->longitude;
830 _wait_count= time_diff;
832 } else if (next->name == "WAITUNTIL") {
834 lat = curr->latitude;
835 lon = curr->longitude;
838 setSpeed(prev->speed);
839 distance_nm = speed * time_diff / (60 * 60);
840 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
842 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
843 // << " lat " << curr->latitude << " lon " << curr->longitude
844 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
846 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
847 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
848 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
849 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
850 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
851 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
854 //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;