From c1336db66481d25514ac5441355d0a3b5b173b1a Mon Sep 17 00:00:00 2001
From: Torsten Dreyer <Torsten@t3r.de>
Date: Sat, 4 Dec 2010 12:05:35 +0100
Subject: [PATCH 1/5] METAR: symbolic cloudnames

- use symbolic names for scattered, broken, overcast, etc. cloud
coverages.
---
 src/Environment/fgmetar.cxx | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/Environment/fgmetar.cxx b/src/Environment/fgmetar.cxx
index b2b331fbf..c9d046ca9 100644
--- a/src/Environment/fgmetar.cxx
+++ b/src/Environment/fgmetar.cxx
@@ -61,7 +61,7 @@ FGMetar::FGMetar(const string& icao, const string& proxy, const string& port, co
 		vector<SGMetarCloud> cv = _clouds;;
 		if (!cv.size()) {
 			SGMetarCloud cl;
-			cl.set(5500 * SG_FEET_TO_METER, 2);
+			cl.set(5500 * SG_FEET_TO_METER, SGMetarCloud::COVERAGE_SCATTERED);
 			_clouds.push_back(cl);
 		}
 	}
@@ -109,9 +109,9 @@ FGMetar::FGMetar(const string& icao, const string& proxy, const string& port, co
 	vector<SGMetarCloud>::iterator cloud, cv_end = cv.end();
 
 	for (i = 0, cloud = cv.begin(); cloud != cv_end; ++cloud, i++) {
-		int cov = cloud->getCoverage();
-		if (cov == -1)
-			cov = 0;
+		SGMetarCloud::Coverage cov = cloud->getCoverage();
+		if (cov == SGMetarCloud::COVERAGE_NIL)
+			cov = SGMetarCloud::COVERAGE_CLEAR;
 
 		double alt = cloud->getAltitude_ft();
 		if (alt == SGMetarNaN)

From ebbd5bfd0542b2b3bb731f2964f5500a5f2bd12c Mon Sep 17 00:00:00 2001
From: ThorstenB <brehmt@gmail.com>
Date: Sun, 5 Dec 2010 20:35:21 +0100
Subject: [PATCH 2/5] fix bug #177: crash caused by route manager/gps/navradio
 Uninitialized variables were sources for NaN values. Once NaNs are passed to
 Nasal (through (tied) properties), these cause a crash. Nasal cannot handle
 NaNs - it interprets these as pointer values...

---
 src/Instrumentation/navradio.cxx              | 20 +++++++++++--
 src/Instrumentation/navradio.hxx              |  2 --
 src/Instrumentation/rnav_waypt_controller.cxx | 30 ++++++++++++-------
 src/Instrumentation/rnav_waypt_controller.hxx |  1 +
 4 files changed, 39 insertions(+), 14 deletions(-)

diff --git a/src/Instrumentation/navradio.cxx b/src/Instrumentation/navradio.cxx
index 2aac4b26d..143951694 100644
--- a/src/Instrumentation/navradio.cxx
+++ b/src/Instrumentation/navradio.cxx
@@ -92,12 +92,19 @@ SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, const char* aN
 
 // Constructor
 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
+    term_tbl(NULL),
+    low_tbl(NULL),
+    high_tbl(NULL),
     lon_node(fgGetNode("/position/longitude-deg", true)),
     lat_node(fgGetNode("/position/latitude-deg", true)),
     alt_node(fgGetNode("/position/altitude-ft", true)),
+    _operable(false),
     play_count(0),
     last_time(0),
     target_radial(0.0),
+    effective_range(0.0),
+    target_gs(0.0),
+    twist(0.0),
     horiz_vel(0.0),
     last_x(0.0),
     last_loc_dist(0.0),
@@ -107,6 +114,16 @@ FGNavRadio::FGNavRadio(SGPropertyNode *node) :
     _name(node->getStringValue("name", "nav")),
     _num(node->getIntValue("number", 0)),
     _time_before_search_sec(-1.0),
+    _gsCart(SGVec3d::zeros()),
+    _gsAxis(SGVec3d::zeros()),
+    _gsVertical(SGVec3d::zeros()),
+    _dmeInRange(false),
+    _toFlag(false),
+    _fromFlag(false),
+    _cdiDeflection(0.0),
+    _cdiCrossTrackErrorM(0.0),
+    _gsNeedleDeflection(0.0),
+    _gsNeedleDeflectionNorm(0.0),
     _sgr(NULL)
 {
     SGPath path( globals->get_fg_root() );
@@ -120,8 +137,7 @@ FGNavRadio::FGNavRadio(SGPropertyNode *node) :
     term_tbl = new SGInterpTable( term.str() );
     low_tbl = new SGInterpTable( low.str() );
     high_tbl = new SGInterpTable( high.str() );
-    
-    
+
     string branch("/instrumentation/" + _name);
     _radio_node = fgGetNode(branch.c_str(), _num, true);
 }
diff --git a/src/Instrumentation/navradio.hxx b/src/Instrumentation/navradio.hxx
index f272f6700..a8451a649 100644
--- a/src/Instrumentation/navradio.hxx
+++ b/src/Instrumentation/navradio.hxx
@@ -137,8 +137,6 @@ class FGNavRadio : public SGSubsystem, public SGPropertyChangeListener
     string dme_fx_name;
 
     double target_radial;
-    SGTimeStamp prev_time;
-    SGTimeStamp curr_time;
     double effective_range;
     double target_gs;
     double twist;
diff --git a/src/Instrumentation/rnav_waypt_controller.cxx b/src/Instrumentation/rnav_waypt_controller.cxx
index 977452e18..09ac2b812 100644
--- a/src/Instrumentation/rnav_waypt_controller.cxx
+++ b/src/Instrumentation/rnav_waypt_controller.cxx
@@ -69,8 +69,8 @@ bool geocRadialIntersection(const SGGeoc& a, double r1, const SGGeoc& b, double
   double crs12 = SGGeodesy::courseRad(a, b),
     crs21 = SGGeodesy::courseRad(b, a);
     
-  double degCrs12 = crs12 * SG_RADIANS_TO_DEGREES;
-  double degCrs21 = crs21 * SG_RADIANS_TO_DEGREES;
+  //double degCrs12 = crs12 * SG_RADIANS_TO_DEGREES;
+  //double degCrs21 = crs21 * SG_RADIANS_TO_DEGREES;
     
  /* 
   if (sin(diffLon) < 0.0) {
@@ -157,7 +157,9 @@ class BasicWayptCtl : public WayptController
 {
 public:
   BasicWayptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
-    WayptController(aRNAV, aWpt)
+    WayptController(aRNAV, aWpt),
+    _distanceM(0.0),
+    _courseDev(0.0)
   {
     if (aWpt->flag(WPT_DYNAMIC)) {
       throw sg_exception("BasicWayptCtrl doesn't work with dynamic waypoints");
@@ -226,7 +228,10 @@ class RunwayCtl : public WayptController
 {
 public:
   RunwayCtl(RNAV* aRNAV, const WayptRef& aWpt) :
-    WayptController(aRNAV, aWpt)
+    WayptController(aRNAV, aWpt),
+    _runway(NULL),
+    _distanceM(0.0),
+    _courseDev(0.0)
   {
   }
   
@@ -365,8 +370,8 @@ class InterceptCtl : public WayptController
 {
 public:
   InterceptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
-    WayptController(aRNAV, aWpt)
-    
+    WayptController(aRNAV, aWpt),
+    _trueRadial(0.0)
   {
     if (_waypt->type() != "radialIntercept") {
       throw sg_exception("invalid waypoint type", "InterceptCtl ctor");
@@ -412,8 +417,9 @@ class DMEInterceptCtl : public WayptController
 {
 public:
   DMEInterceptCtl(RNAV* aRNAV, const WayptRef& aWpt) :
-    WayptController(aRNAV, aWpt)
-    
+    WayptController(aRNAV, aWpt),
+    _dme(NULL),
+    _distanceNm(0.0)
   {
     if (_waypt->type() != "dmeIntercept") {
       throw sg_exception("invalid waypoint type", "DMEInterceptCtl ctor");
@@ -546,7 +552,9 @@ private:
 
 DirectToController::DirectToController(RNAV* aRNAV, const WayptRef& aWpt, const SGGeod& aOrigin) :
   WayptController(aRNAV, aWpt),
-  _origin(aOrigin)
+  _origin(aOrigin),
+  _distanceM(0.0),
+  _courseDev(0.0)
 {
 }
 
@@ -600,7 +608,9 @@ SGGeod DirectToController::position() const
 ///////////////////////////////////////////////////////////////////////////////
 
 OBSController::OBSController(RNAV* aRNAV, const WayptRef& aWpt) :
-  WayptController(aRNAV, aWpt)
+  WayptController(aRNAV, aWpt),
+  _distanceM(0.0),
+  _courseDev(0.0)
 {
 }
 
diff --git a/src/Instrumentation/rnav_waypt_controller.hxx b/src/Instrumentation/rnav_waypt_controller.hxx
index 4d99c8af7..b5c4b19e1 100644
--- a/src/Instrumentation/rnav_waypt_controller.hxx
+++ b/src/Instrumentation/rnav_waypt_controller.hxx
@@ -129,6 +129,7 @@ public:
 protected:
   WayptController(RNAV* aRNAV, const WayptRef& aWpt) :
     _waypt(aWpt),
+    _targetTrack(0),
     _rnav(aRNAV),
     _isDone(false)
   { }

From 138449f4bd677884d1968461fa7a0c0d47194c4a Mon Sep 17 00:00:00 2001
From: ThorstenB <brehmt@gmail.com>
Date: Sun, 5 Dec 2010 21:26:51 +0100
Subject: [PATCH 3/5] Avoid exceptions in route manager module. Avoid segfaults
 in gps when route manager doesn't throw exceptions. Minor fix when removing
 waypoints by negative index.

---
 src/Autopilot/route_mgr.cxx | 9 +++++----
 src/Instrumentation/gps.cxx | 8 ++++++--
 2 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/src/Autopilot/route_mgr.cxx b/src/Autopilot/route_mgr.cxx
index c0f8f2631..1530497e8 100644
--- a/src/Autopilot/route_mgr.cxx
+++ b/src/Autopilot/route_mgr.cxx
@@ -345,7 +345,7 @@ flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
 {
   int index = aIndex;
   if (aIndex < 0) { // negative indices count the the end
-    index = _route.size() -  index;
+    index = _route.size() + index;
   }
   
   if ((index < 0) || (index >= numWaypts())) {
@@ -1027,7 +1027,7 @@ void FGRouteMgr::jumpToIndex(int index)
 
 void FGRouteMgr::currentWaypointChanged()
 {
-  Waypt* cur = (_currentIndex<numWaypts()) ? currentWaypt() : NULL;
+  Waypt* cur = currentWaypt();
   Waypt* next = nextWaypt();
 
   wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
@@ -1050,6 +1050,8 @@ int FGRouteMgr::findWayptIndex(const SGGeod& aPos) const
 
 Waypt* FGRouteMgr::currentWaypt() const
 {
+  if ((_currentIndex < 0) || (_currentIndex >= numWaypts()))
+      return NULL;
   return wayptAtIndex(_currentIndex);
 }
 
@@ -1064,7 +1066,7 @@ Waypt* FGRouteMgr::previousWaypt() const
 
 Waypt* FGRouteMgr::nextWaypt() const
 {
-  if ((_currentIndex + 1) >= numWaypts()) {
+  if ((_currentIndex < 0) || ((_currentIndex + 1) >= numWaypts())) {
     return NULL;
   }
   
@@ -1353,4 +1355,3 @@ void FGRouteMgr::setDestinationICAO(const char* aIdent)
   
   arrivalChanged();
 }
-    
diff --git a/src/Instrumentation/gps.cxx b/src/Instrumentation/gps.cxx
index 1add1b97f..7e4b2b398 100644
--- a/src/Instrumentation/gps.cxx
+++ b/src/Instrumentation/gps.cxx
@@ -697,6 +697,8 @@ void GPS::routeManagerSequenced()
   int index = _routeMgr->currentIndex(),
     count = _routeMgr->numWaypts();
   if ((index < 0) || (index >= count)) {
+    _currentWaypt=NULL;
+    _prevWaypt=NULL;
     SG_LOG(SG_INSTR, SG_ALERT, "GPS: malformed route, index=" << index);
     return;
   }
@@ -971,6 +973,8 @@ void GPS::driveAutopilot()
 
 void GPS::wp1Changed()
 {
+  if (!_currentWaypt)
+    return;
   if (_mode == "leg") {
     _wayptController.reset(WayptController::createForWaypt(this, _currentWaypt));
   } else if (_mode == "obs") {
@@ -1082,7 +1086,7 @@ double GPS::getCDIDeflection() const
 
 const char* GPS::getWP0Ident() const
 {
-  if (!_dataValid || (_mode != "leg")) {
+  if (!_dataValid || (_mode != "leg") || (!_prevWaypt)) {
     return "";
   }
   
@@ -1096,7 +1100,7 @@ const char* GPS::getWP0Name() const
 
 const char* GPS::getWP1Ident() const
 {
-  if (!_dataValid) {
+  if ((!_dataValid)||(!_currentWaypt)) {
     return "";
   }
   

From 29161c21146ee344729de79c283d33991086b2ca Mon Sep 17 00:00:00 2001
From: Torsten Dreyer <Torsten@t3r.de>
Date: Sun, 5 Dec 2010 21:34:28 +0100
Subject: [PATCH 4/5] First shot at implementing fog from METAR

---
 src/Environment/metarproperties.cxx | 78 +++++++++++++++++++++++++++--
 src/Environment/metarproperties.hxx |  2 +
 2 files changed, 75 insertions(+), 5 deletions(-)

diff --git a/src/Environment/metarproperties.cxx b/src/Environment/metarproperties.cxx
index f1e25f419..23d16b59c 100644
--- a/src/Environment/metarproperties.cxx
+++ b/src/Environment/metarproperties.cxx
@@ -100,6 +100,7 @@ MetarProperties::MetarProperties( SGPropertyNode_ptr rootNode ) :
   _tiedProperties.Tie("hail-norm", &_hail );
   _tiedProperties.Tie("snow-norm", &_snow);
   _tiedProperties.Tie("snow-cover", &_snow_cover );
+  _tiedProperties.Tie("decoded", this, &MetarProperties::get_decoded );
 }
 
 MetarProperties::~MetarProperties()
@@ -123,6 +124,13 @@ void MetarProperties::set_metar( const char * metar )
         return;
     }
 
+    _decoded.clear();
+    const vector<string> weather = m->getWeather();
+    for( vector<string>::const_iterator it = weather.begin(); it != weather.end(); it++ ) {
+        if( false == _decoded.empty() ) _decoded.append(", ");
+        _decoded.append(*it);
+    }
+
     _min_visibility = m->getMinVisibility().getVisibility_m();
     _max_visibility = m->getMaxVisibility().getVisibility_m();
 
@@ -189,6 +197,38 @@ void MetarProperties::set_metar( const char * metar )
         _sea_level_pressure = P_layer(0, elevation_m, fieldPressure, _temperature + atmodel::freezing, atmodel::ISA::lam0) / atmodel::inHg;
     }
 
+    bool isBC = false;
+    bool isBR = false;
+    bool isFG = false;
+    bool isMI = false;
+    bool isHZ = false;
+
+    {
+        for( unsigned i = 0; i < 3; i++ ) {
+            SGPropertyNode_ptr n = _rootNode->getChild("weather", i, true );
+            vector<struct SGMetar::Weather> weather = m->getWeather2();
+            struct SGMetar::Weather * w = i < weather.size() ? &weather[i] : NULL;
+            n->getNode("intensity",true)->setIntValue( w != NULL ? w->intensity : 0 );
+            n->getNode("vincinity",true)->setBoolValue( w != NULL ? w->vincinity : false );
+            for( unsigned j = 0; j < 3; j++ ) { 
+
+                const string & phenomenon = w != NULL && j < w->phenomena.size() ? w->phenomena[j].c_str() : "";
+                n->getChild( "phenomenon", j, true )->setStringValue( phenomenon );
+
+                const string & description = w != NULL && j < w->descriptions.size() ? w->descriptions[j].c_str() : "";
+                n->getChild( "description", j, true )->setStringValue( description );
+
+                // need to know later, 
+                // if its fog(FG) (might be shallow(MI) or patches(BC)) or haze (HZ) or mist(BR)
+                if( phenomenon == "FG" ) isFG = true;
+                if( phenomenon == "HZ" ) isHZ = true;
+                if( description == "MI" ) isMI = true;
+                if( description == "BC" ) isBC = true;
+                if( description == "BR" ) isBR = true;
+            }
+        }
+    }
+
     vector<SGMetarCloud> cv = m->getClouds();
     vector<SGMetarCloud>::const_iterator cloud, cloud_end = cv.end();
 
@@ -196,17 +236,45 @@ void MetarProperties::set_metar( const char * metar )
         static const char * LAYER = "layer";
         SGPropertyNode_ptr cloudsNode = _rootNode->getNode("clouds", true );
         const vector<SGMetarCloud> & metarClouds = m->getClouds();
-        for( unsigned i = 0; i < 5; i++ ) {
-            SGPropertyNode_ptr layerNode = cloudsNode->getChild(LAYER, i, true );
-            int coverage = i < metarClouds.size() ? metarClouds[i].getCoverage() : 0;
-            double elevation = i >= metarClouds.size() || coverage == 0 ? -9999.0 : metarClouds[i].getAltitude_ft() + _station_elevation;
+        unsigned layerOffset = 0; // Oh, this is ugly!
+        bool setGroundCloudLayer = _rootNode->getBoolValue("set-ground-cloud-layer", false );
+
+        if( setGroundCloudLayer && isFG ) {
+            // make sure fog actually starts at ground and set it's bottom at a constant
+            // value below the station's elevation
+            const double LAYER_BOTTOM_BELOW_STATION_ELEVATION=200;
+
+            // fog - create a cloud layer #0 starting at the ground
+            // fog is "overcast" by default of "broken" for patches of fog
+            SGPropertyNode_ptr layerNode = cloudsNode->getChild(LAYER, 0, true );
+            SGMetarCloud::Coverage coverage = isBC ? SGMetarCloud::COVERAGE_SCATTERED : SGMetarCloud::COVERAGE_BROKEN;
+            layerNode->setDoubleValue( "coverage-type", SGCloudLayer::getCoverageType(coverage_string[coverage]) );
+            layerNode->setStringValue( "coverage", coverage_string[coverage] );
+            layerNode->setDoubleValue( "elevation-ft", _station_elevation - LAYER_BOTTOM_BELOW_STATION_ELEVATION );
+            layerNode->setDoubleValue( "thickness-ft", isMI ? 
+               30 + LAYER_BOTTOM_BELOW_STATION_ELEVATION : // shallow fog, 10m/30ft
+               500 + LAYER_BOTTOM_BELOW_STATION_ELEVATION ); // fog, 150m/500ft
+            layerNode->setDoubleValue( "visibility-m", _min_visibility );
+            _min_visibility = _max_visibility = 20000.0; // assume good visibility above the fog
+            layerOffset = 1;  // shudder
+        } else if( setGroundCloudLayer && isHZ ) {
+        }
+
+        for( unsigned i = 0; i < 5-layerOffset; i++ ) {
+            SGPropertyNode_ptr layerNode = cloudsNode->getChild(LAYER, i+layerOffset, true );
+            SGMetarCloud::Coverage coverage = i < metarClouds.size() ? metarClouds[i].getCoverage() : SGMetarCloud::COVERAGE_CLEAR;
+            double elevation = 
+                i >= metarClouds.size() || coverage == SGMetarCloud::COVERAGE_CLEAR ? 
+                -9999.0 : 
+                metarClouds[i].getAltitude_ft() + _station_elevation;
+
             layerNode->setStringValue( "coverage", coverage_string[coverage] );
             layerNode->setDoubleValue( "coverage-type", SGCloudLayer::getCoverageType(coverage_string[coverage]) );
             layerNode->setDoubleValue( "elevation-ft", elevation );
             layerNode->setDoubleValue( "thickness-ft", thickness_value[coverage]);
             layerNode->setDoubleValue( "span-m", 40000 );
+            layerNode->setDoubleValue( "visibility-m", 50.0 );
         }
-
     }
 
     _rain = m->getRain();
diff --git a/src/Environment/metarproperties.hxx b/src/Environment/metarproperties.hxx
index 060cb69f5..221219f98 100644
--- a/src/Environment/metarproperties.hxx
+++ b/src/Environment/metarproperties.hxx
@@ -41,6 +41,7 @@ private:
     const char * get_metar() const { return _metar.c_str(); }
     void set_metar( const char * metar );
     const char * get_station_id() const { return _station_id.c_str(); }
+    const char * get_decoded() const { return _decoded.c_str(); }
 
     SGPropertyNode_ptr _rootNode;
     SGPropertyNode_ptr _metarValidNode;
@@ -69,6 +70,7 @@ private:
     double _hail;
     double _snow;
     bool _snow_cover;
+    std::string _decoded;
 
     TiedPropertyList _tiedProperties;
 };

From ca8cd763af41e974b6e6ef1ec7e9137366390c07 Mon Sep 17 00:00:00 2001
From: ThorstenB <brehmt@gmail.com>
Date: Sun, 5 Dec 2010 23:01:57 +0100
Subject: [PATCH 5/5] Rid some uninitialized vectors (NaNs).

---
 src/Main/viewmgr.cxx | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/Main/viewmgr.cxx b/src/Main/viewmgr.cxx
index 5a978be63..955529189 100644
--- a/src/Main/viewmgr.cxx
+++ b/src/Main/viewmgr.cxx
@@ -42,9 +42,12 @@ FGViewMgr::FGViewMgr( void ) :
   inited(false),
   view_number(fgGetNode("/sim/current-view/view-number", true)),
   config_list(fgGetNode("/sim", true)->getChildren("view")),
-  current(0)
+  abs_viewer_position(SGVec3d::zeros()),
+  current(0),
+  current_view_orientation(SGQuatd::zeros()),
+  current_view_or_offset(SGQuatd::zeros()),
+  smgr(globals->get_soundmgr())
 {
-    smgr = globals->get_soundmgr();
 }
 
 // Destructor