]> git.mxchange.org Git - flightgear.git/blobdiff - src/Traffic/Schedule.cxx
Don't restore initial screen geometry because there is nothing in fg_os* to resize...
[flightgear.git] / src / Traffic / Schedule.cxx
index 29bd9a743bdfda52b97fddd4fb85ea0685da6f09..3a20c96685d988d3aa5d270a25e4ef14b2cb888f 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
+
 #include <stdlib.h>
 #include <time.h>
 #include <iostream>
@@ -42,6 +47,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
 
@@ -59,17 +65,39 @@ FGAISchedule::FGAISchedule()
 {
   firstRun     = true;
   AIManagerRef = 0;
+
+  heavy = false;
+  lat = 0;
+  lon = 0;
+  radius = 0;
+  groundOffset = 0;
+  distanceToUser = 0;
 }
 
 FGAISchedule::FGAISchedule(string    mdl, 
                           string    liv, 
                           string    reg, 
                           bool      hvy, 
+                          string act, 
+                          string arln, 
+                          string mclass, 
+                          string fltpe,
+                          double rad,
+                          double grnd,
                           FGScheduledFlightVec flt)
 {
   modelPath    = mdl; 
   livery       = liv; 
   registration = reg;
+  acType       = act;
+  airline      = arln;
+  m_class      = mclass;
+  flightType   = fltpe;
+  lat = 0;
+  lon = 0;
+  radius       = rad;
+  groundOffset = grnd;
+  distanceToUser = 0;
   heavy = hvy;
   for (FGScheduledFlightVecIterator i = flt.begin();
        i != flt.end();
@@ -89,15 +117,49 @@ FGAISchedule::FGAISchedule(const FGAISchedule &other)
   lat          = other.lat;
   lon          = other.lon;
   AIManagerRef = other.AIManagerRef;
+  acType       = other.acType;
+  airline      = other.airline;
+  m_class      = other.m_class;
   firstRun     = other.firstRun;
+  radius       = other.radius;
+  groundOffset = other.groundOffset;
+  flightType   = other.flightType;
+  distanceToUser = other.distanceToUser;
 }
 
+
 FGAISchedule::~FGAISchedule()
 {
   
 } 
 
-void FGAISchedule::update(time_t now)
+bool FGAISchedule::init()
+{
+  //tm targetTimeDate;
+  //SGTime* currTimeDate = globals->get_time_params();
+
+  //tm *temp = currTimeDate->getGmt();
+  //char buffer[512];
+  //sgTimeFormatTime(&targetTimeDate, buffer);
+  //cout << "Scheduled Time " << buffer << endl; 
+  //cout << "Time :" << time(NULL) << " SGTime : " << sgTimeGetGMT(temp) << endl;
+  for (FGScheduledFlightVecIterator i = flights.begin(); 
+       i != flights.end(); 
+       i++)
+    {
+      //i->adjustTime(now);
+      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();
+  return true;
+}
+
+bool FGAISchedule::update(time_t now)
 {
   FGAirport *dep;
   FGAirport *arr;
@@ -110,7 +172,7 @@ void FGAISchedule::update(time_t now)
   string airport;
   
   double courseToUser,   courseToDest;
-  double distanceToUser, distanceToDest;
+  double distanceToDest;
   double speed;
 
   Point3D temp;
@@ -123,7 +185,7 @@ void FGAISchedule::update(time_t now)
     userLongitude;
 
   if (fgGetBool("/sim/traffic-manager/enabled") == false)
-    return;
+    return true;
   
   aimgr = (FGAIManager *) globals-> get_subsystem("ai_model");  
   // Before the flight status of this traffic entity is updated 
@@ -142,11 +204,11 @@ void FGAISchedule::update(time_t now)
   if (firstRun)
     {
       for (FGScheduledFlightVecIterator i = flights.begin(); 
-          i != flights.end(); 
-          i++)
-       {
-         i->adjustTime(now);
-       }
+          i != flights.end(); 
+          i++)
+       {
+         i->adjustTime(now);
+       }
       firstRun = false;
     }
   
@@ -168,13 +230,13 @@ void FGAISchedule::update(time_t now)
       userLatitude  = fgGetDouble("/position/latitude-deg");
       userLongitude = fgGetDouble("/position/longitude-deg");
 
-
+      //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))
        {
          i->update();
-         return;
+         return true;
        }
 
       // Departure time in the past and arrival time in the future.
@@ -189,19 +251,21 @@ void FGAISchedule::update(time_t now)
        {
          dep = i->getDepartureAirport();
          arr = i->getArrivalAirport  ();
+         if (!(dep && arr))
+           return false;
          
-         temp = sgPolarToCart3d(Point3D(dep->longitude * 
+         temp = sgPolarToCart3d(Point3D(dep->getLongitude() * 
                                         SG_DEGREES_TO_RADIANS, 
-                                        dep->latitude  * 
+                                        dep->getLatitude()  * 
                                         SG_DEGREES_TO_RADIANS, 
                                         1.0));
          a[0] = temp.x();
          a[1] = temp.y();
          a[2] = temp.z();
          
-         temp = sgPolarToCart3d(Point3D(arr->longitude *
+         temp = sgPolarToCart3d(Point3D(arr->getLongitude() *
                                         SG_DEGREES_TO_RADIANS,
-                                        arr->latitude  *
+                                        arr->getLatitude()  *
                                         SG_DEGREES_TO_RADIANS, 
                                         1.0));
          b[0] = temp.x();
@@ -219,9 +283,21 @@ void FGAISchedule::update(time_t now)
          // total time enroute and elapsed time enroute. 
  
          totalTimeEnroute     = i->getArrivalTime() - i->getDepartureTime();
-         elapsedTimeEnroute   = now - i->getDepartureTime();
-         remainingTimeEnroute = i->getArrivalTime()   - now;  
-         
+         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;  
+           }
+         else
+           {
+             lat = dep->getLatitude();
+             lon = dep->getLongitude();
+             elapsedTimeEnroute = 0;
+             remainingTimeEnroute = totalTimeEnroute;
+           }
+                 
          angle *= ( (double) elapsedTimeEnroute/ (double) totalTimeEnroute);
          
          
@@ -236,32 +312,30 @@ void FGAISchedule::update(time_t now)
                  newPos[j] += matrix[j][k]*a[k];
                }
            }
-
+         
          temp = sgCartToPolar3d(Point3D(newPos[0], newPos[1],newPos[2]));
-
          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; 
-             //err << "Lat = " << lat << ", lon = " << lon << endl;
-             //cerr << "Time diff: " << now-i->getDepartureTime() << endl;
            }
          else
            {
-             lat = dep->latitude;
-             lon = dep->longitude;
+             lat = dep->getLatitude();
+             lon = dep->getLongitude();
            }
          
+         
          SGWayPoint current  (lon,
                               lat,
                               i->getCruiseAlt());
          SGWayPoint user (   userLongitude,
                              userLatitude,
                              i->getCruiseAlt());
-         SGWayPoint dest (   arr->longitude,
-                             arr->latitude,
+         SGWayPoint dest (   arr->getLongitude(),
+                             arr->getLatitude(),
                              i->getCruiseAlt());
          // We really only need distance to user
          // and course to destination 
@@ -276,11 +350,11 @@ void FGAISchedule::update(time_t now)
          // one hour flight time, so that would be a good approximate point
          // to start a more detailed simulation of this aircraft.
          //cerr << registration << " is currently enroute from " 
-         //   << dep->id << " to " << arr->id << "distance : " 
+         //   << dep->_id << " to " << arr->_id << "distance : " 
           //   << distanceToUser*SG_METER_TO_NM << endl;
-         if ((distanceToUser*SG_METER_TO_NM) < 500.0)
+         if ((distanceToUser*SG_METER_TO_NM) < TRAFFICTOAIDIST)
            {
-             string flightPlanName = dep->id + string("-") + arr->id + 
+             string flightPlanName = dep->getId() + string("-") + arr->getId() + 
                string(".xml");
              int alt;
              //if  ((i->getDepartureTime() < now))
@@ -289,39 +363,67 @@ void FGAISchedule::update(time_t now)
              //        }
              //else
              //{
-             //          alt = dep->elevation+19;
+             //          alt = dep->_elevation+19;
              //        }
 
-              FGAIModelEntity entity;
-
-              entity.m_class = "jet_transport";
-              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 = 450;
-             entity.fp = new FGAIFlightPlan(&entity, courseToDest, i->getDepartureTime(), dep, arr);
-
-             // Fixme: A non-existent model path results in an
-             // abort, due to an unhandled exeption, in fg main loop.
-             AIManagerRef = aimgr->createAircraft( &entity, this);
-             //cerr << "Created: " << AIManagerRef << endl;
+             // Only allow traffic to be created when the model path exists
+             SGPath mp(globals->get_fg_root());
+             mp.append(modelPath);
+             if (mp.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, i->getDepartureTime(), 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;
-       }
+         return true;
+    }
 
       // Both departure and arrival time are in the future, so this
       // the aircraft is parked at the departure airport.
       // 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();
-         return;
+         return true;
        } 
     }
+  //cerr << "Traffic schedule got to beyond last clause" << endl;
+    // EMH: prevent a warning, should this be 'true' instead?
+    // DT: YES. Originally, this code couldn't be reached, but
+    // when the "if(!(AIManagerManager))" clause is false we
+    // fall through right to the end. This is a valid flow.
+    // the actual value is pretty innocent, only it triggers
+    // warning in TrafficManager::update().
+    // (which was added as a sanity check for myself in the first place. :-)
+    return true;
 }
 
 
@@ -331,3 +433,74 @@ void FGAISchedule::next()
   sort(flights.begin(), flights.end());
 }
 
