]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIShip.cxx
Clear chat messages when an aircraft becomes inactive in the property tree.
[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 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/timing/sg_time.hxx>
34 #include <simgear/math/sg_random.h>
35
36 #include "AIShip.hxx"
37
38
39 FGAIShip::FGAIShip(object_type ot) :
40     FGAIBase(ot),
41     _dt_count(0),
42     _next_run(0)
43 {
44 }
45
46 FGAIShip::~FGAIShip() {
47 }
48
49 void FGAIShip::readFromScenario(SGPropertyNode* scFileNode) {
50
51     if (!scFileNode)
52         return;
53
54     FGAIBase::readFromScenario(scFileNode);
55
56     setRudder(scFileNode->getFloatValue("rudder", 0.0));
57     setName(scFileNode->getStringValue("name", "Titanic"));
58     setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
59     std::string flightplan = scFileNode->getStringValue("flightplan");
60     setRepeat(scFileNode->getBoolValue("repeat", false));
61     setStartTime(scFileNode->getStringValue("time", ""));
62
63     if (!flightplan.empty()) {
64         FGAIFlightPlan* fp = new FGAIFlightPlan(flightplan);
65         setFlightPlan(fp);
66     }
67
68 }
69
70 bool FGAIShip::init(bool search_in_AI_path) {
71     prev = 0; // the one behind you
72     curr = 0; // the one ahead
73     next = 0; // the next plus 1
74
75     _until_time = "";
76
77     props->setStringValue("name", _name.c_str());
78     props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
79     props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
80     props->setStringValue("position/waypoint-name-next", _next_name.c_str());
81     props->setStringValue("submodels/path", _path.c_str());
82     props->setStringValue("position/waypoint-start-time", _start_time.c_str());
83     props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
84
85     _hdg_lock = false;
86     _rudder = 0.0;
87     no_roll = false;
88
89     _rudder_constant = 0.5;
90     _roll_constant = 0.001;
91     _speed_constant = 0.05;
92     _hdg_constant = 0.01;
93     _roll_factor = -0.0083335;
94
95     _rd_turn_radius_ft = _sp_turn_radius_ft = turn_radius_ft;
96
97     _fp_init = false;
98     _missed = false;
99     _waiting = false;
100     _new_waypoint = true;
101
102     _missed_count = 0;
103     _wait_count = 0;
104     _missed_time_sec = 30;
105
106     _day = 86400;
107
108
109     _wp_range = _old_range = 0;
110     _range_rate = 0;
111
112     if (fp)
113         _fp_init = initFlightPlan();
114
115     return FGAIBase::init(search_in_AI_path);
116 }
117
118
119 void FGAIShip::bind() {
120     FGAIBase::bind();
121
122     props->tie("surface-positions/rudder-pos-deg",
123         SGRawValuePointer<float>(&_rudder));
124     props->tie("controls/heading-lock",
125         SGRawValuePointer<bool>(&_hdg_lock));
126     props->tie("controls/tgt-speed-kts",
127         SGRawValuePointer<double>(&tgt_speed));
128     props->tie("controls/tgt-heading-degs",
129         SGRawValuePointer<double>(&tgt_heading));
130     props->tie("controls/constants/rudder",
131         SGRawValuePointer<double>(&_rudder_constant));
132     props->tie("controls/constants/roll-factor",
133         SGRawValuePointer<double>(&_roll_factor));
134     props->tie("controls/constants/roll",
135         SGRawValuePointer<double>(&_roll_constant));
136     props->tie("controls/constants/rudder",
137         SGRawValuePointer<double>(&_rudder_constant));
138     props->tie("controls/constants/speed",
139         SGRawValuePointer<double>(&_speed_constant));
140     props->tie("position/waypoint-range-nm",
141         SGRawValuePointer<double>(&_wp_range));
142     props->tie("position/waypoint-range-old-nm",
143         SGRawValuePointer<double>(&_old_range));
144     props->tie("position/waypoint-range-rate-nm-sec",
145         SGRawValuePointer<double>(&_range_rate));
146     props->tie("position/waypoint-new",
147         SGRawValuePointer<bool>(&_new_waypoint));
148     props->tie("position/waypoint-missed",
149         SGRawValuePointer<bool>(&_missed));
150     props->tie("position/waypoint-missed-count",
151         SGRawValuePointer<double>(&_missed_count));
152     props->tie("position/waypoint-missed-time-sec",
153         SGRawValuePointer<double>(&_missed_time_sec));
154     props->tie("position/waypoint-wait-count",
155         SGRawValuePointer<double>(&_wait_count));
156     props->tie("position/waypoint-waiting",
157         SGRawValuePointer<bool>(&_waiting));
158     props->tie("submodels/serviceable",
159         SGRawValuePointer<bool>(&_serviceable));
160 }
161
162 void FGAIShip::unbind() {
163     FGAIBase::unbind();
164     props->untie("surface-positions/rudder-pos-deg");
165     props->untie("controls/heading-lock");
166     props->untie("controls/tgt-speed-kts");
167     props->untie("controls/tgt-heading-degs");
168     props->untie("controls/constants/roll");
169     props->untie("controls/constants/rudder");
170     props->untie("controls/constants/roll-factor");
171     props->untie("controls/constants/speed");
172     props->untie("position/waypoint-range-nm");
173     props->untie("position/waypoint-range-old-nm");
174     props->untie("position/waypoint-range-rate-nm-sec");
175     props->untie("position/waypoint-new");
176     props->untie("position/waypoint-missed");
177     props->untie("position/waypoint-missed-count");
178     props->untie("position/waypoint-missed-time-sec");
179     props->untie("position/waypoint-wait-count");
180     props->untie("position/waypoint-waiting");
181     props->untie("submodels/serviceable");
182 }
183
184 void FGAIShip::update(double dt) {
185     FGAIBase::update(dt);
186     Run(dt);
187     Transform();
188 }
189
190 void FGAIShip::Run(double dt) {
191     //cout << _name << " init: " << _fp_init << endl;
192     if (_fp_init)
193         ProcessFlightPlan(dt);
194
195     //    double speed_north_deg_sec;
196     //    double speed_east_deg_sec;
197     double alpha;
198     double rudder_limit;
199     double raw_roll;
200
201     // adjust speed
202     double speed_diff = tgt_speed - speed;
203
204     if (fabs(speed_diff) > 0.1) {
205
206         if (speed_diff > 0.0)
207             speed += _speed_constant * dt;
208
209         if (speed_diff < 0.0)
210             speed -= _speed_constant * dt;
211
212     }
213
214     // do not allow unreasonable ship speeds
215     if (speed > 40)
216         speed = 40;
217
218     // convert speed to degrees per second
219     speed_north_deg_sec = cos(hdg / SGD_RADIANS_TO_DEGREES)
220         * speed * 1.686 / ft_per_deg_lat;
221     speed_east_deg_sec = sin(hdg / SGD_RADIANS_TO_DEGREES)
222         * speed * 1.686 / ft_per_deg_lon;
223
224     // set new position
225     pos.setLatitudeDeg(pos.getLatitudeDeg() + speed_north_deg_sec * dt);
226     pos.setLongitudeDeg(pos.getLongitudeDeg() + speed_east_deg_sec * dt);
227
228     // adjust heading based on current _rudder angle
229
230     //cout << "turn_radius_ft " << turn_radius_ft ;
231
232     if (turn_radius_ft <= 0)
233         turn_radius_ft = 0; // don't allow nonsense values
234
235     if (_rudder > 45)
236         _rudder = 45;
237
238     if (_rudder < -45)
239         _rudder = -45;
240
241     //we assume that at slow speed ships will manoeuvre using engines/bow thruster
242     if (fabs(speed)<=5)
243         _sp_turn_radius_ft = 500;
244     else
245         // adjust turn radius for speed. The equation is very approximate.
246         // we need to allow for negative speeds
247         _sp_turn_radius_ft = 10 * pow ((fabs(speed) - 15), 2) + turn_radius_ft;
248
249     //cout << " speed turn radius " << _sp_turn_radius_ft ;
250
251     if (_rudder <= -0.25 || _rudder >= 0.25) {
252         // adjust turn radius for _rudder angle. The equation is even more approximate.
253         float a = 19;
254         float b = -0.2485;
255         float c = 0.543;
256
257         _rd_turn_radius_ft = (a * exp(b * fabs(_rudder)) + c) * _sp_turn_radius_ft;
258
259         //cout <<" _rudder turn radius " << _rd_turn_radius_ft << endl;
260
261         // calculate the angle, alpha, subtended by the arc traversed in time dt
262         alpha = ((speed * 1.686 * dt) / _rd_turn_radius_ft) * SG_RADIANS_TO_DEGREES;
263
264         // make sure that alpha is applied in the right direction
265         hdg += alpha * sign(_rudder);
266
267         if (hdg > 360.0)
268             hdg -= 360.0;
269
270         if (hdg < 0.0)
271             hdg += 360.0;
272
273         //adjust roll for rudder angle and speed. Another bit of voodoo
274         raw_roll = _roll_factor * speed * _rudder;
275     } else {
276         // _rudder angle is 0
277         raw_roll = 0;
278     }
279
280     //low pass filter
281     if (speed < 0)
282         roll = -roll;
283
284     roll = (raw_roll * _roll_constant) + (roll * (1 - _roll_constant));
285
286     // adjust target _rudder angle if heading lock engaged
287     double rudder_diff = 0.0;
288     if (_hdg_lock) {
289         double rudder_sense = 0.0;
290         double diff = fabs(hdg - tgt_heading);
291         //cout << "_rudder diff" << diff << endl;
292         if (diff > 180)
293             diff = fabs(diff - 360);
294
295         double sum = hdg + diff;
296
297         if (sum > 360.0)
298             sum -= 360.0;
299
300         if (fabs(sum - tgt_heading)< 1.0)
301             rudder_sense = 1.0;
302         else
303             rudder_sense = -1.0;
304
305         if (speed < 0)
306             rudder_sense = -rudder_sense;
307
308         if (diff < 15)
309             _tgt_rudder = diff * rudder_sense;
310         else
311             _tgt_rudder = 45 * rudder_sense;
312
313         rudder_diff = _tgt_rudder - _rudder;
314     }
315
316     // set the _rudder limit by speed
317     if (speed <= 40)
318         rudder_limit = (-0.825 * speed) + 35;
319     else
320         rudder_limit = 2;
321
322     if (fabs(rudder_diff)> 0.1) { // apply dead zone
323
324         if (rudder_diff > 0.0) {
325             _rudder += _rudder_constant * dt;
326
327             if (_rudder > rudder_limit) // apply the _rudder limit
328                 _rudder = rudder_limit;
329
330         } else if (rudder_diff < 0.0) {
331             _rudder -= _rudder_constant * dt;
332
333             if (_rudder < -rudder_limit)
334                 _rudder = -rudder_limit;
335
336         }
337
338         // do calculations for radar
339         UpdateRadar(manager);
340     }
341 }//end function
342
343 void FGAIShip::AccelTo(double speed) {
344     tgt_speed = speed;
345 }
346
347 void FGAIShip::PitchTo(double angle) {
348     tgt_pitch = angle;
349 }
350
351 void FGAIShip::RollTo(double angle) {
352     tgt_roll = angle;
353 }
354
355 void FGAIShip::YawTo(double angle) {
356 }
357
358 void FGAIShip::ClimbTo(double altitude) {
359 }
360
361
362 void FGAIShip::TurnTo(double heading) {
363     tgt_heading = heading;
364     _hdg_lock = true;
365 }
366
367 double FGAIShip::sign(double x) {
368     if (x < 0.0)
369         return -1.0;
370     else
371         return 1.0;
372 }
373
374 void FGAIShip::setFlightPlan(FGAIFlightPlan* f) {
375     fp = f;
376 }
377
378 void FGAIShip::setName(const string& n) {
379     _name = n;
380 }
381
382 void FGAIShip::setStartTime(const string& st) {
383     _start_time = st;
384 }
385
386 void FGAIShip::setUntilTime(const string& ut) {
387     _until_time = ut;
388     props->setStringValue("position/waypoint-wait-until-time", _until_time.c_str());
389 }
390
391 void FGAIShip::setCurrName(const string& c) {
392     _curr_name = c;
393     props->setStringValue("position/waypoint-name-curr", _curr_name.c_str());
394 }
395
396 void FGAIShip::setNextName(const string& n) {
397     _next_name = n;
398     props->setStringValue("position/waypoint-name-next", _next_name.c_str());
399 }
400
401 void FGAIShip::setPrevName(const string& p) {
402     _prev_name = p;
403     props->setStringValue("position/waypoint-name-prev", _prev_name.c_str());
404 }
405
406 void FGAIShip::setRepeat(bool r) {
407     _repeat = r;
408 }
409
410 void FGAIShip::setMissed(bool m) {
411     _missed = m;
412     props->setBoolValue("position/waypoint-missed", _missed);
413 }
414
415 void FGAIShip::setRudder(float r) {
416     _rudder = r;
417 }
418
419 void FGAIShip::setRoll(double rl) {
420     roll = rl;
421 }
422
423 void FGAIShip::setWPNames() {
424
425     if (prev != 0)
426         setPrevName(prev->name);
427     else
428         setPrevName("");
429
430     setCurrName(curr->name);
431
432     if (next != 0)
433         setNextName(next->name);
434     else
435         setNextName("");
436
437     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: prev wp name " << prev->name);
438     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: current wp name " << curr->name);
439     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: next wp name " << next->name);
440
441 }
442
443 double FGAIShip::getRange(double lat, double lon, double lat2, double lon2) const {
444
445     double course, distance, az2;
446
447     //calculate the bearing and range of the second pos from the first
448     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &az2, &distance);
449     distance *= SG_METER_TO_NM;
450     return distance;
451 }
452
453 double FGAIShip::getCourse(double lat, double lon, double lat2, double lon2) const {
454
455     double course, distance, recip;
456
457     //calculate the bearing and range of the second pos from the first
458     geo_inverse_wgs_84(lat, lon, lat2, lon2, &course, &recip, &distance);
459     if (tgt_speed >= 0) {
460         return course;
461     } else {
462         return recip;
463     }
464 }
465
466 void FGAIShip::ProcessFlightPlan(double dt) {
467
468     double time_sec = getDaySeconds();
469     double until_time_sec = 0;
470
471     _missed = false;
472     _dt_count += dt;
473
474     ///////////////////////////////////////////////////////////////////////////
475     // Check Execution time (currently once every 1 sec)
476     // Add a bit of randomization to prevent the execution of all flight plans
477     // in synchrony, which can add significant periodic framerate flutter.
478     ///////////////////////////////////////////////////////////////////////////
479
480     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
481     if (_dt_count < _next_run && _start_sec < time_sec)
482         return;
483
484     _next_run = 1.0 + (0.5 * sg_random());
485
486     // check to see if we've reached the point for our next turn
487     // if the range to the waypoint is less than the calculated turn
488     // radius we can start the turn to the next leg
489     _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
490     _range_rate = (_wp_range - _old_range) / _dt_count;
491     double sp_turn_radius_nm = _sp_turn_radius_ft / 6076.1155;
492
493     // we need to try to identify a _missed waypoint
494
495     // calculate the time needed to turn through an arc of 90 degrees, and allow an error of 30 secs
496     if (speed != 0)
497         _missed_time_sec = 30 + ((SGD_PI * sp_turn_radius_nm * 60 * 60) / (2 * fabs(speed)));
498     else
499         _missed_time_sec = 30;
500
501     if ((_range_rate > 0) && (_wp_range < 3 * sp_turn_radius_nm) && !_new_waypoint)
502         _missed_count += _dt_count;
503
504     if (_missed_count >= _missed_time_sec) {
505         setMissed(true);
506     } else {
507         setMissed(false);
508     }
509
510     _old_range = _wp_range;
511     setWPNames();
512
513     if ((_wp_range < sp_turn_radius_nm) || _missed || _waiting && !_new_waypoint) {
514
515         if (_next_name == "END") {
516
517             if (_repeat) {
518                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan restarting ");
519                 fp->restart();
520                 prev = curr;
521                 curr = fp->getCurrentWaypoint();
522                 next = fp->getNextWaypoint();
523                 setWPNames();
524                 _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
525                 _old_range = _wp_range;
526                 _range_rate = 0;
527                 _new_waypoint = true;
528                 _missed_count = 0;
529                 AccelTo(prev->speed);
530             } else {
531                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Flightplan dieing ");
532                 setDie(true);
533                 _dt_count = 0;
534                 return;
535             }
536
537         } else if (_next_name == "WAIT") {
538
539             if (_wait_count < next->time_sec) {
540                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting ");
541                 setSpeed(0);
542                 _waiting = true;
543                 _wait_count += _dt_count;
544                 _dt_count = 0;
545                 return;
546             } else {
547                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name
548                     << " wait done: getting new waypoints ");
549                 _waiting = false;
550                 _wait_count = 0;
551                 fp->IncrementWaypoint(false);
552                 next = fp->getNextWaypoint();
553
554                 if (next->name == "WAITUNTIL" || next->name == "WAIT"
555                         || next->name == "END")
556                     return;
557
558                 prev = curr;
559                 fp->IncrementWaypoint(false);
560                 curr = fp->getCurrentWaypoint();
561                 next = fp->getNextWaypoint();
562             }
563
564         } else if (_next_name == "WAITUNTIL") {
565             time_sec = getDaySeconds();
566             until_time_sec = processTimeString(next->time);
567             _until_time = next->time;
568             setUntilTime(next->time);
569             if (until_time_sec > time_sec) {
570                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " waiting until: "
571                     << _until_time << " " << until_time_sec << " now " << time_sec );
572                 setSpeed(0);
573                 _waiting = true;
574                 return;
575             } else {
576                 SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: "
577                     << _name << " wait until done: getting new waypoints ");
578                 setUntilTime("");
579                 fp->IncrementWaypoint(false);
580
581                 while (next->name == "WAITUNTIL") {
582                     fp->IncrementWaypoint(false);
583                     next = fp->getNextWaypoint();
584                 }
585
586                 if (next->name == "WAIT")
587                     return;
588
589                 prev = curr;
590                 fp->IncrementWaypoint(false);
591                 curr = fp->getCurrentWaypoint();
592                 next = fp->getNextWaypoint();
593                 _waiting = false;
594             }
595
596         } else {
597             //now reorganise the waypoints, so that next becomes current and so on
598             SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " getting new waypoints ");
599             fp->IncrementWaypoint(false);
600             prev = fp->getPreviousWaypoint(); //first waypoint
601             curr = fp->getCurrentWaypoint();  //second waypoint
602             next = fp->getNextWaypoint();     //third waypoint (might not exist!)
603         }
604
605         setWPNames();
606         _new_waypoint = true;
607         _missed_count = 0;
608         _range_rate = 0;
609         _wp_range = getRange(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
610         _old_range = _wp_range;
611         AccelTo(prev->speed);
612     } else {
613         _new_waypoint = false;
614     }
615
616     //   now revise the required course for the next way point
617     double course = getCourse(pos.getLatitudeDeg(), pos.getLongitudeDeg(), curr->latitude, curr->longitude);
618
619     if (finite(course))
620         TurnTo(course);
621     else
622         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: Bearing or Range is not a finite number");
623
624      _dt_count = 0;
625 } // end Processing FlightPlan
626
627 bool FGAIShip::initFlightPlan() {
628
629     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " initializing waypoints ");
630
631     bool init = false;
632
633     _start_sec = 0;
634
635     fp->restart();
636     fp->IncrementWaypoint(false);
637
638     prev = fp->getPreviousWaypoint(); //first waypoint
639     curr = fp->getCurrentWaypoint();  //second waypoint
640     next = fp->getNextWaypoint();     //third waypoint (might not exist!)
641
642     while (curr->name == "WAIT" || curr->name == "WAITUNTIL") {  // don't wait when initialising
643         SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " re-initializing waypoints ");
644         fp->IncrementWaypoint(false);
645         curr = fp->getCurrentWaypoint();
646         next = fp->getNextWaypoint();
647     }
648
649     if (!_start_time.empty()){
650         _start_sec = processTimeString(_start_time);
651         double day_sec = getDaySeconds();
652
653         if (_start_sec < day_sec){
654             //cout << "flight plan has already started " << _start_time << endl;
655             init = advanceFlightPlan(_start_sec, day_sec);
656
657         } else if (_start_sec > day_sec && _repeat) {
658             //cout << "flight plan has not started, " << _start_time;
659             //cout << "offsetting start time by -24 hrs" << endl;
660             _start_sec -= _day;
661             init = advanceFlightPlan(_start_sec, day_sec);
662         }
663
664         if (init)
665             _start_sec = 0; // set to zero for an immediate start of the Flight Plan
666         else {
667             fp->restart();
668             fp->IncrementWaypoint(false);
669             prev = fp->getPreviousWaypoint();
670             curr = fp->getCurrentWaypoint();
671             next = fp->getNextWaypoint();
672             return false;
673         }
674
675     } else {
676     setLatitude(prev->latitude);
677     setLongitude(prev->longitude);
678     setSpeed(prev->speed);
679     }
680
681     setWPNames();
682     setHeading(getCourse(prev->latitude, prev->longitude, curr->latitude, curr->longitude));
683     _wp_range = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
684     _old_range = _wp_range;
685     _range_rate = 0;
686     _hdg_lock = true;
687     _missed = false;
688     _missed_count = 0;
689     _new_waypoint = true;
690
691     SG_LOG(SG_GENERAL, SG_DEBUG, "AIShip: " << _name << " done initialising waypoints ");
692     if (prev)
693         init = true;
694
695     if (init)
696         return true;
697     else
698         return false;
699
700 } // end of initialization
701
702
703 double FGAIShip::processTimeString(const string& theTime) {
704
705     int Hour;
706     int Minute;
707     int Second;
708
709     // first split theTime string into
710     //  hour, minute, second and convert to int;
711     Hour   = atoi(theTime.substr(0,2).c_str());
712     Minute = atoi(theTime.substr(3,5).c_str());
713     Second = atoi(theTime.substr(6,8).c_str());
714
715     // offset by a day-sec to allow for starting a day earlier
716     double time_seconds = Hour * 3600
717         + Minute * 60
718         + Second;
719
720     return time_seconds;
721 }
722
723 double FGAIShip::getDaySeconds () {
724     // Date and time
725     struct tm *t = globals->get_time_params()->getGmt();
726
727     double day_seconds = t->tm_hour * 3600
728         + t->tm_min * 60
729         + t->tm_sec;
730
731     return day_seconds;
732 }
733
734 bool FGAIShip::advanceFlightPlan (double start_sec, double day_sec) {
735
736     double elapsed_sec = start_sec;
737     double distance_nm = 0;
738
739     //cout << "advancing flight plan start_sec: " << start_sec << " " << day_sec << endl;
740
741     while ( elapsed_sec < day_sec ) {
742
743         if (next->name == "END") {
744
745             if (_repeat ) {
746                 //cout << _name << ": " << "restarting flightplan" << endl;
747                 fp->restart();
748                 curr = fp->getCurrentWaypoint();
749                 next = fp->getNextWaypoint();
750             } else {
751                 //cout << _name << ": " << "ending flightplan" << endl;
752                 setDie(true);
753                 return false;
754             }
755
756         } else if (next->name == "WAIT") {
757             //cout << _name << ": begin WAIT: " << prev->name << " ";
758             //cout << curr->name << " " << next->name << endl;
759
760             elapsed_sec += next->time_sec;
761
762             if ( elapsed_sec >= day_sec)
763                 continue;
764
765             fp->IncrementWaypoint(false);
766             next = fp->getNextWaypoint();
767
768             if (next->name != "WAITUNTIL" && next->name != "WAIT"
769                     && next->name != "END") {
770                 prev = curr;
771                 fp->IncrementWaypoint(false);
772                 curr = fp->getCurrentWaypoint();
773                 next = fp->getNextWaypoint();
774             }
775
776         } else if (next->name == "WAITUNTIL") {
777             double until_sec = processTimeString(next->time);
778
779             if (until_sec > _start_sec && start_sec < 0)
780                 until_sec -= _day;
781
782             if (elapsed_sec < until_sec)
783                 elapsed_sec = until_sec;
784
785             if (elapsed_sec >= day_sec )
786                 break;
787
788             fp->IncrementWaypoint(false);
789             next = fp->getNextWaypoint();
790
791             if (next->name != "WAITUNTIL" && next->name != "WAIT") {
792                 prev = curr;
793                 fp->IncrementWaypoint(false);
794                 curr = fp->getCurrentWaypoint();
795                 next = fp->getNextWaypoint();
796             }
797
798             //cout << _name << ": end WAITUNTIL: ";
799             //cout << prev->name << " " << curr->name << " " << next->name <<  endl;
800
801         } else {
802             distance_nm = getRange(prev->latitude, prev->longitude, curr->latitude, curr->longitude);
803             elapsed_sec += distance_nm * 60 * 60 / prev->speed;
804
805             if (elapsed_sec >= day_sec)
806                 continue;
807
808             fp->IncrementWaypoint(false);
809             prev = fp->getPreviousWaypoint();
810             curr = fp->getCurrentWaypoint();
811             next = fp->getNextWaypoint();
812         }
813
814     }   // end while
815
816     // the required position lies between the previous and current waypoints
817     // so we will calculate the distance back up the track from the current waypoint
818     // then calculate the lat and lon.
819     /*cout << "advancing flight plan done elapsed_sec: " << elapsed_sec
820         << " " << day_sec << endl;*/
821
822     double time_diff = elapsed_sec - day_sec;
823     double lat, lon, recip;
824
825     //cout << " time diff " << time_diff << endl;
826
827     if (next->name == "WAIT" ){
828         setSpeed(0);
829         lat = curr->latitude;
830         lon = curr->longitude;
831         _wait_count= time_diff;
832         _waiting = true;
833     } else if (next->name == "WAITUNTIL") {
834         setSpeed(0);
835         lat = curr->latitude;
836         lon = curr->longitude;
837         _waiting = true;
838     } else {
839         setSpeed(prev->speed);
840         distance_nm = speed * time_diff / (60 * 60);
841         double brg = getCourse(curr->latitude, curr->longitude, prev->latitude, prev->longitude);
842
843         //cout << " brg " << brg << " from " << curr->name << " to " << prev->name << " "
844         //    << " lat "  << curr->latitude << " lon " << curr->longitude
845         //    << " distance m " << distance_nm * SG_NM_TO_METER << endl;
846
847         lat = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
848             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
849         lon = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
850             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
851         recip = geo_direct_wgs_84 (curr->latitude, curr->longitude, brg,
852             distance_nm * SG_NM_TO_METER, &lat, &lon, &recip );
853     }
854
855     //cout << "Pos " << lat << ", " << lon << " recip " << recip << endl;
856
857     setLatitude(lat);
858     setLongitude(lon);
859     return true;
860 }