]> git.mxchange.org Git - flightgear.git/blobdiff - src/FDM/YASim/YASim.cxx
Fix for bug 1304 - crash loading XML route
[flightgear.git] / src / FDM / YASim / YASim.cxx
index 9f7594b2e7c3b2cb34af00b70ad975157f16b6c1..d82d14398c0a2628430360ae2f0266a10a956e15 100644 (file)
@@ -1,4 +1,11 @@
 
+#ifdef HAVE_CONFIG_H
+#  include "config.h"
+#endif
+
+#include <cstdlib>
+#include <cstdio>
+
 #include <simgear/debug/logstream.hxx>
 #include <simgear/math/sg_geodesy.hxx>
 #include <simgear/misc/sg_path.hxx>
 #include "Integrator.hpp"
 #include "Glue.hpp"
 #include "Gear.hpp"
+#include "Hook.hpp"
+#include "Launchbar.hpp"
+#include "FGGround.hpp"
 #include "PropEngine.hpp"
 #include "PistonEngine.hpp"
 
 #include "YASim.hxx"
 
 using namespace yasim;
+using std::string;
 
 static const float YASIM_PI = 3.14159265358979323846;
 static const float RAD2DEG = 180/YASIM_PI;
@@ -36,16 +47,25 @@ static const float W2HP = 1.3416e-3;
 static const float INHG2PA = 3386.389;
 static const float SLUG2KG = 14.59390;
 
-YASim::YASim(double dt)
+YASim::YASim(double dt) :
+    _simTime(0)
 {
 //     set_delta_t(dt);
     _fdm = new FGFDM();
 
     _dt = dt;
 
+    _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
 }
 
+YASim::~YASim()
+{
+    delete _fdm;
+
+    _gearProps.clear();
+}
+
 void YASim::report()
 {
     Airplane* a = _fdm->getAirplane();
@@ -61,7 +81,6 @@ void YASim::report()
     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
-    
 
     float cg[3];
     char buf[256];
@@ -81,35 +100,59 @@ void YASim::bind()
     // Run the superclass bind to set up a bunch of property ties
     FGInterface::bind();
 
+//Torsten Dreyer: we shouldn't do this anymore because we don't set these values nomore
     // Now UNtie the ones that we are going to set ourselves.
-    fgUntie("/consumables/fuel/tank[0]/level-gal_us");
-    fgUntie("/consumables/fuel/tank[1]/level-gal_us");
+//    fgUntie("/consumables/fuel/tank[0]/level-gal_us");
+//    fgUntie("/consumables/fuel/tank[1]/level-gal_us");
 
     char buf[256];
     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
-       sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
-       sprintf(buf, "/engines/engine[%d]/rpm", i);           fgUntie(buf);
-       sprintf(buf, "/engines/engine[%d]/mp-osi", i);        fgUntie(buf);
-       sprintf(buf, "/engines/engine[%d]/egt-degf", i);      fgUntie(buf);
+        sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i);        fgUntie(buf);
+        sprintf(buf, "/engines/engine[%d]/rpm", i);                  fgUntie(buf);
+        sprintf(buf, "/engines/engine[%d]/mp-osi", i);               fgUntie(buf);
+        sprintf(buf, "/engines/engine[%d]/egt-degf", i);             fgUntie(buf);
+        sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
     }
 }
 
