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-missed-count");
178 props->untie("position/waypoint-missed-time-sec");
179 props->untie("position/waypoint-wait-count");
180 props->untie("position/waypoint-waiting");
181 props->untie("submodels/serviceable");
184 void FGAIShip::update(double dt) {
185 FGAIBase::update(dt);
190 void FGAIShip::Run(double dt) {
191 //cout << _name << " init: " << _fp_init << endl;
193 ProcessFlightPlan(dt);
195 // double speed_north_deg_sec;
196 // double speed_east_deg_sec;
202 double speed_diff = tgt_speed - speed;
204 if (fabs(speed_diff) > 0.1) {
206 if (speed_diff > 0.0)
207 speed += _speed_constant * dt;
209 if (speed_diff < 0.0)
210 speed -= _speed_constant * dt;
214 // do not allow unreasonable ship speeds
218 // convert speed to degrees per second
219 speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
220 * speed * 1.686 / ft_per_deg_lat;
221 speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
222 * speed * 1.686 / ft_per_deg_lon;
225 pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
226 pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
228 // adjust heading based on current _rudder angle
230 //cout << "turn_radius_ft " << turn_radius_ft ;
232 if (turn_radius_ft <= 0)
233 turn_radius_ft = 0; // don't allow nonsense values
241 //we assume that at slow speed ships will manoeuvre using engines/bow thruster
243 _sp_turn_radius_ft = 500;
245 // adjust turn radius for speed. The equation is very approximate.
246 // we need to allow for negative speeds
247 _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
249 //cout << " speed turn radius " << _sp_turn_radius_ft ;
251 if (_rudder <= -0.25 || _rudder >= 0.25) {
252 // adjust turn radius for _rudder angle. The equation is even more approximate.
257 _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
259 //cout <<" _rudder turn radius " << _rd_turn_radius_ft << endl;
261 // calculate the angle, alpha, subtended by the arc traversed in time dt
262 alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
264 // make sure that alpha is applied in the right direction
265 hdg += alpha * sign(_rudder);
273 //adjust roll for rudder angle and speed. Another bit of voodoo
274 raw_roll = _roll_factor * speed * _rudder;
276 // _rudder angle is 0
284 roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
286 // adjust target _rudder angle if heading lock engaged
287 double rudder_diff = 0.0;
289 double rudder_sense = 0.0;
290 double diff = fabs(hdg - tgt_heading);
291 //cout << "_rudder diff" << diff << endl;
293 diff = fabs(diff - 360);
295 double sum = hdg + diff;
300 if (fabs(sum - tgt_heading)< 1.0)
306 rudder_sense = -rudder_sense;
309 _tgt_rudder = diff * rudder_sense;
311 _tgt_rudder = 45 * rudder_sense;
313 rudder_diff = _tgt_rudder - _rudder;
316 // set the _rudder limit by speed
318 rudder_limit = (-0.825 * speed) + 35;
322 if (fabs(rudder_diff)> 0.1) { // apply dead zone
324 if (rudder_diff > 0.0) {
325 _rudder += _rudder_constant * dt;
327 if (_rudder > rudder_limit) // apply the _rudder limit
328 _rudder = rudder_limit;
330 } else if (rudder_diff < 0.0) {
331 _rudder -= _rudder_constant * dt;
333 if (_rudder < -rudder_limit)
334 _rudder = -rudder_limit;
338 // do calculations for radar
339 UpdateRadar(manager);
343 void FGAIShip::AccelTo(double speed) {
347 void FGAIShip::PitchTo(double angle) {
351 void FGAIShip::RollTo(double angle) {
355 void FGAIShip::YawTo(double angle) {
358 void FGAIShip::ClimbTo(double altitude) {
362 void FGAIShip::TurnTo(double heading) {
363 tgt_heading = heading;
367 double FGAIShip::sign(double x) {
374 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
378 void FGAIShip::setName(const string& n) {
382 void FGAIShip::setStartTime(const string& st) {
386 void FGAIShip::setUntilTime(const string& ut) {
388 props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
391 void FGAIShip::setCurrName(const string& c) {
393 props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
396 void FGAIShip::setNextName(const string& n) {
398 props->setStringValue("position/waypoint-name-next", _next_name.c_str());
401 void FGAIShip::setPrevName(const string& p) {
403 props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
406 void FGAIShip::setRepeat(bool r) {
410 void FGAIShip::setMissed(bool m) {
412 props->setBoolValue("position/waypoint-missed", _missed);
415 void FGAIShip::setRudder(float r) {
419 void FGAIShip::setRoll(double rl) {
423 void FGAIShip::setWPNames() {
426 setPrevName(prev->name);
430 setCurrName(curr->name);
433 setNextName(next->name);
437 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
438 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
439 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
443 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
445 double course, distance, az2;
447 //calculate the bearing and range of the second pos from the first
448 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
449 distance *= SG_METER_TO_NM;
453 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
455 double course, distance, recip;
457 //calculate the bearing and range of the second pos from the first
458 geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
459 if (tgt_speed >= 0) {
466 void FGAIShip::ProcessFlightPlan(double dt) {
468 double time_sec = getDaySeconds();
469 double until_time_sec = 0;
474 ///////////////////////////////////////////////////////////////////////////
475 // Check Execution time (currently once every 1 sec)
476 // Add a bit of randomization to prevent the execution of all flight plans
477 // in synchrony, which can add significant periodic framerate flutter.
478 ///////////////////////////////////////////////////////////////////////////
480 //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
481 if (_dt_count < _next_run && _start_sec < time_sec)
484 _next_run = 1.0 + (0.5 * sg_random());
486 // check to see if we've reached the point for our next turn
487 // if the range to the waypoint is less than the calculated turn
488 // radius we can start the turn to the next leg
489 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
490 _range_rate = (_wp_range - _old_range) / _dt_count;
491 double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
493 // we need to try to identify a _missed waypoint
495 // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
497 _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
499 _missed_time_sec = 30;
501 if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
502 _missed_count += _dt_count;
504 if (_missed_count >= _missed_time_sec) {
510 _old_range = _wp_range;
513 if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
515 if (_next_name == "END") {
518 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
521 curr = fp->getCurrentWaypoint();
522 next = fp->getNextWaypoint();
524 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
525 _old_range = _wp_range;
527 _new_waypoint = true;
529 AccelTo(prev->speed);
531 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
537 } else if (_next_name == "WAIT") {
539 if (_wait_count < next->time_sec) {
540 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
543 _wait_count += _dt_count;
547 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
548 << " wait done: getting new waypoints ");
551 fp->IncrementWaypoint(false);
552 next = fp->getNextWaypoint();
554 if (next->name == "WAITUNTIL" || next->name == "WAIT"
555 || next->name == "END")
559 fp->IncrementWaypoint(false);
560 curr = fp->getCurrentWaypoint();
561 next = fp->getNextWaypoint();
564 } else if (_next_name == "WAITUNTIL") {
565 time_sec = getDaySeconds();
566 until_time_sec = processTimeString(next->time);
567 _until_time = next->time;
568 setUntilTime(next->time);
569 if (until_time_sec > time_sec) {
570 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
571 << _until_time << " " << until_time_sec << " now " << time_sec );
576 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
577 << _name << " wait until done: getting new waypoints ");
579 fp->IncrementWaypoint(false);
581 while (next->name == "WAITUNTIL") {
582 fp->IncrementWaypoint(false);
583 next = fp->getNextWaypoint();
586 if (next->name == "WAIT")
590 fp->IncrementWaypoint(false);
591 curr = fp->getCurrentWaypoint();
592 next = fp->getNextWaypoint();
597 //now reorganise the waypoints, so that next becomes current and so on
598 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
599 fp->IncrementWaypoint(false);
600 prev = fp->getPreviousWaypoint(); //first waypoint
601 curr = fp->getCurrentWaypoint(); //second waypoint
602 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
606 _new_waypoint = true;
609 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
610 _old_range = _wp_range;
611 AccelTo(prev->speed);
613 _new_waypoint = false;
616 // now revise the required course for the next way point
617 double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
622 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
625 } // end Processing FlightPlan
627 bool FGAIShip::initFlightPlan() {
629 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
636 fp->IncrementWaypoint(false);
638 prev = fp->getPreviousWaypoint(); //first waypoint
639 curr = fp->getCurrentWaypoint(); //second waypoint
640 next = fp->getNextWaypoint(); //third waypoint (might not exist!)
642 while (curr->name == "WAIT" || curr->name == "WAITUNTIL") { // don't wait when initialising
643 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
644 fp->IncrementWaypoint(false);
645 curr = fp->getCurrentWaypoint();
646 next = fp->getNextWaypoint();
649 if (!_start_time.empty()){
650 _start_sec = processTimeString(_start_time);
651 double day_sec = getDaySeconds();
653 if (_start_sec < day_sec){
654 //cout << "flight plan has already started " << _start_time << endl;
655 init = advanceFlightPlan(_start_sec, day_sec);
657 } else if (_start_sec > day_sec && _repeat) {
658 //cout << "flight plan has not started, " << _start_time;
659 //cout << "offsetting start time by -24 hrs" << endl;
661 init = advanceFlightPlan(_start_sec, day_sec);
665 _start_sec = 0; // set to zero for an immediate start of the Flight Plan
668 fp->IncrementWaypoint(false);
669 prev = fp->getPreviousWaypoint();
670 curr = fp->getCurrentWaypoint();
671 next = fp->getNextWaypoint();
676 setLatitude(prev->latitude);
677 setLongitude(prev->longitude);
678 setSpeed(prev->speed);
682 setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
683 _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
684 _old_range = _wp_range;
689 _new_waypoint = true;
691 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
700 } // end of initialization
703 double FGAIShip::processTimeString(const string& theTime) {
709 // first split theTime string into
710 // hour, minute, second and convert to int;
711 Hour = atoi(theTime.substr(0,2).c_str());
712 Minute = atoi(theTime.substr(3,5).c_str());
713 Second = atoi(theTime.substr(6,8).c_str());
715 // offset by a day-sec to allow for starting a day earlier
716 double time_seconds = Hour * 3600
723 double FGAIShip::getDaySeconds () {
725 struct tm *t = globals->get_time_params()->getGmt();
727 double day_seconds = t->tm_hour * 3600
734 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
736 double elapsed_sec = start_sec;
737 double distance_nm = 0;
739 //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
741 while ( elapsed_sec < day_sec ) {
743 if (next->name == "END") {
746 //cout << _name << ": " << "restarting flightplan" << endl;
748 curr = fp->getCurrentWaypoint();
749 next = fp->getNextWaypoint();
751 //cout << _name << ": " << "ending flightplan" << endl;
756 } else if (next->name == "WAIT") {
757 //cout << _name << ": begin WAIT: " << prev->name << " ";
758 //cout << curr->name << " " << next->name << endl;
760 elapsed_sec += next->time_sec;
762 if ( elapsed_sec >= day_sec)
765 fp->IncrementWaypoint(false);
766 next = fp->getNextWaypoint();
768 if (next->name != "WAITUNTIL" && next->name != "WAIT"
769 && next->name != "END") {
771 fp->IncrementWaypoint(false);
772 curr = fp->getCurrentWaypoint();
773 next = fp->getNextWaypoint();
776 } else if (next->name == "WAITUNTIL") {
777 double until_sec = processTimeString(next->time);
779 if (until_sec > _start_sec && start_sec < 0)
782 if (elapsed_sec < until_sec)
783 elapsed_sec = until_sec;
785 if (elapsed_sec >= day_sec )
788 fp->IncrementWaypoint(false);
789 next = fp->getNextWaypoint();
791 if (next->name != "WAITUNTIL" && next->name != "WAIT") {
793 fp->IncrementWaypoint(false);
794 curr = fp->getCurrentWaypoint();
795 next = fp->getNextWaypoint();
798 //cout << _name << ": end WAITUNTIL: ";
799 //cout << prev->name << " " << curr->name << " " << next->name << endl;
802 distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
803 elapsed_sec += distance_nm * 60 * 60 / prev->speed;
805 if (elapsed_sec >= day_sec)
808 fp->IncrementWaypoint(false);
809 prev = fp->getPreviousWaypoint();
810 curr = fp->getCurrentWaypoint();
811 next = fp->getNextWaypoint();
816 // the required position lies between the previous and current waypoints
817 // so we will calculate the distance back up the track from the current waypoint
818 // then calculate the lat and lon.
819 /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
820 << " " << day_sec << endl;*/
822 double time_diff = elapsed_sec - day_sec;
823 double lat, lon, recip;
825 //cout << " time diff " << time_diff << endl;
827 if (next->name == "WAIT" ){
829 lat = curr->latitude;
830 lon = curr->longitude;
831 _wait_count= time_diff;
833 } else if (next->name == "WAITUNTIL") {
835 lat = curr->latitude;
836 lon = curr->longitude;
839 setSpeed(prev->speed);
840 distance_nm = speed * time_diff / (60 * 60);
841 double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
843 //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
844 // << " lat " << curr->latitude << " lon " << curr->longitude
845 // << " distance m " << distance_nm * SG_NM_TO_METER << endl;
847 lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
848 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
849 lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
850 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
851 recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
852 distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
855 //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;