1
0
Fork 0

Merge branch 'next' of ssh://git.code.sf.net/p/flightgear/flightgear into next

This commit is contained in:
Erik Hofman 2017-03-30 11:24:07 +02:00
commit f3893c54bd
16 changed files with 265 additions and 91 deletions

View file

@ -2,4 +2,4 @@
add_definitions(-DSQLITE_OMIT_LOAD_EXTENSION) add_definitions(-DSQLITE_OMIT_LOAD_EXTENSION)
add_definitions(-DNDEBUG) add_definitions(-DNDEBUG)
add_library(fgsqlite3 sqlite3.c) add_library(fgsqlite3 sqlite3.c)
set_target_properties(fgsqlite3 PROPERTIES COMPILE_FLAGS "-fno-fast-math") set_target_properties(fgsqlite3 PROPERTIES COMPILE_FLAGS "-fpic -fno-fast-math")

View file

@ -509,8 +509,6 @@ configure_file (
add_subdirectory(3rdparty) add_subdirectory(3rdparty)
add_subdirectory(utils) add_subdirectory(utils)
add_subdirectory(src)
add_subdirectory(man)
if(ENABLE_TESTS) if(ENABLE_TESTS)
# enable CTest / make test target # enable CTest / make test target
@ -528,6 +526,9 @@ else()
message(STATUS "Tests: DISABLED") message(STATUS "Tests: DISABLED")
endif(ENABLE_TESTS) endif(ENABLE_TESTS)
add_subdirectory(src)
add_subdirectory(man)
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
### uninstall target ### uninstall target
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------

View file

@ -832,7 +832,12 @@ Wing* FGFDM::parseWing(XMLAttributes* a, const char* type, Version * version)
w->setSweep(attrf(a, "sweep", 0) * DEG2RAD); w->setSweep(attrf(a, "sweep", 0) * DEG2RAD);
w->setTaper(attrf(a, "taper", 1)); w->setTaper(attrf(a, "taper", 1));
w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD); w->setDihedral(attrf(a, "dihedral", defDihed) * DEG2RAD);
w->setCamber(attrf(a, "camber", 0));
float camber = attrf(a, "camber", 0);
if (!version->isVersionOrNewer(Version::YASIM_VERSION_2017_2) && (camber == 0)) {
SG_LOG(SG_FLIGHT, SG_DEV_WARN, "YASIM warning: versions before 2017.2 are buggy for wings with camber=0");
}
w->setCamber(camber);
// These come in with positive indicating positive AoA, but the // These come in with positive indicating positive AoA, but the
// internals expect a rotation about the left-pointing Y axis, so // internals expect a rotation about the left-pointing Y axis, so

View file