+YASim::GearProps::GearProps(SGPropertyNode_ptr gear_root) :
+    has_brake(gear_root->getNode("has-brake", true)),
+    wow(gear_root->getNode("wow", true)),
+    compression_norm(gear_root->getNode("compression-norm", true)),
+    compression_m(gear_root->getNode("compression-m", true)),
+    caster_angle_deg(gear_root->getNode("caster-angle-deg", true)),
+    rollspeed_ms(gear_root->getNode("rollspeed-ms", true)),
+    ground_is_solid(gear_root->getNode("ground-is-solid", true)),
+    ground_friction_factor(gear_root->getNode("ground-friction-factor", true))
+{
+}
+
 void YASim::init()
 {
-    Airplane* a = _fdm->getAirplane();
-    Model* m = a->getModel();
+    Airplane* airplane = _fdm->getAirplane();
+    Model* model = airplane->getModel();
+
+    _crashed         = fgGetNode("/sim/crashed", true);
+    _pressure_inhg   = fgGetNode("/environment/pressure-inhg", true);
+    _temp_degc       = fgGetNode("/environment/temperature-degc", true);
+    _density_slugft3 = fgGetNode("/environment/density-slugft3", true);
+    _gear_agl_m      = fgGetNode("/position/gear-agl-m", true);
+    _gear_agl_ft     = fgGetNode("/position/gear-agl-ft", true);
+    _pilot_g         = fgGetNode("/accelerations/pilot-g", true);
+    _speed_setprop   = fgGetNode("/sim/presets/speed-set", true);
 
     // Superclass hook
     common_init();
 
-    m->setCrashed(false);
+    model->setCrashed(false);
+    _crashed->setBoolValue(false);
 
     // Figure out the initial speed type
-    string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
-    if (speed_set == "NED")
-        _speed_set = NED;
-    else if (speed_set == "UVW")
+    string speed_set = _speed_setprop->getStringValue();
+    if ((speed_set == "") || (speed_set == "UVW"))
         _speed_set = UVW;
+    else if (speed_set == "NED")
+        _speed_set = NED;
     else if (speed_set == "knots")
         _speed_set = KNOTS;
     else if (speed_set == "mach")
@@ -123,24 +166,45 @@ void YASim::init()
     SGPath f(fgGetString("/sim/aircraft-dir"));
     f.append(fgGetString("/sim/aero"));
     f.concat(".xml");
-    readXML(f.str(), *_fdm);
+    try {
+        readXML(f.str(), *_fdm);
+    } catch (const sg_exception &e) {
+        SG_LOG(SG_FLIGHT, SG_ALERT,
+               "Error reading YASim FDM: '" << f.str() << "'" << std::endl
+               << e.getFormattedMessage());
+        throw e;
+    }
 
     // Compile it into a real airplane, and tell the user what they got
-    a->compile();
+    airplane->compile();
     report();
 
     _fdm->init();
 
+    if (model->getLaunchbar())
+    {
+        _catapult_launch_cmd         = fgGetNode("/controls/gear/catapult-launch-cmd", true);
+        _launchbar_position_norm     = fgGetNode("/gear/launchbar/position-norm", true);
+        _launchbar_holdback_pos_norm = fgGetNode("/gear/launchbar/holdback-position-norm", true);
+        _launchbar_state             = fgGetNode("/gear/launchbar/state", true);
+        _launchbar_strop             = fgGetNode("/gear/launchbar/strop", true);
+    }
+    if (airplane->getHook())
+    {
+        _tailhook_position_norm = fgGetNode("/gear/tailhook/position-norm", 0, true);
+    }
+
     // Create some FG{Eng|Gear}Interface objects
-    int i;
-    for(i=0; i<a->numGear(); i++) {
-        Gear* g = a->getGear(i);
-       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
+    for(int i=0; i<airplane->numGear(); i++) {
+        Gear* g = airplane->getGear(i);
+        SGPropertyNode * node = fgGetNode("gear/gear", i, true);
         float pos[3];
         g->getPosition(pos);
-       node->setDoubleValue("xoffset-in", pos[0]);
-       node->setDoubleValue("yoffset-in", pos[1]);
-       node->setDoubleValue("zoffset-in", pos[2]);
+        node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
+        node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
+        node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
+
+        _gearProps.push_back(GearProps(node));
     }
 
     // Are we at ground level?  If so, lift the plane up so the gear
@@ -148,21 +212,27 @@ void YASim::init()
     double runway_altitude = get_Runway_altitude();
     if(get_Altitude() - runway_altitude < 50) {
         fgSetBool("/controls/gear/gear-down", false);
-       float minGearZ = 1e18;
-       for(i=0; i<a->numGear(); i++) {
-           Gear* g = a->getGear(i);
-           float pos[3];
-           g->getPosition(pos);
-           if(pos[2] < minGearZ)
-               minGearZ = pos[2];
-       }
-       _set_Altitude(runway_altitude - minGearZ*M2FT);
-       fgSetBool("/controls/gear/gear-down", true);
+        float minGearZ = 1e18;
+        for(int i=0; i<airplane->numGear(); i++) {
+            Gear* g = airplane->getGear(i);
+            float pos[3];
+            g->getPosition(pos);
+            if(pos[2] < minGearZ)
+                minGearZ = pos[2];
+        }
+        _set_Altitude(runway_altitude - minGearZ*M2FT);
+        // ground start-up: gear down
+        fgSetBool("/controls/gear/gear-down", true);
+    }
+    else
+    {
+        // airborne start-up: gear up
+        fgSetBool("/controls/gear/gear-down", false);
     }
 
     // Blank the state, and copy in ours
     State s;
-    m->setState(&s);
+    model->setState(&s);
     copyToYASim(true);
 
     _fdm->getExternalInput();
@@ -179,25 +249,51 @@ void YASim::update(double dt)
     int iterations = _calc_multiloop(dt);
 
     // If we're crashed, then we don't care
-    if(_fdm->getAirplane()->getModel()->isCrashed()) {
-        if(!fgGetBool("/sim/crashed"))
-            fgSetBool("/sim/crashed", true);
+    if(_crashed->getBoolValue() || _fdm->getAirplane()->getModel()->isCrashed()) {
+        if(!_crashed->getBoolValue())
+            _crashed->setBoolValue(true);
+        _fdm->getAirplane()->getModel()->setCrashed(false);
         return;
     }
 
+    // ground.  Calculate a cartesian coordinate for the ground under
+    // us, find the (geodetic) up vector normal to the ground, then
+    // use that to find the final (radius) term of the plane equation.
+    float v[3] = {
+      static_cast<float>(get_uBody()),
+      static_cast<float>(get_vBody()),
+      static_cast<float>(get_wBody())
+    };
+    float lat = get_Latitude(); float lon = get_Longitude();
+    float alt = get_Altitude() * FT2M; double xyz[3];
+    sgGeodToCart(lat, lon, alt, xyz);
+    // build the environment cache.
+    float vr = _fdm->getVehicleRadius();
+    vr += 2.0*FT2M*dt*Math::mag3(v);
+    prepare_ground_cache_m( _simTime, _simTime + dt, xyz, vr );
+
+    // Track time increments.
+    FGGround* gr
+      = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
+
     int i;
     for(i=0; i<iterations; i++) {
+        gr->setTimeOffset(_simTime + i*_dt);
         copyToYASim(false);
         _fdm->iterate(_dt);
         copyFromYASim();
     }
+
+    // Increment the local sim time
+    _simTime += dt;
+    gr->setTimeOffset(_simTime);
 }
 
 void YASim::copyToYASim(bool copyState)
 {
     // Physical state
-    float lat = get_Latitude();
-    float lon = get_Longitude();
+    double lat = get_Latitude();
+    double lon = get_Longitude();
     float alt = get_Altitude() * FT2M;
     float roll = get_Phi();
     float pitch = get_Theta();
@@ -209,14 +305,10 @@ void YASim::copyToYASim(bool copyState)
     wind[1] = get_V_east_airmass() * FT2M * -1.0;
     wind[2] = get_V_down_airmass() * FT2M * -1.0;
 
-    // Get ground elevation
-    double ground = fgGetDouble("/position/ground-elev-m");
-    // cout << "YASIM: ground = " << ground << endl;
-
-    float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
-    float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
-    float dens = fgGetFloat("/environment/density-slugft3") 
-        * SLUG2KG * M2FT*M2FT*M2FT;
+    float pressure = _pressure_inhg->getFloatValue() * INHG2PA;
+    float temp     = _temp_degc->getFloatValue() + 273.15;
+    float dens     = _density_slugft3->getFloatValue() *
+                            SLUG2KG * M2FT*M2FT*M2FT;
 
     // Convert and set:
     Model* model = _fdm->getAirplane()->getModel();
@@ -226,13 +318,17 @@ void YASim::copyToYASim(bool copyState)
 
     // position
     sgGeodToCart(lat, lon, alt, s.pos);
+    {
+      // allow setting of /position/[lat|long|alti]tude
+      double * dp = &model->getState()->pos[0];
+      dp[0] = s.pos[0]; dp[1] = s.pos[1]; dp[2] = s.pos[2];
+    }
 
     // orientation
     Glue::euler2orient(roll, pitch, hdg, s.orient);
     Math::mmul33(s.orient, xyz2ned, s.orient);
 
     // Velocity
-    string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
     float v[3];
     bool needCopy = false;
     switch (_speed_set) {
@@ -273,25 +369,22 @@ void YASim::copyToYASim(bool copyState)
     Math::set3(v, s.v);
 
     if(copyState || needCopy)
-       model->setState(&s);
+        model->setState(&s);
 
     // wind
     Math::tmul33(xyz2ned, wind, wind);
     model->setWind(wind);
 
-    // ground.  Calculate a cartesian coordinate for the ground under
-    // us, find the (geodetic) up vector normal to the ground, then
-    // use that to find the final (radius) term of the plane equation.
-    double xyz[3], gplane[3]; float up[3];
-    sgGeodToCart(lat, lon, ground, xyz);
-    Glue::geodUp(lat, lon, up); // FIXME, needless reverse computation...
-    int i;
-    for(i=0; i<3; i++) gplane[i] = up[i];
-    double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
-    model->setGroundPlane(gplane, rad);
-
     // air
     model->setAir(pressure, temp, dens);
+
+    // Query a ground plane for each gear/hook/launchbar and
+    // write that value into the corresponding class.
+    _fdm->getAirplane()->getModel()->updateGround(&s);
+
+    Launchbar* l = model->getLaunchbar();
+    if (l)
+        l->setLaunchCmd(0.0 < _catapult_launch_cmd->getFloatValue());
 }
 
 // All the settables:
@@ -304,7 +397,7 @@ void YASim::copyToYASim(bool copyState)
 // _set_Accels_CG_Body_N 
 // _set_Velocities_Local
 // _set_Velocities_Ground
-// _set_Velocities_Wind_Body
+// _set_Velocities_Body
 // _set_Omega_Body
 // _set_Euler_Rates
 // _set_Euler_Angles
@@ -349,12 +442,17 @@ void YASim::copyFromYASim()
     double lat, lon, alt;
     sgCartToGeod(s->pos, &lat, &lon, &alt);
     _set_Geodetic_Position(lat, lon, alt*M2FT);
+    double groundlevel_m = get_groundlevel_m(lat, lon, alt);
+    _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
+    _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
+
+    // the smallest agl of all gears
+    _gear_agl_m->setFloatValue(model->getAGL());
+    _gear_agl_ft->setFloatValue(model->getAGL()*M2FT);
 
     // UNUSED
     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
 
-    _set_Altitude_AGL(model->getAGL() * M2FT);
-
     // useful conversion matrix
     float xyz2ned[9];
     Glue::xyz2nedMat(lat, lon, xyz2ned);
@@ -364,7 +462,7 @@ void YASim::copyFromYASim()
     Math::vmul33(xyz2ned, s->v, v);
     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
-                                  M2FT*v[1]*M2FT*v[1]));
+                                   M2FT*v[1]*M2FT*v[1]));
     _set_Climb_Rate(-M2FT*v[2]);
 
     // The HUD uses this, but inverts down (?!)
