]> git.mxchange.org Git - flightgear.git/blobdiff - src/Traffic/Schedule.cxx
make --enable-osgviewer the default
[flightgear.git] / src / Traffic / Schedule.cxx
index 1aae3e683f14e81fcd91840014907ea6b7862b4f..ac2a305c4f2b5cc2817c7b3a628a753728b1264b 100644 (file)
  *
  * You should have received a copy of the GNU General Public License
  * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
  *
  *
  ****************************************************************************
  *
  *****************************************************************************/
+
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#define BOGUS 0xFFFF
+
 #include <stdlib.h>
 #include <time.h>
 #include <iostream>
@@ -42,6 +49,7 @@
 
 #include <AIModel/AIFlightPlan.hxx>
 #include <AIModel/AIManager.hxx>
+#include <AIModel/AIAircraft.hxx>
 #include <Airports/simple.hxx>
 #include <Main/fg_init.hxx>   // That's pretty ugly, but I need fgFindAirportID
 
@@ -66,6 +74,7 @@ FGAISchedule::FGAISchedule()
   radius = 0;
   groundOffset = 0;
   distanceToUser = 0;
+  score = 0;
 }
 
 FGAISchedule::FGAISchedule(string    mdl, 
@@ -78,6 +87,7 @@ FGAISchedule::FGAISchedule(string    mdl,
                           string fltpe,
                           double rad,
                           double grnd,
+                          int    scre,
                           FGScheduledFlightVec flt)
 {
   modelPath    = mdl; 
@@ -96,8 +106,9 @@ FGAISchedule::FGAISchedule(string    mdl,
   for (FGScheduledFlightVecIterator i = flt.begin();
        i != flt.end();
        i++)
-    flights.push_back(FGScheduledFlight((*i)));
+    flights.push_back(new FGScheduledFlight((*(*i))));
   AIManagerRef = 0;
+  score    = scre;
   firstRun = true;
 }
 
@@ -118,13 +129,18 @@ FGAISchedule::FGAISchedule(const FGAISchedule &other)
   radius       = other.radius;
   groundOffset = other.groundOffset;
   flightType   = other.flightType;
+  score        = other.score;
   distanceToUser = other.distanceToUser;
 }
 
 
 FGAISchedule::~FGAISchedule()
 {
-  
+  for (FGScheduledFlightVecIterator flt = flights.begin(); flt != flights.end(); flt++)
+    {
+      delete (*flt);
+    }
+  flights.clear();
 } 
 
 bool FGAISchedule::init()
@@ -142,14 +158,14 @@ bool FGAISchedule::init()
        i++)
     {
       //i->adjustTime(now);
-      if (!(i->initializeAirports()))
+      if (!((*i)->initializeAirports()))
        return false;
     } 
   //sort(flights.begin(), flights.end());
   // Since time isn't initialized yet when this function is called,
   // Find the closest possible airport.
   // This should give a reasonable initialization order. 
-  setClosestDistanceToUser();
+  //setClosestDistanceToUser();
   return true;
 }
 
