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