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