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