]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AIBase.cxx
27cc00eb96ed9f87a893241e1c227f7bdfa26e89
[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
129 bool FGAIBase::init() {
130
131    if (!model_path.empty()) {
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 &) {
138        model = NULL;
139      }
140      if (!model) {
141        try {
142          model = load3DModel( globals->get_fg_root(), model_path, props,
143                         globals->get_sim_time_sec() );
144        } catch (const sg_exception &) {
145          model = NULL;
146        }
147      }
148    }
149    if (model.get()) {
150      aip.init( model.get() );
151      aip.setVisible(true);
152      invisible = false;
153      globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
154      // Register that one at the scenery manager
155      globals->get_scenery()->register_placement_transform(aip.getTransform());
156      fgSetString("/ai/models/model-added", props->getPath());
157    } else {
158      if (!model_path.empty()) {
159        SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
160      }
161    }
162
163    setDie(false);
164
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("orientation/pitch-deg",   SGRawValuePointer<double>(&pitch));
211    props->tie("orientation/roll-deg",    SGRawValuePointer<double>(&roll));
212    props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
213
214    props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
215    props->tie("radar/bearing-deg",   SGRawValuePointer<double>(&bearing));
216    props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
217    props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
218    props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
219    props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
220    props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
221    props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
222    props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
223    props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
224
225    props->tie("controls/lighting/nav-lights",
226                SGRawValueFunctions<bool>(_isNight));
227    props->setBoolValue("controls/lighting/beacon", true);
228    props->setBoolValue("controls/lighting/strobe", true);
229    props->setBoolValue("controls/glide-path", true);
230
231    props->setStringValue("controls/flight/lateral-mode", "roll");
232    props->setDoubleValue("controls/flight/target-hdg", hdg);
233    props->setDoubleValue("controls/flight/target-roll", roll);
234
235    props->setStringValue("controls/flight/longitude-mode", "alt");
236    props->setDoubleValue("controls/flight/target-alt", altitude_ft);
237    props->setDoubleValue("controls/flight/target-pitch", pitch);
238
239    props->setDoubleValue("controls/flight/target-spd", speed);
240
241 }
242
243 void FGAIBase::unbind() {
244     props->untie("id");
245     props->untie("velocities/true-airspeed-kt");
246     props->untie("velocities/vertical-speed-fps");
247
248     props->untie("position/altitude-ft");
249     props->untie("position/latitude-deg");
250     props->untie("position/longitude-deg");
251
252     props->untie("orientation/pitch-deg");
253     props->untie("orientation/roll-deg");
254     props->untie("orientation/true-heading-deg");
255
256     props->untie("radar/in-range");
257     props->untie("radar/bearing-deg");
258     props->untie("radar/elevation-deg");
259     props->untie("radar/range-nm");
260     props->untie("radar/h-offset");
261     props->untie("radar/v-offset");
262     props->untie("radar/x-shift");
263     props->untie("radar/y-shift");
264     props->untie("radar/rotation");
265     props->untie("radar/ht-diff-ft");
266
267     props->untie("controls/lighting/nav-lights");
268 }
269
270 double FGAIBase::UpdateRadar(FGAIManager* manager)
271 {
272    double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
273    bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
274    radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
275    radar_range_ft2 *= radar_range_ft2;
276
277    double user_latitude  = manager->get_user_latitude();
278    double user_longitude = manager->get_user_longitude();
279    double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
280    double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
281    double range_ft2 = lat_range*lat_range + lon_range*lon_range;
282
283    //
284    // Test whether the target is within radar range.
285    //
286    in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
287    if ( in_range || force_on )
288    {
289      props->setBoolValue("radar/in-range", true);
290
291      // copy values from the AIManager
292      double user_altitude  = manager->get_user_altitude();
293      double user_heading   = manager->get_user_heading();
294      double user_pitch     = manager->get_user_pitch();
295      //double user_yaw       = manager->get_user_yaw();
296      //double user_speed     = manager->get_user_speed();
297
298      // calculate range to target in feet and nautical miles
299      double range_ft = sqrt( range_ft2 );
300      range = range_ft / 6076.11549;
301
302      // calculate bearing to target
303      if (pos.getLatitudeDeg() >= user_latitude) {
304         bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
305         if (pos.getLongitudeDeg() >= user_longitude) {
306            bearing = 90.0 - bearing;
307         } else {
308            bearing = 270.0 + bearing;
309         }
310      } else {
311         bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
312         if (pos.getLongitudeDeg() >= user_longitude) {
313            bearing = 180.0 - bearing;
314         } else {
315            bearing = 180.0 + bearing;
316         }
317      }
318
319      // This is an alternate way to compute bearing and distance which
320      // agrees with the original scheme within about 0.1 degrees.
321      //
322      // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
323      //                user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
324      // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
325      // double gc_bearing, gc_range;
326      // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
327      // gc_range *= SG_METER_TO_NM;
328      // gc_bearing *= SGD_RADIANS_TO_DEGREES;
329      // printf("orig b = %.3f %.2f  gc b= %.3f, %.2f\n",
330      //        bearing, range, gc_bearing, gc_range);
331
332      // calculate look left/right to target, without yaw correction
333      horiz_offset = bearing - user_heading;
334      if (horiz_offset > 180.0) horiz_offset -= 360.0;
335      if (horiz_offset < -180.0) horiz_offset += 360.0;
336
337      // calculate elevation to target
338      elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
339
340      // calculate look up/down to target
341      vert_offset = elevation - user_pitch;
342
343      /* this calculation needs to be fixed, but it isn't important anyway
344      // calculate range rate
345      double recip_bearing = bearing + 180.0;
346      if (recip_bearing > 360.0) recip_bearing -= 360.0;
347      double my_horiz_offset = recip_bearing - hdg;
348      if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
349      if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
350      rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
351              +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
352 */
353
354      // now correct look left/right for yaw
355      // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
356
357      // calculate values for radar display
358      y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
359      x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
360      rotation = hdg - user_heading;
361      if (rotation < 0.0) rotation += 360.0;
362      ht_diff = altitude_ft - user_altitude;
363
364    }
365
366    return range_ft2;
367 }
368
369 SGVec3d
370 FGAIBase::getCartPosAt(const SGVec3d& _off) const
371 {
372   // Transform that one to the horizontal local coordinate system.
373   
374   SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
375   // and postrotate the orientation of the AIModel wrt the horizontal
376   // local frame
377   hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
378
379   // The offset converted to the usual body fixed coordinate system
380   // rotated to the earth fiexed coordinates axis
381   SGVec3d off = hlTrans.backTransform(_off);
382
383   // Add the position offset of the AIModel to gain the earth centered position
384   SGVec3d cartPos = SGVec3d::fromGeod(pos);
385
386   return cartPos + off;
387 }
388
389 /*
390  * getters and Setters
391  */
392 void FGAIBase::_setLongitude( double longitude ) {
393     pos.setLongitudeDeg(longitude);
394 }
395 void FGAIBase::_setLatitude ( double latitude )  {
396     pos.setLatitudeDeg(latitude);
397 }
398
399 double FGAIBase::_getLongitude() const {
400     return pos.getLongitudeDeg();
401 }
402 double FGAIBase::_getLatitude () const {
403     return pos.getLatitudeDeg();
404 }
405 double FGAIBase::_getRdot() const {
406     return rdot;
407 }
408 double FGAIBase::_getVS_fps() const {
409     return vs*60.0;
410 }
411 void FGAIBase::_setVS_fps( double _vs ) {
412     vs = _vs/60.0;
413 }
414
415 double FGAIBase::_getAltitude() const {
416     return altitude_ft;
417 }
418 void FGAIBase::_setAltitude( double _alt ) {
419     setAltitude( _alt );
420 }
421
422 bool FGAIBase::_isNight() {
423     return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
424 }
425
426 int FGAIBase::getID() const {
427     return  _refID;
428 }
429
430 void FGAIBase::CalculateMach() {
431     // Calculate rho at altitude, using standard atmosphere
432     // For the temperature T and the pressure p,
433
434     double altitude = altitude_ft;
435
436     if (altitude < 36152) {             // curve fits for the troposphere
437       T = 59 - 0.00356 * altitude;
438       p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
439
440     } else if ( 36152 < altitude && altitude < 82345 ) {    // lower stratosphere
441       T = -70;
442       p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
443
444     } else {                                    //  upper stratosphere
445       T = -205.05 + (0.00164 * altitude);
446       p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
447     }
448
449     rho = p / (1718 * (T + 459.7));
450
451     // calculate the speed of sound at altitude
452     // a = sqrt ( g * R * (T + 459.7))
453     // where:
454     // a = speed of sound [ft/s]
455     // g = specific heat ratio, which is usually equal to 1.4
456     // R = specific gas constant, which equals 1716 ft-lb/slug/°R
457
458     a = sqrt ( 1.4 * 1716 * (T + 459.7));
459
460     // calculate Mach number
461
462     Mach = speed/a;
463
464     // cout  << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach;
465 }
466
467 int FGAIBase::_newAIModelID() {
468     static int id = 0;
469    if (!++id)
470       id++;     // id = 0 is not allowed.
471    return id;
472 }
473