@ -55,13 +55,12 @@ void RigidBody::setMass(int handle, float mass)
void RigidBody::setMass(int handle, float mass, const float* pos, bool isStatic) void RigidBody::setMass(int handle, float mass, const float* pos, bool isStatic)
{ {
_masses[handle].m = mass;
_masses[handle].isStatic = isStatic; _masses[handle].isStatic = isStatic;
Math::set3(pos, _masses[handle].p); Math::set3(pos, _masses[handle].p);
setMass(handle, mass);
if (_bodyN != 0) { if (_bodyN != 0) {
SGPropertyNode_ptr n = _bodyN->getChild("mass", handle, true); SGPropertyNode_ptr n = _bodyN->getChild("mass", handle, true);
n->getNode("isStatic", true)->setValue(isStatic); n->getNode("isStatic", true)->setValue(isStatic);
n->getNode("mass", true)->setFloatValue(mass);
n->getNode("pos-x", true)->setFloatValue(pos[0]); n->getNode("pos-x", true)->setFloatValue(pos[0]);
n->getNode("pos-y", true)->setFloatValue(pos[1]); n->getNode("pos-y", true)->setFloatValue(pos[1]);
n->getNode("pos-z", true)->setFloatValue(pos[2]); n->getNode("pos-z", true)->setFloatValue(pos[2]);

View file

@ -82,7 +82,7 @@ public:
void setBodySpin(const float* rotation) { Math::set3(rotation, _spin); } void setBodySpin(const float* rotation) { Math::set3(rotation, _spin); }
// Returns the center of gravity of the masses, in the body // Returns the center of gravity of the masses, in the body
// coordinate system. // coordinate system. valid only after recalc()
void getCG(float* cgOut) { Math::set3(_cg, cgOut); } void getCG(float* cgOut) { Math::set3(_cg, cgOut); }
// Returns the acceleration of the body's c.g. relative to the // Returns the acceleration of the body's c.g. relative to the

View file

@ -174,12 +174,15 @@ void yasim_drag(Airplane* a, const float aoa, const float alt, int cfg = CONFIG_
int usage() int usage()
{ {
fprintf(stderr, "Usage: yasim <ac.xml> [-g [-a alt] [-s kts] [-approach | -cruise] ]\n"); fprintf(stderr, "Usage: \n");
fprintf(stderr, " yasim <ac.xml> [-d [-a alt] [-approach | -cruise] ]\n"); fprintf(stderr, " yasim <aircraft.xml> [-g [-a meters] [-s kts] [-approach | -cruise] ]\n");
fprintf(stderr, " yasim <ac.xml> [-m]\n"); fprintf(stderr, " yasim <aircraft.xml> [-d [-a meters] [-approach | -cruise] ]\n");
fprintf(stderr, " -g print lift/drag table: aoa, lift, drag, lift/drag \n"); fprintf(stderr, " yasim <aircraft.xml> [-m]\n");
fprintf(stderr, " -d print drag over TAS: kts, drag\n"); fprintf(stderr, " -g print lift/drag table: aoa, lift, drag, lift/drag \n");
fprintf(stderr, " -m print mass distribution table: id, x, y, z, mass \n"); fprintf(stderr, " -d print drag over TAS: kts, drag\n");
fprintf(stderr, " -a set altitude in meters!\n");
fprintf(stderr, " -s set speed in knots\n");
fprintf(stderr, " -m print mass distribution table: id, x, y, z, mass \n");
return 1; return 1;
} }

View file

@ -34,6 +34,7 @@
#define PKGLIBDIR "@FG_DATA_DIR@" #define PKGLIBDIR "@FG_DATA_DIR@"
#define FGSRCDIR "@PROJECT_SOURCE_DIR@" #define FGSRCDIR "@PROJECT_SOURCE_DIR@"
#define FGBUILDDIR "@PROJECT_BINARY_DIR@"
#define WEB_BROWSER "@WEB_BROWSER@" #define WEB_BROWSER "@WEB_BROWSER@"
// Ensure FG_HAVE_xxx always have a value // Ensure FG_HAVE_xxx always have a value

View file

@ -184,3 +184,7 @@ if(ENABLE_METAR)
install(TARGETS metar RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) install(TARGETS metar RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif() endif()
if (ENABLE_TESTS)
flightgear_test(posinit test_posinit.cxx)
endif()

View file

@ -231,7 +231,7 @@ do_tile_cache_reload (const SGPropertyNode * arg)
master_freeze->setBoolValue(true); master_freeze->setBoolValue(true);
} }
globals->get_subsystem("tile-manager")->reinit(); globals->get_subsystem("scenery")->reinit();
if ( !freeze ) { if ( !freeze ) {
master_freeze->setBoolValue(false); master_freeze->setBoolValue(false);

View file

@ -95,7 +95,7 @@ using namespace flightgear;
#define NEW_DEFAULT_MODEL_HZ 120 #define NEW_DEFAULT_MODEL_HZ 120
static flightgear::Options* shared_instance = NULL; static flightgear::Options* shared_instance = nullptr;
static double static double
atof( const string& str ) atof( const string& str )
@ -1979,6 +1979,14 @@ Options* Options::sharedInstance()
return shared_instance; return shared_instance;
} }
void Options::reset()
{
if (shared_instance != nullptr) {
delete shared_instance;
shared_instance = nullptr;
}
}
Options::Options() : Options::Options() :
p(new OptionsPrivate()) p(new OptionsPrivate())
{ {
@ -2034,7 +2042,9 @@ void Options::init(int argc, char **argv, const SGPath& appDataPath)
} }
if (!p->shouldLoadDefaultConfig) { if (!p->shouldLoadDefaultConfig) {
#if !defined(FG_TESTLIB)
setupRoot(argc, argv); setupRoot(argc, argv);
#endif
return; return;
} }

View file

@ -67,6 +67,13 @@ private:
public: public:
static Options* sharedInstance(); static Options* sharedInstance();
/**
* Delete the entire options object. Use with a degree of care, no code
* should ever be caching the Options pointer but this has not actually been
* checked across the whole code :)
*/
static void reset();
~Options(); ~Options();
/** /**

View file

@ -46,7 +46,7 @@ using std::string;
namespace flightgear namespace flightgear
{ {
/// to avoid blocking when metar-fetch is enabled, but the network is /// to avoid blocking when metar-fetch is enabled, but the network is
/// unresponsive, we need a timeout value. This value is reset on initPosition, /// unresponsive, we need a timeout value. This value is reset on initPosition,
/// and tracked through each call to finalizePosition. /// and tracked through each call to finalizePosition.
@ -54,7 +54,7 @@ static SGTimeStamp global_finalizeTime;
static bool global_callbackRegistered = false; static bool global_callbackRegistered = false;
static void finalizePosition(); static void finalizePosition();
// Set current tower position lon/lat given an airport id // Set current tower position lon/lat given an airport id
static bool fgSetTowerPosFromAirportID( const string& id) { static bool fgSetTowerPosFromAirportID( const string& id) {
const FGAirport *a = fgFindAirportID( id); const FGAirport *a = fgFindAirportID( id);
@ -67,11 +67,11 @@ static bool fgSetTowerPosFromAirportID( const string& id) {
} else { } else {
return false; return false;
} }
} }
class FGTowerLocationListener : public SGPropertyChangeListener { class FGTowerLocationListener : public SGPropertyChangeListener {
void valueChanged(SGPropertyNode* node) { void valueChanged(SGPropertyNode* node) {
string id(node->getStringValue()); string id(node->getStringValue());
if (fgGetBool("/sim/tower/auto-position",true)) if (fgGetBool("/sim/tower/auto-position",true))
@ -104,12 +104,12 @@ class FGClosestTowerLocationListener : public SGPropertyChangeListener
}; };
void initTowerLocationListener() { void initTowerLocationListener() {
SGPropertyChangeListener* tll = new FGTowerLocationListener(); SGPropertyChangeListener* tll = new FGTowerLocationListener();
globals->addListenerToCleanup(tll); globals->addListenerToCleanup(tll);
fgGetNode("/sim/tower/airport-id", true) fgGetNode("/sim/tower/airport-id", true)
->addChangeListener( tll, true ); ->addChangeListener( tll, true );
FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener(); FGClosestTowerLocationListener* ntcl = new FGClosestTowerLocationListener();
globals->addListenerToCleanup(ntcl); globals->addListenerToCleanup(ntcl);
fgGetNode("/sim/airport/closest-airport-id", true) fgGetNode("/sim/airport/closest-airport-id", true)
@ -144,7 +144,7 @@ static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double
if (aTargetHeading == HUGE_VAL) { if (aTargetHeading == HUGE_VAL) {
aTargetHeading = aHeading; aTargetHeading = aHeading;
} }
if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) { if ( fabs( fgGetDouble("/sim/presets/offset-distance-nm") ) > SG_EPSILON ) {
double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm"); double offsetDistance = fgGetDouble("/sim/presets/offset-distance-nm");
offsetDistance *= SG_NM_TO_METER; offsetDistance *= SG_NM_TO_METER;
@ -153,13 +153,13 @@ static void fgApplyStartOffset(const SGGeod& aStartPos, double aHeading, double
offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg"); offsetAzimuth = fgGetDouble("/sim/presets/offset-azimuth-deg");
aHeading = aTargetHeading; aHeading = aTargetHeading;
} }
SGGeod offset; SGGeod offset;
double az2; // dummy double az2; // dummy
SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2); SGGeodesy::direct(startPos, offsetAzimuth + 180, offsetDistance, offset, az2);
startPos = offset; startPos = offset;
} }
setInitialPosition(startPos, aHeading); setInitialPosition(startPos, aHeading);
} }
@ -176,7 +176,7 @@ boost::tuple<SGGeod, double> runwayStartPos(FGRunwayRef runway)
FGGroundNetwork* groundNet = runway->airport()->groundNetwork(); FGGroundNetwork* groundNet = runway->airport()->groundNetwork();
// add a margin, try to keep the entire aeroplane comfortable off the // add a margin, try to keep the entire aeroplane comfortable off the
// runway. // runway.
double margin = startOffset + (runway->widthM() * 1.5); double margin = startOffset + (runway->widthM() * 1.5);
FGTaxiNodeRef taxiNode = groundNet ? groundNet->findNearestNodeOffRunway(pos, runway, margin) : 0; FGTaxiNodeRef taxiNode = groundNet ? groundNet->findNearestNodeOffRunway(pos, runway, margin) : 0;
if (taxiNode) { if (taxiNode) {
@ -196,12 +196,12 @@ boost::tuple<SGGeod, double> runwayStartPos(FGRunwayRef runway)
static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) { static bool setPosFromAirportIDandHdg( const string& id, double tgt_hdg ) {
if ( id.empty() ) if ( id.empty() )
return false; return false;
// set initial position from runway and heading // set initial position from runway and heading
SG_LOG( SG_GENERAL, SG_INFO, SG_LOG( SG_GENERAL, SG_INFO,
"Attempting to set starting position from airport code " "Attempting to set starting position from airport code "
<< id << " heading " << tgt_hdg ); << id << " heading " << tgt_hdg );
const FGAirport* apt = fgFindAirportID(id); const FGAirport* apt = fgFindAirportID(id);
if (!apt) return false; if (!apt) return false;
@ -231,7 +231,7 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
SGPath acData; SGPath acData;
if ( id.empty() ) if ( id.empty() )
return false; return false;
const FGAirport* apt = fgFindAirportID(id); const FGAirport* apt = fgFindAirportID(id);
if (!apt) { if (!apt) {
SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id ); SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport " << id );
@ -247,11 +247,11 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
setInitialPosition(apt->geod(), 0.0); setInitialPosition(apt->geod(), 0.0);
return true; return true;
} }
ParkingAssignment pka; ParkingAssignment pka;
double radius = fgGetDouble("/sim/dimensions/radius-m"); double radius = fgGetDouble("/sim/dimensions/radius-m");
if ((parkpos == "AVAILABLE") && (radius > 0)) { if ((parkpos == "AVAILABLE") && (radius > 0)) {
try { try {
acData = globals->get_fg_home(); acData = globals->get_fg_home();
acData.append("aircraft-data"); acData.append("aircraft-data");
@ -265,7 +265,7 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
} catch (const sg_exception &) { } catch (const sg_exception &) {
SG_LOG(SG_GENERAL, SG_INFO, SG_LOG(SG_GENERAL, SG_INFO,
"Could not load aircraft aircrat type and operator information from: " << acData << ". Using defaults"); "Could not load aircraft aircrat type and operator information from: " << acData << ". Using defaults");
// cout << path.str() << endl; // cout << path.str() << endl;
} }
if (fltType.empty() || fltType == "NONE") { if (fltType.empty() || fltType == "NONE") {
@ -278,8 +278,8 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
"Aircraft operator information not found in: " << acData << ". Using default value"); "Aircraft operator information not found in: " << acData << ". Using default value");
acOperator = fgGetString("/sim/aircraft-operator" ); acOperator = fgGetString("/sim/aircraft-operator" );
} }
pka = dcs->getAvailableParking(radius, fltType, acType, acOperator); pka = dcs->getAvailableParking(radius, fltType, acType, acOperator);
if (pka.isValid()) { if (pka.isValid()) {
// why is the following line necessary? // why is the following line necessary?
@ -291,7 +291,7 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
return false; return false;
} }
} else { } else {
pka = dcs->getParkingByName(parkpos); pka = dcs->getParkingByName(parkpos);
if (!pka.isValid()) { if (!pka.isValid()) {
SG_LOG( SG_GENERAL, SG_ALERT, SG_LOG( SG_GENERAL, SG_ALERT,
@ -303,9 +303,9 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
fgGetString("/sim/presets/parkpos"); fgGetString("/sim/presets/parkpos");
fgSetString("/sim/presets/parkpos", pka.parking()->getName()); fgSetString("/sim/presets/parkpos", pka.parking()->getName());
// The problem is, this line doesn't work because the ParkingAssignment's refcounting mechanism: // The problem is, this line doesn't work because the ParkingAssignment's refcounting mechanism:
// The parking will be released after this function returns. // The parking will be released after this function returns.
// As a temporary measure, I'll try to reserve the parking via the atc_manager, which should work, because it uses the same // As a temporary measure, I'll try to reserve the parking via the atc_manager, which should work, because it uses the same
// mechanism as the AI traffic code. // mechanism as the AI traffic code.
dcs->setParkingAvailable(pka.parking(), false); dcs->setParkingAvailable(pka.parking(), false);
fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading()); fgApplyStartOffset(pka.parking()->geod(), pka.parking()->getHeading());
return true; return true;
@ -316,12 +316,12 @@ static bool fgSetPosFromAirportIDandParkpos( const string& id, const string& par
static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) { static bool fgSetPosFromAirportIDandRwy( const string& id, const string& rwy, bool rwy_req ) {
if ( id.empty() ) if ( id.empty() )
return false; return false;
// set initial position from airport and runway number // set initial position from airport and runway number
SG_LOG( SG_GENERAL, SG_INFO, SG_LOG( SG_GENERAL, SG_INFO,
"Attempting to set starting position for " "Attempting to set starting position for "
<< id << ":" << rwy ); << id << ":" << rwy );
const FGAirport* apt = fgFindAirportID(id); const FGAirport* apt = fgFindAirportID(id);
if (!apt) { if (!apt) {
SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id); SG_LOG( SG_GENERAL, SG_ALERT, "Failed to find airport:" << id);
@ -361,7 +361,7 @@ static void fgSetDistOrAltFromGlideSlope() {
* SG_DEGREES_TO_RADIANS ; * SG_DEGREES_TO_RADIANS ;
double od = fgGetDouble("/sim/presets/offset-distance-nm"); double od = fgGetDouble("/sim/presets/offset-distance-nm");
double alt = fgGetDouble("/sim/presets/altitude-ft"); double alt = fgGetDouble("/sim/presets/altitude-ft");
double apt_elev = 0.0; double apt_elev = 0.0;
if ( ! apt_id.empty() ) { if ( ! apt_id.empty() ) {
apt_elev = fgGetAirportElev( apt_id ); apt_elev = fgGetAirportElev( apt_id );
@ -371,7 +371,7 @@ static void fgSetDistOrAltFromGlideSlope() {
} else { } else {
apt_elev = 0.0; apt_elev = 0.0;
} }
if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) { if( fabs(gs) > 0.01 && fabs(od) > 0.1 && alt < -9990 ) {
// set altitude from glideslope and offset-distance // set altitude from glideslope and offset-distance
od *= SG_NM_TO_METER * SG_METER_TO_FEET; od *= SG_NM_TO_METER * SG_METER_TO_FEET;
@ -448,20 +448,22 @@ static bool fgSetPosFromNAV( const string& id,
// Set current_options lon/lat given an aircraft carrier id // Set current_options lon/lat given an aircraft carrier id
static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) { static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
// set initial position from runway and heading // set initial position from runway and heading
SGGeod geodPos; SGGeod geodPos;
double heading; double heading;
SGVec3d uvw; SGVec3d uvw;
#ifndef FG_TESTLIB
if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) { if (FGAIManager::getStartPosition(carrier, posid, geodPos, heading, uvw)) {
double lon = geodPos.getLongitudeDeg(); double lon = geodPos.getLongitudeDeg();
double lat = geodPos.getLatitudeDeg(); double lat = geodPos.getLatitudeDeg();
double alt = geodPos.getElevationFt(); double alt = geodPos.getElevationFt();
SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for " SG_LOG( SG_GENERAL, SG_INFO, "Attempting to set starting position for "
<< carrier << " at lat = " << lat << ", lon = " << lon << carrier << " at lat = " << lat << ", lon = " << lon
<< ", alt = " << alt << ", heading = " << heading); << ", alt = " << alt << ", heading = " << heading);
fgSetDouble("/sim/presets/longitude-deg", lon); fgSetDouble("/sim/presets/longitude-deg", lon);
fgSetDouble("/sim/presets/latitude-deg", lat); fgSetDouble("/sim/presets/latitude-deg", lat);
fgSetDouble("/sim/presets/altitude-ft", alt); fgSetDouble("/sim/presets/altitude-ft", alt);
@ -470,7 +472,7 @@ static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
fgSetDouble("/position/latitude-deg", lat); fgSetDouble("/position/latitude-deg", lat);
fgSetDouble("/position/altitude-ft", alt); fgSetDouble("/position/altitude-ft", alt);
fgSetDouble("/orientation/heading-deg", heading); fgSetDouble("/orientation/heading-deg", heading);
fgSetString("/sim/presets/speed-set", "UVW"); fgSetString("/sim/presets/speed-set", "UVW");
fgSetDouble("/velocities/uBody-fps", uvw(0)); fgSetDouble("/velocities/uBody-fps", uvw(0));
fgSetDouble("/velocities/vBody-fps", uvw(1)); fgSetDouble("/velocities/vBody-fps", uvw(1));
@ -478,11 +480,13 @@ static bool fgSetPosFromCarrier( const string& carrier, const string& posid ) {
fgSetDouble("/sim/presets/uBody-fps", uvw(0)); fgSetDouble("/sim/presets/uBody-fps", uvw(0));
fgSetDouble("/sim/presets/vBody-fps", uvw(1)); fgSetDouble("/sim/presets/vBody-fps", uvw(1));
fgSetDouble("/sim/presets/wBody-fps", uvw(2)); fgSetDouble("/sim/presets/wBody-fps", uvw(2));
fgSetBool("/sim/presets/onground", true); fgSetBool("/sim/presets/onground", true);
return true; return true;
} else { } else
#endif
{
SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = " SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate aircraft carrier = "
<< carrier ); << carrier );
return false; return false;
@ -504,7 +508,7 @@ static bool fgSetPosFromFix( const string& id, PositionedID guid )
SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id ); SG_LOG( SG_GENERAL, SG_ALERT, "Failed to locate fix = " << id );
return false; return false;
} }
fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg")); fgApplyStartOffset(fix->geod(), fgGetDouble("/sim/presets/heading-deg"));
return true; return true;
} }
@ -517,22 +521,22 @@ bool initPosition()
globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1); globals->get_event_mgr()->addTask("finalizePosition", &finalizePosition, 0.1);
global_callbackRegistered = true; global_callbackRegistered = true;
} }
double gs = fgGetDouble("/sim/presets/glideslope-deg") double gs = fgGetDouble("/sim/presets/glideslope-deg")
* SG_DEGREES_TO_RADIANS ; * SG_DEGREES_TO_RADIANS ;
double od = fgGetDouble("/sim/presets/offset-distance-nm"); double od = fgGetDouble("/sim/presets/offset-distance-nm");
double alt = fgGetDouble("/sim/presets/altitude-ft"); double alt = fgGetDouble("/sim/presets/altitude-ft");
bool set_pos = false; bool set_pos = false;
// If glideslope is specified, then calculate offset-distance or // If glideslope is specified, then calculate offset-distance or
// altitude relative to glide slope if either of those was not // altitude relative to glide slope if either of those was not
// specified. // specified.
if ( fabs( gs ) > 0.01 ) { if ( fabs( gs ) > 0.01 ) {
fgSetDistOrAltFromGlideSlope(); fgSetDistOrAltFromGlideSlope();
} }
// If we have an explicit, in-range lon/lat, don't change it, just use it. // If we have an explicit, in-range lon/lat, don't change it, just use it.
// If not, check for an airport-id and use that. // If not, check for an airport-id and use that.
// If not, default to the middle of the KSFO field. // If not, default to the middle of the KSFO field.
@ -546,7 +550,7 @@ bool initPosition()
{ {
set_pos = true; set_pos = true;
} }
string apt = fgGetString("/sim/presets/airport-id"); string apt = fgGetString("/sim/presets/airport-id");
const bool apt_req = fgGetBool("/sim/presets/airport-requested"); const bool apt_req = fgGetBool("/sim/presets/airport-requested");
string rwy_no = fgGetString("/sim/presets/runway"); string rwy_no = fgGetString("/sim/presets/runway");
@ -564,21 +568,21 @@ bool initPosition()
SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true); SGPropertyNode *hdg_preset = fgGetNode("/sim/presets/heading-deg", true);
double hdg = hdg_preset->getDoubleValue(); double hdg = hdg_preset->getDoubleValue();
// save some start parameters, so that we can later say what the // save some start parameters, so that we can later say what the
// user really requested. TODO generalize that and move it to options.cxx // user really requested. TODO generalize that and move it to options.cxx
static bool start_options_saved = false; static bool start_options_saved = false;
if (!start_options_saved) { if (!start_options_saved) {
start_options_saved = true; start_options_saved = true;
SGPropertyNode *opt = fgGetNode("/sim/startup/options", true); SGPropertyNode *opt = fgGetNode("/sim/startup/options", true);
opt->setDoubleValue("latitude-deg", lat_deg); opt->setDoubleValue("latitude-deg", lat_deg);
opt->setDoubleValue("longitude-deg", lon_deg); opt->setDoubleValue("longitude-deg", lon_deg);
opt->setDoubleValue("heading-deg", hdg); opt->setDoubleValue("heading-deg", hdg);
opt->setStringValue("airport", apt.c_str()); opt->setStringValue("airport", apt.c_str());
opt->setStringValue("runway", rwy_no.c_str()); opt->setStringValue("runway", rwy_no.c_str());
} }
if (hdg > 9990.0) if (hdg > 9990.0)
hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270); hdg = fgGetDouble("/environment/config/boundary/entry/wind-from-heading-deg", 270);
@ -602,7 +606,7 @@ bool initPosition()
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos && !apt.empty() && !rwy_no.empty() ) { if ( !set_pos && !apt.empty() && !rwy_no.empty() ) {
// An airport + runway is requested // An airport + runway is requested
if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) { if ( fgSetPosFromAirportIDandRwy( apt, rwy_no, rwy_req ) ) {
@ -613,7 +617,7 @@ bool initPosition()
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos && !apt.empty() ) { if ( !set_pos && !apt.empty() ) {
// An airport is requested (find runway closest to hdg) // An airport is requested (find runway closest to hdg)
if ( setPosFromAirportIDandHdg( apt, hdg ) ) { if ( setPosFromAirportIDandHdg( apt, hdg ) ) {
@ -624,38 +628,38 @@ bool initPosition()
set_pos = true; set_pos = true;
} }
} }
if (hdg_preset->getDoubleValue() > 9990.0) if (hdg_preset->getDoubleValue() > 9990.0)
hdg_preset->setDoubleValue(hdg); hdg_preset->setDoubleValue(hdg);
if ( !set_pos && !vor.empty() ) { if ( !set_pos && !vor.empty() ) {
// a VOR is requested // a VOR is requested
if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR, navaidId ) ) { if ( fgSetPosFromNAV( vor, vor_freq, FGPositioned::VOR, navaidId ) ) {
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos && !ndb.empty() ) { if ( !set_pos && !ndb.empty() ) {
// an NDB is requested // an NDB is requested
if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB, navaidId ) ) { if ( fgSetPosFromNAV( ndb, ndb_freq, FGPositioned::NDB, navaidId ) ) {
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos && !carrier.empty() ) { if ( !set_pos && !carrier.empty() ) {
// an aircraft carrier is requested // an aircraft carrier is requested
if ( fgSetPosFromCarrier( carrier, parkpos ) ) { if ( fgSetPosFromCarrier( carrier, parkpos ) ) {
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos && !fix.empty() ) { if ( !set_pos && !fix.empty() ) {
// a Fix is requested // a Fix is requested
if ( fgSetPosFromFix( fix, navaidId ) ) { if ( fgSetPosFromFix( fix, navaidId ) ) {
set_pos = true; set_pos = true;
} }
} }
if ( !set_pos ) { if ( !set_pos ) {
// No lon/lat specified, no airport specified, use the default airport // No lon/lat specified, no airport specified, use the default airport
// TODO: don't hardcode this. Really. // TODO: don't hardcode this. Really.
@ -665,37 +669,37 @@ bool initPosition()
fgSetDouble("/sim/presets/longitude-deg", airportGeod.getLongitudeDeg()); fgSetDouble("/sim/presets/longitude-deg", airportGeod.getLongitudeDeg());
fgSetDouble("/sim/presets/latitude-deg", airportGeod.getLatitudeDeg()); fgSetDouble("/sim/presets/latitude-deg", airportGeod.getLatitudeDeg());
} else { } else {
// So, the default airport is unknown? We are in serious trouble. // So, the default airport is unknown? We are in serious trouble.
// Let's hope KSFO still exists somehow // Let's hope KSFO still exists somehow
fgSetDouble("/sim/presets/longitude-deg", -122.374843); fgSetDouble("/sim/presets/longitude-deg", -122.374843);
fgSetDouble("/sim/presets/latitude-deg", 37.619002); fgSetDouble("/sim/presets/latitude-deg", 37.619002);
SG_LOG(SG_GENERAL, SG_ALERT, "Sorry, the default airport seems to be unknown."); SG_LOG(SG_GENERAL, SG_ALERT, "Sorry, the default airport seems to be unknown.");
} }
} }
fgSetDouble( "/position/longitude-deg", fgSetDouble( "/position/longitude-deg",
fgGetDouble("/sim/presets/longitude-deg") ); fgGetDouble("/sim/presets/longitude-deg") );
fgSetDouble( "/position/latitude-deg", fgSetDouble( "/position/latitude-deg",
fgGetDouble("/sim/presets/latitude-deg") ); fgGetDouble("/sim/presets/latitude-deg") );
fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue()); fgSetDouble( "/orientation/heading-deg", hdg_preset->getDoubleValue());
// determine if this should be an on-ground or in-air start // determine if this should be an on-ground or in-air start
if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) { if ((fabs(gs) > 0.01 || fabs(od) > 0.1 || alt > 0.1) && carrier.empty()) {
fgSetBool("/sim/presets/onground", false); fgSetBool("/sim/presets/onground", false);
} else { } else {
fgSetBool("/sim/presets/onground", true); fgSetBool("/sim/presets/onground", true);
} }
fgSetBool("/sim/position-finalized", false); fgSetBool("/sim/position-finalized", false);
// Initialize the longitude, latitude and altitude to the initial position // Initialize the longitude, latitude and altitude to the initial position
fgSetDouble("/position/altitude-ft", fgGetDouble("/sim/presets/altitude-ft")); fgSetDouble("/position/altitude-ft", fgGetDouble("/sim/presets/altitude-ft"));
fgSetDouble("/position/longitude-deg", fgGetDouble("/sim/presets/longitude-deg")); fgSetDouble("/position/longitude-deg", fgGetDouble("/sim/presets/longitude-deg"));
fgSetDouble("/position/latitude-deg", fgGetDouble("/sim/presets/latitude-deg")); fgSetDouble("/position/latitude-deg", fgGetDouble("/sim/presets/latitude-deg"));
return true; return true;
} }
bool finalizeMetar() bool finalizeMetar()
{ {
double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 ); double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
@ -711,14 +715,14 @@ bool finalizeMetar()
!rwy_req && !rwy_req &&
onground && onground &&
parkpos.empty(); parkpos.empty();
if (needMetar) { if (needMetar) {
// timeout so we don't spin forever if the network is down // timeout so we don't spin forever if the network is down
if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 6000)) { if (global_finalizeTime.elapsedMSec() > fgGetInt("/sim/startup/metar-fetch-timeout-msec", 6000)) {
SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch"); SG_LOG(SG_GENERAL, SG_WARN, "finalizePosition: timed out waiting for METAR fetch");
return true; return true;
} }
if (fgGetBool( "/environment/metar/failure" )) { if (fgGetBool( "/environment/metar/failure" )) {
SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failed, not waiting"); SG_LOG(SG_ENVIRONMENT, SG_INFO, "metar download failed, not waiting");
return true; return true;
@ -727,32 +731,32 @@ bool finalizeMetar()
if (!fgGetBool( "/environment/metar/valid" )) { if (!fgGetBool( "/environment/metar/valid" )) {
return false; return false;
} }
SG_LOG(SG_ENVIRONMENT, SG_INFO, SG_LOG(SG_ENVIRONMENT, SG_INFO,
"Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" ); "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
setPosFromAirportIDandHdg( apt, hdg ); setPosFromAirportIDandHdg( apt, hdg );
// fall through to return true // fall through to return true
} // of need-metar case } // of need-metar case
return true; return true;
} }
void finalizePosition() void finalizePosition()
{ {
// first call to finalize after an initPosition call // first call to finalize after an initPosition call
if (global_finalizeTime.get_usec() == 0) { if (global_finalizeTime.get_usec() == 0) {
global_finalizeTime = SGTimeStamp::now(); global_finalizeTime = SGTimeStamp::now();
} }
bool done = true; bool done = true;
/* Scenarios require Nasal, so FGAIManager loads the scenarios, /* Scenarios require Nasal, so FGAIManager loads the scenarios,
* including its models such as a/c carriers, in its 'postinit', * including its models such as a/c carriers, in its 'postinit',
* which is the very last thing we do. * which is the very last thing we do.
* flightgear::initPosition is called very early in main.cxx/fgIdleFunction, * flightgear::initPosition is called very early in main.cxx/fgIdleFunction,
* one of the first things we do, long before scenarios/carriers are * one of the first things we do, long before scenarios/carriers are
* loaded. => When requested "initial preset position" relates to a * loaded. => When requested "initial preset position" relates to a
* carrier, recalculate the 'initial' position here * carrier, recalculate the 'initial' position here
*/ */
std::string carrier = fgGetString("/sim/presets/carrier"); std::string carrier = fgGetString("/sim/presets/carrier");
std::string parkpos = fgGetString("/sim/presets/parkpos"); std::string parkpos = fgGetString("/sim/presets/parkpos");
@ -772,12 +776,12 @@ void finalizePosition()
} else { } else {
done = finalizeMetar(); done = finalizeMetar();
} }
fgSetBool("/sim/position-finalized", done); fgSetBool("/sim/position-finalized", done);
if (done) { if (done) {
globals->get_event_mgr()->removeTask("finalizePosition"); globals->get_event_mgr()->removeTask("finalizePosition");
global_callbackRegistered = false; global_callbackRegistered = false;
} }
} }
} // of namespace flightgear } // of namespace flightgear

