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