]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIAircraft.cxx
bbed46642da14e0baa2e52c60d0df2523139dc66
[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 };
50
51
52 FGAIAircraft *FGAIAircraft::_self = NULL;
53
54 FGAIAircraft::FGAIAircraft(FGAIManager* mgr) {
55    manager = mgr;   
56    _self = this;
57    _type_str = "aircraft";
58    _otype = otAircraft;
59    fp = 0;
60    fp_count = 0;
61    use_perf_vs = true;
62
63    // set heading and altitude locks
64    hdg_lock = false;
65    alt_lock = false;
66 }
67
68
69 FGAIAircraft::~FGAIAircraft() {
70     if (fp) delete fp;
71     _self = NULL;
72 }
73
74
75 bool FGAIAircraft::init() {
76    return FGAIBase::init();
77 }
78
79 void FGAIAircraft::bind() {
80     FGAIBase::bind();
81
82     props->tie("controls/gear/gear-down",
83                SGRawValueFunctions<bool>(FGAIAircraft::_getGearDown));
84
85 /*
86     props->getNode("controls/lighting/landing-lights", true)
87            ->alias("controls/gear/gear-down");
88 */
89 }
90
91 void FGAIAircraft::unbind() {
92     FGAIBase::unbind();
93
94     props->untie("controls/gear/gear-down");
95 //    props->getNode("controls/lighting/landing-lights")->unalias();
96 }
97
98
99 void FGAIAircraft::update(double dt) {
100
101    Run(dt);
102    Transform();
103    FGAIBase::update(dt);
104 }
105
106 void FGAIAircraft::SetPerformance(const PERF_STRUCT *ps) {
107    
108    performance = ps;
109
110
111
112 void FGAIAircraft::Run(double dt) {
113
114    FGAIAircraft::dt = dt;
115
116    if (fp) ProcessFlightPlan();
117         
118    double turn_radius_ft;
119    double turn_circum_ft;
120    double speed_north_deg_sec;
121    double speed_east_deg_sec;
122    double ft_per_deg_lon;
123    double ft_per_deg_lat;
124    double dist_covered_ft;
125    double alpha;
126
127    // get size of a degree at this latitude
128    ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.lat()/SG_RADIANS_TO_DEGREES);
129    ft_per_deg_lon = 365228.16 * cos(pos.lat() / SG_RADIANS_TO_DEGREES);
130
131    // adjust speed
132    double speed_diff = tgt_speed - speed;
133    if (fabs(speed_diff) > 0.2) {
134      if (speed_diff > 0.0) speed += performance->accel * dt;
135      if (speed_diff < 0.0) speed -= performance->decel * dt;
136    } 
137    
138    // convert speed to degrees per second
139    speed_north_deg_sec = cos( hdg / SG_RADIANS_TO_DEGREES )
140                           * speed * 1.686 / ft_per_deg_lat;
141    speed_east_deg_sec  = sin( hdg / SG_RADIANS_TO_DEGREES )
142                           * speed * 1.686 / ft_per_deg_lon;
143
144    // set new position
145    pos.setlat( pos.lat() + speed_north_deg_sec * dt);
146    pos.setlon( pos.lon() + speed_east_deg_sec * dt); 
147
148    // adjust heading based on current bank angle
149    if (roll != 0.0) {
150      turn_radius_ft = 0.088362 * speed * speed
151                        / tan( fabs(roll) / SG_RADIANS_TO_DEGREES );
152      turn_circum_ft = SGD_2PI * turn_radius_ft;
153      dist_covered_ft = speed * 1.686 * dt; 
154      alpha = dist_covered_ft / turn_circum_ft * 360.0;
155      hdg += alpha * sign( roll );
156      if ( hdg > 360.0 ) hdg -= 360.0;
157      if ( hdg < 0.0) hdg += 360.0;
158    }
159
160    // adjust target bank angle if heading lock engaged
161    if (hdg_lock) {
162      double bank_sense = 0.0;
163      double diff = fabs(hdg - tgt_heading);
164      if (diff > 180) diff = fabs(diff - 360);
165      double sum = hdg + diff;
166      if (sum > 360.0) sum -= 360.0;
167      if (fabs(sum - tgt_heading) < 1.0) { 
168        bank_sense = 1.0;   // right turn
169      } else {
170        bank_sense = -1.0;  // left turn
171      } 
172      if (diff < 30) {
173          tgt_roll = diff * bank_sense; 
174      } else {
175          tgt_roll = 30.0 * bank_sense;
176      }
177    }
178
179    // adjust bank angle, use 9 degrees per second
180    double bank_diff = tgt_roll - roll;
181    if (fabs(bank_diff) > 0.2) {
182      if (bank_diff > 0.0) roll += 9.0 * dt;
183      if (bank_diff < 0.0) roll -= 9.0 * dt;
184    }
185
186    // adjust altitude (meters) based on current vertical speed (fpm)
187    altitude += vs / 60.0 * dt;
188    pos.setelev(altitude * SG_FEET_TO_METER);  
189    double altitude_ft = altitude;
190
191    // find target vertical speed if altitude lock engaged
192    if (alt_lock && use_perf_vs) {
193      if (altitude_ft < tgt_altitude) {
194        tgt_vs = tgt_altitude - altitude_ft;
195        if (tgt_vs > performance->climb_rate)
196          tgt_vs = performance->climb_rate;
197      } else {
198        tgt_vs = tgt_altitude - altitude_ft;
199        if (tgt_vs  < (-performance->descent_rate))
200          tgt_vs = -performance->descent_rate;
201      }
202    }
203
204    if (alt_lock && !use_perf_vs) {
205      double max_vs = 2*(tgt_altitude - altitude);
206      if ((fabs(tgt_altitude - altitude) < 1500.0) && 
207          (fabs(max_vs) < fabs(tgt_vs))) tgt_vs = max_vs;
208    }   
209
210    // adjust vertical speed
211    double vs_diff = tgt_vs - vs;
212    if (fabs(vs_diff) > 10.0) {
213      if (vs_diff > 0.0) {
214        vs += 400.0 * dt;
215        if (vs > tgt_vs) vs = tgt_vs;
216      } else {
217        vs -= 300.0 * dt;
218        if (vs < tgt_vs) vs = tgt_vs;
219      }
220    }   
221    
222    // match pitch angle to vertical speed
223    pitch = vs * 0.005;
224
225    //###########################//
226    // do calculations for radar //
227    //###########################//
228
229    // copy values from the AIManager
230    double user_latitude  = manager->get_user_latitude();
231    double user_longitude = manager->get_user_longitude();
232    double user_altitude  = manager->get_user_altitude();
233    double user_heading   = manager->get_user_heading();
234    double user_pitch     = manager->get_user_pitch();
235    double user_yaw       = manager->get_user_yaw();
236    double user_speed     = manager->get_user_speed();
237
238    // calculate range to target in feet and nautical miles
239    double lat_range = fabs(pos.lat() - user_latitude) * ft_per_deg_lat;
240    double lon_range = fabs(pos.lon() - user_longitude) * ft_per_deg_lon;
241    double range_ft = sqrt( lat_range*lat_range + lon_range*lon_range );
242    range = range_ft / 6076.11549;
243
244    // calculate bearing to target
245    if (pos.lat() >= user_latitude) {   
246       bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
247         if (pos.lon() >= user_longitude) {
248            bearing = 90.0 - bearing;
249         } else {
250            bearing = 270.0 + bearing;
251         }
252    } else {
253       bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
254         if (pos.lon() >= user_longitude) {
255            bearing = 180.0 - bearing;
256         } else {
257            bearing = 180.0 + bearing;
258         }
259    }
260
261    // calculate look left/right to target, without yaw correction
262    horiz_offset = bearing - user_heading;
263    if (horiz_offset > 180.0) horiz_offset -= 360.0;
264    if (horiz_offset < -180.0) horiz_offset += 360.0;
265
266    // calculate elevation to target
267    elevation = atan2( altitude_ft - user_altitude, range_ft )
268                       * SG_RADIANS_TO_DEGREES;
269    
270    // calculate look up/down to target
271    vert_offset = elevation + user_pitch;
272
273 /* this calculation needs to be fixed, but it isn't important anyway
274    // calculate range rate
275    double recip_bearing = bearing + 180.0;
276    if (recip_bearing > 360.0) recip_bearing -= 360.0;
277    double my_horiz_offset = recip_bearing - hdg;
278    if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
279    if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
280    rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
281                + (-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
282 */
283    
284    // now correct look left/right for yaw
285    horiz_offset += user_yaw;
286
287    // calculate values for radar display
288    y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
289    x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
290    rotation = hdg - user_heading;
291    if (rotation < 0.0) rotation += 360.0; 
292
293 }
294
295
296 void FGAIAircraft::AccelTo(double speed) {
297    tgt_speed = speed;
298 }
299
300
301 void FGAIAircraft::PitchTo(double angle) {
302    tgt_pitch = angle;
303    alt_lock = false;
304 }
305
306
307 void FGAIAircraft::RollTo(double angle) {
308    tgt_roll = angle;
309    hdg_lock = false; 
310 }
311
312
313 void FGAIAircraft::YawTo(double angle) {
314    tgt_yaw = angle;
315 }
316
317
318 void FGAIAircraft::ClimbTo(double altitude) {
319    tgt_altitude = altitude;
320    alt_lock = true;
321 }
322
323
324 void FGAIAircraft::TurnTo(double heading) {
325    tgt_heading = heading;
326    hdg_lock = true;
327 }
328
329
330 double FGAIAircraft::sign(double x) {
331   if ( x < 0.0 ) { return -1.0; }
332   else { return 1.0; }
333 }
334
335 void FGAIAircraft::SetFlightPlan(FGAIFlightPlan *f) {
336   fp = f;
337 }
338
339 void FGAIAircraft::ProcessFlightPlan( void ) {
340   FGAIFlightPlan::waypoint* prev = 0; // the one behind you
341   FGAIFlightPlan::waypoint* curr = 0; // the one ahead
342   FGAIFlightPlan::waypoint* next = 0; // the next plus 1
343   prev = fp->getPreviousWaypoint();
344   curr = fp->getCurrentWaypoint();
345   next = fp->getNextWaypoint();
346   ++fp_count;
347
348   if (!prev) {  //beginning of flightplan, do this initialization once
349     fp->IncrementWaypoint();
350     prev = fp->getPreviousWaypoint(); //first waypoint
351     curr = fp->getCurrentWaypoint();  //second waypoint
352     next = fp->getNextWaypoint();     //third waypoint (might not exist!) 
353     setLatitude(prev->latitude);
354     setLongitude(prev->longitude);
355     setSpeed(prev->speed);
356     setAltitude(prev->altitude);
357     setHeading(fp->getBearing(prev->latitude, prev->longitude, curr));
358     if (next) fp->setLeadDistance(speed, hdg, curr, next);
359     
360     if (curr->crossat > -1000.0) { //start descent/climb now
361         use_perf_vs = false;
362         tgt_vs = (curr->crossat - prev->altitude)/
363                  (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/
364                                       6076.0/prev->speed*60.0);
365         tgt_altitude = curr->crossat;
366     } else {
367         use_perf_vs = true;
368         tgt_altitude = prev->altitude;
369     }
370     alt_lock = hdg_lock = true;
371     //cout << "First waypoint:  " << prev->name << endl;
372     //cout << "  Target speed:    " << tgt_speed << endl;
373     //cout << "  Target altitude: " << tgt_altitude << endl;
374     //cout << "  Target heading:  " << tgt_heading << endl << endl;       
375     return;  
376   } // end of initialization
377
378   // let's only process the flight plan every 11 time steps
379   if (fp_count < 11) { 
380     return;
381   } else {
382     fp_count = 0;
383
384     // check to see if we've reached the lead point for our next turn
385     double dist_to_go = fp->getDistanceToGo(pos.lat(), pos.lon(), curr); 
386     double lead_dist = fp->getLeadDistance();
387     if (lead_dist < (2*speed)) lead_dist = 2*speed;  //don't skip over the waypoint
388     //cout << "dist_to_go: " << dist_to_go << ",  lead_dist: " << lead_dist << endl;
389
390     if ( dist_to_go < lead_dist ) {
391       if (curr->name == "END") {  //end of the flight plan, so terminate
392         setDie(true);
393         return;
394       }
395       // we've reached the lead-point for the waypoint ahead 
396       if (next) tgt_heading = fp->getBearing(curr, next);  
397       fp->IncrementWaypoint();
398       prev = fp->getPreviousWaypoint();
399       curr = fp->getCurrentWaypoint();
400       next = fp->getNextWaypoint();
401       if (next) fp->setLeadDistance(speed, tgt_heading, curr, next);
402       if (curr->crossat > -1000.0) {
403         use_perf_vs = false;
404         tgt_vs = (curr->crossat - altitude)/
405                  (fp->getDistanceToGo(pos.lat(), pos.lon(), curr)/6076.0/speed*60.0);
406         tgt_altitude = curr->crossat;
407       } else {
408         use_perf_vs = true;
409         tgt_altitude = prev->altitude;
410       }
411       tgt_speed = prev->speed;
412       hdg_lock = alt_lock = true;
413       //cout << "Crossing waypoint: " << prev->name << endl;
414       //cout << "  Target speed:    " << tgt_speed << endl;
415       //cout << "  Target altitude: " << tgt_altitude << endl;
416       //cout << "  Target heading:  " << tgt_heading << endl << endl;       
417     } else {
418         double calc_bearing = fp->getBearing(pos.lat(), pos.lon(), curr);
419         double hdg_error = calc_bearing - tgt_heading;
420         if (fabs(hdg_error) > 1.0) {
421           TurnTo( calc_bearing ); 
422         }
423     }
424      
425   }
426
427 }
428
429