]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
ebf34e94db7911eb7f25d055f28566a0a442c4dc
[flightgear.git] / src / AIModel / AIBase.cxx
1 // FGAIBase - abstract base class for AI objects
2 // Written by David Culp, started Nov 2003, based on
3 // David Luff's FGAIEntity class.
4 // - davidculp2@comcast.net
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
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24
25 #include <simgear/compiler.h>
26
27 #include STL_STRING
28
29 #include <osg/ref_ptr>
30 #include <osg/Node>
31
32 #include <simgear/math/point3d.hxx>
33 #include <simgear/math/polar3d.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/misc/sg_path.hxx>
36 #include <simgear/scene/model/location.hxx>
37 #include <simgear/scene/model/model.hxx>
38 #include <simgear/scene/util/SGNodeMasks.hxx>
39 #include <simgear/debug/logstream.hxx>
40 #include <simgear/props/props.hxx>
41
42 #include <Main/globals.hxx>
43 #include <Scenery/scenery.hxx>
44
45
46 #include "AIBase.hxx"
47 #include "AIManager.hxx"
48
49
50 const double FGAIBase::e = 2.71828183;
51 const double FGAIBase::lbs_to_slugs = 0.031080950172;   //conversion factor
52
53
54 FGAIBase::FGAIBase(object_type ot) :
55     props( NULL ),
56     model_removed( fgGetNode("/ai/models/model-removed", true) ),
57     manager( NULL ),
58     fp( NULL ),
59     _refID( _newAIModelID() ),
60     _otype(ot)
61 {
62     tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
63     tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
64     bearing = elevation = range = rdot = 0.0;
65     x_shift = y_shift = rotation = 0.0;
66     in_range = false;
67     invisible = true;
68     no_roll = true;
69     life = 900;
70     delete_me = false;
71 }
72
73 FGAIBase::~FGAIBase() {
74     // Unregister that one at the scenery manager
75     if (globals->get_scenery()) {
76         globals->get_scenery()->unregister_placement_transform(aip.getTransform());
77         globals->get_scenery()->get_scene_graph()->removeChild(aip.getSceneGraph());
78     }
79     if (props) {
80         SGPropertyNode* parent = props->getParent();
81         if (parent) {
82             model_removed->setStringValue(props->getPath());
83             parent->removeChild(props->getName(), props->getIndex(), false);
84         }
85     }
86     delete fp;
87     fp = 0;
88 }
89
90
91 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
92 {
93     if (!scFileNode)
94         return;
95
96     setPath(scFileNode->getStringValue("model", "Models/Geometry/glider.ac"));
97
98     setHeading(scFileNode->getDoubleValue("heading", 0.0));
99     setSpeed(scFileNode->getDoubleValue("speed", 0.0));
100     setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
101     setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
102     setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
103     setBank(scFileNode->getDoubleValue("roll", 0.0));
104 }
105
106 void FGAIBase::update(double dt) {
107     if (_otype == otStatic)
108         return;
109     if (_otype == otBallistic)
110         CalculateMach();
111
112     ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
113     ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
114 }
115
116 void FGAIBase::Transform() {
117     if (!invisible) {
118       aip.setPosition(pos);
119       if (no_roll) {
120          aip.setOrientation(0.0, pitch, hdg);
121       } else {
122          aip.setOrientation(roll, pitch, hdg);
123       }
124       aip.update();
125     }
126 }
127
128 bool FGAIBase::init(bool search_in_AI_path) {
129     if (!model_path.empty()) {
130      if ( (search_in_AI_path)
131           &&(model_path.substr(model_path.size() - 4, 4) == ".xml")) {
132        SGPath ai_path("AI");
133        ai_path.append(model_path);
134        try {
135          model = load3DModel( globals->get_fg_root(), ai_path.str(), props,
136                         globals->get_sim_time_sec() );
137        } catch (const sg_exception &e) {
138          model = NULL;
139        }
140      } else model = NULL;
141      if (!model) {
142        try {
143          model = load3DModel( globals->get_fg_root(), model_path, props,
144                         globals->get_sim_time_sec() );
145        } catch (const sg_exception &e) {
146          model = NULL;
147        }
148       }
149     }
150    if (model.get()) {
151      aip.init( model.get() );
152      aip.setVisible(true);
153      invisible = false;
154      globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
155      // Register that one at the scenery manager
156      globals->get_scenery()->register_placement_transform(aip.getTransform());
157      fgSetString("/ai/models/model-added", props->getPath());
158    } else {
159      if (!model_path.empty()) {
160        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
161      }
162    }
163
164    setDie(false);
165    return true;
166 }
167
168
169 osg::Node*
170 FGAIBase::load3DModel(const string& fg_root,
171                       const string &path,
172                       SGPropertyNode *prop_root,
173                       double sim_time_sec)
174 {
175   model = sgLoad3DModel(fg_root, path, prop_root, sim_time_sec);
176   model->setNodeMask(model->getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
177   return model.get();
178 }
179
180 bool FGAIBase::isa( object_type otype ) {
181  if ( otype == _otype )
182    return true;
183  else
184    return false;
185 }
186
187
188 void FGAIBase::bind() {
189    props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
190                                          &FGAIBase::getID));
191    props->tie("velocities/true-airspeed-kt",  SGRawValuePointer<double>(&speed));
192    props->tie("velocities/vertical-speed-fps",
193                SGRawValueMethods<FGAIBase,double>(*this,
194                                          &FGAIBase::_getVS_fps,
195                                          &FGAIBase::_setVS_fps));
196
197    props->tie("position/altitude-ft",
198                SGRawValueMethods<FGAIBase,double>(*this,
199                                          &FGAIBase::_getAltitude,
200                                          &FGAIBase::_setAltitude));
201    props->tie("position/latitude-deg",
202                SGRawValueMethods<FGAIBase,double>(*this,
203                                          &FGAIBase::_getLatitude,
204                                          &FGAIBase::_setLatitude));
205    props->tie("position/longitude-deg",
206                SGRawValueMethods<FGAIBase,double>(*this,
207                                          &FGAIBase::_getLongitude,
208                                          &FGAIBase::_setLongitude));
209
210    props->tie("position/global-x",
211                SGRawValueMethods<FGAIBase,double>(*this,
212                                          &FGAIBase::_getCartPosX,
213                                          0));
214    props->tie("position/global-y",
215                SGRawValueMethods<FGAIBase,double>(*this,
216                                          &FGAIBase::_getCartPosY,
217                                          0));
218    props->tie("position/global-z",
219                SGRawValueMethods<FGAIBase,double>(*this,
220                                          &FGAIBase::_getCartPosZ,
221                                          0));
222
223    props->tie("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
224    props->tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
225    props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
226
227    props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
228    props->tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
229    props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
230    props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
231    props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
232    props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
233    props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
234    props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
235    props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
236    props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
237
238    props->tie("controls/lighting/nav-lights",
239                SGRawValueFunctions<bool>(_isNight));
240    props->setBoolValue("controls/lighting/beacon", true);
241    props->setBoolValue("controls/lighting/strobe", true);
242    props->setBoolValue("controls/glide-path", true);
243
244    props->setStringValue("controls/flight/lateral-mode", "roll");
245    props->setDoubleValue("controls/flight/target-hdg", hdg);
246    props->setDoubleValue("controls/flight/target-roll", roll);
247
248    props->setStringValue("controls/flight/longitude-mode", "alt");
249    props->setDoubleValue("controls/flight/target-alt", altitude_ft);
250    props->setDoubleValue("controls/flight/target-pitch", pitch);
251
252    props->setDoubleValue("controls/flight/target-spd", speed);
253
254 }
255
256 void FGAIBase::unbind() {
257     props->untie("id");
258     props->untie("velocities/true-airspeed-kt");
259     props->untie("velocities/vertical-speed-fps");
260
261     props->untie("position/altitude-ft");
262     props->untie("position/latitude-deg");
263     props->untie("position/longitude-deg");
264     props->untie("position/global-x");
265     props->untie("position/global-y");
266     props->untie("position/global-z");
267
268     props->untie("orientation/pitch-deg");
269     props->untie("orientation/roll-deg");
270     props->untie("orientation/true-heading-deg");
271
272     props->untie("radar/in-range");
273     props->untie("radar/bearing-deg");
274     props->untie("radar/elevation-deg");
275     props->untie("radar/range-nm");
276     props->untie("radar/h-offset");
277     props->untie("radar/v-offset");
278     props->untie("radar/x-shift");
279     props->untie("radar/y-shift");
280     props->untie("radar/rotation");
281     props->untie("radar/ht-diff-ft");
282
283     props->untie("controls/lighting/nav-lights");
284 }
285
286 double FGAIBase::UpdateRadar(FGAIManager* manager)
287 {
288    double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
289    bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
290    radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
291    radar_range_ft2 *= radar_range_ft2;
292
293    double user_latitude  = manager->get_user_latitude();
294    double user_longitude = manager->get_user_longitude();
295    double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
296    double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
297    double range_ft2 = lat_range*lat_range + lon_range*lon_range;
298
299    //
300    // Test whether the target is within radar range.
301    //
302    in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
303    if ( in_range || force_on )
304    {
305      props->setBoolValue("radar/in-range", true);
306
307      // copy values from the AIManager
308      double user_altitude  = manager->get_user_altitude();
309      double user_heading   = manager->get_user_heading();
310      double user_pitch     = manager->get_user_pitch();
311      //double user_yaw       = manager->get_user_yaw();
312      //double user_speed     = manager->get_user_speed();
313
314      // calculate range to target in feet and nautical miles
315      double range_ft = sqrt( range_ft2 );
316      range = range_ft / 6076.11549;
317
318      // calculate bearing to target
319      if (pos.getLatitudeDeg() >= user_latitude) {
320         bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
321         if (pos.getLongitudeDeg() >= user_longitude) {
322            bearing = 90.0 - bearing;
323         } else {
324            bearing = 270.0 + bearing;
325         }
326      } else {
327         bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
328         if (pos.getLongitudeDeg() >= user_longitude) {
329            bearing = 180.0 - bearing;
330         } else {
331            bearing = 180.0 + bearing;
332         }
333      }
334
335      // This is an alternate way to compute bearing and distance which
336      // agrees with the original scheme within about 0.1 degrees.
337      //
338      // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
339      //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
340      // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
341      // double gc_bearing, gc_range;
342      // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
343      // gc_range *= SG_METER_TO_NM;
344      // gc_bearing *= SGD_RADIANS_TO_DEGREES;
345      // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
346      //        bearing, range, gc_bearing, gc_range);
347
348      // calculate look left/right to target, without yaw correction
349      horiz_offset = bearing - user_heading;
350      if (horiz_offset > 180.0) horiz_offset -= 360.0;
351      if (horiz_offset < -180.0) horiz_offset += 360.0;
352
353      // calculate elevation to target
354      elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
355
356      // calculate look up/down to target
357      vert_offset = elevation - user_pitch;
358
359      /* this calculation needs to be fixed, but it isn't important anyway
360      // calculate range rate
361      double recip_bearing = bearing + 180.0;
362      if (recip_bearing > 360.0) recip_bearing -= 360.0;
363      double my_horiz_offset = recip_bearing - hdg;
364      if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
365      if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
366      rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
367              +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
368 */
369
370      // now correct look left/right for yaw
371      // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
372
373      // calculate values for radar display
374      y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
375      x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
376      rotation = hdg - user_heading;
377      if (rotation < 0.0) rotation += 360.0;
378      ht_diff = altitude_ft - user_altitude;
379
380    }
381
382    return range_ft2;
383 }
384
385 SGVec3d
386 FGAIBase::getCartPosAt(const SGVec3d& _off) const
387 {
388   // Transform that one to the horizontal local coordinate system.
389   
390   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
391   // and postrotate the orientation of the AIModel wrt the horizontal
392   // local frame
393   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
394
395   // The offset converted to the usual body fixed coordinate system
396   // rotated to the earth fiexed coordinates axis
397   SGVec3d off = hlTrans.backTransform(_off);
398
399   // Add the position offset of the AIModel to gain the earth centered position
400   SGVec3d cartPos = SGVec3d::fromGeod(pos);
401
402   return cartPos + off;
403 }
404
405 SGVec3d
406 FGAIBase::getCartPos() const
407 {
408   // Transform that one to the horizontal local coordinate system.
409   
410   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
411   // and postrotate the orientation of the AIModel wrt the horizontal
412   // local frame
413   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
414
415   SGVec3d cartPos = SGVec3d::fromGeod(pos);
416
417   return cartPos;
418 }
419
420 double
421 FGAIBase::_getCartPosX() const
422 {
423     SGVec3d cartPos = getCartPos();
424     return cartPos.x();
425 }
426
427 double
428 FGAIBase::_getCartPosY() const
429 {
430     SGVec3d cartPos = getCartPos();
431     return cartPos.y();
432 }
433
434 double
435 FGAIBase::_getCartPosZ() const
436 {
437     SGVec3d cartPos = getCartPos();
438     return cartPos.z();
439 }
440
441 /*
442  * getters and Setters
443  */
444 void FGAIBase::_setLongitude( double longitude ) {
445     pos.setLongitudeDeg(longitude);
446 }
447 void FGAIBase::_setLatitude ( double latitude )  {
448     pos.setLatitudeDeg(latitude);
449 }
450
451 double FGAIBase::_getLongitude() const {
452     return pos.getLongitudeDeg();
453 }
454 double FGAIBase::_getLatitude () const {
455     return pos.getLatitudeDeg();
456 }
457 double FGAIBase::_getRdot() const {
458     return rdot;
459 }
460 double FGAIBase::_getVS_fps() const {
461     return vs*60.0;
462 }
463 void FGAIBase::_setVS_fps( double _vs ) {
464     vs = _vs/60.0;
465 }
466
467 double FGAIBase::_getAltitude() const {
468     return altitude_ft;
469 }
470 void FGAIBase::_setAltitude( double _alt ) {
471     setAltitude( _alt );
472 }
473
474 bool FGAIBase::_isNight() {
475     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
476 }
477
478 int FGAIBase::getID() const {
479     return  _refID;
480 }
481
482 void FGAIBase::CalculateMach() {
483     // Calculate rho at altitude, using standard atmosphere
484     // For the temperature T and the pressure p,
485
486     double altitude = altitude_ft;
487
488     if (altitude < 36152) {             // curve fits for the troposphere
489       T = 59 - 0.00356 * altitude;
490       p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
491
492     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
493       T = -70;
494       p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
495
496     } else {                                    //  upper stratosphere
497       T = -205.05 + (0.00164 * altitude);
498       p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
499     }
500
501     rho = p / (1718 * (T + 459.7));
502
503     // calculate the speed of sound at altitude
504     // a = sqrt ( g * R * (T + 459.7))
505     // where:
506     // a = speed of sound [ft/s]
507     // g = specific heat ratio, which is usually equal to 1.4
508     // R = specific gas constant, which equals 1716 ft-lb/slug/°R
509
510     a = sqrt ( 1.4 * 1716 * (T + 459.7));
511
512     // calculate Mach number
513
514     Mach = speed/a;
515
516     // cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach;
517 }
518
519 int FGAIBase::_newAIModelID() {
520     static int id = 0;
521    if (!++id)
522       id++;     // id = 0 is not allowed.
523    return id;
524 }
525