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 // 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.
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.
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.
25 #include <simgear/compiler.h>
29 #include <osg/ref_ptr>
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>
42 #include <Main/globals.hxx>
43 #include <Scenery/scenery.hxx>
47 #include "AIManager.hxx"
50 const double FGAIBase::e = 2.71828183;
51 const double FGAIBase::lbs_to_slugs = 0.031080950172; //conversion factor
54 FGAIBase::FGAIBase(object_type ot) :
56 model_removed( fgGetNode("/ai/models/model-removed", true) ),
59 _refID( _newAIModelID() ),
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;
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());
80 SGPropertyNode* parent = props->getParent();
82 model_removed->setStringValue(props->getPath());
83 parent->removeChild(props->getName(), props->getIndex(), false);
91 void FGAIBase::readFromScenario(SGPropertyNode* scFileNode)
96 setPath(scFileNode->getStringValue("model", "Models/Geometry/glider.ac"));
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));
106 void FGAIBase::update(double dt) {
107 if (_otype == otStatic)
109 if (_otype == otBallistic)
112 ft_per_deg_lat = 366468.96 - 3717.12 * cos(pos.getLatitudeRad());
113 ft_per_deg_lon = 365228.16 * cos(pos.getLatitudeRad());
116 void FGAIBase::Transform() {
118 aip.setPosition(pos);
120 aip.setOrientation(0.0, pitch, hdg);
122 aip.setOrientation(roll, pitch, hdg);
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);
135 model = load3DModel( globals->get_fg_root(), ai_path.str(), props,
136 globals->get_sim_time_sec() );
137 } catch (const sg_exception &e) {
143 model = load3DModel( globals->get_fg_root(), model_path, props,
144 globals->get_sim_time_sec() );
145 } catch (const sg_exception &e) {
151 aip.init( model.get() );
152 aip.setVisible(true);
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());
159 if (!model_path.empty()) {
160 SG_LOG(SG_INPUT, SG_WARN, "AIBase: Could not load model " << model_path);
170 FGAIBase::load3DModel(const string& fg_root,
172 SGPropertyNode *prop_root,
175 model = sgLoad3DModel(fg_root, path, prop_root, sim_time_sec);
176 model->setNodeMask(model->getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
180 bool FGAIBase::isa( object_type otype ) {
181 if ( otype == _otype )
188 void FGAIBase::bind() {
189 props->tie("id", SGRawValueMethods<FGAIBase,int>(*this,
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));
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));
210 props->tie("position/global-x",
211 SGRawValueMethods<FGAIBase,double>(*this,
212 &FGAIBase::_getCartPosX,
214 props->tie("position/global-y",
215 SGRawValueMethods<FGAIBase,double>(*this,
216 &FGAIBase::_getCartPosY,
218 props->tie("position/global-z",
219 SGRawValueMethods<FGAIBase,double>(*this,
220 &FGAIBase::_getCartPosZ,
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));
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));
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);
244 props->setStringValue("controls/flight/lateral-mode", "roll");
245 props->setDoubleValue("controls/flight/target-hdg", hdg);
246 props->setDoubleValue("controls/flight/target-roll", roll);
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);
252 props->setDoubleValue("controls/flight/target-spd", speed);
256 void FGAIBase::unbind() {
258 props->untie("velocities/true-airspeed-kt");
259 props->untie("velocities/vertical-speed-fps");
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");
268 props->untie("orientation/pitch-deg");
269 props->untie("orientation/roll-deg");
270 props->untie("orientation/true-heading-deg");
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");
283 props->untie("controls/lighting/nav-lights");
286 double FGAIBase::UpdateRadar(FGAIManager* manager)
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;
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;
300 // Test whether the target is within radar range.
302 in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
303 if ( in_range || force_on )
305 props->setBoolValue("radar/in-range", true);
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();
314 // calculate range to target in feet and nautical miles
315 double range_ft = sqrt( range_ft2 );
316 range = range_ft / 6076.11549;
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;
324 bearing = 270.0 + bearing;
327 bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
328 if (pos.getLongitudeDeg() >= user_longitude) {
329 bearing = 180.0 - bearing;
331 bearing = 180.0 + bearing;
335 // This is an alternate way to compute bearing and distance which
336 // agrees with the original scheme within about 0.1 degrees.
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);
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;
353 // calculate elevation to target
354 elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
356 // calculate look up/down to target
357 vert_offset = elevation - user_pitch;
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 ));
370 // now correct look left/right for yaw
371 // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
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;
386 FGAIBase::getCartPosAt(const SGVec3d& _off) const
388 // Transform that one to the horizontal local coordinate system.
390 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
391 // and postrotate the orientation of the AIModel wrt the horizontal
393 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
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);
399 // Add the position offset of the AIModel to gain the earth centered position
400 SGVec3d cartPos = SGVec3d::fromGeod(pos);
402 return cartPos + off;
406 FGAIBase::getCartPos() const
408 // Transform that one to the horizontal local coordinate system.
410 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
411 // and postrotate the orientation of the AIModel wrt the horizontal
413 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
415 SGVec3d cartPos = SGVec3d::fromGeod(pos);
421 FGAIBase::_getCartPosX() const
423 SGVec3d cartPos = getCartPos();
428 FGAIBase::_getCartPosY() const
430 SGVec3d cartPos = getCartPos();
435 FGAIBase::_getCartPosZ() const
437 SGVec3d cartPos = getCartPos();
442 * getters and Setters
444 void FGAIBase::_setLongitude( double longitude ) {
445 pos.setLongitudeDeg(longitude);
447 void FGAIBase::_setLatitude ( double latitude ) {
448 pos.setLatitudeDeg(latitude);
451 double FGAIBase::_getLongitude() const {
452 return pos.getLongitudeDeg();
454 double FGAIBase::_getLatitude () const {
455 return pos.getLatitudeDeg();
457 double FGAIBase::_getRdot() const {
460 double FGAIBase::_getVS_fps() const {
463 void FGAIBase::_setVS_fps( double _vs ) {
467 double FGAIBase::_getAltitude() const {
470 void FGAIBase::_setAltitude( double _alt ) {
474 bool FGAIBase::_isNight() {
475 return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
478 int FGAIBase::getID() const {
482 void FGAIBase::CalculateMach() {
483 // Calculate rho at altitude, using standard atmosphere
484 // For the temperature T and the pressure p,
486 double altitude = altitude_ft;
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);
492 } else if ( 36152 < altitude && altitude < 82345 ) { // lower stratosphere
494 p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
496 } else { // upper stratosphere
497 T = -205.05 + (0.00164 * altitude);
498 p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
501 rho = p / (1718 * (T + 459.7));
503 // calculate the speed of sound at altitude
504 // a = sqrt ( g * R * (T + 459.7))
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
510 a = sqrt ( 1.4 * 1716 * (T + 459.7));
512 // calculate Mach number
516 // cout << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach;
519 int FGAIBase::_newAIModelID() {
522 id++; // id = 0 is not allowed.