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;
340 void FGAIShip::AccelTo(double speed) {
344 void FGAIShip::PitchTo(double angle) {
348 void FGAIShip::RollTo(double angle) {
352 void FGAIShip::YawTo(double angle) {
355 void FGAIShip::ClimbTo(double altitude) {
359 void FGAIShip::TurnTo(double heading) {
360 tgt_heading = heading;
364 double FGAIShip::sign(double x) {
371 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
375 void FGAIShip::setName(const string& n) {
379 void FGAIShip::setStartTime(const string& st) {
383 void FGAIShip::setUntilTime(const string& ut) {
385 props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
388 void FGAIShip::setCurrName(const string& c) {
390 props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
393 void FGAIShip::setNextName(const string& n) {
395 props->setStringValue("position/waypoint-name-next", _next_name.c_str());
398 void FGAIShip::setPrevName(const string& p) {
400 props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
403 void FGAIShip::setRepeat(bool r) {
407 void FGAIShip::setMissed(bool m) {
409 props->setBoolValue("position/waypoint-missed", _missed);
412 void FGAIShip::setRudder(float r) {
416 void FGAIShip::setRoll(double rl) {
420 void FGAIShip::setWPNames() {
423 setPrevName(prev->name);
427 setCurrName(curr->name);
430 setNextName(next->name);
434 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
435 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
436 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
440 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
442 double course, distance, az2;
444 //calculate the bearing and range of the second pos from the first
445 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
446 distance *= SG_METER_TO_NM;
450 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
452 double course, distance, recip;
454 //calculate the bearing and range of the second pos from the first
455 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
456 if (tgt_speed >= 0) {
463 void FGAIShip::ProcessFlightPlan(double dt) {
465 double time_sec = getDaySeconds();
466 double until_time_sec = 0;
471 ///////////////////////////////////////////////////////////////////////////
472 // Check Execution time (currently once every 1 sec)
473 // Add a bit of randomization to prevent the execution of all flight plans
474 // in synchrony, which can add significant periodic framerate flutter.
475 ///////////////////////////////////////////////////////////////////////////
477 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
478 if (_dt_count < _next_run && _start_sec < time_sec)
481 _next_run = 1.0 + (0.5 * sg_random());
483 // check to see if we've reached the point for our next turn
484 // if the range to the waypoint is less than the calculated turn
485 // radius we can start the turn to the next leg
486 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
487 _range_rate = (_wp_range - _old_range) / _dt_count;
488 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
490 // we need to try to identify a _missed waypoint
492 // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
494 _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
496 _missed_time_sec = 30;
498 if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
499 _missed_count += _dt_count;
501 if (_missed_count >= _missed_time_sec) {
507 _old_range = _wp_range;
510 if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
512 if (_next_name == "END") {
515 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
518 curr = fp->getCurrentWaypoint();
519 next = fp->getNextWaypoint();
521 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
522 _old_range = _wp_range;
524 _new_waypoint = true;
526 AccelTo(prev->speed);
528 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
534 } else if (_next_name == "WAIT") {
536 if (_wait_count < next->time_sec) {
537 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
540 _wait_count += _dt_count;
544 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
545 << " wait done: getting new waypoints ");
548 fp->IncrementWaypoint(false);
549 next = fp->getNextWaypoint();
551 if (next->name == "WAITUNTIL" || next->name == "WAIT"
552 || next->name == "END")
556 fp->IncrementWaypoint(false);
557 curr = fp->getCurrentWaypoint();
558 next = fp->getNextWaypoint();
561 } else if (_next_name == "WAITUNTIL") {
562 time_sec = getDaySeconds();
563 until_time_sec = processTimeString(next->time);
564 _until_time = next->time;
565 setUntilTime(next->time);
566 if (until_time_sec > time_sec) {
567 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
568 << _until_time << " " << until_time_sec << " now " << time_sec );
573 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
574 << _name << " wait until done: getting new waypoints ");
576 fp->IncrementWaypoint(false);
578 while (next->name == "WAITUNTIL") {
579 fp->IncrementWaypoint(false);
580 next = fp->getNextWaypoint();
583 if (next->name == "WAIT")
587 fp->IncrementWaypoint(false);
588 curr = fp->getCurrentWaypoint();
589 next = fp->getNextWaypoint();
594 //now reorganise the waypoints, so that next becomes current and so on
595 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
596 fp->IncrementWaypoint(false);
597 prev = fp->getPreviousWaypoint(); //first waypoint
598 curr = fp->getCurrentWaypoint(); //second waypoint
599 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
603 _new_waypoint = true;
606 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
607 _old_range = _wp_range;
608 AccelTo(prev->speed);
610 _new_waypoint = false;
613 // now revise the required course for the next way point
614 double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
619 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
622 } // end Processing FlightPlan
624 bool FGAIShip::initFlightPlan() {
626 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
633 fp->IncrementWaypoint(false);
635 prev = fp->getPreviousWaypoint(); //first waypoint
636 curr = fp->getCurrentWaypoint(); //second waypoint
637 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
639 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
640 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
641 fp->IncrementWaypoint(false);
642 curr = fp->getCurrentWaypoint();
643 next = fp->getNextWaypoint();
646 if (!_start_time.empty()){
647 _start_sec = processTimeString(_start_time);
648 double day_sec = getDaySeconds();
650 if (_start_sec < day_sec){
651 //cout << "flight plan has already started " << _start_time << endl;
652 init = advanceFlightPlan(_start_sec, day_sec);
654 } else if (_start_sec > day_sec && _repeat) {
655 //cout << "flight plan has not started, " << _start_time;
656 //cout << "offsetting start time by -24 hrs" << endl;
658 init = advanceFlightPlan(_start_sec, day_sec);
662 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
665 fp->IncrementWaypoint(false);
666 prev = fp->getPreviousWaypoint();
667 curr = fp->getCurrentWaypoint();
668 next = fp->getNextWaypoint();
673 setLatitude(prev->latitude);
674 setLongitude(prev->longitude);
675 setSpeed(prev->speed);
679 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
680 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
681 _old_range = _wp_range;
686 _new_waypoint = true;
688 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
697 } // end of initialization
700 double FGAIShip::processTimeString(const string& theTime) {
706 // first split theTime string into
707 // hour, minute, second and convert to int;
708 Hour = atoi(theTime.substr(0,2).c_str());
709 Minute = atoi(theTime.substr(3,5).c_str());
710 Second = atoi(theTime.substr(6,8).c_str());
712 // offset by a day-sec to allow for starting a day earlier
713 double time_seconds = Hour * 3600
720 double FGAIShip::getDaySeconds () {
722 struct tm *t = globals->get_time_params()->getGmt();
724 double day_seconds = t->tm_hour * 3600
731 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
733 double elapsed_sec = start_sec;
734 double distance_nm = 0;
736 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
738 while ( elapsed_sec < day_sec ) {
740 if (next->name == "END") {
743 //cout << _name << ": " << "restarting flightplan" << endl;
745 curr = fp->getCurrentWaypoint();
746 next = fp->getNextWaypoint();
748 //cout << _name << ": " << "ending flightplan" << endl;
753 } else if (next->name == "WAIT") {
754 //cout << _name << ": begin WAIT: " << prev->name << " ";
755 //cout << curr->name << " " << next->name << endl;
757 elapsed_sec += next->time_sec;
759 if ( elapsed_sec >= day_sec)
762 fp->IncrementWaypoint(false);
763 next = fp->getNextWaypoint();
765 if (next->name != "WAITUNTIL" && next->name != "WAIT"
766 && next->name != "END") {
768 fp->IncrementWaypoint(false);
769 curr = fp->getCurrentWaypoint();
770 next = fp->getNextWaypoint();
773 } else if (next->name == "WAITUNTIL") {
774 double until_sec = processTimeString(next->time);
776 if (until_sec > _start_sec && start_sec < 0)
779 if (elapsed_sec < until_sec)
780 elapsed_sec = until_sec;
782 if (elapsed_sec >= day_sec )
785 fp->IncrementWaypoint(false);
786 next = fp->getNextWaypoint();
788 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
790 fp->IncrementWaypoint(false);
791 curr = fp->getCurrentWaypoint();
792 next = fp->getNextWaypoint();
795 //cout << _name << ": end WAITUNTIL: ";
796 //cout << prev->name << " " << curr->name << " " << next->name << endl;
799 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
800 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
802 if (elapsed_sec >= day_sec)
805 fp->IncrementWaypoint(false);
806 prev = fp->getPreviousWaypoint();
807 curr = fp->getCurrentWaypoint();
808 next = fp->getNextWaypoint();
813 // the required position lies between the previous and current waypoints
814 // so we will calculate the distance back up the track from the current waypoint
815 // then calculate the lat and lon.
816 /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
817 << " " << day_sec << endl;*/
819 double time_diff = elapsed_sec - day_sec;
820 double lat, lon, recip;
822 //cout << " time diff " << time_diff << endl;
824 if (next->name == "WAIT" ){
826 lat = curr->latitude;
827 lon = curr->longitude;
828 _wait_count= time_diff;
830 } else if (next->name == "WAITUNTIL") {
832 lat = curr->latitude;
833 lon = curr->longitude;
836 setSpeed(prev->speed);
837 distance_nm = speed * time_diff / (60 * 60);
838 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
840 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
841 // << " lat " << curr->latitude << " lon " << curr->longitude
842 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
844 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
845 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
846 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
847 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
848 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
849 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
852 //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;