]> git.mxchange.org Git - flightgear.git/blob - src/ATC/atc_mgr.cxx
Fix crash starting at heliport.
[flightgear.git] / src / ATC / atc_mgr.cxx
1 /******************************************************************************
2  * atc_mgr.cxx
3  * Written by Durk Talsma, started August 1, 2010.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18  *
19  *
20  **************************************************************************/
21
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <iostream>
28
29 #include <Airports/dynamics.hxx>
30 #include <Airports/airport.hxx>
31 #include <Scenery/scenery.hxx>
32 #include "atc_mgr.hxx"
33
34
35 FGATCManager::FGATCManager() {
36     controller = 0;
37     prevController = 0;
38     networkVisible = false;
39     initSucceeded  = false;
40 }
41
42 FGATCManager::~FGATCManager() {
43
44 }
45
46 void FGATCManager::init() {
47     SGSubsystem::init();
48
49     int leg = 0;
50
51     trans_num = globals->get_props()->getNode("/sim/atc/transmission-num", true);
52
53     // find a reasonable controller for our user's aircraft..
54     // Let's start by working out the following three scenarios: 
55     // Starting on ground at a parking position
56     // Starting on ground at the runway.
57     // Starting in the Air
58     bool onGround  = fgGetBool("/sim/presets/onground");
59     string runway  = fgGetString("/sim/atc/runway");
60     string airport = fgGetString("/sim/presets/airport-id");
61     string parking = fgGetString("/sim/presets/parkpos");
62     
63
64     // Create an (invisible) AIAircraft represenation of the current
65     // Users, aircraft, that mimicks the user aircraft's behavior.
66     string callsign= fgGetString("/sim/multiplay/callsign");
67     double longitude = fgGetDouble("/position/longitude-deg");
68     double latitude  = fgGetDouble("/position/latitude-deg");
69     double altitude  = fgGetDouble("/position/altitude-ft");
70     double heading   = fgGetDouble("/orientation/heading-deg");
71     double speed     = fgGetDouble("/velocities/groundspeed-kt");
72     double aircraftRadius = 40; // note that this is currently hardcoded to a one-size-fits all JumboJet value. Should change later;
73
74
75     ai_ac.setCallSign ( callsign  );
76     ai_ac.setLongitude( longitude );
77     ai_ac.setLatitude ( latitude  );
78     ai_ac.setAltitude ( altitude  );
79     ai_ac.setPerformance("", "jet_transport");
80
81     // NEXT UP: Create a traffic Schedule and fill that with appropriate information. This we can use to flight planning.
82     // Note that these are currently only defaults. 
83     FGAISchedule *trafficRef = new FGAISchedule;
84     trafficRef->setFlightType("gate");
85
86     FGScheduledFlight *flight =  new FGScheduledFlight;
87     flight->setDepartureAirport(airport);
88     flight->setArrivalAirport(airport);
89     flight->initializeAirports();
90     flight->setFlightRules("IFR");
91     flight->setCallSign(callsign);
92     
93     trafficRef->assign(flight);
94     FGAIFlightPlan *fp = 0; 
95     ai_ac.setTrafficRef(trafficRef);
96     
97     string flightPlanName = airport + "-" + airport + ".xml";
98     //double cruiseAlt = 100; // Doesn't really matter right now.
99     //double courseToDest = 180; // Just use something neutral; this value might affect the runway that is used though...
100     //time_t deptime = 0;        // just make sure how flightplan processing is affected by this...
101
102
103     FGAirport *apt = FGAirport::findByIdent(airport); 
104     if (apt && onGround) {// && !runway.empty()) {
105         FGAirportDynamics* dcs = apt->getDynamics();
106         ParkingAssignment pk(dcs->getParkingByName(parking));
107       
108         // No valid parking location, so either at the runway or at a random location.
109         if (pk.isValid()) {
110             fp = new FGAIFlightPlan;
111             controller = apt->getDynamics()->getStartupController();
112             int stationFreq = apt->getDynamics()->getGroundFrequency(1);
113             if (stationFreq > 0)
114             {
115                 //cerr << "Setting radio frequency to : " << stationFreq << endl;
116                 fgSetDouble("/instrumentation/comm[0]/frequencies/selected-mhz", ((double) stationFreq / 100.0));
117             }
118             leg = 1;
119             //double, lat, lon, head; // Unused variables;
120             //int getId = apt->getDynamics()->getParking(gateId, &lat, &lon, &head);
121             aircraftRadius = pk.parking()->getRadius();
122             string fltType = pk.parking()->getType(); // gate / ramp, ga, etc etc.
123             string aircraftType; // Unused.
124             string airline;      // Currently used for gate selection, but a fallback mechanism will apply when not specified.
125             fp->setGate(pk);
126             if (!(fp->createPushBack(&ai_ac,
127                                      false,
128                                      apt,
129                                      aircraftRadius,
130                                      fltType,
131                                      aircraftType,
132                                      airline))) {
133                 controller = 0;
134                 return;
135             }
136
137             
138             
139         } else if (!runway.empty()) {
140             controller = apt->getDynamics()->getTowerController();
141             int stationFreq = apt->getDynamics()->getTowerFrequency(2);
142             if (stationFreq > 0)
143             {
144                 //cerr << "Setting radio frequency to in airfrequency: " << stationFreq << endl;
145                 fgSetDouble("/instrumentation/comm[0]/frequencies/selected-mhz", ((double) stationFreq / 100.0));
146             }
147             fp = new FGAIFlightPlan;
148             leg = 3;
149             string fltType = "ga";
150             fp->setRunway(runway);
151             fp->createTakeOff(&ai_ac, false, apt, 0, fltType);
152             ai_ac.setTakeOffStatus(2);
153         } else {
154                 // We're on the ground somewhere. Handle this case later.
155         }
156         
157         if (fp) {
158             fp->getLastWaypoint()->setName( fp->getLastWaypoint()->getName() + string("legend"));
159         }
160      } else {
161         controller = 0;
162      }
163
164     // Create an initial flightplan and assign it to the ai_ac. We won't use this flightplan, but it is necessary to
165     // keep the ATC code happy. 
166     if (fp) {
167         fp->restart();
168         fp->setLeg(leg);
169         ai_ac.SetFlightPlan(fp);
170     }
171     if (controller) {
172         controller->announcePosition(ai_ac.getID(), fp, fp->getCurrentWaypoint()->getRouteIndex(),
173                                       ai_ac._getLatitude(), ai_ac._getLongitude(), heading, speed, altitude,
174                                       aircraftRadius, leg, &ai_ac);
175
176     //dialog.init();
177
178    //osg::Node* node = apt->getDynamics()->getGroundNetwork()->getRenderNode();
179    //cerr << "Adding groundnetWork to the scenegraph::init" << endl;
180    //globals->get_scenery()->get_scene_graph()->addChild(node);
181    }
182    initSucceeded = true;
183 }
184
185 void FGATCManager::addController(FGATCController *controller) {
186     activeStations.push_back(controller);
187 }
188
189 void FGATCManager::update ( double time ) {
190     //cerr << "ATC update code is running at time: " << time << endl;
191     // Test code: let my virtual co-pilot handle ATC:
192    
193     
194
195     FGAIFlightPlan *fp = ai_ac.GetFlightPlan();
196         
197     /* test code : find out how the routing develops */
198     if (fp) {
199         int size = fp->getNrOfWayPoints();
200         //cerr << "Setting pos" << pos << " ";
201         //cerr << "setting intentions " ;
202         // This indicates that we have run out of waypoints: Im future versions, the
203         // user should be able to select a new route, but for now just shut down the
204         // system. 
205         if (size < 3) {
206             //cerr << "Shutting down the atc_mgr" << endl;
207             return;
208         }
209         //cerr << "Size of waypoint cue " << size << " ";
210         //for (int i = 0; i < size; i++) {
211         //    int val = fp->getRouteIndex(i);
212             //cerr << fp->getWayPoint(i)->getName() << " ";
213             //if ((val) && (val != pos)) {
214                 //intentions.push_back(val);
215                 //cerr << "[done ] " << endl;
216             //}
217         //}
218         //cerr << "[done ] " << endl;
219     }
220     if (fp) {
221         //cerr << "Currently at leg : " << fp->getLeg() << endl;
222     }
223     double longitude = fgGetDouble("/position/longitude-deg");
224     double latitude  = fgGetDouble("/position/latitude-deg");
225     double heading   = fgGetDouble("/orientation/heading-deg");
226     double speed     = fgGetDouble("/velocities/groundspeed-kt");
227     double altitude  = fgGetDouble("/position/altitude-ft");
228     
229     /*
230     SGGeod me(SGGeod::fromDegM(longitude,
231                                latitude,
232                                altitude));
233     SGGeod wpt1(SGGeod::fromDegM(fp->getWayPoint(1)->getLongitude(), 
234                                 fp->getWayPoint(1)->getLatitude(),
235                                 fp->getWayPoint(1)->getAltitude()));
236     SGGeod wpt2(SGGeod::fromDegM(fp->getWayPoint(1)->getLongitude(), 
237                                 fp->getWayPoint(1)->getLatitude(),
238                                 fp->getWayPoint(1)->getAltitude()));
239         
240     double course1, az1, dist1;
241     double course2, az2, dist2;
242     SGGeodesy::inverse(me, wpt1, course1, az1, dist1);
243     
244     cerr << "Bearing to nearest waypoint : " << course1 << " " << dist1 << ". (course " << course2 << ")." <<  endl;
245     */
246     ai_ac.setLatitude(latitude);
247     ai_ac.setLongitude(longitude);
248     ai_ac.setAltitude(altitude);
249     ai_ac.setHeading(heading);
250     ai_ac.setSpeed(speed);
251     ai_ac.update(time);
252     controller = ai_ac.getATCController();
253     FGATCDialogNew::instance()->update(time);
254     if (controller) {
255        //cerr << "name of previous waypoint : " << fp->getPreviousWaypoint()->getName() << endl;
256
257         //cerr << "Running FGATCManager::update()" << endl;
258         //cerr << "Currently under control of " << controller->getName() << endl;
259         controller->updateAircraftInformation(ai_ac.getID(),
260                                               latitude,
261                                               longitude,
262                                               heading,
263                                               speed,
264                                               altitude, time);
265         //string airport = fgGetString("/sim/presets/airport-id");
266         //FGAirport *apt = FGAirport::findByIdent(airport); 
267         // AT this stage we should update the flightplan, so that waypoint incrementing is conducted as well as leg loading. 
268         int n = trans_num->getIntValue();
269         if (n == 1) {
270             //cerr << "Toggling ground network visibility " << networkVisible << endl;
271             networkVisible = !networkVisible;
272             trans_num->setIntValue(-1);
273         }
274         if ((controller != prevController) && (prevController)) {
275             prevController->render(false);
276         }
277         controller->render(networkVisible);
278
279         //cerr << "Adding groundnetWork to the scenegraph::update" << endl;
280         prevController = controller;
281    }
282    for (AtcVecIterator atc = activeStations.begin(); atc != activeStations.end(); atc++) {
283        (*atc)->update(time);
284    }
285 }