]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Merge branch 'next' into comm-subsystem
[flightgear.git] / src / ATC / trafficcontrol.cxx
1 // trafficrecord.cxx - Implementation of AIModels ATC code.
2 //
3 // Written by Durk Talsma, started September 2006.
4 //
5 // Copyright (C) 2006 Durk Talsma.
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include <config.h>
25 #endif
26
27 #include <algorithm>
28
29 #include <osg/Geode>
30 #include <osg/Geometry>
31 #include <osg/MatrixTransform>
32 #include <osg/Shape>
33
34 #include <simgear/scene/material/EffectGeode.hxx>
35 #include <simgear/scene/material/matlib.hxx>
36 #include <simgear/scene/material/mat.hxx>
37 #include <Scenery/scenery.hxx>
38
39 #include "trafficcontrol.hxx"
40 #include "atc_mgr.hxx"
41 #include <AIModel/AIAircraft.hxx>
42 #include <AIModel/AIFlightPlan.hxx>
43 #include <AIModel/performancedata.hxx>
44 #include <AIModel/performancedb.hxx>
45 #include <ATC/atc_mgr.hxx>
46 #include <Traffic/TrafficMgr.hxx>
47 #include <Airports/groundnetwork.hxx>
48 #include <Airports/dynamics.hxx>
49 #include <Airports/simple.hxx>
50
51 using std::sort;
52
53 /***************************************************************************
54  * ActiveRunway
55  **************************************************************************/
56 time_t ActiveRunway::requestTimeSlot(time_t eta)
57 {
58     time_t newEta;
59     time_t separation = 90;
60     bool found = false;
61     if (estimatedArrivalTimes.size() == 0) {
62         estimatedArrivalTimes.push_back(eta);
63         return eta;
64     } else {
65         TimeVectorIterator i = estimatedArrivalTimes.begin();
66         //cerr << "Checking eta slots " << eta << ": " << endl;
67         for (i = estimatedArrivalTimes.begin();
68                 i != estimatedArrivalTimes.end(); i++) {
69             //cerr << "Stored time : " << (*i) << endl;
70         }
71         i = estimatedArrivalTimes.begin();
72         if ((eta + separation) < (*i)) {
73             newEta = eta;
74             found = true;
75             //cerr << "Storing at beginning" << endl;
76         }
77         while ((i != estimatedArrivalTimes.end()) && (!found)) {
78             TimeVectorIterator j = i + 1;
79             if (j == estimatedArrivalTimes.end()) {
80                 if (((*i) + separation) < eta) {
81                     //cerr << "Storing at end" << endl;
82                     newEta = eta;
83                 } else {
84                     newEta = (*i) + separation;
85                     //cerr << "Storing at end + separation" << endl;
86                 }
87             } else {
88                 if ((((*j) - (*i)) > (separation * 2))) {       // found a potential slot
89                     // now check whether this slot is usable:
90                     // 1) eta should fall between the two points
91                     //    i.e. eta > i AND eta < j
92                     //
93                     //cerr << "Found potential slot after " << (*i) << endl;
94                     if (eta > (*i) && (eta < (*j))) {
95                         found = true;
96                         if (eta < ((*i) + separation)) {
97                             newEta = (*i) + separation;
98                             //cerr << "Using  original" << (*i) << " + separation " << endl;
99                         } else {
100                             newEta = eta;
101                             //cerr << "Using original after " << (*i) << endl;
102                         }
103                     } else if (eta < (*i)) {
104                         found = true;
105                         newEta = (*i) + separation;
106                         //cerr << "Using delayed slot after " << (*i) << endl;
107                     }
108                     /*
109                        if (((*j) - separation) < eta) {
110                        found = true;
111                        if (((*i) + separation) < eta) {
112                        newEta = eta;
113                        cerr << "Using original after " << (*i) << endl;
114                        } else {
115                        newEta = (*i) + separation;
116                        cerr << "Using  " << (*i) << " + separation " << endl;
117                        }
118                        } */
119                 }
120             }
121             i++;
122         }
123     }
124     //cerr << ". done. New ETA : " << newEta << endl;
125
126     estimatedArrivalTimes.push_back(newEta);
127     sort(estimatedArrivalTimes.begin(), estimatedArrivalTimes.end());
128     // do some housekeeping : remove any timestamps that are past
129     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
130     TimeVectorIterator i = estimatedArrivalTimes.begin();
131     while (i != estimatedArrivalTimes.end()) {
132         if ((*i) < now) {
133             //cerr << "Deleting timestamp " << (*i) << " (now = " << now << "). " << endl;
134             estimatedArrivalTimes.erase(i);
135             i = estimatedArrivalTimes.begin();
136         } else {
137             i++;
138         }
139     }
140     return newEta;
141 }
142
143 /***************************************************************************
144  * FGTrafficRecord
145  **************************************************************************/
146 FGTrafficRecord::FGTrafficRecord():
147         id(0), waitsForId(0),
148         currentPos(0),
149         leg(0),
150         frequencyId(0),
151         state(0),
152         allowTransmission(true),
153         allowPushback(true),
154         priority(0),
155         latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
156 {
157 }
158
159 void FGTrafficRecord::setPositionAndIntentions(int pos,
160         FGAIFlightPlan * route)
161 {
162
163     currentPos = pos;
164     if (intentions.size()) {
165         intVecIterator i = intentions.begin();
166         if ((*i) != pos) {
167             SG_LOG(SG_GENERAL, SG_ALERT,
168                    "Error in FGTrafficRecord::setPositionAndIntentions");
169             //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
170             for (intVecIterator i = intentions.begin();
171                     i != intentions.end(); i++) {
172                 //cerr << (*i) << " ";
173             }
174             //cerr << endl;
175         }
176         intentions.erase(i);
177     } else {
178         //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
179         int size = route->getNrOfWayPoints();
180         //cerr << "Setting pos" << pos << " ";
181         //cerr << "setting intentions ";
182         for (int i = 0; i < size; i++) {
183             int val = route->getRouteIndex(i);
184             //cerr << val<< " ";
185             if ((val) && (val != pos)) {
186                 intentions.push_back(val);
187                 //cerr << "[set] ";
188             }
189         }
190         //cerr << endl;
191         //while (route->next(&legNr, &routeNr)) {
192         //intentions.push_back(routeNr);
193         //}
194         //route->rewind(currentPos);
195     }
196     //exit(1);
197 }
198 /**
199  * Check if another aircraft is ahead of the current one, and on the same
200  * return true / false is the is/isn't the case.
201  *
202  ****************************************************************************/
203
204 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
205 {
206     bool result = false;
207     //cerr << "Start check 1" << endl;
208     if (currentPos == other.currentPos) {
209         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
210         result = true;
211     }
212     //  else if (other.intentions.size())
213     //     {
214     //       cerr << "Start check 2" << endl;
215     //       intVecIterator i = other.intentions.begin();
216     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
217     //     i++;
218     //       if (i != other.intentions.end()) {
219     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
220     //     result = true;
221     //       }
222     else if (intentions.size()) {
223         //cerr << "Start check 3" << endl;
224         intVecIterator i = intentions.begin();
225         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
226         while (i != intentions.end()) {
227             if ((*i) == other.currentPos) {
228                 break;
229             }
230             i++;
231         }
232         if (i != intentions.end()) {
233             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
234             result = true;
235         }
236     }
237     //cerr << "Done !!" << endl;
238     return result;
239 }
240
241 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
242         double hdg, double spd,
243         double alt)
244 {
245     latitude = lat;
246     longitude = lon;
247     heading = hdg;
248     speed = spd;
249     altitude = alt;
250 }
251
252 int FGTrafficRecord::crosses(FGGroundNetwork * net,
253                              FGTrafficRecord & other)
254 {
255     if (checkPositionAndIntentions(other)
256             || (other.checkPositionAndIntentions(*this)))
257         return -1;
258     intVecIterator i, j;
259     int currentTargetNode = 0, otherTargetNode = 0;
260     if (currentPos > 0)
261         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,...
262     if (other.currentPos > 0)
263         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
264     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
265         return currentTargetNode;
266     if (intentions.size()) {
267         for (i = intentions.begin(); i != intentions.end(); i++) {
268             if ((*i) > 0) {
269                 if ((currentTargetNode ==
270                         net->findSegment(*i)->getEnd()->getIndex())) {
271                     //cerr << "Current crosses at " << currentTargetNode <<endl;
272                     return currentTargetNode;
273                 }
274             }
275         }
276     }
277     if (other.intentions.size()) {
278         for (i = other.intentions.begin(); i != other.intentions.end();
279                 i++) {
280             if ((*i) > 0) {
281                 if (otherTargetNode ==
282                         net->findSegment(*i)->getEnd()->getIndex()) {
283                     //cerr << "Other crosses at " << currentTargetNode <<endl;
284                     return otherTargetNode;
285                 }
286             }
287         }
288     }
289     if (intentions.size() && other.intentions.size()) {
290         for (i = intentions.begin(); i != intentions.end(); i++) {
291             for (j = other.intentions.begin(); j != other.intentions.end();
292                     j++) {
293                 //cerr << "finding segment " << *i << " and " << *j << endl;
294                 if (((*i) > 0) && ((*j) > 0)) {
295                     currentTargetNode =
296                         net->findSegment(*i)->getEnd()->getIndex();
297                     otherTargetNode =
298                         net->findSegment(*j)->getEnd()->getIndex();
299                     if (currentTargetNode == otherTargetNode) {
300                         //cerr << "Routes will cross at " << currentTargetNode << endl;
301                         return currentTargetNode;
302                     }
303                 }
304             }
305         }
306     }
307     return -1;
308 }
309
310 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
311                               FGTrafficRecord & other)
312 {
313     int node = -1, othernode = -1;
314     if (currentPos > 0)
315         node = net->findSegment(currentPos)->getEnd()->getIndex();
316     if (other.currentPos > 0)
317         othernode =
318             net->findSegment(other.currentPos)->getEnd()->getIndex();
319     if ((node == othernode) && (node != -1))
320         return true;
321     if (other.intentions.size()) {
322         for (intVecIterator i = other.intentions.begin();
323                 i != other.intentions.end(); i++) {
324             if (*i > 0) {
325                 othernode = net->findSegment(*i)->getEnd()->getIndex();
326                 if ((node == othernode) && (node > -1))
327                     return true;
328             }
329         }
330     }
331     //if (other.currentPos > 0)
332     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
333     //if (intentions.size())
334     //  {
335     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
336     //    {
337     //      if (*i > 0)
338     //        {
339     //          node = net->findSegment(*i)->getEnd()->getIndex();
340     //          if ((node == othernode) && (node > -1))
341     //            return true;
342     //        }
343     //    }
344     //  }
345     return false;
346 }
347
348
349 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
350                                  FGTrafficRecord & other, int node)
351 {
352     // Check if current segment is the reverse segment for the other aircraft
353     FGTaxiSegment *opp;
354     //cerr << "Current segment " << currentPos << endl;
355     if ((currentPos > 0) && (other.currentPos > 0)) {
356         opp = net->findSegment(currentPos)->opposite();
357         if (opp) {
358             if (opp->getIndex() == other.currentPos)
359                 return true;
360         }
361
362         for (intVecIterator i = intentions.begin(); i != intentions.end();
363                 i++) {
364             if ((opp = net->findSegment(other.currentPos)->opposite())) {
365                 if ((*i) > 0)
366                     if (opp->getIndex() ==
367                             net->findSegment(*i)->getIndex()) {
368                         if (net->findSegment(*i)->getStart()->getIndex() ==
369                                 node) {
370                             {
371                                 //cerr << "Found the node " << node << endl;
372                                 return true;
373                             }
374                         }
375                     }
376             }
377             if (other.intentions.size()) {
378                 for (intVecIterator j = other.intentions.begin();
379                         j != other.intentions.end(); j++) {
380                     // cerr << "Current segment 1 " << (*i) << endl;
381                     if ((*i) > 0) {
382                         if ((opp = net->findSegment(*i)->opposite())) {
383                             if (opp->getIndex() ==
384                                     net->findSegment(*j)->getIndex()) {
385                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
386                                 //   << " and  " << net->findSegment(*j)->getIndex()
387                                 //   << " are opposites " << endl;
388                                 if (net->findSegment(*i)->getStart()->
389                                         getIndex() == node) {
390                                     {
391                                         //cerr << "Found the node " << node << endl;
392                                         return true;
393                                     }
394                                 }
395                             }
396                         }
397                     }
398                 }
399             }
400         }
401     }
402     return false;
403 }
404
405 bool FGTrafficRecord::isActive(int margin)
406 {
407     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
408     time_t deptime = aircraft->getTrafficRef()->getDepartureTime();
409     return ((now + margin) > deptime);
410 }
411
412
413 void FGTrafficRecord::setSpeedAdjustment(double spd)
414 {
415     instruction.setChangeSpeed(true);
416     instruction.setSpeed(spd);
417 }
418
419 void FGTrafficRecord::setHeadingAdjustment(double heading)
420 {
421     instruction.setChangeHeading(true);
422     instruction.setHeading(heading);
423 }
424
425 bool FGTrafficRecord::pushBackAllowed()
426 {
427     return allowPushback;
428 }
429
430
431
432
433 /***************************************************************************
434  * FGATCInstruction
435  *
436  **************************************************************************/
437 FGATCInstruction::FGATCInstruction()
438 {
439     holdPattern = false;
440     holdPosition = false;
441     changeSpeed = false;
442     changeHeading = false;
443     changeAltitude = false;
444     resolveCircularWait = false;
445
446     speed = 0;
447     heading = 0;
448     alt = 0;
449 }
450
451
452 bool FGATCInstruction::hasInstruction()
453 {
454     return (holdPattern || holdPosition || changeSpeed || changeHeading
455             || changeAltitude || resolveCircularWait);
456 }
457
458 /***************************************************************************
459  * FGATCController
460  *
461  **************************************************************************/
462
463
464
465
466 FGATCController::FGATCController()
467 {
468     //cerr << "running FGATController constructor" << endl;
469     dt_count = 0;
470     available = true;
471     lastTransmission = 0;
472     initialized = false;
473 }
474
475 FGATCController::~FGATCController()
476 {
477     //cerr << "running FGATController destructor" << endl;
478 }
479
480 string FGATCController::getGateName(FGAIAircraft * ref)
481 {
482     return ref->atGate();
483 }
484
485 bool FGATCController::isUserAircraft(FGAIAircraft* ac)
486 {
487     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false;
488 };
489
490 void FGATCController::transmit(FGTrafficRecord * rec, FGAirportDynamics *parent, AtcMsgId msgId,
491                                AtcMsgDir msgDir, bool audible)
492 {
493     string sender, receiver;
494     int stationFreq = 0;
495     int taxiFreq = 0;
496     int towerFreq = 0;
497     int freqId = 0;
498     string atisInformation;
499     string text;
500     string taxiFreqStr;
501     string towerFreqStr;
502     double heading = 0;
503     string activeRunway;
504     string fltType;
505     string rwyClass;
506     string SID;
507     string transponderCode;
508     FGAIFlightPlan *fp;
509     string fltRules;
510     string instructionText;
511     int ground_to_air=0;
512
513     //double commFreqD;
514     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
515     if (rec->getAircraft()->getTaxiClearanceRequest()) {
516         instructionText = "push-back and taxi";
517     } else {
518         instructionText = "taxi";
519     }
520     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
521     switch (rec->getLeg()) {
522     case 1:
523     case 2:
524         freqId = rec->getNextFrequency();
525         stationFreq =
526             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
527             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
528         taxiFreq =
529             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
530             getDynamics()->getGroundFrequency(2);
531         towerFreq =
532             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
533             getDynamics()->getTowerFrequency(2);
534         receiver =
535             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536             getName() + "-Ground";
537         atisInformation =
538             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
539             getDynamics()->getAtisSequence();
540         break;
541     case 3:
542         receiver =
543             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
544             getName() + "-Tower";
545         break;
546     }
547     // Swap sender and receiver value in case of a ground to air transmission
548     if (msgDir == ATC_GROUND_TO_AIR) {
549         string tmp = sender;
550         sender = receiver;
551         receiver = tmp;
552         ground_to_air=1;
553     }
554     switch (msgId) {
555     case MSG_ANNOUNCE_ENGINE_START:
556         text = sender + ". Ready to Start up";
557         break;
558     case MSG_REQUEST_ENGINE_START:
559         text =
560             receiver + ", This is " + sender + ". Position " +
561             getGateName(rec->getAircraft()) + ". Information " +
562             atisInformation + ". " +
563             rec->getAircraft()->getTrafficRef()->getFlightRules() +
564             " to " +
565             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
566             getName() + ". Request start-up";
567         break;
568         // Acknowledge engine startup permission
569         // Assign departure runway
570         // Assign SID, if necessery (TODO)
571     case MSG_PERMIT_ENGINE_START:
572         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
573
574         heading = rec->getAircraft()->getTrafficRef()->getCourse();
575         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
576         rwyClass =
577             rec->getAircraft()->GetFlightPlan()->
578             getRunwayClassFromTrafficType(fltType);
579
580         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
581         getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
582                                        heading);
583         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
584         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
585              getDynamics()->getSID(activeRunway, heading);
586         rec->getAircraft()->GetFlightPlan()->setSID(fp);
587         if (fp) {
588             SID = fp->getName() + " departure";
589         } else {
590             SID = "fly runway heading ";
591         }
592         //snprintf(buffer, 7, "%3.2f", heading);
593         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
594         transponderCode = genTransponderCode(fltRules);
595         rec->getAircraft()->SetTransponderCode(transponderCode);
596         text =
597             receiver + ". Start-up approved. " + atisInformation +
598             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
599             transponderCode + ". " +
600             "For "+ instructionText + " clearance call " + taxiFreqStr + ". " +
601             sender + " control.";
602         break;
603     case MSG_DENY_ENGINE_START:
604         text = receiver + ". Standby";
605         break;
606     case MSG_ACKNOWLEDGE_ENGINE_START:
607         fp = rec->getAircraft()->GetFlightPlan()->getSID();
608         if (fp) {
609             SID =
610                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
611                 " departure";
612         } else {
613             SID = "fly runway heading ";
614         }
615         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
616         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
617         transponderCode = rec->getAircraft()->GetTransponderCode();
618
619         text =
620             receiver + ". Start-up approved. " + atisInformation +
621             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
622             transponderCode + ". " +
623             "For " + instructionText + " clearance call " + taxiFreqStr + ". " +
624             sender;
625         break;
626     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
627         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
628         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
629         break;
630     case MSG_INITIATE_CONTACT:
631         text = receiver + ". With you. " + sender;
632         break;
633     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
634         text = receiver + ". Roger. " + sender;
635         break;
636     case MSG_REQUEST_PUSHBACK_CLEARANCE:
637         if (rec->getAircraft()->getTaxiClearanceRequest()) {
638             text = receiver + ". Request push-back. " + sender;
639         } else {
640             text = receiver + ". Request Taxi clearance. " + sender;
641         }
642         break;
643     case MSG_PERMIT_PUSHBACK_CLEARANCE:
644         if (rec->getAircraft()->getTaxiClearanceRequest()) {
645             text = receiver + ". Push-back approved. " + sender;
646         } else {
647             text = receiver + ". Cleared to Taxi." + sender;
648         }
649         break;
650     case MSG_HOLD_PUSHBACK_CLEARANCE:
651         text = receiver + ". Standby. " + sender;
652         break;
653     case MSG_REQUEST_TAXI_CLEARANCE:
654         text = receiver + ". Ready to Taxi. " + sender;
655         break;
656     case MSG_ISSUE_TAXI_CLEARANCE:
657         text = receiver + ". Cleared to taxi. " + sender;
658         break;
659     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
660         text = receiver + ". Cleared to taxi. " + sender;
661         break;
662     case MSG_HOLD_POSITION:
663         text = receiver + ". Hold Position. " + sender;
664         break;
665     case MSG_ACKNOWLEDGE_HOLD_POSITION:
666         text = receiver + ". Holding Position. " + sender;
667         break;
668     case MSG_RESUME_TAXI:
669         text = receiver + ". Resume Taxiing. " + sender;
670         break;
671     case MSG_ACKNOWLEDGE_RESUME_TAXI:
672         text = receiver + ". Continuing Taxi. " + sender;
673         break;
674     case MSG_REPORT_RUNWAY_HOLD_SHORT:
675         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
676         //activeRunway = "test";
677         text = receiver + ". Holding short runway "
678                + activeRunway
679                + ". " + sender;
680         //text = "test1";
681         //cerr << "1 Currently at leg " << rec->getLeg() << endl;
682         break;
683     case MSG_ACKNOWLEDGE_REPORT_RUNWAY_HOLD_SHORT:
684         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
685         text = receiver + "Roger. Holding short runway "
686                //                + activeRunway
687                + ". " + sender;
688         //text = "test2";
689         //cerr << "2 Currently at leg " << rec->getLeg() << endl;
690         break;
691     case MSG_SWITCH_TOWER_FREQUENCY:
692         towerFreqStr = formatATCFrequency3_2(towerFreq);
693         text = receiver + "Contact Tower at " + towerFreqStr + ". " + sender;
694         //text = "test3";
695         //cerr << "3 Currently at leg " << rec->getLeg() << endl;
696         break;
697     case MSG_ACKNOWLEDGE_SWITCH_TOWER_FREQUENCY:
698         towerFreqStr = formatATCFrequency3_2(towerFreq);
699         text = receiver + "Roger, switching to tower at " + towerFreqStr + ". " + sender;
700         //text = "test4";
701         //cerr << "4 Currently at leg " << rec->getLeg() << endl;
702         break;
703     default:
704         //text = "test3";
705         text = text + sender + ". Transmitting unknown Message";
706         break;
707     }
708     if (audible) {
709         double onBoardRadioFreq0 =
710             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
711         double onBoardRadioFreq1 =
712             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
713         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
714         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
715         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
716
717         // Display ATC message only when one of the radios is tuned
718         // the relevant frequency.
719         // Note that distance attenuation is currently not yet implemented
720                 
721         if ((onBoardRadioFreqI0 == stationFreq)
722                 || (onBoardRadioFreqI1 == stationFreq)) {
723             if (rec->allowTransmissions()) {
724                 
725                 fgSetString("/sim/messages/atc", text.c_str());
726             }
727         }
728     } else {
729         FGATCDialogNew::instance()->addEntry(1, text);
730     }
731 }
732
733
734 string FGATCController::formatATCFrequency3_2(int freq)
735 {
736     char buffer[7];
737     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
738     return string(buffer);
739 }
740
741 // TODO: Set transponder codes according to real-world routes.
742 // The current version just returns a random string of four octal numbers.
743 string FGATCController::genTransponderCode(string fltRules)
744 {
745     if (fltRules == "VFR") {
746         return string("1200");
747     } else {
748         char buffer[5];
749         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
750                  rand() % 8);
751         return string(buffer);
752     }
753 }
754
755 void FGATCController::init()
756 {
757     if (!initialized) {
758         FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
759         mgr->addController(this);
760         initialized = true;
761     }
762 }
763
764 /***************************************************************************
765  * class FGTowerController
766  *
767  **************************************************************************/
768 FGTowerController::FGTowerController(FGAirportDynamics *par) :
769         FGATCController()
770 {
771     parent = par;
772 }
773
774 //
775 void FGTowerController::announcePosition(int id,
776         FGAIFlightPlan * intendedRoute,
777         int currentPosition, double lat,
778         double lon, double heading,
779         double speed, double alt,
780         double radius, int leg,
781         FGAIAircraft * ref)
782 {
783     init();
784     TrafficVectorIterator i = activeTraffic.begin();
785     // Search whether the current id alread has an entry
786     // This might be faster using a map instead of a vector, but let's start by taking a safe route
787     if (activeTraffic.size()) {
788         //while ((i->getId() != id) && i != activeTraffic.end()) {
789         while (i != activeTraffic.end()) {
790             if (i->getId() == id) {
791                 break;
792             }
793             i++;
794         }
795     }
796     // Add a new TrafficRecord if no one exsists for this aircraft.
797     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
798         FGTrafficRecord rec;
799         rec.setId(id);
800
801         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
802         rec.setRunway(intendedRoute->getRunway());
803         rec.setLeg(leg);
804         //rec.setCallSign(callsign);
805         rec.setRadius(radius);
806         rec.setAircraft(ref);
807         activeTraffic.push_back(rec);
808         // Don't just schedule the aircraft for the tower controller, also assign if to the correct active runway.
809         ActiveRunwayVecIterator rwy = activeRunways.begin();
810         if (activeRunways.size()) {
811             while (rwy != activeRunways.end()) {
812                 if (rwy->getRunwayName() == intendedRoute->getRunway()) {
813                     break;
814                 }
815                 rwy++;
816             }
817         }
818         if (rwy == activeRunways.end()) {
819             ActiveRunway aRwy(intendedRoute->getRunway(), id);
820             aRwy.addToDepartureCue(ref);
821             activeRunways.push_back(aRwy);
822             rwy = (activeRunways.end()-1);
823         } else {
824             rwy->addToDepartureCue(ref);
825         }
826
827         //cerr << ref->getTrafficRef()->getCallSign() << " You are number " << rwy->getDepartureCueSize() <<  " for takeoff " << endl;
828     } else {
829         i->setPositionAndHeading(lat, lon, heading, speed, alt);
830     }
831 }
832
833 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
834         double heading, double speed, double alt,
835         double dt)
836 {
837     TrafficVectorIterator i = activeTraffic.begin();
838     // Search whether the current id has an entry
839     // This might be faster using a map instead of a vector, but let's start by taking a safe route
840     TrafficVectorIterator current, closest;
841     if (activeTraffic.size()) {
842         //while ((i->getId() != id) && i != activeTraffic.end()) {
843         while (i != activeTraffic.end()) {
844             if (i->getId() == id) {
845                 break;
846             }
847             i++;
848         }
849     }
850 //    // update position of the current aircraft
851     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
852         SG_LOG(SG_GENERAL, SG_ALERT,
853                "AI error: updating aircraft without traffic record");
854     } else {
855         i->setPositionAndHeading(lat, lon, heading, speed, alt);
856         current = i;
857     }
858     setDt(getDt() + dt);
859
860     // see if we already have a clearance record for the currently active runway
861     // NOTE: dd. 2011-08-07: Because the active runway has been constructed in the announcePosition function, we may safely assume that is
862     // already exists here. So, we can simplify the current code.
863     ActiveRunwayVecIterator rwy = activeRunways.begin();
864     while (rwy != activeRunways.end()) {
865         if (rwy->getRunwayName() == current->getRunway()) {
866             break;
867         }
868         rwy++;
869     }
870
871     // only bother running the following code if the current aircraft is the
872     // first in line for depature
873     /* if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
874         if (rwy->getCleared()) {
875             if (id == rwy->getCleared()) {
876                 current->setHoldPosition(false);
877             } else {
878                 current->setHoldPosition(true);
879             }
880         } else {
881             // For now. At later stages, this will probably be the place to check for inbound traffc.
882             rwy->setCleared(id);
883         }
884     } */
885     // only bother with aircraft that have a takeoff status of 2, since those are essentially under tower control
886     if (current->getAircraft()->getTakeOffStatus() == 2) {
887         current->setHoldPosition(true);
888         int clearanceId = rwy->getCleared();
889         if (clearanceId) {
890             if (id == clearanceId) {
891                 current->setHoldPosition(false);
892             }
893         } else {
894             if (current->getAircraft() == rwy->getFirstAircraftInDepartureCue()) {
895                 rwy->setCleared(id);
896             }
897         }
898     } else {
899         
900     }
901 }
902
903
904 void FGTowerController::signOff(int id)
905 {
906     TrafficVectorIterator i = activeTraffic.begin();
907     // Search search if the current id alread has an entry
908     // This might be faster using a map instead of a vector, but let's start by taking a safe route
909     if (activeTraffic.size()) {
910         //while ((i->getId() != id) && i != activeTraffic.end()) {
911         while (i != activeTraffic.end()) {
912             if (i->getId() == id) {
913                 break;
914             }
915             i++;
916         }
917     }
918     // If this aircraft has left the runway, we can clear the departure record for this runway
919     ActiveRunwayVecIterator rwy = activeRunways.begin();
920     if (activeRunways.size()) {
921         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
922         while (rwy != activeRunways.end()) {
923             if (rwy->getRunwayName() == i->getRunway()) {
924                 break;
925             }
926             rwy++;
927         }
928         if (rwy != activeRunways.end()) {
929             rwy->setCleared(0);
930             rwy->updateDepartureCue();
931         } else {
932             SG_LOG(SG_GENERAL, SG_ALERT,
933                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
934         }
935     }
936     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
937         SG_LOG(SG_GENERAL, SG_ALERT,
938                "AI error: Aircraft without traffic record is signing off from tower");
939     } else {
940         i->getAircraft()->resetTakeOffStatus();
941         i = activeTraffic.erase(i);
942         //cerr << "Signing off from tower controller" << endl;
943     }
944 }
945
946 // NOTE:
947 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
948 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
949 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
950 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
951 // Note that this function is probably obsolete
952 bool FGTowerController::hasInstruction(int id)
953 {
954     TrafficVectorIterator i = activeTraffic.begin();
955     // Search search if the current id has an entry
956     // This might be faster using a map instead of a vector, but let's start by taking a safe route
957     if (activeTraffic.size()) {
958         //while ((i->getId() != id) && i != activeTraffic.end()) {
959         while (i != activeTraffic.end()) {
960             if (i->getId() == id) {
961                 break;
962             }
963             i++;
964         }
965     }
966     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
967         SG_LOG(SG_GENERAL, SG_ALERT,
968                "AI error: checking ATC instruction for aircraft without traffic record");
969     } else {
970         return i->hasInstruction();
971     }
972     return false;
973 }
974
975
976 FGATCInstruction FGTowerController::getInstruction(int id)
977 {
978     TrafficVectorIterator i = activeTraffic.begin();
979     // Search search if the current id has an entry
980     // This might be faster using a map instead of a vector, but let's start by taking a safe route
981     if (activeTraffic.size()) {
982         //while ((i->getId() != id) && i != activeTraffic.end()) {
983         while (i != activeTraffic.end()) {
984             if (i->getId() == id) {
985                 break;
986             }
987             i++;
988         }
989     }
990     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
991         SG_LOG(SG_GENERAL, SG_ALERT,
992                "AI error: requesting ATC instruction for aircraft without traffic record");
993     } else {
994         return i->getInstruction();
995     }
996     return FGATCInstruction();
997 }
998
999 void FGTowerController::render(bool visible) {
1000     //cerr << "FGTowerController::render function not yet implemented" << endl;
1001 }
1002
1003 string FGTowerController::getName() {
1004     return string(parent->getId() + "-tower");
1005 }
1006
1007 void FGTowerController::update(double dt)
1008 {
1009
1010 }
1011
1012
1013
1014 /***************************************************************************
1015  * class FGStartupController
1016  *
1017  **************************************************************************/
1018 FGStartupController::FGStartupController(FGAirportDynamics *par):
1019         FGATCController()
1020 {
1021     parent = par;
1022 }
1023
1024 void FGStartupController::announcePosition(int id,
1025         FGAIFlightPlan * intendedRoute,
1026         int currentPosition, double lat,
1027         double lon, double heading,
1028         double speed, double alt,
1029         double radius, int leg,
1030         FGAIAircraft * ref)
1031 {
1032     init();
1033     TrafficVectorIterator i = activeTraffic.begin();
1034     // Search whether the current id alread has an entry
1035     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1036     if (activeTraffic.size()) {
1037         //while ((i->getId() != id) && i != activeTraffic.end()) {
1038         while (i != activeTraffic.end()) {
1039             if (i->getId() == id) {
1040                 break;
1041             }
1042             i++;
1043         }
1044     }
1045     // Add a new TrafficRecord if no one exsists for this aircraft.
1046     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1047         FGTrafficRecord rec;
1048         rec.setId(id);
1049
1050         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1051         rec.setRunway(intendedRoute->getRunway());
1052         rec.setLeg(leg);
1053         rec.setPositionAndIntentions(currentPosition, intendedRoute);
1054         //rec.setCallSign(callsign);
1055         rec.setAircraft(ref);
1056         rec.setHoldPosition(true);
1057         activeTraffic.push_back(rec);
1058     } else {
1059         i->setPositionAndIntentions(currentPosition, intendedRoute);
1060         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1061
1062     }
1063 }
1064
1065 // NOTE:
1066 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
1067 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN
1068 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
1069 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
1070 // Note that this function is probably obsolete
1071 bool FGStartupController::hasInstruction(int id)
1072 {
1073     TrafficVectorIterator i = activeTraffic.begin();
1074     // Search search if the current id has an entry
1075     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1076     if (activeTraffic.size()) {
1077         //while ((i->getId() != id) && i != activeTraffic.end()) {
1078         while (i != activeTraffic.end()) {
1079             if (i->getId() == id) {
1080                 break;
1081             }
1082             i++;
1083         }
1084     }
1085     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1086         SG_LOG(SG_GENERAL, SG_ALERT,
1087                "AI error: checking ATC instruction for aircraft without traffic record");
1088     } else {
1089         return i->hasInstruction();
1090     }
1091     return false;
1092 }
1093
1094
1095 FGATCInstruction FGStartupController::getInstruction(int id)
1096 {
1097     TrafficVectorIterator i = activeTraffic.begin();
1098     // Search search if the current id has an entry
1099     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1100     if (activeTraffic.size()) {
1101         //while ((i->getId() != id) && i != activeTraffic.end()) {
1102         while (i != activeTraffic.end()) {
1103             if (i->getId() == id) {
1104                 break;
1105             }
1106             i++;
1107         }
1108     }
1109     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1110         SG_LOG(SG_GENERAL, SG_ALERT,
1111                "AI error: requesting ATC instruction for aircraft without traffic record");
1112     } else {
1113         return i->getInstruction();
1114     }
1115     return FGATCInstruction();
1116 }
1117
1118 void FGStartupController::signOff(int id)
1119 {
1120     TrafficVectorIterator i = activeTraffic.begin();
1121     // Search search if the current id alread has an entry
1122     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1123     if (activeTraffic.size()) {
1124         //while ((i->getId() != id) && i != activeTraffic.end()) {
1125         while (i != activeTraffic.end()) {
1126             if (i->getId() == id) {
1127                 break;
1128             }
1129             i++;
1130         }
1131     }
1132     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1133         SG_LOG(SG_GENERAL, SG_ALERT,
1134                "AI error: Aircraft without traffic record is signing off from tower");
1135     } else {
1136         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1137         i = activeTraffic.erase(i);
1138     }
1139 }
1140
1141 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1142         AtcMsgDir msgDir)
1143 {
1144     int state = i->getState();
1145     if ((state == st) && available) {
1146         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1147
1148             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1149             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1150             int n = trans_num->getIntValue();
1151             if (n == 0) {
1152                 trans_num->setIntValue(-1);
1153                 // PopupCallback(n);
1154                 //cerr << "Selected transmission message " << n << endl;
1155                 FGATCDialogNew::instance()->removeEntry(1);
1156             } else {
1157                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1158                 transmit(&(*i), &(*parent), msgId, msgDir, false);
1159                 return false;
1160             }
1161         }
1162         if (now > startTime) {
1163             //cerr << "Transmitting startup msg" << endl;
1164             transmit(&(*i), &(*parent), msgId, msgDir, true);
1165             i->updateState();
1166             lastTransmission = now;
1167             available = false;
1168             return true;
1169         }
1170     }
1171     return false;
1172 }
1173
1174 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1175         double heading, double speed, double alt,
1176         double dt)
1177 {
1178     TrafficVectorIterator i = activeTraffic.begin();
1179     // Search search if the current id has an entry
1180     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1181     TrafficVectorIterator current, closest;
1182     if (activeTraffic.size()) {
1183         //while ((i->getId() != id) && i != activeTraffic.end()) {
1184         while (i != activeTraffic.end()) {
1185             if (i->getId() == id) {
1186                 break;
1187             }
1188             i++;
1189         }
1190     }
1191 //    // update position of the current aircraft
1192
1193     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1194         SG_LOG(SG_GENERAL, SG_ALERT,
1195                "AI error: updating aircraft without traffic record");
1196     } else {
1197         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1198         current = i;
1199     }
1200     setDt(getDt() + dt);
1201
1202     int state = i->getState();
1203
1204     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference.
1205     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1206     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1207     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1208     //cerr << i->getAircraft()->getTrafficRef()->getCallSign()
1209     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1210     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1211
1212     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1213         available = true;
1214     }
1215
1216     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1217     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1218     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1219     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1220     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1221         i->nextFrequency();
1222     }
1223     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1224     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1225     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1226
1227
1228
1229     if ((state == 8) && available) {
1230         if (now > startTime + 200) {
1231             if (i->pushBackAllowed()) {
1232                 i->allowRepeatedTransmissions();
1233                 transmit(&(*i), &(*parent), MSG_PERMIT_PUSHBACK_CLEARANCE,
1234                          ATC_GROUND_TO_AIR, true);
1235                 i->updateState();
1236             } else {
1237                 transmit(&(*i), &(*parent), MSG_HOLD_PUSHBACK_CLEARANCE,
1238                          ATC_GROUND_TO_AIR, true);
1239                 i->suppressRepeatedTransmissions();
1240             }
1241             lastTransmission = now;
1242             available = false;
1243         }
1244     }
1245     if ((state == 9) && available) {
1246         i->setHoldPosition(false);
1247     }
1248 }
1249
1250 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1251 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1252                             double lon, double elev, double hdg, double slope)
1253 {
1254     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1255     obj_pos = geod.makeZUpFrame();
1256     // hdg is not a compass heading, but a counter-clockwise rotation
1257     // around the Z axis
1258     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1259                                         0.0, 0.0, 1.0));
1260     obj_pos.preMult(osg::Matrix::rotate(slope * SGD_DEGREES_TO_RADIANS,
1261                                         0.0, 1.0, 0.0));
1262 }
1263
1264
1265 void FGStartupController::render(bool visible)
1266 {
1267
1268     SGMaterialLib *matlib = globals->get_matlib();
1269     if (group) {
1270         //int nr = ;
1271         globals->get_scenery()->get_scene_graph()->removeChild(group);
1272         //while (group->getNumChildren()) {
1273         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1274         //simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1275         //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1276         //geode->releaseGLObjects();
1277         //group->removeChild(geode);
1278         //delete geode;
1279         group = 0;
1280     }
1281     if (visible) {
1282         group = new osg::Group;
1283         FGScenery * local_scenery = globals->get_scenery();
1284         double elevation_meters = 0.0;
1285         double elevation_feet = 0.0;
1286
1287
1288         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1289         double dx = 0;
1290         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1291             if (i->isActive(300)) {
1292                 // Handle start point
1293                 int pos = i->getCurrentPosition();
1294                 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1295                 if (pos > 0) {
1296                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1297                     SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1298                     SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1299
1300                     double length = SGGeodesy::distanceM(start, end);
1301                     //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1302
1303                     double az2, heading; //, distanceM;
1304                     SGGeodesy::inverse(start, end, heading, az2, length);
1305                     double coveredDistance = length * 0.5;
1306                     SGGeod center;
1307                     SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1308                     //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1309                     ///////////////////////////////////////////////////////////////////////////////
1310                     // Make a helper function out of this
1311                     osg::Matrix obj_pos;
1312                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1313                     obj_trans->setDataVariance(osg::Object::STATIC);
1314                     // Experimental: Calculate slope here, based on length, and the individual elevations
1315                     double elevationStart;
1316                     if (isUserAircraft((i)->getAircraft())) {
1317                         elevationStart = fgGetDouble("/position/ground-elev-m");
1318                     } else {
1319                         elevationStart = ((i)->getAircraft()->_getAltitude() * SG_FEET_TO_METER);
1320                     }
1321                     double elevationEnd   = segment->getEnd()->getElevation();
1322                     if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1323                         SGGeod center2 = end;
1324                         center2.setElevationM(SG_MAX_ELEVATION_M);
1325                         if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1326                             elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1327                             //elevation_meters += 0.5;
1328                         }
1329                         else {
1330                             elevationEnd = parent->getElevation();
1331                         }
1332                         segment->getEnd()->setElevation(elevationEnd);
1333                     }
1334
1335                     double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1336                     double elevDiff       = elevationEnd - elevationStart;
1337
1338                     double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1339
1340                     //cerr << "1. Using mean elevation : " << elevationMean << " and " << slope << endl;
1341
1342                     WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), elevationMean + 0.5 + dx, -(heading), slope );
1343                     ;
1344
1345                     obj_trans->setMatrix( obj_pos );
1346                     //osg::Vec3 center(0, 0, 0)
1347
1348                     float width = length /2.0;
1349                     osg::Vec3 corner(-width, 0, 0.25f);
1350                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1351                     osg::Vec3 heightVec(0, 1, 0);
1352                     osg::Geometry* geometry;
1353                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1354                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1355                     geode->setName("test");
1356                     geode->addDrawable(geometry);
1357                     //osg::Node *custom_obj;
1358                     SGMaterial *mat;
1359                     if (segment->hasBlock()) {
1360                         mat = matlib->find("UnidirectionalTaperRed");
1361                     } else {
1362                         mat = matlib->find("UnidirectionalTaperGreen");
1363                     }
1364                     if (mat)
1365                         geode->setEffect(mat->get_effect());
1366                     obj_trans->addChild(geode);
1367                     // wire as much of the scene graph together as we can
1368                     //->addChild( obj_trans );
1369                     group->addChild( obj_trans );
1370                     /////////////////////////////////////////////////////////////////////
1371                 } else {
1372                     //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1373                 }
1374                 for (intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1375                     osg::Matrix obj_pos;
1376                     int k = (*j);
1377                     if (k > 0) {
1378                         //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1379                         osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1380                         obj_trans->setDataVariance(osg::Object::STATIC);
1381                         FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1382
1383                         double elevationStart = segment->getStart()->getElevation();
1384                         double elevationEnd   = segment->getEnd  ()->getElevation();
1385                         if ((elevationStart == 0) || (elevationStart == parent->getElevation())) {
1386                             SGGeod center2 = segment->getStart()->getGeod();
1387                             center2.setElevationM(SG_MAX_ELEVATION_M);
1388                             if (local_scenery->get_elevation_m( center2, elevationStart, NULL )) {
1389                                 elevation_feet = elevationStart * SG_METER_TO_FEET + 0.5;
1390                                 //elevation_meters += 0.5;
1391                             }
1392                             else {
1393                                 elevationStart = parent->getElevation();
1394                             }
1395                             segment->getStart()->setElevation(elevationStart);
1396                         }
1397                         if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
1398                             SGGeod center2 = segment->getEnd()->getGeod();
1399                             center2.setElevationM(SG_MAX_ELEVATION_M);
1400                             if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
1401                                 elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
1402                                 //elevation_meters += 0.5;
1403                             }
1404                             else {
1405                                 elevationEnd = parent->getElevation();
1406                             }
1407                             segment->getEnd()->setElevation(elevationEnd);
1408                         }
1409
1410                         double elevationMean  = (elevationStart + elevationEnd) / 2.0;
1411                         double elevDiff       = elevationEnd - elevationStart;
1412                         double length         = segment->getLength();
1413                         double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
1414
1415                         //cerr << "2. Using mean elevation : " << elevationMean << " and " << slope << endl;
1416
1417
1418                         WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), elevationMean + 0.5 + dx, -(segment->getHeading()), slope );
1419
1420                         //WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1421
1422                         obj_trans->setMatrix( obj_pos );
1423                         //osg::Vec3 center(0, 0, 0)
1424
1425                         float width = segment->getLength() /2.0;
1426                         osg::Vec3 corner(-width, 0, 0.25f);
1427                         osg::Vec3 widthVec(2*width + 1, 0, 0);
1428                         osg::Vec3 heightVec(0, 1, 0);
1429                         osg::Geometry* geometry;
1430                         geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1431                         simgear::EffectGeode* geode = new simgear::EffectGeode;
1432                         geode->setName("test");
1433                         geode->addDrawable(geometry);
1434                         //osg::Node *custom_obj;
1435                         SGMaterial *mat;
1436                         if (segment->hasBlock()) {
1437                             mat = matlib->find("UnidirectionalTaperRed");
1438                         } else {
1439                             mat = matlib->find("UnidirectionalTaperGreen");
1440                         }
1441                         if (mat)
1442                             geode->setEffect(mat->get_effect());
1443                         obj_trans->addChild(geode);
1444                         // wire as much of the scene graph together as we can
1445                         //->addChild( obj_trans );
1446                         group->addChild( obj_trans );
1447                     } else {
1448                         //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1449                     }
1450                 }
1451                 dx += 0.2;
1452             }
1453         }
1454         globals->get_scenery()->get_scene_graph()->addChild(group);
1455     }
1456 }
1457
1458 string FGStartupController::getName() {
1459     return string(parent->getId() + "-startup");
1460 }
1461
1462 void FGStartupController::update(double dt)
1463 {
1464
1465 }
1466
1467
1468
1469 /***************************************************************************
1470  * class FGApproachController
1471  *
1472  **************************************************************************/
1473 FGApproachController::FGApproachController(FGAirportDynamics *par):
1474         FGATCController()
1475 {
1476     parent = par;
1477 }
1478
1479 //
1480 void FGApproachController::announcePosition(int id,
1481         FGAIFlightPlan * intendedRoute,
1482         int currentPosition,
1483         double lat, double lon,
1484         double heading, double speed,
1485         double alt, double radius,
1486         int leg, FGAIAircraft * ref)
1487 {
1488     init();
1489     TrafficVectorIterator i = activeTraffic.begin();
1490     // Search whether the current id alread has an entry
1491     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1492     if (activeTraffic.size()) {
1493         //while ((i->getId() != id) && i != activeTraffic.end()) {
1494         while (i != activeTraffic.end()) {
1495             if (i->getId() == id) {
1496                 break;
1497             }
1498             i++;
1499         }
1500     }
1501     // Add a new TrafficRecord if no one exsists for this aircraft.
1502     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1503         FGTrafficRecord rec;
1504         rec.setId(id);
1505
1506         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1507         rec.setRunway(intendedRoute->getRunway());
1508         rec.setLeg(leg);
1509         //rec.setCallSign(callsign);
1510         rec.setAircraft(ref);
1511         activeTraffic.push_back(rec);
1512     } else {
1513         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1514     }
1515 }
1516
1517 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1518         double heading, double speed, double alt,
1519         double dt)
1520 {
1521     TrafficVectorIterator i = activeTraffic.begin();
1522     // Search search if the current id has an entry
1523     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1524     TrafficVectorIterator current, closest;
1525     if (activeTraffic.size()) {
1526         //while ((i->getId() != id) && i != activeTraffic.end()) {
1527         while (i != activeTraffic.end()) {
1528             if (i->getId() == id) {
1529                 break;
1530             }
1531             i++;
1532         }
1533     }
1534 //    // update position of the current aircraft
1535     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1536         SG_LOG(SG_GENERAL, SG_ALERT,
1537                "AI error: updating aircraft without traffic record");
1538     } else {
1539         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1540         current = i;
1541         //cerr << "ApproachController: checking for speed" << endl;
1542         time_t time_diff =
1543             current->getAircraft()->
1544             checkForArrivalTime(string("final001"));
1545         if (time_diff > 15) {
1546             current->setSpeedAdjustment(current->getAircraft()->
1547                                         getPerformance()->vDescent() *
1548                                         1.35);
1549         } else if (time_diff > 5) {
1550             current->setSpeedAdjustment(current->getAircraft()->
1551                                         getPerformance()->vDescent() *
1552                                         1.2);
1553         } else if (time_diff < -15) {
1554             current->setSpeedAdjustment(current->getAircraft()->
1555                                         getPerformance()->vDescent() *
1556                                         0.65);
1557         } else if (time_diff < -5) {
1558             current->setSpeedAdjustment(current->getAircraft()->
1559                                         getPerformance()->vDescent() *
1560                                         0.8);
1561         } else {
1562             current->clearSpeedAdjustment();
1563         }
1564         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1565     }
1566     setDt(getDt() + dt);
1567 }
1568
1569 void FGApproachController::signOff(int id)
1570 {
1571     TrafficVectorIterator i = activeTraffic.begin();
1572     // Search search if the current id alread has an entry
1573     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1574     if (activeTraffic.size()) {
1575         //while ((i->getId() != id) && i != activeTraffic.end()) {
1576         while (i != activeTraffic.end()) {
1577             if (i->getId() == id) {
1578                 break;
1579             }
1580             i++;
1581         }
1582     }
1583     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1584         SG_LOG(SG_GENERAL, SG_ALERT,
1585                "AI error: Aircraft without traffic record is signing off from approach");
1586     } else {
1587         i = activeTraffic.erase(i);
1588     }
1589 }
1590
1591 void FGApproachController::update(double dt)
1592 {
1593
1594 }
1595
1596
1597
1598 bool FGApproachController::hasInstruction(int id)
1599 {
1600     TrafficVectorIterator i = activeTraffic.begin();
1601     // Search search if the current id has an entry
1602     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1603     if (activeTraffic.size()) {
1604         //while ((i->getId() != id) && i != activeTraffic.end()) {
1605         while (i != activeTraffic.end()) {
1606             if (i->getId() == id) {
1607                 break;
1608             }
1609             i++;
1610         }
1611     }
1612     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1613         SG_LOG(SG_GENERAL, SG_ALERT,
1614                "AI error: checking ATC instruction for aircraft without traffic record");
1615     } else {
1616         return i->hasInstruction();
1617     }
1618     return false;
1619 }
1620
1621
1622 FGATCInstruction FGApproachController::getInstruction(int id)
1623 {
1624     TrafficVectorIterator i = activeTraffic.begin();
1625     // Search search if the current id has an entry
1626     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1627     if (activeTraffic.size()) {
1628         //while ((i->getId() != id) && i != activeTraffic.end()) {
1629         while (i != activeTraffic.end()) {
1630             if (i->getId() == id) {
1631                 break;
1632             }
1633             i++;
1634         }
1635     }
1636     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1637         SG_LOG(SG_GENERAL, SG_ALERT,
1638                "AI error: requesting ATC instruction for aircraft without traffic record");
1639     } else {
1640         return i->getInstruction();
1641     }
1642     return FGATCInstruction();
1643 }
1644
1645
1646 ActiveRunway *FGApproachController::getRunway(string name)
1647 {
1648     ActiveRunwayVecIterator rwy = activeRunways.begin();
1649     if (activeRunways.size()) {
1650         while (rwy != activeRunways.end()) {
1651             if (rwy->getRunwayName() == name) {
1652                 break;
1653             }
1654             rwy++;
1655         }
1656     }
1657     if (rwy == activeRunways.end()) {
1658         ActiveRunway aRwy(name, 0);
1659         activeRunways.push_back(aRwy);
1660         rwy = activeRunways.end() - 1;
1661     }
1662     return &(*rwy);
1663 }
1664
1665 void FGApproachController::render(bool visible) {
1666     //cerr << "FGApproachController::render function not yet implemented" << endl;
1667 }
1668
1669
1670
1671 string FGApproachController::getName() {
1672     return string(parent->getId() + "-approach");
1673 }