]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Added a small and simple dialogbox that allows the user to issue ATC commands.
[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 "trafficcontrol.hxx"
30 #include "atc_mgr.hxx"
31 #include <AIModel/AIAircraft.hxx>
32 #include <AIModel/AIFlightPlan.hxx>
33 #include <AIModel/performancedata.hxx>
34 #include <AIModel/performancedb.hxx>
35 #include <ATC/atc_mgr.hxx>
36 #include <Traffic/TrafficMgr.hxx>
37 #include <Airports/groundnetwork.hxx>
38 #include <Airports/dynamics.hxx>
39 #include <Airports/simple.hxx>
40
41 using std::sort;
42
43 /***************************************************************************
44  * ActiveRunway
45  **************************************************************************/
46 time_t ActiveRunway::requestTimeSlot(time_t eta)
47 {
48     time_t newEta;
49     time_t separation = 90;
50     bool found = false;
51     if (estimatedArrivalTimes.size() == 0) {
52         estimatedArrivalTimes.push_back(eta);
53         return eta;
54     } else {
55         TimeVectorIterator i = estimatedArrivalTimes.begin();
56         //cerr << "Checking eta slots " << eta << ": " << endl;
57         for (i = estimatedArrivalTimes.begin();
58              i != estimatedArrivalTimes.end(); i++) {
59             //cerr << "Stored time : " << (*i) << endl;
60         }
61         i = estimatedArrivalTimes.begin();
62         if ((eta + separation) < (*i)) {
63             newEta = eta;
64             found = true;
65             //cerr << "Storing at beginning" << endl;
66         }
67         while ((i != estimatedArrivalTimes.end()) && (!found)) {
68             TimeVectorIterator j = i + 1;
69             if (j == estimatedArrivalTimes.end()) {
70                 if (((*i) + separation) < eta) {
71                     //cerr << "Storing at end" << endl;
72                     newEta = eta;
73                 } else {
74                     newEta = (*i) + separation;
75                     //cerr << "Storing at end + separation" << endl;
76                 }
77             } else {
78                 if ((((*j) - (*i)) > (separation * 2))) {       // found a potential slot
79                     // now check whether this slow is usable:
80                     // 1) eta should fall between the two points
81                     //    i.e. eta > i AND eta < j
82                     //
83                     //cerr << "Found potential slot after " << (*i) << endl;
84                     if (eta > (*i) && (eta < (*j))) {
85                         found = true;
86                         if (eta < ((*i) + separation)) {
87                             newEta = (*i) + separation;
88                             //cerr << "Using  original" << (*i) << " + separation " << endl;
89                         } else {
90                             newEta = eta;
91                             //cerr << "Using original after " << (*i) << endl;
92                         }
93                     } else if (eta < (*i)) {
94                         found = true;
95                         newEta = (*i) + separation;
96                         //cerr << "Using delayed slot after " << (*i) << endl;
97                     }
98                     /*
99                        if (((*j) - separation) < eta) {
100                        found = true;
101                        if (((*i) + separation) < eta) {
102                        newEta = eta;
103                        cerr << "Using original after " << (*i) << endl;
104                        } else {
105                        newEta = (*i) + separation;
106                        cerr << "Using  " << (*i) << " + separation " << endl;
107                        }
108                        } */
109                 }
110             }
111             i++;
112         }
113     }
114     //cerr << ". done. New ETA : " << newEta << endl;
115
116     estimatedArrivalTimes.push_back(newEta);
117     sort(estimatedArrivalTimes.begin(), estimatedArrivalTimes.end());
118     // do some housekeeping : remove any timestamps that are past
119     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
120     TimeVectorIterator i = estimatedArrivalTimes.begin();
121     while (i != estimatedArrivalTimes.end()) {
122         if ((*i) < now) {
123             //cerr << "Deleting timestamp " << (*i) << " (now = " << now << "). " << endl;
124             estimatedArrivalTimes.erase(i);
125             i = estimatedArrivalTimes.begin();
126         } else {
127             i++;
128         }
129     }
130     return newEta;
131 }
132
133 /***************************************************************************
134  * FGTrafficRecord
135  **************************************************************************/
136 FGTrafficRecord::FGTrafficRecord():
137 id(0), waitsForId(0),
138 currentPos(0),
139 leg(0),
140 frequencyId(0),
141 state(0),
142 allowTransmission(true),
143 latitude(0), longitude(0), heading(0), speed(0), altitude(0), radius(0)
144 {
145 }
146
147 void FGTrafficRecord::setPositionAndIntentions(int pos,
148                                                FGAIFlightPlan * route)
149 {
150
151     currentPos = pos;
152     if (intentions.size()) {
153         intVecIterator i = intentions.begin();
154         if ((*i) != pos) {
155             SG_LOG(SG_GENERAL, SG_ALERT,
156                    "Error in FGTrafficRecord::setPositionAndIntentions");
157             //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
158             for (intVecIterator i = intentions.begin();
159                  i != intentions.end(); i++) {
160                 //cerr << (*i) << " ";
161             }
162             //cerr << endl;
163         }
164         intentions.erase(i);
165     } else {
166         //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
167         int size = route->getNrOfWayPoints();
168         //cerr << "Setting pos" << pos << " ";
169         //cerr << "setting intentions ";
170         for (int i = 0; i < size; i++) {
171             int val = route->getRouteIndex(i);
172             //cerr << val<< " ";
173             if ((val) && (val != pos)) {
174                 intentions.push_back(val);
175                 //cerr << "[set] ";
176             }
177         }
178         //cerr << endl;
179         //while (route->next(&legNr, &routeNr)) {
180         //intentions.push_back(routeNr);
181         //}
182         //route->rewind(currentPos);
183     }
184     //exit(1);
185 }
186
187 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord & other)
188 {
189     bool result = false;
190     //cerr << "Start check 1" << endl;
191     if (currentPos == other.currentPos) {
192         //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
193         result = true;
194     }
195     //  else if (other.intentions.size()) 
196     //     {
197     //       cerr << "Start check 2" << endl;
198     //       intVecIterator i = other.intentions.begin(); 
199     //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
200     //     i++;
201     //       if (i != other.intentions.end()) {
202     //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
203     //     result = true;
204     //       }
205     else if (intentions.size()) {
206         //cerr << "Start check 3" << endl;
207         intVecIterator i = intentions.begin();
208         //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
209         while (i != intentions.end()) {
210             if ((*i) == other.currentPos) {
211                 break;
212             }
213             i++;
214         }
215         if (i != intentions.end()) {
216             //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
217             result = true;
218         }
219     }
220     //cerr << "Done !!" << endl;
221     return result;
222 }
223
224 void FGTrafficRecord::setPositionAndHeading(double lat, double lon,
225                                             double hdg, double spd,
226                                             double alt)
227 {
228     latitude = lat;
229     longitude = lon;
230     heading = hdg;
231     speed = spd;
232     altitude = alt;
233 }
234
235 int FGTrafficRecord::crosses(FGGroundNetwork * net,
236                              FGTrafficRecord & other)
237 {
238     if (checkPositionAndIntentions(other)
239         || (other.checkPositionAndIntentions(*this)))
240         return -1;
241     intVecIterator i, j;
242     int currentTargetNode = 0, otherTargetNode = 0;
243     if (currentPos > 0)
244         currentTargetNode = net->findSegment(currentPos)->getEnd()->getIndex(); // OKAY,... 
245     if (other.currentPos > 0)
246         otherTargetNode = net->findSegment(other.currentPos)->getEnd()->getIndex();     // OKAY,...
247     if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
248         return currentTargetNode;
249     if (intentions.size()) {
250         for (i = intentions.begin(); i != intentions.end(); i++) {
251             if ((*i) > 0) {
252                 if ((currentTargetNode ==
253                      net->findSegment(*i)->getEnd()->getIndex())) {
254                     //cerr << "Current crosses at " << currentTargetNode <<endl;
255                     return currentTargetNode;
256                 }
257             }
258         }
259     }
260     if (other.intentions.size()) {
261         for (i = other.intentions.begin(); i != other.intentions.end();
262              i++) {
263             if ((*i) > 0) {
264                 if (otherTargetNode ==
265                     net->findSegment(*i)->getEnd()->getIndex()) {
266                     //cerr << "Other crosses at " << currentTargetNode <<endl;
267                     return otherTargetNode;
268                 }
269             }
270         }
271     }
272     if (intentions.size() && other.intentions.size()) {
273         for (i = intentions.begin(); i != intentions.end(); i++) {
274             for (j = other.intentions.begin(); j != other.intentions.end();
275                  j++) {
276                 //cerr << "finding segment " << *i << " and " << *j << endl;
277                 if (((*i) > 0) && ((*j) > 0)) {
278                     currentTargetNode =
279                         net->findSegment(*i)->getEnd()->getIndex();
280                     otherTargetNode =
281                         net->findSegment(*j)->getEnd()->getIndex();
282                     if (currentTargetNode == otherTargetNode) {
283                         //cerr << "Routes will cross at " << currentTargetNode << endl;
284                         return currentTargetNode;
285                     }
286                 }
287             }
288         }
289     }
290     return -1;
291 }
292
293 bool FGTrafficRecord::onRoute(FGGroundNetwork * net,
294                               FGTrafficRecord & other)
295 {
296     int node = -1, othernode = -1;
297     if (currentPos > 0)
298         node = net->findSegment(currentPos)->getEnd()->getIndex();
299     if (other.currentPos > 0)
300         othernode =
301             net->findSegment(other.currentPos)->getEnd()->getIndex();
302     if ((node == othernode) && (node != -1))
303         return true;
304     if (other.intentions.size()) {
305         for (intVecIterator i = other.intentions.begin();
306              i != other.intentions.end(); i++) {
307             if (*i > 0) {
308                 othernode = net->findSegment(*i)->getEnd()->getIndex();
309                 if ((node == othernode) && (node > -1))
310                     return true;
311             }
312         }
313     }
314     //if (other.currentPos > 0)
315     //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
316     //if (intentions.size())
317     //  {
318     //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
319     //    {
320     //      if (*i > 0) 
321     //        {
322     //          node = net->findSegment(*i)->getEnd()->getIndex();
323     //          if ((node == othernode) && (node > -1))
324     //            return true;
325     //        }
326     //    }
327     //  }
328     return false;
329 }
330
331
332 bool FGTrafficRecord::isOpposing(FGGroundNetwork * net,
333                                  FGTrafficRecord & other, int node)
334 {
335     // Check if current segment is the reverse segment for the other aircraft
336     FGTaxiSegment *opp;
337     //cerr << "Current segment " << currentPos << endl;
338     if ((currentPos > 0) && (other.currentPos > 0)) {
339         opp = net->findSegment(currentPos)->opposite();
340         if (opp) {
341             if (opp->getIndex() == other.currentPos)
342                 return true;
343         }
344
345         for (intVecIterator i = intentions.begin(); i != intentions.end();
346              i++) {
347             if ((opp = net->findSegment(other.currentPos)->opposite())) {
348                 if ((*i) > 0)
349                     if (opp->getIndex() ==
350                         net->findSegment(*i)->getIndex()) {
351                         if (net->findSegment(*i)->getStart()->getIndex() ==
352                             node) {
353                             {
354                                 //cerr << "Found the node " << node << endl;
355                                 return true;
356                             }
357                         }
358                     }
359             }
360             if (other.intentions.size()) {
361                 for (intVecIterator j = other.intentions.begin();
362                      j != other.intentions.end(); j++) {
363                     // cerr << "Current segment 1 " << (*i) << endl;
364                     if ((*i) > 0) {
365                         if ((opp = net->findSegment(*i)->opposite())) {
366                             if (opp->getIndex() ==
367                                 net->findSegment(*j)->getIndex()) {
368                                 //cerr << "Nodes " << net->findSegment(*i)->getIndex()
369                                 //   << " and  " << net->findSegment(*j)->getIndex()
370                                 //   << " are opposites " << endl;
371                                 if (net->findSegment(*i)->getStart()->
372                                     getIndex() == node) {
373                                     {
374                                         //cerr << "Found the node " << node << endl;
375                                         return true;
376                                     }
377                                 }
378                             }
379                         }
380                     }
381                 }
382             }
383         }
384     }
385     return false;
386 }
387
388 void FGTrafficRecord::setSpeedAdjustment(double spd)
389 {
390     instruction.setChangeSpeed(true);
391     instruction.setSpeed(spd);
392 }
393
394 void FGTrafficRecord::setHeadingAdjustment(double heading)
395 {
396     instruction.setChangeHeading(true);
397     instruction.setHeading(heading);
398 }
399
400 bool FGTrafficRecord::pushBackAllowed()
401 {
402     double course, az2, dist;
403     SGGeod curr(SGGeod::fromDegM(getLongitude(),
404                                  getLatitude(), getAltitude()));
405
406     double userLatitude = fgGetDouble("/position/latitude-deg");
407     double userLongitude = fgGetDouble("/position/longitude-deg");
408     SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
409     SGGeodesy::inverse(curr, user, course, az2, dist);
410     //cerr << "Distance to user : " << dist << endl;
411     return (dist > 250);
412
413 }
414
415
416
417 /***************************************************************************
418  * FGATCInstruction
419  *
420  **************************************************************************/
421 FGATCInstruction::FGATCInstruction()
422 {
423     holdPattern = false;
424     holdPosition = false;
425     changeSpeed = false;
426     changeHeading = false;
427     changeAltitude = false;
428     resolveCircularWait = false;
429
430     speed = 0;
431     heading = 0;
432     alt = 0;
433 }
434
435
436 bool FGATCInstruction::hasInstruction()
437 {
438     return (holdPattern || holdPosition || changeSpeed || changeHeading
439             || changeAltitude || resolveCircularWait);
440 }
441
442 /***************************************************************************
443  * FGATCController
444  *
445  **************************************************************************/
446
447
448
449
450 FGATCController::FGATCController()
451 {
452     cerr << "running FGATController constructor" << endl;
453     dt_count = 0;
454     available = true;
455     lastTransmission = 0;
456     initialized = false;
457 }
458
459 FGATCController::~FGATCController()
460 {
461      cerr << "running FGATController destructor" << endl;
462 }
463
464 string FGATCController::getGateName(FGAIAircraft * ref)
465 {
466     return ref->atGate();
467 }
468
469 bool FGATCController::isUserAircraft(FGAIAircraft* ac) 
470
471     return (ac->getCallSign() == fgGetString("/sim/multiplay/callsign")) ? true : false; 
472 };
473
474 void FGATCController::transmit(FGTrafficRecord * rec, AtcMsgId msgId,
475                                AtcMsgDir msgDir, bool audible)
476 {
477     string sender, receiver;
478     int stationFreq = 0;
479     int taxiFreq = 0;
480     int freqId = 0;
481     string atisInformation;
482     string text;
483     string taxiFreqStr;
484     double heading = 0;
485     string activeRunway;
486     string fltType;
487     string rwyClass;
488     string SID;
489     string transponderCode;
490     FGAIFlightPlan *fp;
491     string fltRules;
492
493     //double commFreqD;
494     sender = rec->getAircraft()->getTrafficRef()->getCallSign();
495     //cerr << "transmitting for: " << sender << "Leg = " << rec->getLeg() << endl;
496     switch (rec->getLeg()) {
497     case 2:
498     case 3:
499         freqId = rec->getNextFrequency();
500         stationFreq =
501             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
502             getDynamics()->getGroundFrequency(rec->getLeg() + freqId);
503         taxiFreq =
504             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
505             getDynamics()->getGroundFrequency(3);
506         receiver =
507             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
508             getName() + "-Ground";
509         atisInformation =
510             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
511             getDynamics()->getAtisInformation();
512         break;
513     case 4:
514         receiver =
515             rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
516             getName() + "-Tower";
517         break;
518     }
519     // Swap sender and receiver value in case of a ground to air transmission
520     if (msgDir == ATC_GROUND_TO_AIR) {
521         string tmp = sender;
522         sender = receiver;
523         receiver = tmp;
524     }
525     switch (msgId) {
526     case MSG_ANNOUNCE_ENGINE_START:
527         text = sender + ". Ready to Start up";
528         break;
529     case MSG_REQUEST_ENGINE_START:
530         text =
531             receiver + ", This is " + sender + ". Position " +
532             getGateName(rec->getAircraft()) + ". Information " +
533             atisInformation + ". " +
534             rec->getAircraft()->getTrafficRef()->getFlightRules() +
535             " to " +
536             rec->getAircraft()->getTrafficRef()->getArrivalAirport()->
537             getName() + ". Request start-up";
538         break;
539         // Acknowledge engine startup permission
540         // Assign departure runway
541         // Assign SID, if necessery (TODO)
542     case MSG_PERMIT_ENGINE_START:
543         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
544
545         heading = rec->getAircraft()->getTrafficRef()->getCourse();
546         fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
547         rwyClass =
548             rec->getAircraft()->GetFlightPlan()->
549             getRunwayClassFromTrafficType(fltType);
550
551         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
552             getDynamics()->getActiveRunway(rwyClass, 1, activeRunway,
553                                            heading);
554         rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
555         fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->
556             getDynamics()->getSID(activeRunway, heading);
557         rec->getAircraft()->GetFlightPlan()->setSID(fp);
558         if (fp) {
559             SID = fp->getName() + " departure";
560         } else {
561             SID = "fly runway heading ";
562         }
563         //snprintf(buffer, 7, "%3.2f", heading);
564         fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
565         transponderCode = genTransponderCode(fltRules);
566         rec->getAircraft()->SetTransponderCode(transponderCode);
567         text =
568             receiver + ". Start-up approved. " + atisInformation +
569             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
570             transponderCode + ". " +
571             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
572             sender + " control.";
573         break;
574     case MSG_DENY_ENGINE_START:
575         text = receiver + ". Standby";
576         break;
577     case MSG_ACKNOWLEDGE_ENGINE_START:
578         fp = rec->getAircraft()->GetFlightPlan()->getSID();
579         if (fp) {
580             SID =
581                 rec->getAircraft()->GetFlightPlan()->getSID()->getName() +
582                 " departure";
583         } else {
584             SID = "fly runway heading ";
585         }
586         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
587         activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
588         transponderCode = rec->getAircraft()->GetTransponderCode();
589         text =
590             receiver + ". Start-up approved. " + atisInformation +
591             " correct, runway " + activeRunway + ", " + SID + ", squawk " +
592             transponderCode + ". " +
593             "For push-back and taxi clearance call " + taxiFreqStr + ". " +
594             sender;
595         break;
596     case MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY:
597         taxiFreqStr = formatATCFrequency3_2(taxiFreq);
598         text = receiver + ". Switching to " + taxiFreqStr + ". " + sender;
599         break;
600     case MSG_INITIATE_CONTACT:
601         text = receiver + ". With you. " + sender;
602         break;
603     case MSG_ACKNOWLEDGE_INITIATE_CONTACT:
604         text = receiver + ". Roger. " + sender;
605         break;
606     case MSG_REQUEST_PUSHBACK_CLEARANCE:
607         text = receiver + ". Request push-back. " + sender;
608         break;
609     case MSG_PERMIT_PUSHBACK_CLEARANCE:
610         text = receiver + ". Push-back approved. " + sender;
611         break;
612     case MSG_HOLD_PUSHBACK_CLEARANCE:
613         text = receiver + ". Standby. " + sender;
614         break;
615     case MSG_REQUEST_TAXI_CLEARANCE:
616         text = receiver + ". Ready to Taxi. " + sender;
617         break;
618     case MSG_ISSUE_TAXI_CLEARANCE:
619         text = receiver + ". Cleared to taxi. " + sender;
620         break;
621     case MSG_ACKNOWLEDGE_TAXI_CLEARANCE:
622         text = receiver + ". Cleared to taxi. " + sender;
623         break;
624     case MSG_HOLD_POSITION:
625         text = receiver + ". Hold Position. " + sender;
626         break;
627     case MSG_ACKNOWLEDGE_HOLD_POSITION:
628         text = receiver + ". Holding Position. " + sender;
629         break;
630     case MSG_RESUME_TAXI:
631         text = receiver + ". Resume Taxiing. " + sender;
632         break;
633     case MSG_ACKNOWLEDGE_RESUME_TAXI:
634         text = receiver + ". Continuing Taxi. " + sender;
635         break;
636     default:
637         text = text + sender + ". Transmitting unknown Message";
638         break;
639     }
640     if (audible) {
641         double onBoardRadioFreq0 =
642             fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
643         double onBoardRadioFreq1 =
644             fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
645         int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
646         int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
647         //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << " for " << text << endl;
648
649         // Display ATC message only when one of the radios is tuned
650         // the relevant frequency.
651         // Note that distance attenuation is currently not yet implemented
652         if ((onBoardRadioFreqI0 == stationFreq)
653             || (onBoardRadioFreqI1 == stationFreq)) {
654             if (rec->allowTransmissions()) {
655                 fgSetString("/sim/messages/atc", text.c_str());
656             }
657         }
658     } else {
659         FGATCManager *atc = (FGATCManager*) globals->get_subsystem("atc");
660         atc->getATCDialog()->addEntry(1, text);
661         
662     }
663 }
664
665 string FGATCController::formatATCFrequency3_2(int freq)
666 {
667     char buffer[7];
668     snprintf(buffer, 7, "%3.2f", ((float) freq / 100.0));
669     return string(buffer);
670 }
671
672 // TODO: Set transponder codes according to real-world routes.
673 // The current version just returns a random string of four octal numbers. 
674 string FGATCController::genTransponderCode(string fltRules)
675 {
676     if (fltRules == "VFR") {
677         return string("1200");
678     } else {
679         char buffer[5];
680         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8, rand() % 8,
681                  rand() % 8);
682         return string(buffer);
683     }
684 }
685
686 void FGATCController::init() 
687 {
688    if (!initialized) {
689        FGATCManager *mgr = (FGATCManager*) globals->get_subsystem("ATC");
690        mgr->addController(this);
691        initialized = true;
692     }
693 }
694
695 /***************************************************************************
696  * class FGTowerController
697  *
698  **************************************************************************/
699 FGTowerController::FGTowerController():
700 FGATCController()
701 {
702 }
703
704 // 
705 void FGTowerController::announcePosition(int id,
706                                          FGAIFlightPlan * intendedRoute,
707                                          int currentPosition, double lat,
708                                          double lon, double heading,
709                                          double speed, double alt,
710                                          double radius, int leg,
711                                          FGAIAircraft * ref)
712 {
713     init();
714     TrafficVectorIterator i = activeTraffic.begin();
715     // Search whether the current id alread has an entry
716     // This might be faster using a map instead of a vector, but let's start by taking a safe route
717     if (activeTraffic.size()) {
718         //while ((i->getId() != id) && i != activeTraffic.end()) {
719         while (i != activeTraffic.end()) {
720             if (i->getId() == id) {
721                 break;
722             }
723             i++;
724         }
725     }
726     // Add a new TrafficRecord if no one exsists for this aircraft.
727     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
728         FGTrafficRecord rec;
729         rec.setId(id);
730
731         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
732         rec.setRunway(intendedRoute->getRunway());
733         rec.setLeg(leg);
734         //rec.setCallSign(callsign);
735         rec.setAircraft(ref);
736         activeTraffic.push_back(rec);
737     } else {
738         i->setPositionAndHeading(lat, lon, heading, speed, alt);
739     }
740 }
741
742 void FGTowerController::updateAircraftInformation(int id, double lat, double lon,
743                                                   double heading, double speed, double alt,
744                                                   double dt)
745 {
746     TrafficVectorIterator i = activeTraffic.begin();
747     // Search whether the current id has an entry
748     // This might be faster using a map instead of a vector, but let's start by taking a safe route
749     TrafficVectorIterator current, closest;
750     if (activeTraffic.size()) {
751         //while ((i->getId() != id) && i != activeTraffic.end()) {
752         while (i != activeTraffic.end()) {
753             if (i->getId() == id) {
754                 break;
755             }
756             i++;
757         }
758     }
759 //    // update position of the current aircraft
760     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
761         SG_LOG(SG_GENERAL, SG_ALERT,
762                "AI error: updating aircraft without traffic record");
763     } else {
764         i->setPositionAndHeading(lat, lon, heading, speed, alt);
765         current = i;
766     }
767     setDt(getDt() + dt);
768
769 //    // see if we already have a clearance record for the currently active runway
770     ActiveRunwayVecIterator rwy = activeRunways.begin();
771     // again, a map might be more efficient here
772     if (activeRunways.size()) {
773         //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
774         while (rwy != activeRunways.end()) {
775             if (rwy->getRunwayName() == current->getRunway()) {
776                 break;
777             }
778             rwy++;
779         }
780     }
781     if (rwy == activeRunways.end()) {
782         ActiveRunway aRwy(current->getRunway(), id);
783         activeRunways.push_back(aRwy);  // Since there are no clearance records for this runway yet
784         current->setHoldPosition(false);        // Clear the current aircraft to continue
785     } else {
786         // Okay, we have a clearance record for this runway, so check
787         // whether the clearence ID matches that of the current aircraft
788         if (id == rwy->getCleared()) {
789             current->setHoldPosition(false);
790         } else {
791             current->setHoldPosition(true);
792         }
793     }
794 }
795
796
797 void FGTowerController::signOff(int id)
798 {
799     TrafficVectorIterator i = activeTraffic.begin();
800     // Search search if the current id alread has an entry
801     // This might be faster using a map instead of a vector, but let's start by taking a safe route
802     if (activeTraffic.size()) {
803         //while ((i->getId() != id) && i != activeTraffic.end()) {
804         while (i != activeTraffic.end()) {
805             if (i->getId() == id) {
806                 break;
807             }
808             i++;
809         }
810     }
811     // If this aircraft has left the runway, we can clear the departure record for this runway
812     ActiveRunwayVecIterator rwy = activeRunways.begin();
813     if (activeRunways.size()) {
814         //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
815         while (rwy != activeRunways.end()) {
816             if (rwy->getRunwayName() == i->getRunway()) {
817                 break;
818             }
819             rwy++;
820         }
821         if (rwy != activeRunways.end()) {
822             rwy = activeRunways.erase(rwy);
823         } else {
824             SG_LOG(SG_GENERAL, SG_ALERT,
825                    "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
826         }
827     }
828     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
829         SG_LOG(SG_GENERAL, SG_ALERT,
830                "AI error: Aircraft without traffic record is signing off from tower");
831     } else {
832         i = activeTraffic.erase(i);
833     }
834 }
835
836 // NOTE:
837 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
838 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
839 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
840 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
841 // Note that this function is probably obsolete
842 bool FGTowerController::hasInstruction(int id)
843 {
844     TrafficVectorIterator i = activeTraffic.begin();
845     // Search search if the current id has an entry
846     // This might be faster using a map instead of a vector, but let's start by taking a safe route
847     if (activeTraffic.size()) {
848         //while ((i->getId() != id) && i != activeTraffic.end()) {
849         while (i != activeTraffic.end()) {
850             if (i->getId() == id) {
851                 break;
852             }
853             i++;
854         }
855     }
856     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
857         SG_LOG(SG_GENERAL, SG_ALERT,
858                "AI error: checking ATC instruction for aircraft without traffic record");
859     } else {
860         return i->hasInstruction();
861     }
862     return false;
863 }
864
865
866 FGATCInstruction FGTowerController::getInstruction(int id)
867 {
868     TrafficVectorIterator i = activeTraffic.begin();
869     // Search search if the current id has an entry
870     // This might be faster using a map instead of a vector, but let's start by taking a safe route
871     if (activeTraffic.size()) {
872         //while ((i->getId() != id) && i != activeTraffic.end()) {
873         while (i != activeTraffic.end()) {
874             if (i->getId() == id) {
875                 break;
876             }
877             i++;
878         }
879     }
880     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
881         SG_LOG(SG_GENERAL, SG_ALERT,
882                "AI error: requesting ATC instruction for aircraft without traffic record");
883     } else {
884         return i->getInstruction();
885     }
886     return FGATCInstruction();
887 }
888
889 /***************************************************************************
890  * class FGStartupController
891  *
892  **************************************************************************/
893 FGStartupController::FGStartupController():
894 FGATCController()
895 {
896 }
897
898 void FGStartupController::announcePosition(int id,
899                                            FGAIFlightPlan * intendedRoute,
900                                            int currentPosition, double lat,
901                                            double lon, double heading,
902                                            double speed, double alt,
903                                            double radius, int leg,
904                                            FGAIAircraft * ref)
905 {
906     init();
907     TrafficVectorIterator i = activeTraffic.begin();
908     // Search whether the current id alread has an entry
909     // This might be faster using a map instead of a vector, but let's start by taking a safe route
910     if (activeTraffic.size()) {
911         //while ((i->getId() != id) && i != activeTraffic.end()) {
912         while (i != activeTraffic.end()) {
913             if (i->getId() == id) {
914                 break;
915             }
916             i++;
917         }
918     }
919     // Add a new TrafficRecord if no one exsists for this aircraft.
920     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
921         FGTrafficRecord rec;
922         rec.setId(id);
923
924         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
925         rec.setRunway(intendedRoute->getRunway());
926         rec.setLeg(leg);
927         //rec.setCallSign(callsign);
928         rec.setAircraft(ref);
929         rec.setHoldPosition(true);
930         activeTraffic.push_back(rec);
931     } else {
932         i->setPositionAndHeading(lat, lon, heading, speed, alt);
933
934     }
935 }
936
937 // NOTE:
938 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
939 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
940 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
941 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
942 // Note that this function is probably obsolete
943 bool FGStartupController::hasInstruction(int id)
944 {
945     TrafficVectorIterator i = activeTraffic.begin();
946     // Search search if the current id has an entry
947     // This might be faster using a map instead of a vector, but let's start by taking a safe route
948     if (activeTraffic.size()) {
949         //while ((i->getId() != id) && i != activeTraffic.end()) {
950         while (i != activeTraffic.end()) {
951             if (i->getId() == id) {
952                 break;
953             }
954             i++;
955         }
956     }
957     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
958         SG_LOG(SG_GENERAL, SG_ALERT,
959                "AI error: checking ATC instruction for aircraft without traffic record");
960     } else {
961         return i->hasInstruction();
962     }
963     return false;
964 }
965
966
967 FGATCInstruction FGStartupController::getInstruction(int id)
968 {
969     TrafficVectorIterator i = activeTraffic.begin();
970     // Search search if the current id has an entry
971     // This might be faster using a map instead of a vector, but let's start by taking a safe route
972     if (activeTraffic.size()) {
973         //while ((i->getId() != id) && i != activeTraffic.end()) {
974         while (i != activeTraffic.end()) {
975             if (i->getId() == id) {
976                 break;
977             }
978             i++;
979         }
980     }
981     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
982         SG_LOG(SG_GENERAL, SG_ALERT,
983                "AI error: requesting ATC instruction for aircraft without traffic record");
984     } else {
985         return i->getInstruction();
986     }
987     return FGATCInstruction();
988 }
989
990 void FGStartupController::signOff(int id)
991 {
992     TrafficVectorIterator i = activeTraffic.begin();
993     // Search search if the current id alread has an entry
994     // This might be faster using a map instead of a vector, but let's start by taking a safe route
995     if (activeTraffic.size()) {
996         //while ((i->getId() != id) && i != activeTraffic.end()) {
997         while (i != activeTraffic.end()) {
998             if (i->getId() == id) {
999                 break;
1000             }
1001             i++;
1002         }
1003     }
1004     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1005         SG_LOG(SG_GENERAL, SG_ALERT,
1006                "AI error: Aircraft without traffic record is signing off from tower");
1007     } else {
1008         i = activeTraffic.erase(i);
1009     }
1010 }
1011
1012 bool FGStartupController::checkTransmissionState(int st, time_t now, time_t startTime, TrafficVectorIterator i, AtcMsgId msgId,
1013                                AtcMsgDir msgDir)
1014 {
1015     int state = i->getState();
1016     if ((state == st) && available) {
1017         if ((msgDir == ATC_AIR_TO_GROUND) && isUserAircraft(i->getAircraft())) {
1018             
1019             cerr << "Checking state " << st << " for " << i->getAircraft()->getCallSign() << endl;
1020             static SGPropertyNode_ptr trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
1021             int n = trans_num->getIntValue();
1022             if (n >= 0) {
1023                 trans_num->setIntValue(-1);
1024                  // PopupCallback(n);
1025                  cerr << "Selected transmission message" << n << endl;
1026             } else {
1027                 cerr << "creading message for " << i->getAircraft()->getCallSign() << endl;
1028                 transmit(&(*i), msgId, msgDir, false);
1029                 return false;
1030             }
1031         }
1032         if (now > startTime) {
1033             //cerr << "Transmitting startup msg" << endl;
1034             transmit(&(*i), msgId, msgDir, true);
1035             i->updateState();
1036             lastTransmission = now;
1037             available = false;
1038             return true;
1039         }
1040     }
1041     return false;
1042 }
1043
1044 void FGStartupController::updateAircraftInformation(int id, double lat, double lon,
1045                                                     double heading, double speed, double alt,
1046                                                     double dt)
1047 {
1048     TrafficVectorIterator i = activeTraffic.begin();
1049     // Search search if the current id has an entry
1050     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1051     TrafficVectorIterator current, closest;
1052     if (activeTraffic.size()) {
1053         //while ((i->getId() != id) && i != activeTraffic.end()) {
1054         while (i != activeTraffic.end()) {
1055             if (i->getId() == id) {
1056                 break;
1057             }
1058             i++;
1059         }
1060     }
1061 //    // update position of the current aircraft
1062
1063     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1064         SG_LOG(SG_GENERAL, SG_ALERT,
1065                "AI error: updating aircraft without traffic record");
1066     } else {
1067         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1068         current = i;
1069     }
1070     setDt(getDt() + dt);
1071
1072     int state = i->getState();
1073
1074     // The user controlled aircraft should have crased here, because it doesn't have a traffic reference. 
1075     // NOTE: if we create a traffic schedule for the user aircraft, we can use this to plan a flight.
1076     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
1077     time_t now = time(NULL) + fgGetLong("/sim/time/warp");
1078     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
1079     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
1080     //     << " at parking " << getGateName(i->getAircraft()) << endl;
1081
1082     if ((now - lastTransmission) > 3 + (rand() % 15)) {
1083         available = true;
1084     }
1085
1086     checkTransmissionState(0, now, (startTime + 0  ), i, MSG_ANNOUNCE_ENGINE_START,                     ATC_AIR_TO_GROUND);
1087     checkTransmissionState(1, now, (startTime + 60 ), i, MSG_REQUEST_ENGINE_START,                      ATC_AIR_TO_GROUND);
1088     checkTransmissionState(2, now, (startTime + 80 ), i, MSG_PERMIT_ENGINE_START,                       ATC_GROUND_TO_AIR);
1089     checkTransmissionState(3, now, (startTime + 100), i, MSG_ACKNOWLEDGE_ENGINE_START,                  ATC_AIR_TO_GROUND);
1090     if (checkTransmissionState(4, now, (startTime + 130), i, MSG_ACKNOWLEDGE_SWITCH_GROUND_FREQUENCY,       ATC_AIR_TO_GROUND)) {
1091         i->nextFrequency();
1092     }
1093     checkTransmissionState(5, now, (startTime + 140), i, MSG_INITIATE_CONTACT,                          ATC_AIR_TO_GROUND);
1094     checkTransmissionState(6, now, (startTime + 150), i, MSG_ACKNOWLEDGE_INITIATE_CONTACT,              ATC_GROUND_TO_AIR);
1095
1096
1097    
1098     if ((state == 8) && available) {
1099         if (now > startTime + 200) {
1100             if (i->pushBackAllowed()) {
1101                 i->allowRepeatedTransmissions();
1102                 transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE,
1103                          ATC_GROUND_TO_AIR, true);
1104                 i->updateState();
1105             } else {
1106                 transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE,
1107                          ATC_GROUND_TO_AIR, true);
1108                 i->suppressRepeatedTransmissions();
1109             }
1110             lastTransmission = now;
1111             available = false;
1112         }
1113     }
1114     if ((state == 9) && available) {
1115         i->setHoldPosition(false);
1116     }
1117 }
1118
1119
1120 /***************************************************************************
1121  * class FGApproachController
1122  *
1123  **************************************************************************/
1124 FGApproachController::FGApproachController():
1125 FGATCController()
1126 {
1127 }
1128
1129 // 
1130 void FGApproachController::announcePosition(int id,
1131                                             FGAIFlightPlan * intendedRoute,
1132                                             int currentPosition,
1133                                             double lat, double lon,
1134                                             double heading, double speed,
1135                                             double alt, double radius,
1136                                             int leg, FGAIAircraft * ref)
1137 {
1138     init();
1139     TrafficVectorIterator i = activeTraffic.begin();
1140     // Search whether the current id alread has an entry
1141     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1142     if (activeTraffic.size()) {
1143         //while ((i->getId() != id) && i != activeTraffic.end()) {
1144         while (i != activeTraffic.end()) {
1145             if (i->getId() == id) {
1146                 break;
1147             }
1148             i++;
1149         }
1150     }
1151     // Add a new TrafficRecord if no one exsists for this aircraft.
1152     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1153         FGTrafficRecord rec;
1154         rec.setId(id);
1155
1156         rec.setPositionAndHeading(lat, lon, heading, speed, alt);
1157         rec.setRunway(intendedRoute->getRunway());
1158         rec.setLeg(leg);
1159         //rec.setCallSign(callsign);
1160         rec.setAircraft(ref);
1161         activeTraffic.push_back(rec);
1162     } else {
1163         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1164     }
1165 }
1166
1167 void FGApproachController::updateAircraftInformation(int id, double lat, double lon,
1168                                                      double heading, double speed, double alt,
1169                                                      double dt)
1170 {
1171     TrafficVectorIterator i = activeTraffic.begin();
1172     // Search search if the current id has an entry
1173     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1174     TrafficVectorIterator current, closest;
1175     if (activeTraffic.size()) {
1176         //while ((i->getId() != id) && i != activeTraffic.end()) {
1177         while (i != activeTraffic.end()) {
1178             if (i->getId() == id) {
1179                 break;
1180             }
1181             i++;
1182         }
1183     }
1184 //    // update position of the current aircraft
1185     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1186         SG_LOG(SG_GENERAL, SG_ALERT,
1187                "AI error: updating aircraft without traffic record");
1188     } else {
1189         i->setPositionAndHeading(lat, lon, heading, speed, alt);
1190         current = i;
1191         //cerr << "ApproachController: checking for speed" << endl;
1192         time_t time_diff =
1193             current->getAircraft()->
1194             checkForArrivalTime(string("final001"));
1195         if (time_diff > 15) {
1196             current->setSpeedAdjustment(current->getAircraft()->
1197                                         getPerformance()->vDescent() *
1198                                         1.35);
1199         } else if (time_diff > 5) {
1200             current->setSpeedAdjustment(current->getAircraft()->
1201                                         getPerformance()->vDescent() *
1202                                         1.2);
1203         } else if (time_diff < -15) {
1204             current->setSpeedAdjustment(current->getAircraft()->
1205                                         getPerformance()->vDescent() *
1206                                         0.65);
1207         } else if (time_diff < -5) {
1208             current->setSpeedAdjustment(current->getAircraft()->
1209                                         getPerformance()->vDescent() *
1210                                         0.8);
1211         } else {
1212             current->clearSpeedAdjustment();
1213         }
1214         //current->setSpeedAdjustment(current->getAircraft()->getPerformance()->vDescent() + time_diff);
1215     }
1216     setDt(getDt() + dt);
1217 }
1218
1219 void FGApproachController::signOff(int id)
1220 {
1221     TrafficVectorIterator i = activeTraffic.begin();
1222     // Search search if the current id alread has an entry
1223     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1224     if (activeTraffic.size()) {
1225         //while ((i->getId() != id) && i != activeTraffic.end()) {
1226         while (i != activeTraffic.end()) {
1227             if (i->getId() == id) {
1228                 break;
1229             }
1230             i++;
1231         }
1232     }
1233     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1234         SG_LOG(SG_GENERAL, SG_ALERT,
1235                "AI error: Aircraft without traffic record is signing off from approach");
1236     } else {
1237         i = activeTraffic.erase(i);
1238     }
1239 }
1240
1241
1242
1243
1244 bool FGApproachController::hasInstruction(int id)
1245 {
1246     TrafficVectorIterator i = activeTraffic.begin();
1247     // Search search if the current id has an entry
1248     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1249     if (activeTraffic.size()) {
1250         //while ((i->getId() != id) && i != activeTraffic.end()) {
1251         while (i != activeTraffic.end()) {
1252             if (i->getId() == id) {
1253                 break;
1254             }
1255             i++;
1256         }
1257     }
1258     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1259         SG_LOG(SG_GENERAL, SG_ALERT,
1260                "AI error: checking ATC instruction for aircraft without traffic record");
1261     } else {
1262         return i->hasInstruction();
1263     }
1264     return false;
1265 }
1266
1267
1268 FGATCInstruction FGApproachController::getInstruction(int id)
1269 {
1270     TrafficVectorIterator i = activeTraffic.begin();
1271     // Search search if the current id has an entry
1272     // This might be faster using a map instead of a vector, but let's start by taking a safe route
1273     if (activeTraffic.size()) {
1274         //while ((i->getId() != id) && i != activeTraffic.end()) {
1275         while (i != activeTraffic.end()) {
1276             if (i->getId() == id) {
1277                 break;
1278             }
1279             i++;
1280         }
1281     }
1282     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
1283         SG_LOG(SG_GENERAL, SG_ALERT,
1284                "AI error: requesting ATC instruction for aircraft without traffic record");
1285     } else {
1286         return i->getInstruction();
1287     }
1288     return FGATCInstruction();
1289 }
1290
1291
1292 ActiveRunway *FGApproachController::getRunway(string name)
1293 {
1294     ActiveRunwayVecIterator rwy = activeRunways.begin();
1295     if (activeRunways.size()) {
1296         while (rwy != activeRunways.end()) {
1297             if (rwy->getRunwayName() == name) {
1298                 break;
1299             }
1300             rwy++;
1301         }
1302     }
1303     if (rwy == activeRunways.end()) {
1304         ActiveRunway aRwy(name, 0);
1305         activeRunways.push_back(aRwy);
1306         rwy = activeRunways.end() - 1;
1307     }
1308     return &(*rwy);
1309 }