@@ -372,6 +470,10 @@ void YASim::copyFromYASim()
 
     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
 
+    // ecef speed in body axis
+    Math::vmul33(s->orient, s->v, v);
+    _set_Velocities_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
+
     // Airflow velocity.
     float wind[3];
     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
@@ -380,16 +482,15 @@ void YASim::copyFromYASim()
     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
     Math::sub3(s->v, wind, v);                      // V - wind in global
     Math::vmul33(s->orient, v, v);               // to body coordinates
-    _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
 
-    float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
-    float T = fgGetDouble("/environment/temperature-degC") + 273.15;
-    float D = fgGetFloat("/environment/density-slugft3")
+    float P = _pressure_inhg->getFloatValue() * INHG2PA;
+    float T = _temp_degc->getFloatValue() + 273.15;
+    float D = _density_slugft3->getFloatValue()
         *SLUG2KG * M2FT*M2FT*M2FT;
     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
-    _set_Mach_number(Atmosphere::calcMach(v[0], T));
+    _set_Mach_number(Atmosphere::calcMach(Math::mag3(v), T));
 
     // acceleration
     Math::vmul33(xyz2ned, s->acc, v);
@@ -400,12 +501,12 @@ void YASim::copyFromYASim()
     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
 
     _fdm->getAirplane()->getPilotAccel(v);
