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