+double FGAISchedule::getSpeed()
+{
+  double courseToUser,   courseToDest;
+  double distanceToUser, distanceToDest;
+  double speed, remainingTimeEnroute;
+  FGAirport *dep, *arr;
+
+  FGScheduledFlightVecIterator i = flights.begin();
+  dep = i->getDepartureAirport();
+  arr = i->getArrivalAirport  ();
+  if (!(dep && arr))
+    return 0;
+  SGWayPoint dest (   dep->getLongitude(),
+                     dep->getLatitude(),
+                     i->getCruiseAlt()); 
+  SGWayPoint curr (    arr->getLongitude(),
+                     arr->getLatitude(),
+                     i->getCruiseAlt());
+  remainingTimeEnroute     = i->getArrivalTime() - i->getDepartureTime();
+  dest.CourseAndDistance(curr, &courseToDest, &distanceToDest);
+  speed =  (distanceToDest*SG_METER_TO_NM) / 
+    ((double) remainingTimeEnroute/3600.0);
+  return speed;
+}
+
+
+void FGAISchedule::setClosestDistanceToUser()
+{
+  
+  
+  double course;
+  double dist;
+
+  Point3D temp;
+  time_t 
+    totalTimeEnroute, 
+    elapsedTimeEnroute;
+  double userLatitude  = fgGetDouble("/position/latitude-deg");
+  double userLongitude = fgGetDouble("/position/longitude-deg");
+
+  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;
+      
+      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;
+}