1 /******************************************************************************
3 * Written by Durk Talsma, started May 5, 2004.
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.
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.
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., 675 Mass Ave, Cambridge, MA 02139, USA.
20 ****************************************************************************
22 *****************************************************************************/
35 #include <simgear/compiler.h>
36 #include <simgear/math/polar3d.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/props/props.hxx>
39 #include <simgear/route/waypoint.hxx>
40 #include <simgear/structure/subsystem_mgr.hxx>
41 #include <simgear/xml/easyxml.hxx>
43 #include <AIModel/AIFlightPlan.hxx>
44 #include <AIModel/AIManager.hxx>
45 #include <Airports/simple.hxx>
46 #include <Main/fg_init.hxx> // That's pretty ugly, but I need fgFindAirportID
49 #include "SchedFlight.hxx"
50 #include "TrafficMgr.hxx"
54 /******************************************************************************
55 * the FGAISchedule class contains data members and code to maintain a
56 * schedule of Flights for an articically controlled aircraft.
57 *****************************************************************************/
58 FGAISchedule::FGAISchedule()
64 FGAISchedule::FGAISchedule(string mdl,
74 FGScheduledFlightVec flt)
86 for (FGScheduledFlightVecIterator i = flt.begin();
89 flights.push_back(FGScheduledFlight((*i)));
94 FGAISchedule::FGAISchedule(const FGAISchedule &other)
96 modelPath = other.modelPath;
97 livery = other.livery;
98 registration = other.registration;
100 flights = other.flights;
103 AIManagerRef = other.AIManagerRef;
104 acType = other.acType;
105 airline = other.airline;
106 m_class = other.m_class;
107 firstRun = other.firstRun;
108 radius = other.radius;
109 groundOffset = other.groundOffset;
110 flightType = other.flightType;
111 distanceToUser = other.distanceToUser;
115 FGAISchedule::~FGAISchedule()
120 bool FGAISchedule::init()
123 //SGTime* currTimeDate = globals->get_time_params();
125 //tm *temp = currTimeDate->getGmt();
127 //sgTimeFormatTime(&targetTimeDate, buffer);
128 //cout << "Scheduled Time " << buffer << endl;
129 //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
130 for (FGScheduledFlightVecIterator i = flights.begin();
134 //i->adjustTime(now);
135 if (!(i->initializeAirports()))
138 //sort(flights.begin(), flights.end());
139 // Since time isn't initialized yet when this function is called,
140 // Find the closest possible airport.
141 // This should give a reasonable initialization order.
142 setClosestDistanceToUser();
146 bool FGAISchedule::update(time_t now)
158 double courseToUser, courseToDest;
159 double distanceToDest;
166 remainingTimeEnroute;
171 if (fgGetBool("/sim/traffic-manager/enabled") == false)
174 aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");
175 // Before the flight status of this traffic entity is updated
176 // for the first time, we need to roll back it's flight schedule so
177 // so that all the flights are centered around this simulated week's time
178 // table. This is to avoid the situation where the first scheduled flight is
179 // in the future, causing the traffic manager to not generate traffic until
180 // simulated time has caught up with the real world time at initialization.
181 // This is to counter a more general initialization bug, caused by the fact
182 // that warp is not yet set when the schedule is initialized. This is
183 // especially a problem when using a negative time offset.
184 // i.e let's say we specify FlightGear to run with --time-offset=-24:00:00.
185 // Then the schedule will initialize using today, but we will fly yesterday.
186 // Thus, it would take a whole day of simulation before the traffic manager
190 for (FGScheduledFlightVecIterator i = flights.begin();
199 // Sort all the scheduled flights according to scheduled departure time.
200 // Because this is done at every update, we only need to check the status
201 // of the first listed flight.
202 sort(flights.begin(), flights.end());
203 FGScheduledFlightVecIterator i = flights.begin();
206 // Check if this aircraft has been released.
207 FGTrafficManager *tmgr = (FGTrafficManager *) globals->get_subsystem("Traffic Manager");
208 if (tmgr->isReleased(AIManagerRef))
214 userLatitude = fgGetDouble("/position/latitude-deg");
215 userLongitude = fgGetDouble("/position/longitude-deg");
217 //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
218 // This flight entry is entirely in the past, do we need to
219 // push it forward in time to the next scheduled departure.
220 if ((i->getDepartureTime() < now) && (i->getArrivalTime() < now))
226 // Departure time in the past and arrival time in the future.
227 // This flight is in progress, so we need to calculate it's
228 // approximate position and -if in range- create an AIAircraft
230 //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
233 // Part of this flight is in the future.
234 if (i->getArrivalTime() > now)
236 dep = i->getDepartureAirport();
237 arr = i->getArrivalAirport ();
241 temp = sgPolarToCart3d(Point3D(dep->getLongitude() *
242 SG_DEGREES_TO_RADIANS,
244 SG_DEGREES_TO_RADIANS,
250 temp = sgPolarToCart3d(Point3D(arr->getLongitude() *
251 SG_DEGREES_TO_RADIANS,
253 SG_DEGREES_TO_RADIANS,
260 sgdVectorProductVec3(cross,b,a);
262 angle = sgACos(sgdScalarProductVec3(a,b));
264 // Okay, at this point we have the angle between departure and
265 // arrival airport, in degrees. From here we can interpolate the
266 // position of the aircraft by calculating the ratio between
267 // total time enroute and elapsed time enroute.
269 totalTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
270 if (now > i->getDepartureTime())
272 //err << "Lat = " << lat << ", lon = " << lon << endl;
273 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
274 elapsedTimeEnroute = now - i->getDepartureTime();
275 remainingTimeEnroute = i->getArrivalTime() - now;
279 lat = dep->getLatitude();
280 lon = dep->getLongitude();
281 elapsedTimeEnroute = 0;
282 remainingTimeEnroute = totalTimeEnroute;
285 angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
288 //cout << "a = " << a[0] << " " << a[1] << " " << a[2]
289 // << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;
290 sgdMakeRotMat4(matrix, angle, cross);
291 for(int j = 0; j < 3; j++)
294 for (int k = 0; k<3; k++)
296 newPos[j] += matrix[j][k]*a[k];
300 temp = sgCartToPolar3d(Point3D(newPos[0], newPos[1],newPos[2]));
301 if (now > i->getDepartureTime())
303 //cerr << "Lat = " << lat << ", lon = " << lon << endl;
304 //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
305 lat = temp.lat() * SG_RADIANS_TO_DEGREES;
306 lon = temp.lon() * SG_RADIANS_TO_DEGREES;
310 lat = dep->getLatitude();
311 lon = dep->getLongitude();
315 SGWayPoint current (lon,
318 SGWayPoint user ( userLongitude,
321 SGWayPoint dest ( arr->getLongitude(),
324 // We really only need distance to user
325 // and course to destination
326 user.CourseAndDistance(current, &courseToUser, &distanceToUser);
327 dest.CourseAndDistance(current, &courseToDest, &distanceToDest);
328 speed = (distanceToDest*SG_METER_TO_NM) /
329 ((double) remainingTimeEnroute/3600.0);
332 // If distance between user and simulated aircaft is less
333 // then 500nm, create this flight. At jet speeds 500 nm is roughly
334 // one hour flight time, so that would be a good approximate point
335 // to start a more detailed simulation of this aircraft.
336 //cerr << registration << " is currently enroute from "
337 // << dep->_id << " to " << arr->_id << "distance : "
338 // << distanceToUser*SG_METER_TO_NM << endl;
339 if ((distanceToUser*SG_METER_TO_NM) < TRAFFICTOAIDIST)
341 string flightPlanName = dep->getId() + string("-") + arr->getId() +
344 //if ((i->getDepartureTime() < now))
346 // alt = i->getCruiseAlt() *100;
350 // alt = dep->_elevation+19;
353 FGAIModelEntity entity;
355 entity.m_class = m_class; //"jet_transport";
356 entity.company = airline; //i->getAirline();
357 entity.acType = acType; //i->getAcType();
358 entity.path = modelPath.c_str();
359 entity.flightplan = flightPlanName.c_str();
360 entity.latitude = lat;
361 entity.longitude = lon;
362 entity.altitude = i->getCruiseAlt() *100; // convert from FL to feet
363 entity.speed = speed;
365 entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep,
366 arr,true, radius, flightType, acType, airline);
368 // Fixme: A non-existent model path results in an
369 // abort, due to an unhandled exeption, in fg main loop.
370 FGAIBase *aircraft = (FGAIBase*)aimgr->createAircraft( &entity, this);
371 AIManagerRef = aircraft->getID();
372 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
373 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
374 //cerr << "Dep : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
375 //cerr << "Arr : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
376 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
377 //cerr << "Total time = " << (totalTimeEnroute/3600.0) << endl;
378 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
384 // Both departure and arrival time are in the future, so this
385 // the aircraft is parked at the departure airport.
386 // Currently this status is mostly ignored, but in future
387 // versions, code should go here that -if within user range-
388 // positions these aircraft at parking locations at the airport.
389 if ((i->getDepartureTime() > now) && (i->getArrivalTime() > now))
391 dep = i->getDepartureAirport();
395 //cerr << "Traffic schedule got to beyond last clause" << endl;
396 // EMH: prevent a warning, should this be 'true' instead?
397 // DT: YES. Originally, this code couldn't be reached, but
398 // when the "if(!(AIManagerManager))" clause is false we
399 // fall through right to the end. This is a valid flow.
400 // the actual value is pretty innocent, only it triggers
401 // warning in TrafficManager::update().
402 // (which was added as a sanity check for myself in the first place. :-)
407 void FGAISchedule::next()
409 flights.begin()->update();
410 sort(flights.begin(), flights.end());
413 double FGAISchedule::getSpeed()
415 double courseToUser, courseToDest;
416 double distanceToUser, distanceToDest;
417 double speed, remainingTimeEnroute;
418 FGAirport *dep, *arr;
420 FGScheduledFlightVecIterator i = flights.begin();
421 dep = i->getDepartureAirport();
422 arr = i->getArrivalAirport ();
426 SGWayPoint dest ( dep->getLongitude(),
429 SGWayPoint curr ( arr->getLongitude(),
432 remainingTimeEnroute = i->getArrivalTime() - i->getDepartureTime();
433 dest.CourseAndDistance(curr, &courseToDest, &distanceToDest);
434 speed = (distanceToDest*SG_METER_TO_NM) /
435 ((double) remainingTimeEnroute/3600.0);
440 void FGAISchedule::setClosestDistanceToUser()
452 double userLatitude = fgGetDouble("/position/latitude-deg");
453 double userLongitude = fgGetDouble("/position/longitude-deg");
457 #if defined( __CYGWIN__) || defined( __MINGW32__)
458 #define HUGE HUGE_VAL
460 distanceToUser = HUGE;
461 FGScheduledFlightVecIterator i = flights.begin();
462 while (i != flights.end())
464 dep = i->getDepartureAirport();
468 SGWayPoint user ( userLongitude,
471 SGWayPoint current (dep->getLongitude(),
474 user.CourseAndDistance(current, &course, &dist);
475 if (dist < distanceToUser)
477 distanceToUser = dist;
478 //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;