]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIShip.cxx
AIShip: remove duplicate property tie.
[flightgear.git] / src / AIModel / AIShip.cxx
1 // FGAIShip - FGAIBase-derived class creates an AI ship
2 //
3 // Written by David Culp, started October 2003.
4 // with major amendments and additions by Vivian Meazza, 2004 - 2007
5 //
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.
10 //
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.
15 //
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.
19
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #include <cmath>
25
26 #ifdef _MSC_VER
27 #  include <float.h>
28     double fgIsFinite(double x) { return _finite(x); }
29 #else
30     double fgIsFinite(double x) { return std::isfinite(x); }
31 #endif
32
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>
37
38 #include <simgear/scene/util/SGNodeMasks.hxx>
39 #include <Scenery/scenery.hxx>
40
41 #include "AIShip.hxx"
42
43 using std::string;
44
45 FGAIShip::FGAIShip(object_type ot) :
46 // allow HOT to be enabled
47 FGAIBase(ot, true),
48
49
50 _waiting(false),
51 _new_waypoint(true),
52 _tunnel(false),
53 _initial_tunnel(false),
54 _restart(false),
55 _hdg_constant(0.01),
56 _limit(100),
57 _elevation_m(0),
58 _elevation_ft(0),
59 _tow_angle(0),
60 _missed_count(0),
61 _wp_range(0),
62 _dt_count(0),
63 _next_run(0),
64 _roll_constant(0.001),
65 _roll_factor(-0.0083335),
66 _old_range(0),
67 _range_rate(0),
68 _missed_time_sec(30),
69 _day(86400),
70 _lead_angle(0),
71 _xtrack_error(0),
72 _curr_alt(0),
73 _prev_alt(0),
74 _until_time(""),
75 _fp_init(false),
76 _missed(false)
77 {
78         invisible = false;
79 }
80
81 FGAIShip::~FGAIShip() {
82 }
83
84 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
85
86     if (!scFileNode)
87         return;
88
89     FGAIBase::readFromScenario(scFileNode);
90
91     setRudder(scFileNode->getFloatValue("rudder", 0.0));
92     setName(scFileNode->getStringValue("name", "Titanic"));
93     setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
94     const std::string& flightplan = scFileNode->getStringValue("flightplan");
95     setRepeat(scFileNode->getBoolValue("repeat", false));
96     setRestart(scFileNode->getBoolValue("restart", false));
97     setStartTime(scFileNode->getStringValue("time", ""));
98     setLeadAngleGain(scFileNode->getDoubleValue("lead-angle-gain", 1.5));
99     setLeadAngleLimit(scFileNode->getDoubleValue("lead-angle-limit-deg", 15));
100     setLeadAngleProp(scFileNode->getDoubleValue("lead-angle-proportion", 0.75));
101     setRudderConstant(scFileNode->getDoubleValue("rudder-constant", 0.5));
102     setFixedTurnRadius(scFileNode->getDoubleValue("fixed-turn-radius-ft", 500));
103     setSpeedConstant(scFileNode->getDoubleValue("speed-constant", 0.5));
104     setSMPath(scFileNode->getStringValue("submodel-path", ""));
105     setRollFactor(scFileNode->getDoubleValue("roll-factor", 1));
106
107     if (!flightplan.empty()) {
108         SG_LOG(SG_AI, SG_ALERT, "getting flightplan: " << _name );
109
110         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
111         setFlightPlan(fp);
112     }
113
114 }
115
116 bool FGAIShip::init(bool search_in_AI_path) {
117     reinit();
118     return FGAIBase::init(search_in_AI_path);
119 }
120
121 void FGAIShip::reinit()
122 {
123     prev = 0; // the one behind you
124     curr = 0; // the one ahead
125     next = 0; // the next plus 1
126
127     props->setStringValue("name", _name.c_str());
128     props->setStringValue("waypoint/name-prev", _prev_name.c_str());
129     props->setStringValue("waypoint/name-curr", _curr_name.c_str());
130     props->setStringValue("waypoint/name-next", _next_name.c_str());
131     props->setStringValue("submodels/path", _path.c_str());
132     props->setStringValue("waypoint/start-time", _start_time.c_str());
133     props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
134
135     _hdg_lock = false;
136     _rudder = 0.0;
137     no_roll = false;
138
139     _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
140
141     if (fp)
142         _fp_init = initFlightPlan();
143
144     FGAIBase::reinit();
145 }
146
147 void FGAIShip::bind() {
148     FGAIBase::bind();
149
150     tie("surface-positions/rudder-pos-deg",
151         SGRawValuePointer<float>(&_rudder));
152     tie("controls/heading-lock",
153         SGRawValuePointer<bool>(&_hdg_lock));
154     tie("controls/tgt-speed-kts",
155         SGRawValuePointer<double>(&tgt_speed));
156     tie("controls/tgt-heading-degs",
157         SGRawValuePointer<double>(&tgt_heading));
158     tie("controls/constants/roll-factor",
159         SGRawValuePointer<double>(&_roll_factor));
160     tie("controls/constants/roll",
161         SGRawValuePointer<double>(&_roll_constant));
162     tie("controls/constants/rudder",
163         SGRawValuePointer<double>(&_rudder_constant));
164     tie("controls/constants/speed",
165         SGRawValuePointer<double>(&_speed_constant));
166     tie("waypoint/range-nm",
167         SGRawValuePointer<double>(&_wp_range));
168     tie("waypoint/brg-deg",
169         SGRawValuePointer<double>(&_course));
170     tie("waypoint/rangerate-nm-sec",
171         SGRawValuePointer<double>(&_range_rate));
172     tie("waypoint/new",
173         SGRawValuePointer<bool>(&_new_waypoint));
174     tie("waypoint/missed",
175         SGRawValuePointer<bool>(&_missed));
176     tie("waypoint/missed-count-sec",
177         SGRawValuePointer<double>(&_missed_count));
178     tie("waypoint/missed-range-nm",
179         SGRawValuePointer<double>(&_missed_range));
180     tie("waypoint/missed-time-sec",
181         SGRawValuePointer<double>(&_missed_time_sec));
182     tie("waypoint/wait-count-sec",
183         SGRawValuePointer<double>(&_wait_count));
184     tie("waypoint/xtrack-error-ft",
185         SGRawValuePointer<double>(&_xtrack_error));
186     tie("waypoint/waiting",
187         SGRawValuePointer<bool>(&_waiting));
188     tie("waypoint/lead-angle-deg",
189         SGRawValuePointer<double>(&_lead_angle));
190     tie("waypoint/tunnel",
191         SGRawValuePointer<bool>(&_tunnel));
192     tie("waypoint/alt-curr-m",
193         SGRawValuePointer<double>(&_curr_alt));
194     tie("waypoint/alt-prev-m",
195         SGRawValuePointer<double>(&_prev_alt));
196     tie("submodels/serviceable",
197         SGRawValuePointer<bool>(&_serviceable));
198     tie("controls/turn-radius-ft",
199         SGRawValuePointer<double>(&turn_radius_ft));
200     tie("controls/turn-radius-corrected-ft",
201         SGRawValuePointer<double>(&_rd_turn_radius_ft));
202     tie("controls/constants/lead-angle/gain",
203         SGRawValuePointer<double>(&_lead_angle_gain));
204     tie("controls/constants/lead-angle/limit-deg",
205         SGRawValuePointer<double>(&_lead_angle_limit));
206     tie("controls/constants/lead-angle/proportion",
207         SGRawValuePointer<double>(&_proportion));
208     tie("controls/fixed-turn-radius-ft",
209         SGRawValuePointer<double>(&_fixed_turn_radius));
210     tie("controls/restart",
211         SGRawValuePointer<bool>(&_restart));
212     tie("velocities/speed-kts",
213         SGRawValuePointer<double>(&speed));
214 }
215
216 void FGAIShip::update(double dt) {
217     //SG_LOG(SG_AI, SG_ALERT, "updating Ship: " << _name <<hdg<<pitch<<roll);
218     // For computation of rotation speeds we just use finite differences here.
219     // That is perfectly valid since this thing is not driven by accelerations
220     // but by just apply discrete changes at its velocity variables.
221     // Update the velocity information stored in those nodes.
222     // Transform that one to the horizontal local coordinate system.
223     SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
224     // The orientation of the ship wrt the horizontal local frame
225     SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
226     // and postrotate the orientation of the AIModel wrt the horizontal
227     // local frame
228     SGQuatd ec2body = ec2hl*hl2body;
229     // The cartesian position of the ship in the wgs84 world
230     //SGVec3d cartPos = SGVec3d::fromGeod(pos);
231
232     // The simulation time this transform is meant for
233     aip.setReferenceTime(globals->get_sim_time_sec());
234
235     // Compute the velocity in m/s in the body frame
236     aip.setBodyLinearVelocity(SGVec3d(0.51444444*speed, 0, 0));
237
238     FGAIBase::update(dt);
239     Run(dt);
240     Transform();
241     if (fp)
242         setXTrackError();
243
244     // Only change these values if we are able to compute them safely
245     if (SGLimits<double>::min() < dt) {
246         // Now here is the finite difference ...
247
248         // Transform that one to the horizontal local coordinate system.
249         SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
250         // compute the new orientation
251         SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
252         // The rotation difference
253         SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
254         SGVec3d dOrAngleAxis;
255         dOr.getAngleAxis(dOrAngleAxis);
256         // divided by the time difference provides a rotation speed vector
257         dOrAngleAxis /= dt;
258
259         aip.setBodyAngularVelocity(dOrAngleAxis);
260     }
261 }
262
263 void FGAIShip::Run(double dt) {
264     if (_fp_init)
265         ProcessFlightPlan(dt);
266
267     const string& type = getTypeString();
268
269     double alpha;
270     double rudder_limit;
271     double raw_roll;
272
273     // adjust speed
274     double speed_diff = tgt_speed - speed;
275
276     if (fabs(speed_diff) > 0.1) {
277
278         if (speed_diff > 0.0)
279             speed += _speed_constant * dt;
280
281         if (speed_diff < 0.0)
282             speed -= _speed_constant * dt;
283
284     }
285
286     // do not allow unreasonable speeds
287     SG_CLAMP_RANGE(speed, -_limit * 0.75, _limit);
288
289     // convert speed to degrees per second
290     speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
291         * speed * 1.686 / ft_per_deg_lat;
292     speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
293         * speed * 1.686 / ft_per_deg_lon;
294
295     // set new position
296     //cout << _name << " " << type << " run: " << _elevation_m << " " <<_elevation_ft << endl;
297     pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
298     pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
299     pos.setElevationFt(tgt_altitude_ft);
300     pitch = tgt_pitch;
301
302     // adjust heading based on current _rudder angle
303     if (turn_radius_ft <= 0)
304         turn_radius_ft = 0; // don't allow nonsense values
305
306     if (_rudder > 45)
307         _rudder = 45;
308
309     if (_rudder < -45)
310         _rudder = -45;
311
312
313     //we assume that at slow speed ships will manoeuvre using engines/bow thruster
314         if(type == "ship" || type == "carrier" || type == "escort"){
315
316                 if (fabs(speed)<=5)
317                         _sp_turn_radius_ft = _fixed_turn_radius;
318                 else {
319                         // adjust turn radius for speed. The equation is very approximate.
320                         // we need to allow for negative speeds
321                         _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
322                 }
323
324         } else {
325                 
326                 if (fabs(speed) <= 40)
327            _sp_turn_radius_ft = _fixed_turn_radius;
328                 else {
329                         // adjust turn radius for speed. 
330                         _sp_turn_radius_ft = turn_radius_ft;
331                 }
332         }
333
334
335     if (_rudder <= -0.25 || _rudder >= 0.25) {
336         // adjust turn radius for _rudder angle. The equation is even more approximate.
337         float a = 19;
338         float b = -0.2485;
339         float c = 0.543;
340
341         _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
342
343         // calculate the angle, alpha, subtended by the arc traversed in time dt
344         alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
345         //cout << _name << " alpha " << alpha << endl;
346         // make sure that alpha is applied in the right direction
347         hdg += alpha * sign(_rudder);
348
349         SG_NORMALIZE_RANGE(hdg, 0.0, 360.0);
350
351         //adjust roll for rudder angle and speed. Another bit of voodoo
352         raw_roll = _roll_factor * speed * _rudder;
353     } else {
354         // _rudder angle is 0
355         raw_roll = 0;
356     }
357
358     //low pass filter
359     if (speed < 0)
360         roll = -roll;
361
362     roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
363
364     // adjust target _rudder angle if heading lock engaged
365     double rudder_diff = 0.0;
366     if (_hdg_lock) {
367         double rudder_sense = 0.0;
368         double diff = fabs(hdg - tgt_heading);
369         //cout << "_rudder diff" << diff << endl;
370         if (diff > 180)
371             diff = fabs(diff - 360);
372
373         double sum = hdg + diff;
374
375         if (sum > 360.0)
376             sum -= 360.0;
377
378         if (fabs(sum - tgt_heading)< 1.0)
379             rudder_sense = 1.0;
380         else
381             rudder_sense = -1.0;
382
383         if (speed < 0)
384             rudder_sense = -rudder_sense;
385
386         if (diff < 15)
387             _tgt_rudder = diff * rudder_sense;
388         else
389             _tgt_rudder = 45 * rudder_sense;
390
391         rudder_diff = _tgt_rudder - _rudder;
392     }
393
394     // set the _rudder limit by speed
395     if (type == "ship" || type == "carrier" || type == "escort"){
396
397         if (speed <= 40)
398             rudder_limit = (-0.825 * speed) + 35;
399         else
400             rudder_limit = 2;
401
402     } else
403         rudder_limit = 20;
404
405     if (fabs(rudder_diff)> 0.1) { // apply dead zone
406
407         if (rudder_diff > 0.0) {
408             _rudder += _rudder_constant * dt;
409
410             if (_rudder > rudder_limit) // apply the _rudder limit
411                 _rudder = rudder_limit;
412
413         } else if (rudder_diff < 0.0) {
414             _rudder -= _rudder_constant * dt;
415
416             if (_rudder < -rudder_limit)
417                 _rudder = -rudder_limit;
418
419         }
420
421         // do calculations for radar
422         UpdateRadar(manager);
423     }
424 }//end function
425
426 void FGAIShip::AccelTo(double speed) {
427     tgt_speed = speed;
428 }
429
430 void FGAIShip::PitchTo(double angle) {
431     tgt_pitch = angle;
432 }
433
434 void FGAIShip::RollTo(double angle) {
435     tgt_roll = angle;
436 }
437
438 void FGAIShip::YawTo(double angle) {
439 }
440
441 void FGAIShip::ClimbTo(double altitude) {
442     tgt_altitude_ft = altitude;
443     _setAltitude(altitude);
444 }
445
446 void FGAIShip::TurnTo(double heading) {
447     tgt_heading = heading - _lead_angle + _tow_angle;
448     SG_NORMALIZE_RANGE(tgt_heading, 0.0, 360.0);
449     _hdg_lock = true;
450 }
451
452 double FGAIShip::sign(double x) {
453     if (x < 0.0)
454         return -1.0;
455     else
456         return 1.0;
457 }
458
459 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
460     fp = f;
461 }
462
463 void FGAIShip::setStartTime(const string& st) {
464     _start_time = st;
465 }
466
467 void FGAIShip::setUntilTime(const string& ut) {
468     _until_time = ut;
469     props->setStringValue("waypoint/wait-until-time", _until_time.c_str());
470 }
471
472 void FGAIShip::setCurrName(const string& c) {
473     _curr_name = c;
474     props->setStringValue("waypoint/name-curr", _curr_name.c_str());
475 }
476
477 void FGAIShip::setNextName(const string& n) {
478     _next_name = n;
479     props->setStringValue("waypoint/name-next", _next_name.c_str());
480 }
481
482 void FGAIShip::setPrevName(const string& p) {
483     _prev_name = p;
484     props->setStringValue("waypoint/name-prev", _prev_name.c_str());
485 }
486
487 void FGAIShip::setRepeat(bool r) {
488     _repeat = r;
489 }
490
491 void FGAIShip::setRestart(bool r) {
492     _restart = r;
493 }
494
495 void FGAIShip::setMissed(bool m) {
496     _missed = m;
497     props->setBoolValue("waypoint/missed", _missed);
498 }
499
500 void FGAIShip::setRudder(float r) {
501     _rudder = r;
502 }
503
504 void FGAIShip::setRoll(double rl) {
505     roll = rl;
506 }
507
508 void FGAIShip::setLeadAngleGain(double g) {
509     _lead_angle_gain = g;
510 }
511
512 void FGAIShip::setLeadAngleLimit(double l) {
513     _lead_angle_limit = l;
514 }
515
516 void FGAIShip::setLeadAngleProp(double p) {
517     _proportion = p;
518 }
519
520 void FGAIShip::setRudderConstant(double rc) {
521     _rudder_constant = rc;
522 }
523
524 void FGAIShip::setSpeedConstant(double sc) {
525     _speed_constant = sc;
526 }
527
528 void FGAIShip::setFixedTurnRadius(double ftr) {
529     _fixed_turn_radius = ftr;
530 }
531
532 void FGAIShip::setRollFactor(double rf) {
533     _roll_factor = rf * -0.0083335;
534 }
535
536 void FGAIShip::setInitialTunnel(bool t) {
537     _initial_tunnel = t;
538     setTunnel(_initial_tunnel);
539 }
540
541 void FGAIShip::setTunnel(bool t) {
542     _tunnel = t;
543 }
544
545 void FGAIShip::setWPNames() {
546
547     if (prev != 0)
548         setPrevName(prev->getName());
549     else
550         setPrevName("");
551
552     if (curr != 0)
553         setCurrName(curr->getName());
554     else{
555         setCurrName("");
556         SG_LOG(SG_AI, SG_ALERT, "AIShip: current wp name error" );
557     }
558
559     if (next != 0)
560         setNextName(next->getName());
561     else
562         setNextName("");
563
564     SG_LOG(SG_AI, SG_DEBUG, "AIShip: prev wp name " << prev->getName());
565     SG_LOG(SG_AI, SG_DEBUG, "AIShip: current wp name " << curr->getName());
566     SG_LOG(SG_AI, SG_DEBUG, "AIShip: next wp name " << next->getName());
567
568 }
569
570 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
571
572     double course, distance, az2;
573
574     //calculate the bearing and range of the second pos from the first
575     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
576     distance *= SG_METER_TO_NM;
577     return distance;
578 }
579
580 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
581
582     double course, distance, recip;
583
584     //calculate the bearing and range of the second pos from the first
585     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
586     if (tgt_speed >= 0) {
587         return course;
588         SG_LOG(SG_AI, SG_DEBUG, "AIShip: course " << course);
589     } else {
590         return recip;
591         SG_LOG(SG_AI, SG_DEBUG, "AIShip: recip " << recip);
592     }
593 }
594
595 void FGAIShip::ProcessFlightPlan(double dt) {
596
597     if ( dt < 0.00001 ) {
598         return;
599     }
600
601     double time_sec = getDaySeconds();
602
603     _dt_count += dt;
604
605     ///////////////////////////////////////////////////////////////////////////
606     // Check Execution time (currently once every 1 sec)
607     // Add a bit of randomization to prevent the execution of all flight plans
608     // in synchrony, which can add significant periodic framerate flutter.
609     ///////////////////////////////////////////////////////////////////////////
610
611     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
612     if (_dt_count < _next_run && _start_sec < time_sec)
613         return;
614
615     _next_run = 0.05 + (0.025 * sg_random());
616
617     double until_time_sec = 0;
618     _missed = false;
619
620     // check to see if we've reached the point for our next turn
621     // if the range to the waypoint is less than the calculated turn
622     // radius we can start the turn to the next leg
623     _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
624     _range_rate = (_wp_range - _old_range) / _dt_count;
625     double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
626     // we need to try to identify a _missed waypoint
627
628     // calculate the time needed to turn through an arc of 90 degrees,
629     // and allow a time error
630     if (speed != 0)
631         _missed_time_sec = 10 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
632     else
633         _missed_time_sec = 10;
634
635     _missed_range = 4 * sp_turn_radius_nm;
636
637     //cout << _name << " range_rate " << _range_rate << " " << _new_waypoint<< endl ;
638     //if ((_range_rate > 0) && !_new_waypoint){
639     if (_range_rate > 0 && _wp_range < _missed_range && !_new_waypoint){
640         _missed_count += _dt_count;
641     }
642
643     if (_missed_count >= 120)
644         setMissed(true);
645     else if (_missed_count >= _missed_time_sec)
646         setMissed(true);
647     else
648         setMissed(false);
649
650     _old_range = _wp_range;
651     setWPNames();
652
653     if ((_wp_range < (sp_turn_radius_nm * 1.25)) || _missed || (_waiting && !_new_waypoint)) {
654
655         if (_next_name == "TUNNEL"){
656             _tunnel = !_tunnel;
657
658             SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " " << sp_turn_radius_nm );
659
660             fp->IncrementWaypoint(false);
661             next = fp->getNextWaypoint();
662
663             if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
664                 || next->getName() == "END" || next->getName() == "TUNNEL")
665                 return;
666
667             prev = curr;
668             fp->IncrementWaypoint(false);
669             curr = fp->getCurrentWaypoint();
670             next = fp->getNextWaypoint();
671
672         }else if(_next_name == "END" || fp->getNextWaypoint() == 0) {
673
674             if (_repeat) {
675                 SG_LOG(SG_AI, SG_INFO, "AIShip: "<< _name << " Flightplan repeating ");
676                 fp->restart();
677                 prev = curr;
678                 curr = fp->getCurrentWaypoint();
679                 next = fp->getNextWaypoint();
680                 setWPNames();
681                 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
682                 _old_range = _wp_range;
683                 _range_rate = 0;
684                 _new_waypoint = true;
685                 _missed_count = 0;
686                 _lead_angle = 0;
687                 AccelTo(prev->getSpeed());
688             } else if (_restart){
689                 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " Flightplan restarting ");
690                 _missed_count = 0;
691                 initFlightPlan();
692             } else {
693                 SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " Flightplan dying ");
694                 setDie(true);
695                 _dt_count = 0;
696                 return;
697             }
698
699         } else if (_next_name == "WAIT") {
700
701             if (_wait_count < next->getTime_sec()) {
702                 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " waiting ");
703                 setSpeed(0);
704                 _waiting = true;
705                 _wait_count += _dt_count;
706                 _dt_count = 0;
707                 _lead_angle = 0;
708                 return;
709             } else {
710                 SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name
711                     << " wait done: getting new waypoints ");
712                 _waiting = false;
713                 _wait_count = 0;
714                 fp->IncrementWaypoint(false);
715                 next = fp->getNextWaypoint();
716
717                 if (next->getName() == "WAITUNTIL" || next->getName() == "WAIT"
718                     || next->getName() == "END" || next->getName() == "TUNNEL")
719                     return;
720
721                 prev = curr;
722                 fp->IncrementWaypoint(false);
723                 curr = fp->getCurrentWaypoint();
724                 next = fp->getNextWaypoint();
725             }
726
727         } else if (_next_name == "WAITUNTIL") {
728             time_sec = getDaySeconds();
729             until_time_sec = processTimeString(next->getTime());
730             _until_time = next->getTime();
731             setUntilTime(next->getTime());
732             if (until_time_sec > time_sec) {
733                 SG_LOG(SG_AI, SG_INFO, "AIShip: " << _name << " "
734                     << curr->getName() << " waiting until: "
735                     << _until_time << " " << until_time_sec << " now " << time_sec );
736                 setSpeed(0);
737                 _lead_angle = 0;
738                 _waiting = true;
739                 return;
740             } else {
741                 SG_LOG(SG_AI, SG_INFO, "AIShip: "
742                     << _name << " wait until done: getting new waypoints ");
743                 setUntilTime("");
744                 fp->IncrementWaypoint(false);
745
746                 while (next->getName() == "WAITUNTIL") {
747                     fp->IncrementWaypoint(false);
748                     next = fp->getNextWaypoint();
749                 }
750
751                 if (next->getName() == "WAIT")
752                     return;
753
754                 prev = curr;
755                 fp->IncrementWaypoint(false);
756                 curr = fp->getCurrentWaypoint();
757                 next = fp->getNextWaypoint();
758                 _waiting = false;
759             }
760
761         } else {
762             //now reorganise the waypoints, so that next becomes current and so on
763             SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
764             fp->IncrementWaypoint(false);
765             prev = fp->getPreviousWaypoint(); //first waypoint
766             curr = fp->getCurrentWaypoint();  //second waypoint
767             next = fp->getNextWaypoint();     //third waypoint (might not exist!)
768         }
769
770         setWPNames();
771         _new_waypoint = true;
772         _missed_count = 0;
773         _range_rate = 0;
774         _lead_angle = 0;
775         _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
776         _old_range = _wp_range;
777         setWPPos();
778         object_type type = getType();
779
780         if (type != 10)
781             AccelTo(prev->getSpeed());
782
783         _curr_alt = curr->getAltitude();
784         _prev_alt = prev->getAltitude();
785
786     } else {
787         _new_waypoint = false;
788     }
789
790     //   now revise the required course for the next way point
791     _course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->getLatitude(), curr->getLongitude());
792
793     if (fgIsFinite(_course))
794         TurnTo(_course);
795     else
796         SG_LOG(SG_AI, SG_ALERT, "AIShip: Bearing or Range is not a finite number");
797
798     _dt_count = 0;
799 } // end Processing FlightPlan
800
801 bool FGAIShip::initFlightPlan() {
802
803     SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " initializing waypoints ");
804
805     bool init = false;
806     _start_sec = 0;
807     _tunnel = _initial_tunnel;
808
809     fp->restart();
810     fp->IncrementWaypoint(false);
811
812     prev = fp->getPreviousWaypoint(); //first waypoint
813     curr = fp->getCurrentWaypoint();  //second waypoint
814     next = fp->getNextWaypoint();     //third waypoint (might not exist!)
815
816     while (curr->getName() == "WAIT" || curr->getName() == "WAITUNTIL") {  // don't wait when initialising
817         SG_LOG(SG_AI, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
818         fp->IncrementWaypoint(false);
819         curr = fp->getCurrentWaypoint();
820         next = fp->getNextWaypoint();
821     } // end while loop
822
823     if (!_start_time.empty()){
824         _start_sec = processTimeString(_start_time);
825         double day_sec = getDaySeconds();
826
827         if (_start_sec < day_sec){
828             //cout << "flight plan has already started " << _start_time << endl;
829             init = advanceFlightPlan(_start_sec, day_sec);
830
831         } else if (_start_sec > day_sec && _repeat) {
832             //cout << "flight plan has not started, " << _start_time;
833             //cout << "offsetting start time by -24 hrs" << endl;
834             _start_sec -= _day;
835             init = advanceFlightPlan(_start_sec, day_sec);
836         }
837
838         if (init)
839             _start_sec = 0; // set to zero for an immediate start of the Flight Plan
840         else {
841             fp->restart();
842             fp->IncrementWaypoint(false);
843             prev = fp->getPreviousWaypoint();
844             curr = fp->getCurrentWaypoint();
845             next = fp->getNextWaypoint();
846             return false;
847         }
848
849     } else {
850         setLatitude(prev->getLatitude());
851         setLongitude(prev->getLongitude());
852         setSpeed(prev->getSpeed());
853     }
854
855     setWPNames();
856     setHeading(getCourse(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude()));
857     _wp_range = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
858     _old_range = _wp_range;
859     _range_rate = 0;
860     _hdg_lock = true;
861     _missed = false;
862     _missed_count = 0;
863     _new_waypoint = true;
864
865     SG_LOG(SG_AI, SG_ALERT, "AIShip: " << _name << " done initialising waypoints " << _tunnel);
866     if (prev)
867         init = true;
868
869     if (init)
870         return true;
871     else
872         return false;
873
874 } // end of initialization
875
876
877 double FGAIShip::processTimeString(const string& theTime) {
878
879     int Hour;
880     int Minute;
881     int Second;
882
883     // first split theTime string into
884     //  hour, minute, second and convert to int;
885     Hour   = atoi(theTime.substr(0,2).c_str());
886     Minute = atoi(theTime.substr(3,5).c_str());
887     Second = atoi(theTime.substr(6,8).c_str());
888
889     // offset by a day-sec to allow for starting a day earlier
890     double time_seconds = Hour * 3600
891         + Minute * 60
892         + Second;
893
894     return time_seconds;
895 }
896
897 double FGAIShip::getDaySeconds () {
898     // Date and time
899     struct tm *t = globals->get_time_params()->getGmt();
900
901     double day_seconds = t->tm_hour * 3600
902         + t->tm_min * 60
903         + t->tm_sec;
904
905     return day_seconds;
906 }
907
908 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
909
910     double elapsed_sec = start_sec;
911     double distance_nm = 0;
912
913     //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
914
915     while ( elapsed_sec < day_sec ) {
916
917         if (next->getName() == "END" || fp->getNextWaypoint() == 0) {
918
919             if (_repeat ) {
920                 //cout << _name << ": " << "restarting flightplan" << endl;
921                 fp->restart();
922                 curr = fp->getCurrentWaypoint();
923                 next = fp->getNextWaypoint();
924             } else {
925                 //cout << _name << ": " << "ending flightplan" << endl;
926                 setDie(true);
927                 return false;
928             }
929
930         } else if (next->getName() == "WAIT") {
931             //cout << _name << ": begin WAIT: " << prev->name << " ";
932             //cout << curr->name << " " << next->name << endl;
933
934             elapsed_sec += next->getTime_sec();
935
936             if ( elapsed_sec >= day_sec)
937                 continue;
938
939             fp->IncrementWaypoint(false);
940             next = fp->getNextWaypoint();
941
942             if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT"
943                 && next->getName() != "END") {
944                     prev = curr;
945                     fp->IncrementWaypoint(false);
946                     curr = fp->getCurrentWaypoint();
947                     next = fp->getNextWaypoint();
948             }
949
950         } else if (next->getName() == "WAITUNTIL") {
951             double until_sec = processTimeString(next->getTime());
952
953             if (until_sec > _start_sec && start_sec < 0)
954                 until_sec -= _day;
955
956             if (elapsed_sec < until_sec)
957                 elapsed_sec = until_sec;
958
959             if (elapsed_sec >= day_sec )
960                 break;
961
962             fp->IncrementWaypoint(false);
963             next = fp->getNextWaypoint();
964
965             if (next->getName() != "WAITUNTIL" && next->getName() != "WAIT") {
966                 prev = curr;
967                 fp->IncrementWaypoint(false);
968                 curr = fp->getCurrentWaypoint();
969                 next = fp->getNextWaypoint();
970             }
971
972             //cout << _name << ": end WAITUNTIL: ";
973             //cout << prev->name << " " << curr->name << " " << next->name <<  endl;
974
975         } else {
976             distance_nm = getRange(prev->getLatitude(), prev->getLongitude(), curr->getLatitude(), curr->getLongitude());
977             elapsed_sec += distance_nm * 60 * 60 / prev->getSpeed();
978
979             if (elapsed_sec >= day_sec)
980                 continue;
981
982             fp->IncrementWaypoint(false);
983             prev = fp->getPreviousWaypoint();
984             curr = fp->getCurrentWaypoint();
985             next = fp->getNextWaypoint();
986         }
987
988     }   // end while
989
990     // the required position lies between the previous and current waypoints
991     // so we will calculate the distance back up the track from the current waypoint
992     // then calculate the lat and lon.
993
994     //cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
995     //    << " " << day_sec << endl;
996
997     double time_diff = elapsed_sec - day_sec;
998     double lat, lon, recip;
999
1000     //cout << " time diff " << time_diff << endl;
1001
1002     if (next->getName() == "WAIT" ){
1003         setSpeed(0);
1004         lat = curr->getLatitude();
1005         lon = curr->getLongitude();
1006         _wait_count= time_diff;
1007         _waiting = true;
1008     } else if (next->getName() == "WAITUNTIL") {
1009         setSpeed(0);
1010         lat = curr->getLatitude();
1011         lon = curr->getLongitude();
1012         _waiting = true;
1013     } else {
1014         setSpeed(prev->getSpeed());
1015         distance_nm = speed * time_diff / (60 * 60);
1016         double brg = getCourse(curr->getLatitude(), curr->getLongitude(), prev->getLatitude(), prev->getLongitude());
1017
1018         //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
1019         //    << " lat "  << curr->latitude << " lon " << curr->longitude
1020         //    << " distance m " << distance_nm * SG_NM_TO_METER << endl;
1021
1022         lat = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1023             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1024         lon = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1025             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1026         recip = geo_direct_wgs_84 (curr->getLatitude(), curr->getLongitude(), brg,
1027             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
1028     }
1029
1030     setLatitude(lat);
1031     setLongitude(lon);
1032
1033     return true;
1034 }
1035
1036 void FGAIShip::setWPPos() {
1037
1038     if (curr->getName() == "END" || curr->getName() == "WAIT"
1039         || curr->getName() == "WAITUNTIL" || curr->getName() == "TUNNEL"){
1040             //cout << curr->name << " returning" << endl;
1041             return;
1042     }
1043
1044     double elevation_m = 0;
1045     wppos.setLatitudeDeg(curr->getLatitude());
1046     wppos.setLongitudeDeg(curr->getLongitude());
1047     wppos.setElevationM(0);
1048
1049     if (curr->getOn_ground()){
1050
1051         if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(wppos, 3000),
1052             elevation_m, NULL, 0)){
1053                 wppos.setElevationM(elevation_m);
1054         }
1055
1056         //cout << curr->name << " setting measured  elev " << elevation_m << endl;
1057
1058     } else {
1059         wppos.setElevationM(curr->getAltitude());
1060         //cout << curr->name << " setting FP elev " << elevation_m << endl;
1061     }
1062
1063     curr->setAltitude(wppos.getElevationM());
1064
1065 }
1066
1067 void FGAIShip::setXTrackError() {
1068
1069     double course = getCourse(prev->getLatitude(), prev->getLongitude(),
1070         curr->getLatitude(), curr->getLongitude());
1071     double brg = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
1072         curr->getLatitude(), curr->getLongitude());
1073     double xtrack_error_nm = sin((course - brg)* SG_DEGREES_TO_RADIANS) * _wp_range;
1074     double factor = -0.0045 * speed + 1;
1075     double limit = _lead_angle_limit * factor;
1076
1077     if (_wp_range > 0){
1078         _lead_angle = atan2(xtrack_error_nm,(_wp_range * _proportion)) * SG_RADIANS_TO_DEGREES;
1079     } else
1080         _lead_angle = 0;
1081
1082     _lead_angle *= _lead_angle_gain * factor;
1083     _xtrack_error = xtrack_error_nm * 6076.1155;
1084
1085     SG_CLAMP_RANGE(_lead_angle, -limit, limit);
1086
1087 }