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