1 // FGAICarrier - FGAIShip-derived class creates an AI aircraft carrier
3 // Written by David Culp, started October 2004.
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.
28 #include <osg/NodeVisitor>
30 #include <simgear/sg_inlines.h>
31 #include <simgear/math/SGMath.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/scene/util/SGNodeMasks.hxx>
36 #include <Main/util.hxx>
37 #include <Main/viewer.hxx>
39 #include "AICarrier.hxx"
41 class FGCarrierVisitor : public osg::NodeVisitor {
43 FGCarrierVisitor(FGAICarrier* carrier,
44 const std::list<std::string>& wireObjects,
45 const std::list<std::string>& catapultObjects,
46 const std::list<std::string>& solidObjects) :
47 osg::NodeVisitor(osg::NodeVisitor::NODE_VISITOR,
48 osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
49 mWireObjects(wireObjects),
50 mCatapultObjects(catapultObjects),
51 mSolidObjects(solidObjects),
55 virtual void apply(osg::Node& node)
57 osg::ref_ptr<osg::Referenced> oldUserData = mUserData;
58 bool oldFoundHot = mFoundHot;
61 if (std::find(mWireObjects.begin(), mWireObjects.end(), node.getName())
62 != mWireObjects.end()) {
64 mUserData = FGAICarrierHardware::newWire(mCarrier);
66 if (std::find(mCatapultObjects.begin(), mCatapultObjects.end(), node.getName())
67 != mCatapultObjects.end()) {
69 mUserData = FGAICarrierHardware::newCatapult(mCarrier);
71 if (std::find(mSolidObjects.begin(), mSolidObjects.end(), node.getName())
72 != mSolidObjects.end()) {
74 mUserData = FGAICarrierHardware::newSolid(mCarrier);
75 //SG_LOG(SG_GENERAL, SG_ALERT, "AICarrierVisitor::apply() solidObject" );
77 node.setUserData(mUserData.get());
81 mFoundHot = oldFoundHot || mFoundHot;
84 node.setNodeMask(node.getNodeMask() | SG_NODEMASK_TERRAIN_BIT);
86 node.setNodeMask(node.getNodeMask() & ~SG_NODEMASK_TERRAIN_BIT);
88 mUserData = oldUserData;
92 std::list<std::string> mWireObjects;
93 std::list<std::string> mCatapultObjects;
94 std::list<std::string> mSolidObjects;
96 FGAICarrier* mCarrier;
97 osg::ref_ptr<osg::Referenced> mUserData;
100 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
103 FGAICarrier::~FGAICarrier() {
106 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
110 FGAIShip::readFromScenario(scFileNode);
112 setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
113 setSign(scFileNode->getStringValue("pennant-number"));
114 setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
115 setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
116 setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
117 setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
118 setMinLat(scFileNode->getDoubleValue("min-lat", 0));
119 setMaxLong(scFileNode->getDoubleValue("max-long", 0));
120 setMinLong(scFileNode->getDoubleValue("min-long", 0));
122 SGPropertyNode* flols = scFileNode->getChild("flols-pos");
124 // Transform to the right coordinate frame, configuration is done in
125 // the usual x-back, y-right, z-up coordinates, computations
126 // in the simulation usual body x-forward, y-right, z-down coordinates
127 flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
128 flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
129 flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
131 flols_off = SGVec3d::zeros();
133 std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("wire");
134 std::vector<SGPropertyNode_ptr>::const_iterator it;
135 for (it = props.begin(); it != props.end(); ++it) {
136 std::string s = (*it)->getStringValue();
138 wire_objects.push_back(s);
141 props = scFileNode->getChildren("catapult");
142 for (it = props.begin(); it != props.end(); ++it) {
143 std::string s = (*it)->getStringValue();
145 catapult_objects.push_back(s);
148 props = scFileNode->getChildren("solid");
149 for (it = props.begin(); it != props.end(); ++it) {
150 std::string s = (*it)->getStringValue();
152 solid_objects.push_back(s);
155 props = scFileNode->getChildren("parking-pos");
156 for (it = props.begin(); it != props.end(); ++it) {
157 string name = (*it)->getStringValue("name", "unnamed");
158 // Transform to the right coordinate frame, configuration is done in
159 // the usual x-back, y-right, z-up coordinates, computations
160 // in the simulation usual body x-forward, y-right, z-down coordinates
161 double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
162 double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
163 double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
164 double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
165 ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
166 ppositions.push_back(pp);
170 void FGAICarrier::setWind_from_east(double fps) {
171 wind_from_east = fps;
174 void FGAICarrier::setWind_from_north(double fps) {
175 wind_from_north = fps;
178 void FGAICarrier::setMaxLat(double deg) {
182 void FGAICarrier::setMinLat(double deg) {
186 void FGAICarrier::setMaxLong(double deg) {
187 max_long = fabs(deg);
190 void FGAICarrier::setMinLong(double deg) {
191 min_long = fabs(deg);
194 void FGAICarrier::setSign(const string& s) {
198 void FGAICarrier::setTACANChannelID(const string& id) {
199 TACAN_channel_id = id;
202 void FGAICarrier::getVelocityWrtEarth(SGVec3d& v, SGVec3d& omega, SGVec3d& pivot) {
204 omega = rot_wrt_earth;
205 pivot = rot_pivot_wrt_earth;
208 void FGAICarrier::update(double dt) {
209 // For computation of rotation speeds we just use finite differences here.
210 // That is perfectly valid since this thing is not driven by accelerations
211 // but by just apply discrete changes at its velocity variables.
212 // Update the velocity information stored in those nodes.
213 // Transform that one to the horizontal local coordinate system.
214 SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
215 // The orientation of the carrier wrt the horizontal local frame
216 SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
217 // and postrotate the orientation of the AIModel wrt the horizontal
219 SGQuatd ec2body = ec2hl*hl2body;
220 // The cartesian position of the carrier in the wgs84 world
221 SGVec3d cartPos = SGVec3d::fromGeod(pos);
222 // Store for later use by the groundcache
223 rot_pivot_wrt_earth = cartPos;
225 // Compute the velocity in m/s in the earth centered coordinate system axis
226 double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
227 double v_east = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
228 vel_wrt_earth = ec2hl.backTransform(SGVec3d(v_north, v_east, 0));
230 // Now update the position and heading. This will compute new hdg and
231 // roll values required for the rotation speed computation.
232 FGAIShip::update(dt);
235 //automatic turn into wind with a target wind of 25 kts otd
236 if(turn_to_launch_hdg){
238 } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
244 // Only change these values if we are able to compute them safely
246 rot_wrt_earth = SGVec3d::zeros();
248 // Now here is the finite difference ...
250 // Transform that one to the horizontal local coordinate system.
251 SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
252 // compute the new orientation
253 SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
254 // The rotation difference
255 SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
256 SGVec3d dOrAngleAxis;
257 dOr.getAngleAxis(dOrAngleAxis);
258 // divided by the time difference provides a rotation speed vector
261 // now rotate the rotation speed vector back into the
262 // earth centered frames coordinates
263 dOrAngleAxis = ec2body.backTransform(dOrAngleAxis);
264 // dOrAngleAxis = hl2body.backTransform(dOrAngleAxis);
265 // dOrAngleAxis(1) = 0;
266 // dOrAngleAxis = ec2hl.backTransform(dOrAngleAxis);
267 rot_wrt_earth = dOrAngleAxis;
271 UpdateElevator(dt, transition_time);
272 UpdateJBD(dt, jbd_transition_time);
273 // For the flols reuse some computations done above ...
275 // The position of the eyepoint - at least near that ...
276 SGVec3d eyePos(globals->get_current_view()->get_view_pos());
277 // Add the position offset of the AIModel to gain the earth
279 SGVec3d eyeWrtCarrier = eyePos - cartPos;
280 // rotate the eyepoint wrt carrier vector into the carriers frame
281 eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
282 // the eyepoints vector wrt the flols position
283 SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
285 // the distance from the eyepoint to the flols
286 dist = norm(eyeWrtFlols);
288 // now the angle, positive angles are upwards
289 if (fabs(dist) < SGLimits<float>::min()) {
292 double sAngle = -eyeWrtFlols(2)/dist;
293 sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
294 angle = SGMiscd::rad2deg(asin(sAngle));
297 // set the value of source
298 if ( angle <= 4.35 && angle > 4.01 )
300 else if ( angle <= 4.01 && angle > 3.670 )
302 else if ( angle <= 3.670 && angle > 3.330 )
304 else if ( angle <= 3.330 && angle > 2.990 )
306 else if ( angle <= 2.990 && angle > 2.650 )
308 else if ( angle <= 2.650 )
314 bool FGAICarrier::init(bool search_in_AI_path) {
315 if (!FGAIShip::init(search_in_AI_path))
318 _longitude_node = fgGetNode("/position/longitude-deg", true);
319 _latitude_node = fgGetNode("/position/latitude-deg", true);
320 _altitude_node = fgGetNode("/position/altitude-ft", true);
322 _launchbar_state_node = fgGetNode("/gear/launchbar/state", true);
324 _surface_wind_from_deg_node =
325 fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
326 _surface_wind_speed_node =
327 fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
330 turn_to_launch_hdg = false;
339 transition_time = 150;
340 time_constant = 0.005;
341 jbd_pos_norm = raw_jbd_pos_norm = 0;
343 jbd_transition_time = 3;
344 jbd_time_constant = 0.1;
348 void FGAICarrier::initModel(osg::Node *node)
350 // SG_LOG(SG_GENERAL, SG_BULK, "AICarrier::initModel()" );
351 FGAIShip::initModel(node);
352 // process the 3d model here
353 // mark some objects solid, mark the wires ...
355 // The model should be used for altitude computations.
356 // To avoid that every detail in a carrier 3D model will end into
357 // the aircraft local cache, only set the HOT traversal bit on
360 // Clear the HOT traversal flag
361 // Selectively set that flag again for wires/cats/solid objects.
362 // Attach a pointer to this carrier class to those objects.
363 // SG_LOG(SG_GENERAL, SG_BULK, "AICarrier::initModel() visit" );
364 FGCarrierVisitor carrierVisitor(this, wire_objects, catapult_objects, solid_objects);
365 model->accept(carrierVisitor);
366 // model->setNodeMask(node->getNodeMask() & SG_NODEMASK_TERRAIN_BIT | model->getNodeMask());
369 void FGAICarrier::bind() {
372 props->untie("velocities/true-airspeed-kt");
374 props->tie("controls/flols/source-lights",
375 SGRawValuePointer<int>(&source));
376 props->tie("controls/flols/distance-m",
377 SGRawValuePointer<double>(&dist));
378 props->tie("controls/flols/angle-degs",
379 SGRawValuePointer<double>(&angle));
380 props->tie("controls/turn-to-launch-hdg",
381 SGRawValuePointer<bool>(&turn_to_launch_hdg));
382 props->tie("controls/in-to-wind",
383 SGRawValuePointer<bool>(&turn_to_launch_hdg));
384 props->tie("controls/base-course-deg",
385 SGRawValuePointer<double>(&base_course));
386 props->tie("controls/base-speed-kts",
387 SGRawValuePointer<double>(&base_speed));
388 props->tie("controls/start-pos-lat-deg",
389 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLatitudeDeg));
390 props->tie("controls/start-pos-long-deg",
391 SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLongitudeDeg));
392 props->tie("velocities/speed-kts",
393 SGRawValuePointer<double>(&speed));
394 props->tie("environment/surface-wind-speed-true-kts",
395 SGRawValuePointer<double>(&wind_speed_kts));
396 props->tie("environment/surface-wind-from-true-degs",
397 SGRawValuePointer<double>(&wind_from_deg));
398 props->tie("environment/rel-wind-from-degs",
399 SGRawValuePointer<double>(&rel_wind_from_deg));
400 props->tie("environment/rel-wind-from-carrier-hdg-degs",
401 SGRawValuePointer<double>(&rel_wind));
402 props->tie("environment/rel-wind-speed-kts",
403 SGRawValuePointer<double>(&rel_wind_speed_kts));
404 props->tie("controls/flols/wave-off-lights",
405 SGRawValuePointer<bool>(&wave_off_lights));
406 props->tie("controls/elevators",
407 SGRawValuePointer<bool>(&elevators));
408 props->tie("surface-positions/elevators-pos-norm",
409 SGRawValuePointer<double>(&pos_norm));
410 props->tie("controls/elevators-trans-time-s",
411 SGRawValuePointer<double>(&transition_time));
412 props->tie("controls/elevators-time-constant",
413 SGRawValuePointer<double>(&time_constant));
414 props->tie("controls/jbd",
415 SGRawValuePointer<bool>(&jbd));
416 props->tie("surface-positions/jbd-pos-norm",
417 SGRawValuePointer<double>(&jbd_pos_norm));
418 props->tie("controls/jbd-trans-time-s",
419 SGRawValuePointer<double>(&jbd_transition_time));
420 props->tie("controls/jbd-time-constant",
421 SGRawValuePointer<double>(&jbd_time_constant));
423 props->setBoolValue("controls/flols/cut-lights", false);
424 props->setBoolValue("controls/flols/wave-off-lights", false);
425 props->setBoolValue("controls/flols/cond-datum-lights", true);
426 props->setBoolValue("controls/crew", false);
427 props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
428 props->setStringValue("sign", sign.c_str());
432 void FGAICarrier::unbind() {
435 props->untie("velocities/true-airspeed-kt");
436 props->untie("controls/flols/source-lights");
437 props->untie("controls/flols/distance-m");
438 props->untie("controls/flols/angle-degs");
439 props->untie("controls/turn-to-launch-hdg");
440 props->untie("velocities/speed-kts");
441 props->untie("environment/wind-speed-true-kts");
442 props->untie("environment/wind-from-true-degs");
443 props->untie("environment/rel-wind-from-degs");
444 props->untie("environment/rel-wind-speed-kts");
445 props->untie("controls/flols/wave-off-lights");
446 props->untie("controls/elevators");
447 props->untie("surface-positions/elevators-pos-norm");
448 props->untie("controls/elevators-trans-time-secs");
449 props->untie("controls/elevators-time-constant");
450 props->untie("controls/jbd");
451 props->untie("surface-positions/jbd-pos-norm");
452 props->untie("controls/jbd-trans-time-s");
453 props->untie("controls/jbd-time-constant");
458 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
459 double& hdng, SGVec3d& uvw)
462 // FIXME: does not yet cover rotation speeds.
463 list<ParkPosition>::iterator it = ppositions.begin();
464 while (it != ppositions.end()) {
465 // Take either the specified one or the first one ...
466 if ((*it).name == id || id.empty()) {
467 ParkPosition ppos = *it;
468 SGVec3d cartPos = getCartPosAt(ppos.offset);
469 geodPos = SGGeod::fromCart(cartPos);
470 hdng = hdg + ppos.heading_deg;
471 double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
472 double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
473 double speed_fps = speed*1.6878099;
474 uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
483 // find relative wind
484 void FGAICarrier::UpdateWind( double dt) {
486 //get the surface wind speed and direction
487 wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
488 wind_speed_kts = _surface_wind_speed_node->getDoubleValue();
490 //calculate the surface wind speed north and east in kts
491 double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
492 double wind_speed_from_east_kts = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
494 //calculate the carrier speed north and east in kts
495 double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
496 double speed_east_kts = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
498 //calculate the relative wind speed north and east in kts
499 double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
500 double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
502 //combine relative speeds north and east to get relative windspeed in kts
503 rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
504 + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
506 //calculate the relative wind direction
507 rel_wind_from_deg = atan2(rel_wind_speed_from_east_kts, rel_wind_speed_from_north_kts)
508 * SG_RADIANS_TO_DEGREES;
511 rel_wind = rel_wind_from_deg - hdg;
512 SG_NORMALIZE_RANGE(rel_wind, -180.0, 180.0);
514 //switch the wave-off lights
516 wave_off_lights = false;
518 wave_off_lights = true;
520 // cout << "rel wind: " << rel_wind << endl;
525 void FGAICarrier::TurnToLaunch(){
527 //calculate tgt speed
528 double tgt_speed = 25 - wind_speed_kts;
533 FGAIShip::TurnTo(wind_from_deg);
534 FGAIShip::AccelTo(tgt_speed);
539 void FGAICarrier::TurnToBase(){
542 FGAIShip::TurnTo(base_course);
543 FGAIShip::AccelTo(base_speed);
548 void FGAICarrier::ReturnToBox(){
549 double course, distance, az2;
551 //calculate the bearing and range of the initial position from the carrier
552 geo_inverse_wgs_84(pos, mOpBoxPos, &course, &az2, &distance);
554 distance *= SG_METER_TO_NM;
556 //cout << "return course: " << course << " distance: " << distance << endl;
558 FGAIShip::TurnTo(course);
559 FGAIShip::AccelTo(base_speed);
566 } // end turn to base
569 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
571 if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
572 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
576 if (mOpBoxPos.getLatitudeDeg() >= 0) { //northern hemisphere
577 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + max_lat)
580 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - min_lat)
583 } else { //southern hemisphere
584 if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - max_lat)
587 if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + min_lat)
591 if (mOpBoxPos.getLongitudeDeg() >=0) { //eastern hemisphere
592 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + max_long)
595 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - min_long)
598 } else { //western hemisphere
599 if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - max_long)
602 if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + min_long)
606 SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
612 bool FGAICarrier::InToWind() {
613 if ( fabs(rel_wind) < 5 )
620 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
624 if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
627 // move the elevators
629 step = dt/transition_time;
633 step = -dt/transition_time;
637 // assume a linear relationship
638 raw_pos_norm += step;
641 pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
643 //sanitise the output
644 if (raw_pos_norm >= 1) {
646 } else if (raw_pos_norm <= 0) {
651 } // end UpdateElevator
653 void FGAICarrier::UpdateJBD(double dt, double jbd_transition_time) {
655 string launchbar_state = _launchbar_state_node->getStringValue();
658 if (launchbar_state == "Engaged"){
664 if (( jbd && jbd_pos_norm >= 1 ) || ( !jbd && jbd_pos_norm <= 0 )){
670 step = dt/jbd_transition_time;
674 step = -dt/jbd_transition_time;
679 // assume a linear relationship
680 raw_jbd_pos_norm += step;
683 jbd_pos_norm = (raw_jbd_pos_norm * jbd_time_constant) + (jbd_pos_norm * (1 - jbd_time_constant));
685 //sanitise the output
686 if (jbd_pos_norm >= 1) {
688 } else if (jbd_pos_norm <= 0) {
697 int FGAICarrierHardware::unique_id = 1;