@@ -157,9 +173,6 @@ bool FGAISchedule::update(time_t now)
 {
   FGAirport *dep;
   FGAirport *arr;
-  sgdVec3 a, b, cross;
-  sgdVec3 newPos;
-  sgdMat4 matrix;
   double angle;
 
   FGAIManager *aimgr;
@@ -169,11 +182,10 @@ bool FGAISchedule::update(time_t now)
   double distanceToDest;
   double speed;
 
-  Point3D temp;
   time_t 
     totalTimeEnroute, 
     elapsedTimeEnroute,
-    remainingTimeEnroute;
+    remainingTimeEnroute, deptime = 0;
   double
     userLatitude,
     userLongitude;
@@ -197,20 +209,29 @@ bool FGAISchedule::update(time_t now)
   // finally kicks in. 
   if (firstRun)
     {
+      if (init() == false)
+       AIManagerRef = BOGUS;
+       
       for (FGScheduledFlightVecIterator i = flights.begin(); 
           i != flights.end(); 
           i++)
        {
-         i->adjustTime(now);
+         (*i)->adjustTime(now);
        }
+      if (fgGetBool("/sim/traffic-manager/instantaneous-action") == true)
+       deptime = now + rand() % 300; // Wait up to 5 minutes until traffic starts moving to prevent too many aircraft 
+                                      // from cluttering the gate areas.
       firstRun = false;
     }
   
   // Sort all the scheduled flights according to scheduled departure time.
   // Because this is done at every update, we only need to check the status
   // of the first listed flight. 
-  sort(flights.begin(), flights.end());
+  sort(flights.begin(), flights.end(), compareScheduledFlights);
+  if (!deptime)
+    deptime = (*flights.begin())->getDepartureTime();
   FGScheduledFlightVecIterator i = flights.begin();
+  SG_LOG (SG_GENERAL, SG_DEBUG,"Processing registration " << registration << " with callsign " << (*i)->getCallSign());
   if (AIManagerRef)
     {
       // Check if this aircraft has been released. 
@@ -227,9 +248,9 @@ bool FGAISchedule::update(time_t now)
       //cerr << "Estimated minimum distance to user: " << distanceToUser << endl;
       // This flight entry is entirely in the past, do we need to 
       // push it forward in time to the next scheduled departure. 
-      if ((i->getDepartureTime() < now) && (i->getArrivalTime() < now))
+      if (((*i)->getDepartureTime() < now) && ((*i)->getArrivalTime() < now))
        {
-         i->update();
+         (*i)->update();
          return true;
        }
 
@@ -239,50 +260,34 @@ bool FGAISchedule::update(time_t now)
       // object for it. 
       //if ((i->getDepartureTime() < now) && (i->getArrivalTime() > now))
       
-
       // Part of this flight is in the future.
-      if (i->getArrivalTime() > now)
+      if ((*i)->getArrivalTime() > now)
        {
-         dep = i->getDepartureAirport();
-         arr = i->getArrivalAirport  ();
+         dep = (*i)->getDepartureAirport();
+         arr = (*i)->getArrivalAirport  ();
          if (!(dep && arr))
            return false;
          
-         temp = sgPolarToCart3d(Point3D(dep->getLongitude() * 
-                                        SG_DEGREES_TO_RADIANS, 
-                                        dep->getLatitude()  * 
-                                        SG_DEGREES_TO_RADIANS, 
-                                        1.0));
-         a[0] = temp.x();
-         a[1] = temp.y();
-         a[2] = temp.z();
-         
-         temp = sgPolarToCart3d(Point3D(arr->getLongitude() *
-                                        SG_DEGREES_TO_RADIANS,
-                                        arr->getLatitude()  *
-                                        SG_DEGREES_TO_RADIANS, 
-                                        1.0));
-         b[0] = temp.x();
-         b[1] = temp.y();
-         b[2] = temp.z();
-         sgdNormaliseVec3(a);
-         sgdNormaliseVec3(b);
-         sgdVectorProductVec3(cross,b,a);
+          SGVec3d a = SGVec3d::fromGeoc(SGGeoc::fromDegM(dep->getLongitude(),
+                                                dep->getLatitude(), 1));
+          SGVec3d b = SGVec3d::fromGeoc(SGGeoc::fromDegM(arr->getLongitude(),
+                                                arr->getLatitude(), 1));
+          SGVec3d _cross = cross(b, a);
          
-         angle = sgACos(sgdScalarProductVec3(a,b));
+         angle = sgACos(dot(a, b));
          
          // Okay, at this point we have the angle between departure and 
          // arrival airport, in degrees. From here we can interpolate the
          // position of the aircraft by calculating the ratio between 
          // total time enroute and elapsed time enroute. 
  
-         totalTimeEnroute     = i->getArrivalTime() - i->getDepartureTime();
-         if (now > i->getDepartureTime())
+         totalTimeEnroute     = (*i)->getArrivalTime() - (*i)->getDepartureTime();
+         if (now > (*i)->getDepartureTime())
            {
              //err << "Lat = " << lat << ", lon = " << lon << endl;
              //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
-             elapsedTimeEnroute   = now - i->getDepartureTime();
-             remainingTimeEnroute = i->getArrivalTime()   - now;  
+             elapsedTimeEnroute   = now - (*i)->getDepartureTime();
+             remainingTimeEnroute = (*i)->getArrivalTime()   - now;  
            }
          else
            {
@@ -297,23 +302,22 @@ bool FGAISchedule::update(time_t now)
          
          //cout << "a = " << a[0] << " " << a[1] << " " << a[2] 
          //     << "b = " << b[0] << " " << b[1] << " " << b[2] << endl;  
-         sgdMakeRotMat4(matrix, angle, cross); 
+          sgdMat4 matrix;
+         sgdMakeRotMat4(matrix, angle, _cross.sg()); 
+          SGVec3d newPos(0, 0, 0);
          for(int j = 0; j < 3; j++)
            {
-             newPos[j] =0.0;
              for (int k = 0; k<3; k++)
                {
                  newPos[j] += matrix[j][k]*a[k];
                }
            }
          
-         temp = sgCartToPolar3d(Point3D(newPos[0], newPos[1],newPos[2]));
-         if (now > i->getDepartureTime())
+         if (now > (*i)->getDepartureTime())
            {
-             //cerr << "Lat = " << lat << ", lon = " << lon << endl;
-             //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
-             lat = temp.lat() * SG_RADIANS_TO_DEGREES;
-             lon = temp.lon() * SG_RADIANS_TO_DEGREES; 
+              SGGeoc geoc = SGGeoc::fromCart(newPos);
+             lat = geoc.getLatitudeDeg();
+             lon = geoc.getLongitudeDeg(); 
            }
          else
            {
@@ -324,13 +328,16 @@ bool FGAISchedule::update(time_t now)
          
          SGWayPoint current  (lon,
                               lat,
-                              i->getCruiseAlt());
+                              (*i)->getCruiseAlt(), 
+                              SGWayPoint::SPHERICAL);
          SGWayPoint user (   userLongitude,
                              userLatitude,
-                             i->getCruiseAlt());
+                             (*i)->getCruiseAlt(), 
+                             SGWayPoint::SPHERICAL);
          SGWayPoint dest (   arr->getLongitude(),
                              arr->getLatitude(),
-                             i->getCruiseAlt());
+                             (*i)->getCruiseAlt(), 
+                             SGWayPoint::SPHERICAL);
          // We really only need distance to user
          // and course to destination 
          user.CourseAndDistance(current, &courseToUser, &distanceToUser);
@@ -350,7 +357,7 @@ bool FGAISchedule::update(time_t now)
            {
              string flightPlanName = dep->getId() + string("-") + arr->getId() + 
                string(".xml");
-             int alt;
+             //int alt;
              //if  ((i->getDepartureTime() < now))
              //{
              //          alt = i->getCruiseAlt() *100;
@@ -360,33 +367,48 @@ bool FGAISchedule::update(time_t now)
              //          alt = dep->_elevation+19;
              //        }
 
-              FGAIModelEntity entity;
-
-              entity.m_class = m_class; //"jet_transport";
-             entity.company = airline; //i->getAirline();
-             entity.acType  = acType; //i->getAcType();
-              entity.path = modelPath.c_str();
-              entity.flightplan = flightPlanName.c_str();
-              entity.latitude = lat;
-              entity.longitude = lon;
-              entity.altitude = i->getCruiseAlt() *100; // convert from FL to feet
-              entity.speed = speed;
-             entity.roll  = 0.0;
-             entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, 
-                                            arr,true, radius, flightType, acType, airline);
-             
-             // Fixme: A non-existent model path results in an
-             // abort, due to an unhandled exeption, in fg main loop.
-              FGAIBase *aircraft = (FGAIBase*)aimgr->createAircraft( &entity, this);
-             AIManagerRef = aircraft->getID();
-             //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
-             //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
-             //cerr << "Dep      : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
-             //cerr << "Arr      : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
-             //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
-             //cerr << "Total time     = " << (totalTimeEnroute/3600.0) << endl;
-             //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
-             
+             // Only allow traffic to be created when the model path (or the AI version of mp) exists
+             SGPath mp(globals->get_fg_root());
+             SGPath mp_ai = mp;
+
+             mp.append(modelPath);
+             mp_ai.append("AI");
+             mp_ai.append(modelPath);
+
+             if (mp.exists() || mp_ai.exists())
+             {
+                 FGAIAircraft *aircraft = new FGAIAircraft(this);
+                 aircraft->setPerformance(m_class); //"jet_transport";
+                 aircraft->setCompany(airline); //i->getAirline();
+                 aircraft->setAcType(acType); //i->getAcType();
+                 aircraft->setPath(modelPath.c_str());
+                 //aircraft->setFlightPlan(flightPlanName);
+                 aircraft->setLatitude(lat);
+                 aircraft->setLongitude(lon);
+                 aircraft->setAltitude((*i)->getCruiseAlt()*100); // convert from FL to feet
+                 aircraft->setSpeed(speed);
+                 aircraft->setBank(0);
+                 aircraft->SetFlightPlan(new FGAIFlightPlan(flightPlanName, courseToDest, deptime, 
+                                                            dep, arr,true, radius, 
+                                                            (*i)->getCruiseAlt()*100, 
+                                                            lat, lon, speed, flightType, acType, 
+                                                            airline));
+                 aimgr->attach(aircraft);
+                 
+                 
+                 AIManagerRef = aircraft->getID();
+                 //cerr << "Class: " << m_class << ". acType: " << acType << ". Airline: " << airline << ". Speed = " << speed << ". From " << dep->getId() << " to " << arr->getId() << ". Time Fraction = " << (remainingTimeEnroute/(double) totalTimeEnroute) << endl;
+                 //cerr << "Latitude : " << lat << ". Longitude : " << lon << endl;
+                 //cerr << "Dep      : " << dep->getLatitude()<< ", "<< dep->getLongitude() << endl;
+                 //cerr << "Arr      : " << arr->getLatitude()<< ", "<< arr->getLongitude() << endl;
+                 //cerr << "Time remaining = " << (remainingTimeEnroute/3600.0) << endl;
+                 //cerr << "Total time     = " << (totalTimeEnroute/3600.0) << endl;
+                 //cerr << "Distance remaining = " << distanceToDest*SG_METER_TO_NM << endl;
+                 }
+             else
+               {
+                 SG_LOG(SG_INPUT, SG_WARN, "TrafficManager: Could not load model " << mp.str());
+               }
            }
          return true;
     }
