Debian Codegraph @

src/ATC/GroundController.cxx

raw symbols SCIP
1 // GroundController.hxx - forked from groundnetwork.cxx
2
3 // Written by Durk Talsma, started June 2005.
4 //
5 // Copyright (C) 2004 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 #include <config.h>
24
25 #include <cmath>
26 #include <algorithm>
27 #include <fstream>
28 #include <map>
29 #include <algorithm>
30
31 #include <osg/Geode>
32 #include <osg/Geometry>
33 #include <osg/MatrixTransform>
34 #include <osg/Shape>
35
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/scene/material/EffectGeode.hxx>
38 #include <simgear/scene/material/matlib.hxx>
39 #include <simgear/scene/material/mat.hxx>
40 #include <simgear/scene/util/OsgMath.hxx>
41 #include <simgear/structure/exception.hxx>
42 #include <simgear/timing/timestamp.hxx>
43 #include <simgear/timing/sg_time.hxx>
44
45 #include <Airports/airport.hxx>
46 #include <Airports/dynamics.hxx>
47 #include <Airports/runways.hxx>
48 #include <Airports/groundnetwork.hxx>
49
50 #include <Main/globals.hxx>
51 #include <Main/fg_props.hxx>
52 #include <AIModel/AIAircraft.hxx>
53 #include <AIModel/performancedata.hxx>
54 #include <AIModel/AIFlightPlan.hxx>
55 #include <Navaids/NavDataCache.hxx>
56
57 #include <ATC/atc_mgr.hxx>
58
59 #include <Scenery/scenery.hxx>
60
61 #include <ATC/ATCController.hxx>
62 #include <ATC/GroundController.hxx>
63
64 using std::string;
65
66
67 /***************************************************************************
68 * FGGroundController()
69 **************************************************************************/
70 FGGroundController::FGGroundController(FGAirportDynamics *par)
71 {
72 hasNetwork = false;
73 count = 0;
74 group = 0;
75 version = 0;
76 networkInitialized = false;
77 FGATCController::init();
78
79 parent = par;
80 hasNetwork = true;
81 networkInitialized = true;
82
83 }
84
85 FGGroundController::~FGGroundController()
86 {
87 }
88
89 bool compare_trafficrecords(FGTrafficRecord a, FGTrafficRecord b)
90 {
91 return (a.getIntentions().size() < b.getIntentions().size());
92 }
93
94 void FGGroundController::announcePosition(int id,
95 FGAIFlightPlan * intendedRoute,
96 int currentPosition, double lat,
97 double lon, double heading,
98 double speed, double alt,
99 double radius, int leg,
100 FGAIAircraft * aircraft)
101 {
102 if (!aircraft || !aircraft->getPerformance()) {
103 SG_LOG(SG_ATC, SG_ALERT, "announcePosition: missing aircraft performance");
104 return;
105 }
106
107 // Search the activeTraffic vector to find a traffic vector with our id
108 TrafficVectorIterator i = FGATCController::searchActiveTraffic(id);
109
110 // Add a new TrafficRecord if none exists for this aircraft
111 // otherwise set the information for the TrafficRecord
112 if (i == activeTraffic.end() || (activeTraffic.empty())) {
113 FGTrafficRecord rec;
114 rec.setId(id);
115 rec.setLeg(leg);
116 rec.setPositionAndIntentions(currentPosition, intendedRoute);
117 rec.setPositionAndHeading(lat, lon, heading, speed, alt);
118 rec.setRadius(radius); // only need to do this when creating the record.
119 rec.setCallsign(aircraft->getCallSign());
120 rec.setAircraft(aircraft);
121 // add to the front of the list of activeTraffic if the aircraft is already taxiing
122 if (leg == 2) {
123 activeTraffic.push_front(rec);
124 } else {
125 activeTraffic.push_back(rec);
126 }
127 } else {
128 i->setPositionAndIntentions(currentPosition, intendedRoute);
129 i->setPositionAndHeading(lat, lon, heading, speed, alt);
130 }
131 }
132
133 /**
134 * The ground network can deal with the following states:
135 * 0 = Normal; no action required
136 * 1 = "Acknowledge "Hold position
137 * 2 = "Acknowledge "Resume taxi".
138 * 3 = "Issue TaxiClearance"
139 * 4 = Acknowledge Taxi Clearance"
140 * 5 = Post acknowlegde taxiclearance: Start taxiing
141 * 6 = Report runway
142 * 7 = Acknowledge report runway
143 * 8 = Switch tower frequency
144 * 9 = Acknowledge switch tower frequency
145 */
146
147 void FGGroundController::updateAircraftInformation(int id, SGGeod geod,
148 double heading, double speed, double alt,
149 double dt)
150 {
151 // Check whether aircraft are on hold due to a preceding pushback. If so, make sure to
152 // Transmit air-to-ground "Ready to taxi request:
153 // Transmit ground to air approval / hold
154 // Transmit confirmation ...
155 // Probably use a status mechanism similar to the Engine start procedure in the startup controller.
156
157 // Search the activeTraffic vector to find a traffic vector with our id
158 TrafficVectorIterator i = FGATCController::searchActiveTraffic(id);
159
160 // update position of the current aircraft
161 if (i == activeTraffic.end() || activeTraffic.empty()) {
162 SG_LOG(SG_GENERAL, SG_DEV_WARN,
163 "AI error: updating aircraft without traffic record at " << SG_ORIGIN << ", id=" << id);
164 return;
165 }
166
167 i->setPositionAndHeading(geod.getLatitudeDeg(), geod.getLongitudeDeg(), heading, speed, alt);
168 TrafficVectorIterator current = i;
169
170 setDt(getDt() + dt);
171
172 // Update every three secs, but add some randomness
173 // to prevent all IA objects doing this in synchrony
174 //if (getDt() < (3.0) + (rand() % 10))
175 // return;
176 //else
177 // setDt(0);
178 current->clearResolveCircularWait();
179 current->setWaitsForId(0);
180 checkSpeedAdjustment(id, geod.getLatitudeDeg(), geod.getLongitudeDeg(), heading, speed, alt);
181 bool needsTaxiClearance = current->getAircraft()->getTaxiClearanceRequest();
182 if (!needsTaxiClearance) {
183 checkHoldPosition(id, geod.getLatitudeDeg(), geod.getLongitudeDeg(), heading, speed, alt);
184 //if (checkForCircularWaits(id)) {
185 // i->setResolveCircularWait();
186 //}
187 } else {
188 current->setHoldPosition(true);
189 int state = current->getState();
190 time_t now = globals->get_time_params()->get_cur_time();
191
192 if ((now - lastTransmission) > 15) {
193 available = true;
194 }
195 if (checkTransmissionState(ATCMessageState::NORMAL,ATCMessageState::ACK_RESUME_TAXI, current, now, MSG_REQUEST_TAXI_CLEARANCE, ATC_AIR_TO_GROUND)) {
196 current->setState(ATCMessageState::TAXI_CLEARED);
197 }
198 if (checkTransmissionState(ATCMessageState::TAXI_CLEARED,ATCMessageState::TAXI_CLEARED, current, now, MSG_ISSUE_TAXI_CLEARANCE, ATC_GROUND_TO_AIR)) {
199 current->setState(ATCMessageState::ACK_TAXI_CLEARED);
200 }
201 if (checkTransmissionState(ATCMessageState::ACK_TAXI_CLEARED,ATCMessageState::ACK_TAXI_CLEARED, current, now, MSG_ACKNOWLEDGE_TAXI_CLEARANCE, ATC_AIR_TO_GROUND)) {
202 current->setState(ATCMessageState::START_TAXI);
203 }
204 if ((state == ATCMessageState::START_TAXI) && available) {
205 current->setState(ATCMessageState::NORMAL);
206 current->getAircraft()->setTaxiClearanceRequest(false);
207 current->setHoldPosition(false);
208 available = false;
209 }
210 }
211 }
212
213 /**
214 * Scan for a speed adjustment change. Find the nearest aircraft that is in front
215 * and adjust speed when we get too close. Only do this when current position and/or
216 * intentions of the current aircraft match current taxiroute position of the proximate
217 * aircraft. For traffic that is on other routes we need to issue a "HOLD Position"
218 * instruction. See below for the hold position instruction.
219
220 * Note that there currently still is one flaw in the logic that needs to be addressed.
221 * There can be situations where one aircraft is in front of the current aircraft, on a separate
222 * route, but really close after an intersection coming off the current route. This
223 * aircraft is still close enough to block the current aircraft. This situation is currently
224 * not addressed yet, but should be.
225 */
226
227 void FGGroundController::checkSpeedAdjustment(int id, double lat,
228 double lon, double heading,
229 double speed, double alt)
230 {
231
232 TrafficVectorIterator current, closest, closestOnNetwork;
233 // bool previousInstruction;
234 TrafficVectorIterator i = FGATCController::searchActiveTraffic(id);
235 if (!activeTraffic.size()) {
236 return;
237 }
238 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
239 SG_LOG(SG_GENERAL, SG_ALERT,
240 "AI error: Trying to access non-existing aircraft in FGGroundNetwork::checkSpeedAdjustment at " << SG_ORIGIN);
241 }
242 current = i;
243 //closest = current;
244
245 // previousInstruction = current->getSpeedAdjustment();
246 double mindist = HUGE_VAL;
247
248 // First check all our activeTraffic
249 if (activeTraffic.size()) {
250 bool otherReasonToSlowDown = false;
251 double course, dist, bearing, az2; // minbearing,
252 SGGeod curr(SGGeod::fromDegM(lon, lat, alt));
253 closest = current;
254 closestOnNetwork = current;
255
256 for (TrafficVectorIterator iter = activeTraffic.begin();
257 iter != activeTraffic.end(); ++iter) {
258 if (iter == current) {
259 continue;
260 }
261
262 SGGeod other = iter->getPos();
263 SGGeodesy::inverse(curr, other, course, az2, dist);
264 bearing = fabs(heading - course);
265 if (bearing > 180)
266 bearing = 360 - bearing;
267 if ((dist < mindist) && (bearing < 60.0)) {
268 mindist = dist;
269 closest = iter;
270 closestOnNetwork = iter;
271 // minbearing = bearing;
272 }
273 }
274
275 // Next check with the tower controller
276 if (towerController->hasActiveTraffic()) {
277 for (TrafficVectorIterator iter =
278 towerController->getActiveTraffic().begin();
279 iter != towerController->getActiveTraffic().end(); ++iter) {
280 if( current->getId() == iter->getId()) {
281 continue;
282 }
283 SG_LOG(SG_ATC, SG_BULK, current->getCallsign() << "| Comparing with " << iter->getCallsign() << " Id: " << iter->getId());
284 SGGeod other = iter->getPos();
285 SGGeodesy::inverse(curr, other, course, az2, dist);
286 bearing = fabs(heading - course);
287 if (bearing > 180)
288 bearing = 360 - bearing;
289 if ((dist < mindist) && (bearing < 60.0)) {
290 //SG_LOG(SG_ATC, SG_BULK, "Current aircraft " << current->getAircraft()->getTrafficRef()->getCallSign()
291 // << " is closest to " << iter->getAircraft()->getTrafficRef()->getCallSign()
292 // << ", which has status " << iter->getAircraft()->isScheduledForTakeoff());
293 mindist = dist;
294 closest = iter;
295 // minbearing = bearing;
296 otherReasonToSlowDown = true;
297 }
298 }
299 }
300
301 // Finally, check UserPosition
302 // Note, as of 2011-08-01, this should no longer be necessary.
303 /*
304 double userLatitude = fgGetDouble("/position/latitude-deg");
305 double userLongitude = fgGetDouble("/position/longitude-deg");
306 SGGeod user(SGGeod::fromDeg(userLongitude, userLatitude));
307 SGGeodesy::inverse(curr, user, course, az2, dist);
308
309 bearing = fabs(heading - course);
310 if (bearing > 180)
311 bearing = 360 - bearing;
312 if ((dist < mindist) && (bearing < 60.0)) {
313 mindist = dist;
314 //closest = i;
315 minbearing = bearing;
316 otherReasonToSlowDown = true;
317 }
318 */
319
320 // Clear any active speed adjustment, check if the aircraft needs to brake
321 current->clearSpeedAdjustment();
322 bool needBraking = false;
323
324 if (current->checkPositionAndIntentions(*closest)
325 || otherReasonToSlowDown) {
326 double maxAllowableDistance =
327 (1.1 * current->getRadius()) +
328 (1.1 * closest->getRadius());
329 if (mindist < 2 * maxAllowableDistance) {
330 if (current->getId() == closest->getWaitsForId())
331 return;
332 else
333 current->setWaitsForId(closest->getId());
334
335 if (closest->getId() != current->getId()) {
336 current->setSpeedAdjustment(closest->getSpeed() *
337 (mindist / 100));
338 needBraking = true;
339
340 // if (
341 // closest->getAircraft()->getTakeOffStatus() &&
342 // (current->getAircraft()->getTrafficRef()->getDepartureAirport() == closest->getAircraft()->getTrafficRef()->getDepartureAirport()) &&
343 // (current->getAircraft()->GetFlightPlan()->getRunway() == closest->getAircraft()->GetFlightPlan()->getRunway())
344 // )
345 // current->getAircraft()->scheduleForATCTowerDepartureControl(1);
346 } else {
347 current->setSpeedAdjustment(0); // This can only happen when the user aircraft is the one closest
348 }
349
350 if (mindist < maxAllowableDistance) {
351 //double newSpeed = (maxAllowableDistance-mindist);
352 //current->setSpeedAdjustment(newSpeed);
353 //if (mindist < 0.5* maxAllowableDistance)
354 // {
355 current->setSpeedAdjustment(0);
356 // }
357 }
358 }
359 }
360
361 if ((closest->getId() == closestOnNetwork->getId()) && (current->getPriority() < closest->getPriority()) && needBraking) {
362 swap(current, closest);
363 }
364 }
365 }
366
367 /**
368 * Check for "Hold position instruction".
369 * The hold position should be issued under the following conditions:
370 * 1) For aircraft entering or crossing a runway with active traffic on it, or landing aircraft near it
371 * 2) For taxiing aircraft that use one taxiway in opposite directions
372 * 3) For crossing or merging taxiroutes.
373 */
374
375 void FGGroundController::checkHoldPosition(int id, double lat,
376 double lon, double heading,
377 double speed, double alt)
378 {
379 FGGroundNetwork* network = parent->parent()->groundNetwork();
380 TrafficVectorIterator current;
381 TrafficVectorIterator i = activeTraffic.begin();
382 if (activeTraffic.size()) {
383 //while ((i->getId() != id) && i != activeTraffic.end())
384 while (i != activeTraffic.end()) {
385 if (i->getId() == id) {
386 break;
387 }
388 i++;
389 }
390 } else {
391 return;
392 }
393
394 time_t now = globals->get_time_params()->get_cur_time();
395 if (i == activeTraffic.end() || (activeTraffic.size() == 0)) {
396 SG_LOG(SG_GENERAL, SG_ALERT,
397 "AI error: Trying to access non-existing aircraft in FGGroundNetwork::checkHoldPosition at " << SG_ORIGIN);
398 }
399 current = i;
400 if (current->getAircraft()->getTakeOffStatus() == AITakeOffStatus::QUEUED) {
401 current->setHoldPosition(true);
402 return;
403 }
404 if ((now - lastTransmission) > 15) {
405 available = true;
406 }
407
408 if (current->getAircraft()->getTakeOffStatus() == AITakeOffStatus::CLEARED_FOR_TAKEOFF) {
409 current->setHoldPosition(false);
410 current->clearSpeedAdjustment();
411 return;
412 }
413 bool origStatus = current->hasHoldPosition();
414 current->setHoldPosition(false);
415 //SGGeod curr(SGGeod::fromDegM(lon, lat, alt));
416 int currentRoute = i->getCurrentPosition();
417 int nextRoute;
418 if (i->getIntentions().size()) {
419 nextRoute = (*(i->getIntentions().begin()));
420 } else {
421 nextRoute = 0;
422 }
423 if (currentRoute > 0) {
424 FGTaxiSegment *tx = network->findSegment(currentRoute);
425 FGTaxiSegment *nx;
426 if (nextRoute) {
427 nx = network->findSegment(nextRoute);
428 } else {
429 nx = tx;
430 }
431 //if (tx->hasBlock(now) || nx->hasBlock(now) ) {
432 // current->setHoldPosition(true);
433 //}
434 SGGeod start = i->getPos();
435 SGGeod end (nx->getStart()->geod());
436
437 double distance = SGGeodesy::distanceM(start, end);
438 if (nx->hasBlock(now) && (distance < i->getRadius() * 4)) {
439 current->setHoldPosition(true);
440 } else {
441 intVecIterator ivi = i->getIntentions().begin();
442 while (ivi != i->getIntentions().end()) {
443 if ((*ivi) > 0) {
444 FGTaxiSegment* seg = network->findSegment(*ivi);
445 distance += seg->getLength();
446 if ((seg->hasBlock(now)) && (distance < i->getRadius() * 4)) {
447 current->setHoldPosition(true);
448 break;
449 }
450 }
451 ivi++;
452 }
453 }
454 }
455 bool currStatus = current->hasHoldPosition();
456 current->setHoldPosition(origStatus);
457 // Either a Hold Position or a resume taxi transmission has been issued
458 if ((now - lastTransmission) > 2) {
459 available = true;
460 }
461 if (current->getState() == ATCMessageState::NORMAL) {
462 if ((origStatus != currStatus) && available) {
463 SG_LOG(SG_ATC, SG_DEBUG, "Issuing hold short instruction " << currStatus << " " << available);
464 if (currStatus == true) { // No has a hold short instruction
465 transmit(&(*current), parent, MSG_HOLD_POSITION, ATC_GROUND_TO_AIR, true);
466 SG_LOG(SG_ATC, SG_DEBUG, "Transmitting hold short instruction " << currStatus << " " << available);
467 current->setState(ATCMessageState::ACK_HOLD);
468 } else {
469 transmit(&(*current), parent, MSG_RESUME_TAXI, ATC_GROUND_TO_AIR, true);
470 SG_LOG(SG_ATC, SG_DEBUG, "Transmitting resume instruction " << currStatus << " " << available);
471 current->setState(ATCMessageState::ACK_RESUME_TAXI);
472 }
473 lastTransmission = now;
474 available = false;
475 // Don't act on the changed instruction until the transmission is confirmed
476 // So set back to original status
477 SG_LOG(SG_ATC, SG_DEBUG, "Current state " << current->getState());
478 }
479
480 }
481 // 6 = Report runway
482 // 7 = Acknowledge report runway
483 // 8 = Switch tower frequency
484 //9 = Acknowledge switch tower frequency
485
486 //int state = current->getState();
487 if (checkTransmissionState(ATCMessageState::ACK_HOLD, ATCMessageState::ACK_HOLD, current, now, MSG_ACKNOWLEDGE_HOLD_POSITION, ATC_AIR_TO_GROUND)) {
488 current->setState(ATCMessageState::NORMAL);
489 current->setHoldPosition(true);
490 }
491 if (checkTransmissionState(ATCMessageState::ACK_RESUME_TAXI, ATCMessageState::ACK_RESUME_TAXI, current, now, MSG_ACKNOWLEDGE_RESUME_TAXI, ATC_AIR_TO_GROUND)) {
492 current->setState(ATCMessageState::NORMAL);
493 current->setHoldPosition(false);
494 }
495 if (current->getAircraft()->getTakeOffStatus() && (current->getState() == 0)) {
496 SG_LOG(SG_ATC, SG_DEBUG, "Scheduling " << current->getAircraft()->getCallSign() << " for hold short");
497 current->setState(ATCMessageState::REPORT_RUNWAY);
498 }
499 if (checkTransmissionState(ATCMessageState::REPORT_RUNWAY ,ATCMessageState::REPORT_RUNWAY , current, now, MSG_REPORT_RUNWAY_HOLD_SHORT, ATC_AIR_TO_GROUND)) {
500 }
501 if (checkTransmissionState(ATCMessageState::ACK_REPORT_RUNWAY, ATCMessageState::ACK_REPORT_RUNWAY, current, now, MSG_ACKNOWLEDGE_REPORT_RUNWAY_HOLD_SHORT, ATC_GROUND_TO_AIR)) {
502 }
503 if (checkTransmissionState(ATCMessageState::SWITCH_GROUND_TOWER, ATCMessageState::SWITCH_GROUND_TOWER, current, now, MSG_SWITCH_TOWER_FREQUENCY, ATC_GROUND_TO_AIR)) {
504 }
505 if (checkTransmissionState(ATCMessageState::ACK_SWITCH_GROUND_TOWER, ATCMessageState::ACK_SWITCH_GROUND_TOWER, current, now, MSG_ACKNOWLEDGE_SWITCH_TOWER_FREQUENCY, ATC_AIR_TO_GROUND)) {
506 }
507
508 //current->setState(0);
509 }
510
511 /*
512 * Check whether situations occur where the current aircraft is waiting for itself
513 * due to higher order interactions.
514 * A 'circular' wait is a situation where a waits for b, b waits for c, and c waits
515 * for a. Ideally each aircraft only waits for one other aircraft, so by tracing
516 * through this list of waiting aircraft, we can check if we'd eventually end back
517 * at the current aircraft.
518 *
519 * Note that we should consider the situation where we are actually checking aircraft
520 * d, which is waiting for aircraft a. d is not part of the loop, but is held back by
521 * the looping aircraft. If we don't check for that, this function will get stuck into
522 * endless loop.
523 */
524
525 bool FGGroundController::checkForCircularWaits(int id)
526 {
527 SG_LOG(SG_ATC, SG_DEBUG, "Performing circular check for " << id);
528 int target = 0;
529 TrafficVectorIterator current, other;
530 TrafficVectorIterator i = activeTraffic.begin();
531 int trafficSize = activeTraffic.size();
532 if (trafficSize) {
533 while (i != activeTraffic.end()) {
534 if (i->getId() == id) {
535 break;
536 }
537 i++;
538 }
539 } else {
540 return false;
541 }
542
543 if (i == activeTraffic.end()) {
544 SG_LOG(SG_GENERAL, SG_ALERT,
545 "AI error: Trying to access non-existing aircraft in FGGroundNetwork::checkForCircularWaits at " << SG_ORIGIN);
546 }
547
548 current = i;
549 target = current->getWaitsForId();
550 //bool printed = false; // Note that this variable is for debugging purposes only.
551 int counter = 0;
552
553 if (id == target) {
554 SG_LOG(SG_ATC, SG_DEBUG, "aircraft is waiting for user");
555 return false;
556 }
557
558 while ((target > 0) && (target != id) && counter++ < trafficSize) {
559 //printed = true;
560 TrafficVectorIterator iter = activeTraffic.begin();
561 if (trafficSize) {
562 while (iter != activeTraffic.end()) {
563 if (iter->getId() == target) {
564 break;
565 }
566 ++iter;
567 }
568 } else {
569 return false;
570 }
571
572 if (iter == activeTraffic.end()) {
573 SG_LOG(SG_ATC, SG_DEBUG, "[Waiting for traffic at Runway: DONE] ");
574 // The target id is not found on the current network, which means it's at the tower
575 SG_LOG(SG_ATC, SG_ALERT, "AI error: Trying to access non-existing aircraft in FGGroundNetwork::checkForCircularWaits");
576 return false;
577 }
578
579 other = iter;
580 target = other->getWaitsForId();
581
582 // actually this trap isn't as impossible as it first seemed:
583 // the setWaitsForID(id) is set to current when the aircraft
584 // is waiting for the user controlled aircraft.
585 if (current->getId() == other->getId())
586 return false;
587 }
588
589 //if (printed)
590 SG_LOG(SG_ATC, SG_DEBUG, "[done] ");
591 if (id == target) {
592 SG_LOG(SG_GENERAL, SG_WARN,
593 "Detected circular wait condition: Id = " << id <<
594 "target = " << target);
595 return true;
596 } else {
597 return false;
598 }
599 }
600
601 // Note that this function is copied from simgear. for maintanance purposes, it's probabtl better to make a general function out of that.
602 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
603 double lon, double elev, double hdg, double slope)
604 {
605 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
606 obj_pos = makeZUpFrame(geod);
607 // hdg is not a compass heading, but a counter-clockwise rotation
608 // around the Z axis
609 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
610 0.0, 0.0, 1.0));
611 obj_pos.preMult(osg::Matrix::rotate(slope * SGD_DEGREES_TO_RADIANS,
612 0.0, 1.0, 0.0));
613 }
614
615 /** Draw visible taxi routes */
616 void FGGroundController::render(bool visible)
617 {
618 SGMaterialLib *matlib = globals->get_matlib();
619 FGGroundNetwork* network = parent->parent()->groundNetwork();
620
621 if (group) {
622 //int nr = ;
623 globals->get_scenery()->get_scene_graph()->removeChild(group);
624 //while (group->getNumChildren()) {
625 // SG_LOG(SG_ATC, SG_DEBUG, "Number of children: " << group->getNumChildren());
626 //simgear::EffectGeode* geode = (simgear::EffectGeode*) group->getChild(0);
627 //osg::MatrixTransform *obj_trans = (osg::MatrixTransform*) group->getChild(0);
628 //geode->releaseGLObjects();
629 //group->removeChild(geode);
630 //delete geode;
631 group = 0;
632 }
633 if (visible) {
634 group = new osg::Group;
635 FGScenery * local_scenery = globals->get_scenery();
636 // double elevation_meters = 0.0;
637 // double elevation_feet = 0.0;
638 time_t now = globals->get_time_params()->get_cur_time();
639
640 //for ( FGTaxiSegmentVectorIterator i = segments.begin(); i != segments.end(); i++) {
641 //double dx = 0;
642
643 for (TrafficVectorIterator i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
644 // Handle start point i.e. the segment that is connected to the aircraft itself on the starting end
645 // and to the the first "real" taxi segment on the other end.
646 const int pos = i->getCurrentPosition();
647 if (pos > 0) {
648 FGTaxiSegment* segment = network->findSegment(pos);
649 SGGeod start = i->getPos();
650 SGGeod end (segment->getEnd()->geod());
651
652 double length = SGGeodesy::distanceM(start, end);
653 //heading = SGGeodesy::headingDeg(start->geod(), end->geod());
654
655 double az2, heading; //, distanceM;
656 SGGeodesy::inverse(start, end, heading, az2, length);
657 double coveredDistance = length * 0.5;
658 SGGeod center;
659 SGGeodesy::direct(start, heading, coveredDistance, center, az2);
660 SG_LOG(SG_ATC, SG_BULK, "Active Aircraft : Centerpoint = (" << center.getLatitudeDeg() << ", " << center.getLongitudeDeg() << "). Heading = " << heading);
661 ///////////////////////////////////////////////////////////////////////////////
662 // Make a helper function out of this
663 osg::Matrix obj_pos;
664 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
665 obj_trans->setDataVariance(osg::Object::STATIC);
666 // Experimental: Calculate slope here, based on length, and the individual elevations
667 double elevationStart;
668 if (isUserAircraft((i)->getAircraft())) {
669 elevationStart = fgGetDouble("/position/ground-elev-m");
670 } else {
671 elevationStart = ((i)->getAircraft()->_getAltitude());
672 }
673 double elevationEnd = segment->getEnd()->getElevationM();
674 SG_LOG(SG_ATC, SG_DEBUG, "Using elevation " << elevationEnd);
675
676 if ((elevationEnd == 0) || (elevationEnd = parent->getElevation())) {
677 SGGeod center2 = end;
678 center2.setElevationM(SG_MAX_ELEVATION_M);
679 if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
680 // elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
681 //elevation_meters += 0.5;
682 }
683 else {
684 elevationEnd = parent->getElevation();
685 }
686 segment->getEnd()->setElevation(elevationEnd);
687 }
688 double elevationMean = (elevationStart + elevationEnd) / 2.0;
689 double elevDiff = elevationEnd - elevationStart;
690
691 double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
692
693 SG_LOG(SG_ATC, SG_DEBUG, "1. Using mean elevation : " << elevationMean << " and " << slope);
694
695 WorldCoordinate( obj_pos, center.getLatitudeDeg(), center.getLongitudeDeg(), elevationMean+ 0.5, -(heading), slope );
696
697 obj_trans->setMatrix( obj_pos );
698 //osg::Vec3 center(0, 0, 0)
699
700 float width = length /2.0;
701 osg::Vec3 corner(-width, 0, 0.25f);
702 osg::Vec3 widthVec(2*width + 1, 0, 0);
703 osg::Vec3 heightVec(0, 1, 0);
704 osg::Geometry* geometry;
705 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
706 simgear::EffectGeode* geode = new simgear::EffectGeode;
707 geode->setName("test");
708 geode->addDrawable(geometry);
709 //osg::Node *custom_obj;
710 SGMaterial *mat;
711 if (segment->hasBlock(now)) {
712 mat = matlib->find("UnidirectionalTaperRed", center);
713 } else {
714 mat = matlib->find("UnidirectionalTaperGreen", center);
715 }
716 if (mat)
717 geode->setEffect(mat->get_effect());
718 obj_trans->addChild(geode);
719 // wire as much of the scene graph together as we can
720 //->addChild( obj_trans );
721 group->addChild( obj_trans );
722 /////////////////////////////////////////////////////////////////////
723 } else {
724 SG_LOG(SG_ATC, SG_INFO, "BIG FAT WARNING: current position is here : " << pos);
725 }
726 // Next: Draw the other taxi segments.
727 for (intVecIterator j = (i)->getIntentions().begin(); j != (i)->getIntentions().end(); j++) {
728 osg::Matrix obj_pos;
729 const int k = (*j);
730 if (k > 0) {
731 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
732 obj_trans->setDataVariance(osg::Object::STATIC);
733 FGTaxiSegment* segmentK = network->findSegment(k);
734 // Experimental: Calculate slope here, based on length, and the individual elevations
735 double elevationStart = segmentK->getStart()->getElevationM();
736 double elevationEnd = segmentK->getEnd ()->getElevationM();
737 if ((elevationStart == 0) || (elevationStart == parent->getElevation())) {
738 SGGeod center2 = segmentK->getStart()->geod();
739 center2.setElevationM(SG_MAX_ELEVATION_M);
740 if (local_scenery->get_elevation_m( center2, elevationStart, NULL )) {
741 // elevation_feet = elevationStart * SG_METER_TO_FEET + 0.5;
742 //elevation_meters += 0.5;
743 }
744 else {
745 elevationStart = parent->getElevation();
746 }
747 segmentK->getStart()->setElevation(elevationStart);
748 }
749 if ((elevationEnd == 0) || (elevationEnd == parent->getElevation())) {
750 SGGeod center2 = segmentK->getEnd()->geod();
751 center2.setElevationM(SG_MAX_ELEVATION_M);
752 if (local_scenery->get_elevation_m( center2, elevationEnd, NULL )) {
753 // elevation_feet = elevationEnd * SG_METER_TO_FEET + 0.5;
754 //elevation_meters += 0.5;
755 }
756 else {
757 elevationEnd = parent->getElevation();
758 }
759 segmentK->getEnd()->setElevation(elevationEnd);
760 }
761
762 double elevationMean = (elevationStart + elevationEnd) / 2.0;
763 double elevDiff = elevationEnd - elevationStart;
764 double length = segmentK->getLength();
765 double slope = atan2(elevDiff, length) * SGD_RADIANS_TO_DEGREES;
766
767 SG_LOG(SG_ATC, SG_DEBUG, "2. Using mean elevation : " << elevationMean << " and " << slope);
768
769 SGGeod segCenter = segmentK->getCenter();
770 WorldCoordinate( obj_pos, segCenter.getLatitudeDeg(), segCenter.getLongitudeDeg(),
771 elevationMean+ 0.5, -(segmentK->getHeading()), slope );
772
773 obj_trans->setMatrix( obj_pos );
774 //osg::Vec3 center(0, 0, 0)
775
776 float width = segmentK->getLength() /2.0;
777 osg::Vec3 corner(-width, 0, 0.25f);
778 osg::Vec3 widthVec(2*width + 1, 0, 0);
779 osg::Vec3 heightVec(0, 1, 0);
780 osg::Geometry* geometry;
781 geometry = osg::createTexturedQuadGeometry(corner, widthVec, heightVec);
782 simgear::EffectGeode* geode = new simgear::EffectGeode;
783 geode->setName("test");
784 geode->addDrawable(geometry);
785 //osg::Node *custom_obj;
786 SGMaterial *mat;
787 if (segmentK->hasBlock(now)) {
788 mat = matlib->find("UnidirectionalTaperRed", segCenter);
789 } else {
790 mat = matlib->find("UnidirectionalTaperGreen", segCenter);
791 }
792 if (mat)
793 geode->setEffect(mat->get_effect());
794 obj_trans->addChild(geode);
795 // wire as much of the scene graph together as we can
796 //->addChild( obj_trans );
797 group->addChild( obj_trans );
798 }
799 }
800 //dx += 0.1;
801 }
802 globals->get_scenery()->get_scene_graph()->addChild(group);
803 }
804 }
805
806 string FGGroundController::getName() {
807 return string(parent->parent()->getName() + "-ground");
808 }
809
810 void FGGroundController::update(double dt)
811 {
812 time_t now = globals->get_time_params()->get_cur_time();
813 FGGroundNetwork* network = parent->parent()->groundNetwork();
814 network->unblockAllSegments(now);
815 int priority = 1;
816
817 TrafficVector& startupTraffic(parent->getStartupController()->getActiveTraffic());
818 TrafficVectorIterator i;
819
820 //sort(activeTraffic.begin(), activeTraffic.end(), compare_trafficrecords);
821 // Handle traffic that is under ground control first; this way we'll prevent clutter at the gate areas.
822 // Don't allow an aircraft to pushback when a taxiing aircraft is currently using part of the intended route.
823 for (i = startupTraffic.begin(); i != startupTraffic.end(); ++i) {
824 updateStartupTraffic(i, priority, now);
825 }
826
827 for (i = activeTraffic.begin(); i != activeTraffic.end(); i++) {
828 updateActiveTraffic(i, priority, now);
829 }
830
831 //FIXME
832 //FGATCController::eraseDeadTraffic(startupTraffic);
833 FGATCController::eraseDeadTraffic();
834 }
835
836 void FGGroundController::updateStartupTraffic(TrafficVectorIterator i,
837 int& priority,
838 time_t now)
839 {
840 if (!i->getAircraft()) {
841 SG_LOG(SG_ATC, SG_ALERT, "updateStartupTraffic: missing aircraft");
842 return;
843 }
844
845 if (!i->getAircraft()->getPerformance()) {
846 SG_LOG(SG_ATC, SG_ALERT, "updateStartupTraffic: missing aircraft performance");
847 return;
848 }
849
850 i->allowPushBack();
851 i->setPriority(priority++);
852 // in meters per second;
853 double vTaxi = (i->getAircraft()->getPerformance()->vTaxi() * SG_NM_TO_METER) / 3600;
854 if (!i->isActive(0)) {
855 return;
856 }
857
858 FGGroundNetwork* network = parent->parent()->groundNetwork();
859
860 if (!network) {
861 SG_LOG(SG_ATC, SG_ALERT, "updateStartupTraffic: missing ground network");
862 return;
863 }
864
865 // Check for all active aircraft whether it's current pos segment is
866 // an opposite of one of the departing aircraft's intentions
867 for (TrafficVectorIterator j = activeTraffic.begin(); j != activeTraffic.end(); j++) {
868 int pos = j->getCurrentPosition();
869 if (pos > 0) {
870 FGTaxiSegment *seg = network->findOppositeSegment(pos-1);
871 if (seg) {
872 int posReverse = seg->getIndex();
873 for (intVecIterator k = i->getIntentions().begin(); k != i->getIntentions().end(); k++) {
874 if ((*k) == posReverse) {
875 i->denyPushBack();
876 network->findSegment(posReverse)->block(i->getId(), now, now);
877 }
878 }
879 }
880 }
881 }
882 // if the current aircraft is still allowed to pushback, we can start reserving a route for if by blocking all the entry taxiways.
883 if (!i->pushBackAllowed()) {
884 return;
885 }
886
887 double length = 0;
888 int pos = i->getCurrentPosition();
889 if (pos > 0) {
890 FGTaxiSegment *seg = network->findSegment(pos);
891 length = seg->getLength();
892 network->blockSegmentsEndingAt(seg, i->getId(), now, now);
893 }
894
895 for (intVecIterator j = i->getIntentions().begin(); j != i->getIntentions().end(); j++) {
896 pos = (*j);
897 if (pos > 0) {
898 FGTaxiSegment *seg = network->findSegment(pos);
899 length += seg->getLength();
900 time_t blockTime = now + (length / vTaxi);
901 network->blockSegmentsEndingAt(seg, i->getId(), blockTime - 30, now);
902 }
903 }
904 }
905
906 bool FGGroundController::updateActiveTraffic(TrafficVectorIterator i,
907 int& priority,
908 time_t now)
909 {
910 if (!i->getAircraft()) {
911 SG_LOG(SG_ATC, SG_ALERT, "updateActiveTraffic: missing aircraft");
912 return false;
913 }
914
915 if (i->getAircraft()->getDie()) {
916 // aircraft has died
917 return false;
918 }
919
920 if (!i->getAircraft()->getPerformance()) {
921 SG_LOG(SG_ATC, SG_ALERT, "updateActiveTraffic: missing aircraft performance");
922 return false;
923 }
924
925 double length = 0;
926 double vTaxi = (i->getAircraft()->getPerformance()->vTaxi() * SG_NM_TO_METER) / 3600;
927 FGGroundNetwork* network = parent->parent()->groundNetwork();
928
929 if (!network) {
930 SG_LOG(SG_ATC, SG_ALERT, "updateActiveTraffic: missing ground network");
931 return false;
932 }
933
934 i->setPriority(priority++);
935 int pos = i->getCurrentPosition();
936 if (pos > 0) {
937 FGTaxiSegment* segment = network->findSegment(pos);
938 length = segment->getLength();
939 if (segment->hasBlock(now)) {
940 SG_LOG(SG_ATC, SG_BULK, "Taxiway incursion for AI aircraft" << i->getAircraft()->getCallSign());
941 }
942
943 }
944
945 intVecIterator ivi;
946 for (ivi = i->getIntentions().begin(); ivi != i->getIntentions().end(); ivi++) {
947 int segIndex = (*ivi);
948 if (segIndex > 0) {
949 FGTaxiSegment* seg = network->findSegment(segIndex);
950 if (seg->hasBlock(now)) {
951 break;
952 }
953 }
954 }
955
956 //after this, ivi points just behind the last valid unblocked taxi segment.
957 for (intVecIterator j = i->getIntentions().begin(); j != ivi; j++) {
958 pos = (*j);
959 if (pos > 0) {
960 FGTaxiSegment *seg = network->findSegment(pos);
961 length += seg->getLength();
962 time_t blockTime = now + (length / vTaxi);
963 network->blockSegmentsEndingAt(seg, i->getId(), blockTime - 30, now);
964 }
965 }
966
967 return true;
968 }
969
970 int FGGroundController::getFrequency() {
971 int groundFreq = parent->getGroundFrequency(2);
972 int towerFreq = parent->getTowerFrequency(2);
973 return groundFreq>0?groundFreq:towerFreq;
974 }