119
src/Main/test_posinit.cxx Normal file
View file

@ -0,0 +1,119 @@
#include "config.h"
#include "unitTestHelpers.hxx"
#include <simgear/misc/test_macros.hxx>
#include <simgear/props/props_io.hxx>
#include "Main/positioninit.hxx"
#include "Main/options.hxx"
#include "Main/globals.hxx"
#include "Main/fg_props.hxx"
#include "Airports/airport.hxx"
using namespace flightgear;
void testDefaultStartup()
{
fgtest::initTestGlobals("posinit");
Options::reset();
fgLoadProps("defaults.xml", globals->get_props());
{
Options* opts = Options::sharedInstance();
opts->setShouldLoadDefaultConfig(false);
const char* args[] = {"dummypath"};
opts->init(1, (char**) args, SGPath());
opts->processOptions();
}
initPosition();
// verify we got the location specified in location-preset.xml
// this unfortunately means manually parsing that file, oh well
{
SGPath presets = fgtest::fgdataPath() / "location-presets.xml";
SG_VERIFY(presets.exists());
SGPropertyNode_ptr props(new SGPropertyNode);
readProperties(presets, props);
std::string icao = props->getStringValue("/sim/presets/airport-id");
SG_CHECK_EQUAL(globals->get_props()->getStringValue("/sim/airport/closest-airport-id"), icao);
SGGeod pos = globals->get_aircraft_position();
FGAirportRef defaultAirport = FGAirport::getByIdent(icao);
double dist = SGGeodesy::distanceM(pos, defaultAirport->geod());
SG_CHECK_LT(dist, 10000);
}
fgtest::shutdownTestGlobals();
}
void testAirportOnlyStartup()
{
fgtest::initTestGlobals("posinit");
Options::reset();
fgLoadProps("defaults.xml", globals->get_props());
{
Options* opts = Options::sharedInstance();
opts->setShouldLoadDefaultConfig(false);
const char* args[] = {"dummypath", "--airport=EDDF"};
opts->init(2, (char**) args, SGPath());
opts->processOptions();
}
SG_VERIFY(fgGetBool("/sim/presets/airport-requested"));
initPosition();
SG_CHECK_EQUAL(globals->get_props()->getStringValue("/sim/airport/closest-airport-id"), std::string("EDDF"));
double dist = SGGeodesy::distanceM(globals->get_aircraft_position(),
FGAirport::getByIdent("EDDF")->geod());
SG_CHECK_LT(dist, 10000);
fgtest::shutdownTestGlobals();
}
void testAirportAndMetarStartup()
{
fgtest::initTestGlobals("posinit");
Options::reset();
fgLoadProps("defaults.xml", globals->get_props());
{
Options* opts = Options::sharedInstance();
opts->setShouldLoadDefaultConfig(false);
const char* args[] = {"dummypath", "--airport=LOWI", "--metar=XXXX 271320Z 08007KT 030V130 CAVOK 17/02 Q1020 NOSIG"};
opts->init(3, (char**) args, SGPath());
opts->processOptions();
}
initPosition();
SG_CHECK_EQUAL(globals->get_props()->getStringValue("/sim/airport/closest-airport-id"), std::string("LOWI"));
double dist = SGGeodesy::distanceM(globals->get_aircraft_position(),
FGAirport::getByIdent("LOWI")->geod());
SG_CHECK_LT(dist, 10000);
///sim/atc/runway
SG_CHECK_EQUAL(globals->get_props()->getStringValue("sim/atc/runway"), std::string("26"));
fgtest::shutdownTestGlobals();
}
int main(int argc, char* argv[])
{
testDefaultStartup();
testAirportOnlyStartup();
testAirportAndMetarStartup();
return EXIT_SUCCESS;
}

