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