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