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