]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
Melchior FRANZ:
[flightgear.git] / src / AIModel / AIAircraft.cxx
1 // FGAIAircraft - FGAIBase-derived class creates an AI airplane
2 //
3 // Written by David Culp, started October 2003.
4 //
5 // Copyright (C) 2003  David P. Culp - davidculp2@comcast.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., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/math/point3d.hxx>
26 #include <Main/fg_props.hxx>
27 #include <Main/globals.hxx>
28 #include <Scenery/scenery.hxx>
29 #include <string>
30 #include <math.h>
31
32 SG_USING_STD(string);
33
34 #include "AIAircraft.hxx"
35
36 //
37 // accel, decel, climb_rate, descent_rate, takeoff_speed, climb_speed,
38 // cruise_speed, descent_speed, land_speed
39 //
40 const FGAIAircraft::PERF_STRUCT FGAIAircraft::settings[] = {
41     // light aircraft
42     {2.0, 2.0,  450.0, 1000.0,  70.0,  80.0, 100.0,  80.0,  60.0},
43     // ww2_fighter
44     {4.0, 2.0, 3000.0, 1500.0, 110.0, 180.0, 250.0, 200.0, 100.0},
45     // jet_transport
46     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0},
47     // jet_fighter
48     {7.0, 3.0, 4000.0, 2000.0, 150.0, 350.0, 500.0, 350.0, 150.0},
49     // tanker
50     {5.0, 2.0, 3000.0, 1500.0, 140.0, 300.0, 430.0, 300.0, 130.0}
51 };
52
53
54 FGAIAircraft::FGAIAircraft(FGAIManager* mgr, FGAISchedule *ref) {
55   trafficRef = ref;
56    manager = mgr;   
57    _type_str = "aircraft";
58    _otype = otAircraft;
59    fp = 0;
60    dt_count = 0;
61    use_perf_vs = true;
62    isTanker = false;
63
64    // set heading and altitude locks
65    hdg_lock = false;
66    alt_lock = false;
67 }
68
69
70 FGAIAircraft::~FGAIAircraft() {
71 }
72
73
74 bool FGAIAircraft::init() {
75    refuel_node = fgGetNode("systems/refuel/contact", true);
76    return FGAIBase::init();
77 }
78
79 void FGAIAircraft::bind() {
80     FGAIBase::bind();
81
82     props->tie("controls/gear/gear-down",
83                SGRawValueMethods<FGAIAircraft,bool>(*this,
84                                               &FGAIAircraft::_getGearDown));
85 #if 0
86     props->getNode("controls/lighting/landing-lights", true)
87            ->alias("controls/gear/gear-down");
88 #endif
89 }
90
91 void FGAIAircraft::unbind() {
92     FGAIBase::unbind();
93
94     props->untie("controls/gear/gear-down");
95 #if 0
96     props->getNode("controls/lighting/landing-lights")->unalias();
97 #endif
98 }
99
100
101 void FGAIAircraft::update(double dt) {
102
103    FGAIBase::update(dt);
104    Run(dt);
105    Transform();
106 }
107
108 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
109    
110    performance = ps;
111
112
113
114 void FGAIAircraft::Run(double dt) {
115
116    FGAIAircraft::dt = dt;
117
118    if (fp) 
119      {
120        ProcessFlightPlan(dt);
121        time_t now = time(NULL) + fgGetLong("/sim/time/warp");
122        if (now < fp->getStartTime())
123         return;
124        //ProcessFlightPlan(dt);
125      }
126         
127    double turn_radius_ft;
128    double turn_circum_ft;
129    double speed_north_deg_sec;
130    double speed_east_deg_sec;
131    double dist_covered_ft;
132    double alpha;
133
134    // adjust speed
135    double speed_diff = tgt_speed - speed;
136    if (fabs(speed_diff) > 0.2) {
137      if (speed_diff > 0.0) speed += performance->accel * dt;
138      if (speed_diff < 0.0) {
139         if (!no_roll) {
140            speed -= performance->decel * dt * 3;
141         } else {
142            speed -= performance->decel * dt;
143         }
144      }
145    } 
146    
147    // convert speed to degrees per second
148    speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
149                           * speed * 1.686 / ft_per_deg_lat;
150    speed_east_deg_sec  = sin( hdg / SG_RADIANS_TO_DEGREES )
151                           * speed * 1.686 / ft_per_deg_lon;
152
153    // set new position
154    pos.setlat( pos.lat() + speed_north_deg_sec * dt);
155    pos.setlon( pos.lon() + speed_east_deg_sec * dt); 
156
157    // adjust heading based on current bank angle
158    if (roll != 0.0) {
159      turn_radius_ft = 0.088362 * speed * speed
160                        / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
161      turn_circum_ft = SGD_2PI * turn_radius_ft;
162      dist_covered_ft = speed * 1.686 * dt; 
163      alpha = dist_covered_ft / turn_circum_ft * 360.0;
164      hdg += alpha * sign( roll );
165      if ( hdg > 360.0 ) hdg -= 360.0;
166      if ( hdg < 0.0) hdg += 360.0;
167    }
168
169    // adjust target bank angle if heading lock engaged
170    if (hdg_lock) {
171      double bank_sense = 0.0;
172      double diff = fabs(hdg - tgt_heading);
173      if (diff > 180) diff = fabs(diff - 360);
174      double sum = hdg + diff;
175      if (sum > 360.0) sum -= 360.0;
176      if (fabs(sum - tgt_heading) < 1.0) { 
177        bank_sense = 1.0;   // right turn
178      } else {
179        bank_sense = -1.0;  // left turn
180      } 
181      if (diff < 30) {
182          tgt_roll = diff * bank_sense; 
183      } else {
184          tgt_roll = 30.0 * bank_sense;
185      }
186    }
187
188    // adjust bank angle, use 9 degrees per second
189    double bank_diff = tgt_roll - roll;
190    if (fabs(bank_diff) > 0.2) {
191      if (bank_diff > 0.0) roll += 9.0 * dt;
192      if (bank_diff < 0.0) roll -= 9.0 * dt;
193    }
194
195    // adjust altitude (meters) based on current vertical speed (fpm)
196    altitude += vs / 60.0 * dt;
197    pos.setelev(altitude * SG_FEET_TO_METER);  
198    double altitude_ft = altitude;
199
200    // find target vertical speed if altitude lock engaged
201    if (alt_lock && use_perf_vs) {
202      if (altitude_ft < tgt_altitude) {
203        tgt_vs = tgt_altitude - altitude_ft;
204        if (tgt_vs > performance->climb_rate)
205          tgt_vs = performance->climb_rate;
206      } else {
207        tgt_vs = tgt_altitude - altitude_ft;
208        if (tgt_vs  < (-performance->descent_rate))
209          tgt_vs = -performance->descent_rate;
210      }
211    }
212
213    if (alt_lock && !use_perf_vs) {
214      double max_vs = 4*(tgt_altitude - altitude);
215      double min_vs = 100;
216      if (tgt_altitude < altitude) min_vs = -100.0;
217      if ((fabs(tgt_altitude - altitude) < 1500.0) && 
218          (fabs(max_vs) < fabs(tgt_vs))) tgt_vs = max_vs;
219      if (fabs(tgt_vs) < fabs(min_vs)) tgt_vs = min_vs;
220    }   
221
222    // adjust vertical speed
223    double vs_diff = tgt_vs - vs;
224    if (fabs(vs_diff) > 10.0) {
225      if (vs_diff > 0.0) {
226        vs += 900.0 * dt;
227        if (vs > tgt_vs) vs = tgt_vs;
228      } else {
229        vs -= 400.0 * dt;
230        if (vs < tgt_vs) vs = tgt_vs;
231      }
232    }   
233    
234    // match pitch angle to vertical speed
235    if (vs > 0){
236      pitch = vs * 0.005;
237    } else {
238      pitch = vs * 0.002;
239    }
240
241    //###########################//
242    // do calculations for radar //
243    //###########################//
244    double range_ft2 = UpdateRadar(manager);
245
246    //************************************//
247    // Tanker code                        //
248    //************************************//
249
250    if ( isTanker) {
251      if ( (range_ft2 < 250.0 * 250.0) &&
252           (y_shift > 0.0)    &&
253           (elevation > 0.0) ) {
254        refuel_node->setBoolValue(true);
255      } else {
256        refuel_node->setBoolValue(false);
257      } 
258    }
259 }
260
261
262 void FGAIAircraft::AccelTo(double speed) {
263    tgt_speed = speed;
264 }
265
266
267 void FGAIAircraft::PitchTo(double angle) {
268    tgt_pitch = angle;
269    alt_lock = false;
270 }
271
272
273 void FGAIAircraft::RollTo(double angle) {
274    tgt_roll = angle;
275    hdg_lock = false; 
276 }
277
278
279 void FGAIAircraft::YawTo(double angle) {
280    tgt_yaw = angle;
281 }
282
283
284 void FGAIAircraft::ClimbTo(double altitude) {
285    tgt_altitude = altitude;
286    alt_lock = true;
287 }
288
289
290 void FGAIAircraft::TurnTo(double heading) {
291    tgt_heading = heading;
292    hdg_lock = true;
293 }
294
295
296 double FGAIAircraft::sign(double x) {
297   if ( x < 0.0 ) { return -1.0; }
298   else { return 1.0; }
299 }
300
301 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
302   fp = f;
303 }
304
305 void FGAIAircraft::ProcessFlightPlan( double dt ) {
306  
307
308   FGAIFlightPlan::waypoint* prev = 0; // the one behind you
309   FGAIFlightPlan::waypoint* curr = 0; // the one ahead
310   FGAIFlightPlan::waypoint* next = 0; // the next plus 1
311   prev = fp->getPreviousWaypoint();
312   curr = fp->getCurrentWaypoint();
313   next = fp->getNextWaypoint();
314   dt_count += dt;
315
316   if (!prev) {  //beginning of flightplan, do this initialization once
317     fp->IncrementWaypoint();
318     prev = fp->getPreviousWaypoint(); //first waypoint
319     curr = fp->getCurrentWaypoint();  //second waypoint
320     next = fp->getNextWaypoint();     //third waypoint (might not exist!) 
321     setLatitude(prev->latitude);
322     setLongitude(prev->longitude);
323     setSpeed(prev->speed);
324     setAltitude(prev->altitude);
325     setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
326     if (next) fp->setLeadDistance(speed, hdg, curr, next);
327     
328     if (curr->crossat > -1000.0) { //use a calculated descent/climb rate
329         use_perf_vs = false;
330         tgt_vs = (curr->crossat - prev->altitude)/
331                  (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/
332                                       6076.0/prev->speed*60.0);
333         tgt_altitude = curr->crossat;
334     } else {
335         use_perf_vs = true;
336         tgt_altitude = prev->altitude;
337     }
338     alt_lock = hdg_lock = true;
339     no_roll = prev->on_ground;
340     //cout << "First waypoint:  " << prev->name << endl;
341     //cout << "  Target speed:    " << tgt_speed << endl;
342     //cout << "  Target altitude: " << tgt_altitude << endl;
343     //cout << "  Target heading:  " << tgt_heading << endl << endl;       
344     return;  
345   } // end of initialization
346
347   // let's only process the flight plan every 100 ms.
348   if (dt_count < 0.1) {
349     return;
350   } else {
351     dt_count = 0;
352
353     // check to see if we've reached the lead point for our next turn
354     double dist_to_go = fp->getDistanceToGo(pos.lat(), pos.lon(), curr); 
355     double lead_dist = fp->getLeadDistance();
356     if (lead_dist < (2*speed)) lead_dist = 2*speed;  //don't skip over the waypoint
357     //cout << "dist_to_go: " << dist_to_go << ",  lead_dist: " << lead_dist << endl;
358
359     if ( dist_to_go < lead_dist ) {
360       if (curr->finished) {  //end of the flight plan, so terminate
361           if (trafficRef)
362             {
363               delete fp;
364               //time_t now = time(NULL) + fgGetLong("/sim/time/warp");
365               trafficRef->next();
366
367               FGAIModelEntity entity;
368               entity.m_class = "jet_transport";
369               //entity.path = modelPath.c_str();
370               entity.flightplan = "none";
371               entity.latitude = _getLatitude();
372               entity.longitude = _getLongitude();
373               entity.altitude = trafficRef->getCruiseAlt() * 100; // convert from FL to feet
374               entity.speed = 450;
375               //entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
376               entity.fp = new FGAIFlightPlan(&entity, 
377                                              999,  // A hack
378                                              trafficRef->getDepartureTime(), 
379                                              trafficRef->getDepartureAirport(), 
380                                              trafficRef->getArrivalAirport());
381               SetFlightPlan(entity.fp);
382             }
383           else 
384             {
385               setDie(true);
386               return;
387             }
388       }
389         // we've reached the lead-point for the waypoint ahead 
390       if (next) tgt_heading = fp->getBearing(curr, next);  
391       fp->IncrementWaypoint();
392       prev = fp->getPreviousWaypoint();
393       curr = fp->getCurrentWaypoint();
394       next = fp->getNextWaypoint();
395       if (next) fp->setLeadDistance(speed, tgt_heading, curr, next);
396       if (curr->crossat > -1000.0) {
397         use_perf_vs = false;
398         tgt_vs = (curr->crossat - altitude)/
399                  (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
400         tgt_altitude = curr->crossat;
401       } else {
402         use_perf_vs = true;
403         tgt_altitude = prev->altitude;
404       }
405       tgt_speed = prev->speed;
406       hdg_lock = alt_lock = true;
407       no_roll = prev->on_ground;
408       //cout << "Crossing waypoint: " << prev->name << endl;
409       //cout << "  Target speed:    " << tgt_speed << endl;
410       //cout << "  Target altitude: " << tgt_altitude << endl;
411       //cout << "  Target heading:  " << tgt_heading << endl << endl;       
412     } else {
413         double calc_bearing = fp->getBearing(pos.lat(), pos.lon(), curr);
414         double hdg_error = calc_bearing - tgt_heading;
415         if (fabs(hdg_error) > 1.0) {
416           TurnTo( calc_bearing ); 
417         }
418     }
419      
420   }
421
422 }
423
424
425 bool FGAIAircraft::_getGearDown() const {
426    return ((props->getFloatValue("position/altitude-agl-ft") < 900.0)
427             && (props->getFloatValue("velocities/airspeed-kt")
428                  < performance->land_speed*1.25));
429 }