]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Some preparory work for enabling the handover from ground to tower controller.
[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 latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
154 {
155 }
156
157 void FGTrafficRecord::setPositionAndIntentions(int pos,
158                                                FGAIFlightPlan * route)
159 {
160
161     currentPos = pos;
162     if (intentions.size()) {
163         intVecIterator i = intentions.begin();
164         if ((*i) != pos) {
165             SG_LOG(SG_GENERAL, SG_ALERT,
166                    "Error in FGTrafficRecord::setPositionAndIntentions");
167             //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
168             for (intVecIterator i = intentions.begin();
169                  i != intentions.end(); i++) {
170                 //cerr << (*i) << " ";
171             }
172             //cerr << endl;
173         }
174         intentions.erase(i);
175     } else {
176         //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
177         int size = route->getNrOfWayPoints();
178         //cerr << "Setting pos" << pos << " ";
179         //cerr << "setting intentions ";
180         for (int i = 0; i < size; i++) {
181             int val = route->getRouteIndex(i);
182             //cerr << val<< " ";
183             if ((val) && (val != pos)) {
184                 intentions.push_back(val);
185                 //cerr << "[set] ";
186             }
187         }
188         //cerr << endl;
189         //while (route->next(&legNr, &routeNr)) {
190         //intentions.push_back(routeNr);
191         //}
192         //route->rewind(currentPos);
193     }
194     //exit(1);
195 }
196
197 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
198 {
199     bool result = false;
200     //cerr << "Start check 1" << endl;
201     if (currentPos == other.currentPos) {
202         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
203         result = true;
204     }
205     //  else if (other.intentions.size()) 
206     //     {
207     //       cerr << "Start check 2" << endl;
208     //       intVecIterator i = other.intentions.begin(); 
209     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
210     //     i++;
211     //       if (i != other.intentions.end()) {
212     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
213     //     result = true;
214     //       }
215     else if (intentions.size()) {
216         //cerr << "Start check 3" << endl;
217         intVecIterator i = intentions.begin();
218         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
219         while (i != intentions.end()) {
220             if ((*i) == other.currentPos) {
221                 break;
222             }
223             i++;
224         }
225         if (i != intentions.end()) {
226             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
227             result = true;
228         }
229     }
230     //cerr << "Done !!" << endl;
231     return result;
232 }
233
234 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
235                                             double hdg, double spd,
236                                             double alt)
237 {
238     latitude = lat;
239     longitude = lon;
240     heading = hdg;
241     speed = spd;
242     altitude = alt;
243 }
244
245 int FGTrafficRecord::crosses(FGGroundNetwork * net,
246                              FGTrafficRecord & other)
247 {
248     if (checkPositionAndIntentions(other)
249         || (other.checkPositionAndIntentions(*this)))
250         return -1;
251     intVecIterator i, j;
252     int currentTargetNode = 0, otherTargetNode = 0;
253     if (currentPos > 0)
254         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,... 
255     if (other.currentPos > 0)
256         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
257     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
258         return currentTargetNode;
259     if (intentions.size()) {
260         for (i = intentions.begin(); i != intentions.end(); i++) {
261             if ((*i) > 0) {
262                 if ((currentTargetNode ==
263                      net->findSegment(*i)->getEnd()->getIndex())) {
264                     //cerr << "Current crosses at " << currentTargetNode <<endl;
265                     return currentTargetNode;
266                 }
267             }
268         }
269     }
270     if (other.intentions.size()) {
271         for (i = other.intentions.begin(); i != other.intentions.end();
272              i++) {
273             if ((*i) > 0) {
274                 if (otherTargetNode ==
275                     net->findSegment(*i)->getEnd()->getIndex()) {
276                     //cerr << "Other crosses at " << currentTargetNode <<endl;
277                     return otherTargetNode;
278                 }
279             }
280         }
281     }
282     if (intentions.size() && other.intentions.size()) {
283         for (i = intentions.begin(); i != intentions.end(); i++) {
284             for (j = other.intentions.begin(); j != other.intentions.end();
285                  j++) {
286                 //cerr << "finding segment " << *i << " and " << *j << endl;
287                 if (((*i) > 0) && ((*j) > 0)) {
288                     currentTargetNode =
289                         net->findSegment(*i)->getEnd()->getIndex();
290                     otherTargetNode =
291                         net->findSegment(*j)->getEnd()->getIndex();
292                     if (currentTargetNode == otherTargetNode) {
293                         //cerr << "Routes will cross at " << currentTargetNode << endl;
294                         return currentTargetNode;
295                     }
296                 }
297             }
298         }
299     }
300     return -1;
301 }
302
303 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
304                               FGTrafficRecord & other)
305 {
306     int node = -1, othernode = -1;
307     if (currentPos > 0)
308         node = net->findSegment(currentPos)->getEnd()->getIndex();
309     if (other.currentPos > 0)
310         othernode =
311             net->findSegment(other.currentPos)->getEnd()->getIndex();
312     if ((node == othernode) && (node != -1))
313         return true;
314     if (other.intentions.size()) {
315         for (intVecIterator i = other.intentions.begin();
316              i != other.intentions.end(); i++) {
317             if (*i > 0) {
318                 othernode = net->findSegment(*i)->getEnd()->getIndex();
319                 if ((node == othernode) && (node > -1))
320                     return true;
321             }
322         }
323     }
324     //if (other.currentPos > 0)
325     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
326     //if (intentions.size())
327     //  {
328     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
329     //    {
330     //      if (*i > 0) 
331     //        {
332     //          node = net->findSegment(*i)->getEnd()->getIndex();
333     //          if ((node == othernode) && (node > -1))
334     //            return true;
335     //        }
336     //    }
337     //  }
338     return false;
339 }
340
341
342 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
343                                  FGTrafficRecord & other, int node)
344 {
345     // Check if current segment is the reverse segment for the other aircraft
346     FGTaxiSegment *opp;
347     //cerr << "Current segment " << currentPos << endl;
348     if ((currentPos > 0) && (other.currentPos > 0)) {
349         opp = net->findSegment(currentPos)->opposite();
350         if (opp) {
351             if (opp->getIndex() == other.currentPos)
352                 return true;
353         }
354
355         for (intVecIterator i = intentions.begin(); i != intentions.end();
356              i++) {
357             if ((opp = net->findSegment(other.currentPos)->opposite())) {
358                 if ((*i) > 0)
359                     if (opp->getIndex() ==
360                         net->findSegment(*i)->getIndex()) {
361                         if (net->findSegment(*i)->getStart()->getIndex() ==
362                             node) {
363                             {
364                                 //cerr << "Found the node " << node << endl;
365                                 return true;
366                             }
367                         }
368                     }
369             }
370             if (other.intentions.size()) {
371                 for (intVecIterator j = other.intentions.begin();
372                      j != other.intentions.end(); j++) {
373                     // cerr << "Current segment 1 " << (*i) << endl;
374                     if ((*i) > 0) {
375                         if ((opp = net->findSegment(*i)->opposite())) {
376                             if (opp->getIndex() ==
377                                 net->findSegment(*j)->getIndex()) {
378                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
379                                 //   << " and  " << net->findSegment(*j)->getIndex()
380                                 //   << " are opposites " << endl;
381                                 if (net->findSegment(*i)->getStart()->
382                                     getIndex() == node) {
383                                     {
384                                         //cerr << "Found the node " << node << endl;
385                                         return true;
386                                     }
387                                 }
388                             }
389                         }
390                     }
391                 }
392             }
393         }
394     }
395     return false;
396 }
397
398 void FGTrafficRecord::setSpeedAdjustment(double spd)
399 {
400     instruction.setChangeSpeed(true);
401     instruction.setSpeed(spd);
402 }
403
404 void FGTrafficRecord::setHeadingAdjustment(double heading)
405 {
406     instruction.setChangeHeading(true);
407     instruction.setHeading(heading);
408 }
409
410 bool FGTrafficRecord::pushBackAllowed()
411 {
412     // With the user ATC / AI integration, checking whether the user's aircraft is near no longer works, because
413     // this will effectively block the user's aircraft itself from receiving pushback clearance. 
414     // So, what can we do?
415     /*
416     double course, az2, dist;
417     SGGeod curr(SGGeod::fromDegM(getLongitude(),
418                                  getLatitude(), getAltitude()));
419
420     double userLatitude = fgGetDouble("/position/latitude-deg");
421     double userLongitude = fgGetDouble("/position/longitude-deg");
422     SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
423     SGGeodesy::inverse(curr, user, course, az2, dist);
424     //cerr << "Distance to user : " << dist << endl;
425     return (dist > 250);
426     */
427
428
429     // In essence, we should check whether the pusbback route itself, as well as the associcated
430     // taxiways near the pushback point are free of traffic. 
431     // To do so, we need to 
432     return true;
433 }
434
435
436
437 /***************************************************************************
438  * FGATCInstruction
439  *
440  **************************************************************************/
441 FGATCInstruction::FGATCInstruction()
442 {
443     holdPattern = false;
444     holdPosition = false;
445     changeSpeed = false;
446     changeHeading = false;
447     changeAltitude = false;
448     resolveCircularWait = false;
449
450     speed = 0;
451     heading = 0;
452     alt = 0;
453 }
454
455
456 bool FGATCInstruction::hasInstruction()
457 {
458     return (holdPattern || holdPosition || changeSpeed || changeHeading
459             || changeAltitude || resolveCircularWait);
460 }
461
462 /***************************************************************************
463  * FGATCController
464  *
465  **************************************************************************/
466
467
468
469
470 FGATCController::FGATCController()
471 {
472     //cerr << "running FGATController constructor" << endl;
473     dt_count = 0;
474     available = true;
475     lastTransmission = 0;
476     initialized = false;
477 }
478
479 FGATCController::~FGATCController()
480 {
481      //cerr << "running FGATController destructor" << endl;
482 }
483
484 string FGATCController::getGateName(FGAIAircraft * ref)
485 {
486     return ref->atGate();
487 }
488
489 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
490
491     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
492 };
493
494 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
495                                AtcMsgDir msgDir, bool audible)
496 {
497     string sender, receiver;
498     int stationFreq = 0;
499     int taxiFreq = 0;
500     int freqId = 0;
501     string atisInformation;
502     string text;
503     string taxiFreqStr;
504     double heading = 0;
505     string activeRunway;
506     string fltType;
507     string rwyClass;
508     string SID;
509     string transponderCode;
510     FGAIFlightPlan *fp;
511     string fltRules;
512
513     //double commFreqD;
514     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
515     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
516     switch (rec->getLeg()) {
517     case 1:
518     case 2:
519         freqId = rec->getNextFrequency();
520         stationFreq =
521             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
522             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
523         taxiFreq =
524             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
525             getDynamics()->getGroundFrequency(2);
526         receiver =
527             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
528             getName() + "-Ground";
529         atisInformation =
530             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
531             getDynamics()->getAtisSequence();
532         break;
533     case 3:
534         receiver =
535             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
536             getName() + "-Tower";
537         break;
538     }
539     // Swap sender and receiver value in case of a ground to air transmission
540     if (msgDir == ATC_GROUND_TO_AIR) {
541         string tmp = sender;
542         sender = receiver;
543         receiver = tmp;
544     }
545     switch (msgId) {
546     case MSG_ANNOUNCE_ENGINE_START:
547         text = sender + ". Ready to Start up";
548         break;
549     case MSG_REQUEST_ENGINE_START:
550         text =
551             receiver + ", This is " + sender + ". Position " +
552             getGateName(rec->getAircraft()) + ". Information " +
553             atisInformation + ". " +
554             rec->getAircraft()->getTrafficRef()->getFlightRules() +
555             " to " +
556             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
557             getName() + ". Request start-up";
558         break;
559         // Acknowledge engine startup permission
560         // Assign departure runway
561         // Assign SID, if necessery (TODO)
562     case MSG_PERMIT_ENGINE_START:
563         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
564
565         heading = rec->getAircraft()->getTrafficRef()->getCourse();
566         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
567         rwyClass =
568             rec->getAircraft()->GetFlightPlan()->
569             getRunwayClassFromTrafficType(fltType);
570
571         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
572             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
573                                            heading);
574         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
575         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
576             getDynamics()->getSID(activeRunway, heading);
577         rec->getAircraft()->GetFlightPlan()->setSID(fp);
578         if (fp) {
579             SID = fp->getName() + " departure";
580         } else {
581             SID = "fly runway heading ";
582         }
583         //snprintf(buffer, 7, "%3.2f", heading);
584         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
585         transponderCode = genTransponderCode(fltRules);
586         rec->getAircraft()->SetTransponderCode(transponderCode);
587         text =
588             receiver + ". Start-up approved. " + atisInformation +
589             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
590             transponderCode + ". " +
591             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
592             sender + " control.";
593         break;
594     case MSG_DENY_ENGINE_START:
595         text = receiver + ". Standby";
596         break;
597     case MSG_ACKNOWLEDGE_ENGINE_START:
598         fp = rec->getAircraft()->GetFlightPlan()->getSID();
599         if (fp) {
600             SID =
601                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
602                 " departure";
603         } else {
604             SID = "fly runway heading ";
605         }
606         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
607         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
608         transponderCode = rec->getAircraft()->GetTransponderCode();
609         text =
610             receiver + ". Start-up approved. " + atisInformation +
611             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
612             transponderCode + ". " +
613             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
614             sender;
615         break;
616     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
617         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
618         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
619         break;
620     case MSG_INITIATE_CONTACT:
621         text = receiver + ". With you. " + sender;
622         break;
623     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
624         text = receiver + ". Roger. " + sender;
625         break;
626     case MSG_REQUEST_PUSHBACK_CLEARANCE:
627         text = receiver + ". Request push-back. " + sender;
628         break;
629     case MSG_PERMIT_PUSHBACK_CLEARANCE:
630         text = receiver + ". Push-back approved. " + sender;
631         break;
632     case MSG_HOLD_PUSHBACK_CLEARANCE:
633         text = receiver + ". Standby. " + sender;
634         break;
635     case MSG_REQUEST_TAXI_CLEARANCE:
636         text = receiver + ". Ready to Taxi. " + sender;
637         break;
638     case MSG_ISSUE_TAXI_CLEARANCE:
639         text = receiver + ". Cleared to taxi. " + sender;
640         break;
641     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
642         text = receiver + ". Cleared to taxi. " + sender;
643         break;
644     case MSG_HOLD_POSITION:
645         text = receiver + ". Hold Position. " + sender;
646         break;
647     case MSG_ACKNOWLEDGE_HOLD_POSITION:
648         text = receiver + ". Holding Position. " + sender;
649         break;
650     case MSG_RESUME_TAXI:
651         text = receiver + ". Resume Taxiing. " + sender;
652         break;
653     case MSG_ACKNOWLEDGE_RESUME_TAXI:
654         text = receiver + ". Continuing Taxi. " + sender;
655         break;
656     default:
657         text = text + sender + ". Transmitting unknown Message";
658         break;
659     }
660     if (audible) {
661         double onBoardRadioFreq0 =
662             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
663         double onBoardRadioFreq1 =
664             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
665         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
666         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
667         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
668
669         // Display ATC message only when one of the radios is tuned
670         // the relevant frequency.
671         // Note that distance attenuation is currently not yet implemented
672         if ((onBoardRadioFreqI0 == stationFreq)
673             || (onBoardRadioFreqI1 == stationFreq)) {
674             if (rec->allowTransmissions()) {
675                 fgSetString("/sim/messages/atc", text.c_str());
676             }
677         }
678     } else {
679         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
680         atc->getATCDialog()->addEntry(1, text);
681         
682     }
683 }
684
685 string FGATCController::formatATCFrequency3_2(int freq)
686 {
687     char buffer[7];
688     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
689     return string(buffer);
690 }
691
692 // TODO: Set transponder codes according to real-world routes.
693 // The current version just returns a random string of four octal numbers. 
694 string FGATCController::genTransponderCode(string fltRules)
695 {
696     if (fltRules == "VFR") {
697         return string("1200");
698     } else {
699         char buffer[5];
700         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
701                  rand() % 8);
702         return string(buffer);
703     }
704 }
705
706 void FGATCController::init() 
707 {
708    if (!initialized) {
709        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
710        mgr->addController(this);
711        initialized = true;
712     }
713 }
714
715 /***************************************************************************
716  * class FGTowerController
717  *
718  **************************************************************************/
719 FGTowerController::FGTowerController(FGAirportDynamics *par) :
720 FGATCController()
721 {
722     parent = par;
723 }
724
725 // 
726 void FGTowerController::announcePosition(int id,
727                                          FGAIFlightPlan * intendedRoute,
728                                          int currentPosition, double lat,
729                                          double lon, double heading,
730                                          double speed, double alt,
731                                          double radius, int leg,
732                                          FGAIAircraft * ref)
733 {
734     init();
735     TrafficVectorIterator i = activeTraffic.begin();
736     // Search whether the current id alread has an entry
737     // This might be faster using a map instead of a vector, but let's start by taking a safe route
738     if (activeTraffic.size()) {
739         //while ((i->getId() != id) && i != activeTraffic.end()) {
740         while (i != activeTraffic.end()) {
741             if (i->getId() == id) {
742                 break;
743             }
744             i++;
745         }
746     }
747     // Add a new TrafficRecord if no one exsists for this aircraft.
748     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
749         FGTrafficRecord rec;
750         rec.setId(id);
751
752         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
753         rec.setRunway(intendedRoute->getRunway());
754         rec.setLeg(leg);
755         //rec.setCallSign(callsign);
756         rec.setAircraft(ref);
757         activeTraffic.push_back(rec);
758         cerr << ref->getTrafficRef()->getCallSign() << " You are number " << activeTraffic.size() <<  " for takeoff " << endl;
759     } else {
760         i->setPositionAndHeading(lat, lon, heading, speed, alt);
761     }
762 }
763
764 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
765                                                   double heading, double speed, double alt,
766                                                   double dt)
767 {
768     TrafficVectorIterator i = activeTraffic.begin();
769     // Search whether the current id has an entry
770     // This might be faster using a map instead of a vector, but let's start by taking a safe route
771     TrafficVectorIterator current, closest;
772     if (activeTraffic.size()) {
773         //while ((i->getId() != id) && i != activeTraffic.end()) {
774         while (i != activeTraffic.end()) {
775             if (i->getId() == id) {
776                 break;
777             }
778             i++;
779         }
780     }
781 //    // update position of the current aircraft
782     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
783         SG_LOG(SG_GENERAL, SG_ALERT,
784                "AI error: updating aircraft without traffic record");
785     } else {
786         i->setPositionAndHeading(lat, lon, heading, speed, alt);
787         current = i;
788     }
789     setDt(getDt() + dt);
790
791 //    // see if we already have a clearance record for the currently active runway
792     ActiveRunwayVecIterator rwy = activeRunways.begin();
793     // again, a map might be more efficient here
794     if (activeRunways.size()) {
795         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
796         while (rwy != activeRunways.end()) {
797             if (rwy->getRunwayName() == current->getRunway()) {
798                 break;
799             }
800             rwy++;
801         }
802     }
803     if (rwy == activeRunways.end()) {
804         ActiveRunway aRwy(current->getRunway(), id);
805         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
806         current->setHoldPosition(false);        // Clear the current aircraft to continue
807     } else {
808         // Okay, we have a clearance record for this runway, so check
809         // whether the clearence ID matches that of the current aircraft
810         if (id == rwy->getCleared()) {
811             current->setHoldPosition(false);
812         } else {
813             current->setHoldPosition(true);
814         }
815     }
816 }
817
818
819 void FGTowerController::signOff(int id)
820 {
821     TrafficVectorIterator i = activeTraffic.begin();
822     // Search search if the current id alread has an entry
823     // This might be faster using a map instead of a vector, but let's start by taking a safe route
824     if (activeTraffic.size()) {
825         //while ((i->getId() != id) && i != activeTraffic.end()) {
826         while (i != activeTraffic.end()) {
827             if (i->getId() == id) {
828                 break;
829             }
830             i++;
831         }
832     }
833     // If this aircraft has left the runway, we can clear the departure record for this runway
834     ActiveRunwayVecIterator rwy = activeRunways.begin();
835     if (activeRunways.size()) {
836         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
837         while (rwy != activeRunways.end()) {
838             if (rwy->getRunwayName() == i->getRunway()) {
839                 break;
840             }
841             rwy++;
842         }
843         if (rwy != activeRunways.end()) {
844             rwy = activeRunways.erase(rwy);
845         } else {
846             SG_LOG(SG_GENERAL, SG_ALERT,
847                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
848         }
849     }
850     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
851         SG_LOG(SG_GENERAL, SG_ALERT,
852                "AI error: Aircraft without traffic record is signing off from tower");
853     } else {
854         i = activeTraffic.erase(i);
855         //cerr << "Signing off from tower controller" << endl;
856     }
857 }
858
859 // NOTE:
860 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
861 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
862 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
863 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
864 // Note that this function is probably obsolete
865 bool FGTowerController::hasInstruction(int id)
866 {
867     TrafficVectorIterator i = activeTraffic.begin();
868     // Search search if the current id has an entry
869     // This might be faster using a map instead of a vector, but let's start by taking a safe route
870     if (activeTraffic.size()) {
871         //while ((i->getId() != id) && i != activeTraffic.end()) {
872         while (i != activeTraffic.end()) {
873             if (i->getId() == id) {
874                 break;
875             }
876             i++;
877         }
878     }
879     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
880         SG_LOG(SG_GENERAL, SG_ALERT,
881                "AI error: checking ATC instruction for aircraft without traffic record");
882     } else {
883         return i->hasInstruction();
884     }
885     return false;
886 }
887
888
889 FGATCInstruction FGTowerController::getInstruction(int id)
890 {
891     TrafficVectorIterator i = activeTraffic.begin();
892     // Search search if the current id has an entry
893     // This might be faster using a map instead of a vector, but let's start by taking a safe route
894     if (activeTraffic.size()) {
895         //while ((i->getId() != id) && i != activeTraffic.end()) {
896         while (i != activeTraffic.end()) {
897             if (i->getId() == id) {
898                 break;
899             }
900             i++;
901         }
902     }
903     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
904         SG_LOG(SG_GENERAL, SG_ALERT,
905                "AI error: requesting ATC instruction for aircraft without traffic record");
906     } else {
907         return i->getInstruction();
908     }
909     return FGATCInstruction();
910 }
911
912 void FGTowerController::render(bool visible) {
913     //cerr << "FGTowerController::render function not yet implemented" << endl;
914 }
915
916 string FGTowerController::getName() {
917     return string(parent->getId() + "-tower");
918 }
919
920
921
922 /***************************************************************************
923  * class FGStartupController
924  *
925  **************************************************************************/
926 FGStartupController::FGStartupController(FGAirportDynamics *par):
927     FGATCController()
928 {
929     parent = par;
930 }
931
932 void FGStartupController::announcePosition(int id,
933                                            FGAIFlightPlan * intendedRoute,
934                                            int currentPosition, double lat,
935                                            double lon, double heading,
936                                            double speed, double alt,
937                                            double radius, int leg,
938                                            FGAIAircraft * ref)
939 {
940     init();
941     TrafficVectorIterator i = activeTraffic.begin();
942     // Search whether the current id alread has an entry
943     // This might be faster using a map instead of a vector, but let's start by taking a safe route
944     if (activeTraffic.size()) {
945         //while ((i->getId() != id) && i != activeTraffic.end()) {
946         while (i != activeTraffic.end()) {
947             if (i->getId() == id) {
948                 break;
949             }
950             i++;
951         }
952     }
953     // Add a new TrafficRecord if no one exsists for this aircraft.
954     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
955         FGTrafficRecord rec;
956         rec.setId(id);
957
958         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
959         rec.setRunway(intendedRoute->getRunway());
960         rec.setLeg(leg);
961         rec.setPositionAndIntentions(currentPosition, intendedRoute);
962         //rec.setCallSign(callsign);
963         rec.setAircraft(ref);
964         rec.setHoldPosition(true);
965         activeTraffic.push_back(rec);
966     } else {
967         i->setPositionAndIntentions(currentPosition, intendedRoute);
968         i->setPositionAndHeading(lat, lon, heading, speed, alt);
969
970     }
971 }
972
973 // NOTE:
974 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
975 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
976 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
977 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
978 // Note that this function is probably obsolete
979 bool FGStartupController::hasInstruction(int id)
980 {
981     TrafficVectorIterator i = activeTraffic.begin();
982     // Search search if the current id has an entry
983     // This might be faster using a map instead of a vector, but let's start by taking a safe route
984     if (activeTraffic.size()) {
985         //while ((i->getId() != id) && i != activeTraffic.end()) {
986         while (i != activeTraffic.end()) {
987             if (i->getId() == id) {
988                 break;
989             }
990             i++;
991         }
992     }
993     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
994         SG_LOG(SG_GENERAL, SG_ALERT,
995                "AI error: checking ATC instruction for aircraft without traffic record");
996     } else {
997         return i->hasInstruction();
998     }
999     return false;
1000 }
1001
1002
1003 FGATCInstruction FGStartupController::getInstruction(int id)
1004 {
1005     TrafficVectorIterator i = activeTraffic.begin();
1006     // Search search if the current id has an entry
1007     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1008     if (activeTraffic.size()) {
1009         //while ((i->getId() != id) && i != activeTraffic.end()) {
1010         while (i != activeTraffic.end()) {
1011             if (i->getId() == id) {
1012                 break;
1013             }
1014             i++;
1015         }
1016     }
1017     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1018         SG_LOG(SG_GENERAL, SG_ALERT,
1019                "AI error: requesting ATC instruction for aircraft without traffic record");
1020     } else {
1021         return i->getInstruction();
1022     }
1023     return FGATCInstruction();
1024 }
1025
1026 void FGStartupController::signOff(int id)
1027 {
1028     TrafficVectorIterator i = activeTraffic.begin();
1029     // Search search if the current id alread has an entry
1030     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1031     if (activeTraffic.size()) {
1032         //while ((i->getId() != id) && i != activeTraffic.end()) {
1033         while (i != activeTraffic.end()) {
1034             if (i->getId() == id) {
1035                 break;
1036             }
1037             i++;
1038         }
1039     }
1040     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1041         SG_LOG(SG_GENERAL, SG_ALERT,
1042                "AI error: Aircraft without traffic record is signing off from tower");
1043     } else {
1044         //cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1045         i = activeTraffic.erase(i);
1046     }
1047 }
1048
1049 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1050                                AtcMsgDir msgDir)
1051 {
1052     int state = i->getState();
1053     if ((state == st) && available) {
1054         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1055             
1056             //cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1057             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1058             int n = trans_num->getIntValue();
1059             if (n == 0) {
1060                 trans_num->setIntValue(-1);
1061                  // PopupCallback(n);
1062                  //cerr << "Selected transmission message " << n << endl;
1063                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1064                  atc->getATCDialog()->removeEntry(1);
1065             } else {
1066                 //cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1067                 transmit(&(*i), msgId, msgDir, false);
1068                 return false;
1069             }
1070         }
1071         if (now > startTime) {
1072             //cerr << "Transmitting startup msg" << endl;
1073             transmit(&(*i), msgId, msgDir, true);
1074             i->updateState();
1075             lastTransmission = now;
1076             available = false;
1077             return true;
1078         }
1079     }
1080     return false;
1081 }
1082
1083 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1084                                                     double heading, double speed, double alt,
1085                                                     double dt)
1086 {
1087     TrafficVectorIterator i = activeTraffic.begin();
1088     // Search search if the current id has an entry
1089     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1090     TrafficVectorIterator current, closest;
1091     if (activeTraffic.size()) {
1092         //while ((i->getId() != id) && i != activeTraffic.end()) {
1093         while (i != activeTraffic.end()) {
1094             if (i->getId() == id) {
1095                 break;
1096             }
1097             i++;
1098         }
1099     }
1100 //    // update position of the current aircraft
1101
1102     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1103         SG_LOG(SG_GENERAL, SG_ALERT,
1104                "AI error: updating aircraft without traffic record");
1105     } else {
1106         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1107         current = i;
1108     }
1109     setDt(getDt() + dt);
1110
1111     int state = i->getState();
1112
1113     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1114     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1115     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1116     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1117     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1118     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1119     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1120
1121     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1122         available = true;
1123     }
1124
1125     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1126     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1127     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1128     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1129     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1130         i->nextFrequency();
1131     }
1132     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1133     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1134     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1135
1136
1137    
1138     if ((state == 8) && available) {
1139         if (now > startTime + 200) {
1140             if (i->pushBackAllowed()) {
1141                 i->allowRepeatedTransmissions();
1142                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1143                          ATC_GROUND_TO_AIR, true);
1144                 i->updateState();
1145             } else {
1146                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1147                          ATC_GROUND_TO_AIR, true);
1148                 i->suppressRepeatedTransmissions();
1149             }
1150             lastTransmission = now;
1151             available = false;
1152         }
1153     }
1154     if ((state == 9) && available) {
1155         i->setHoldPosition(false);
1156     }
1157 }
1158
1159 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1160 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1161                             double lon, double elev, double hdg)
1162 {
1163     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1164     obj_pos = geod.makeZUpFrame();
1165     // hdg is not a compass heading, but a counter-clockwise rotation
1166     // around the Z axis
1167     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1168                                         0.0, 0.0, 1.0));
1169 }
1170
1171
1172 void FGStartupController::render(bool visible)
1173 {
1174
1175     SGMaterialLib *matlib = globals->get_matlib();
1176     if (group) {
1177         //int nr = ;
1178         globals->get_scenery()->get_scene_graph()->removeChild(group);
1179         //while (group->getNumChildren()) {
1180         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1181         simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1182           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1183            //geode->releaseGLObjects();
1184            //group->removeChild(geode);
1185            //delete geode;
1186         group = 0;
1187     }
1188     if (visible) {
1189         group = new osg::Group;
1190
1191         //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1192         double dx = 0;
1193         for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1194             // Handle start point
1195             int pos = i->getCurrentPosition();
1196             //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1197             if (pos > 0) {
1198                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1199                 SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1200                 SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1201
1202                 double length = SGGeodesy::distanceM(start, end);
1203                 //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1204
1205                 double az2, heading; //, distanceM;
1206                 SGGeodesy::inverse(start, end, heading, az2, length);
1207                 double coveredDistance = length * 0.5;
1208                 SGGeod center;
1209                 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1210                 //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1211                 ///////////////////////////////////////////////////////////////////////////////
1212                 // Make a helper function out of this
1213                 osg::Matrix obj_pos;
1214                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1215                 obj_trans->setDataVariance(osg::Object::STATIC);
1216
1217                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1218
1219                 obj_trans->setMatrix( obj_pos );
1220                 //osg::Vec3 center(0, 0, 0)
1221
1222                 float width = length /2.0;
1223                 osg::Vec3 corner(-width, 0, 0.25f);
1224                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1225                 osg::Vec3 heightVec(0, 1, 0);
1226                 osg::Geometry* geometry;
1227                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1228                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1229                 geode->setName("test");
1230                 geode->addDrawable(geometry);
1231                 //osg::Node *custom_obj;
1232                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1233                 if (mat)
1234                     geode->setEffect(mat->get_effect());
1235                 obj_trans->addChild(geode);
1236                 // wire as much of the scene graph together as we can
1237                 //->addChild( obj_trans );
1238                 group->addChild( obj_trans );
1239                 /////////////////////////////////////////////////////////////////////
1240             } else {
1241                 //cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1242             }
1243             for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1244                 osg::Matrix obj_pos;
1245                 int k = (*j);
1246                 if (k > 0) {
1247                     //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1248                     osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1249                     obj_trans->setDataVariance(osg::Object::STATIC);
1250                     FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1251                     WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1252
1253                     obj_trans->setMatrix( obj_pos );
1254                     //osg::Vec3 center(0, 0, 0)
1255
1256                     float width = segment->getLength() /2.0;
1257                     osg::Vec3 corner(-width, 0, 0.25f);
1258                     osg::Vec3 widthVec(2*width + 1, 0, 0);
1259                     osg::Vec3 heightVec(0, 1, 0);
1260                     osg::Geometry* geometry;
1261                     geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1262                     simgear::EffectGeode* geode = new simgear::EffectGeode;
1263                     geode->setName("test");
1264                     geode->addDrawable(geometry);
1265                     //osg::Node *custom_obj;
1266                     SGMaterial *mat = matlib->find("UnidirectionalTaper");
1267                     if (mat)
1268                         geode->setEffect(mat->get_effect());
1269                     obj_trans->addChild(geode);
1270                     // wire as much of the scene graph together as we can
1271                     //->addChild( obj_trans );
1272                     group->addChild( obj_trans );
1273                 } else {
1274                     //cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1275                 }
1276             }
1277             //dx += 0.1;
1278         }
1279         globals->get_scenery()->get_scene_graph()->addChild(group);
1280     }
1281 }
1282
1283 string FGStartupController::getName() {
1284     return string(parent->getId() + "-startup");
1285 }
1286
1287
1288 /***************************************************************************
1289  * class FGApproachController
1290  *
1291  **************************************************************************/
1292 FGApproachController::FGApproachController(FGAirportDynamics *par):
1293 FGATCController()
1294 {
1295     parent = par;
1296 }
1297
1298 // 
1299 void FGApproachController::announcePosition(int id,
1300                                             FGAIFlightPlan * intendedRoute,
1301                                             int currentPosition,
1302                                             double lat, double lon,
1303                                             double heading, double speed,
1304                                             double alt, double radius,
1305                                             int leg, FGAIAircraft * ref)
1306 {
1307     init();
1308     TrafficVectorIterator i = activeTraffic.begin();
1309     // Search whether the current id alread has an entry
1310     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1311     if (activeTraffic.size()) {
1312         //while ((i->getId() != id) && i != activeTraffic.end()) {
1313         while (i != activeTraffic.end()) {
1314             if (i->getId() == id) {
1315                 break;
1316             }
1317             i++;
1318         }
1319     }
1320     // Add a new TrafficRecord if no one exsists for this aircraft.
1321     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1322         FGTrafficRecord rec;
1323         rec.setId(id);
1324
1325         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1326         rec.setRunway(intendedRoute->getRunway());
1327         rec.setLeg(leg);
1328         //rec.setCallSign(callsign);
1329         rec.setAircraft(ref);
1330         activeTraffic.push_back(rec);
1331     } else {
1332         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1333     }
1334 }
1335
1336 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1337                                                      double heading, double speed, double alt,
1338                                                      double dt)
1339 {
1340     TrafficVectorIterator i = activeTraffic.begin();
1341     // Search search if the current id has an entry
1342     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1343     TrafficVectorIterator current, closest;
1344     if (activeTraffic.size()) {
1345         //while ((i->getId() != id) && i != activeTraffic.end()) {
1346         while (i != activeTraffic.end()) {
1347             if (i->getId() == id) {
1348                 break;
1349             }
1350             i++;
1351         }
1352     }
1353 //    // update position of the current aircraft
1354     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1355         SG_LOG(SG_GENERAL, SG_ALERT,
1356                "AI error: updating aircraft without traffic record");
1357     } else {
1358         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1359         current = i;
1360         //cerr << "ApproachController: checking for speed" << endl;
1361         time_t time_diff =
1362             current->getAircraft()->
1363             checkForArrivalTime(string("final001"));
1364         if (time_diff > 15) {
1365             current->setSpeedAdjustment(current->getAircraft()->
1366                                         getPerformance()->vDescent() *
1367                                         1.35);
1368         } else if (time_diff > 5) {
1369             current->setSpeedAdjustment(current->getAircraft()->
1370                                         getPerformance()->vDescent() *
1371                                         1.2);
1372         } else if (time_diff < -15) {
1373             current->setSpeedAdjustment(current->getAircraft()->
1374                                         getPerformance()->vDescent() *
1375                                         0.65);
1376         } else if (time_diff < -5) {
1377             current->setSpeedAdjustment(current->getAircraft()->
1378                                         getPerformance()->vDescent() *
1379                                         0.8);
1380         } else {
1381             current->clearSpeedAdjustment();
1382         }
1383         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1384     }
1385     setDt(getDt() + dt);
1386 }
1387
1388 void FGApproachController::signOff(int id)
1389 {
1390     TrafficVectorIterator i = activeTraffic.begin();
1391     // Search search if the current id alread has an entry
1392     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1393     if (activeTraffic.size()) {
1394         //while ((i->getId() != id) && i != activeTraffic.end()) {
1395         while (i != activeTraffic.end()) {
1396             if (i->getId() == id) {
1397                 break;
1398             }
1399             i++;
1400         }
1401     }
1402     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1403         SG_LOG(SG_GENERAL, SG_ALERT,
1404                "AI error: Aircraft without traffic record is signing off from approach");
1405     } else {
1406         i = activeTraffic.erase(i);
1407     }
1408 }
1409
1410
1411
1412
1413 bool FGApproachController::hasInstruction(int id)
1414 {
1415     TrafficVectorIterator i = activeTraffic.begin();
1416     // Search search if the current id has an entry
1417     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1418     if (activeTraffic.size()) {
1419         //while ((i->getId() != id) && i != activeTraffic.end()) {
1420         while (i != activeTraffic.end()) {
1421             if (i->getId() == id) {
1422                 break;
1423             }
1424             i++;
1425         }
1426     }
1427     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1428         SG_LOG(SG_GENERAL, SG_ALERT,
1429                "AI error: checking ATC instruction for aircraft without traffic record");
1430     } else {
1431         return i->hasInstruction();
1432     }
1433     return false;
1434 }
1435
1436
1437 FGATCInstruction FGApproachController::getInstruction(int id)
1438 {
1439     TrafficVectorIterator i = activeTraffic.begin();
1440     // Search search if the current id has an entry
1441     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1442     if (activeTraffic.size()) {
1443         //while ((i->getId() != id) && i != activeTraffic.end()) {
1444         while (i != activeTraffic.end()) {
1445             if (i->getId() == id) {
1446                 break;
1447             }
1448             i++;
1449         }
1450     }
1451     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1452         SG_LOG(SG_GENERAL, SG_ALERT,
1453                "AI error: requesting ATC instruction for aircraft without traffic record");
1454     } else {
1455         return i->getInstruction();
1456     }
1457     return FGATCInstruction();
1458 }
1459
1460
1461 ActiveRunway *FGApproachController::getRunway(string name)
1462 {
1463     ActiveRunwayVecIterator rwy = activeRunways.begin();
1464     if (activeRunways.size()) {
1465         while (rwy != activeRunways.end()) {
1466             if (rwy->getRunwayName() == name) {
1467                 break;
1468             }
1469             rwy++;
1470         }
1471     }
1472     if (rwy == activeRunways.end()) {
1473         ActiveRunway aRwy(name, 0);
1474         activeRunways.push_back(aRwy);
1475         rwy = activeRunways.end() - 1;
1476     }
1477     return &(*rwy);
1478 }
1479
1480 void FGApproachController::render(bool visible) {
1481     //cerr << "FGApproachController::render function not yet implemented" << endl;
1482 }
1483
1484
1485
1486 string FGApproachController::getName() {
1487     return string(parent->getId() + "-approach");
1488 }