]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AICarrier.cxx
Make the vertical acceleration rate scale with vertical performance. The
[flightgear.git] / src / AIModel / AICarrier.cxx
1 // FGAICarrier - FGAIShip-derived class creates an AI aircraft carrier
2 //
3 // Written by David Culp, started October 2004.
4 // - davidculp2@comcast.net
5 //
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.
10 //
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.
15 //
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.
19
20 #ifdef HAVE_CONFIG_H
21 #  include <config.h>
22 #endif
23
24 #include <string>
25 #include <vector>
26
27 #include <simgear/math/SGMath.hxx>
28 #include <simgear/math/point3d.hxx>
29 #include <simgear/math/sg_geodesy.hxx>
30 #include <math.h>
31 #include <Main/util.hxx>
32 #include <Main/viewer.hxx>
33
34 #include "AICarrier.hxx"
35
36 /** Value of earth radius (meters) */
37 #define RADIUS_M   SG_EQUATORIAL_RADIUS_M
38
39
40
41 FGAICarrier::FGAICarrier() : FGAIShip(otCarrier) {
42 }
43
44 FGAICarrier::~FGAICarrier() {
45 }
46
47 void FGAICarrier::readFromScenario(SGPropertyNode* scFileNode) {
48   if (!scFileNode)
49     return;
50
51   FGAIShip::readFromScenario(scFileNode);
52
53   setRadius(scFileNode->getDoubleValue("turn-radius-ft", 2000));
54   setSign(scFileNode->getStringValue("pennant-number"));
55   setWind_from_east(scFileNode->getDoubleValue("wind_from_east", 0));
56   setWind_from_north(scFileNode->getDoubleValue("wind_from_north", 0));
57   setTACANChannelID(scFileNode->getStringValue("TACAN-channel-ID", "029Y"));
58   setMaxLat(scFileNode->getDoubleValue("max-lat", 0));
59   setMinLat(scFileNode->getDoubleValue("min-lat", 0));
60   setMaxLong(scFileNode->getDoubleValue("max-long", 0));
61   setMinLong(scFileNode->getDoubleValue("min-long", 0));
62
63   SGPropertyNode* flols = scFileNode->getChild("flols-pos");
64   if (flols) {
65     // Transform to the right coordinate frame, configuration is done in
66     // the usual x-back, y-right, z-up coordinates, computations
67     // in the simulation usual body x-forward, y-right, z-down coordinates
68     flols_off(0) = - flols->getDoubleValue("x-offset-m", 0);
69     flols_off(1) = flols->getDoubleValue("y-offset-m", 0);
70     flols_off(2) = - flols->getDoubleValue("z-offset-m", 0);
71   } else
72     flols_off = SGVec3d::zeros();
73
74   std::vector<SGPropertyNode_ptr> props = scFileNode->getChildren("wire");
75   std::vector<SGPropertyNode_ptr>::const_iterator it;
76   for (it = props.begin(); it != props.end(); ++it) {
77     std::string s = (*it)->getStringValue();
78     if (!s.empty())
79       wire_objects.push_back(s);
80   }
81
82   props = scFileNode->getChildren("catapult");
83   for (it = props.begin(); it != props.end(); ++it) {
84     std::string s = (*it)->getStringValue();
85     if (!s.empty())
86       catapult_objects.push_back(s);
87   }
88
89   props = scFileNode->getChildren("solid");
90   for (it = props.begin(); it != props.end(); ++it) {
91     std::string s = (*it)->getStringValue();
92     if (!s.empty())
93       solid_objects.push_back(s);
94   }
95
96   props = scFileNode->getChildren("parking-pos");
97   for (it = props.begin(); it != props.end(); ++it) {
98     string name = (*it)->getStringValue("name", "unnamed");
99     // Transform to the right coordinate frame, configuration is done in
100     // the usual x-back, y-right, z-up coordinates, computations
101     // in the simulation usual body x-forward, y-right, z-down coordinates
102     double offset_x = -(*it)->getDoubleValue("x-offset-m", 0);
103     double offset_y = (*it)->getDoubleValue("y-offset-m", 0);
104     double offset_z = -(*it)->getDoubleValue("z-offset-m", 0);
105     double hd = (*it)->getDoubleValue("heading-offset-deg", 0);
106     ParkPosition pp(name, SGVec3d(offset_x, offset_y, offset_z), hd);
107     ppositions.push_back(pp);
108   }
109 }
110
111 void FGAICarrier::setWind_from_east(double fps) {
112     wind_from_east = fps;
113 }
114
115 void FGAICarrier::setWind_from_north(double fps) {
116     wind_from_north = fps;
117 }
118
119 void FGAICarrier::setMaxLat(double deg) {
120     max_lat = fabs(deg);
121 }
122
123 void FGAICarrier::setMinLat(double deg) {
124     min_lat = fabs(deg);
125 }
126
127 void FGAICarrier::setMaxLong(double deg) {
128     max_long = fabs(deg);
129 }
130
131 void FGAICarrier::setMinLong(double deg) {
132     min_long = fabs(deg);
133 }
134
135 void FGAICarrier::setSign(const string& s) {
136     sign = s;
137 }
138
139 void FGAICarrier::setTACANChannelID(const string& id) {
140     TACAN_channel_id = id;
141 }
142
143 void FGAICarrier::getVelocityWrtEarth(sgdVec3& v, sgdVec3& omega, sgdVec3& pivot) {
144     sgdCopyVec3(v, vel_wrt_earth.sg() );
145     sgdCopyVec3(omega, rot_wrt_earth.sg() );
146     sgdCopyVec3(pivot, rot_pivot_wrt_earth.sg() );
147 }
148
149 void FGAICarrier::update(double dt) {
150     // For computation of rotation speeds we just use finite differences here.
151     // That is perfectly valid since this thing is not driven by accelerations
152     // but by just apply discrete changes at its velocity variables.
153     // Update the velocity information stored in those nodes.
154     // Transform that one to the horizontal local coordinate system.
155     SGQuatd ec2hl = SGQuatd::fromLonLat(pos);
156     // The orientation of the carrier wrt the horizontal local frame
157     SGQuatd hl2body = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
158     // and postrotate the orientation of the AIModel wrt the horizontal
159     // local frame
160     SGQuatd ec2body = ec2hl*hl2body;
161     // The cartesian position of the carrier in the wgs84 world
162     SGVec3d cartPos = SGVec3d::fromGeod(pos);
163     // Store for later use by the groundcache
164     rot_pivot_wrt_earth = cartPos;
165
166     // Compute the velocity in m/s in the earth centered coordinate system axis
167     double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
168     double v_east  = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
169     vel_wrt_earth = ec2hl.backTransform(SGVec3d(v_north, v_east, 0));
170
171     // Now update the position and heading. This will compute new hdg and
172     // roll values required for the rotation speed computation.
173     FGAIShip::update(dt);
174
175
176     //automatic turn into wind with a target wind of 25 kts otd
177     if(turn_to_launch_hdg){
178         TurnToLaunch();
179     } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
180         ReturnToBox();
181     } else {
182         TurnToBase();
183     }
184
185     // Only change these values if we are able to compute them safely
186     if (dt < DBL_MIN)
187       rot_wrt_earth = SGVec3d::zeros();
188     else {
189       // Now here is the finite difference ...
190
191       // Transform that one to the horizontal local coordinate system.
192       SGQuatd ec2hlNew = SGQuatd::fromLonLat(pos);
193       // compute the new orientation
194       SGQuatd hl2bodyNew = SGQuatd::fromYawPitchRollDeg(hdg, pitch, roll);
195       // The rotation difference
196       SGQuatd dOr = inverse(ec2body)*ec2hlNew*hl2bodyNew;
197       SGVec3d dOrAngleAxis;
198       dOr.getAngleAxis(dOrAngleAxis);
199       // divided by the time difference provides a rotation speed vector
200       dOrAngleAxis /= dt;
201
202       // now rotate the rotation speed vector back into the
203       // earth centered frames coordinates
204       dOrAngleAxis = ec2body.backTransform(dOrAngleAxis);
205 //       dOrAngleAxis = hl2body.backTransform(dOrAngleAxis);
206 //       dOrAngleAxis(1) = 0;
207 //       dOrAngleAxis = ec2hl.backTransform(dOrAngleAxis);
208       rot_wrt_earth = dOrAngleAxis;
209     }
210
211     UpdateWind(dt);
212     UpdateElevator(dt, transition_time);
213     UpdateJBD(dt, jbd_transition_time);
214     // For the flols reuse some computations done above ...
215
216     // The position of the eyepoint - at least near that ...
217     SGVec3d eyePos(globals->get_current_view()->get_absolute_view_pos());
218     // Add the position offset of the AIModel to gain the earth
219     // centered position
220     SGVec3d eyeWrtCarrier = eyePos - cartPos;
221     // rotate the eyepoint wrt carrier vector into the carriers frame
222     eyeWrtCarrier = ec2body.transform(eyeWrtCarrier);
223     // the eyepoints vector wrt the flols position
224     SGVec3d eyeWrtFlols = eyeWrtCarrier - flols_off;
225     
226     // the distance from the eyepoint to the flols
227     dist = norm(eyeWrtFlols);
228     
229     // now the angle, positive angles are upwards
230     if (fabs(dist) < SGLimits<float>::min()) {
231       angle = 0;
232     } else {
233       double sAngle = -eyeWrtFlols(2)/dist;
234       sAngle = SGMiscd::min(1, SGMiscd::max(-1, sAngle));
235       angle = SGMiscd::rad2deg(asin(sAngle));
236     }
237     
238     // set the value of source
239     if ( angle <= 4.35 && angle > 4.01 )
240       source = 1;
241     else if ( angle <= 4.01 && angle > 3.670 )
242       source = 2;
243     else if ( angle <= 3.670 && angle > 3.330 )
244       source = 3;
245     else if ( angle <= 3.330 && angle > 2.990 )
246       source = 4;
247     else if ( angle <= 2.990 && angle > 2.650 )
248       source = 5;
249     else if ( angle <= 2.650 )
250       source = 6;
251     else
252       source = 0;
253 } //end update
254
255 bool FGAICarrier::init() {
256     if (!FGAIShip::init())
257         return false;
258
259     // process the 3d model here
260     // mark some objects solid, mark the wires ...
261
262     // The model should be used for altitude computations.
263     // To avoid that every detail in a carrier 3D model will end into
264     // the aircraft local cache, only set the HOT traversal bit on
265     // selected objects.
266     ssgEntity *sel = aip.getSceneGraph();
267     // Clear the HOT traversal flag
268     mark_nohot(sel);
269     // Selectively set that flag again for wires/cats/solid objects.
270     // Attach a pointer to this carrier class to those objects.
271     mark_wires(sel, wire_objects);
272     mark_cat(sel, catapult_objects);
273     mark_solid(sel, solid_objects);
274
275     _longitude_node = fgGetNode("/position/longitude-deg", true);
276     _latitude_node = fgGetNode("/position/latitude-deg", true);
277     _altitude_node = fgGetNode("/position/altitude-ft", true);
278
279     _launchbar_state_node = fgGetNode("/gear/launchbar/state", true);
280
281     _surface_wind_from_deg_node =
282             fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
283     _surface_wind_speed_node =
284             fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
285
286
287     turn_to_launch_hdg = false;
288     returning = false;
289
290     mOpBoxPos = pos;
291     base_course = hdg;
292     base_speed = speed;
293
294     pos_norm = 0;
295     elevators = false;
296     transition_time = 150;
297     time_constant = 0.005;
298     jbd_pos_norm = raw_jbd_pos_norm = 0;
299     jbd = false ;
300     jbd_transition_time = 3;
301     jbd_time_constant = 0.1;
302     return true;
303 }
304
305 void FGAICarrier::bind() {
306     FGAIShip::bind();
307
308     props->untie("velocities/true-airspeed-kt");
309
310     props->tie("controls/flols/source-lights",
311                 SGRawValuePointer<int>(&source));
312     props->tie("controls/flols/distance-m",
313                 SGRawValuePointer<double>(&dist));
314     props->tie("controls/flols/angle-degs",
315                 SGRawValuePointer<double>(&angle));
316     props->tie("controls/turn-to-launch-hdg",
317                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
318     props->tie("controls/in-to-wind",
319                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
320     props->tie("controls/base-course-deg",
321                 SGRawValuePointer<double>(&base_course));
322     props->tie("controls/base-speed-kts",
323                 SGRawValuePointer<double>(&base_speed));
324     props->tie("controls/start-pos-lat-deg",
325                SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLatitudeDeg));
326     props->tie("controls/start-pos-long-deg",
327                SGRawValueMethods<SGGeod,double>(pos, &SGGeod::getLongitudeDeg));
328     props->tie("velocities/speed-kts",
329                 SGRawValuePointer<double>(&speed));
330     props->tie("environment/surface-wind-speed-true-kts",
331                 SGRawValuePointer<double>(&wind_speed_kts));
332     props->tie("environment/surface-wind-from-true-degs",
333                 SGRawValuePointer<double>(&wind_from_deg));
334     props->tie("environment/rel-wind-from-degs",
335                 SGRawValuePointer<double>(&rel_wind_from_deg));
336     props->tie("environment/rel-wind-from-carrier-hdg-degs",
337                 SGRawValuePointer<double>(&rel_wind));
338     props->tie("environment/rel-wind-speed-kts",
339                 SGRawValuePointer<double>(&rel_wind_speed_kts));
340     props->tie("controls/flols/wave-off-lights",
341                 SGRawValuePointer<bool>(&wave_off_lights));
342     props->tie("controls/elevators",
343                 SGRawValuePointer<bool>(&elevators));
344     props->tie("surface-positions/elevators-pos-norm",
345                 SGRawValuePointer<double>(&pos_norm));
346     props->tie("controls/elevators-trans-time-s",
347                 SGRawValuePointer<double>(&transition_time));
348     props->tie("controls/elevators-time-constant",
349                 SGRawValuePointer<double>(&time_constant));
350     props->tie("controls/jbd",
351         SGRawValuePointer<bool>(&jbd));
352     props->tie("surface-positions/jbd-pos-norm",
353         SGRawValuePointer<double>(&jbd_pos_norm));
354     props->tie("controls/jbd-trans-time-s",
355         SGRawValuePointer<double>(&jbd_transition_time));
356     props->tie("controls/jbd-time-constant",
357         SGRawValuePointer<double>(&jbd_time_constant));
358
359     props->setBoolValue("controls/flols/cut-lights", false);
360     props->setBoolValue("controls/flols/wave-off-lights", false);
361     props->setBoolValue("controls/flols/cond-datum-lights", true);
362     props->setBoolValue("controls/crew", false);
363     props->setStringValue("navaids/tacan/channel-ID", TACAN_channel_id.c_str());
364     props->setStringValue("sign", sign.c_str());
365 }
366
367
368 void FGAICarrier::unbind() {
369     FGAIShip::unbind();
370
371     props->untie("velocities/true-airspeed-kt");
372     props->untie("controls/flols/source-lights");
373     props->untie("controls/flols/distance-m");
374     props->untie("controls/flols/angle-degs");
375     props->untie("controls/turn-to-launch-hdg");
376     props->untie("velocities/speed-kts");
377     props->untie("environment/wind-speed-true-kts");
378     props->untie("environment/wind-from-true-degs");
379     props->untie("environment/rel-wind-from-degs");
380     props->untie("environment/rel-wind-speed-kts");
381     props->untie("controls/flols/wave-off-lights");
382     props->untie("controls/elevators");
383     props->untie("surface-positions/elevators-pos-norm");
384     props->untie("controls/elevators-trans-time-secs");
385     props->untie("controls/elevators-time-constant");
386     props->untie("controls/jbd");
387     props->untie("surface-positions/jbd-pos-norm");
388     props->untie("controls/jbd-trans-time-s");
389     props->untie("controls/jbd-time-constant");
390
391 }
392
393
394 bool FGAICarrier::getParkPosition(const string& id, SGGeod& geodPos,
395                                   double& hdng, SGVec3d& uvw)
396 {
397
398     // FIXME: does not yet cover rotation speeds.
399     list<ParkPosition>::iterator it = ppositions.begin();
400     while (it != ppositions.end()) {
401         // Take either the specified one or the first one ...
402         if ((*it).name == id || id.empty()) {
403             ParkPosition ppos = *it;
404             SGVec3d cartPos = getCartPosAt(ppos.offset);
405             geodPos = SGGeod::fromCart(cartPos);
406             hdng = hdg + ppos.heading_deg;
407             double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
408             double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
409             double speed_fps = speed*1.6878099;
410             uvw = SGVec3d(chdng*speed_fps, shdng*speed_fps, 0);
411             return true;
412         }
413         ++it;
414     }
415
416     return false;
417 }
418
419
420 void FGAICarrier::mark_nohot(ssgEntity* e) {
421     if (e->isAKindOf(ssgTypeBranch())) {
422         ssgBranch* br = (ssgBranch*)e;
423         ssgEntity* kid;
424         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
425             mark_nohot(kid);
426
427         br->clrTraversalMaskBits(SSGTRAV_HOT);
428
429     } else if (e->isAKindOf(ssgTypeLeaf())) {
430
431         e->clrTraversalMaskBits(SSGTRAV_HOT);
432     }
433 }
434
435
436 bool FGAICarrier::mark_wires(ssgEntity* e, const list<string>& wire_objects, bool mark) {
437     bool found = false;
438     if (e->isAKindOf(ssgTypeBranch())) {
439         ssgBranch* br = (ssgBranch*)e;
440         ssgEntity* kid;
441
442         list<string>::const_iterator it;
443         for (it = wire_objects.begin(); it != wire_objects.end(); ++it)
444             mark = mark || (e->getName() && (*it) == e->getName());
445
446         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
447             found = mark_wires(kid, wire_objects, mark) || found;
448
449         if (found)
450             br->setTraversalMaskBits(SSGTRAV_HOT);
451
452     } else if (e->isAKindOf(ssgTypeLeaf())) {
453         list<string>::const_iterator it;
454         for (it = wire_objects.begin(); it != wire_objects.end(); ++it) {
455             if (mark || (e->getName() && (*it) == e->getName())) {
456                 e->setTraversalMaskBits(SSGTRAV_HOT);
457                 ssgBase* ud = e->getUserData();
458                 if (ud) {
459                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
460                     if (ch) {
461                         SG_LOG(SG_GENERAL, SG_WARN,
462                                 "AICarrier: Carrier hardware gets marked twice!\n"
463                                 "           You have probably a whole branch marked as"
464                                 " a wire which also includes other carrier hardware.");
465                     } else {
466                         SG_LOG(SG_GENERAL, SG_ALERT,
467                                 "AICarrier: Found user data attached to a leaf node which "
468                                 "should be marked as a wire!\n    ****Skipping!****");
469                     }
470                 } else {
471                     e->setUserData( FGAICarrierHardware::newWire( this ) );
472                     ssgLeaf *l = (ssgLeaf*)e;
473                     if ( l->getNumLines() != 1 ) {
474                         SG_LOG(SG_GENERAL, SG_ALERT,
475                                 "AICarrier: Found wires not modeled with exactly one line!");
476                     }
477                     found = true;
478                 }
479             }
480         }
481     }
482     return found;
483 }
484
485
486 bool FGAICarrier::mark_solid(ssgEntity* e, const list<string>& solid_objects, bool mark) {
487     bool found = false;
488     if (e->isAKindOf(ssgTypeBranch())) {
489         ssgBranch* br = (ssgBranch*)e;
490         ssgEntity* kid;
491
492         list<string>::const_iterator it;
493         for (it = solid_objects.begin(); it != solid_objects.end(); ++it)
494             mark = mark || (e->getName() && (*it) == e->getName());
495
496         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
497             found = mark_solid(kid, solid_objects, mark) || found;
498
499         if (found)
500             br->setTraversalMaskBits(SSGTRAV_HOT);
501
502     } else if (e->isAKindOf(ssgTypeLeaf())) {
503         list<string>::const_iterator it;
504         for (it = solid_objects.begin(); it != solid_objects.end(); ++it) {
505             if (mark || (e->getName() && (*it) == e->getName())) {
506                 e->setTraversalMaskBits(SSGTRAV_HOT);
507                 ssgBase* ud = e->getUserData();
508
509                 if (ud) {
510                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
511                     if (ch) {
512                         SG_LOG(SG_GENERAL, SG_WARN,
513                                 "AICarrier: Carrier hardware gets marked twice!\n"
514                                 "           You have probably a whole branch marked solid"
515                                 " which also includes other carrier hardware.");
516                     } else {
517                         SG_LOG(SG_GENERAL, SG_ALERT,
518                                 "AICarrier: Found user data attached to a leaf node which "
519                                 "should be marked solid!\n    ****Skipping!****");
520                     }
521                 } else {
522                     e->setUserData( FGAICarrierHardware::newSolid( this ) );
523                     found = true;
524                 }
525             }
526         }
527     }
528     return found;
529 }
530
531
532 bool FGAICarrier::mark_cat(ssgEntity* e, const list<string>& cat_objects, bool mark) {
533     bool found = false;
534     if (e->isAKindOf(ssgTypeBranch())) {
535         ssgBranch* br = (ssgBranch*)e;
536         ssgEntity* kid;
537
538         list<string>::const_iterator it;
539         for (it = cat_objects.begin(); it != cat_objects.end(); ++it)
540             mark = mark || (e->getName() && (*it) == e->getName());
541
542         for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
543             found = mark_cat(kid, cat_objects, mark) || found;
544
545         if (found)
546             br->setTraversalMaskBits(SSGTRAV_HOT);
547
548     } else if (e->isAKindOf(ssgTypeLeaf())) {
549         list<string>::const_iterator it;
550         for (it = cat_objects.begin(); it != cat_objects.end(); ++it) {
551             if (mark || (e->getName() && (*it) == e->getName())) {
552                 e->setTraversalMaskBits(SSGTRAV_HOT);
553                 ssgBase* ud = e->getUserData();
554                 if (ud) {
555                     FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
556                     if (ch) {
557                         SG_LOG(SG_GENERAL, SG_WARN,
558                                 "AICarrier: Carrier hardware gets marked twice!\n"
559                                 "You have probably a whole branch marked as"
560                                 "a catapult which also includes other carrier hardware.");
561                     } else {
562                         SG_LOG(SG_GENERAL, SG_ALERT,
563                                 "AICarrier: Found user data attached to a leaf node which "
564                                 "should be marked as a catapult!\n    ****Skipping!****");
565                     }
566                 } else {
567                     e->setUserData( FGAICarrierHardware::newCatapult( this ) );
568                     ssgLeaf *l = (ssgLeaf*)e;
569                     if ( l->getNumLines() != 1 ) {
570                         SG_LOG(SG_GENERAL, SG_ALERT,
571                                 "AICarrier: Found a cat not modeled with exactly "
572                                 "one line!");
573                     } else {
574                         // Now some special code to make sure the cat points in the right
575                         // direction. The 0 index must be the backward end, the 1 index
576                         // the forward end.
577                         // Forward is positive x-direction in our 3D model, also the model
578                         // as such is flattened when it is loaded, so we do not need to
579                         // care for transforms ...
580                         short v[2];
581                         l->getLine(0, v, v+1 );
582                         SGVec3f ends[2];
583                         for (int k=0; k<2; ++k)
584                             sgCopyVec3( ends[k].sg(), l->getVertex( v[k] ) );
585
586                         // When the 1 end is behind the 0 end, swap the coordinates.
587                         if (ends[0][0] < ends[1][0]) {
588                             sgCopyVec3( l->getVertex( v[0] ), ends[1].sg() );
589                             sgCopyVec3( l->getVertex( v[1] ), ends[0].sg() );
590                         }
591                         found = true;
592                     }
593                 }
594             }
595         }
596     }
597     return found;
598 }
599
600 // find relative wind
601 void FGAICarrier::UpdateWind( double dt) {
602
603     double recip;
604
605     //calculate the reciprocal hdg
606
607     if (hdg >= 180)
608         recip = hdg - 180;
609     else
610         recip = hdg + 180;
611
612     //cout <<" heading: " << hdg << "recip: " << recip << endl;
613
614     //get the surface wind speed and direction
615     wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
616     wind_speed_kts  = _surface_wind_speed_node->getDoubleValue();
617
618     //calculate the surface wind speed north and east in kts
619     double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
620     double wind_speed_from_east_kts  = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
621
622     //calculate the carrier speed north and east in kts
623     double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
624     double speed_east_kts  = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
625
626     //calculate the relative wind speed north and east in kts
627     double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
628     double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
629
630     //combine relative speeds north and east to get relative windspeed in kts
631     rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts)
632     + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
633
634     //calculate the relative wind direction
635     rel_wind_from_deg = atan(rel_wind_speed_from_east_kts/rel_wind_speed_from_north_kts)
636                             * SG_RADIANS_TO_DEGREES;
637
638     // rationalise the output
639     if (rel_wind_speed_from_north_kts <= 0) {
640         rel_wind_from_deg = 180 + rel_wind_from_deg;
641     } else {
642         if(rel_wind_speed_from_east_kts <= 0)
643             rel_wind_from_deg = 360 + rel_wind_from_deg;
644     }
645
646     //calculate rel wind
647     rel_wind = rel_wind_from_deg - hdg;
648     if (rel_wind > 180)
649         rel_wind -= 360;
650
651     //switch the wave-off lights
652     if (InToWind())
653        wave_off_lights = false;
654     else
655        wave_off_lights = true;
656
657     // cout << "rel wind: " << rel_wind << endl;
658
659 }// end update wind
660
661
662 void FGAICarrier::TurnToLaunch(){
663
664     //calculate tgt speed
665     double tgt_speed = 25 - wind_speed_kts;
666     if (tgt_speed < 10)
667         tgt_speed = 10;
668
669     //turn the carrier
670     FGAIShip::TurnTo(wind_from_deg);
671     FGAIShip::AccelTo(tgt_speed);
672
673 }
674
675
676 void FGAICarrier::TurnToBase(){
677
678     //turn the carrier
679     FGAIShip::TurnTo(base_course);
680     FGAIShip::AccelTo(base_speed);
681
682 }
683
684
685 void FGAICarrier::ReturnToBox(){
686     double course, distance, az2;
687
688     //calculate the bearing and range of the initial position from the carrier
689     geo_inverse_wgs_84(pos, mOpBoxPos, &course, &az2, &distance);
690
691     distance *= SG_METER_TO_NM;
692
693     //cout << "return course: " << course << " distance: " << distance << endl;
694     //turn the carrier
695     FGAIShip::TurnTo(course);
696     FGAIShip::AccelTo(base_speed);
697
698     if (distance >= 1)
699         returning = true;
700     else
701         returning = false;
702
703 } //  end turn to base
704
705
706 bool FGAICarrier::OutsideBox() { //returns true if the carrier is outside operating box
707
708     if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
709         SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: No Operating Box defined" );
710         return false;
711     }
712
713     if (mOpBoxPos.getLatitudeDeg() >= 0) { //northern hemisphere
714         if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + max_lat)
715             return true;
716
717         if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - min_lat)
718             return true;
719
720     } else {                  //southern hemisphere
721         if (pos.getLatitudeDeg() <= mOpBoxPos.getLatitudeDeg() - max_lat)
722             return true;
723
724         if (pos.getLatitudeDeg() >= mOpBoxPos.getLatitudeDeg() + min_lat)
725             return true;
726     }
727
728     if (mOpBoxPos.getLongitudeDeg() >=0) { //eastern hemisphere
729         if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + max_long)
730             return true;
731
732         if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - min_long)
733             return true;
734
735     } else {                 //western hemisphere
736         if (pos.getLongitudeDeg() <= mOpBoxPos.getLongitudeDeg() - max_long)
737             return true;
738
739         if (pos.getLongitudeDeg() >= mOpBoxPos.getLongitudeDeg() + min_long)
740             return true;
741     }
742
743     SG_LOG(SG_GENERAL, SG_DEBUG, "AICarrier: Inside Operating Box" );
744     return false;
745
746 } // end OutsideBox
747
748
749 // return the distance to the horizon, given the altitude and the radius of the earth
750 float FGAICarrier::Horizon(float h) {
751     return RADIUS_M * acos(RADIUS_M / (RADIUS_M + h));
752 }
753
754
755 bool FGAICarrier::InToWind() {
756     if ( fabs(rel_wind) < 5 )
757         return true;
758
759     return false;
760 }
761
762
763 void FGAICarrier::UpdateElevator(double dt, double transition_time) {
764
765     double step = 0;
766
767     if ((elevators && pos_norm >= 1 ) || (!elevators && pos_norm <= 0 ))
768         return;
769
770     // move the elevators
771     if ( elevators ) {
772         step = dt/transition_time;
773         if ( step > 1 )
774             step = 1;
775     } else {
776         step = -dt/transition_time;
777         if ( step < -1 )
778             step = -1;
779     }
780     // assume a linear relationship
781     raw_pos_norm += step;
782
783     //low pass filter
784     pos_norm = (raw_pos_norm * time_constant) + (pos_norm * (1 - time_constant));
785
786     //sanitise the output
787     if (raw_pos_norm >= 1) {
788         raw_pos_norm = 1;
789     } else if (raw_pos_norm <= 0) {
790         raw_pos_norm = 0;
791     }
792     return;
793
794 } // end UpdateElevator
795
796 void FGAICarrier::UpdateJBD(double dt, double jbd_transition_time) {
797
798     string launchbar_state = _launchbar_state_node->getStringValue();
799     double step = 0;
800
801     if (launchbar_state == "Engaged"){
802         jbd = true;
803     } else {
804         jbd = false;
805     }
806
807     if (( jbd && jbd_pos_norm >= 1 ) || ( !jbd && jbd_pos_norm <= 0 )){
808         return;
809     }
810
811     // move the jbds
812     if ( jbd ) {
813         step = dt/jbd_transition_time;
814         if ( step > 1 )
815             step = 1;
816     } else {
817         step = -dt/jbd_transition_time;
818         if ( step < -1 )
819             step = -1;
820     }
821
822     // assume a linear relationship
823     raw_jbd_pos_norm += step;
824
825     //low pass filter
826     jbd_pos_norm = (raw_jbd_pos_norm * jbd_time_constant) + (jbd_pos_norm * (1 - jbd_time_constant));
827
828     //sanitise the output
829     if (jbd_pos_norm >= 1) {
830         jbd_pos_norm = 1;
831     } else if (jbd_pos_norm <= 0) {
832         jbd_pos_norm = 0;
833     }
834
835     return;
836
837 } // end UpdateJBD
838
839
840 int FGAICarrierHardware::unique_id = 1;
841