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
6 // With additions by Mathias Froehlich & Vivian Meazza 2004 -2007
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <simgear/compiler.h>
31 #include <osg/ref_ptr>
34 #include <simgear/math/point3d.hxx>
35 #include <simgear/math/polar3d.hxx>
36 #include <simgear/math/sg_geodesy.hxx>
37 #include <simgear/misc/sg_path.hxx>
38 #include <simgear/scene/model/location.hxx>
39 #include <simgear/scene/model/model.hxx>
40 #include <simgear/scene/util/SGNodeMasks.hxx>
41 #include <simgear/debug/logstream.hxx>
42 #include <simgear/props/props.hxx>
44 #include <Main/globals.hxx>
45 #include <Scenery/scenery.hxx>
46 #include <Scripting/NasalSys.hxx>
50 #include "AIManager.hxx"
53 const double FGAIBase::e = 2.71828183;
54 const double FGAIBase::lbs_to_slugs = 0.031080950172; //conversion factor
57 FGAIBase::FGAIBase(object_type ot) :
59 model_removed( fgGetNode("/ai/models/model-removed", true) ),
62 _refID( _newAIModelID() ),
65 tgt_heading = hdg = tgt_altitude_ft = tgt_speed = 0.0;
66 tgt_roll = roll = tgt_pitch = tgt_yaw = tgt_vs = vs = pitch = 0.0;
67 bearing = elevation = range = rdot = 0.0;
68 x_shift = y_shift = rotation = 0.0;
76 FGAIBase::~FGAIBase() {
77 // Unregister that one at the scenery manager
78 if (globals->get_scenery()) {
79 globals->get_scenery()->get_scene_graph()->removeChild(aip.getSceneGraph());
83 SGPropertyNode* parent = props->getParent();
86 model_removed->setStringValue(props->getPath());
92 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
97 setPath(scFileNode->getStringValue("model", "Models/Geometry/glider.ac"));
99 setHeading(scFileNode->getDoubleValue("heading", 0.0));
100 setSpeed(scFileNode->getDoubleValue("speed", 0.0));
101 setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
102 setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
103 setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
104 setBank(scFileNode->getDoubleValue("roll", 0.0));
106 SGPropertyNode* submodels = scFileNode->getChild("submodels");
109 setServiceable(submodels->getBoolValue("serviceable", false));
110 setSMPath(submodels->getStringValue("path", ""));
115 void FGAIBase::update(double dt) {
117 if (_otype == otStatic)
120 if (_otype == otBallistic)
123 ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
124 ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
127 void FGAIBase::Transform() {
130 aip.setPosition(pos);
133 aip.setOrientation(0.0, pitch, hdg);
135 aip.setOrientation(roll, pitch, hdg);
142 bool FGAIBase::init(bool search_in_AI_path) {
144 if (!model_path.empty()) {
146 if ( (search_in_AI_path)
147 &&(model_path.substr(model_path.size() - 4, 4) == ".xml")) {
148 SGPath ai_path("AI");
149 ai_path.append(model_path);
151 model = load3DModel( globals->get_fg_root(), ai_path.str(), props,
152 globals->get_sim_time_sec() );
153 } catch (const sg_exception &e) {
161 model = load3DModel( globals->get_fg_root(), model_path, props,
162 globals->get_sim_time_sec() );
163 } catch (const sg_exception &e) {
171 aip.init( model.get() );
172 aip.setVisible(true);
174 globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
176 fgSetString("/ai/models/model-added", props->getPath());
179 if (!model_path.empty())
180 SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
184 props->setStringValue("submodels/path", _path.c_str());
190 osg::Node* FGAIBase::load3DModel(const string& fg_root,
192 SGPropertyNode *prop_root,
195 model = sgLoad3DModel(fg_root, path, prop_root, sim_time_sec, 0,
196 new FGNasalModelData(prop_root));
197 model->setNodeMask(model->getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
201 bool FGAIBase::isa( object_type otype ) {
203 if ( otype == _otype )
210 void FGAIBase::bind() {
211 props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
213 props->tie("velocities/true-airspeed-kt", SGRawValuePointer<double>(&speed));
214 props->tie("velocities/vertical-speed-fps",
215 SGRawValueMethods<FGAIBase,double>(*this,
216 &FGAIBase::_getVS_fps,
217 &FGAIBase::_setVS_fps));
219 props->tie("position/altitude-ft",
220 SGRawValueMethods<FGAIBase,double>(*this,
221 &FGAIBase::_getAltitude,
222 &FGAIBase::_setAltitude));
223 props->tie("position/latitude-deg",
224 SGRawValueMethods<FGAIBase,double>(*this,
225 &FGAIBase::_getLatitude,
226 &FGAIBase::_setLatitude));
227 props->tie("position/longitude-deg",
228 SGRawValueMethods<FGAIBase,double>(*this,
229 &FGAIBase::_getLongitude,
230 &FGAIBase::_setLongitude));
232 props->tie("position/global-x",
233 SGRawValueMethods<FGAIBase,double>(*this,
234 &FGAIBase::_getCartPosX,
236 props->tie("position/global-y",
237 SGRawValueMethods<FGAIBase,double>(*this,
238 &FGAIBase::_getCartPosY,
240 props->tie("position/global-z",
241 SGRawValueMethods<FGAIBase,double>(*this,
242 &FGAIBase::_getCartPosZ,
245 props->tie("orientation/pitch-deg", SGRawValuePointer<double>(&pitch));
246 props->tie("orientation/roll-deg", SGRawValuePointer<double>(&roll));
247 props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
249 props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
250 props->tie("radar/bearing-deg", SGRawValuePointer<double>(&bearing));
251 props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
252 props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
253 props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
254 props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
255 props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
256 props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
257 props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
258 props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
260 props->tie("controls/lighting/nav-lights",
261 SGRawValueFunctions<bool>(_isNight));
262 props->setBoolValue("controls/lighting/beacon", true);
263 props->setBoolValue("controls/lighting/strobe", true);
264 props->setBoolValue("controls/glide-path", true);
266 props->setStringValue("controls/flight/lateral-mode", "roll");
267 props->setDoubleValue("controls/flight/target-hdg", hdg);
268 props->setDoubleValue("controls/flight/target-roll", roll);
270 props->setStringValue("controls/flight/longitude-mode", "alt");
271 props->setDoubleValue("controls/flight/target-alt", altitude_ft);
272 props->setDoubleValue("controls/flight/target-pitch", pitch);
274 props->setDoubleValue("controls/flight/target-spd", speed);
278 void FGAIBase::unbind() {
280 props->untie("velocities/true-airspeed-kt");
281 props->untie("velocities/vertical-speed-fps");
283 props->untie("position/altitude-ft");
284 props->untie("position/latitude-deg");
285 props->untie("position/longitude-deg");
286 props->untie("position/global-x");
287 props->untie("position/global-y");
288 props->untie("position/global-z");
290 props->untie("orientation/pitch-deg");
291 props->untie("orientation/roll-deg");
292 props->untie("orientation/true-heading-deg");
294 props->untie("radar/in-range");
295 props->untie("radar/bearing-deg");
296 props->untie("radar/elevation-deg");
297 props->untie("radar/range-nm");
298 props->untie("radar/h-offset");
299 props->untie("radar/v-offset");
300 props->untie("radar/x-shift");
301 props->untie("radar/y-shift");
302 props->untie("radar/rotation");
303 props->untie("radar/ht-diff-ft");
305 props->untie("controls/lighting/nav-lights");
308 double FGAIBase::UpdateRadar(FGAIManager* manager) {
309 bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
310 double radar_range_nm = fgGetDouble("/instrumentation/radar/range");
311 double radar_range_ft2 = radar_range_nm;
312 radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
313 radar_range_ft2 *= radar_range_ft2;
315 double user_latitude = manager->get_user_latitude();
316 double user_longitude = manager->get_user_longitude();
317 double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
318 double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
319 double range_ft2 = lat_range*lat_range + lon_range*lon_range;
322 // Test whether the target is within radar range.
324 in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
326 if ( in_range || force_on ) {
327 props->setBoolValue("radar/in-range", true);
329 // copy values from the AIManager
330 double user_altitude = manager->get_user_altitude();
331 double user_heading = manager->get_user_heading();
332 double user_pitch = manager->get_user_pitch();
333 //double user_yaw = manager->get_user_yaw();
334 //double user_speed = manager->get_user_speed();
336 // calculate range to target in feet and nautical miles
337 double range_ft = sqrt( range_ft2 );
338 range = range_ft / 6076.11549;
340 // calculate bearing to target
341 if (pos.getLatitudeDeg() >= user_latitude) {
342 bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
343 if (pos.getLongitudeDeg() >= user_longitude) {
344 bearing = 90.0 - bearing;
346 bearing = 270.0 + bearing;
349 bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
350 if (pos.getLongitudeDeg() >= user_longitude) {
351 bearing = 180.0 - bearing;
353 bearing = 180.0 + bearing;
357 // This is an alternate way to compute bearing and distance which
358 // agrees with the original scheme within about 0.1 degrees.
360 // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
361 // user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
362 // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
363 // double gc_bearing, gc_range;
364 // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
365 // gc_range *= SG_METER_TO_NM;
366 // gc_bearing *= SGD_RADIANS_TO_DEGREES;
367 // printf("orig b = %.3f %.2f gc b= %.3f, %.2f\n",
368 // bearing, range, gc_bearing, gc_range);
370 // calculate look left/right to target, without yaw correction
371 horiz_offset = bearing - user_heading;
372 if (horiz_offset > 180.0) horiz_offset -= 360.0;
373 if (horiz_offset < -180.0) horiz_offset += 360.0;
375 // calculate elevation to target
376 elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
378 // calculate look up/down to target
379 vert_offset = elevation - user_pitch;
381 /* this calculation needs to be fixed, but it isn't important anyway
382 // calculate range rate
383 double recip_bearing = bearing + 180.0;
384 if (recip_bearing > 360.0) recip_bearing -= 360.0;
385 double my_horiz_offset = recip_bearing - hdg;
386 if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
387 if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
388 rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
389 +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
392 // now correct look left/right for yaw
393 // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
395 // calculate values for radar display
396 y_shift = (range * cos( horiz_offset * SG_DEGREES_TO_RADIANS)) / radar_range_nm;
397 x_shift = (range * sin( horiz_offset * SG_DEGREES_TO_RADIANS)) / radar_range_nm;
398 rotation = hdg - user_heading;
399 if (rotation < 0.0) rotation += 360.0;
400 ht_diff = altitude_ft - user_altitude;
408 * Getters and Setters
411 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
412 // Transform that one to the horizontal local coordinate system.
413 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
415 // and postrotate the orientation of the AIModel wrt the horizontal
417 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
419 // The offset converted to the usual body fixed coordinate system
420 // rotated to the earth fiexed coordinates axis
421 SGVec3d off = hlTrans.backTransform(_off);
423 // Add the position offset of the AIModel to gain the earth centered position
424 SGVec3d cartPos = SGVec3d::fromGeod(pos);
426 return cartPos + off;
429 SGVec3d FGAIBase::getCartPos() const {
430 // Transform that one to the horizontal local coordinate system.
431 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
433 // and postrotate the orientation of the AIModel wrt the horizontal
435 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
437 SGVec3d cartPos = SGVec3d::fromGeod(pos);
442 double FGAIBase::_getCartPosX() const {
443 SGVec3d cartPos = getCartPos();
447 double FGAIBase::_getCartPosY() const {
448 SGVec3d cartPos = getCartPos();
452 double FGAIBase::_getCartPosZ() const {
453 SGVec3d cartPos = getCartPos();
457 void FGAIBase::_setLongitude( double longitude ) {
458 pos.setLongitudeDeg(longitude);
461 void FGAIBase::_setLatitude ( double latitude ) {
462 pos.setLatitudeDeg(latitude);
465 double FGAIBase::_getLongitude() const {
466 return pos.getLongitudeDeg();
469 double FGAIBase::_getLatitude () const {
470 return pos.getLatitudeDeg();
473 double FGAIBase::_getRdot() const {
477 double FGAIBase::_getVS_fps() const {
481 double FGAIBase::_get_speed_east_fps() const {
482 return speed_east_deg_sec * ft_per_deg_lon;
485 double FGAIBase::_get_speed_north_fps() const {
486 return speed_north_deg_sec * ft_per_deg_lat;
489 void FGAIBase::_setVS_fps( double _vs ) {
493 double FGAIBase::_getAltitude() const {
497 bool FGAIBase::_getServiceable() const {
501 SGPropertyNode* FGAIBase::_getProps() const {
505 void FGAIBase::_setAltitude( double _alt ) {
509 bool FGAIBase::_isNight() {
510 return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
513 int FGAIBase::getID() const {
517 double FGAIBase::_getSpeed() const {
521 double FGAIBase::_getRoll() const {
525 double FGAIBase::_getPitch() const {
529 double FGAIBase::_getHeading() const {
533 const char* FGAIBase::_getPath() {
534 return _path.c_str();
537 void FGAIBase::CalculateMach() {
538 // Calculate rho at altitude, using standard atmosphere
539 // For the temperature T and the pressure p,
540 double altitude = altitude_ft;
542 if (altitude < 36152) { // curve fits for the troposphere
543 T = 59 - 0.00356 * altitude;
544 p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
545 } else if ( 36152 < altitude && altitude < 82345 ) { // lower stratosphere
547 p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
548 } else { // upper stratosphere
549 T = -205.05 + (0.00164 * altitude);
550 p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
553 rho = p / (1718 * (T + 459.7));
555 // calculate the speed of sound at altitude
556 // a = sqrt ( g * R * (T + 459.7))
558 // a = speed of sound [ft/s]
559 // g = specific heat ratio, which is usually equal to 1.4
560 // R = specific gas constant, which equals 1716 ft-lb/slug/°R
561 a = sqrt ( 1.4 * 1716 * (T + 459.7));
563 // calculate Mach number
566 // cout << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
569 int FGAIBase::_newAIModelID() {
573 id++; // id = 0 is not allowed.