@@ -396,9 +418,9 @@ bool FGAISchedule::update(time_t now)
       // Currently this status is mostly ignored, but in future
       // versions, code should go here that -if within user range-
       // positions these aircraft at parking locations at the airport.
-  if ((i->getDepartureTime() > now) && (i->getArrivalTime() > now))
+      if (((*i)->getDepartureTime() > now) && ((*i)->getArrivalTime() > now))
        { 
-         dep = i->getDepartureAirport();
+         dep = (*i)->getDepartureAirport();
          return true;
        } 
     }
@@ -416,78 +438,86 @@ bool FGAISchedule::update(time_t now)
 
 void FGAISchedule::next()
 {
-  flights.begin()->update();
-  sort(flights.begin(), flights.end());
+  (*flights.begin())->update();
+  sort(flights.begin(), flights.end(), compareScheduledFlights);
 }
 
 double FGAISchedule::getSpeed()
 {
-  double courseToUser,   courseToDest;
-  double distanceToUser, distanceToDest;
+  double courseToDest;
+  double distanceToDest;
   double speed, remainingTimeEnroute;
   FGAirport *dep, *arr;
 
   FGScheduledFlightVecIterator i = flights.begin();
-  dep = i->getDepartureAirport();
-  arr = i->getArrivalAirport  ();
+  dep = (*i)->getDepartureAirport();
+  arr = (*i)->getArrivalAirport  ();
   if (!(dep && arr))
     return 0;
  
   SGWayPoint dest (   dep->getLongitude(),
                      dep->getLatitude(),
-                     i->getCruiseAlt()); 
+                     (*i)->getCruiseAlt(), 
+                     SGWayPoint::SPHERICAL); 
   SGWayPoint curr (    arr->getLongitude(),
                      arr->getLatitude(),
-                     i->getCruiseAlt());
-  remainingTimeEnroute     = i->getArrivalTime() - i->getDepartureTime();
+                      (*i)->getCruiseAlt(), 
+                      SGWayPoint::SPHERICAL);
+  remainingTimeEnroute     = (*i)->getArrivalTime() - (*i)->getDepartureTime();
   dest.CourseAndDistance(curr, &courseToDest, &distanceToDest);
   speed =  (distanceToDest*SG_METER_TO_NM) / 
     ((double) remainingTimeEnroute/3600.0);
   return speed;
 }
 