-    _set_Accels_Pilot_Body(-M2FT*v[0], M2FT*v[1], M2FT*v[2]);
+    _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
 
     // There is no property for pilot G's, but I need it for a panel
     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
     // REAL HOME!
-    fgSetFloat("/accelerations/pilot-g", -v[2]/9.8);
+    _pilot_g->setFloatValue(-v[2]/9.8);
 
     // The one appears (!) to want inverted pilot acceleration
     // numbers, in G's...
@@ -414,9 +515,9 @@ void YASim::copyFromYASim()
 
     // orientation
     float alpha, beta;
-    Glue::calcAlphaBeta(s, &alpha, &beta);
+    Glue::calcAlphaBeta(s, wind, &alpha, &beta);
     _set_Alpha(alpha);
-    _set_Beta(beta);
+    _set_Beta(-beta);
 
     float tmp[9];
     Math::trans33(xyz2ned, tmp);
@@ -435,12 +536,53 @@ void YASim::copyFromYASim()
     _set_Euler_Rates(roll, pitch, hdg);
 
     // Fill out our engine and gear objects
-    int i;
-    for(i=0; i<airplane->numGear(); i++) {
+    for(int i=0; i<airplane->numGear(); i++) {
         Gear* g = airplane->getGear(i);
-       SGPropertyNode * node = fgGetNode("gear/gear", i, true);
-       node->setBoolValue("has-brake", g->getBrake() != 0);
-       node->setBoolValue("wow", g->getCompressFraction() != 0);
-       node->setFloatValue("compression-norm", g->getCompressFraction());
+        GearProps& gearProps = _gearProps[i];
+        gearProps.has_brake->setBoolValue(
+                g->getBrake() != 0);
+        gearProps.wow->setBoolValue(
+                g->getCompressFraction() != 0);
+        gearProps.compression_norm->setFloatValue(
+                g->getCompressFraction());
+        gearProps.compression_m->setFloatValue(
+                g->getCompressDist());
+        gearProps.caster_angle_deg->setFloatValue(
+                g->getCasterAngle() * RAD2DEG);
+        gearProps.rollspeed_ms->setFloatValue(
+                g->getRollSpeed());
+        gearProps.ground_is_solid->setBoolValue(
+                g->getGroundIsSolid()!=0);
+        gearProps.ground_friction_factor->setFloatValue(
+                g->getGroundFrictionFactor());
+    }
+
+    Hook* h = airplane->getHook();
+    if(h) {
+        _tailhook_position_norm->setFloatValue(h->getCompressFraction());
+    }
+
+    Launchbar* l = airplane->getLaunchbar();
+    if(l) {
+        _launchbar_position_norm->setFloatValue(l->getCompressFraction());
+        _launchbar_holdback_pos_norm->setFloatValue(l->getHoldbackCompressFraction());
+        _launchbar_state->setStringValue(l->getState());
+        _launchbar_strop->setBoolValue(l->getStrop());
     }
 }
+
+/** Reinit the FDM.
+ * This is only used after a replay session and when the user requested to resume at
+ * a past point of time. In this case the FDM must reload all values from the property
+ * tree (as given by the replay system). */
+void YASim::reinit()
+{
+    // Process inputs. Use excessive value for dt to make sure all transition effects
+    // have reached their final state (i.e. gear is extended/retracted) - which is vital
+    // for many properties to be complete before the first FDM run (otherwise the gear may
+    // still be up, thrust-reversers/speed-brakes/... may still be partially deployed...).
+    _fdm->getExternalInput(1000);
+
+    // get current FDM values from the property tree
+    copyToYASim(true);
+}