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