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