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()->unregister_placement_transform(aip.getTransform());
80 globals->get_scenery()->get_scene_graph()->removeChild(aip.getSceneGraph());
84 SGPropertyNode* parent = props->getParent();
87 model_removed->setStringValue(props->getPath());
88 parent->removeChild(props->getName(), props->getIndex(), false);
91 // so that radar does not have to do extra checks
92 props->setBoolValue("radar/in-range", false);
93 props->removeChild("id", 0);
100 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
105 setPath(scFileNode->getStringValue("model", "Models/Geometry/glider.ac"));
107 setHeading(scFileNode->getDoubleValue("heading", 0.0));
108 setSpeed(scFileNode->getDoubleValue("speed", 0.0));
109 setAltitude(scFileNode->getDoubleValue("altitude", 0.0));
110 setLongitude(scFileNode->getDoubleValue("longitude", 0.0));
111 setLatitude(scFileNode->getDoubleValue("latitude", 0.0));
112 setBank(scFileNode->getDoubleValue("roll", 0.0));
114 SGPropertyNode* submodels = scFileNode->getChild("submodels");
117 setServiceable(submodels->getBoolValue("serviceable", false));
118 setSMPath(submodels->getStringValue("path", ""));
123 void FGAIBase::update(double dt) {
125 if (_otype == otStatic)
128 if (_otype == otBallistic)
131 ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
132 ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
135 void FGAIBase::Transform() {
138 aip.setPosition(pos);
141 aip.setOrientation(0.0, pitch, hdg);
143 aip.setOrientation(roll, pitch, hdg);
150 bool FGAIBase::init(bool search_in_AI_path) {
152 if (!model_path.empty()) {
154 if ( (search_in_AI_path)
155 &&(model_path.substr(model_path.size() - 4, 4) == ".xml")) {
156 SGPath ai_path("AI");
157 ai_path.append(model_path);
159 model = load3DModel( globals->get_fg_root(), ai_path.str(), props,
160 globals->get_sim_time_sec() );
161 } catch (const sg_exception &e) {
169 model = load3DModel( globals->get_fg_root(), model_path, props,
170 globals->get_sim_time_sec() );
171 } catch (const sg_exception &e) {
179 aip.init( model.get() );
180 aip.setVisible(true);
182 globals->get_scenery()->get_scene_graph()->addChild(aip.getSceneGraph());
184 // Register that one at the scenery manager
185 globals->get_scenery()->register_placement_transform(aip.getTransform());
186 fgSetString("/ai/models/model-added", props->getPath());
189 if (!model_path.empty())
190 SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
194 props->setStringValue("submodels/path", _path.c_str());
200 osg::Node* FGAIBase::load3DModel(const string& fg_root,
202 SGPropertyNode *prop_root,
205 model = sgLoad3DModel(fg_root, path, prop_root, sim_time_sec, 0,
206 new FGNasalModelData(prop_root));
207 model->setNodeMask(model->getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
211 bool FGAIBase::isa( object_type otype ) {
213 if ( otype == _otype )
220 void FGAIBase::bind() {
221 props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
223 props->tie("velocities/true-airspeed-kt", SGRawValuePointer<double>(&speed));
224 props->tie("velocities/vertical-speed-fps",
225 SGRawValueMethods<FGAIBase,double>(*this,
226 &FGAIBase::_getVS_fps,
227 &FGAIBase::_setVS_fps));
229 props->tie("position/altitude-ft",
230 SGRawValueMethods<FGAIBase,double>(*this,
231 &FGAIBase::_getAltitude,
232 &FGAIBase::_setAltitude));
233 props->tie("position/latitude-deg",
234 SGRawValueMethods<FGAIBase,double>(*this,
235 &FGAIBase::_getLatitude,
236 &FGAIBase::_setLatitude));
237 props->tie("position/longitude-deg",
238 SGRawValueMethods<FGAIBase,double>(*this,
239 &FGAIBase::_getLongitude,
240 &FGAIBase::_setLongitude));
242 props->tie("position/global-x",
243 SGRawValueMethods<FGAIBase,double>(*this,
244 &FGAIBase::_getCartPosX,
246 props->tie("position/global-y",
247 SGRawValueMethods<FGAIBase,double>(*this,
248 &FGAIBase::_getCartPosY,
250 props->tie("position/global-z",
251 SGRawValueMethods<FGAIBase,double>(*this,
252 &FGAIBase::_getCartPosZ,
255 props->tie("orientation/pitch-deg", SGRawValuePointer<double>(&pitch));
256 props->tie("orientation/roll-deg", SGRawValuePointer<double>(&roll));
257 props->tie("orientation/true-heading-deg", SGRawValuePointer<double>(&hdg));
259 props->tie("radar/in-range", SGRawValuePointer<bool>(&in_range));
260 props->tie("radar/bearing-deg", SGRawValuePointer<double>(&bearing));
261 props->tie("radar/elevation-deg", SGRawValuePointer<double>(&elevation));
262 props->tie("radar/range-nm", SGRawValuePointer<double>(&range));
263 props->tie("radar/h-offset", SGRawValuePointer<double>(&horiz_offset));
264 props->tie("radar/v-offset", SGRawValuePointer<double>(&vert_offset));
265 props->tie("radar/x-shift", SGRawValuePointer<double>(&x_shift));
266 props->tie("radar/y-shift", SGRawValuePointer<double>(&y_shift));
267 props->tie("radar/rotation", SGRawValuePointer<double>(&rotation));
268 props->tie("radar/ht-diff-ft", SGRawValuePointer<double>(&ht_diff));
270 props->tie("controls/lighting/nav-lights",
271 SGRawValueFunctions<bool>(_isNight));
272 props->setBoolValue("controls/lighting/beacon", true);
273 props->setBoolValue("controls/lighting/strobe", true);
274 props->setBoolValue("controls/glide-path", true);
276 props->setStringValue("controls/flight/lateral-mode", "roll");
277 props->setDoubleValue("controls/flight/target-hdg", hdg);
278 props->setDoubleValue("controls/flight/target-roll", roll);
280 props->setStringValue("controls/flight/longitude-mode", "alt");
281 props->setDoubleValue("controls/flight/target-alt", altitude_ft);
282 props->setDoubleValue("controls/flight/target-pitch", pitch);
284 props->setDoubleValue("controls/flight/target-spd", speed);
288 void FGAIBase::unbind() {
290 props->untie("velocities/true-airspeed-kt");
291 props->untie("velocities/vertical-speed-fps");
293 props->untie("position/altitude-ft");
294 props->untie("position/latitude-deg");
295 props->untie("position/longitude-deg");
296 props->untie("position/global-x");
297 props->untie("position/global-y");
298 props->untie("position/global-z");
300 props->untie("orientation/pitch-deg");
301 props->untie("orientation/roll-deg");
302 props->untie("orientation/true-heading-deg");
304 props->untie("radar/in-range");
305 props->untie("radar/bearing-deg");
306 props->untie("radar/elevation-deg");
307 props->untie("radar/range-nm");
308 props->untie("radar/h-offset");
309 props->untie("radar/v-offset");
310 props->untie("radar/x-shift");
311 props->untie("radar/y-shift");
312 props->untie("radar/rotation");
313 props->untie("radar/ht-diff-ft");
315 props->untie("controls/lighting/nav-lights");
318 double FGAIBase::UpdateRadar(FGAIManager* manager) {
319 double radar_range_ft2 = fgGetDouble("/instrumentation/radar/range");
320 bool force_on = fgGetBool("/instrumentation/radar/debug-mode", false);
321 radar_range_ft2 *= SG_NM_TO_METER * SG_METER_TO_FEET * 1.1; // + 10%
322 radar_range_ft2 *= radar_range_ft2;
324 double user_latitude = manager->get_user_latitude();
325 double user_longitude = manager->get_user_longitude();
326 double lat_range = fabs(pos.getLatitudeDeg() - user_latitude) * ft_per_deg_lat;
327 double lon_range = fabs(pos.getLongitudeDeg() - user_longitude) * ft_per_deg_lon;
328 double range_ft2 = lat_range*lat_range + lon_range*lon_range;
331 // Test whether the target is within radar range.
333 in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
335 if ( in_range || force_on ) {
336 props->setBoolValue("radar/in-range", true);
338 // copy values from the AIManager
339 double user_altitude = manager->get_user_altitude();
340 double user_heading = manager->get_user_heading();
341 double user_pitch = manager->get_user_pitch();
342 //double user_yaw = manager->get_user_yaw();
343 //double user_speed = manager->get_user_speed();
345 // calculate range to target in feet and nautical miles
346 double range_ft = sqrt( range_ft2 );
347 range = range_ft / 6076.11549;
349 // calculate bearing to target
350 if (pos.getLatitudeDeg() >= user_latitude) {
351 bearing = atan2(lat_range, lon_range) * SG_RADIANS_TO_DEGREES;
352 if (pos.getLongitudeDeg() >= user_longitude) {
353 bearing = 90.0 - bearing;
355 bearing = 270.0 + bearing;
358 bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
359 if (pos.getLongitudeDeg() >= user_longitude) {
360 bearing = 180.0 - bearing;
362 bearing = 180.0 + bearing;
366 // This is an alternate way to compute bearing and distance which
367 // agrees with the original scheme within about 0.1 degrees.
369 // Point3D start( user_longitude * SGD_DEGREES_TO_RADIANS,
370 // user_latitude * SGD_DEGREES_TO_RADIANS, 0 );
371 // Point3D dest( pos.getLongitudeRad(), pos.getLatitudeRad(), 0 );
372 // double gc_bearing, gc_range;
373 // calc_gc_course_dist( start, dest, &gc_bearing, &gc_range );
374 // gc_range *= SG_METER_TO_NM;
375 // gc_bearing *= SGD_RADIANS_TO_DEGREES;
376 // printf("orig b = %.3f %.2f gc b= %.3f, %.2f\n",
377 // bearing, range, gc_bearing, gc_range);
379 // calculate look left/right to target, without yaw correction
380 horiz_offset = bearing - user_heading;
381 if (horiz_offset > 180.0) horiz_offset -= 360.0;
382 if (horiz_offset < -180.0) horiz_offset += 360.0;
384 // calculate elevation to target
385 elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
387 // calculate look up/down to target
388 vert_offset = elevation - user_pitch;
390 /* this calculation needs to be fixed, but it isn't important anyway
391 // calculate range rate
392 double recip_bearing = bearing + 180.0;
393 if (recip_bearing > 360.0) recip_bearing -= 360.0;
394 double my_horiz_offset = recip_bearing - hdg;
395 if (my_horiz_offset > 180.0) my_horiz_offset -= 360.0;
396 if (my_horiz_offset < -180.0) my_horiz_offset += 360.0;
397 rdot = (-user_speed * cos( horiz_offset * SG_DEGREES_TO_RADIANS ))
398 +(-speed * 1.686 * cos( my_horiz_offset * SG_DEGREES_TO_RADIANS ));
401 // now correct look left/right for yaw
402 // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
404 // calculate values for radar display
405 y_shift = range * cos( horiz_offset * SG_DEGREES_TO_RADIANS);
406 x_shift = range * sin( horiz_offset * SG_DEGREES_TO_RADIANS);
407 rotation = hdg - user_heading;
408 if (rotation < 0.0) rotation += 360.0;
409 ht_diff = altitude_ft - user_altitude;
417 * Getters and Setters
420 SGVec3d FGAIBase::getCartPosAt(const SGVec3d& _off) const {
421 // Transform that one to the horizontal local coordinate system.
422 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
424 // and postrotate the orientation of the AIModel wrt the horizontal
426 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
428 // The offset converted to the usual body fixed coordinate system
429 // rotated to the earth fiexed coordinates axis
430 SGVec3d off = hlTrans.backTransform(_off);
432 // Add the position offset of the AIModel to gain the earth centered position
433 SGVec3d cartPos = SGVec3d::fromGeod(pos);
435 return cartPos + off;
438 SGVec3d FGAIBase::getCartPos() const {
439 // Transform that one to the horizontal local coordinate system.
440 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
442 // and postrotate the orientation of the AIModel wrt the horizontal
444 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
446 SGVec3d cartPos = SGVec3d::fromGeod(pos);
451 double FGAIBase::_getCartPosX() const {
452 SGVec3d cartPos = getCartPos();
456 double FGAIBase::_getCartPosY() const {
457 SGVec3d cartPos = getCartPos();
461 double FGAIBase::_getCartPosZ() const {
462 SGVec3d cartPos = getCartPos();
466 void FGAIBase::_setLongitude( double longitude ) {
467 pos.setLongitudeDeg(longitude);
470 void FGAIBase::_setLatitude ( double latitude ) {
471 pos.setLatitudeDeg(latitude);
474 double FGAIBase::_getLongitude() const {
475 return pos.getLongitudeDeg();
478 double FGAIBase::_getLatitude () const {
479 return pos.getLatitudeDeg();
482 double FGAIBase::_getRdot() const {
486 double FGAIBase::_getVS_fps() const {
490 double FGAIBase::_get_speed_east_fps() const {
491 return speed_east_deg_sec * ft_per_deg_lon;
494 double FGAIBase::_get_speed_north_fps() const {
495 return speed_north_deg_sec * ft_per_deg_lat;
498 void FGAIBase::_setVS_fps( double _vs ) {
502 double FGAIBase::_getAltitude() const {
506 bool FGAIBase::_getServiceable() const {
510 void FGAIBase::_setAltitude( double _alt ) {
514 bool FGAIBase::_isNight() {
515 return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
518 int FGAIBase::getID() const {
522 double FGAIBase::_getSpeed() const {
526 double FGAIBase::_getRoll() const {
530 double FGAIBase::_getPitch() const {
534 double FGAIBase::_getHeading() const {
538 const char* FGAIBase::_getPath() {
539 return _path.c_str();
542 void FGAIBase::CalculateMach() {
543 // Calculate rho at altitude, using standard atmosphere
544 // For the temperature T and the pressure p,
545 double altitude = altitude_ft;
547 if (altitude < 36152) { // curve fits for the troposphere
548 T = 59 - 0.00356 * altitude;
549 p = 2116 * pow( ((T + 459.7) / 518.6) , 5.256);
550 } else if ( 36152 < altitude && altitude < 82345 ) { // lower stratosphere
552 p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
553 } else { // upper stratosphere
554 T = -205.05 + (0.00164 * altitude);
555 p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
558 rho = p / (1718 * (T + 459.7));
560 // calculate the speed of sound at altitude
561 // a = sqrt ( g * R * (T + 459.7))
563 // a = speed of sound [ft/s]
564 // g = specific heat ratio, which is usually equal to 1.4
565 // R = specific gas constant, which equals 1716 ft-lb/slug/°R
566 a = sqrt ( 1.4 * 1716 * (T + 459.7));
568 // calculate Mach number
571 // cout << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach << endl;
574 int FGAIBase::_newAIModelID() {
578 id++; // id = 0 is not allowed.