]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Merge branch 'next' into durk-atc
[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 slow 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 2:
518     case 3:
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(3);
526         receiver =
527             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
528             getName() + "-Ground";
529         atisInformation =
530             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
531             getDynamics()->getAtisSequence();
532         break;
533     case 4:
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():
720 FGATCController()
721 {
722 }
723
724 // 
725 void FGTowerController::announcePosition(int id,
726                                          FGAIFlightPlan * intendedRoute,
727                                          int currentPosition, double lat,
728                                          double lon, double heading,
729                                          double speed, double alt,
730                                          double radius, int leg,
731                                          FGAIAircraft * ref)
732 {
733     init();
734     TrafficVectorIterator i = activeTraffic.begin();
735     // Search whether the current id alread has an entry
736     // This might be faster using a map instead of a vector, but let's start by taking a safe route
737     if (activeTraffic.size()) {
738         //while ((i->getId() != id) && i != activeTraffic.end()) {
739         while (i != activeTraffic.end()) {
740             if (i->getId() == id) {
741                 break;
742             }
743             i++;
744         }
745     }
746     // Add a new TrafficRecord if no one exsists for this aircraft.
747     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
748         FGTrafficRecord rec;
749         rec.setId(id);
750
751         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
752         rec.setRunway(intendedRoute->getRunway());
753         rec.setLeg(leg);
754         //rec.setCallSign(callsign);
755         rec.setAircraft(ref);
756         activeTraffic.push_back(rec);
757     } else {
758         i->setPositionAndHeading(lat, lon, heading, speed, alt);
759     }
760 }
761
762 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
763                                                   double heading, double speed, double alt,
764                                                   double dt)
765 {
766     TrafficVectorIterator i = activeTraffic.begin();
767     // Search whether the current id has an entry
768     // This might be faster using a map instead of a vector, but let's start by taking a safe route
769     TrafficVectorIterator current, closest;
770     if (activeTraffic.size()) {
771         //while ((i->getId() != id) && i != activeTraffic.end()) {
772         while (i != activeTraffic.end()) {
773             if (i->getId() == id) {
774                 break;
775             }
776             i++;
777         }
778     }
779 //    // update position of the current aircraft
780     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
781         SG_LOG(SG_GENERAL, SG_ALERT,
782                "AI error: updating aircraft without traffic record");
783     } else {
784         i->setPositionAndHeading(lat, lon, heading, speed, alt);
785         current = i;
786     }
787     setDt(getDt() + dt);
788
789 //    // see if we already have a clearance record for the currently active runway
790     ActiveRunwayVecIterator rwy = activeRunways.begin();
791     // again, a map might be more efficient here
792     if (activeRunways.size()) {
793         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
794         while (rwy != activeRunways.end()) {
795             if (rwy->getRunwayName() == current->getRunway()) {
796                 break;
797             }
798             rwy++;
799         }
800     }
801     if (rwy == activeRunways.end()) {
802         ActiveRunway aRwy(current->getRunway(), id);
803         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
804         current->setHoldPosition(false);        // Clear the current aircraft to continue
805     } else {
806         // Okay, we have a clearance record for this runway, so check
807         // whether the clearence ID matches that of the current aircraft
808         if (id == rwy->getCleared()) {
809             current->setHoldPosition(false);
810         } else {
811             current->setHoldPosition(true);
812         }
813     }
814 }
815
816
817 void FGTowerController::signOff(int id)
818 {
819     TrafficVectorIterator i = activeTraffic.begin();
820     // Search search if the current id alread has an entry
821     // This might be faster using a map instead of a vector, but let's start by taking a safe route
822     if (activeTraffic.size()) {
823         //while ((i->getId() != id) && i != activeTraffic.end()) {
824         while (i != activeTraffic.end()) {
825             if (i->getId() == id) {
826                 break;
827             }
828             i++;
829         }
830     }
831     // If this aircraft has left the runway, we can clear the departure record for this runway
832     ActiveRunwayVecIterator rwy = activeRunways.begin();
833     if (activeRunways.size()) {
834         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
835         while (rwy != activeRunways.end()) {
836             if (rwy->getRunwayName() == i->getRunway()) {
837                 break;
838             }
839             rwy++;
840         }
841         if (rwy != activeRunways.end()) {
842             rwy = activeRunways.erase(rwy);
843         } else {
844             SG_LOG(SG_GENERAL, SG_ALERT,
845                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
846         }
847     }
848     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
849         SG_LOG(SG_GENERAL, SG_ALERT,
850                "AI error: Aircraft without traffic record is signing off from tower");
851     } else {
852         i = activeTraffic.erase(i);
853     }
854 }
855
856 // NOTE:
857 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
858 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
859 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
860 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
861 // Note that this function is probably obsolete
862 bool FGTowerController::hasInstruction(int id)
863 {
864     TrafficVectorIterator i = activeTraffic.begin();
865     // Search search if the current id has an entry
866     // This might be faster using a map instead of a vector, but let's start by taking a safe route
867     if (activeTraffic.size()) {
868         //while ((i->getId() != id) && i != activeTraffic.end()) {
869         while (i != activeTraffic.end()) {
870             if (i->getId() == id) {
871                 break;
872             }
873             i++;
874         }
875     }
876     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
877         SG_LOG(SG_GENERAL, SG_ALERT,
878                "AI error: checking ATC instruction for aircraft without traffic record");
879     } else {
880         return i->hasInstruction();
881     }
882     return false;
883 }
884
885
886 FGATCInstruction FGTowerController::getInstruction(int id)
887 {
888     TrafficVectorIterator i = activeTraffic.begin();
889     // Search search if the current id has an entry
890     // This might be faster using a map instead of a vector, but let's start by taking a safe route
891     if (activeTraffic.size()) {
892         //while ((i->getId() != id) && i != activeTraffic.end()) {
893         while (i != activeTraffic.end()) {
894             if (i->getId() == id) {
895                 break;
896             }
897             i++;
898         }
899     }
900     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
901         SG_LOG(SG_GENERAL, SG_ALERT,
902                "AI error: requesting ATC instruction for aircraft without traffic record");
903     } else {
904         return i->getInstruction();
905     }
906     return FGATCInstruction();
907 }
908
909 void FGTowerController::render() {
910     cerr << "FGTowerController::render function not yet implemented" << endl;
911 }
912
913
914 /***************************************************************************
915  * class FGStartupController
916  *
917  **************************************************************************/
918 FGStartupController::FGStartupController(FGAirportDynamics *par):
919     FGATCController()
920 {
921     parent = par;
922 }
923
924 void FGStartupController::announcePosition(int id,
925                                            FGAIFlightPlan * intendedRoute,
926                                            int currentPosition, double lat,
927                                            double lon, double heading,
928                                            double speed, double alt,
929                                            double radius, int leg,
930                                            FGAIAircraft * ref)
931 {
932     init();
933     TrafficVectorIterator i = activeTraffic.begin();
934     // Search whether the current id alread has an entry
935     // This might be faster using a map instead of a vector, but let's start by taking a safe route
936     if (activeTraffic.size()) {
937         //while ((i->getId() != id) && i != activeTraffic.end()) {
938         while (i != activeTraffic.end()) {
939             if (i->getId() == id) {
940                 break;
941             }
942             i++;
943         }
944     }
945     // Add a new TrafficRecord if no one exsists for this aircraft.
946     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
947         FGTrafficRecord rec;
948         rec.setId(id);
949
950         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
951         rec.setRunway(intendedRoute->getRunway());
952         rec.setLeg(leg);
953         rec.setPositionAndIntentions(currentPosition, intendedRoute);
954         //rec.setCallSign(callsign);
955         rec.setAircraft(ref);
956         rec.setHoldPosition(true);
957         activeTraffic.push_back(rec);
958     } else {
959         i->setPositionAndIntentions(currentPosition, intendedRoute);
960         i->setPositionAndHeading(lat, lon, heading, speed, alt);
961
962     }
963 }
964
965 // NOTE:
966 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
967 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
968 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
969 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
970 // Note that this function is probably obsolete
971 bool FGStartupController::hasInstruction(int id)
972 {
973     TrafficVectorIterator i = activeTraffic.begin();
974     // Search search if the current id has an entry
975     // This might be faster using a map instead of a vector, but let's start by taking a safe route
976     if (activeTraffic.size()) {
977         //while ((i->getId() != id) && i != activeTraffic.end()) {
978         while (i != activeTraffic.end()) {
979             if (i->getId() == id) {
980                 break;
981             }
982             i++;
983         }
984     }
985     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
986         SG_LOG(SG_GENERAL, SG_ALERT,
987                "AI error: checking ATC instruction for aircraft without traffic record");
988     } else {
989         return i->hasInstruction();
990     }
991     return false;
992 }
993
994
995 FGATCInstruction FGStartupController::getInstruction(int id)
996 {
997     TrafficVectorIterator i = activeTraffic.begin();
998     // Search search if the current id has an entry
999     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1000     if (activeTraffic.size()) {
1001         //while ((i->getId() != id) && i != activeTraffic.end()) {
1002         while (i != activeTraffic.end()) {
1003             if (i->getId() == id) {
1004                 break;
1005             }
1006             i++;
1007         }
1008     }
1009     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1010         SG_LOG(SG_GENERAL, SG_ALERT,
1011                "AI error: requesting ATC instruction for aircraft without traffic record");
1012     } else {
1013         return i->getInstruction();
1014     }
1015     return FGATCInstruction();
1016 }
1017
1018 void FGStartupController::signOff(int id)
1019 {
1020     TrafficVectorIterator i = activeTraffic.begin();
1021     // Search search if the current id alread has an entry
1022     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1023     if (activeTraffic.size()) {
1024         //while ((i->getId() != id) && i != activeTraffic.end()) {
1025         while (i != activeTraffic.end()) {
1026             if (i->getId() == id) {
1027                 break;
1028             }
1029             i++;
1030         }
1031     }
1032     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1033         SG_LOG(SG_GENERAL, SG_ALERT,
1034                "AI error: Aircraft without traffic record is signing off from tower");
1035     } else {
1036         cerr << i->getAircraft()->getCallSign() << " signing off from startupcontroller" << endl;
1037         i = activeTraffic.erase(i);
1038     }
1039 }
1040
1041 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1042                                AtcMsgDir msgDir)
1043 {
1044     int state = i->getState();
1045     if ((state == st) && available) {
1046         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1047             
1048             cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1049             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1050             int n = trans_num->getIntValue();
1051             if (n >= 0) {
1052                 trans_num->setIntValue(-1);
1053                  // PopupCallback(n);
1054                  cerr << "Selected transmission message" << n << endl;
1055                  FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
1056                  atc->getATCDialog()->removeEntry(1);
1057             } else {
1058                 cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1059                 transmit(&(*i), msgId, msgDir, false);
1060                 return false;
1061             }
1062         }
1063         if (now > startTime) {
1064             //cerr << "Transmitting startup msg" << endl;
1065             transmit(&(*i), msgId, msgDir, true);
1066             i->updateState();
1067             lastTransmission = now;
1068             available = false;
1069             return true;
1070         }
1071     }
1072     return false;
1073 }
1074
1075 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1076                                                     double heading, double speed, double alt,
1077                                                     double dt)
1078 {
1079     TrafficVectorIterator i = activeTraffic.begin();
1080     // Search search if the current id has an entry
1081     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1082     TrafficVectorIterator current, closest;
1083     if (activeTraffic.size()) {
1084         //while ((i->getId() != id) && i != activeTraffic.end()) {
1085         while (i != activeTraffic.end()) {
1086             if (i->getId() == id) {
1087                 break;
1088             }
1089             i++;
1090         }
1091     }
1092 //    // update position of the current aircraft
1093
1094     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1095         SG_LOG(SG_GENERAL, SG_ALERT,
1096                "AI error: updating aircraft without traffic record");
1097     } else {
1098         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1099         current = i;
1100     }
1101     setDt(getDt() + dt);
1102
1103     int state = i->getState();
1104
1105     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1106     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1107     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1108     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1109     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1110     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1111     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1112
1113     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1114         available = true;
1115     }
1116
1117     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1118     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1119     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1120     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1121     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1122         i->nextFrequency();
1123     }
1124     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1125     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1126     checkTransmissionState(7, now, (startTime + 180), i, MSG_REQUEST_PUSHBACK_CLEARANCE,                ATC_AIR_TO_GROUND);
1127
1128
1129    
1130     if ((state == 8) && available) {
1131         if (now > startTime + 200) {
1132             if (i->pushBackAllowed()) {
1133                 i->allowRepeatedTransmissions();
1134                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1135                          ATC_GROUND_TO_AIR, true);
1136                 i->updateState();
1137             } else {
1138                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1139                          ATC_GROUND_TO_AIR, true);
1140                 i->suppressRepeatedTransmissions();
1141             }
1142             lastTransmission = now;
1143             available = false;
1144         }
1145     }
1146     if ((state == 9) && available) {
1147         i->setHoldPosition(false);
1148     }
1149 }
1150
1151 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
1152 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
1153                             double lon, double elev, double hdg)
1154 {
1155     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
1156     obj_pos = geod.makeZUpFrame();
1157     // hdg is not a compass heading, but a counter-clockwise rotation
1158     // around the Z axis
1159     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
1160                                         0.0, 0.0, 1.0));
1161 }
1162
1163
1164 void FGStartupController::render()
1165 {
1166
1167     SGMaterialLib *matlib = globals->get_matlib();
1168     if (group) {
1169         //int nr = ;
1170         globals->get_scenery()->get_scene_graph()->removeChild(group);
1171         //while (group->getNumChildren()) {
1172         //  cerr << "Number of children: " << group->getNumChildren() << endl;
1173         simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
1174           //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
1175            //geode->releaseGLObjects();
1176            //group->removeChild(geode);
1177            //delete geode;
1178     }
1179     group = new osg::Group;
1180
1181     //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
1182     double dx = 0;
1183     for   (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
1184         // Handle start point
1185         int pos = i->getCurrentPosition();
1186         //cerr << "rendering for " << i->getAircraft()->getCallSign() << "pos = " << pos << endl;
1187         if (pos > 0) {
1188             FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(pos);
1189             SGGeod start(SGGeod::fromDeg((i->getLongitude()), (i->getLatitude())));
1190             SGGeod end  (SGGeod::fromDeg(segment->getEnd()->getLongitude(), segment->getEnd()->getLatitude()));
1191
1192             double length = SGGeodesy::distanceM(start, end);
1193             //heading = SGGeodesy::headingDeg(start->getGeod(), end->getGeod());
1194
1195             double az2, heading; //, distanceM;
1196             SGGeodesy::inverse(start, end, heading, az2, length);
1197             double coveredDistance = length * 0.5;
1198             SGGeod center;
1199             SGGeodesy::direct(start, heading, coveredDistance, center, az2);
1200             //cerr << "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading << endl;
1201             ///////////////////////////////////////////////////////////////////////////////
1202             // Make a helper function out of this
1203             osg::Matrix obj_pos;
1204                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1205                 obj_trans->setDataVariance(osg::Object::STATIC);
1206
1207                 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), parent->getElevation()+8+dx, -(heading) );
1208
1209                 obj_trans->setMatrix( obj_pos );
1210                 //osg::Vec3 center(0, 0, 0)
1211
1212                 float width = length /2.0;
1213                 osg::Vec3 corner(-width, 0, 0.25f);
1214                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1215                 osg::Vec3 heightVec(0, 1, 0);
1216                 osg::Geometry* geometry;
1217                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1218                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1219                 geode->setName("test");
1220                 geode->addDrawable(geometry);
1221                 //osg::Node *custom_obj;
1222                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1223                 if (mat)
1224                     geode->setEffect(mat->get_effect());
1225                 obj_trans->addChild(geode);
1226                 // wire as much of the scene graph together as we can
1227                 //->addChild( obj_trans );
1228                 group->addChild( obj_trans );
1229         /////////////////////////////////////////////////////////////////////
1230         } else {
1231              cerr << "BIG FAT WARNING: current position is here : " << pos << endl;
1232         }
1233         for(intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
1234              osg::Matrix obj_pos;
1235             int k = (*j);
1236             if (k > 0) {
1237                 //cerr << "rendering for " << i->getAircraft()->getCallSign() << "intention = " << k << endl;
1238                 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
1239                 obj_trans->setDataVariance(osg::Object::STATIC);
1240                 FGTaxiSegment *segment  = parent->getGroundNetwork()->findSegment(k);
1241                 WorldCoordinate( obj_pos, segment->getLatitude(), segment->getLongitude(), parent->getElevation()+8+dx, -(segment->getHeading()) );
1242
1243                 obj_trans->setMatrix( obj_pos );
1244                 //osg::Vec3 center(0, 0, 0)
1245
1246                 float width = segment->getLength() /2.0;
1247                 osg::Vec3 corner(-width, 0, 0.25f);
1248                 osg::Vec3 widthVec(2*width + 1, 0, 0);
1249                 osg::Vec3 heightVec(0, 1, 0);
1250                 osg::Geometry* geometry;
1251                 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
1252                 simgear::EffectGeode* geode = new simgear::EffectGeode;
1253                 geode->setName("test");
1254                 geode->addDrawable(geometry);
1255                 //osg::Node *custom_obj;
1256                 SGMaterial *mat = matlib->find("UnidirectionalTaper");
1257                 if (mat)
1258                     geode->setEffect(mat->get_effect());
1259                 obj_trans->addChild(geode);
1260                 // wire as much of the scene graph together as we can
1261                 //->addChild( obj_trans );
1262                 group->addChild( obj_trans );
1263             } else {
1264                 cerr << "BIG FAT WARNING: k is here : " << pos << endl;
1265             }
1266         }
1267         //dx += 0.1;
1268     }
1269     globals->get_scenery()->get_scene_graph()->addChild(group);
1270 }
1271
1272
1273 /***************************************************************************
1274  * class FGApproachController
1275  *
1276  **************************************************************************/
1277 FGApproachController::FGApproachController():
1278 FGATCController()
1279 {
1280 }
1281
1282 // 
1283 void FGApproachController::announcePosition(int id,
1284                                             FGAIFlightPlan * intendedRoute,
1285                                             int currentPosition,
1286                                             double lat, double lon,
1287                                             double heading, double speed,
1288                                             double alt, double radius,
1289                                             int leg, FGAIAircraft * ref)
1290 {
1291     init();
1292     TrafficVectorIterator i = activeTraffic.begin();
1293     // Search whether the current id alread has an entry
1294     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1295     if (activeTraffic.size()) {
1296         //while ((i->getId() != id) && i != activeTraffic.end()) {
1297         while (i != activeTraffic.end()) {
1298             if (i->getId() == id) {
1299                 break;
1300             }
1301             i++;
1302         }
1303     }
1304     // Add a new TrafficRecord if no one exsists for this aircraft.
1305     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1306         FGTrafficRecord rec;
1307         rec.setId(id);
1308
1309         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1310         rec.setRunway(intendedRoute->getRunway());
1311         rec.setLeg(leg);
1312         //rec.setCallSign(callsign);
1313         rec.setAircraft(ref);
1314         activeTraffic.push_back(rec);
1315     } else {
1316         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1317     }
1318 }
1319
1320 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1321                                                      double heading, double speed, double alt,
1322                                                      double dt)
1323 {
1324     TrafficVectorIterator i = activeTraffic.begin();
1325     // Search search if the current id has an entry
1326     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1327     TrafficVectorIterator current, closest;
1328     if (activeTraffic.size()) {
1329         //while ((i->getId() != id) && i != activeTraffic.end()) {
1330         while (i != activeTraffic.end()) {
1331             if (i->getId() == id) {
1332                 break;
1333             }
1334             i++;
1335         }
1336     }
1337 //    // update position of the current aircraft
1338     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1339         SG_LOG(SG_GENERAL, SG_ALERT,
1340                "AI error: updating aircraft without traffic record");
1341     } else {
1342         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1343         current = i;
1344         //cerr << "ApproachController: checking for speed" << endl;
1345         time_t time_diff =
1346             current->getAircraft()->
1347             checkForArrivalTime(string("final001"));
1348         if (time_diff > 15) {
1349             current->setSpeedAdjustment(current->getAircraft()->
1350                                         getPerformance()->vDescent() *
1351                                         1.35);
1352         } else if (time_diff > 5) {
1353             current->setSpeedAdjustment(current->getAircraft()->
1354                                         getPerformance()->vDescent() *
1355                                         1.2);
1356         } else if (time_diff < -15) {
1357             current->setSpeedAdjustment(current->getAircraft()->
1358                                         getPerformance()->vDescent() *
1359                                         0.65);
1360         } else if (time_diff < -5) {
1361             current->setSpeedAdjustment(current->getAircraft()->
1362                                         getPerformance()->vDescent() *
1363                                         0.8);
1364         } else {
1365             current->clearSpeedAdjustment();
1366         }
1367         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1368     }
1369     setDt(getDt() + dt);
1370 }
1371
1372 void FGApproachController::signOff(int id)
1373 {
1374     TrafficVectorIterator i = activeTraffic.begin();
1375     // Search search if the current id alread has an entry
1376     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1377     if (activeTraffic.size()) {
1378         //while ((i->getId() != id) && i != activeTraffic.end()) {
1379         while (i != activeTraffic.end()) {
1380             if (i->getId() == id) {
1381                 break;
1382             }
1383             i++;
1384         }
1385     }
1386     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1387         SG_LOG(SG_GENERAL, SG_ALERT,
1388                "AI error: Aircraft without traffic record is signing off from approach");
1389     } else {
1390         i = activeTraffic.erase(i);
1391     }
1392 }
1393
1394
1395
1396
1397 bool FGApproachController::hasInstruction(int id)
1398 {
1399     TrafficVectorIterator i = activeTraffic.begin();
1400     // Search search if the current id has an entry
1401     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1402     if (activeTraffic.size()) {
1403         //while ((i->getId() != id) && i != activeTraffic.end()) {
1404         while (i != activeTraffic.end()) {
1405             if (i->getId() == id) {
1406                 break;
1407             }
1408             i++;
1409         }
1410     }
1411     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1412         SG_LOG(SG_GENERAL, SG_ALERT,
1413                "AI error: checking ATC instruction for aircraft without traffic record");
1414     } else {
1415         return i->hasInstruction();
1416     }
1417     return false;
1418 }
1419
1420
1421 FGATCInstruction FGApproachController::getInstruction(int id)
1422 {
1423     TrafficVectorIterator i = activeTraffic.begin();
1424     // Search search if the current id has an entry
1425     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1426     if (activeTraffic.size()) {
1427         //while ((i->getId() != id) && i != activeTraffic.end()) {
1428         while (i != activeTraffic.end()) {
1429             if (i->getId() == id) {
1430                 break;
1431             }
1432             i++;
1433         }
1434     }
1435     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1436         SG_LOG(SG_GENERAL, SG_ALERT,
1437                "AI error: requesting ATC instruction for aircraft without traffic record");
1438     } else {
1439         return i->getInstruction();
1440     }
1441     return FGATCInstruction();
1442 }
1443
1444
1445 ActiveRunway *FGApproachController::getRunway(string name)
1446 {
1447     ActiveRunwayVecIterator rwy = activeRunways.begin();
1448     if (activeRunways.size()) {
1449         while (rwy != activeRunways.end()) {
1450             if (rwy->getRunwayName() == name) {
1451                 break;
1452             }
1453             rwy++;
1454         }
1455     }
1456     if (rwy == activeRunways.end()) {
1457         ActiveRunway aRwy(name, 0);
1458         activeRunways.push_back(aRwy);
1459         rwy = activeRunways.end() - 1;
1460     }
1461     return &(*rwy);
1462 }
1463
1464 void FGApproachController::render() {
1465     cerr << "FGApproachController::render function not yet implemented" << endl;
1466 }