View file

@ -6,6 +6,7 @@ set(sources
Main/globals.cxx Main/globals.cxx
Main/locale.cxx Main/locale.cxx
Main/util.cxx Main/util.cxx
Main/positioninit.cxx
Aircraft/controls.cxx Aircraft/controls.cxx
Aircraft/FlightHistory.cxx Aircraft/FlightHistory.cxx
Aircraft/flightrecorder.cxx Aircraft/flightrecorder.cxx
@ -90,16 +91,21 @@ set_target_properties (fgtestlib
COMPILE_DEFINITIONS "FG_TESTLIB" COMPILE_DEFINITIONS "FG_TESTLIB"
) )
target_link_libraries(fgtestlib SimGearCore ${PLATFORM_LIBS}) if(FG_HAVE_GPERFTOOLS)
target_include_directories(fgtestlib PRIVATE ${GooglePerfTools_INCLUDE_DIR})
target_link_libraries(fgtestlib ${GooglePerfTools_LIBRARIES})
endif()
target_link_libraries(fgtestlib SimGearCore ${PLATFORM_LIBS} ${SQLITE3_LIBRARY})
add_executable(fgtest fgTestDriver.cxx) add_executable(fgtest fgTestDriver.cxx)
target_link_libraries(fgtest fgtestlib) target_link_libraries(fgtest fgtestlib)
# repeat this section for each unit-test executable macro(flightgear_test name sources)
add_executable(testnavs test_navaids2.cxx) add_executable(${name} ${sources})
target_link_libraries(testnavs fgtestlib fgsqlite3) target_include_directories(${name} PRIVATE ${CMAKE_SOURCE_DIR}/tests)
add_test(testnavs ${EXECUTABLE_OUTPUT_PATH}/testnavs) target_link_libraries(${name} fgtestlib)
add_test(${name} ${EXECUTABLE_OUTPUT_PATH}/${name})
endmacro()
add_executable(testflightplan test_flightplan.cxx) flightgear_test(test_navs test_navaids2.cxx)
target_link_libraries(testflightplan fgtestlib fgsqlite3) flightgear_test(test_flightplan test_flightplan.cxx)
add_test(testflightplan ${EXECUTABLE_OUTPUT_PATH}/testflightplan)

