]> git.mxchange.org Git - flightgear.git/blob - src/AIModel/AICarrier.cxx
Mathias Fröhölöiööhlich:
[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., 675 Mass Ave, Cambridge, MA 02139, 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/point3d.hxx>
28 #include <simgear/math/sg_geodesy.hxx>
29 #include <math.h>
30 #include <Main/util.hxx>
31 #include <Main/viewer.hxx>
32
33 #include "AICarrier.hxx"
34
35 #include "AIScenario.hxx"
36
37 /** Value of earth radius (meters) */
38 #define RADIUS_M   SG_EQUATORIAL_RADIUS_M
39
40
41
42 FGAICarrier::FGAICarrier(FGAIManager* mgr) : FGAIShip(mgr) {
43   _type_str = "carrier";
44   _otype = otCarrier;
45   
46   
47 }
48
49 FGAICarrier::~FGAICarrier() {
50 }
51
52 void FGAICarrier::setWind_from_east(double fps) {
53    wind_from_east = fps;
54 }
55
56 void FGAICarrier::setWind_from_north(double fps) {
57    wind_from_north = fps;
58 }
59
60 void FGAICarrier::setMaxLat(double deg) {
61    max_lat = fabs(deg);
62 }
63
64 void FGAICarrier::setMinLat(double deg) {
65    min_lat = fabs(deg);
66 }
67
68 void FGAICarrier::setMaxLong(double deg) {
69    max_long = fabs(deg);
70 }
71
72 void FGAICarrier::setMinLong(double deg) {
73    min_long = fabs(deg);
74 }
75
76 void FGAICarrier::setSolidObjects(const list<string>& so) {
77   solid_objects = so;
78 }
79
80 void FGAICarrier::setWireObjects(const list<string>& wo) {
81   wire_objects = wo;
82 }
83
84 void FGAICarrier::setCatapultObjects(const list<string>& co) {
85   catapult_objects = co;
86 }
87
88 void FGAICarrier::setParkingPositions(const list<ParkPosition>& p) {
89   ppositions = p;
90 }
91
92 void FGAICarrier::setSign(const string& s) {
93   sign = s;
94 }
95
96 void FGAICarrier::setTACANChannelID(const string& id) {
97    TACAN_channel_id = id;
98 }
99
100 void FGAICarrier::setFlolsOffset(const Point3D& off) {
101   flols_off = off;
102 }
103
104 void FGAICarrier::getVelocityWrtEarth(sgdVec3 v, sgdVec3 omega, sgdVec3 pivot) {
105   sgdCopyVec3(v, vel_wrt_earth );
106   sgdCopyVec3(omega, rot_wrt_earth );
107   sgdCopyVec3(pivot, rot_pivot_wrt_earth );
108 }
109
110 void FGAICarrier::update(double dt) {
111    
112    // For computation of rotation speeds we just use finite differences her.
113    // That is perfectly valid since this thing is not driven by accelerations
114    // but by just apply discrete changes at its velocity variables.
115    double old_hdg = hdg;
116    double old_roll = roll;
117    double old_pitch = pitch;
118
119    // Update the velocity information stored in those nodes.
120    double v_north = 0.51444444*speed*cos(hdg * SGD_DEGREES_TO_RADIANS);
121    double v_east  = 0.51444444*speed*sin(hdg * SGD_DEGREES_TO_RADIANS);
122
123    double sin_lat = sin(pos.lat() * SGD_DEGREES_TO_RADIANS);
124    double cos_lat = cos(pos.lat() * SGD_DEGREES_TO_RADIANS);
125    double sin_lon = sin(pos.lon() * SGD_DEGREES_TO_RADIANS);
126    double cos_lon = cos(pos.lon() * SGD_DEGREES_TO_RADIANS);
127    double sin_roll = sin(roll * SGD_DEGREES_TO_RADIANS);
128    double cos_roll = cos(roll * SGD_DEGREES_TO_RADIANS);
129    double sin_pitch = sin(pitch * SGD_DEGREES_TO_RADIANS);
130    double cos_pitch = cos(pitch * SGD_DEGREES_TO_RADIANS);
131    double sin_hdg = sin(hdg * SGD_DEGREES_TO_RADIANS);
132    double cos_hdg = cos(hdg * SGD_DEGREES_TO_RADIANS);
133
134    // Transform this back the the horizontal local frame.
135    sgdMat3 trans;
136    
137    // set up the transform matrix
138    trans[0][0] =          cos_pitch*cos_hdg;
139    trans[0][1] = sin_roll*sin_pitch*cos_hdg - cos_roll*sin_hdg;
140    trans[0][2] = cos_roll*sin_pitch*cos_hdg + sin_roll*sin_hdg;
141    
142    trans[1][0] =          cos_pitch*sin_hdg;
143    trans[1][1] = sin_roll*sin_pitch*sin_hdg + cos_roll*cos_hdg;
144    trans[1][2] = cos_roll*sin_pitch*sin_hdg - sin_roll*cos_hdg;
145    
146    trans[2][0] =         -sin_pitch;
147    trans[2][1] = sin_roll*cos_pitch;
148    trans[2][2] = cos_roll*cos_pitch;
149    
150    sgdSetVec3( vel_wrt_earth,
151               - cos_lon*sin_lat*v_north - sin_lon*v_east,
152               - sin_lon*sin_lat*v_north + cos_lon*v_east,
153                 cos_lat*v_north );
154    sgGeodToCart(pos.lat() * SGD_DEGREES_TO_RADIANS,
155                 pos.lon() * SGD_DEGREES_TO_RADIANS,
156                 pos.elev(), rot_pivot_wrt_earth);
157
158    // Now update the position and heading. This will compute new hdg and
159    // roll values required for the rotation speed computation.
160    FGAIShip::update(dt);
161    
162    
163    //automatic turn into wind with a target wind of 25 kts otd
164    if(turn_to_launch_hdg){
165        TurnToLaunch();
166    } else if(OutsideBox() || returning) {// check that the carrier is inside the operating box
167        ReturnToBox();
168    } else {                   //if(!returning
169        TurnToBase();
170    }  //end if  
171
172    // Only change these values if we are able to compute them safely
173    if (dt < DBL_MIN)
174      sgdSetVec3( rot_wrt_earth, 0.0, 0.0, 0.0);
175    else {
176      // Compute the change of the euler angles.
177      double hdg_dot = SGD_DEGREES_TO_RADIANS * (hdg-old_hdg)/dt;
178      // Allways assume that the movement was done by the shorter way.
179      if (hdg_dot < - SGD_DEGREES_TO_RADIANS * 180)
180        hdg_dot += SGD_DEGREES_TO_RADIANS * 360;
181      if (hdg_dot > SGD_DEGREES_TO_RADIANS * 180)
182        hdg_dot -= SGD_DEGREES_TO_RADIANS * 360;
183      double pitch_dot = SGD_DEGREES_TO_RADIANS * (pitch-old_pitch)/dt;
184      // Allways assume that the movement was done by the shorter way.
185      if (pitch_dot < - SGD_DEGREES_TO_RADIANS * 180)
186        pitch_dot += SGD_DEGREES_TO_RADIANS * 360;
187      if (pitch_dot > SGD_DEGREES_TO_RADIANS * 180)
188        pitch_dot -= SGD_DEGREES_TO_RADIANS * 360;
189      double roll_dot = SGD_DEGREES_TO_RADIANS * (roll-old_roll)/dt;
190      // Allways assume that the movement was done by the shorter way.
191      if (roll_dot < - SGD_DEGREES_TO_RADIANS * 180)
192        roll_dot += SGD_DEGREES_TO_RADIANS * 360;
193      if (roll_dot > SGD_DEGREES_TO_RADIANS * 180)
194        roll_dot -= SGD_DEGREES_TO_RADIANS * 360;
195      /*cout << "euler derivatives = "
196           << roll_dot << " " << pitch_dot << " " << hdg_dot << endl;*/
197
198      // Now Compute the rotation vector in the carriers coordinate frame
199      // originating from the euler angle changes.
200      sgdVec3 body;
201      body[0] = roll_dot - hdg_dot*sin_pitch;
202      body[1] = pitch_dot*cos_roll + hdg_dot*sin_roll*cos_pitch;
203      body[2] = -pitch_dot*sin_roll + hdg_dot*cos_roll*cos_pitch;
204
205      // Transform that back to the horizontal local frame.
206      sgdVec3 hl;
207      hl[0] = body[0]*trans[0][0] + body[1]*trans[0][1] + body[2]*trans[0][2];
208      hl[1] = body[0]*trans[1][0] + body[1]*trans[1][1] + body[2]*trans[1][2];
209      hl[2] = body[0]*trans[2][0] + body[1]*trans[2][1] + body[2]*trans[2][2];
210
211      // Now we need to project out rotation components ending in speeds in y
212      // direction in the hoirizontal local frame.
213      hl[1] = 0;
214
215      // Transform that to the earth centered frame.
216      sgdSetVec3(rot_wrt_earth,
217                - cos_lon*sin_lat*hl[0] - sin_lon*hl[1] - cos_lat*cos_lon*hl[2],
218                - sin_lon*sin_lat*hl[0] + cos_lon*hl[1] - cos_lat*sin_lon*hl[2],
219                  cos_lat*hl[0] - sin_lat*hl[2]);
220    }
221
222    UpdateWind(dt);
223    UpdateTACAN(dt);
224    UpdateFlols(trans);
225 } //end update
226
227 bool FGAICarrier::init() {
228    if (!FGAIShip::init())
229       return false;
230
231    // process the 3d model here
232    // mark some objects solid, mark the wires ...
233
234    // The model should be used for altitude computations.
235    // To avoid that every detail in a carrier 3D model will end into
236    // the aircraft local cache, only set the HOT traversal bit on
237    // selected objects.
238    ssgEntity *sel = aip.getSceneGraph();
239    // Clear the HOT traversal flag
240    mark_nohot(sel);
241    // Selectively set that flag again for wires/cats/solid objects.
242    // Attach a pointer to this carrier class to those objects.
243    mark_wires(sel, wire_objects);
244    mark_cat(sel, catapult_objects);
245    mark_solid(sel, solid_objects);
246
247    _longitude_node = fgGetNode("/position/longitude-deg", true);
248    _latitude_node = fgGetNode("/position/latitude-deg", true);
249    _altitude_node = fgGetNode("/position/altitude-ft", true);
250    _dme_freq_node = fgGetNode("/instrumentation/dme/frequencies/selected-mhz", true);
251    _surface_wind_from_deg_node = 
252               fgGetNode("/environment/config/boundary/entry[0]/wind-from-heading-deg", true);
253    _surface_wind_speed_node = 
254               fgGetNode("/environment/config/boundary/entry[0]/wind-speed-kt", true);
255    
256   
257    turn_to_launch_hdg = false;
258    returning = false;
259   
260    initialpos = pos;
261    base_course = hdg;
262    base_speed = speed;
263    
264    return true;
265 }
266
267 void FGAICarrier::bind() {
268    FGAIShip::bind();
269
270    props->untie("velocities/true-airspeed-kt");
271    
272    props->tie("controls/flols/source-lights",
273                 SGRawValuePointer<int>(&source));
274    props->tie("controls/flols/distance-m",
275                 SGRawValuePointer<double>(&dist));
276    props->tie("controls/flols/angle-degs",
277                 SGRawValuePointer<double>(&angle));
278    props->tie("controls/turn-to-launch-hdg",
279                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
280    props->tie("controls/in-to-wind",
281                 SGRawValuePointer<bool>(&turn_to_launch_hdg));
282    props->tie("controls/base-course-deg",
283                 SGRawValuePointer<double>(&base_course));
284    props->tie("controls/base-speed-kts",
285                 SGRawValuePointer<double>(&base_speed));
286    props->tie("controls/start-pos-lat-deg",
287                 SGRawValuePointer<double>(&initialpos[1]));
288    props->tie("controls/start-pos-long-deg",
289                 SGRawValuePointer<double>(&initialpos[0]));
290    props->tie("velocities/speed-kts",  
291                 SGRawValuePointer<double>(&speed));
292    props->tie("environment/surface-wind-speed-true-kts",  
293                 SGRawValuePointer<double>(&wind_speed_kts));
294    props->tie("environment/surface-wind-from-true-degs",  
295                 SGRawValuePointer<double>(&wind_from_deg));
296    props->tie("environment/rel-wind-from-degs",  
297                 SGRawValuePointer<double>(&rel_wind_from_deg));
298    props->tie("environment/rel-wind-from-carrier-hdg-degs",  
299                 SGRawValuePointer<double>(&rel_wind));
300    props->tie("environment/rel-wind-speed-kts",  
301                 SGRawValuePointer<double>(&rel_wind_speed_kts));
302    props->tie("controls/flols/wave-off-lights",  
303                 SGRawValuePointer<bool>(&wave_off_lights));
304    props->tie("instrumentation/TACAN/bearing-true-deg",  
305                 SGRawValuePointer<double>(&bearing));
306    props->tie("instrumentation/TACAN/range-nm",  
307                 SGRawValuePointer<double>(&range));
308                     
309    props->setBoolValue("controls/flols/cut-lights", false);
310    props->setBoolValue("controls/flols/wave-off-lights", false);
311    props->setBoolValue("controls/flols/cond-datum-lights", true);
312    props->setBoolValue("controls/crew", false);
313
314    props->setStringValue("instrumentation/TACAN/channel-ID", TACAN_channel_id.c_str());
315   
316    props->setStringValue("sign", sign.c_str());
317 }
318
319 void FGAICarrier::unbind() {
320     FGAIShip::unbind();
321     
322     props->untie("velocities/true-airspeed-kt");
323     
324     props->untie("controls/flols/source-lights");
325     props->untie("controls/flols/distance-m");
326     props->untie("controls/flols/angle-degs");
327     props->untie("controls/turn-to-launch-hdg");
328     props->untie("velocities/speed-kts");
329     props->untie("environment/wind-speed-true-kts");
330     props->untie("environment/wind-from-true-degs");
331     props->untie("environment/rel-wind-from-degs");
332     props->untie("environment/rel-wind-speed-kts");
333     props->untie("controls/flols/wave-off-lights");
334     props->untie("instrumentation/TACAN/bearing-true-deg");
335     props->untie("instrumentation/TACAN/range-nm");
336     props->untie("instrumentation/TACAN/channel-ID");
337 }
338
339 bool FGAICarrier::getParkPosition(const string& id, Point3D& geodPos,
340                                   double& hdng, sgdVec3 uvw)
341 {
342
343   // FIXME: does not yet cover rotation speeds.
344   list<ParkPosition>::iterator it = ppositions.begin();
345   while (it != ppositions.end()) {
346     // Take either the specified one or the first one ...
347     if ((*it).name == id || id.empty()) {
348       ParkPosition ppos = *it;
349       geodPos = getGeocPosAt(ppos.offset);
350       hdng = hdg + ppos.heading_deg;
351       double shdng = sin(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
352       double chdng = cos(ppos.heading_deg * SGD_DEGREES_TO_RADIANS);
353       double speed_fps = speed*1.6878099;
354       sgdSetVec3(uvw, chdng*speed_fps, shdng*speed_fps, 0);
355       return true;
356     }
357     ++it;
358   }
359
360   return false;
361 }
362
363 void FGAICarrier::mark_nohot(ssgEntity* e) {
364   if (e->isAKindOf(ssgTypeBranch())) {
365     ssgBranch* br = (ssgBranch*)e;
366     ssgEntity* kid;
367     for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
368       mark_nohot(kid);
369
370     br->clrTraversalMaskBits(SSGTRAV_HOT);
371     
372   } else if (e->isAKindOf(ssgTypeLeaf())) {
373
374     e->clrTraversalMaskBits(SSGTRAV_HOT);
375
376   }
377 }
378
379 bool FGAICarrier::mark_wires(ssgEntity* e, const list<string>& wire_objects, bool mark) {
380   bool found = false;
381   if (e->isAKindOf(ssgTypeBranch())) {
382     ssgBranch* br = (ssgBranch*)e;
383     ssgEntity* kid;
384
385     list<string>::const_iterator it;
386     for (it = wire_objects.begin(); it != wire_objects.end(); ++it)
387       mark = mark || (e->getName() && (*it) == e->getName());
388
389     for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
390       found = mark_wires(kid, wire_objects, mark) || found;
391
392     if (found)
393       br->setTraversalMaskBits(SSGTRAV_HOT);
394     
395   } else if (e->isAKindOf(ssgTypeLeaf())) {
396     list<string>::const_iterator it;
397     for (it = wire_objects.begin(); it != wire_objects.end(); ++it) {
398       if (mark || (e->getName() && (*it) == e->getName())) {
399         e->setTraversalMaskBits(SSGTRAV_HOT);
400         ssgBase* ud = e->getUserData();
401         if (ud) {
402           FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
403           if (ch) {
404             SG_LOG(SG_GENERAL, SG_WARN,
405                    "AICarrier: Carrier hardware gets marked twice!\n"
406                    "           You have propably a whole branch marked as"
407                    " a wire which also includes other carrier hardware."
408                    );
409           } else {
410             SG_LOG(SG_GENERAL, SG_ALERT,
411                    "AICarrier: Found user data attached to a leaf node which "
412                    "should be marked as a wire!\n    ****Skipping!****");
413           }
414         } else {
415           e->setUserData( FGAICarrierHardware::newWire( this ) );
416           ssgLeaf *l = (ssgLeaf*)e;
417           if ( l->getNumLines() != 1 ) {
418             SG_LOG(SG_GENERAL, SG_ALERT,
419                    "AICarrier: Found wires not modelled with exactly one line!");
420           }
421           found = true;
422         }
423       }
424     }
425   }
426   return found;
427 }
428
429 bool FGAICarrier::mark_solid(ssgEntity* e, const list<string>& solid_objects, bool mark) {
430   bool found = false;
431   if (e->isAKindOf(ssgTypeBranch())) {
432     ssgBranch* br = (ssgBranch*)e;
433     ssgEntity* kid;
434
435     list<string>::const_iterator it;
436     for (it = solid_objects.begin(); it != solid_objects.end(); ++it)
437       mark = mark || (e->getName() && (*it) == e->getName());
438
439     for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
440       found = mark_solid(kid, solid_objects, mark) || found;
441
442     if (found)
443       br->setTraversalMaskBits(SSGTRAV_HOT);
444     
445   } else if (e->isAKindOf(ssgTypeLeaf())) {
446     list<string>::const_iterator it;
447     for (it = solid_objects.begin(); it != solid_objects.end(); ++it) {
448       if (mark || (e->getName() && (*it) == e->getName())) {
449         e->setTraversalMaskBits(SSGTRAV_HOT);
450         ssgBase* ud = e->getUserData();
451         if (ud) {
452           FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
453           if (ch) {
454             SG_LOG(SG_GENERAL, SG_WARN,
455                    "AICarrier: Carrier hardware gets marked twice!\n"
456                    "           You have propably a whole branch marked solid"
457                    " which also includes other carrier hardware."
458                    );
459           } else {
460             SG_LOG(SG_GENERAL, SG_ALERT,
461                    "AICarrier: Found user data attached to a leaf node which "
462                    "should be marked solid!\n    ****Skipping!****");
463           }
464         } else {
465           e->setUserData( FGAICarrierHardware::newSolid( this ) );
466           found = true;
467         }
468       }
469     }
470   }
471   return found;
472 }
473
474 bool FGAICarrier::mark_cat(ssgEntity* e, const list<string>& cat_objects, bool mark) {
475   bool found = false;
476   if (e->isAKindOf(ssgTypeBranch())) {
477     ssgBranch* br = (ssgBranch*)e;
478     ssgEntity* kid;
479
480     list<string>::const_iterator it;
481     for (it = cat_objects.begin(); it != cat_objects.end(); ++it)
482       mark = mark || (e->getName() && (*it) == e->getName());
483
484     for ( kid = br->getKid(0); kid != NULL ; kid = br->getNextKid() )
485       found = mark_cat(kid, cat_objects, mark) || found;
486
487     if (found)
488       br->setTraversalMaskBits(SSGTRAV_HOT);
489     
490   } else if (e->isAKindOf(ssgTypeLeaf())) {
491     list<string>::const_iterator it;
492     for (it = cat_objects.begin(); it != cat_objects.end(); ++it) {
493       if (mark || (e->getName() && (*it) == e->getName())) {
494         e->setTraversalMaskBits(SSGTRAV_HOT);
495         ssgBase* ud = e->getUserData();
496         if (ud) {
497           FGAICarrierHardware* ch = dynamic_cast<FGAICarrierHardware*>(ud);
498           if (ch) {
499             SG_LOG(SG_GENERAL, SG_WARN,
500                    "AICarrier: Carrier hardware gets marked twice!\n"
501                    "You have probably a whole branch marked as"
502                    "a catapult which also includes other carrier hardware."
503                     );
504           } else {
505             SG_LOG(SG_GENERAL, SG_ALERT,
506                    "AICarrier: Found user data attached to a leaf node which "
507                    "should be marked as a catapult!\n    ****Skipping!****");
508           }
509         } else {
510           e->setUserData( FGAICarrierHardware::newCatapult( this ) );
511           ssgLeaf *l = (ssgLeaf*)e;
512           if ( l->getNumLines() != 1 ) {
513             SG_LOG(SG_GENERAL, SG_ALERT,
514                    "AICarrier: Found a cat not modelled with exactly "
515                    "one line!");
516           } else {
517             // Now some special code to make sure the cat points in the right
518             // direction. The 0 index must be the backward end, the 1 index
519             // the forward end.
520             // Forward is positive x-direction in our 3D model, also the model
521             // as such is flattened when it is loaded, so we do not need to
522             // care for transforms ...
523             short v[2];
524             l->getLine(0, v, v+1 );
525             sgVec3 ends[2];
526             for (int k=0; k<2; ++k)
527               sgCopyVec3( ends[k], l->getVertex( v[k] ) );
528             
529             // When the 1 end is behind the 0 end, swap the coordinates.
530             if (ends[0][0] < ends[1][0]) {
531               sgCopyVec3( l->getVertex( v[0] ), ends[1] );
532               sgCopyVec3( l->getVertex( v[1] ), ends[0] );
533             }
534
535             found = true;
536           }
537         }
538       }
539     }
540   }
541   return found;
542 }
543
544 void FGAICarrier::UpdateFlols(sgdMat3 trans) {
545     
546     float in[3];
547     float out[3];
548
549     double flolsXYZ[3], eyeXYZ[3]; 
550     double lat, lon, alt;
551     Point3D eyepos;
552     Point3D flolspos;   
553
554 /*    cout << "x_offset " << flols_x_offset 
555           << " y_offset " << flols_y_offset 
556           << " z_offset " << flols_z_offset << endl;
557         
558      cout << "roll " << roll 
559           << " heading " << hdg
560           << " pitch " << pitch << endl;
561         
562      cout << "carrier lon " << pos[0] 
563           << " lat " <<  pos[1]
564           << " alt " << pos[2] << endl;*/
565         
566 // set the Flols intitial position to the carrier position
567  
568   flolspos = pos;
569   
570 /*  cout << "flols lon " << flolspos[0] 
571           << " lat " <<  flolspos[1]
572           << " alt " << flolspos[2] << endl;*/
573           
574 // set the offsets in metres
575
576 /*  cout << "flols_x_offset " << flols_x_offset << endl
577        << "flols_y_offset " << flols_y_offset << endl
578        << "flols_z_offset " << flols_z_offset << endl;*/
579      
580   in[0] = flols_off.x();  
581   in[1] = flols_off.y();
582   in[2] = flols_off.z();    
583
584 // multiply the input and transform matrices
585
586    out[0] = in[0] * trans[0][0] + in[1] * trans[0][1] + in[2] * trans[0][2];
587    out[1] = in[0] * trans[1][0] + in[1] * trans[1][1] + in[2] * trans[1][2];
588    out[2] = in[0] * trans[2][0] + in[1] * trans[2][1] + in[2] * trans[2][2];
589  
590 // convert meters to ft to degrees of latitude
591    out[0] = (out[0] * 3.28083989501) /(366468.96 - 3717.12 * cos(flolspos[0] * SG_DEGREES_TO_RADIANS));
592
593 // convert meters to ft to degrees of longitude
594    out[1] = (out[1] * 3.28083989501)/(365228.16 * cos(flolspos[1] * SG_DEGREES_TO_RADIANS));
595
596 //print out the result
597 /*   cout  << "lat adjust deg" << out[0] 
598         << " lon adjust deg " << out[1] 
599         << " alt adjust m " << out[2]  << endl;*/
600
601 // adjust Flols position    
602    flolspos[0] += out[0];
603    flolspos[1] += out[1];
604    flolspos[2] += out[2];   
605
606 // convert flols position to cartesian co-ordinates 
607
608   sgGeodToCart(flolspos[1] * SG_DEGREES_TO_RADIANS,
609                flolspos[0] * SG_DEGREES_TO_RADIANS,
610                flolspos[2] , flolsXYZ );
611
612
613 /*  cout << "flols X " << flolsXYZ[0] 
614        << " Y " <<  flolsXYZ[1]
615        << " Z " << flolsXYZ[2] << endl; 
616
617 // check the conversion
618          
619   sgCartToGeod(flolsXYZ, &lat, &lon, &alt);
620  
621   cout << "flols check lon " << lon   
622         << " lat " << lat 
623         << " alt " << alt << endl;      */
624                
625 //get the current position of the pilot's eyepoint (cartesian cordinates)
626
627   sgdCopyVec3( eyeXYZ, globals->get_current_view()->get_absolute_view_pos() );
628   
629  /* cout  << "Eye_X "  << eyeXYZ[0] 
630         << " Eye_Y " << eyeXYZ[1] 
631         << " Eye_Z " << eyeXYZ[2]  << endl; */
632         
633   sgCartToGeod(eyeXYZ, &lat, &lon, &alt);
634   
635   eyepos[0] = lon * SG_RADIANS_TO_DEGREES;
636   eyepos[1] = lat * SG_RADIANS_TO_DEGREES;
637   eyepos[2] = alt;
638   
639 /*  cout << "eye lon " << eyepos[0]
640         << " eye lat " << eyepos[1] 
641         << " eye alt " << eyepos[2] << endl; */
642
643 //calculate the ditance from eye to flols
644       
645   dist = sgdDistanceVec3( flolsXYZ, eyeXYZ );
646
647 //apply an index error
648
649   dist -= 100;
650   
651   //cout << "distance " << dist << endl; 
652   
653   if ( dist < 5000 ) {
654        // calculate height above FLOLS 
655        double y = eyepos[2] - flolspos[2];
656        
657        // calculate the angle from the flols to eye
658        // above the horizontal
659        // double angle;
660        
661        if ( dist != 0 ) {
662            angle = asin( y / dist );
663          } else {
664            angle = 0.0;
665          }
666         
667        angle *= SG_RADIANS_TO_DEGREES;
668         
669       
670   // cout << " height " << y << " angle " << angle ;
671
672 // set the value of source  
673         
674        if ( angle <= 4.35 && angle > 4.01 )
675          { source = 1; }
676          else if ( angle <= 4.01 && angle > 3.670 )
677          { source = 2; }
678          else if ( angle <= 3.670 && angle > 3.330 )
679          { source = 3; }
680          else if ( angle <= 3.330 && angle > 2.990 )
681          { source = 4; }
682          else if ( angle <= 2.990 && angle > 2.650 )
683          { source = 5; }
684          else if ( angle <= 2.650  )
685          { source = 6; }
686          else
687          { source = 0; }
688          
689 //         cout << " source " << source << endl;
690                      
691    }   
692 } // end updateflols
693
694 // find relative wind
695
696
697
698
699 void FGAICarrier::UpdateWind( double dt) {
700
701     double recip;
702     
703     //calculate the reciprocal hdg
704     
705     if (hdg >= 180){
706         recip = hdg - 180;
707     }
708     else{
709         recip = hdg + 180;
710     }
711     
712     //cout <<" heading: " << hdg << "recip: " << recip << endl;
713     
714     //get the surface wind speed and direction
715     wind_from_deg = _surface_wind_from_deg_node->getDoubleValue();
716     wind_speed_kts  = _surface_wind_speed_node->getDoubleValue();
717     
718     //calculate the surface wind speed north and east in kts   
719     double wind_speed_from_north_kts = cos( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
720     double wind_speed_from_east_kts  = sin( wind_from_deg / SGD_RADIANS_TO_DEGREES )* wind_speed_kts ;
721     
722     //calculate the carrier speed north and east in kts   
723     double speed_north_kts = cos( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
724     double speed_east_kts  = sin( hdg / SGD_RADIANS_TO_DEGREES )* speed ;
725     
726     //calculate the relative wind speed north and east in kts
727     double rel_wind_speed_from_east_kts = wind_speed_from_east_kts + speed_east_kts;
728     double rel_wind_speed_from_north_kts = wind_speed_from_north_kts + speed_north_kts;
729     
730     //combine relative speeds north and east to get relative windspeed in kts                          
731     rel_wind_speed_kts = sqrt((rel_wind_speed_from_east_kts * rel_wind_speed_from_east_kts) 
732     + (rel_wind_speed_from_north_kts * rel_wind_speed_from_north_kts));
733     
734     //calculate the relative wind direction
735     rel_wind_from_deg = atan(rel_wind_speed_from_east_kts/rel_wind_speed_from_north_kts) 
736                             * SG_RADIANS_TO_DEGREES;
737     
738     // rationalise the output
739     if (rel_wind_speed_from_north_kts <= 0){
740         rel_wind_from_deg = 180 + rel_wind_from_deg;
741     }
742     else{
743         if(rel_wind_speed_from_east_kts <= 0){
744             rel_wind_from_deg = 360 + rel_wind_from_deg;
745         }    
746     }
747     
748     //calculate rel wind
749     rel_wind = rel_wind_from_deg - hdg  ;
750     if (rel_wind > 180) rel_wind -= 360;
751     
752     //switch the wave-off lights
753     if (InToWind()){
754        wave_off_lights = false;
755     }else{
756        wave_off_lights = true;
757     }    
758        
759     cout << "rel wind: " << rel_wind << endl;
760
761 }// end update wind
762
763 void FGAICarrier::TurnToLaunch(){
764     
765      //calculate tgt speed
766        double tgt_speed = 25 - wind_speed_kts;
767        if (tgt_speed < 10) tgt_speed = 10;
768        
769      //turn the carrier
770        FGAIShip::TurnTo(wind_from_deg); 
771        FGAIShip::AccelTo(tgt_speed); 
772            
773      
774         
775 }  // end turn to launch
776    
777 void FGAICarrier::TurnToBase(){
778     
779     //turn the carrier
780        FGAIShip::TurnTo(base_course); 
781        FGAIShip::AccelTo(base_speed); 
782     
783 } //  end turn to base  
784
785 void FGAICarrier::ReturnToBox(){
786     double course, distance;
787         
788     //get the carrier position
789     carrierpos = pos;
790     
791     //cout << "lat: " << carrierpos[1] << " lon: " << carrierpos[0] << endl;
792     
793     //calculate the bearing and range of the initial position from the carrier
794     geo_inverse_wgs_84(carrierpos[2],
795                        carrierpos[1],
796                        carrierpos[0],
797                        initialpos[1],
798                        initialpos[0],
799                        &course, &az2, &distance);
800                      
801     distance *= SG_METER_TO_NM;
802
803     cout << "return course: " << course << " distance: " << distance << endl;
804     //turn the carrier
805        FGAIShip::TurnTo(course); 
806        FGAIShip::AccelTo(base_speed);
807        if (distance >= 1 ){
808            returning = true;
809        }else{
810            returning = false;
811        }        
812     
813 } //  end turn to base  
814  
815     
816 void FGAICarrier::UpdateTACAN(double dt){ //update the TACAN 
817
818   //cout << "TACAN: " << TACAN_channel_id << endl;
819
820   double max_range_nm = 100; //nm
821   
822   double dme_freq = _dme_freq_node->getDoubleValue();
823   
824   //cout << "dme_freq: " << dme_freq << endl; 
825   
826   if (TACAN_channel_id == "017X"){
827   
828       //get the aircraft position  
829       double longitude_deg = _longitude_node->getDoubleValue();
830       double latitude_deg  = _latitude_node->getDoubleValue();
831       double altitude_m    = _altitude_node->getDoubleValue() * SG_FEET_TO_METER;
832     
833       //get the carrier position
834       carrierpos = pos;
835       
836       //cout << "lat: " << carrierpos[1] << " lon: " << carrierpos[0] << endl;
837       
838       //calculate the bearing and range of the carrier from the aircraft
839       geo_inverse_wgs_84(altitude_m,
840                          latitude_deg,
841                          longitude_deg,
842                          carrierpos[1],
843                          carrierpos[0],
844                          &bearing, &az2, &range);
845                          
846       range *= SG_METER_TO_NM;
847       
848       
849       
850        double aircraft_horizon_nm = Horizon(altitude_m) * SG_METER_TO_NM;
851        double carrier_horizon_nm = Horizon(50) * SG_METER_TO_NM;
852        double horizon_nm = aircraft_horizon_nm + carrier_horizon_nm;
853                          
854        if (range > horizon_nm || range > max_range_nm) {
855            range = 0;
856            bearing = 0 ;
857         }    
858     /*cout << "bearing: " << bearing << " range: " << range << " altitude: " << altitude_m
859       <<  " horizon: " << horizon_nm << endl; */
860   } else {
861       range = 0;
862       bearing = 0 ;
863   }  // end if
864         
865 }// end update TACAN
866
867 bool FGAICarrier::OutsideBox(){ //returns true if the carrier is outside operating box
868
869     if ( max_lat == 0 && min_lat == 0 && max_long == 0 && min_long == 0) {
870        SG_LOG(SG_GENERAL, SG_INFO,"AICarrier: No Operating Box defined" );
871        return false;
872     }        
873      
874     if (initialpos[1] >= 0){//northern hemisphere
875         if (pos[1] >= initialpos[1] + max_lat) {return true;}
876         else if (pos[1] <= initialpos[1] - min_lat) {return true;}
877     }else{                  //southern hemisphere
878         if (pos[1] <= initialpos[1] - max_lat) {return true;}
879         else if (pos[1] >= initialpos[1] + min_lat) {return true;}
880     }
881     
882     if (initialpos[0] >=0) {//eastern hemisphere
883         if (pos[0] >= initialpos[0] + max_long) {return true;}
884         else if (pos[0] <= initialpos[0] - min_long) {return true;}
885     }else{                 //western hemisphere
886         if (pos[0] <= initialpos[0] - max_long) {return true;}
887         else if (pos[0] >= initialpos[0] + min_long) {return true;}
888     }
889     
890     SG_LOG(SG_GENERAL, SG_INFO,"AICarrier: Inside Operating Box" );
891    
892     return false;   
893
894 } // end OutsideBox
895
896 // return the distance to the horizon, given the altitude and the radius of the earth
897 float FGAICarrier::Horizon(float h) { return RADIUS_M * acos(RADIUS_M / (RADIUS_M + h)); }
898     
899 bool FGAICarrier::InToWind(){
900     
901     // test
902     if ( fabs(rel_wind) < 5 ) return true;
903     return false;
904     
905 } //end InToWind     
906 int FGAICarrierHardware::unique_id = 1;