+bool compareSchedules(FGAISchedule*a, FGAISchedule*b)
+{ 
+  return (*a) < (*b); 
+} 
 
-void FGAISchedule::setClosestDistanceToUser()
-{
+
+// void FGAISchedule::setClosestDistanceToUser()
+// {
   
   
-  double course;
-  double dist;
+//   double course;
+//   double dist;
 
-  Point3D temp;
-  time_t 
-    totalTimeEnroute, 
-    elapsedTimeEnroute;
+//   Point3D temp;
+//   time_t 
+//     totalTimeEnroute, 
+//     elapsedTimeEnroute;
  
-  double userLatitude  = fgGetDouble("/position/latitude-deg");
-  double userLongitude = fgGetDouble("/position/longitude-deg");
+//   double userLatitude  = fgGetDouble("/position/latitude-deg");
+//   double userLongitude = fgGetDouble("/position/longitude-deg");
 
-  FGAirport *dep;
+//   FGAirport *dep;
   
-#if defined( __CYGWIN__) || defined( __MINGW32__)
-  #define HUGE HUGE_VAL
-#endif
-  distanceToUser = HUGE;
-  FGScheduledFlightVecIterator i = flights.begin();
-  while (i != flights.end())
-    {
-      dep = i->getDepartureAirport();
-      //if (!(dep))
-      //return HUGE;
+// #if defined( __CYGWIN__) || defined( __MINGW32__)
+//   #define HUGE HUGE_VAL
+// #endif
+//   distanceToUser = HUGE;
+//   FGScheduledFlightVecIterator i = flights.begin();
+//   while (i != flights.end())
+//     {
+//       dep = i->getDepartureAirport();
+//       //if (!(dep))
+//       //return HUGE;
       
-      SGWayPoint user (   userLongitude,
-                         userLatitude,
-                         i->getCruiseAlt());
-      SGWayPoint current (dep->getLongitude(),
-                         dep->getLatitude(),
-                         0);
-      user.CourseAndDistance(current, &course, &dist);
-      if (dist < distanceToUser)
-       {
-         distanceToUser = dist;
-         //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
-       }
-      i++;
-    }
-  //return distToUser;
-}
+//       SGWayPoint user (   userLongitude,
+//                       userLatitude,
+//                       i->getCruiseAlt());
+//       SGWayPoint current (dep->getLongitude(),
+//                       dep->getLatitude(),
+//                       0);
+//       user.CourseAndDistance(current, &course, &dist);
+//       if (dist < distanceToUser)
+//     {
+//       distanceToUser = dist;
+//       //cerr << "Found closest distance to user for " << registration << " to be " << distanceToUser << " at airport " << dep->getId() << endl;
+//     }
+//       i++;
+//     }
+//   //return distToUser;
+// }
+