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