]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIGroundVehicle.cxx
Improve timing statistics
[flightgear.git] / src / AIModel / AIGroundVehicle.cxx
1 // FGAIGroundVehicle - FGAIShip-derived class creates an AI Ground Vehicle
2 // by adding a ground following utility
3 //
4 // Written by Vivian Meazza, started August 2009.
5 // - vivian.meazza at lineone.net
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/sg_inlines.h>
26
27 #include <Main/viewer.hxx>
28 #include <Scenery/scenery.hxx>
29 #include <Airports/dynamics.hxx>
30
31 #include "AIGroundVehicle.hxx"
32
33 FGAIGroundVehicle::FGAIGroundVehicle() :
34 FGAIShip(otGroundVehicle),
35
36 _pitch(0),
37 _pitch_deg(0),
38 _speed_kt(0),
39 _range_ft(0),
40 _relbrg (0),
41 _parent_speed(0),
42 _parent_x_offset(0),
43 _parent_y_offset(0),
44 _parent_z_offset(0),
45 _dt_count(0),
46 _next_run(0),
47 _break_count(0)
48
49 {
50     invisible = false;
51     _parent = "";
52 }
53
54 FGAIGroundVehicle::~FGAIGroundVehicle() {}
55
56 void FGAIGroundVehicle::readFromScenario(SGPropertyNode* scFileNode) {
57     if (!scFileNode)
58         return;
59
60     FGAIShip::readFromScenario(scFileNode);
61
62     setName(scFileNode->getStringValue("name", "groundvehicle"));
63     setParentName(scFileNode->getStringValue("parent", ""));
64     setNoRoll(scFileNode->getBoolValue("no-roll", true));
65     setContactX1offset(scFileNode->getDoubleValue("contact-x1-offset", 0.0));
66     setContactX2offset(scFileNode->getDoubleValue("contact-x2-offset", 0.0));
67     setXOffset(scFileNode->getDoubleValue("hitch-x-offset", 35.0));
68     setYOffset(scFileNode->getDoubleValue("hitch-y-offset", 0.0));
69     setZOffset(scFileNode->getDoubleValue("hitch-z-offset", 0.0));
70     setPitchoffset(scFileNode->getDoubleValue("pitch-offset", 0.0));
71     setRolloffset(scFileNode->getDoubleValue("roll-offset", 0.0));
72     setYawoffset(scFileNode->getDoubleValue("yaw-offset", 0.0));
73     setPitchCoeff(scFileNode->getDoubleValue("pitch-coefficient", 0.1));
74     setElevCoeff(scFileNode->getDoubleValue("elevation-coefficient", 0.25));
75     setTowAngleGain(scFileNode->getDoubleValue("tow-angle-gain", 1.0));
76     setTowAngleLimit(scFileNode->getDoubleValue("tow-angle-limit-deg", 2.0));
77     setInitialTunnel(scFileNode->getBoolValue("tunnel", false));
78     //we may need these later for towed vehicles
79     //    setSubID(scFileNode->getIntValue("SubID", 0));
80     //    setGroundOffset(scFileNode->getDoubleValue("ground-offset", 0.0));
81     //    setFormate(scFileNode->getBoolValue("formate", true));
82 }
83
84 void FGAIGroundVehicle::bind() {
85     FGAIShip::bind();
86
87     props->tie("controls/constants/elevation-coeff",
88         SGRawValuePointer<double>(&_elevation_coeff));
89     props->tie("controls/constants/pitch-coeff",
90         SGRawValuePointer<double>(&_pitch_coeff));
91     props->tie("position/ht-AGL-ft",
92         SGRawValuePointer<double>(&_ht_agl_ft));
93     props->tie("hitch/rel-bearing-deg",
94          SGRawValuePointer<double>(&_relbrg));
95     props->tie("hitch/tow-angle-deg",
96          SGRawValuePointer<double>(&_tow_angle));
97     props->tie("hitch/range-ft",
98         SGRawValuePointer<double>(&_range_ft));
99     props->tie("hitch/x-offset-ft",
100         SGRawValuePointer<double>(&_x_offset));
101     props->tie("hitch/y-offset-ft",
102         SGRawValuePointer<double>(&_y_offset));
103     props->tie("hitch/z-offset-ft",
104         SGRawValuePointer<double>(&_z_offset));
105     props->tie("hitch/parent-x-offset-ft",
106         SGRawValuePointer<double>(&_parent_x_offset));
107     props->tie("hitch/parent-y-offset-ft",
108         SGRawValuePointer<double>(&_parent_y_offset));
109     props->tie("hitch/parent-z-offset-ft",
110         SGRawValuePointer<double>(&_parent_z_offset));
111     props->tie("controls/constants/tow-angle/gain",
112         SGRawValuePointer<double>(&_tow_angle_gain));
113     props->tie("controls/constants/tow-angle/limit-deg",
114         SGRawValuePointer<double>(&_tow_angle_limit));
115     props->tie("controls/contact-x1-offset-ft",
116         SGRawValuePointer<double>(&_contact_x1_offset));
117     props->tie("controls/contact-x2-offset-ft",
118         SGRawValuePointer<double>(&_contact_x2_offset));
119 }
120
121 void FGAIGroundVehicle::unbind() {
122     FGAIShip::unbind();
123
124     props->untie("controls/constants/elevation-coeff");
125     props->untie("controls/constants/pitch-coeff");
126     props->untie("position/ht-AGL-ft");
127     props->untie("hitch/rel-bearing-deg");
128     props->untie("hitch/tow-angle-deg");
129     props->untie("hitch/range-ft");
130     props->untie("hitch/x-offset-ft");
131     props->untie("hitch/y-offset-ft");
132     props->untie("hitch/z-offset-ft");
133     props->untie("hitch/parent-x-offset-ft");
134     props->untie("hitch/parent-y-offset-ft");
135     props->untie("hitch/parent-y-offset-ft");
136     props->untie("controls/constants/tow-angle/gain");
137     props->untie("controls/constants/tow-angle/limit-deg");
138     props->untie("controls/contact-x1-offset-ft");
139     props->untie("controls/contact-x2-offset-ft");
140 }
141
142 bool FGAIGroundVehicle::init(bool search_in_AI_path) {
143     if (!FGAIShip::init(search_in_AI_path))
144         return false;
145
146     invisible = false;
147     _limit = 200;
148     no_roll = true;
149
150     props->setStringValue("controls/parent-name", _parent.c_str());
151
152     if (setParentNode()){
153         _parent_x_offset = _selected_ac->getDoubleValue("hitch/x-offset-ft");
154         _parent_y_offset = _selected_ac->getDoubleValue("hitch/y-offset-ft");
155         _parent_z_offset = _selected_ac->getDoubleValue("hitch/z-offset-ft");
156         _hitch_x_offset_m = _selected_ac->getDoubleValue("hitch/x-offset-ft")
157             * SG_FEET_TO_METER;
158         _hitch_y_offset_m = _selected_ac->getDoubleValue("hitch/y-offset-ft")
159             * SG_FEET_TO_METER;
160         _hitch_z_offset_m = _selected_ac->getDoubleValue("hitch/z-offset-ft")
161             * SG_FEET_TO_METER;
162         setParent();
163     }
164
165     return true;
166 }
167
168 void FGAIGroundVehicle::update(double dt) {
169     //    SG_LOG(SG_GENERAL, SG_ALERT, "updating GroundVehicle: " << _name );
170     FGAIShip::update(dt);
171
172     RunGroundVehicle(dt);
173 }
174
175 void FGAIGroundVehicle::setNoRoll(bool nr) {
176     no_roll = nr;
177 }
178
179 void FGAIGroundVehicle::setContactX1offset(double x1) {
180     _contact_x1_offset = x1;
181 }
182
183 void FGAIGroundVehicle::setContactX2offset(double x2) {
184     _contact_x2_offset = x2;
185 }
186
187 void FGAIGroundVehicle::setXOffset(double x) {
188     _x_offset = x;
189 }
190
191 void FGAIGroundVehicle::setYOffset(double y) {
192     _y_offset = y;
193 }
194
195 void FGAIGroundVehicle::setZOffset(double z) {
196     _z_offset = z;
197 }
198
199 void FGAIGroundVehicle::setPitchCoeff(double pc) {
200     _pitch_coeff = pc;
201 }
202
203 void FGAIGroundVehicle::setElevCoeff(double ec) {
204     _elevation_coeff = ec;
205 }
206
207 void FGAIGroundVehicle::setTowAngleGain(double g) {
208     _tow_angle_gain = g;
209 }
210
211 void FGAIGroundVehicle::setTowAngleLimit(double l) {
212     _tow_angle_limit = l;
213 }
214
215 void FGAIGroundVehicle::setElevation(double h, double dt, double coeff){
216     double c = dt / (coeff + dt);
217     _elevation_ft = (h * c) + (_elevation_ft * (1 - c));
218 }
219
220 void FGAIGroundVehicle::setPitch(double p, double dt, double coeff){
221     double c = dt / (coeff + dt);
222     _pitch_deg = (p * c) + (_pitch_deg * (1 - c));
223 }
224
225 void FGAIGroundVehicle::setTowAngle(double ta, double dt, double coeff){
226     ta *= _tow_angle_gain;
227     double factor = -0.0045 * speed + 1;
228     double limit = _tow_angle_limit * factor;
229 //      cout << "speed "<< speed << " _factor " << _factor<<" " <<_tow_angle_limit<< endl; 
230      _tow_angle = pow(ta,2) * sign(ta) * factor;
231     SG_CLAMP_RANGE(_tow_angle, -limit, limit);
232 }
233
234 bool FGAIGroundVehicle::getPitch() {
235
236     if (!_tunnel){
237         double vel = props->getDoubleValue("velocities/true-airspeed-kt", 0);
238         double contact_offset_x1_m = _contact_x1_offset * SG_FEET_TO_METER;
239         double contact_offset_x2_m = _contact_x2_offset * SG_FEET_TO_METER;
240         double _z_offset_m = _parent_z_offset * SG_FEET_TO_METER;
241
242         SGVec3d front(-contact_offset_x1_m, 0, 0);
243         SGVec3d rear(-contact_offset_x2_m, 0, 0);
244         SGVec3d Front = getCartPosAt(front);
245         SGVec3d Rear = getCartPosAt(rear);
246
247         SGGeod geodFront = SGGeod::fromCart(Front);
248         SGGeod geodRear = SGGeod::fromCart(Rear);
249
250         double front_elev_m = 0;
251         double rear_elev_m = 0;
252         double elev_front = 0;
253         double elev_rear = 0;
254         //double max_alt = 10000;
255
256         if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodFront, 3000),
257             elev_front, &_material, 0)){
258                 front_elev_m = elev_front + _z_offset_m;
259         } else
260             return false;
261
262         if (globals->get_scenery()->get_elevation_m(SGGeod::fromGeodM(geodRear, 3000),
263             elev_rear, &_material, 0)){
264                 rear_elev_m = elev_rear;
265         } else
266             return false;
267
268         if (vel >= 0){
269             double diff = front_elev_m - rear_elev_m;
270             _pitch = atan2 (diff,
271                 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
272             _elevation = (rear_elev_m + diff/2) * SG_METER_TO_FEET;
273         } else {
274             double diff = rear_elev_m - front_elev_m;
275             _pitch = atan2 (diff,
276                 fabs(contact_offset_x1_m) + fabs(contact_offset_x2_m)) * SG_RADIANS_TO_DEGREES;
277             _elevation = (front_elev_m + diff/2) * SG_METER_TO_FEET;
278             _pitch = -_pitch;
279         }
280
281     } else {
282
283         if (prev->altitude == 0 || curr->altitude == 0) return false;
284
285         static double distance;
286         static double d_alt;
287         static double curr_alt;
288         static double prev_alt;
289
290         if (_new_waypoint){
291             //cout << "new waypoint, calculating pitch " << endl;
292             curr_alt = curr->altitude;
293             prev_alt = prev->altitude;
294             //cout << "prev_alt" <<prev_alt << endl;
295             d_alt = (curr_alt - prev_alt) * SG_METER_TO_FEET;
296             //_elevation = prev->altitude;
297             distance = SGGeodesy::distanceM(SGGeod::fromDeg(prev->longitude, prev->latitude),
298             SGGeod::fromDeg(curr->longitude, curr->latitude));
299             _pitch = atan2(d_alt, distance * SG_METER_TO_FEET) * SG_RADIANS_TO_DEGREES;
300             //cout << "new waypoint, calculating pitch " <<  _pitch << 
301             //    " " << _pitch_offset << " " << _elevation <<endl;
302         }
303
304         double distance_to_go = SGGeodesy::distanceM(SGGeod::fromDeg(pos.getLongitudeDeg(), pos.getLatitudeDeg()),
305             SGGeod::fromDeg(curr->longitude, curr->latitude));
306
307         /*cout << "tunnel " << _tunnel
308              << " distance prev & curr " << prev->name << " " << curr->name << " " << distance * SG_METER_TO_FEET
309              << " distance to go " << distance_to_go * SG_METER_TO_FEET
310              << " d_alt ft " << d_alt
311              << endl;*/
312
313         if (distance_to_go > distance)
314             _elevation = prev_alt;
315         else
316             _elevation = curr_alt - (tan(_pitch * SG_DEGREES_TO_RADIANS) * distance_to_go * SG_METER_TO_FEET);
317
318     }
319
320     return true;
321 }
322
323 void FGAIGroundVehicle::setParent(){
324
325     double lat = _selected_ac->getDoubleValue("position/latitude-deg");
326     double lon = _selected_ac->getDoubleValue("position/longitude-deg");
327     double elevation = _selected_ac->getDoubleValue("position/altitude-ft");
328
329     _selectedpos.setLatitudeDeg(lat);
330     _selectedpos.setLongitudeDeg(lon);
331     _selectedpos.setElevationFt(elevation);
332
333     _parent_speed = _selected_ac->getDoubleValue("velocities/true-airspeed-kt");
334
335     SGVec3d rear_hitch(-_hitch_x_offset_m, _hitch_y_offset_m, 0);
336     SGVec3d RearHitch = getCartHitchPosAt(rear_hitch);
337
338     SGGeod rearpos = SGGeod::fromCart(RearHitch);
339
340     double user_lat = rearpos.getLatitudeDeg();
341     double user_lon = rearpos.getLongitudeDeg();
342
343     double range, bearing;
344
345     calcRangeBearing(pos.getLatitudeDeg(), pos.getLongitudeDeg(),
346         user_lat, user_lon, range, bearing);
347     _range_ft = range * 6076.11549;
348     _relbrg = calcRelBearingDeg(bearing, hdg);
349 }
350
351 void FGAIGroundVehicle::calcRangeBearing(double lat, double lon, double lat2, double lon2,
352                             double &range, double &bearing) const
353 {
354     // calculate the bearing and range of the second pos from the first
355     double az2, distance;
356     geo_inverse_wgs_84(lat, lon, lat2, lon2, &bearing, &az2, &distance);
357     range = distance * SG_METER_TO_NM;
358 }
359
360
361 SGVec3d FGAIGroundVehicle::getCartHitchPosAt(const SGVec3d& _off) const {
362     double hdg = _selected_ac->getDoubleValue("orientation/true-heading-deg");
363     double pitch = _selected_ac->getDoubleValue("orientation/pitch-deg");
364     double roll = _selected_ac->getDoubleValue("orientation/roll-deg");
365
366     // Transform that one to the horizontal local coordinate system.
367     SGQuatd hlTrans = SGQuatd::fromLonLat(_selectedpos);
368
369     // and postrotate the orientation of the AIModel wrt the horizontal
370     // local frame
371     hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
372
373     // The offset converted to the usual body fixed coordinate system
374     // rotated to the earth fiexed coordinates axis
375     SGVec3d off = hlTrans.backTransform(_off);
376
377     // Add the position offset of the AIModel to gain the earth centered position
378     SGVec3d cartPos = SGVec3d::fromGeod(_selectedpos);
379
380     return cartPos + off;
381 }
382
383 void FGAIGroundVehicle::AdvanceFP(){
384
385     double count = 0;
386     string parent_next_name =_selected_ac->getStringValue("waypoint/name-next");
387
388     while(fp->getNextWaypoint() != 0 && fp->getNextWaypoint()->name != "END" && count < 5){
389         SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
390             <<" advancing waypoint to: " << parent_next_name);
391
392         if (fp->getNextWaypoint()->name == parent_next_name){
393             SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
394                 << " not setting waypoint already at: " << fp->getNextWaypoint()->name);
395             return;
396         }
397
398         prev = curr;
399         fp->IncrementWaypoint(false);
400         curr = fp->getCurrentWaypoint();
401         next = fp->getNextWaypoint();
402
403         if (fp->getNextWaypoint()->name == parent_next_name){
404             SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
405             << " waypoint set to: " << fp->getNextWaypoint()->name);
406             return;
407         }
408
409         count++;
410
411     }// end while loop
412
413     while(fp->getPreviousWaypoint() != 0 && fp->getPreviousWaypoint()->name != "END"
414         && count > -10){
415             SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
416             << " retreating waypoint to: " << parent_next_name
417             << " at: " << fp->getNextWaypoint()->name);
418
419         if (fp->getNextWaypoint()->name == parent_next_name){
420             SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
421                 << " not setting waypoint already at:" << fp->getNextWaypoint()->name );
422             return;
423         }
424
425         prev = curr;
426         fp->DecrementWaypoint(false);
427         curr = fp->getCurrentWaypoint();
428         next = fp->getNextWaypoint();
429
430         if (fp->getNextWaypoint()->name == parent_next_name){
431             SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
432             << " waypoint set to: " << fp->getNextWaypoint()->name);
433             return;
434         }
435
436         count--;
437
438     }// end while loop
439 }
440
441 void FGAIGroundVehicle::setTowSpeed(){
442
443     //double diff = _range_ft - _x_offset;
444     double  x = 0;
445
446     if (_range_ft > _x_offset * 3) x = 50;
447
448     if (_relbrg < -90 || _relbrg > 90){
449         setSpeed(_parent_speed - 5 - x);
450         //cout << _name << " case 1r _relbrg spd - 5 " << _relbrg << " " << diff << endl;
451     }else if (_range_ft > _x_offset + 0.25 && _relbrg >= -90 && _relbrg <= 90){
452         setSpeed(_parent_speed + 1 + x);
453         //cout << _name << " case 2r _relbrg spd + 1 " << _relbrg << " "
454         //    << diff << " range " << _range_ft << endl;
455     } else if (_range_ft < _x_offset - 0.25 && _relbrg >= -90 && _relbrg <= 90){
456         setSpeed(_parent_speed - 1 - x);
457         //cout << _name << " case 3r _relbrg spd - 2 " << _relbrg << " "
458         //    << diff << " " << _range_ft << endl;
459     } else {
460         setSpeed(_parent_speed);
461         //cout << _name << " else r _relbrg " << _relbrg << " " << diff << endl;
462     }
463
464 }
465
466 void FGAIGroundVehicle::RunGroundVehicle(double dt){
467
468     _dt_count += dt;
469
470     ///////////////////////////////////////////////////////////////////////////
471     // Check execution time (currently once every 0.05 sec or 20 fps)
472     // Add a bit of randomization to prevent the execution of all flight plans
473     // in synchrony, which can add significant periodic framerate flutter.
474     // Randomization removed to get better appearance
475     ///////////////////////////////////////////////////////////////////////////
476
477     //cout << "_start_sec " << _start_sec << " time_sec " << time_sec << endl;
478     if (_dt_count < _next_run)
479         return;
480
481     _next_run = 0.05 /*+ (0.015 * sg_random())*/;
482
483     if (getPitch()){
484         setElevation(_elevation, _dt_count, _elevation_coeff);
485         ClimbTo(_elevation_ft);
486         setPitch(_pitch, _dt_count, _pitch_coeff);
487         PitchTo(_pitch_deg);
488     }
489
490     if(_parent == ""){
491         AccelTo(prev->speed);
492         _dt_count = 0;
493         return;
494     }
495
496     setParent();
497
498     string parent_next_name = _selected_ac->getStringValue("waypoint/name-next");
499     bool parent_waiting = _selected_ac->getBoolValue("waypoint/waiting");
500     //bool parent_restart = _selected_ac->getBoolValue("controls/restart"); 
501
502     if (parent_next_name == "END" && fp->getNextWaypoint()->name != "END" ){
503         SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
504             << " setting END: getting new waypoints ");
505         AdvanceFP();
506         setWPNames();
507         setTunnel(_initial_tunnel);
508         if(_restart) _missed_count = 200;
509         /*} else if (parent_next_name == "WAIT" && fp->getNextWaypoint()->name != "WAIT" ){*/
510     } else if (parent_waiting && !_waiting){
511         SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
512             << " setting WAIT/WAITUNTIL: getting new waypoints ");
513         AdvanceFP();
514         setWPNames();
515         _waiting = true;
516     } else if (parent_next_name != "WAIT" && fp->getNextWaypoint()->name == "WAIT"){
517         SG_LOG(SG_GENERAL, SG_DEBUG, "AIGroundVeh1cle: " << _name
518             << " wait done: getting new waypoints ");
519         _waiting = false;
520         _wait_count = 0;
521         fp->IncrementWaypoint(false);
522         next = fp->getNextWaypoint();
523
524         if (next->name == "WAITUNTIL" || next->name == "WAIT"
525             || next->name == "END"){
526         } else {
527             prev = curr;
528             fp->IncrementWaypoint(false);
529             curr = fp->getCurrentWaypoint();
530             next = fp->getNextWaypoint();
531         }
532
533         setWPNames();
534     } else if (_range_ft > (_x_offset +_parent_x_offset)* 4
535         ){
536         SG_LOG(SG_GENERAL, SG_ALERT, "AIGroundVeh1cle: " << _name
537             << " rescue: reforming train " << _range_ft 
538             );
539
540         setTowAngle(0, dt, 1);
541         setSpeed(_parent_speed + (10 * sign(_parent_speed)));
542
543     } else if (_parent_speed > 1){
544
545         setTowSpeed();
546         setTowAngle(_relbrg, dt, 1);
547
548     } else if (_parent_speed < -1){
549
550         setTowSpeed();
551
552         if (_relbrg < 0)
553             setTowAngle(-(180 - (360 + _relbrg)), dt, 1);
554         else
555             setTowAngle(-(180 - _relbrg), dt, 1);
556
557     } else
558         setSpeed(_parent_speed);
559
560 //    FGAIShip::update(_dt_count);
561     _dt_count = 0;
562
563 }
564
565 // end AIGroundvehicle