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);
129 bool FGAIBase::init() {
131 if (!model_path.empty()) {
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 &) {
142 model = load3DModel( globals->get_fg_root(), model_path, props,
143 globals->get_sim_time_sec() );
144 } catch (const sg_exception &) {
150 aip.init( model.get() );
151 aip.setVisible(true);
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());
158 if (!model_path.empty()) {
159 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("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));
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));
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);
231 props->setStringValue("controls/flight/lateral-mode", "roll");
232 props->setDoubleValue("controls/flight/target-hdg", hdg);
233 props->setDoubleValue("controls/flight/target-roll", roll);
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);
239 props->setDoubleValue("controls/flight/target-spd", speed);
243 void FGAIBase::unbind() {
245 props->untie("velocities/true-airspeed-kt");
246 props->untie("velocities/vertical-speed-fps");
248 props->untie("position/altitude-ft");
249 props->untie("position/latitude-deg");
250 props->untie("position/longitude-deg");
252 props->untie("orientation/pitch-deg");
253 props->untie("orientation/roll-deg");
254 props->untie("orientation/true-heading-deg");
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");
267 props->untie("controls/lighting/nav-lights");
270 double FGAIBase::UpdateRadar(FGAIManager* manager)
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;
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;
284 // Test whether the target is within radar range.
286 in_range = (range_ft2 && (range_ft2 <= radar_range_ft2));
287 if ( in_range || force_on )
289 props->setBoolValue("radar/in-range", true);
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();
298 // calculate range to target in feet and nautical miles
299 double range_ft = sqrt( range_ft2 );
300 range = range_ft / 6076.11549;
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;
308 bearing = 270.0 + bearing;
311 bearing = atan2(lon_range, lat_range) * SG_RADIANS_TO_DEGREES;
312 if (pos.getLongitudeDeg() >= user_longitude) {
313 bearing = 180.0 - bearing;
315 bearing = 180.0 + bearing;
319 // This is an alternate way to compute bearing and distance which
320 // agrees with the original scheme within about 0.1 degrees.
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);
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;
337 // calculate elevation to target
338 elevation = atan2( altitude_ft - user_altitude, range_ft ) * SG_RADIANS_TO_DEGREES;
340 // calculate look up/down to target
341 vert_offset = elevation - user_pitch;
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 ));
354 // now correct look left/right for yaw
355 // horiz_offset += user_yaw; // FIXME: WHY WOULD WE WANT TO ADD IN SIDE-SLIP HERE?
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;
370 FGAIBase::getCartPosAt(const SGVec3d& _off) const
372 // Transform that one to the horizontal local coordinate system.
374 SGQuatd hlTrans = SGQuatd::fromLonLat(pos);
375 // and postrotate the orientation of the AIModel wrt the horizontal
377 hlTrans *= SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
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);
383 // Add the position offset of the AIModel to gain the earth centered position
384 SGVec3d cartPos = SGVec3d::fromGeod(pos);
386 return cartPos + off;
390 * getters and Setters
392 void FGAIBase::_setLongitude( double longitude ) {
393 pos.setLongitudeDeg(longitude);
395 void FGAIBase::_setLatitude ( double latitude ) {
396 pos.setLatitudeDeg(latitude);
399 double FGAIBase::_getLongitude() const {
400 return pos.getLongitudeDeg();
402 double FGAIBase::_getLatitude () const {
403 return pos.getLatitudeDeg();
405 double FGAIBase::_getRdot() const {
408 double FGAIBase::_getVS_fps() const {
411 void FGAIBase::_setVS_fps( double _vs ) {
415 double FGAIBase::_getAltitude() const {
418 void FGAIBase::_setAltitude( double _alt ) {
422 bool FGAIBase::_isNight() {
423 return (fgGetFloat("/sim/time/sun-angle-rad") > 1.57);
426 int FGAIBase::getID() const {
430 void FGAIBase::CalculateMach() {
431 // Calculate rho at altitude, using standard atmosphere
432 // For the temperature T and the pressure p,
434 double altitude = altitude_ft;
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);
440 } else if ( 36152 < altitude && altitude < 82345 ) { // lower stratosphere
442 p = 473.1 * pow( e , 1.73 - (0.000048 * altitude) );
444 } else { // upper stratosphere
445 T = -205.05 + (0.00164 * altitude);
446 p = 51.97 * pow( ((T + 459.7) / 389.98) , -11.388);
449 rho = p / (1718 * (T + 459.7));
451 // calculate the speed of sound at altitude
452 // a = sqrt ( g * R * (T + 459.7))
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
458 a = sqrt ( 1.4 * 1716 * (T + 459.7));
460 // calculate Mach number
464 // cout << "Speed(ft/s) "<< speed <<" Altitude(ft) "<< altitude << " Mach " << Mach;
467 int FGAIBase::_newAIModelID() {
470 id++; // id = 0 is not allowed.