View file

@ -4,6 +4,8 @@
#include "unitTestHelpers.hxx" #include "unitTestHelpers.hxx"
#include <Main/globals.hxx> #include <Main/globals.hxx>
#include <Main/options.hxx>
#include <Navaids/NavDataCache.hxx> #include <Navaids/NavDataCache.hxx>
#include <Time/TimeManager.hxx> #include <Time/TimeManager.hxx>
@ -13,6 +15,8 @@
#include <iostream> #include <iostream>
static SGPath tests_fgdata;
namespace fgtest namespace fgtest
{ {
@ -21,6 +25,12 @@ namespace fgtest
return (path / "defaults.xml").exists(); return (path / "defaults.xml").exists();
} }
SGPath fgdataPath()
{
return tests_fgdata;
}
void initTestGlobals(const std::string& testName) void initTestGlobals(const std::string& testName)
{ {
sglog().setLogLevels( SG_ALL, SG_WARN ); sglog().setLogLevels( SG_ALL, SG_WARN );
@ -58,15 +68,18 @@ namespace fgtest
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
tests_fgdata = globals->get_fg_root();
// current dir // current dir
SGPath homePath = simgear::Dir::current().path() / "test_home"; SGPath homePath = SGPath::fromUtf8(FGBUILDDIR) / "test_home";
if (!homePath.exists()) { if (!homePath.exists()) {
(homePath / "dummyFile").create_dir(0755); (homePath / "dummyFile").create_dir(0755);
} }
globals->set_fg_home(homePath); globals->set_fg_home(homePath);
fgSetDefaults();
flightgear::NavDataCache* cache = flightgear::NavDataCache::createInstance(); flightgear::NavDataCache* cache = flightgear::NavDataCache::createInstance();
if (cache->isRebuildRequired()) { if (cache->isRebuildRequired()) {
std::cerr << "Navcache rebuild for testing" << std::flush; std::cerr << "Navcache rebuild for testing" << std::flush;

View file

@ -10,6 +10,8 @@ namespace fgtest
void initTestGlobals(const std::string& testName); void initTestGlobals(const std::string& testName);
void shutdownTestGlobals(); void shutdownTestGlobals();
SGPath fgdataPath();
} }
#endif // of FG_TEST_HELPERS_HXX #endif // of FG_TEST_HELPERS_HXX