]> git.mxchange.org Git - flightgear.git/blob - src/ATC/trafficcontrol.cxx
Merge branch 'maint' into next
[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 "trafficcontrol.hxx"
28 #include <AIModel/AIAircraft.hxx>
29 #include <AIModel/AIFlightPlan.hxx>
30 #include <Traffic/TrafficMgr.hxx>
31 #include <Airports/groundnetwork.hxx>
32 #include <Airports/dynamics.hxx>
33
34 /***************************************************************************
35  * FGTrafficRecord
36  **************************************************************************/
37 FGTrafficRecord::FGTrafficRecord() :
38   id(0), waitsForId(0),
39   currentPos(0),
40   leg(0),
41   state(0),
42   latitude(0),
43   longitude(0), 
44    heading(0), 
45    speed(0), 
46    altitude(0), 
47    radius(0),
48    allowTransmission(true) {
49 }
50
51 void FGTrafficRecord::setPositionAndIntentions(int pos, FGAIFlightPlan *route)
52 {
53  
54    currentPos = pos;
55    if (intentions.size()) {
56      intVecIterator i = intentions.begin();
57      if ((*i) != pos) {
58        SG_LOG(SG_GENERAL, SG_ALERT, "Error in FGTrafficRecord::setPositionAndIntentions");
59        //cerr << "Pos : " << pos << " Curr " << *(intentions.begin())  << endl;
60        for (intVecIterator i = intentions.begin(); i != intentions.end() ; i++) {
61         //cerr << (*i) << " ";
62        }
63        //cerr << endl;
64      }
65      intentions.erase(i);
66    } else {
67      //int legNr, routeNr;
68      //FGAIFlightPlan::waypoint* const wpt= route->getCurrentWaypoint();
69      int size = route->getNrOfWayPoints();
70      //cerr << "Setting pos" << pos << " ";
71      //cerr << "setting intentions ";
72      for (int i = 0; i < size; i++) {
73        int val = route->getRouteIndex(i);
74        //cerr << val<< " ";
75        if ((val) && (val != pos))
76         {
77           intentions.push_back(val); 
78           //cerr << "[set] ";
79         }
80      }
81      //cerr << endl;
82      //while (route->next(&legNr, &routeNr)) {
83      //intentions.push_back(routeNr);
84      //}
85      //route->rewind(currentPos);
86    }
87    //exit(1);
88 }
89
90 bool FGTrafficRecord::checkPositionAndIntentions(FGTrafficRecord &other)
91 {
92    bool result = false;
93    //cerr << "Start check 1" << endl;
94    if (currentPos == other.currentPos) 
95      {
96        //cerr << callsign << ": Check Position and intentions: we are on the same taxiway" << other.callsign << "Index = " << currentPos << endl;
97        result = true;
98      }
99   //  else if (other.intentions.size()) 
100  //     {
101  //       cerr << "Start check 2" << endl;
102  //       intVecIterator i = other.intentions.begin(); 
103  //       while (!((i == other.intentions.end()) || ((*i) == currentPos)))
104  //     i++;
105  //       if (i != other.intentions.end()) {
106  //     cerr << "Check Position and intentions: current matches other.intentions" << endl;
107  //     result = true;
108  //       }
109    else if (intentions.size()) {
110      //cerr << "Start check 3" << endl;
111      intVecIterator i = intentions.begin(); 
112      //while (!((i == intentions.end()) || ((*i) == other.currentPos)))
113      while (i != intentions.end()) {
114        if ((*i) == other.currentPos) {
115          break;
116        }
117        i++;
118      }
119      if (i != intentions.end()) {
120        //cerr << callsign << ": Check Position and intentions: .other.current matches" << other.callsign << "Index = " << (*i) << endl;
121        result = true;
122      }
123    }
124    //cerr << "Done !!" << endl;
125    return result;
126 }
127
128 void FGTrafficRecord::setPositionAndHeading(double lat, double lon, double hdg, 
129                                             double spd, double alt)
130 {
131   latitude = lat;
132   longitude = lon;
133   heading = hdg;
134   speed = spd;
135   altitude = alt;
136 }
137
138 int FGTrafficRecord::crosses(FGGroundNetwork *net, FGTrafficRecord &other)
139 {
140    if (checkPositionAndIntentions(other) || (other.checkPositionAndIntentions(*this)))
141      return -1;
142    intVecIterator i, j;
143    int currentTargetNode = 0, otherTargetNode = 0;
144    if (currentPos > 0)
145      currentTargetNode = net->findSegment(currentPos      )->getEnd()->getIndex(); // OKAY,... 
146    if (other.currentPos > 0)
147      otherTargetNode   = net->findSegment(other.currentPos)->getEnd()->getIndex(); // OKAY,...
148    if ((currentTargetNode == otherTargetNode) && currentTargetNode > 0)
149      return currentTargetNode;
150    if (intentions.size())
151      {
152        for (i = intentions.begin(); i != intentions.end(); i++)
153         {
154           if ((*i) > 0) {
155             if ((currentTargetNode == net->findSegment(*i)->getEnd()->getIndex()))
156               {
157                 //cerr << "Current crosses at " << currentTargetNode <<endl;
158                 return currentTargetNode;
159               }
160           }
161         }
162      }
163    if (other.intentions.size())
164      {
165        for (i = other.intentions.begin(); i != other.intentions.end(); i++)
166         {
167           if ((*i) > 0) {
168             if (otherTargetNode == net->findSegment(*i)->getEnd()->getIndex())
169               {
170                 //cerr << "Other crosses at " << currentTargetNode <<endl;
171                 return otherTargetNode;
172               }
173           }
174         }
175      }
176    if (intentions.size() && other.intentions.size())
177      {
178        for (i = intentions.begin(); i != intentions.end(); i++) 
179         {
180           for (j = other.intentions.begin(); j != other.intentions.end(); j++)
181             {
182               //cerr << "finding segment " << *i << " and " << *j << endl;
183               if (((*i) > 0) && ((*j) > 0)) {
184                 currentTargetNode = net->findSegment(*i)->getEnd()->getIndex();
185                 otherTargetNode   = net->findSegment(*j)->getEnd()->getIndex();
186                 if (currentTargetNode == otherTargetNode) 
187                   {
188                     //cerr << "Routes will cross at " << currentTargetNode << endl;
189                     return currentTargetNode;
190                   }
191               }
192             }
193         }
194      }
195   return -1;
196 }
197
198 bool FGTrafficRecord::onRoute(FGGroundNetwork *net, FGTrafficRecord &other)
199 {
200   int node = -1, othernode = -1;
201   if (currentPos >0)
202     node = net->findSegment(currentPos)->getEnd()->getIndex();
203   if (other.currentPos > 0)
204     othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
205   if ((node == othernode) && (node != -1))
206     return true;
207   if (other.intentions.size())
208     {
209       for (intVecIterator i = other.intentions.begin(); i != other.intentions.end(); i++)
210         {
211           if (*i > 0) 
212             {
213               othernode = net->findSegment(*i)->getEnd()->getIndex();
214               if ((node == othernode) && (node > -1))
215                 return true;
216             }
217         }
218     }
219   //if (other.currentPos > 0)
220   //  othernode = net->findSegment(other.currentPos)->getEnd()->getIndex();
221   //if (intentions.size())
222   //  {
223   //    for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
224   //    {
225   //      if (*i > 0) 
226   //        {
227   //          node = net->findSegment(*i)->getEnd()->getIndex();
228   //          if ((node == othernode) && (node > -1))
229   //            return true;
230   //        }
231   //    }
232   //  }
233   return false;
234 }
235
236
237 bool FGTrafficRecord::isOpposing (FGGroundNetwork *net, FGTrafficRecord &other, int node)
238 {
239    // Check if current segment is the reverse segment for the other aircraft
240    FGTaxiSegment *opp;
241    //cerr << "Current segment " << currentPos << endl;
242    if ((currentPos > 0) && (other.currentPos > 0))
243      {
244        opp = net->findSegment(currentPos)->opposite();
245        if (opp) {
246         if (opp->getIndex() == other.currentPos)
247           return true;
248        }
249       
250        for (intVecIterator i = intentions.begin(); i != intentions.end(); i++)
251         {
252          if ((opp = net->findSegment(other.currentPos)->opposite()))
253             {
254               if ((*i) > 0)
255                 if (opp->getIndex() == net->findSegment(*i)->getIndex())
256                   {
257                     if (net->findSegment(*i)->getStart()->getIndex() == node) {
258                       {
259                         //cerr << "Found the node " << node << endl;
260                         return true;
261                       }
262                     }
263                   }
264             }
265           if (other.intentions.size())
266             {
267               for (intVecIterator j = other.intentions.begin(); j != other.intentions.end(); j++)
268                 {
269                   // cerr << "Current segment 1 " << (*i) << endl;
270                   if ((*i) > 0) {
271                     if ((opp = net->findSegment(*i)->opposite()))
272                       {
273                         if (opp->getIndex() == 
274                             net->findSegment(*j)->getIndex())
275                           {
276                             //cerr << "Nodes " << net->findSegment(*i)->getIndex()
277                             //   << " and  " << net->findSegment(*j)->getIndex()
278                             //   << " are opposites " << endl;
279                             if (net->findSegment(*i)->getStart()->getIndex() == node) {
280                               {
281                                 //cerr << "Found the node " << node << endl;
282                                 return true;
283                               }
284                             }
285                           }
286                       }
287                   }
288                 }
289             }
290         }
291      }
292    return false;
293 }
294
295 void FGTrafficRecord::setSpeedAdjustment(double spd) 
296
297   instruction.setChangeSpeed(true); 
298   instruction.setSpeed(spd); 
299 }
300
301 void FGTrafficRecord::setHeadingAdjustment(double heading) 
302
303   instruction.setChangeHeading(true);
304   instruction.setHeading(heading); 
305 }
306
307 bool FGTrafficRecord::pushBackAllowed() {
308       double course, az2,dist;
309        SGGeod curr(SGGeod::fromDegM(getLongitude(),
310                                        getLatitude(), 
311                                        getAltitude()));
312
313       double userLatitude  = fgGetDouble("/position/latitude-deg");
314       double userLongitude = fgGetDouble("/position/longitude-deg");
315       SGGeod user(SGGeod::fromDeg(userLongitude,userLatitude));
316       SGGeodesy::inverse(curr, user, course, az2, dist);
317       //cerr << "Distance to user : " << dist << endl;
318       return (dist > 250);
319
320 }
321
322
323
324 /***************************************************************************
325  * FGATCInstruction
326  *
327  **************************************************************************/
328 FGATCInstruction::FGATCInstruction()
329 {
330   holdPattern    = false; 
331   holdPosition   = false;
332   changeSpeed    = false;
333   changeHeading  = false;
334   changeAltitude = false;
335   resolveCircularWait = false;
336
337   speed   = 0;
338   heading = 0;
339   alt     = 0;
340 }
341
342 bool FGATCInstruction::hasInstruction()
343 {
344   return (holdPattern || holdPosition || changeSpeed || changeHeading || changeAltitude || resolveCircularWait);
345 }
346
347 string FGATCController::getGateName(FGAIAircraft *ref) 
348 {
349     return ref->atGate();
350 }
351
352 void FGATCController::transmit(FGTrafficRecord *rec, AtcMsgId msgId, AtcMsgDir msgDir)
353 {
354     string sender, receiver;
355     int stationFreq = 0;
356     int taxiFreq    = 0;
357     string atisInformation;
358     //double commFreqD;
359     switch (msgDir) {
360          case ATC_AIR_TO_GROUND:
361              sender = rec->getAircraft()->getTrafficRef()->getCallSign();
362              switch (rec->getLeg()) {
363                  case 2:
364                  case 3:
365                      stationFreq =
366                         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getGroundFrequency(rec->getLeg());
367                      taxiFreq =
368                         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getGroundFrequency(3);
369                      receiver = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getName() + "-Ground";
370                      atisInformation = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getAtisInformation();
371                      break;
372                  case 4: 
373                      receiver = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getName() + "-Tower";
374                      break;
375              }
376              break;
377          case ATC_GROUND_TO_AIR:
378              receiver = rec->getAircraft()->getTrafficRef()->getCallSign();
379              switch (rec->getLeg()) {
380                  case 2:
381                  case 3:
382                  stationFreq =
383                         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getGroundFrequency(rec->getLeg());
384                      taxiFreq =
385                         rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getGroundFrequency(3);
386                      sender = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getName() + "-Ground";
387                      atisInformation = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getAtisInformation();
388                      break;
389
390                  case 4: 
391                      sender = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getName() + "-Tower";
392                      break;
393              }
394              break;
395          }
396     string text;
397     string taxiFreqStr;
398     double heading = 0;
399     string activeRunway;
400     string fltType;
401     string rwyClass;
402     string SID;
403     string transponderCode;
404     FGAIFlightPlan *fp;
405     string fltRules;
406     switch (msgId) {
407           case MSG_ANNOUNCE_ENGINE_START:
408                text = sender + ". Ready to Start up";
409                break;
410           case MSG_REQUEST_ENGINE_START:
411                text = receiver + ", This is " + sender + ". Position " +getGateName(rec->getAircraft()) +
412                        ". Information " + atisInformation + ". " +
413                        rec->getAircraft()->getTrafficRef()->getFlightRules() + " to " + 
414                        rec->getAircraft()->getTrafficRef()->getArrivalAirport()->getName() + ". Request start-up";
415                break;
416           // Acknowledge engine startup permission
417           // Assign departure runway
418           // Assign SID, if necessery (TODO)
419           case MSG_PERMIT_ENGINE_START:
420                taxiFreqStr = formatATCFrequency3_2(taxiFreq);
421
422                heading = rec->getAircraft()->getTrafficRef()->getCourse();
423                fltType = rec->getAircraft()->getTrafficRef()->getFlightType();
424                rwyClass= rec->getAircraft()->GetFlightPlan()->getRunwayClassFromTrafficType(fltType);
425
426                rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getActiveRunway(rwyClass, 1, activeRunway, heading);
427                rec->getAircraft()->GetFlightPlan()->setRunway(activeRunway);
428                fp = rec->getAircraft()->getTrafficRef()->getDepartureAirport()->getDynamics()->getSID(activeRunway, heading);
429                rec->getAircraft()->GetFlightPlan()->setSID(fp);
430                if (fp) {
431                    SID = fp->getName() + " departure";
432                } else {
433                    SID = "fly runway heading ";
434                }
435                //snprintf(buffer, 7, "%3.2f", heading);
436                fltRules = rec->getAircraft()->getTrafficRef()->getFlightRules();
437                transponderCode = genTransponderCode(fltRules);
438                rec->getAircraft()->SetTransponderCode(transponderCode);
439                text = receiver + ". Start-up approved. " + atisInformation + " correct, runway " + activeRunway
440                        + ", " + SID + ", squawk " + transponderCode + ". " +
441                       "For push-back and taxi clearance call " + taxiFreqStr + ". " + sender + " control.";
442                break;
443           case MSG_DENY_ENGINE_START:
444                text = receiver + ". Standby";
445                break;
446          case MSG_ACKNOWLEDGE_ENGINE_START:
447                fp = rec->getAircraft()->GetFlightPlan()->getSID();
448                if (fp) {
449                   SID = rec->getAircraft()->GetFlightPlan()->getSID()->getName() + " departure";
450                } else {
451                   SID = "fly runway heading ";
452                }
453                taxiFreqStr = formatATCFrequency3_2(taxiFreq);
454                activeRunway = rec->getAircraft()->GetFlightPlan()->getRunway();
455                transponderCode = rec->getAircraft()->GetTransponderCode();
456                text = receiver + ". Start-up approved. " + atisInformation + " correct, runway " +
457                       activeRunway + ", " + SID + ", squawk " + transponderCode + ". " +
458                       "For push-back and taxi clearance call " + taxiFreqStr + ". " + sender;
459                break;
460            case MSG_REQUEST_PUSHBACK_CLEARANCE:
461                text = receiver + ". Request push-back. " + sender;
462                break;
463            case MSG_PERMIT_PUSHBACK_CLEARANCE:
464                text = receiver + ". Push-back approved. " + sender;
465                break;
466            case MSG_HOLD_PUSHBACK_CLEARANCE:
467                 text = receiver + ". Standby. " + sender;
468                  break;
469             default:
470                  text = sender + ". Transmitting unknown Message";
471                   break;
472     }
473     double onBoardRadioFreq0 = fgGetDouble("/instrumentation/comm[0]/frequencies/selected-mhz");
474     double onBoardRadioFreq1 = fgGetDouble("/instrumentation/comm[1]/frequencies/selected-mhz");
475     int onBoardRadioFreqI0 = (int) floor(onBoardRadioFreq0 * 100 + 0.5);
476     int onBoardRadioFreqI1 = (int) floor(onBoardRadioFreq1 * 100 + 0.5);
477     //cerr << "Using " << onBoardRadioFreq0 << ", " << onBoardRadioFreq1 << " and " << stationFreq << endl;
478
479     // Display ATC message only when one of the radios is tuned
480     // the relevant frequency.
481     // Note that distance attenuation is currently not yet implemented
482     if ((onBoardRadioFreqI0 == stationFreq) || (onBoardRadioFreqI1 == stationFreq)) {
483         if (rec->allowTransmissions()) {
484             fgSetString("/sim/messages/atc", text.c_str());
485         }
486     }
487 }
488
489 string FGATCController::formatATCFrequency3_2(int freq) {
490     char buffer[7];
491     snprintf(buffer, 7, "%3.2f", ( (float) freq / 100.0) );
492     return string(buffer);
493 }
494
495 // TODO: Set transponder codes according to real-world routes.
496 // The current version just returns a random string of four octal numbers. 
497 string FGATCController::genTransponderCode(string fltRules) {
498     if (fltRules == "VFR") {
499         return string("1200");
500     } else {
501         char buffer[5];
502         snprintf(buffer, 5, "%d%d%d%d", rand() % 8, rand() % 8,rand() % 8, rand() % 8);
503         return string(buffer);
504     }
505 }
506
507 /***************************************************************************
508  * class FGTowerController
509  *
510  **************************************************************************/
511 FGTowerController::FGTowerController() :
512   FGATCController()
513 {
514 }
515
516 // 
517 void FGTowerController::announcePosition(int id, FGAIFlightPlan *intendedRoute, int currentPosition,
518                                          double lat, double lon, double heading, 
519                                          double speed, double alt, double radius, int leg,
520                                          FGAIAircraft *ref)
521 {
522   TrafficVectorIterator i = activeTraffic.begin();
523   // Search whether the current id alread has an entry
524   // This might be faster using a map instead of a vector, but let's start by taking a safe route
525   if (activeTraffic.size()) {
526     //while ((i->getId() != id) && i != activeTraffic.end()) {
527     while (i != activeTraffic.end()) {
528       if (i->getId() == id) {
529         break;
530       }
531       i++;
532     }
533   }
534   
535   // Add a new TrafficRecord if no one exsists for this aircraft.
536   if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
537     FGTrafficRecord rec;
538     rec.setId(id);
539
540     rec.setPositionAndHeading(lat, lon, heading, speed, alt);
541     rec.setRunway(intendedRoute->getRunway());
542     rec.setLeg(leg);
543     //rec.setCallSign(callsign);
544     rec.setAircraft(ref);
545     activeTraffic.push_back(rec);
546   } else {
547     i->setPositionAndHeading(lat, lon, heading, speed, alt);
548   }
549 }
550
551 void FGTowerController::update(int id, double lat, double lon, double heading, double speed, double alt, 
552                              double dt)
553 {
554     TrafficVectorIterator i = activeTraffic.begin();
555     // Search search if the current id has an entry
556     // This might be faster using a map instead of a vector, but let's start by taking a safe route
557     TrafficVectorIterator current, closest;
558     if (activeTraffic.size()) {
559       //while ((i->getId() != id) && i != activeTraffic.end()) {
560       while (i != activeTraffic.end()) {
561         if (i->getId() == id) {
562           break;
563         }
564         i++;
565       }
566     }
567
568 //    // update position of the current aircraft
569     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
570       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: updating aircraft without traffic record");
571     } else {
572       i->setPositionAndHeading(lat, lon, heading, speed, alt);
573       current = i;
574     }
575     setDt(getDt() + dt);
576
577 //    // see if we already have a clearance record for the currently active runway
578     ActiveRunwayVecIterator rwy = activeRunways.begin();
579     // again, a map might be more efficient here
580     if (activeRunways.size()) {
581       //while ((rwy->getRunwayName() != current->getRunway()) && (rwy != activeRunways.end())) {
582       while (rwy != activeRunways.end()) {
583         if (rwy->getRunwayName() == current->getRunway()) {
584           break;
585         }
586         rwy++;
587       }
588     }
589     if (rwy == activeRunways.end()) {
590       ActiveRunway aRwy(current->getRunway(), id);
591       activeRunways.push_back(aRwy);   // Since there are no clearance records for this runway yet
592       current->setHoldPosition(false); // Clear the current aircraft to continue
593     }
594     else {
595       // Okay, we have a clearance record for this runway, so check
596       // whether the clearence ID matches that of the current aircraft
597       if (id == rwy->getCleared()) {
598         current->setHoldPosition(false);
599       } else {
600         current->setHoldPosition(true);
601       }
602     }
603 }
604
605
606 void FGTowerController::signOff(int id) 
607 {
608   TrafficVectorIterator i = activeTraffic.begin();
609   // Search search if the current id alread has an entry
610   // This might be faster using a map instead of a vector, but let's start by taking a safe route
611     if (activeTraffic.size()) {
612       //while ((i->getId() != id) && i != activeTraffic.end()) {
613       while (i != activeTraffic.end()) {
614         if (i->getId() == id) {
615           break;
616         }
617         i++;
618       }
619     }
620     // If this aircraft has left the runway, we can clear the departure record for this runway
621     ActiveRunwayVecIterator rwy = activeRunways.begin();
622     if (activeRunways.size()) {
623       //while ((rwy->getRunwayName() != i->getRunway()) && (rwy != activeRunways.end())) {
624       while (rwy != activeRunways.end()) {
625         if (rwy->getRunwayName() == i->getRunway()) {
626           break;
627         }
628         rwy++;
629       }
630       if (rwy != activeRunways.end()) {
631         rwy = activeRunways.erase(rwy);
632       } else {
633         SG_LOG(SG_GENERAL, SG_ALERT, "AI error: Attempting to erase non-existing runway clearance record in FGTowerController::signoff");
634       }
635     }
636     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
637       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: Aircraft without traffic record is signing off from tower");
638     } else {
639       i = activeTraffic.erase(i);
640     }
641 }
642
643 // NOTE:
644 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
645 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
646 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
647 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
648 // Note that this function is probably obsolete
649 bool FGTowerController::hasInstruction(int id)
650 {
651     TrafficVectorIterator i = activeTraffic.begin();
652     // Search search if the current id has an entry
653     // This might be faster using a map instead of a vector, but let's start by taking a safe route
654     if (activeTraffic.size()) 
655       {
656         //while ((i->getId() != id) && i != activeTraffic.end()) {
657         while (i != activeTraffic.end()) {
658           if (i->getId() == id) {
659             break;
660           }
661         i++;
662       }
663     }
664     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
665       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: checking ATC instruction for aircraft without traffic record");
666     } else {
667       return i->hasInstruction();
668     }
669   return false;
670 }
671
672
673 FGATCInstruction FGTowerController::getInstruction(int id)
674 {
675   TrafficVectorIterator i = activeTraffic.begin();
676   // Search search if the current id has an entry
677   // This might be faster using a map instead of a vector, but let's start by taking a safe route
678   if (activeTraffic.size()) {
679     //while ((i->getId() != id) && i != activeTraffic.end()) {
680     while (i != activeTraffic.end()) {
681       if (i->getId() == id) {
682         break;
683       }
684       i++;
685     }
686   }
687   if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
688     SG_LOG(SG_GENERAL, SG_ALERT, "AI error: requesting ATC instruction for aircraft without traffic record");
689   } else {
690     return i->getInstruction();
691   }
692   return FGATCInstruction();
693 }
694
695 /***************************************************************************
696  * class FGStartupController
697  *
698  **************************************************************************/
699 FGStartupController::FGStartupController() :
700   FGATCController()
701 {
702     available        = false;
703     lastTransmission = 0;
704 }
705
706 void FGStartupController::announcePosition(int id, FGAIFlightPlan *intendedRoute, int currentPosition,
707                                          double lat, double lon, double heading, 
708                                          double speed, double alt, double radius, int leg,
709                                          FGAIAircraft *ref)
710 {
711   TrafficVectorIterator i = activeTraffic.begin();
712   // Search whether the current id alread has an entry
713   // This might be faster using a map instead of a vector, but let's start by taking a safe route
714   if (activeTraffic.size()) {
715     //while ((i->getId() != id) && i != activeTraffic.end()) {
716     while (i != activeTraffic.end()) {
717       if (i->getId() == id) {
718         break;
719       }
720       i++;
721     }
722   }
723   
724   // Add a new TrafficRecord if no one exsists for this aircraft.
725   if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
726     FGTrafficRecord rec;
727     rec.setId(id);
728
729     rec.setPositionAndHeading(lat, lon, heading, speed, alt);
730     rec.setRunway(intendedRoute->getRunway());
731     rec.setLeg(leg);
732     //rec.setCallSign(callsign);
733     rec.setAircraft(ref);
734     rec.setHoldPosition(true);
735     activeTraffic.push_back(rec);
736     } else {
737         i->setPositionAndHeading(lat, lon, heading, speed, alt);
738         
739   }
740 }
741
742 // NOTE:
743 // IF WE MAKE TRAFFICRECORD A MEMBER OF THE BASE CLASS
744 // THE FOLLOWING THREE FUNCTIONS: SIGNOFF, HAS INSTRUCTION AND GETINSTRUCTION CAN 
745 // BECOME DEVIRTUALIZED AND BE A MEMBER OF THE BASE ATCCONTROLLER CLASS
746 // WHICH WOULD SIMPLIFY CODE MAINTENANCE.
747 // Note that this function is probably obsolete
748 bool FGStartupController::hasInstruction(int id)
749 {
750     TrafficVectorIterator i = activeTraffic.begin();
751     // Search search if the current id has an entry
752     // This might be faster using a map instead of a vector, but let's start by taking a safe route
753     if (activeTraffic.size()) 
754       {
755         //while ((i->getId() != id) && i != activeTraffic.end()) {
756         while (i != activeTraffic.end()) {
757           if (i->getId() == id) {
758             break;
759           }
760         i++;
761       }
762     }
763     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
764       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: checking ATC instruction for aircraft without traffic record");
765     } else {
766       return i->hasInstruction();
767     }
768   return false;
769 }
770
771
772 FGATCInstruction FGStartupController::getInstruction(int id)
773 {
774   TrafficVectorIterator i = activeTraffic.begin();
775   // Search search if the current id has an entry
776   // This might be faster using a map instead of a vector, but let's start by taking a safe route
777   if (activeTraffic.size()) {
778     //while ((i->getId() != id) && i != activeTraffic.end()) {
779     while (i != activeTraffic.end()) {
780       if (i->getId() == id) {
781         break;
782       }
783       i++;
784     }
785   }
786   if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
787     SG_LOG(SG_GENERAL, SG_ALERT, "AI error: requesting ATC instruction for aircraft without traffic record");
788   } else {
789     return i->getInstruction();
790   }
791   return FGATCInstruction();
792 }
793
794 void FGStartupController::signOff(int id) 
795 {
796   TrafficVectorIterator i = activeTraffic.begin();
797   // Search search if the current id alread has an entry
798   // This might be faster using a map instead of a vector, but let's start by taking a safe route
799     if (activeTraffic.size()) {
800       //while ((i->getId() != id) && i != activeTraffic.end()) {
801       while (i != activeTraffic.end()) {
802         if (i->getId() == id) {
803           break;
804         }
805         i++;
806       }
807     }
808     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
809       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: Aircraft without traffic record is signing off from tower");
810     } else {
811       i = activeTraffic.erase(i);
812     }
813 }
814
815 void FGStartupController::update(int id, double lat, double lon, double heading, double speed, double alt, 
816                              double dt)
817 {
818     TrafficVectorIterator i = activeTraffic.begin();
819     // Search search if the current id has an entry
820     // This might be faster using a map instead of a vector, but let's start by taking a safe route
821     TrafficVectorIterator current, closest;
822     if (activeTraffic.size()) {
823       //while ((i->getId() != id) && i != activeTraffic.end()) {
824       while (i != activeTraffic.end()) {
825         if (i->getId() == id) {
826           break;
827         }
828         i++;
829       }
830     }
831
832 //    // update position of the current aircraft
833     if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
834       SG_LOG(SG_GENERAL, SG_ALERT, "AI error: updating aircraft without traffic record");
835     } else {
836       i->setPositionAndHeading(lat, lon, heading, speed, alt);
837       current = i;
838     }
839     setDt(getDt() + dt);
840
841     int state = i->getState();
842     time_t startTime = i->getAircraft()->getTrafficRef()->getDepartureTime();
843     time_t now       = time(NULL) + fgGetLong("/sim/time/warp");
844     //cerr << i->getAircraft()->getTrafficRef()->getCallSign() 
845     //     << " is scheduled to depart in " << startTime-now << " seconds. Available = " << available
846     //     << " at parking " << getGateName(i->getAircraft()) << endl;
847
848     if ((now - lastTransmission) > 3 + (rand() % 15)) {
849         available = true;
850     }
851
852     if ((state == 0) && available) {
853         if (now > startTime) {
854              //cerr << "Transmitting startup msg" << endl;
855              transmit(&(*i), MSG_ANNOUNCE_ENGINE_START, ATC_AIR_TO_GROUND);
856              i->updateState();
857              lastTransmission = now;
858              available = false;
859         }
860     }
861     if ((state == 1) && available) {
862         if (now > startTime+60) {
863             transmit(&(*i), MSG_REQUEST_ENGINE_START, ATC_AIR_TO_GROUND);
864             i->updateState();
865             lastTransmission = now;
866              available = false;
867         }
868     }
869     if ((state == 2) && available) {
870         if (now > startTime+80) {
871             transmit(&(*i), MSG_PERMIT_ENGINE_START, ATC_GROUND_TO_AIR);
872             i->updateState();
873             lastTransmission = now;
874              available = false;
875         }
876     }
877     if ((state == 3) && available){
878         if (now > startTime+100) {
879             transmit(&(*i), MSG_ACKNOWLEDGE_ENGINE_START, ATC_AIR_TO_GROUND);
880             i->updateState();
881             lastTransmission = now;
882              available = false;
883         }
884      }
885      // TODO: Switch to APRON control and request pushback Clearance.
886      // Get Push back clearance
887      if ((state == 4) && available){
888         if (now > startTime+130) {
889             transmit(&(*i), MSG_REQUEST_PUSHBACK_CLEARANCE, ATC_AIR_TO_GROUND);
890             i->updateState();
891             lastTransmission = now;
892              available = false;
893         }
894      }
895      if ((state == 5) && available){
896         if (now > startTime+130) {
897             if (i->pushBackAllowed()) {
898                  i->allowRepeatedTransmissions();
899                  transmit(&(*i), MSG_PERMIT_PUSHBACK_CLEARANCE, ATC_GROUND_TO_AIR);
900                  i->updateState();
901             } else {
902                  transmit(&(*i), MSG_HOLD_PUSHBACK_CLEARANCE, ATC_GROUND_TO_AIR);
903                  i->suppressRepeatedTransmissions();
904             }
905             lastTransmission = now;
906              available = false;
907         }
908      }
909      if ((state == 6) && available){
910           i->setHoldPosition(false);
911      }
912 }