Compare commits

..
Author SHA1 Message Date
James Turner 506b9130a8 Adjust where we set the deployment SDK on Mac.
Contrary to the CMake docs, settings this value before project()
seems not to work, whereas setting it after works exactly as
desired.
2015-02-18 10:06:03 +00:00
James Turner 5d1b70a7f2 Force SDK version / C++ library on Mac. 2015-02-13 14:47:45 +00:00
Peter Sadrozinski eff3df57d9 memory reduced tile loading.
- do not save the TileGeometryBin and matcach in the randomObjectCallback
- recreate matcache, and get TileGeometry from scenegraph
- split obj.cxx into three distinct files - loadBTG, load surface geometry, and load tile details
- includes fix for sceneries that have missing materials
2015-02-11 09:04:53 +01:00
Rebecca N. Palmer 2931f3380f Fix UpdateOnceCallback crash (bug 1554/1556/1568)
(cherry picked from commit dc1816bb08)
2015-01-19 15:51:36 +00:00
67 changed files with 411 additions and 1233 deletions
+9 -29
View File
@@ -1,28 +1,13 @@
cmake_minimum_required (VERSION 2.6.4) cmake_minimum_required (VERSION 2.6.4)
if(COMMAND cmake_policy)
if(POLICY CMP0054)
cmake_policy(SET CMP0054 NEW)
endif()
if(POLICY CMP0042)
cmake_policy(SET CMP0042 NEW)
endif()
endif()
include (CheckFunctionExists) include (CheckFunctionExists)
include (CheckIncludeFile) include (CheckIncludeFile)
include (CheckLibraryExists)
include (CheckCXXSourceCompiles) include (CheckCXXSourceCompiles)
include (CheckCXXCompilerFlag) include (CheckCXXCompilerFlag)
project(SimGear)
# using 10.7 because boost requires libc++ and 10.6 doesn't include it # using 10.7 because boost requires libc++ and 10.6 doesn't include it
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.7) set(CMAKE_OSX_DEPLOYMENT_TARGET 10.7)
set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk)
# only relevant for building shared libs but let's set it regardless
set(CMAKE_OSX_RPATH 1)
project(SimGear)
# read 'version' file into a variable (stripping any newlines or spaces) # read 'version' file into a variable (stripping any newlines or spaces)
file(READ version versionFile) file(READ version versionFile)
@@ -181,16 +166,11 @@ if(APPLE)
find_library(COCOA_LIBRARY Cocoa) find_library(COCOA_LIBRARY Cocoa)
endif() endif()
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux" OR
${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD")
find_package(Threads REQUIRED)
endif()
# Somehow this only works if included before searching for Boost... # Somehow this only works if included before searching for Boost...
include(BoostTestTargets) include(BoostTestTargets)
find_package(Boost REQUIRED) find_package(Boost REQUIRED)
set (BOOST_CXX_FLAGS "-DBOOST_BIMAP_DISABLE_SERIALIZATION") set (BOOST_CXX_FLAGS "-DBOOST_MULTI_INDEX_DISABLE_SERIALIZATION -DBOOST_BIMAP_DISABLE_SERIALIZATION")
if(SIMGEAR_HEADLESS) if(SIMGEAR_HEADLESS)
message(STATUS "SimGear mode: HEADLESS") message(STATUS "SimGear mode: HEADLESS")
@@ -208,6 +188,7 @@ else()
endif(SIMGEAR_HEADLESS) endif(SIMGEAR_HEADLESS)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
find_package(Threads REQUIRED)
if (SYSTEM_EXPAT) if (SYSTEM_EXPAT)
message(STATUS "Requested to use system Expat library, forcing SIMGEAR_SHARED to true") message(STATUS "Requested to use system Expat library, forcing SIMGEAR_SHARED to true")
@@ -319,12 +300,11 @@ if(CMAKE_COMPILER_IS_GNUCXX)
endif(CMAKE_COMPILER_IS_GNUCXX) endif(CMAKE_COMPILER_IS_GNUCXX)
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang") if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
# Boost redeclares class members set(WARNING_FLAGS_CXX "-Wall -Wno-overloaded-virtual")
set(WARNING_FLAGS_CXX "-Wall -Wno-overloaded-virtual -Wno-redeclared-class-member") set(WARNING_FLAGS_C "-Wall")
set(WARNING_FLAGS_C "-Wall") set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11")
set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++11") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++")
endif() endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang") if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
+65 -103
View File
@@ -44,7 +44,6 @@ namespace canvas
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
const std::string GEO = "-geo"; const std::string GEO = "-geo";
const std::string HDG = "hdg";
const std::string Map::TYPE_NAME = "map"; const std::string Map::TYPE_NAME = "map";
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
@@ -113,50 +112,87 @@ namespace canvas
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
void Map::childAdded(SGPropertyNode* parent, SGPropertyNode* child) void Map::childAdded(SGPropertyNode* parent, SGPropertyNode* child)
{ {
if( boost::ends_with(child->getNameString(), GEO) ) if( !boost::ends_with(child->getNameString(), GEO) )
_geo_nodes[child].reset(new GeoNodePair());
else if( parent != _node && child->getNameString() == HDG )
_hdg_nodes.insert(child);
else
return Element::childAdded(parent, child); return Element::childAdded(parent, child);
_geo_nodes[child].reset(new GeoNodePair());
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
void Map::childRemoved(SGPropertyNode* parent, SGPropertyNode* child) void Map::childRemoved(SGPropertyNode* parent, SGPropertyNode* child)
{ {
if( boost::ends_with(child->getNameString(), GEO) ) if( !boost::ends_with(child->getNameString(), GEO) )
// TODO remove from other node
_geo_nodes.erase(child);
else if( parent != _node && child->getName() == HDG )
{
_hdg_nodes.erase(child);
// Remove rotation matrix (tf[0]) and return to element always being
// oriented upwards (or any orientation inside other matrices).
child->getParent()->removeChild("tf", 0);
}
else
return Element::childRemoved(parent, child); return Element::childRemoved(parent, child);
// TODO remove from other node
_geo_nodes.erase(child);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
void Map::valueChanged(SGPropertyNode* child) void Map::valueChanged(SGPropertyNode * child)
{ {
if( child->getParent() != _node ) const std::string& name = child->getNameString();
if( !boost::ends_with(name, GEO) )
return Group::valueChanged(child);
GeoNodes::iterator it_geo_node = _geo_nodes.find(child);
if( it_geo_node == _geo_nodes.end() )
LOG_GEO_RET("geo node not found!")
GeoNodePair* geo_node = it_geo_node->second.get();
geo_node->setDirty();
if( geo_node->getStatus() & GeoNodePair::INCOMPLETE )
{ {
const std::string& name = child->getNameString(); // Detect lat, lon tuples...
GeoCoord coord = parseGeoCoord(child->getStringValue());
int index_other = -1;
if( boost::ends_with(name, GEO) ) switch( coord.type )
return geoNodeChanged(child); {
else if( name == HDG ) case GeoCoord::LATITUDE:
return hdgNodeChanged(child); index_other = child->getIndex() + 1;
geo_node->setNodeLat(child);
break;
case GeoCoord::LONGITUDE:
index_other = child->getIndex() - 1;
geo_node->setNodeLon(child);
break;
default:
LOG_GEO_RET("Invalid geo coord")
}
SGPropertyNode *other = child->getParent()->getChild(name, index_other);
if( !other )
return;
GeoCoord coord_other = parseGeoCoord(other->getStringValue());
if( coord_other.type == GeoCoord::INVALID
|| coord_other.type == coord.type )
return;
GeoNodes::iterator it_geo_node_other = _geo_nodes.find(other);
if( it_geo_node_other == _geo_nodes.end() )
LOG_GEO_RET("other geo node not found!")
GeoNodePair* geo_node_other = it_geo_node_other->second.get();
// Let use both nodes use the same GeoNodePair instance
if( geo_node_other != geo_node )
it_geo_node_other->second = it_geo_node->second;
if( coord_other.type == GeoCoord::LATITUDE )
geo_node->setNodeLat(other);
else
geo_node->setNodeLon(other);
// Set name for resulting screen coordinate nodes
geo_node->setTargetName( name.substr(0, name.length() - GEO.length()) );
} }
return Group::valueChanged(child);
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
void Map::childChanged(SGPropertyNode* child) void Map::childChanged(SGPropertyNode * child)
{ {
if( child->getParent() != _node ) if( child->getParent() != _node )
return Group::childChanged(child); return Group::childChanged(child);
@@ -165,14 +201,8 @@ namespace canvas
|| child->getNameString() == "ref-lon" ) || child->getNameString() == "ref-lon" )
_projection->setWorldPosition( _node->getDoubleValue("ref-lat"), _projection->setWorldPosition( _node->getDoubleValue("ref-lat"),
_node->getDoubleValue("ref-lon") ); _node->getDoubleValue("ref-lon") );
else if( child->getNameString() == HDG ) else if( child->getNameString() == "hdg" )
{
_projection->setOrientation(child->getFloatValue()); _projection->setOrientation(child->getFloatValue());
for( NodeSet::iterator it = _hdg_nodes.begin();
it != _hdg_nodes.end();
++it )
hdgNodeChanged(*it);
}
else if( child->getNameString() == "range" ) else if( child->getNameString() == "range" )
_projection->setRange(child->getDoubleValue()); _projection->setRange(child->getDoubleValue());
else if( child->getNameString() == "screen-range" ) else if( child->getNameString() == "screen-range" )
@@ -183,74 +213,6 @@ namespace canvas
_projection_dirty = true; _projection_dirty = true;
} }
//----------------------------------------------------------------------------
void Map::geoNodeChanged(SGPropertyNode* child)
{
GeoNodes::iterator it_geo_node = _geo_nodes.find(child);
if( it_geo_node == _geo_nodes.end() )
LOG_GEO_RET("GeoNode not found!")
GeoNodePair* geo_node = it_geo_node->second.get();
geo_node->setDirty();
if( !(geo_node->getStatus() & GeoNodePair::INCOMPLETE) )
return;
// Detect lat, lon tuples...
GeoCoord coord = parseGeoCoord(child->getStringValue());
int index_other = -1;
switch( coord.type )
{
case GeoCoord::LATITUDE:
index_other = child->getIndex() + 1;
geo_node->setNodeLat(child);
break;
case GeoCoord::LONGITUDE:
index_other = child->getIndex() - 1;
geo_node->setNodeLon(child);
break;
default:
LOG_GEO_RET("Invalid geo coord")
}
const std::string& name = child->getNameString();
SGPropertyNode *other = child->getParent()->getChild(name, index_other);
if( !other )
return;
GeoCoord coord_other = parseGeoCoord(other->getStringValue());
if( coord_other.type == GeoCoord::INVALID
|| coord_other.type == coord.type )
return;
GeoNodes::iterator it_geo_node_other = _geo_nodes.find(other);
if( it_geo_node_other == _geo_nodes.end() )
LOG_GEO_RET("other geo node not found!")
GeoNodePair* geo_node_other = it_geo_node_other->second.get();
// Let use both nodes use the same GeoNodePair instance
if( geo_node_other != geo_node )
it_geo_node_other->second = it_geo_node->second;
if( coord_other.type == GeoCoord::LATITUDE )
geo_node->setNodeLat(other);
else
geo_node->setNodeLon(other);
// Set name for resulting screen coordinate nodes
geo_node->setTargetName( name.substr(0, name.length() - GEO.length()) );
}
//----------------------------------------------------------------------------
void Map::hdgNodeChanged(SGPropertyNode* child)
{
child->getParent()->setFloatValue(
"tf[0]/rot",
SGMiscf::deg2rad(child->getFloatValue() - _projection->orientation())
);
}
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
Map::GeoCoord Map::parseGeoCoord(const std::string& val) const Map::GeoCoord Map::parseGeoCoord(const std::string& val) const
{ {
+1 -9
View File
@@ -24,7 +24,6 @@
#include <boost/shared_ptr.hpp> #include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp> #include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
namespace simgear namespace simgear
{ {
@@ -60,18 +59,14 @@ namespace canvas
typedef boost::unordered_map< SGPropertyNode*, typedef boost::unordered_map< SGPropertyNode*,
boost::shared_ptr<GeoNodePair> boost::shared_ptr<GeoNodePair>
> GeoNodes; > GeoNodes;
typedef boost::unordered_set<SGPropertyNode*> NodeSet;
GeoNodes _geo_nodes; GeoNodes _geo_nodes;
NodeSet _hdg_nodes;
boost::shared_ptr<HorizontalProjection> _projection; boost::shared_ptr<HorizontalProjection> _projection;
bool _projection_dirty; bool _projection_dirty;
struct GeoCoord struct GeoCoord
{ {
GeoCoord(): GeoCoord():
type(INVALID), type(INVALID)
value(0)
{} {}
enum enum
{ {
@@ -82,9 +77,6 @@ namespace canvas
double value; double value;
}; };
void geoNodeChanged(SGPropertyNode * child);
void hdgNodeChanged(SGPropertyNode * child);
GeoCoord parseGeoCoord(const std::string& val) const; GeoCoord parseGeoCoord(const std::string& val) const;
}; };
+2 -17
View File
@@ -159,12 +159,8 @@ namespace canvas
if( empty() ) if( empty() )
return pos; return pos;
#if OSG_VERSION_LESS_THAN(3,3,5)
GlyphQuads::Coords2 const& coords = _quads->_coords; GlyphQuads::Coords2 const& coords = _quads->_coords;
#else
GlyphQuads::Coords2 refCoords = _quads->_coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
size_t global_i = _begin + i; size_t global_i = _begin + i;
if( global_i == _begin ) if( global_i == _begin )
@@ -198,12 +194,7 @@ namespace canvas
return cursorPos(0); return cursorPos(0);
GlyphQuads::Glyphs const& glyphs = _quads->_glyphs; GlyphQuads::Glyphs const& glyphs = _quads->_glyphs;
#if OSG_VERSION_LESS_THAN(3,3,5)
GlyphQuads::Coords2 const& coords = _quads->_coords; GlyphQuads::Coords2 const& coords = _quads->_coords;
#else
GlyphQuads::Coords2 refCoords = _quads->_coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
float const HIT_FRACTION = 0.6; float const HIT_FRACTION = 0.6;
float const character_width = _text->getCharacterHeight() float const character_width = _text->getCharacterHeight()
@@ -636,13 +627,7 @@ namespace canvas
const GlyphQuads& quads = _textureGlyphQuadMap.begin()->second; const GlyphQuads& quads = _textureGlyphQuadMap.begin()->second;
const GlyphQuads::Glyphs& glyphs = quads._glyphs; const GlyphQuads::Glyphs& glyphs = quads._glyphs;
#if OSG_VERSION_LESS_THAN(3,3,5) const GlyphQuads::Coords2& coords = quads._coords;
GlyphQuads::Coords2 const& coords = quads._coords;
#else
GlyphQuads::Coords2 refCoords = quads._coords;
GlyphQuads::Coords2::element_type &coords = *refCoords.get();
#endif
const GlyphQuads::LineNumbers& line_numbers = quads._lineNumbers; const GlyphQuads::LineNumbers& line_numbers = quads._lineNumbers;
float wr = _characterHeight / getCharacterAspectRatio(); float wr = _characterHeight / getCharacterAspectRatio();
+11 -28
View File
@@ -34,10 +34,7 @@ namespace canvas
public: public:
struct ScreenPosition struct ScreenPosition
{ {
ScreenPosition(): ScreenPosition() {}
x(0),
y(0)
{}
ScreenPosition(double x, double y): ScreenPosition(double x, double y):
x(x), x(x),
@@ -70,11 +67,8 @@ namespace canvas
public: public:
HorizontalProjection(): HorizontalProjection():
_ref_lat(0), _cos_rot(1),
_ref_lon(0), _sin_rot(0),
_angle(0),
_cos_angle(1),
_sin_angle(0),
_range(5) _range(5)
{ {
setScreenRange(200); setScreenRange(200);
@@ -94,19 +88,9 @@ namespace canvas
*/ */
void setOrientation(float hdg) void setOrientation(float hdg)
{ {
_angle = hdg;
hdg = SGMiscf::deg2rad(hdg); hdg = SGMiscf::deg2rad(hdg);
_sin_angle = sin(hdg); _sin_rot = sin(hdg);
_cos_angle = cos(hdg); _cos_rot = cos(hdg);
}
/**
* Get orientation/heading of the projection (in degree)
*/
float orientation() const
{
return _angle;
} }
void setRange(double range) void setRange(double range)
@@ -130,8 +114,8 @@ namespace canvas
pos.y *= scale; pos.y *= scale;
return ScreenPosition return ScreenPosition
( (
_cos_angle * pos.x - _sin_angle * pos.y, _cos_rot * pos.x - _sin_rot * pos.y,
-_sin_angle * pos.x - _cos_angle * pos.y -_sin_rot * pos.x - _cos_rot * pos.y
); );
} }
@@ -145,11 +129,10 @@ namespace canvas
*/ */
virtual ScreenPosition project(double lat, double lon) const = 0; virtual ScreenPosition project(double lat, double lon) const = 0;
double _ref_lat, ///<! Reference latitude (radian) double _ref_lat,
_ref_lon, ///<! Reference latitude (radian) _ref_lon,
_angle, ///<! Map rotation angle (degree) _cos_rot,
_cos_angle, _sin_rot,
_sin_angle,
_range; _range;
}; };
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "jupiter.hxx" #include "jupiter.hxx"
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "mars.hxx" #include "mars.hxx"
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "mercury.hxx" #include "mercury.hxx"
+1 -1
View File
@@ -25,7 +25,7 @@
#ifdef __BORLANDC__ #ifdef __BORLANDC__
# define exception c_exception # define exception c_exception
#endif #endif
#include <cmath> #include <math.h>
#include "neptune.hxx" #include "neptune.hxx"
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "saturn.hxx" #include "saturn.hxx"
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "uranus.hxx" #include "uranus.hxx"
+1 -1
View File
@@ -22,7 +22,7 @@
* $Id$ * $Id$
**************************************************************************/ **************************************************************************/
#include <cmath> #include <math.h>
#include "venus.hxx" #include "venus.hxx"
+5 -11
View File
@@ -239,6 +239,7 @@ void SVNDirectory::deleteChildByName(const std::string& nm)
{ {
DAVResource* child = dav->childWithName(nm); DAVResource* child = dav->childWithName(nm);
if (!child) { if (!child) {
// std::cerr << "ZZZ: deleteChildByName: unknown:" << nm << std::endl;
return; return;
} }
@@ -246,24 +247,17 @@ void SVNDirectory::deleteChildByName(const std::string& nm)
if (child->isCollection()) { if (child->isCollection()) {
Dir d(path); Dir d(path);
bool ok = d.remove(true); d.remove(true);
if (!ok) {
SG_LOG(SG_NETWORK, SG_ALERT, "SVNDirectory::deleteChildByName: failed to remove dir:"
<< nm << " at path:\n\t" << path);
}
DirectoryList::iterator it = findChildDir(nm); DirectoryList::iterator it = findChildDir(nm);
if (it != _children.end()) { if (it != _children.end()) {
SVNDirectory* c = *it; SVNDirectory* c = *it;
// std::cout << "YYY: deleting SVNDirectory for:" << nm << std::endl;
delete c; delete c;
_children.erase(it); _children.erase(it);
} }
} else { } else {
bool ok = path.remove(); path.remove();
if (!ok) {
SG_LOG(SG_NETWORK, SG_ALERT, "SVNDirectory::deleteChildByName: failed to remove path:" << nm
<< " at path:\n\t" << path);
}
} }
dav->removeChild(child); dav->removeChild(child);
-5
View File
@@ -251,11 +251,6 @@ NetChannelPoller::removeChannel(NetChannel* channel)
assert(channel->poller == this); assert(channel->poller == this);
channel->poller = NULL; channel->poller = NULL;
// portability: MSVC throws assertion failure when empty
if (channels.empty()) {
return;
}
ChannelList::iterator it = channels.begin(); ChannelList::iterator it = channels.begin();
for (; it != channels.end(); ++it) { for (; it != channels.end(); ++it) {
if (*it == channel) { if (*it == channel) {
-1
View File
@@ -27,7 +27,6 @@
#include <cstring> #include <cstring>
#include <cstdlib> #include <cstdlib>
#include <algorithm>
namespace simgear { namespace simgear {
-1
View File
@@ -32,7 +32,6 @@
#include <cstring> #include <cstring>
#include <cstdlib> // for atoi #include <cstdlib> // for atoi
#include <algorithm>
using std::string; using std::string;
+4 -6
View File
@@ -379,8 +379,6 @@ class TestServer : public NetChannel
public: public:
TestServer() TestServer()
{ {
Socket::initSockets();
open(); open();
bind(NULL, 2000); // localhost, any port bind(NULL, 2000); // localhost, any port
listen(5); listen(5);
@@ -416,14 +414,14 @@ TestServer testServer;
void waitForComplete(HTTP::Client* cl, TestRequest* tr) void waitForComplete(HTTP::Client* cl, TestRequest* tr)
{ {
SGTimeStamp start(SGTimeStamp::now()); SGTimeStamp start(SGTimeStamp::now());
while (start.elapsedMSec() < 10000) { while (start.elapsedMSec() < 1000) {
cl->update(); cl->update();
testServer.poll(); testServer.poll();
if (tr->complete) { if (tr->complete) {
return; return;
} }
SGTimeStamp::sleepForMSec(15); SGTimeStamp::sleepForMSec(1);
} }
cerr << "timed out" << endl; cerr << "timed out" << endl;
@@ -432,14 +430,14 @@ void waitForComplete(HTTP::Client* cl, TestRequest* tr)
void waitForFailed(HTTP::Client* cl, TestRequest* tr) void waitForFailed(HTTP::Client* cl, TestRequest* tr)
{ {
SGTimeStamp start(SGTimeStamp::now()); SGTimeStamp start(SGTimeStamp::now());
while (start.elapsedMSec() < 10000) { while (start.elapsedMSec() < 1000) {
cl->update(); cl->update();
testServer.poll(); testServer.poll();
if (tr->failed) { if (tr->failed) {
return; return;
} }
SGTimeStamp::sleepForMSec(15); SGTimeStamp::sleepForMSec(1);
} }
cerr << "timed out waiting for failure" << endl; cerr << "timed out waiting for failure" << endl;
+1 -1
View File
@@ -79,7 +79,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <cmath> #include <math.h>
#include <simgear/constants.h> #include <simgear/constants.h>
#include <simgear/sg_inlines.h> #include <simgear/sg_inlines.h>
+1 -1
View File
@@ -26,7 +26,7 @@
#endif #endif
#include <cmath> #include <math.h>
#include <simgear/magvar/magvar.hxx> #include <simgear/magvar/magvar.hxx>
#include <simgear/math/SGMath.hxx> #include <simgear/math/SGMath.hxx>
+3 -3
View File
@@ -1,8 +1,8 @@
/* 2/14/00 fixed help message- dip angle (down positive), variation (E positive) */ /* 2/14/00 fixed help message- dip angle (down positive), variation (E positive) */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <cmath> #include <math.h>
#include <simgear/constants.h> #include <simgear/constants.h>
+1 -5
View File
@@ -1,7 +1,7 @@
include (SimGearComponent) include (SimGearComponent)
set(HEADERS set(HEADERS
CSSBorder.hxx CSSBorder.hxx
ListDiff.hxx ListDiff.hxx
ResourceManager.hxx ResourceManager.hxx
@@ -37,10 +37,6 @@ set(SOURCES
gzcontainerfile.cxx gzcontainerfile.cxx
) )
if (WINDOWS)
list(APPEND HEADERS sgversionhelpers.hxx)
endif()
if (APPLE) if (APPLE)
list(APPEND SOURCES CocoaHelpers.mm) list(APPEND SOURCES CocoaHelpers.mm)
endif() endif()
+1 -5
View File
@@ -141,12 +141,8 @@ int main(int argc, char* argv[])
// add // add
pc.add("/opt/local"); pc.add("/opt/local");
#ifdef _WIN32
COMPARE(pc.str(), std::string("/usr/local/include/;/opt/local"));
#else
COMPARE(pc.str(), std::string("/usr/local/include/:/opt/local")); COMPARE(pc.str(), std::string("/usr/local/include/:/opt/local"));
#endif
// concat // concat
SGPath pd = pb; SGPath pd = pb;
pd.concat("-1"); pd.concat("-1");
-1
View File
@@ -382,7 +382,6 @@ bool Dir::remove(bool recursive)
if (recursive) { if (recursive) {
if (!removeChildren()) { if (!removeChildren()) {
SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
return false; return false;
} }
} // of recursive deletion } // of recursive deletion
+19 -68
View File
@@ -56,10 +56,7 @@ static const char sgSearchPathSep = ':';
#endif #endif
#ifdef _WIN32 #ifdef _WIN32
#include <ShlObj.h> // for CSIDL #include <ShlObj.h> // for CSIDL
// TODO: replace this include file with the official <versionhelpers.h> header
// included in the Windows 8.1 SDK
#include "sgversionhelpers.hxx"
static SGPath pathForCSIDL(int csidl, const SGPath& def) static SGPath pathForCSIDL(int csidl, const SGPath& def)
{ {
@@ -83,42 +80,6 @@ static SGPath pathForCSIDL(int csidl, const SGPath& def)
return def; return def;
} }
static SGPath pathForKnownFolder(REFKNOWNFOLDERID folderId, const SGPath& def)
{
typedef HRESULT (WINAPI*PSHGKFP)(REFKNOWNFOLDERID, DWORD, HANDLE, PWSTR*);
HINSTANCE shellDll = LoadLibrary(TEXT("shell32"));
if (shellDll != NULL) {
PSHGKFP pSHGetKnownFolderPath = (PSHGKFP) GetProcAddress(shellDll, "SHGetKnownFolderPath");
if (pSHGetKnownFolderPath != NULL) {
// system call will allocate dynamic memory... which we must release when done
wchar_t* localFolder = 0;
if (pSHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT_PATH, NULL, &localFolder) == S_OK) {
// copy into local memory
char path[MAX_PATH];
size_t len;
if (wcstombs_s(&len, path, localFolder, MAX_PATH) != S_OK) {
path[0] = '\0';
SG_LOG(SG_GENERAL, SG_WARN, "WCS to MBS failed");
}
SGPath folder_path = SGPath(path, def.getPermissionChecker());
// release dynamic memory
CoTaskMemFree(static_cast<void*>(localFolder));
return folder_path;
}
}
FreeLibrary(shellDll);
}
return def;
}
#elif __APPLE__ #elif __APPLE__
// defined in CocoaHelpers.mm // defined in CocoaHelpers.mm
@@ -743,35 +704,20 @@ SGPath SGPath::standardLocation(StandardLocation type, const SGPath& def)
{ {
case HOME: case HOME:
return home(def); return home(def);
#ifdef _WIN32 #ifdef _WIN32
case DESKTOP: case DESKTOP:
if (IsWindowsVistaOrGreater()) return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
return pathForKnownFolder(FOLDERID_Desktop, def);
return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
case DOWNLOADS: case DOWNLOADS:
if (IsWindowsVistaOrGreater()) // TODO use KnownFolders
return pathForKnownFolder(FOLDERID_Downloads, def); // http://msdn.microsoft.com/en-us/library/bb776911%28v=vs.85%29.aspx
if( !def.isNull() )
if (!def.isNull()) return def;
return def;
return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
return pathForCSIDL(CSIDL_DESKTOPDIRECTORY, def);
case DOCUMENTS: case DOCUMENTS:
if (IsWindowsVistaOrGreater()) return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
return pathForKnownFolder(FOLDERID_Documents, def);
return pathForCSIDL(CSIDL_MYDOCUMENTS, def);
case PICTURES: case PICTURES:
if (IsWindowsVistaOrGreater()) return pathForCSIDL(CSIDL_MYPICTURES, def);
return pathForKnownFolder(FOLDERID_Pictures, def);
return pathForCSIDL(CSIDL_MYPICTURES, def);
#elif __APPLE__ #elif __APPLE__
// since this is C++, we can't include NSPathUtilities.h to access the enum // since this is C++, we can't include NSPathUtilities.h to access the enum
// values, so hard-coding them here (they are stable, don't worry) // values, so hard-coding them here (they are stable, don't worry)
@@ -810,15 +756,20 @@ SGPath SGPath::fromEnv(const char* name, const SGPath& def)
return def; return def;
} }
#ifdef _WIN32
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
SGPath SGPath::home(const SGPath& def) SGPath SGPath::home(const SGPath& def)
{ {
#ifdef _WIN32 // TODO
return fromEnv("USERPROFILE", def); return def;
#else
return fromEnv("HOME", def);
#endif
} }
#else
//------------------------------------------------------------------------------
SGPath SGPath::home(const SGPath& def)
{
return fromEnv("HOME", def);
}
#endif
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
SGPath SGPath::desktop(const SGPath& def) SGPath SGPath::desktop(const SGPath& def)
-122
View File
@@ -1,122 +0,0 @@
// Clean drop-in replacement for the versionhelpers.h header
//
// Copyright (C) 2015 Alessandro Menti <alessandro.menti@hotmail.it>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
#ifndef SG_VERSIONHELPERS_HXX_
#define SG_VERSIONHELPERS_HXX_
#include <sdkddkver.h>
#ifdef __cplusplus
#define VERSIONHELPERAPI inline bool
#else
#define VERSIONHELPERAPI FORCEINLINE BOOL
#endif // __cplusplus
/* Windows 8/8.1 version numbers, not defined in the Windows 7 SDK. */
#ifndef _WIN32_WINNT_WIN8
#define _WIN32_WINNT_WIN8 0x0602
#endif
#ifndef _WIN32_WINNT_WINBLUE
#define _WIN32_WINNT_WINBLUE 0x0603
#endif
VERSIONHELPERAPI IsWindowsVersionOrGreater(WORD wMajorVersion,
WORD wMinorVersion, WORD wServicePackMajor) {
OSVERSIONINFOEXW osVersionInfo;
DWORDLONG dwlConditionMask = 0;
ZeroMemory(&osVersionInfo, sizeof(osVersionInfo));
osVersionInfo.dwOSVersionInfoSize = sizeof(osVersionInfo);
osVersionInfo.dwMajorVersion = wMajorVersion;
osVersionInfo.dwMinorVersion = wMinorVersion;
osVersionInfo.wServicePackMajor = wServicePackMajor;
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION,
VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION,
VER_GREATER_EQUAL);
VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR,
VER_GREATER_EQUAL);
return VerifyVersionInfoW(&osVersionInfo, VER_MAJORVERSION
| VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask);
}
VERSIONHELPERAPI IsWindowsXPOrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP),
LOBYTE(_WIN32_WINNT_WINXP), 0);
}
VERSIONHELPERAPI IsWindowsXPSP1OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP),
LOBYTE(_WIN32_WINNT_WINXP), 1);
}
VERSIONHELPERAPI IsWindowsXPSP2OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP),
LOBYTE(_WIN32_WINNT_WINXP), 2);
}
VERSIONHELPERAPI IsWindowsXPSP3OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINXP),
LOBYTE(_WIN32_WINNT_WINXP), 3);
}
VERSIONHELPERAPI IsWindowsVistaOrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA),
LOBYTE(_WIN32_WINNT_VISTA), 0);
}
VERSIONHELPERAPI IsWindowsVistaSP1OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA),
LOBYTE(_WIN32_WINNT_VISTA), 1);
}
VERSIONHELPERAPI IsWindowsVistaSP2OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_VISTA),
LOBYTE(_WIN32_WINNT_VISTA), 2);
}
VERSIONHELPERAPI IsWindows7OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7),
LOBYTE(_WIN32_WINNT_WIN7), 0);
}
VERSIONHELPERAPI IsWindows7SP1OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN7),
LOBYTE(_WIN32_WINNT_WIN7), 1);
}
VERSIONHELPERAPI IsWindows8OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN8),
LOBYTE(_WIN32_WINNT_WIN8), 0);
}
VERSIONHELPERAPI IsWindows8Point1OrGreater() {
return IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WINBLUE),
LOBYTE(_WIN32_WINNT_WINBLUE), 0);
}
VERSIONHELPERAPI IsWindowsServer() {
OSVERSIONINFOEXW osVersionInfo;
DWORDLONG dwlConditionMask = 0;
ZeroMemory(&osVersionInfo, sizeof(osVersionInfo));
osVersionInfo.dwOSVersionInfoSize = sizeof(osVersionInfo);
osVersionInfo.wProductType = VER_NT_WORKSTATION;
VER_SET_CONDITION(dwlConditionMask, VER_PRODUCT_TYPE, VER_EQUAL);
return !VerifyVersionInfoW(&osVersionInfo, VER_PRODUCT_TYPE,
dwlConditionMask);
}
#endif // SG_VERSIONHELPERS_HXX_
-1
View File
@@ -23,7 +23,6 @@
#include <ctype.h> #include <ctype.h>
#include <cstring> #include <cstring>
#include <sstream> #include <sstream>
#include <algorithm>
#include "strutils.hxx" #include "strutils.hxx"
+2 -2
View File
@@ -4,7 +4,6 @@ include (SimGearComponent)
set(HEADERS set(HEADERS
naref.h naref.h
nasal.h nasal.h
iolib.h
) )
set(SOURCES set(SOURCES
@@ -27,7 +26,8 @@ set(SOURCES
vector.c vector.c
code.h code.h
data.h data.h
iolib.h
parse.h parse.h
) )
simgear_component(nasal nasal "${SOURCES}" "${HEADERS}") simgear_component(nasal nasal "${SOURCES}" "${HEADERS}")
+8
View File
@@ -66,6 +66,14 @@ namespace nasal
void GhostMetadata::addDerived(const GhostMetadata* derived) void GhostMetadata::addDerived(const GhostMetadata* derived)
{ {
assert(derived); assert(derived);
SG_LOG
(
SG_NASAL,
SG_INFO,
"Ghost::addDerived: " << _name_strong << " -> "
<< derived->_name_strong
);
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@@ -39,12 +39,6 @@ static void runNumTests( double (TestContext::*test_double)(const std::string&),
BOOST_CHECK_EQUAL((c.*test_int)("0x755"), 0x755); BOOST_CHECK_EQUAL((c.*test_int)("0x755"), 0x755);
BOOST_CHECK_EQUAL((c.*test_int)("0x055"), 0x55); BOOST_CHECK_EQUAL((c.*test_int)("0x055"), 0x55);
BOOST_CHECK_EQUAL((c.*test_int)("-0x155"), -0x155); BOOST_CHECK_EQUAL((c.*test_int)("-0x155"), -0x155);
BOOST_CHECK_CLOSE((c.*test_double)("2.000000953656983160"),
2.000000953656983160, 1e-5);
/* this value has bit pattern 0x400000007fff6789L,
* so will look like a pointer if the endianness is set wrong
* (see naref.h, data.h)*/
} }
BOOST_AUTO_TEST_CASE( parse_num ) BOOST_AUTO_TEST_CASE( parse_num )
-6
View File
@@ -142,9 +142,6 @@ naRef naIOGhost(naContext c, FILE* f)
return naNewGhost(c, &naIOGhostType, ghost); return naNewGhost(c, &naIOGhostType, ghost);
} }
#if SG_NASAL_UNRESTRICTED_OPEN
// Allows unrestricted file access, which would be a security hole
// Replaced by the one in flightgear src/Scripting/NasalSys.cxx
static naRef f_open(naContext c, naRef me, int argc, naRef* args) static naRef f_open(naContext c, naRef me, int argc, naRef* args)
{ {
FILE* f; FILE* f;
@@ -155,7 +152,6 @@ static naRef f_open(naContext c, naRef me, int argc, naRef* args)
if(!f) naRuntimeError(c, strerror(errno)); if(!f) naRuntimeError(c, strerror(errno));
return naIOGhost(c, f); return naIOGhost(c, f);
} }
#endif
// frees buffer before tossing an error // frees buffer before tossing an error
static int getcguard(naContext ctx, FILE* f, void* buf) static int getcguard(naContext ctx, FILE* f, void* buf)
@@ -248,9 +244,7 @@ static naCFuncItem funcs[] = {
{ "seek", f_seek }, { "seek", f_seek },
{ "tell", f_tell }, { "tell", f_tell },
{ "flush", f_flush }, { "flush", f_flush },
#if SG_NASAL_UNRESTRICTED_OPEN
{ "open", f_open }, { "open", f_open },
#endif
{ "readln", f_readln }, { "readln", f_readln },
{ "stat", f_stat }, { "stat", f_stat },
{ 0 } { 0 }
+1 -6
View File
@@ -1,8 +1,5 @@
#ifndef _IOLIB_H #ifndef _IOLIB_H
#define _IOLIB_H #define _IOLIB_H
#ifdef __cplusplus
extern "C" {
#endif
#include "nasal.h" #include "nasal.h"
@@ -36,7 +33,5 @@ extern struct naIOType naStdIOType;
// Defined in iolib.c, there is no "library" header to put this in // Defined in iolib.c, there is no "library" header to put this in
naRef naIOGhost(naContext c, FILE* f); naRef naIOGhost(naContext c, FILE* f);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // _IOLIB_H #endif // _IOLIB_H
+15 -18
View File
@@ -1,31 +1,28 @@
#ifndef _NAREF_H #ifndef _NAREF_H
#define _NAREF_H #define _NAREF_H
/* Rather than play elaborate and complicated games with
* platform-dependent endianness headers, just detect the platforms we
* support. This list is simpler and smaller, yet still quite
* complete. */
#if (defined(__x86_64) && defined(__linux__)) || defined(__sparcv9) || \ #if (defined(__x86_64) && defined(__linux__)) || defined(__sparcv9) || \
defined(__powerpc64__) defined(__powerpc64__)
/* NASAL_NAN64 mode requires 64 bit pointers that only use the /* Win64 and Irix should work with this too, but have not been
* lower 48 bits; Win64 and Irix should work with this too, but * tested */
* have not been tested */
# define NASAL_NAN64 # define NASAL_NAN64
#elif defined(__BYTE_ORDER__) #elif defined(_M_IX86) || defined(i386) || defined(__x86_64) || \
/* GCC and Clang define these (as a builtin, while
* __LITTLE_ENDIAN__ requires a header), MSVC doesn't */
# if __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
# define NASAL_LE
# elif __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
# define NASAL_BE
# else
# error Unrecognized endianness
# endif
#elif defined(_M_IX86) || defined(__i386) || defined(__x86_64) || \
defined(__ia64__) || defined(_M_IA64) || defined(__ARMEL__) || \ defined(__ia64__) || defined(_M_IA64) || defined(__ARMEL__) || \
defined(_M_X64) || defined(_M_ARM) defined(_M_X64) || defined(__alpha__) || \
(defined(__sh__) && defined(__LITTLE_ENDIAN__))
# define NASAL_LE # define NASAL_LE
#elif defined(__sparc) || defined(__ARMEB__) || \ #elif defined(__sparc) || defined(__ppc__) || defined(__PPC) || \
defined(__hppa__) || defined(__s390__) || defined(__s390x__) defined (__powerpc__) || defined (__powerpc64__) || defined (__alpha__) || \
defined(__mips) || defined(__ARMEB__) || \
defined(__hppa__) || defined(__s390__) || defined(__s390x__) || \
(defined(__sh__) && !defined(__LITTLE_ENDIAN__))
# define NASAL_BE # define NASAL_BE
#else #else
# error Unknown endianness # error Unrecognized CPU architecture
#endif #endif
typedef union { typedef union {
-12
View File
@@ -26,15 +26,3 @@ if(ENABLE_PKGUTIL)
add_executable(sg_pkgutil pkgutil.cxx) add_executable(sg_pkgutil pkgutil.cxx)
target_link_libraries(sg_pkgutil ${TEST_LIBS}) target_link_libraries(sg_pkgutil ${TEST_LIBS})
endif() endif()
if(ENABLE_TESTS)
add_executable(catalog_test CatalogTest.cxx)
target_link_libraries(catalog_test ${TEST_LIBS})
set_target_properties(catalog_test PROPERTIES
COMPILE_DEFINITIONS "SRC_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}\"" )
add_test(catalog_test ${EXECUTABLE_OUTPUT_PATH}/catalog_test)
endif(ENABLE_TESTS)
+57 -149
View File
@@ -33,39 +33,10 @@
#include <simgear/package/Install.hxx> #include <simgear/package/Install.hxx>
namespace simgear { namespace simgear {
namespace pkg { namespace pkg {
bool checkVersion(const std::string& aVersion, SGPropertyNode_ptr props) CatalogList static_catalogs;
{
BOOST_FOREACH(SGPropertyNode* v, props->getChildren("version")) {
std::string s(v->getStringValue());
if (s== aVersion) {
return true;
}
// allow 3.5.* to match any of 3.5.0, 3.5.1rc1, 3.5.11 or so on
if (strutils::ends_with(s, ".*")) {
size_t lastDot = aVersion.rfind('.');
std::string ver = aVersion.substr(0, lastDot);
if (ver == s.substr(0, s.length() - 2)) {
return true;
}
}
}
return false;
}
std::string redirectUrlForVersion(const std::string& aVersion, SGPropertyNode_ptr props)
{
BOOST_FOREACH(SGPropertyNode* v, props->getChildren("alternate-version")) {
if (v->getStringValue("version") == aVersion) {
return v->getStringValue("url");
}
}
return std::string();
}
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
@@ -75,28 +46,25 @@ public:
Downloader(CatalogRef aOwner, const std::string& aUrl) : Downloader(CatalogRef aOwner, const std::string& aUrl) :
HTTP::Request(aUrl), HTTP::Request(aUrl),
m_owner(aOwner) m_owner(aOwner)
{ {
// refreshing
m_owner->changeStatus(Delegate::FAIL_IN_PROGRESS);
} }
protected: protected:
virtual void gotBodyData(const char* s, int n) virtual void gotBodyData(const char* s, int n)
{ {
m_buffer += std::string(s, n); m_buffer += std::string(s, n);
} }
virtual void onDone() virtual void onDone()
{ {
if (responseCode() != 200) { if (responseCode() != 200) {
SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url()); SG_LOG(SG_GENERAL, SG_ALERT, "catalog download failure:" << m_owner->url());
m_owner->refreshComplete(Delegate::FAIL_DOWNLOAD); m_owner->refreshComplete(Delegate::FAIL_DOWNLOAD);
return; return;
} }
SGPropertyNode* props = new SGPropertyNode; SGPropertyNode* props = new SGPropertyNode;
try { try {
readProperties(m_buffer.data(), m_buffer.size(), props); readProperties(m_buffer.data(), m_buffer.size(), props);
m_owner->parseProps(props); m_owner->parseProps(props);
@@ -105,29 +73,15 @@ protected:
m_owner->refreshComplete(Delegate::FAIL_EXTRACT); m_owner->refreshComplete(Delegate::FAIL_EXTRACT);
return; return;
} }
std::string ver(m_owner->root()->catalogVersion()); std::string ver(m_owner->root()->catalogVersion());
if (!checkVersion(ver, props)) { if (!checkVersion(ver, props)) {
SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t" SG_LOG(SG_GENERAL, SG_WARN, "downloaded catalog " << m_owner->url() << ", version mismatch:\n\t"
<< props->getStringValue("version") << " vs required " << ver); << props->getStringValue("version") << " vs required " << ver);
m_owner->refreshComplete(Delegate::FAIL_VERSION);
// check for a version redirect entry
std::string url = redirectUrlForVersion(ver, props);
if (!url.empty()) {
SG_LOG(SG_GENERAL, SG_WARN, "redirecting from " << m_owner->url() <<
" to \n\t" << url);
// update the URL and kick off a new request
m_owner->m_url = url;
Downloader* dl = new Downloader(m_owner, url);
m_owner->root()->makeHTTPRequest(dl);
} else {
m_owner->refreshComplete(Delegate::FAIL_VERSION);
}
return; return;
} // of version check failed }
// cache the catalog data, now we have a valid install root // cache the catalog data, now we have a valid install root
Dir d(m_owner->installRoot()); Dir d(m_owner->installRoot());
SGPath p = d.file("catalog.xml"); SGPath p = d.file("catalog.xml");
@@ -135,29 +89,45 @@ protected:
std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc); std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
f.write(m_buffer.data(), m_buffer.size()); f.write(m_buffer.data(), m_buffer.size());
f.close(); f.close();
time(&m_owner->m_retrievedTime); time(&m_owner->m_retrievedTime);
m_owner->writeTimestamp(); m_owner->writeTimestamp();
m_owner->refreshComplete(Delegate::CATALOG_REFRESHED); m_owner->refreshComplete(Delegate::FAIL_SUCCESS);
} }
private: private:
bool checkVersion(const std::string& aVersion, SGPropertyNode* aProps)
{
BOOST_FOREACH(SGPropertyNode* v, aProps->getChildren("version")) {
if (v->getStringValue() == aVersion) {
return true;
}
}
return false;
}
CatalogRef m_owner; CatalogRef m_owner;
std::string m_buffer; std::string m_buffer;
}; };
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
CatalogList Catalog::allCatalogs()
{
return static_catalogs;
}
Catalog::Catalog(Root *aRoot) : Catalog::Catalog(Root *aRoot) :
m_root(aRoot), m_root(aRoot),
m_status(Delegate::FAIL_UNKNOWN),
m_retrievedTime(0) m_retrievedTime(0)
{ {
static_catalogs.push_back(this);
} }
Catalog::~Catalog() Catalog::~Catalog()
{ {
CatalogList::iterator it = std::find(static_catalogs.begin(), static_catalogs.end(), this);
static_catalogs.erase(it);
} }
CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl) CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
@@ -166,10 +136,10 @@ CatalogRef Catalog::createFromUrl(Root* aRoot, const std::string& aUrl)
c->m_url = aUrl; c->m_url = aUrl;
Downloader* dl = new Downloader(c, aUrl); Downloader* dl = new Downloader(c, aUrl);
aRoot->makeHTTPRequest(dl); aRoot->makeHTTPRequest(dl);
return c; return c;
} }
CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath) CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
{ {
SGPath xml = aPath; SGPath xml = aPath;
@@ -177,66 +147,29 @@ CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
if (!xml.exists()) { if (!xml.exists()) {
return NULL; return NULL;
} }
SGPropertyNode_ptr props; SGPropertyNode_ptr props;
try { try {
props = new SGPropertyNode; props = new SGPropertyNode;
readProperties(xml.str(), props); readProperties(xml.str(), props);
} catch (sg_exception& e) { } catch (sg_exception& e) {
return NULL;
}
if (props->getStringValue("version") != aRoot->catalogVersion()) {
SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
<< props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
return NULL; return NULL;
} }
if (!checkVersion(aRoot->catalogVersion(), props)) {
std::string redirect = redirectUrlForVersion(aRoot->catalogVersion(), props);
if (!redirect.empty()) {
SG_LOG(SG_GENERAL, SG_WARN, "catalog at " << aPath << ", version mismatch:\n\t"
<< "redirecting to alternate URL:" << redirect);
CatalogRef c = Catalog::createFromUrl(aRoot, redirect);
c->m_installRoot = aPath;
return c;
} else {
SG_LOG(SG_GENERAL, SG_WARN, "skipping catalog at " << aPath << ", version mismatch:\n\t"
<< props->getStringValue("version") << " vs required " << aRoot->catalogVersion());
return NULL;
}
}
CatalogRef c = new Catalog(aRoot); CatalogRef c = new Catalog(aRoot);
c->m_installRoot = aPath; c->m_installRoot = aPath;
c->parseProps(props); // will set status c->parseProps(props);
c->parseTimestamp(); c->parseTimestamp();
return c; return c;
} }
bool Catalog::uninstall()
{
bool ok;
bool atLeastOneFailure = false;
BOOST_FOREACH(PackageRef p, installedPackages()) {
ok = p->existingInstall()->uninstall();
if (!ok) {
SG_LOG(SG_GENERAL, SG_WARN, "uninstall of package " <<
p->id() << " failed");
// continue trying other packages, bailing out here
// gains us nothing
atLeastOneFailure = true;
}
}
Dir d(m_installRoot);
ok = d.remove(true /* recursive */);
if (!ok) {
atLeastOneFailure = true;
}
changeStatus(atLeastOneFailure ? Delegate::FAIL_FILESYSTEM
: Delegate::FAIL_SUCCESS);
return ok;
}
PackageList const& PackageList const&
Catalog::packages() const Catalog::packages() const
{ {
@@ -263,7 +196,7 @@ Catalog::packagesNeedingUpdate() const
if (!p->isInstalled()) { if (!p->isInstalled()) {
continue; continue;
} }
if (p->install()->hasUpdate()) { if (p->install()->hasUpdate()) {
r.push_back(p); r.push_back(p);
} }
@@ -282,7 +215,7 @@ Catalog::installedPackages() const
} }
return r; return r;
} }
InstallRef Catalog::installForPackage(PackageRef pkg) const InstallRef Catalog::installForPackage(PackageRef pkg) const
{ {
PackageInstallDict::const_iterator it = m_installed.find(pkg); PackageInstallDict::const_iterator it = m_installed.find(pkg);
@@ -293,17 +226,16 @@ InstallRef Catalog::installForPackage(PackageRef pkg) const
if (p.exists()) { if (p.exists()) {
return Install::createFromPath(p, CatalogRef(const_cast<Catalog*>(this))); return Install::createFromPath(p, CatalogRef(const_cast<Catalog*>(this)));
} }
return NULL; return NULL;
} }
return it->second; return it->second;
} }
void Catalog::refresh() void Catalog::refresh()
{ {
Downloader* dl = new Downloader(this, url()); Downloader* dl = new Downloader(this, url());
// will iupdate status to IN_PROGRESS
m_root->makeHTTPRequest(dl); m_root->makeHTTPRequest(dl);
m_root->catalogRefreshBegin(this); m_root->catalogRefreshBegin(this);
} }
@@ -362,19 +294,16 @@ void Catalog::parseProps(const SGPropertyNode* aProps)
<< " is now at: " << m_props->getStringValue("url")); << " is now at: " << m_props->getStringValue("url"));
} }
} }
m_url = m_props->getStringValue("url"); m_url = m_props->getStringValue("url");
if (m_installRoot.isNull()) { if (m_installRoot.isNull()) {
m_installRoot = m_root->path(); m_installRoot = m_root->path();
m_installRoot.append(id()); m_installRoot.append(id());
Dir d(m_installRoot); Dir d(m_installRoot);
d.create(0755); d.create(0755);
} }
// parsed XML ok, mark status as valid
changeStatus(Delegate::FAIL_SUCCESS);
} }
PackageRef Catalog::getPackageById(const std::string& aId) const PackageRef Catalog::getPackageById(const std::string& aId) const
@@ -402,7 +331,7 @@ std::string Catalog::description() const
{ {
return getLocalisedString(m_props, "description"); return getLocalisedString(m_props, "description");
} }
SGPropertyNode* Catalog::properties() const SGPropertyNode* Catalog::properties() const
{ {
return m_props.ptr(); return m_props.ptr();
@@ -437,7 +366,7 @@ bool Catalog::needsRefresh() const
unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds()); unsigned int maxAge = m_props->getIntValue("max-age-sec", m_root->maxAgeSeconds());
return (ageInSeconds() > maxAge); return (ageInSeconds() > maxAge);
} }
std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const
{ {
if (aRoot->hasChild(m_root->getLocale())) { if (aRoot->hasChild(m_root->getLocale())) {
@@ -446,14 +375,13 @@ std::string Catalog::getLocalisedString(const SGPropertyNode* aRoot, const char*
return localeRoot->getStringValue(aName); return localeRoot->getStringValue(aName);
} }
} }
return aRoot->getStringValue(aName); return aRoot->getStringValue(aName);
} }
void Catalog::refreshComplete(Delegate::FailureCode aReason) void Catalog::refreshComplete(Delegate::FailureCode aReason)
{ {
m_root->catalogRefreshComplete(this, aReason); m_root->catalogRefreshComplete(this, aReason);
changeStatus(aReason);
} }
void Catalog::registerInstall(Install* ins) void Catalog::registerInstall(Install* ins)
@@ -461,7 +389,7 @@ void Catalog::registerInstall(Install* ins)
if (!ins || ins->package()->catalog() != this) { if (!ins || ins->package()->catalog() != this) {
return; return;
} }
m_installed[ins->package()] = ins; m_installed[ins->package()] = ins;
} }
@@ -470,30 +398,10 @@ void Catalog::unregisterInstall(Install* ins)
if (!ins || ins->package()->catalog() != this) { if (!ins || ins->package()->catalog() != this) {
return; return;
} }
m_installed.erase(ins->package()); m_installed.erase(ins->package());
} }
void Catalog::changeStatus(Delegate::FailureCode newStatus)
{
if (m_status == newStatus) {
return;
}
m_status = newStatus;
m_statusCallbacks(this);
}
void Catalog::addStatusCallback(const Callback& cb)
{
m_statusCallbacks.push_back(cb);
}
Delegate::FailureCode Catalog::status() const
{
return m_status;
}
} // of namespace pkg } // of namespace pkg
} // of namespace simgear } // of namespace simgear
+29 -52
View File
@@ -22,22 +22,19 @@
#include <ctime> #include <ctime>
#include <map> #include <map>
#include <boost/bind.hpp>
#include <simgear/misc/sg_path.hxx> #include <simgear/misc/sg_path.hxx>
#include <simgear/props/props.hxx> #include <simgear/props/props.hxx>
#include <simgear/structure/SGReferenced.hxx> #include <simgear/structure/SGReferenced.hxx>
#include <simgear/structure/SGSharedPtr.hxx> #include <simgear/structure/SGSharedPtr.hxx>
#include <simgear/structure/function_list.hxx>
#include <simgear/package/Delegate.hxx> #include <simgear/package/Delegate.hxx>
namespace simgear namespace simgear
{ {
namespace HTTP { class Client; } namespace HTTP { class Client; }
namespace pkg namespace pkg
{ {
@@ -46,11 +43,11 @@ class Package;
class Catalog; class Catalog;
class Root; class Root;
class Install; class Install;
typedef SGSharedPtr<Package> PackageRef; typedef SGSharedPtr<Package> PackageRef;
typedef SGSharedPtr<Catalog> CatalogRef; typedef SGSharedPtr<Catalog> CatalogRef;
typedef SGSharedPtr<Install> InstallRef; typedef SGSharedPtr<Install> InstallRef;
typedef std::vector<PackageRef> PackageList; typedef std::vector<PackageRef> PackageList;
typedef std::vector<CatalogRef> CatalogList; typedef std::vector<CatalogRef> CatalogList;
@@ -58,18 +55,15 @@ class Catalog : public SGReferenced
{ {
public: public:
virtual ~Catalog(); virtual ~Catalog();
static CatalogRef createFromUrl(Root* aRoot, const std::string& aUrl); static CatalogRef createFromUrl(Root* aRoot, const std::string& aUrl);
static CatalogRef createFromPath(Root* aRoot, const SGPath& aPath); static CatalogRef createFromPath(Root* aRoot, const SGPath& aPath);
static CatalogList allCatalogs();
Root* root() const Root* root() const
{ return m_root;}; { return m_root;};
/**
* uninstall this catalog entirely, including all installed packages
*/
bool uninstall();
/** /**
* perform a refresh of the catalog contents * perform a refresh of the catalog contents
@@ -95,87 +89,70 @@ public:
/** /**
* retrieve all the packages in the catalog which are installed * retrieve all the packages in the catalog which are installed
* and have a pendig update * and have a pendig update
*/ */
PackageList packagesNeedingUpdate() const; PackageList packagesNeedingUpdate() const;
SGPath installRoot() const SGPath installRoot() const
{ return m_installRoot; } { return m_installRoot; }
std::string id() const; std::string id() const;
std::string url() const; std::string url() const;
std::string description() const; std::string description() const;
PackageRef getPackageById(const std::string& aId) const; PackageRef getPackageById(const std::string& aId) const;
InstallRef installForPackage(PackageRef pkg) const; InstallRef installForPackage(PackageRef pkg) const;
/** /**
* test if the catalog data was retrieved longer ago than the * test if the catalog data was retrieved longer ago than the
* maximum permitted age for this catalog. * maximum permitted age for this catalog.
*/ */
bool needsRefresh() const; bool needsRefresh() const;
unsigned int ageInSeconds() const; unsigned int ageInSeconds() const;
/** /**
* access the raw property data in the catalog * access the raw property data in the catalog
*/ */
SGPropertyNode* properties() const; SGPropertyNode* properties() const;
Delegate::FailureCode status() const;
typedef boost::function<void(Catalog*)> Callback;
void addStatusCallback(const Callback& cb);
template<class C>
void addStatusCallback(C* instance, void (C::*mem_func)(Catalog*))
{
return addStatusCallback(boost::bind(mem_func, instance, _1));
}
private: private:
Catalog(Root* aRoot); Catalog(Root* aRoot);
class Downloader; class Downloader;
friend class Downloader; friend class Downloader;
friend class Install; friend class Install;
void registerInstall(Install* ins); void registerInstall(Install* ins);
void unregisterInstall(Install* ins); void unregisterInstall(Install* ins);
void parseProps(const SGPropertyNode* aProps); void parseProps(const SGPropertyNode* aProps);
void refreshComplete(Delegate::FailureCode aReason); void refreshComplete(Delegate::FailureCode aReason);
void parseTimestamp(); void parseTimestamp();
void writeTimestamp(); void writeTimestamp();
std::string getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const; std::string getLocalisedString(const SGPropertyNode* aRoot, const char* aName) const;
void changeStatus(Delegate::FailureCode newStatus);
Root* m_root; Root* m_root;
SGPropertyNode_ptr m_props; SGPropertyNode_ptr m_props;
SGPath m_installRoot; SGPath m_installRoot;
std::string m_url; std::string m_url;
Delegate::FailureCode m_status;
PackageList m_packages; PackageList m_packages;
time_t m_retrievedTime; time_t m_retrievedTime;
typedef std::map<std::string, Package*> PackageWeakMap; typedef std::map<std::string, Package*> PackageWeakMap;
PackageWeakMap m_variantDict; PackageWeakMap m_variantDict;
// important that this is a weak-ref to Installs, // important that this is a weak-ref to Installs,
// since it is only cleaned up in the Install destructor // since it is only cleaned up in the Install destructor
typedef std::map<PackageRef, Install*> PackageInstallDict; typedef std::map<PackageRef, Install*> PackageInstallDict;
PackageInstallDict m_installed; PackageInstallDict m_installed;
function_list<Callback> m_statusCallbacks;
}; };
} // of namespace pkg } // of namespace pkg
} // of namespace simgear } // of namespace simgear
-107
View File
@@ -1,107 +0,0 @@
// Copyright (C) 2015 James Turner - zakalawe@mac.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
#ifdef HAVE_CONFIG_H
# include <simgear_config.h>
#endif
#include <simgear/misc/test_macros.hxx>
#include <cstdlib>
#include <iostream>
#include <simgear/package/Catalog.hxx>
#include <simgear/package/Root.hxx>
#include <simgear/package/Package.hxx>
#include <simgear/misc/sg_dir.hxx>
using namespace simgear;
int parseTest()
{
SGPath rootPath = simgear::Dir::current().path();
rootPath.append("testRoot");
pkg::Root* root = new pkg::Root(rootPath, "8.1.12");
pkg::CatalogRef cat = pkg::Catalog::createFromPath(root, SGPath(SRC_DIR "/catalogTest1"));
VERIFY(cat.valid());
COMPARE(cat->id(), "org.flightgear.test.catalog1");
COMPARE(cat->url(), "http://download.flightgear.org/catalog1/catalog.xml");
COMPARE(cat->description(), "First test catalog");
// check the packages too
COMPARE(cat->packages().size(), 3);
pkg::PackageRef p1 = cat->packages().front();
COMPARE(p1->catalog(), cat.ptr());
COMPARE(p1->id(), "alpha");
COMPARE(p1->qualifiedId(), "org.flightgear.test.catalog1.alpha");
COMPARE(p1->name(), "Alpha package");
COMPARE(p1->revision(), 8);
COMPARE(p1->fileSizeBytes(), 1234567);
pkg::PackageRef p2 = cat->getPackageById("c172p");
VERIFY(p2.valid());
COMPARE(p2->qualifiedId(), "org.flightgear.test.catalog1.c172p");
COMPARE(p2->description(), "A plane made by Cessna");
// test filtering / searching too
string_set tags(p2->tags());
COMPARE(tags.size(), 4);
VERIFY(tags.find("ifr") != tags.end());
VERIFY(tags.find("cessna") != tags.end());
VERIFY(tags.find("jet") == tags.end());
SGPropertyNode_ptr queryA(new SGPropertyNode);
queryA->setStringValue("tag", "ifr");
VERIFY(p2->matches(queryA.ptr()));
SGPropertyNode_ptr queryB(new SGPropertyNode);
queryB->setStringValue("name", "ces");
VERIFY(p2->matches(queryB.ptr()));
SGPropertyNode_ptr queryC(new SGPropertyNode);
queryC->setStringValue("name", "foo");
VERIFY(!p2->matches(queryC.ptr()));
SGPropertyNode_ptr queryD(new SGPropertyNode);
queryD->setIntValue("rating-FDM", 3);
VERIFY(p2->matches(queryD.ptr()));
SGPropertyNode_ptr queryE(new SGPropertyNode);
queryE->setIntValue("rating-model", 5);
queryE->setStringValue("description", "cessna");
VERIFY(p2->matches(queryE.ptr()));
delete root;
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
parseTest();
std::cout << "Successfully passed all tests!" << std::endl;
return EXIT_SUCCESS;
}
+1 -2
View File
@@ -42,8 +42,7 @@ public:
FAIL_DOWNLOAD, ///< network issue FAIL_DOWNLOAD, ///< network issue
FAIL_EXTRACT, ///< package archive failed to extract cleanly FAIL_EXTRACT, ///< package archive failed to extract cleanly
FAIL_FILESYSTEM, ///< unknown filesystem error occurred FAIL_FILESYSTEM, ///< unknown filesystem error occurred
FAIL_VERSION, ///< version check mismatch FAIL_VERSION ///< version check mismatch
CATALOG_REFRESHED
} FailureCode; } FailureCode;
+2 -12
View File
@@ -313,21 +313,11 @@ void Install::startUpdate()
m_package->catalog()->root()->startInstall(this); m_package->catalog()->root()->startInstall(this);
} }
bool Install::uninstall() void Install::uninstall()
{ {
Dir d(m_path); Dir d(m_path);
if (!d.remove(true)) { d.remove(true);
SG_LOG(SG_GENERAL, SG_ALERT, "package uninstall failed: couldn't remove path " << m_path);
return false;
}
m_package->catalog()->unregisterInstall(this); m_package->catalog()->unregisterInstall(this);
return true;
}
bool Install::isDownloading() const
{
return (m_download != NULL);
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
+2 -4
View File
@@ -73,11 +73,9 @@ public:
bool hasUpdate() const; bool hasUpdate() const;
void startUpdate(); void startUpdate();
bool uninstall();
bool isDownloading() const;
void uninstall();
/** /**
* Set the handler to be called when the installation successfully * Set the handler to be called when the installation successfully
* completes. * completes.
+1 -6
View File
@@ -186,11 +186,6 @@ std::string Package::description() const
{ {
return getLocalisedProp("description"); return getLocalisedProp("description");
} }
string_set Package::tags() const
{
return m_tags;
}
SGPropertyNode* Package::properties() const SGPropertyNode* Package::properties() const
{ {
@@ -243,7 +238,7 @@ PackageList Package::dependencies() const
// prefer local hangar package if possible, in case someone does something // prefer local hangar package if possible, in case someone does something
// silly with naming. Of course flightgear's aircraft search doesn't know // silly with naming. Of course flightgear's aircraft search doesn't know
// about hangars, so names still need to be unique. // about hanagrs, so names still need to be unique.
PackageRef depPkg = m_catalog->getPackageById(depName); PackageRef depPkg = m_catalog->getPackageById(depName);
if (!depPkg) { if (!depPkg) {
Root* rt = m_catalog->root(); Root* rt = m_catalog->root();
+1 -3
View File
@@ -112,9 +112,7 @@ public:
{ return m_catalog; } { return m_catalog; }
bool matches(const SGPropertyNode* aFilter) const; bool matches(const SGPropertyNode* aFilter) const;
string_set tags() const;
/** /**
* download URLs for the package * download URLs for the package
*/ */
-22
View File
@@ -336,28 +336,6 @@ void Root::catalogRefreshComplete(CatalogRef aCat, Delegate::FailureCode aReason
} }
} }
bool Root::removeCatalogById(const std::string& aId)
{
CatalogDict::iterator catIt = d->catalogs.find(aId);
if (catIt == d->catalogs.end()) {
SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: unknown ID:" << aId);
return false;
}
CatalogRef cat = catIt->second;
// drop the reference
d->catalogs.erase(catIt);
bool ok = cat->uninstall();
if (!ok) {
SG_LOG(SG_GENERAL, SG_WARN, "removeCatalogById: catalog :" << aId
<< "failed to uninstall");
}
return ok;
}
} // of namespace pkg } // of namespace pkg
} // of namespace simgear } // of namespace simgear
-6
View File
@@ -109,12 +109,6 @@ public:
CatalogRef getCatalogById(const std::string& aId) const; CatalogRef getCatalogById(const std::string& aId) const;
void scheduleToUpdate(InstallRef aInstall); void scheduleToUpdate(InstallRef aInstall);
/**
* remove a catalog. Will uninstall all packages originating
* from the catalog too.
*/
bool removeCatalogById(const std::string& aId);
private: private:
friend class Install; friend class Install;
friend class Catalog; friend class Catalog;
-64
View File
@@ -1,64 +0,0 @@
<?xml version="1.0"?>
<PropertyList>
<id>org.flightgear.test.catalog1</id>
<description>First test catalog</description>
<url>http://download.flightgear.org/catalog1/catalog.xml</url>
<version>8.1.*</version>
<version>8.0.0</version>
<version>8.2.0</version>
<package>
<id>alpha</id>
<name>Alpha package</name>
<revision type="int">8</revision>
<file-size-bytes type="int">1234567</file-size-bytes>
</package>
<package>
<id>c172p</id>
<name>Cessna 172-P</name>
<description>A plane made by Cessna</description>
<revision type="int">42</revision>
<file-size-bytes type="int">34567</file-size-bytes>
<tag>cessna</tag>
<tag>ga</tag>
<tag>piston</tag>
<tag>ifr</tag>
<rating>
<FDM type="int">3</FDM>
<systems type="int">4</systems>
<model type="int">5</model>
<cockpit type="int">4</cockpit>
</rating>
<!-- local dependency -->
<depends>
<id>org.flightgear.test.catalog1.common-sounds</id>
<revision>10</revision>
</depends>
<variant>
<id>c172p-2d-panel</id>
<name>C172 with 2d panel only</name>
</variant>
<variant>
<id>c172p-floats</id>
<name>C172 with floats</name>
</variant>
<variant>
<id>c172p-skis</id>
<name>C172 with skis</name>
</variant>
</package>
<package>
<id>common-sounds</id>
<name>Common sound files for test catalog aircraft</name>
<revision>10</revision>
</package>
</PropertyList>
+2 -3
View File
@@ -158,8 +158,7 @@ SG_MD5Transform(u_int32_t state[4], const u_int8_t block[MD5_BLOCK_LENGTH])
{ {
u_int32_t a, b, c, d, in[MD5_BLOCK_LENGTH / 4]; u_int32_t a, b, c, d, in[MD5_BLOCK_LENGTH / 4];
#if ((defined(__BYTE_ORDER__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || \ #ifndef WORDS_BIGENDIAN
defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) )
memcpy(in, block, sizeof(in)); memcpy(in, block, sizeof(in));
#else #else
for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) {
@@ -248,4 +247,4 @@ defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM) )
state[1] += b; state[1] += b;
state[2] += c; state[2] += c;
state[3] += d; state[3] += d;
} }
+25 -25
View File
@@ -26,7 +26,7 @@
#include <iostream> #include <iostream>
#include <cstring> #include <cstring>
using namespace simgear; using namespace simgear;
using namespace std; using namespace std;
bool keepRunning = true; bool keepRunning = true;
@@ -37,29 +37,29 @@ public:
virtual void refreshComplete() virtual void refreshComplete()
{ {
} }
virtual void failedRefresh(pkg::Catalog* aCatalog, FailureCode aReason) virtual void failedRefresh(pkg::Catalog* aCatalog, FailureCode aReason)
{ {
cerr << "failed refresh of " << aCatalog->description() << ":" << aReason << endl; cerr << "failed refresh of " << aCatalog->description() << ":" << aReason << endl;
} }
virtual void startInstall(pkg::Install* aInstall) virtual void startInstall(pkg::Install* aInstall)
{ {
_lastPercent = 999; _lastPercent = 999;
cout << "starting install of " << aInstall->package()->name() << endl; cout << "starting install of " << aInstall->package()->name() << endl;
} }
virtual void installProgress(pkg::Install* aInstall, unsigned int bytes, unsigned int total) virtual void installProgress(pkg::Install* aInstall, unsigned int bytes, unsigned int total)
{ {
unsigned int percent = (bytes * 100) / total; unsigned int percent = (bytes * 100) / total;
if (percent == _lastPercent) { if (percent == _lastPercent) {
return; return;
} }
_lastPercent = percent; _lastPercent = percent;
cout << percent << "%" << endl; cout << percent << "%" << endl;
} }
virtual void finishInstall(pkg::Install* aInstall) virtual void finishInstall(pkg::Install* aInstall)
{ {
cout << "done install of " << aInstall->package()->name() << endl; cout << "done install of " << aInstall->package()->name() << endl;
@@ -71,7 +71,7 @@ public:
} }
private: private:
unsigned int _lastPercent; unsigned int _lastPercent;
}; };
void printRating(pkg::Package* pkg, const std::string& aRating, const std::string& aLabel) void printRating(pkg::Package* pkg, const std::string& aRating, const std::string& aLabel)
@@ -87,24 +87,24 @@ void printPackageInfo(pkg::Package* pkg)
cout << "Name:" << pkg->name() << endl; cout << "Name:" << pkg->name() << endl;
cout << "Description:" << pkg->description() << endl; cout << "Description:" << pkg->description() << endl;
cout << "Long description:\n" << pkg->getLocalisedProp("long-description") << endl << endl; cout << "Long description:\n" << pkg->getLocalisedProp("long-description") << endl << endl;
if (pkg->properties()->hasChild("author")) { if (pkg->properties()->hasChild("author")) {
cout << "Authors:" << endl; cout << "Authors:" << endl;
BOOST_FOREACH(SGPropertyNode* author, pkg->properties()->getChildren("author")) { BOOST_FOREACH(SGPropertyNode* author, pkg->properties()->getChildren("author")) {
if (author->hasChild("name")) { if (author->hasChild("name")) {
cout << "\t" << author->getStringValue("name") << endl; cout << "\t" << author->getStringValue("name") << endl;
} else { } else {
// simple author structure // simple author structure
cout << "\t" << author->getStringValue() << endl; cout << "\t" << author->getStringValue() << endl;
} }
} }
cout << endl; cout << endl;
} }
cout << "Ratings:" << endl; cout << "Ratings:" << endl;
printRating(pkg, "fdm", "Flight-model "); printRating(pkg, "fdm", "Flight-model ");
printRating(pkg, "cockpit", "Cockpit "); printRating(pkg, "cockpit", "Cockpit ");
@@ -117,15 +117,15 @@ int main(int argc, char** argv)
HTTP::Client* http = new HTTP::Client(); HTTP::Client* http = new HTTP::Client();
pkg::Root* root = new pkg::Root(Dir::current().path(), ""); pkg::Root* root = new pkg::Root(Dir::current().path(), "");
MyDelegate dlg; MyDelegate dlg;
root->setDelegate(&dlg); root->setDelegate(&dlg);
cout << "Package root is:" << Dir::current().path() << endl; cout << "Package root is:" << Dir::current().path() << endl;
cout << "have " << root->catalogs().size() << " catalog(s)" << endl; cout << "have " << pkg::Catalog::allCatalogs().size() << " catalog(s)" << endl;
root->setHTTPClient(http); root->setHTTPClient(http);
if (!strcmp(argv[1], "add")) { if (!strcmp(argv[1], "add")) {
std::string url(argv[2]); std::string url(argv[2]);
pkg::Catalog::createFromUrl(root, url); pkg::Catalog::createFromUrl(root, url);
@@ -137,12 +137,12 @@ int main(int argc, char** argv)
cerr << "unknown package:" << argv[2] << endl; cerr << "unknown package:" << argv[2] << endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (pkg->isInstalled()) { if (pkg->isInstalled()) {
cout << "package " << pkg->id() << " is already installed at " << pkg->install()->path() << endl; cout << "package " << pkg->id() << " is already installed at " << pkg->install()->path() << endl;
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
pkg::CatalogRef catalog = pkg->catalog(); pkg::CatalogRef catalog = pkg->catalog();
cout << "Will install:" << pkg->id() << " from " << catalog->id() << cout << "Will install:" << pkg->id() << " from " << catalog->id() <<
"(" << catalog->description() << ")" << endl; "(" << catalog->description() << ")" << endl;
@@ -153,12 +153,12 @@ int main(int argc, char** argv)
cerr << "unknown package:" << argv[2] << endl; cerr << "unknown package:" << argv[2] << endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
if (!pkg->isInstalled()) { if (!pkg->isInstalled()) {
cerr << "package " << argv[2] << " not installed" << endl; cerr << "package " << argv[2] << " not installed" << endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
cout << "Will uninstall:" << pkg->id() << endl; cout << "Will uninstall:" << pkg->id() << endl;
pkg->install()->uninstall(); pkg->install()->uninstall();
} else if (!strcmp(argv[1], "update-all")) { } else if (!strcmp(argv[1], "update-all")) {
@@ -172,7 +172,7 @@ int main(int argc, char** argv)
cout << "no packages with updates" << endl; cout << "no packages with updates" << endl;
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }
cout << updates.size() << " packages have updates" << endl; cout << updates.size() << " packages have updates" << endl;
BOOST_FOREACH(pkg::Package* p, updates) { BOOST_FOREACH(pkg::Package* p, updates) {
cout << "\t" << p->id() << " " << p->getLocalisedProp("name") << endl; cout << "\t" << p->id() << " " << p->getLocalisedProp("name") << endl;
@@ -183,13 +183,13 @@ int main(int argc, char** argv)
cerr << "unknown package:" << argv[2] << endl; cerr << "unknown package:" << argv[2] << endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printPackageInfo(pkg); printPackageInfo(pkg);
} else { } else {
cerr << "unknown command:" << argv[1] << endl; cerr << "unknown command:" << argv[1] << endl;
return EXIT_FAILURE; return EXIT_FAILURE;
} }
while (http->hasActiveRequests()) { while (http->hasActiveRequests()) {
http->update(); http->update();
} }
+4 -4
View File
@@ -144,9 +144,9 @@ public:
#undef SG_DEF_ASSIGN_OP #undef SG_DEF_ASSIGN_OP
SGPropertyNode* node(bool aCreate = false) const SGPropertyNode* node() const
{ {
return PropertyObjectBase::node(aCreate); return PropertyObjectBase::node(false);
} }
}; // of template PropertyObject }; // of template PropertyObject
@@ -237,9 +237,9 @@ public:
return (s == value); return (s == value);
} }
SGPropertyNode* node(bool aCreate = false) const SGPropertyNode* node() const
{ {
return PropertyObjectBase::node(aCreate); return PropertyObjectBase::node(false);
} }
private: private:
}; };
-10
View File
@@ -326,15 +326,9 @@ public:
= GL2Extensions::Get(static_cast<unsigned>(contextId), true); = GL2Extensions::Get(static_cast<unsigned>(contextId), true);
if (!extensions) if (!extensions)
return; return;
#if OSG_VERSION_LESS_THAN(3,3,4)
if (!extensions->isGlslSupported()) if (!extensions->isGlslSupported())
return; return;
value = extensions->getLanguageVersion(); value = extensions->getLanguageVersion();
#else
if (!extensions->isGlslSupported)
return;
value = extensions->glslLanguageVersion;
#endif
} }
}; };
@@ -363,11 +357,7 @@ public:
= GL2Extensions::Get(static_cast<unsigned>(contextId), true); = GL2Extensions::Get(static_cast<unsigned>(contextId), true);
if (!extensions) if (!extensions)
return; return;
#if OSG_VERSION_LESS_THAN(3,3,4)
value = extensions->isGlslSupported(); value = extensions->isGlslSupported();
#else
value = extensions->isGlslSupported;
#endif
} }
}; };
-1
View File
@@ -323,7 +323,6 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
// Random vegetation properties // Random vegetation properties
wood_coverage = props->getDoubleValue("wood-coverage", 0.0); wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
tree_effect = props->getStringValue("tree-effect", "Effects/tree");
tree_height = props->getDoubleValue("tree-height-m", 0.0); tree_height = props->getDoubleValue("tree-height-m", 0.0);
tree_width = props->getDoubleValue("tree-width-m", 0.0); tree_width = props->getDoubleValue("tree-width-m", 0.0);
tree_range = props->getDoubleValue("tree-range-m", 0.0); tree_range = props->getDoubleValue("tree-range-m", 0.0);
-11
View File
@@ -273,14 +273,6 @@ public:
* @return the texture to use for trees. * @return the texture to use for trees.
*/ */
inline std::string get_tree_texture () const { return tree_texture; } inline std::string get_tree_texture () const { return tree_texture; }
/**
* Get the effect file name to use for trees
*
* @return the effect to use for this set of trees.
*/
inline std::string get_tree_effect () const { return tree_effect; }
/** /**
* Get the cosine of the maximum tree density slope angle. We * Get the cosine of the maximum tree density slope angle. We
@@ -484,9 +476,6 @@ private:
// Tree texture, typically a strip of applicable tree textures // Tree texture, typically a strip of applicable tree textures
std::string tree_texture; std::string tree_texture;
// Tree effect to be used for a particular material
std::string tree_effect;
// Object mask, a simple RGB texture used as a mask when placing // Object mask, a simple RGB texture used as a mask when placing
// random vegetation, objects and buildings // random vegetation, objects and buildings
+1 -5
View File
@@ -127,12 +127,8 @@ void CloudShaderGeometry::drawImplementation(RenderInfo& renderInfo) const
sortData.frameSorted = frameNumber; sortData.frameSorted = frameNumber;
} }
#if OSG_VERSION_LESS_THAN(3,3,4)
const Extensions* extensions = getExtensions(state.getContextID(),true); const Extensions* extensions = getExtensions(state.getContextID(),true);
#else
const GLExtensions* extensions = GLExtensions::Get(state.getContextID(), true);
#endif
GLfloat ua1[3] = { (GLfloat) alpha_factor, GLfloat ua1[3] = { (GLfloat) alpha_factor,
(GLfloat) shade_factor, (GLfloat) shade_factor,
(GLfloat) cloud_height }; (GLfloat) cloud_height };
+5 -5
View File
@@ -386,10 +386,10 @@ BuildingBoundingBoxCallback::computeBound(const Drawable& drawable) const
int row = ((int) (mt_rand(&seed) * 1000)) % 5; int row = ((int) (mt_rand(&seed) * 1000)) % 5;
float base_y = (float) row * 16.0 * 3.0 / 1024.0; float base_y = (float) row * 16.0 * 3.0 / 1024.0;
float top_y = base_y + 16.0 * (float) building.floors / 1024.0; float top_y = base_y + 16.0 * (float) building.floors / 1024.0;
float left_x = 32.0 / 1024.0 * SGMisc<double>::round((float)building.width / 6.0f); float left_x = 32.0 / 1024.0 * round((float) building.width / 6.0f);
float right_x = 0.0f; float right_x = 0.0f;
float front_x = 384.0/1024.0; float front_x = 384.0/1024.0;
float back_x = 384.0 / 1024.0 + 32.0 / 1024.0 * SGMisc<double>::round((float)building.depth / 6.0f); float back_x = 384.0/1024.0 + 32.0 / 1024.0 * round((float) building.depth/ 6.0f);
// BASEMENT - uses the baseline texture // BASEMENT - uses the baseline texture
for (unsigned int i = 0; i < 16; i++) { for (unsigned int i = 0; i < 16; i++) {
@@ -424,7 +424,7 @@ BuildingBoundingBoxCallback::computeBound(const Drawable& drawable) const
if (building.pitched) { if (building.pitched) {
// Use the entire height of the roof texture // Use the entire height of the roof texture
top_y = base_y + 16.0 * 3.0 / 1024.0; top_y = base_y + 16.0 * 3.0 / 1024.0;
left_x = 512 / 1024.0 + 32.0 / 1024.0 * SGMisc<double>::round(building.width / 6.0f); left_x = 512/1024.0 + 32.0 / 1024.0 * round(building.width / 6.0f);
right_x = 512/1024.0; right_x = 512/1024.0;
front_x = 480.0/1024.0; front_x = 480.0/1024.0;
back_x = 512.0/1024.0; back_x = 512.0/1024.0;
@@ -475,7 +475,7 @@ BuildingBoundingBoxCallback::computeBound(const Drawable& drawable) const
int column = ((int) (mt_rand(&seed) * 1000)) % 5; int column = ((int) (mt_rand(&seed) * 1000)) % 5;
float base_y = 288 / 1024.0; float base_y = 288 / 1024.0;
float top_y = base_y + 16.0 * (float) building.floors / 1024.0; float top_y = base_y + 16.0 * (float) building.floors / 1024.0;
float left_x = column * 192.0 / 1024.0 + 32.0 / 1024.0 * SGMisc<double>::round((float)building.width / 10.0f); float left_x = column * 192.0 /1024.0 + 32.0 / 1024.0 * round((float) building.width / 10.0f);
float right_x = column * 192.0 /1024.0; float right_x = column * 192.0 /1024.0;
// BASEMENT - uses the baseline texture // BASEMENT - uses the baseline texture
@@ -560,7 +560,7 @@ BuildingBoundingBoxCallback::computeBound(const Drawable& drawable) const
int column = ((int) (mt_rand(&seed) * 1000)) % 8; int column = ((int) (mt_rand(&seed) * 1000)) % 8;
float base_y = 576 / 1024.0; float base_y = 576 / 1024.0;
float top_y = base_y + 16.0 * (float) building.floors / 1024.0; float top_y = base_y + 16.0 * (float) building.floors / 1024.0;
float left_x = column * 128.0 / 1024.0 + 32.0 / 1024.0 * SGMisc<double>::round((float)building.width / 20.0f); float left_x = column * 128.0 /1024.0 + 32.0 / 1024.0 * round((float) building.width / 20.0f);
float right_x = column * 128.0 /1024.0; float right_x = column * 128.0 /1024.0;
// BASEMENT - uses the baseline texture // BASEMENT - uses the baseline texture
+1 -4
View File
@@ -291,8 +291,7 @@ public:
float vegetation_density, float vegetation_density,
float cos_max_density_angle, float cos_max_density_angle,
float cos_zero_density_angle, float cos_zero_density_angle,
std::vector<SGVec3f>& points, std::vector<SGVec3f>& points)
std::vector<SGVec3f>& normals)
{ {
if ( !geometries.empty() ) { if ( !geometries.empty() ) {
const osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geometries[0]->getVertexArray()); const osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(geometries[0]->getVertexArray());
@@ -367,11 +366,9 @@ public:
if (mt_rand(&seed) < img->getColor(x, y).g()) { if (mt_rand(&seed) < img->getColor(x, y).g()) {
// The red channel contains the rotation for this object // The red channel contains the rotation for this object
points.push_back(randomPoint); points.push_back(randomPoint);
normals.push_back(normalize(normal));
} }
} else { } else {
points.push_back(randomPoint); points.push_back(randomPoint);
normals.push_back(normalize(normal));
} }
} }
} }
+5 -9
View File
@@ -28,7 +28,6 @@
#include <osg/Geometry> #include <osg/Geometry>
#include <osg/PrimitiveSet> #include <osg/PrimitiveSet>
#include <osg/Texture2D> #include <osg/Texture2D>
#include <osg/ref_ptr>
#include <stdio.h> #include <stdio.h>
#include <simgear/math/sg_random.h> #include <simgear/math/sg_random.h>
@@ -123,16 +122,16 @@ public:
osg::DrawElements* getDrawElements() osg::DrawElements* getDrawElements()
{ {
if (count > 65535) { if (count > 65535) {
_ushortElements = 0; free (_ushortElements);
return _uintElements; return _uintElements;
} else { } else {
_uintElements = 0; free (_uintElements);
return _ushortElements; return _ushortElements;
} }
} }
protected: protected:
osg::ref_ptr<osg::DrawElementsUShort> _ushortElements; osg::DrawElementsUShort* _ushortElements;
osg::ref_ptr<osg::DrawElementsUInt> _uintElements; osg::DrawElementsUInt* _uintElements;
unsigned count; unsigned count;
}; };
@@ -216,8 +215,7 @@ public:
float vegetation_density, float vegetation_density,
float cos_max_density_angle, float cos_max_density_angle,
float cos_zero_density_angle, float cos_zero_density_angle,
std::vector<SGVec3f>& points, std::vector<SGVec3f>& points)
std::vector<SGVec3f>& normals)
{ {
unsigned num = getNumTriangles(); unsigned num = getNumTriangles();
for (unsigned i = 0; i < num; ++i) { for (unsigned i = 0; i < num; ++i) {
@@ -283,11 +281,9 @@ public:
if (mt_rand(&seed) < img->getColor(x, y).g()) { if (mt_rand(&seed) < img->getColor(x, y).g()) {
// The red channel contains the rotation for this object // The red channel contains the rotation for this object
points.push_back(randomPoint); points.push_back(randomPoint);
normals.push_back(normalize(normal));
} }
} else { } else {
points.push_back(randomPoint); points.push_back(randomPoint);
normals.push_back(normalize(normal));
} }
} }
} }
+5 -11
View File
@@ -723,7 +723,6 @@ public:
BOOST_FOREACH(bin, randomForest) BOOST_FOREACH(bin, randomForest)
{ {
if ((bin->texture == mat->get_tree_texture() ) && if ((bin->texture == mat->get_tree_texture() ) &&
(bin->teffect == mat->get_tree_effect() ) &&
(bin->texture_varieties == mat->get_tree_varieties()) && (bin->texture_varieties == mat->get_tree_varieties()) &&
(bin->range == mat->get_tree_range() ) && (bin->range == mat->get_tree_range() ) &&
(bin->width == mat->get_tree_width() ) && (bin->width == mat->get_tree_width() ) &&
@@ -737,8 +736,6 @@ public:
bin = new TreeBin(); bin = new TreeBin();
bin->texture = mat->get_tree_texture(); bin->texture = mat->get_tree_texture();
SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture); SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
bin->teffect = mat->get_tree_effect();
SG_LOG(SG_INPUT, SG_DEBUG, "Tree effect " << bin->teffect);
bin->range = mat->get_tree_range(); bin->range = mat->get_tree_range();
bin->width = mat->get_tree_width(); bin->width = mat->get_tree_width();
bin->height = mat->get_tree_height(); bin->height = mat->get_tree_height();
@@ -747,19 +744,16 @@ public:
} }
std::vector<SGVec3f> randomPoints; std::vector<SGVec3f> randomPoints;
std::vector<SGVec3f> randomPointNormals;
matTris[i].addRandomTreePoints(wood_coverage, matTris[i].addRandomTreePoints(wood_coverage,
mat->get_one_object_mask(matTris[i].getTextureIndex()), mat->get_one_object_mask(matTris[i].getTextureIndex()),
vegetation_density, vegetation_density,
mat->get_cos_tree_max_density_slope_angle(), mat->get_cos_tree_max_density_slope_angle(),
mat->get_cos_tree_zero_density_slope_angle(), mat->get_cos_tree_zero_density_slope_angle(),
randomPoints, randomPoints);
randomPointNormals);
std::vector<SGVec3f>::iterator k; std::vector<SGVec3f>::iterator k;
std::vector<SGVec3f>::iterator j; for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
for (k = randomPoints.begin(), j = randomPointNormals.begin(); k != randomPoints.end(); ++k, ++j) { bin->insert(*k);
bin->insert(*k, *j);
} }
} }
} }
@@ -877,7 +871,7 @@ public:
lightGroup->addChild(groundLights2); lightGroup->addChild(groundLights2);
} }
if (! vasiLights.empty()) { if (vasiLights.empty()) {
EffectGeode* vasiGeode = new EffectGeode; EffectGeode* vasiGeode = new EffectGeode;
Effect* vasiEffect = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options); Effect* vasiEffect = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
vasiGeode->setEffect(vasiEffect); vasiGeode->setEffect(vasiEffect);
@@ -1143,4 +1137,4 @@ public:
SGDirectionalLightListBin holdshortLights; SGDirectionalLightListBin holdshortLights;
SGDirectionalLightListBin guardLights; SGDirectionalLightListBin guardLights;
SGDirectionalLightListBin reilLights; SGDirectionalLightListBin reilLights;
}; };
-4
View File
@@ -47,11 +47,7 @@ void ShaderGeometry::addObject(const Vec3& position, float scale,
void ShaderGeometry::drawImplementation(osg::RenderInfo& renderInfo) const void ShaderGeometry::drawImplementation(osg::RenderInfo& renderInfo) const
{ {
State& state = *renderInfo.getState(); State& state = *renderInfo.getState();
#if OSG_VERSION_LESS_THAN(3,3,4)
const Extensions* extensions = getExtensions(state.getContextID(), true); const Extensions* extensions = getExtensions(state.getContextID(), true);
#else
const GLExtensions* extensions = GLExtensions::Get(state.getContextID(), true);
#endif
Vec4Array::const_iterator citer = _posScaleArray->begin(); Vec4Array::const_iterator citer = _posScaleArray->begin();
Vec4Array::const_iterator cend = _posScaleArray->end(); Vec4Array::const_iterator cend = _posScaleArray->end();
FloatArray::const_iterator viter = _vertexAttribArray->begin(); FloatArray::const_iterator viter = _vertexAttribArray->begin();
+9 -47
View File
@@ -49,7 +49,6 @@
#include <simgear/scene/util/QuadTreeBuilder.hxx> #include <simgear/scene/util/QuadTreeBuilder.hxx>
#include <simgear/scene/util/RenderConstants.hxx> #include <simgear/scene/util/RenderConstants.hxx>
#include <simgear/scene/util/StateAttributeFactory.hxx> #include <simgear/scene/util/StateAttributeFactory.hxx>
#include <simgear/scene/util/SGReaderWriterOptions.hxx>
#include <simgear/structure/OSGUtils.hxx> #include <simgear/structure/OSGUtils.hxx>
#include "ShaderGeometry.hxx" #include "ShaderGeometry.hxx"
@@ -63,9 +62,6 @@ using namespace osg;
namespace simgear namespace simgear
{ {
bool use_tree_shadows;
bool use_tree_normals;
// Tree instance scheme: // Tree instance scheme:
// vertex - local position of quad vertex. // vertex - local position of quad vertex.
// normal - x y scaling, z number of varieties // normal - x y scaling, z number of varieties
@@ -168,24 +164,15 @@ Geometry* createTreeGeometry(float width, float height, int varieties)
// Positions // Positions
quadGeom->setColorArray(new Vec3Array); quadGeom->setColorArray(new Vec3Array);
quadGeom->setColorBinding(Geometry::BIND_PER_VERTEX); quadGeom->setColorBinding(Geometry::BIND_PER_VERTEX);
// Normals FloatArray* rotation = new FloatArray(2);
if (use_tree_shadows || use_tree_normals)
{
quadGeom->setSecondaryColorArray(new Vec3Array);
quadGeom->setSecondaryColorBinding(Geometry::BIND_PER_VERTEX);
}
FloatArray* rotation = new FloatArray(3);
(*rotation)[0] = 0.0; (*rotation)[0] = 0.0;
(*rotation)[1] = PI_2; (*rotation)[1] = PI_2;
if (use_tree_shadows) {(*rotation)[2] = -1.0;}
quadGeom->setFogCoordArray(rotation); quadGeom->setFogCoordArray(rotation);
quadGeom->setFogCoordBinding(Geometry::BIND_PER_PRIMITIVE_SET); quadGeom->setFogCoordBinding(Geometry::BIND_PER_PRIMITIVE_SET);
// The primitive sets render the same geometry, but the second // The primitive sets render the same geometry, but the second
// will rotated 90 degrees by the vertex shader, which uses the // will rotated 90 degrees by the vertex shader, which uses the
// fog coordinate as a rotation. // fog coordinate as a rotation.
int imax = 2; for (int i = 0; i < 2; ++i)
if (use_tree_shadows) {imax = 3;}
for (int i = 0; i < imax; ++i)
quadGeom->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS)); quadGeom->addPrimitiveSet(new DrawArrays(PrimitiveSet::QUADS));
return quadGeom; return quadGeom;
} }
@@ -197,17 +184,13 @@ EffectGeode* createTreeGeode(float width, float height, int varieties)
return result; return result;
} }
void addTreeToLeafGeode(Geode* geode, const SGVec3f& p, const SGVec3f& t) void addTreeToLeafGeode(Geode* geode, const SGVec3f& p)
{ {
Vec3 pos = toOsg(p); Vec3 pos = toOsg(p);
Vec3 ter = toOsg(t);
unsigned int numDrawables = geode->getNumDrawables(); unsigned int numDrawables = geode->getNumDrawables();
Geometry* geom Geometry* geom
= static_cast<Geometry*>(geode->getDrawable(numDrawables - 1)); = static_cast<Geometry*>(geode->getDrawable(numDrawables - 1));
Vec3Array* posArray = static_cast<Vec3Array*>(geom->getColorArray()); Vec3Array* posArray = static_cast<Vec3Array*>(geom->getColorArray());
Vec3Array* tnormalArray;
if (use_tree_shadows || use_tree_normals)
{tnormalArray = static_cast<Vec3Array*>(geom->getSecondaryColorArray());}
if (posArray->size() if (posArray->size()
>= static_cast<Vec3Array*>(geom->getVertexArray())->size()) { >= static_cast<Vec3Array*>(geom->getVertexArray())->size()) {
Vec3Array* paramsArray Vec3Array* paramsArray
@@ -215,17 +198,11 @@ void addTreeToLeafGeode(Geode* geode, const SGVec3f& p, const SGVec3f& t)
Vec3 params = (*paramsArray)[0]; Vec3 params = (*paramsArray)[0];
geom = createTreeGeometry(params.x(), params.y(), params.z()); geom = createTreeGeometry(params.x(), params.y(), params.z());
posArray = static_cast<Vec3Array*>(geom->getColorArray()); posArray = static_cast<Vec3Array*>(geom->getColorArray());
if (use_tree_shadows || use_tree_normals)
{tnormalArray = static_cast<Vec3Array*>(geom->getSecondaryColorArray());}
geode->addDrawable(geom); geode->addDrawable(geom);
} }
posArray->insert(posArray->end(), 4, pos); posArray->insert(posArray->end(), 4, pos);
if (use_tree_shadows || use_tree_normals)
{tnormalArray->insert(tnormalArray->end(),4,ter);}
size_t numVerts = posArray->size(); size_t numVerts = posArray->size();
int imax = 2; for (int i = 0; i < 2; ++i) {
if (use_tree_shadows) {imax = 3;}
for (int i = 0; i < imax; ++i) {
DrawArrays* primSet DrawArrays* primSet
= static_cast<DrawArrays*>(geom->getPrimitiveSet(i)); = static_cast<DrawArrays*>(geom->getPrimitiveSet(i));
primSet->setCount(numVerts); primSet->setCount(numVerts);
@@ -241,14 +218,14 @@ namespace
{ {
struct MakeTreesLeaf struct MakeTreesLeaf
{ {
MakeTreesLeaf(float range, int varieties, float width, float height, MakeTreesLeaf(float range, int varieties, float width, float height,
Effect* effect) : Effect* effect) :
_range(range), _varieties(varieties), _range(range), _varieties(varieties),
_width(width), _height(height), _effect(effect) {} _width(width), _height(height), _effect(effect) {}
MakeTreesLeaf(const MakeTreesLeaf& rhs) : MakeTreesLeaf(const MakeTreesLeaf& rhs) :
_range(rhs._range), _range(rhs._range),
_varieties(rhs._varieties), _width(rhs._width), _height(rhs._height), _varieties(rhs._varieties), _width(rhs._width), _height(rhs._height),
_effect(rhs._effect) _effect(rhs._effect)
{} {}
@@ -278,7 +255,7 @@ struct AddTreesLeafObject
void operator() (LOD* lod, const TreeBin::Tree& tree) const void operator() (LOD* lod, const TreeBin::Tree& tree) const
{ {
Geode* geode = static_cast<Geode*>(lod->getChild(int(tree.position.x() * 10.0f) % lod->getNumChildren())); Geode* geode = static_cast<Geode*>(lod->getChild(int(tree.position.x() * 10.0f) % lod->getNumChildren()));
addTreeToLeafGeode(geode, tree.position, tree.tnormal); addTreeToLeafGeode(geode, tree.position);
} }
}; };
@@ -300,8 +277,7 @@ struct TreeTransformer
TreeBin::Tree operator()(const TreeBin::Tree& tree) const TreeBin::Tree operator()(const TreeBin::Tree& tree) const
{ {
Vec3 pos = toOsg(tree.position); Vec3 pos = toOsg(tree.position);
Vec3 norm = toOsg(tree.tnormal); return TreeBin::Tree(toSG(pos * mat));
return TreeBin::Tree(toSG(pos * mat),toSG(norm * mat));
} }
Matrix mat; Matrix mat;
}; };
@@ -356,20 +332,6 @@ osg::Group* createForest(SGTreeBinList& forestList, const osg::Matrix& transform
MatrixTransform* mt = new MatrixTransform(transform); MatrixTransform* mt = new MatrixTransform(transform);
SGTreeBinList::iterator i; SGTreeBinList::iterator i;
use_tree_shadows = false;
use_tree_normals = false;
if (options) {
SGPropertyNode* propertyNode = options->getPropertyNode().get();
if (propertyNode) {
use_tree_shadows
= propertyNode->getBoolValue("/sim/rendering/random-vegetation-shadows",
use_tree_shadows);
use_tree_normals
= propertyNode->getBoolValue("/sim/rendering/random-vegetation-normals",
use_tree_normals);
}
}
for (i = forestList.begin(); i != forestList.end(); ++i) { for (i = forestList.begin(); i != forestList.end(); ++i) {
TreeBin* forest = *i; TreeBin* forest = *i;
@@ -381,7 +343,7 @@ osg::Group* createForest(SGTreeBinList& forestList, const osg::Matrix& transform
(!iter->second.lock(effect))) (!iter->second.lock(effect)))
{ {
SGPropertyNode_ptr effectProp = new SGPropertyNode; SGPropertyNode_ptr effectProp = new SGPropertyNode;
makeChild(effectProp, "inherits-from")->setStringValue(forest->teffect); makeChild(effectProp, "inherits-from")->setStringValue("Effects/tree");
SGPropertyNode* params = makeChild(effectProp, "parameters"); SGPropertyNode* params = makeChild(effectProp, "parameters");
// emphasize n = 0 // emphasize n = 0
params->getChild("texture", 0, true)->getChild("image", 0, true) params->getChild("texture", 0, true)->getChild("image", 0, true)
+5 -7
View File
@@ -36,10 +36,10 @@ namespace simgear
class TreeBin { class TreeBin {
public: public:
struct Tree { struct Tree {
SGVec3f position; Tree(const SGVec3f& p) :
SGVec3f tnormal; position(p)
Tree(const SGVec3f& p, const SGVec3f& t) : position(p),tnormal(t)
{ } { }
SGVec3f position;
}; };
typedef std::vector<Tree> TreeList; typedef std::vector<Tree> TreeList;
@@ -49,13 +49,11 @@ public:
float height; float height;
float width; float width;
std::string texture; std::string texture;
std::string teffect;
void insert(const Tree& t) void insert(const Tree& t)
{ _trees.push_back(t); } { _trees.push_back(t); }
void insert(const SGVec3f& p, int t, float s)
void insert(const SGVec3f& p, const SGVec3f& tnorm) { insert(Tree(p)); }
{insert(Tree(p,tnorm));}
unsigned getNumTrees() const unsigned getNumTrees() const
{ return _trees.size(); } { return _trees.size(); }
+69 -127
View File
@@ -70,7 +70,7 @@ static const bool svn_built_in_available = true;
using namespace simgear; using namespace simgear;
using namespace std; using namespace std;
const char* rsync_cmd = const char* rsync_cmd =
"rsync --verbose --archive --delete --perms --owner --group"; "rsync --verbose --archive --delete --perms --owner --group";
const char* svn_options = const char* svn_options =
@@ -121,30 +121,30 @@ public:
SharedModels, SharedModels,
AIData AIData
}; };
enum Status enum Status
{ {
Invalid = 0, Invalid = 0,
Waiting, Waiting,
Cached, ///< using already cached result Cached, ///< using already cached result
Updated, Updated,
NotFound, NotFound,
Failed Failed
}; };
SyncItem() : SyncItem() :
_dir(), _dir(),
_type(Stop), _type(Stop),
_status(Invalid) _status(Invalid)
{ {
} }
SyncItem(string dir, Type ty) : SyncItem(string dir, Type ty) :
_dir(dir), _dir(dir),
_type(ty), _type(ty),
_status(Waiting) _status(Waiting)
{} {}
string _dir; string _dir;
Type _type; Type _type;
Status _status; Status _status;
@@ -164,14 +164,14 @@ public:
isNewDirectory(false), isNewDirectory(false),
busy(false) busy(false)
{} {}
SyncItem currentItem; SyncItem currentItem;
bool isNewDirectory; bool isNewDirectory;
std::queue<SyncItem> queue; std::queue<SyncItem> queue;
std::auto_ptr<SVNRepository> repository; std::auto_ptr<SVNRepository> repository;
SGTimeStamp stamp; SGTimeStamp stamp;
bool busy; ///< is the slot working or idle bool busy; ///< is the slot working or idle
unsigned int nextWarnTimeout; unsigned int nextWarnTimeout;
}; };
@@ -193,49 +193,12 @@ static unsigned int syncSlotForType(SyncItem::Type ty)
return SYNC_SLOT_SHARED_DATA; return SYNC_SLOT_SHARED_DATA;
case SyncItem::AIData: case SyncItem::AIData:
return SYNC_SLOT_AI_DATA; return SYNC_SLOT_AI_DATA;
default: default:
return SYNC_SLOT_SHARED_DATA; return SYNC_SLOT_SHARED_DATA;
} }
} }
///////////////////////////////////////////////////////////////////////////////
// Base server query
///////////////////////////////////////////////////////////////////////////////
class ServerSelectQuery : public HTTP::Request
{
public:
ServerSelectQuery() :
HTTP::Request("http://scenery.flightgear.org/svn-server", "GET")
{
}
std::string svnUrl() const
{
std::string s = simgear::strutils::strip(m_url);
if (s.at(s.length() - 1) == '/') {
s = s.substr(0, s.length() - 1);
}
return s;
}
protected:
virtual void gotBodyData(const char* s, int n)
{
m_url.append(std::string(s, n));
}
virtual void onFail()
{
SG_LOG(SG_TERRAIN, SG_ALERT, "Failed to query TerraSync SVN server");
HTTP::Request::onFail();
}
private:
std::string m_url;
};
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// SGTerraSync::SvnThread ///////////////////////////////////////////////////// // SGTerraSync::SvnThread /////////////////////////////////////////////////////
@@ -257,7 +220,7 @@ public:
void setSvnServer(string server) { _svn_server = stripPath(server);} void setSvnServer(string server) { _svn_server = stripPath(server);}
void setSvnDataServer(string server) { _svn_data_server = stripPath(server);} void setSvnDataServer(string server) { _svn_data_server = stripPath(server);}
void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);} void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);} void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
void setLocalDir(string dir) { _local_dir = stripPath(dir);} void setLocalDir(string dir) { _local_dir = stripPath(dir);}
@@ -282,10 +245,10 @@ public:
volatile int _transfer_rate; volatile int _transfer_rate;
// kbytes, not bytes, because bytes might overflow 2^31 // kbytes, not bytes, because bytes might overflow 2^31
volatile int _total_kb_downloaded; volatile int _total_kb_downloaded;
private: private:
virtual void run(); virtual void run();
// external model run and helpers // external model run and helpers
void runExternal(); void runExternal();
void syncPathExternal(const SyncItem& next); void syncPathExternal(const SyncItem& next);
@@ -296,14 +259,14 @@ private:
void updateSyncSlot(SyncSlot& slot); void updateSyncSlot(SyncSlot& slot);
// commond helpers between both internal and external models // commond helpers between both internal and external models
SyncItem::Status isPathCached(const SyncItem& next) const; SyncItem::Status isPathCached(const SyncItem& next) const;
void initCompletedTilesPersistentCache(); void initCompletedTilesPersistentCache();
void writeCompletedTilesPersistentCache() const; void writeCompletedTilesPersistentCache() const;
void updated(SyncItem item, bool isNewDirectory); void updated(SyncItem item, bool isNewDirectory);
void fail(SyncItem failedItem); void fail(SyncItem failedItem);
void notFound(SyncItem notFoundItem); void notFound(SyncItem notFoundItem);
bool _use_built_in; bool _use_built_in;
HTTP::Client _http; HTTP::Client _http;
SyncSlot _syncSlots[NUM_SYNC_SLOTS]; SyncSlot _syncSlots[NUM_SYNC_SLOTS];
@@ -311,10 +274,10 @@ private:
volatile bool _is_dirty; volatile bool _is_dirty;
volatile bool _stop; volatile bool _stop;
SGBlockingDeque <SyncItem> waitingTiles; SGBlockingDeque <SyncItem> waitingTiles;
TileAgeCache _completedTiles; TileAgeCache _completedTiles;
TileAgeCache _notFoundItems; TileAgeCache _notFoundItems;
SGBlockingDeque <SyncItem> _freshTiles; SGBlockingDeque <SyncItem> _freshTiles;
bool _use_svn; bool _use_svn;
string _svn_server; string _svn_server;
@@ -400,7 +363,14 @@ bool SGTerraSync::SvnThread::start()
_use_svn |= _use_built_in; _use_svn |= _use_built_in;
if ((_use_svn)&&(_svn_server==""))
{
SG_LOG(SG_TERRAIN,SG_ALERT,
"Cannot start scenery download. Subversion scenery server is undefined.");
_fail_count++;
_stalled = true;
return false;
}
if ((!_use_svn)&&(_rsync_server=="")) if ((!_use_svn)&&(_rsync_server==""))
{ {
SG_LOG(SG_TERRAIN,SG_ALERT, SG_LOG(SG_TERRAIN,SG_ALERT,
@@ -467,7 +437,7 @@ bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
// windows command line parsing is just lovely... // windows command line parsing is just lovely...
// to allow white spaces, the system call needs this: // to allow white spaces, the system call needs this:
// ""C:\Program Files\something.exe" somearg "some other arg"" // ""C:\Program Files\something.exe" somearg "some other arg""
// Note: whitespace strings quoted by a pair of "" _and_ the // Note: whitespace strings quoted by a pair of "" _and_ the
// entire string needs to be wrapped by "" too. // entire string needs to be wrapped by "" too.
// The svn url needs forward slashes (/) as a path separator while // The svn url needs forward slashes (/) as a path separator while
// the local path needs windows-native backslash as a path separator. // the local path needs windows-native backslash as a path separator.
@@ -502,39 +472,13 @@ void SGTerraSync::SvnThread::run()
{ {
_active = true; _active = true;
initCompletedTilesPersistentCache(); initCompletedTilesPersistentCache();
{
if (_svn_server.empty()) {
SG_LOG(SG_TERRAIN,SG_INFO, "Querying closest TerraSync server");
ServerSelectQuery* ssq = new ServerSelectQuery;
HTTP::Request_ptr req = ssq;
_http.makeRequest(req);
while (!req->isComplete()) {
_http.update(20);
}
if (req->readyState() == HTTP::Request::DONE) {
_svn_server = ssq->svnUrl();
SG_LOG(SG_TERRAIN,SG_INFO, "Closest TerraSync server:" << _svn_server);
} else {
SG_LOG(SG_TERRAIN,SG_WARN, "Failed to query closest TerraSync server");
}
} else {
SG_LOG(SG_TERRAIN,SG_INFO, "Explicit: TerraSync server:" << _svn_server);
}
if (_svn_server.empty()) {
// default value
_svn_server = "http://foxtrot.mgras.net:8080/terrascenery/trunk/data/Scenery";
}
}
if (_use_built_in) { if (_use_built_in) {
runInternal(); runInternal();
} else { } else {
runExternal(); runExternal();
} }
_active = false; _active = false;
_running = false; _running = false;
_is_dirty = true; _is_dirty = true;
@@ -558,7 +502,7 @@ void SGTerraSync::SvnThread::runExternal()
_is_dirty = true; _is_dirty = true;
continue; continue;
} }
syncPathExternal(next); syncPathExternal(next);
if ((_allowed_errors >= 0)&& if ((_allowed_errors >= 0)&&
@@ -576,7 +520,7 @@ void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
SGPath path( _local_dir ); SGPath path( _local_dir );
path.append( next._dir ); path.append( next._dir );
bool isNewDirectory = !path.exists(); bool isNewDirectory = !path.exists();
try { try {
if (isNewDirectory) { if (isNewDirectory) {
int rc = path.create_dir( 0755 ); int rc = path.create_dir( 0755 );
@@ -586,7 +530,7 @@ void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
throw sg_exception("Cannot create directory for terrasync", path.str()); throw sg_exception("Cannot create directory for terrasync", path.str());
} }
} }
if (!runExternalSyncCommand(next._dir.c_str())) { if (!runExternalSyncCommand(next._dir.c_str())) {
throw sg_exception("Running external sync command failed"); throw sg_exception("Running external sync command failed");
} }
@@ -595,7 +539,7 @@ void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
_busy = false; _busy = false;
return; return;
} }
updated(next, isNewDirectory); updated(next, isNewDirectory);
_busy = false; _busy = false;
} }
@@ -604,7 +548,7 @@ void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
{ {
if (slot.repository.get()) { if (slot.repository.get()) {
if (slot.repository->isDoingSync()) { if (slot.repository->isDoingSync()) {
#if 1 #if 0
if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) { if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) {
SG_LOG(SG_TERRAIN, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec()); SG_LOG(SG_TERRAIN, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
SG_LOG(SG_TERRAIN, SG_INFO, "HTTP status:" << _http.hasActiveRequests()); SG_LOG(SG_TERRAIN, SG_INFO, "HTTP status:" << _http.hasActiveRequests());
@@ -613,7 +557,7 @@ void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
#endif #endif
return; // easy, still working return; // easy, still working
} }
// check result // check result
SVNRepository::ResultCode res = slot.repository->failure(); SVNRepository::ResultCode res = slot.repository->failure();
if (res == SVNRepository::SVN_ERROR_NOT_FOUND) { if (res == SVNRepository::SVN_ERROR_NOT_FOUND) {
@@ -630,12 +574,12 @@ void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
slot.busy = false; slot.busy = false;
slot.repository.reset(); slot.repository.reset();
} }
// init and start sync of the next repository // init and start sync of the next repository
if (!slot.queue.empty()) { if (!slot.queue.empty()) {
slot.currentItem = slot.queue.front(); slot.currentItem = slot.queue.front();
slot.queue.pop(); slot.queue.pop();
SGPath path(_local_dir); SGPath path(_local_dir);
path.append(slot.currentItem._dir); path.append(slot.currentItem._dir);
slot.isNewDirectory = !path.exists(); slot.isNewDirectory = !path.exists();
@@ -648,20 +592,20 @@ void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
return; return;
} }
} // of creating directory step } // of creating directory step
string serverUrl(_svn_server); string serverUrl(_svn_server);
if (slot.currentItem._type == SyncItem::AIData) { if (slot.currentItem._type == SyncItem::AIData) {
serverUrl = _svn_data_server; serverUrl = _svn_data_server;
} }
slot.repository.reset(new SVNRepository(path, &_http)); slot.repository.reset(new SVNRepository(path, &_http));
slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir); slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir);
slot.repository->update(); slot.repository->update();
slot.nextWarnTimeout = 20000; slot.nextWarnTimeout = 20000;
slot.stamp.stamp(); slot.stamp.stamp();
slot.busy = true; slot.busy = true;
SG_LOG(SG_TERRAIN, SG_INFO, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size()); SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
} }
} }
@@ -672,10 +616,10 @@ void SGTerraSync::SvnThread::runInternal()
_transfer_rate = _http.transferRateBytesPerSec(); _transfer_rate = _http.transferRateBytesPerSec();
// convert from bytes to kbytes // convert from bytes to kbytes
_total_kb_downloaded = static_cast<int>(_http.totalBytesDownloaded() / 1024); _total_kb_downloaded = static_cast<int>(_http.totalBytesDownloaded() / 1024);
if (_stop) if (_stop)
break; break;
// drain the waiting tiles queue into the sync slot queues. // drain the waiting tiles queue into the sync slot queues.
while (!waitingTiles.empty()) { while (!waitingTiles.empty()) {
SyncItem next = waitingTiles.pop_front(); SyncItem next = waitingTiles.pop_front();
@@ -692,7 +636,7 @@ void SGTerraSync::SvnThread::runInternal()
unsigned int slot = syncSlotForType(next._type); unsigned int slot = syncSlotForType(next._type);
_syncSlots[slot].queue.push(next); _syncSlots[slot].queue.push(next);
} }
bool anySlotBusy = false; bool anySlotBusy = false;
// update each sync slot in turn // update each sync slot in turn
for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) { for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
@@ -719,7 +663,7 @@ SyncItem::Status SGTerraSync::SvnThread::isPathCached(const SyncItem& next) cons
// higher levels the cache status // higher levels the cache status
return (ii == _notFoundItems.end()) ? SyncItem::Invalid : SyncItem::NotFound; return (ii == _notFoundItems.end()) ? SyncItem::Invalid : SyncItem::NotFound;
} }
// check if the path still physically exists. This is needed to // check if the path still physically exists. This is needed to
// cope with the user manipulating our cache dir // cope with the user manipulating our cache dir
SGPath p(_local_dir); SGPath p(_local_dir);
@@ -727,7 +671,7 @@ SyncItem::Status SGTerraSync::SvnThread::isPathCached(const SyncItem& next) cons
if (!p.exists()) { if (!p.exists()) {
return SyncItem::Invalid; return SyncItem::Invalid;
} }
time_t now = time(0); time_t now = time(0);
return (ii->second > now) ? SyncItem::Cached : SyncItem::Invalid; return (ii->second > now) ? SyncItem::Cached : SyncItem::Invalid;
} }
@@ -739,8 +683,6 @@ void SGTerraSync::SvnThread::fail(SyncItem failedItem)
_fail_count++; _fail_count++;
failedItem._status = SyncItem::Failed; failedItem._status = SyncItem::Failed;
_freshTiles.push_back(failedItem); _freshTiles.push_back(failedItem);
SG_LOG(SG_TERRAIN,SG_INFO,
"Faield to sync'" << failedItem._dir << "'");
_completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt; _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
_is_dirty = true; _is_dirty = true;
} }
@@ -751,7 +693,7 @@ void SGTerraSync::SvnThread::notFound(SyncItem item)
// as succesful download. Important for MP models and similar so // as succesful download. Important for MP models and similar so
// we don't spam the server with lookups for models that don't // we don't spam the server with lookups for models that don't
// exist // exist
time_t now = time(0); time_t now = time(0);
item._status = SyncItem::NotFound; item._status = SyncItem::NotFound;
_freshTiles.push_back(item); _freshTiles.push_back(item);
@@ -767,7 +709,7 @@ void SGTerraSync::SvnThread::updated(SyncItem item, bool isNewDirectory)
_success_count++; _success_count++;
SG_LOG(SG_TERRAIN,SG_INFO, SG_LOG(SG_TERRAIN,SG_INFO,
"Successfully synchronized directory '" << item._dir << "'"); "Successfully synchronized directory '" << item._dir << "'");
item._status = SyncItem::Updated; item._status = SyncItem::Updated;
if (item._type == SyncItem::Tile) { if (item._type == SyncItem::Tile) {
_updated_tile_count++; _updated_tile_count++;
@@ -784,17 +726,17 @@ void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
if (!_persistentCachePath.exists()) { if (!_persistentCachePath.exists()) {
return; return;
} }
SGPropertyNode_ptr cacheRoot(new SGPropertyNode); SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
time_t now = time(0); time_t now = time(0);
try { try {
readProperties(_persistentCachePath.str(), cacheRoot); readProperties(_persistentCachePath.str(), cacheRoot);
} catch (sg_exception& e) { } catch (sg_exception& e) {
SG_LOG(SG_TERRAIN, SG_INFO, "corrupted persistent cache, discarding"); SG_LOG(SG_TERRAIN, SG_INFO, "corrupted persistent cache, discarding");
return; return;
} }
for (int i=0; i<cacheRoot->nChildren(); ++i) { for (int i=0; i<cacheRoot->nChildren(); ++i) {
SGPropertyNode* entry = cacheRoot->getChild(i); SGPropertyNode* entry = cacheRoot->getChild(i);
bool isNotFound = (strcmp(entry->getName(), "not-found") == 0); bool isNotFound = (strcmp(entry->getName(), "not-found") == 0);
@@ -803,7 +745,7 @@ void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
if (stamp < now) { if (stamp < now) {
continue; continue;
} }
if (isNotFound) { if (isNotFound) {
_completedTiles[tileName] = stamp; _completedTiles[tileName] = stamp;
} else { } else {
@@ -818,12 +760,12 @@ void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
if (_persistentCachePath.isNull()) { if (_persistentCachePath.isNull()) {
return; return;
} }
std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc); std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
if (!f.is_open()) { if (!f.is_open()) {
return; return;
} }
SGPropertyNode_ptr cacheRoot(new SGPropertyNode); SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
TileAgeCache::const_iterator it = _completedTiles.begin(); TileAgeCache::const_iterator it = _completedTiles.begin();
for (; it != _completedTiles.end(); ++it) { for (; it != _completedTiles.end(); ++it) {
@@ -831,14 +773,14 @@ void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
entry->setStringValue("path", it->first); entry->setStringValue("path", it->first);
entry->setIntValue("stamp", it->second); entry->setIntValue("stamp", it->second);
} }
it = _notFoundItems.begin(); it = _notFoundItems.begin();
for (; it != _notFoundItems.end(); ++it) { for (; it != _notFoundItems.end(); ++it) {
SGPropertyNode* entry = cacheRoot->addChild("not-found"); SGPropertyNode* entry = cacheRoot->addChild("not-found");
entry->setStringValue("path", it->first); entry->setStringValue("path", it->first);
entry->setIntValue("stamp", it->second); entry->setIntValue("stamp", it->second);
} }
writeProperties(f, cacheRoot, true /* write_all */); writeProperties(f, cacheRoot, true /* write_all */);
f.close(); f.close();
} }
@@ -854,7 +796,7 @@ SGTerraSync::SGTerraSync() :
_svnThread = new SvnThread(); _svnThread = new SvnThread();
_log = new BufferedLogCallback(SG_TERRAIN, SG_INFO); _log = new BufferedLogCallback(SG_TERRAIN, SG_INFO);
_log->truncateAt(255); _log->truncateAt(255);
sglog().addCallback(_log); sglog().addCallback(_log);
} }
@@ -877,12 +819,12 @@ void SGTerraSync::init()
if (_inited) { if (_inited) {
return; return;
} }
_inited = true; _inited = true;
assert(_terraRoot); assert(_terraRoot);
_terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available); _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
reinit(); reinit();
} }
@@ -899,7 +841,7 @@ void SGTerraSync::reinit()
{ {
return; return;
} }
_svnThread->stop(); _svnThread->stop();
if (_terraRoot->getBoolValue("enabled",false)) if (_terraRoot->getBoolValue("enabled",false))
@@ -929,7 +871,7 @@ void SGTerraSync::bind()
if (_bound) { if (_bound) {
return; return;
} }
_bound = true; _bound = true;
_tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy ); _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
_tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active ); _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
@@ -938,11 +880,11 @@ void SGTerraSync::bind()
_tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count ); _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
_tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits ); _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
_tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate ); _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
// use kbytes here because propety doesn't support 64-bit and we might conceivably // use kbytes here because propety doesn't support 64-bit and we might conceivably
// download more than 2G in a single session // download more than 2G in a single session
_tiedProperties.Tie( _terraRoot->getNode("downloaded-kbytes", true), (int*) &_svnThread->_total_kb_downloaded ); _tiedProperties.Tie( _terraRoot->getNode("downloaded-kbytes", true), (int*) &_svnThread->_total_kb_downloaded );
_terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false); _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
_terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false); _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
_terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false); _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
@@ -962,7 +904,7 @@ void SGTerraSync::unbind()
_tiedProperties.Untie(); _tiedProperties.Untie();
_bound = false; _bound = false;
_inited = false; _inited = false;
_terraRoot.clear(); _terraRoot.clear();
_stalledNode.clear(); _stalledNode.clear();
_cacheHits.clear(); _cacheHits.clear();
@@ -992,7 +934,7 @@ void SGTerraSync::update(double)
while (_svnThread->hasNewTiles()) while (_svnThread->hasNewTiles())
{ {
SyncItem next = _svnThread->getNewTile(); SyncItem next = _svnThread->getNewTile();
if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) { if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) {
_activeTileDirs.erase(next._dir); _activeTileDirs.erase(next._dir);
} }
@@ -1016,7 +958,7 @@ void SGTerraSync::syncAirportsModels()
_svnThread->request( w ); _svnThread->request( w );
} }
} }
SyncItem w("Models", SyncItem::SharedModels); SyncItem w("Models", SyncItem::SharedModels);
_svnThread->request( w ); _svnThread->request( w );
} }
@@ -1030,7 +972,7 @@ void SGTerraSync::syncAreaByPath(const std::string& aPath)
if (_activeTileDirs.find(dir) != _activeTileDirs.end()) { if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
continue; continue;
} }
_activeTileDirs.insert(dir); _activeTileDirs.insert(dir);
SyncItem w(dir, SyncItem::Tile); SyncItem w(dir, SyncItem::Tile);
_svnThread->request( w ); _svnThread->request( w );
@@ -1049,7 +991,7 @@ bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
if (!_svnThread->_running) { if (!_svnThread->_running) {
return false; return false;
} }
const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 }; const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
for (const char** tree = &terrainobjects[0]; *tree; tree++) { for (const char** tree = &terrainobjects[0]; *tree; tree++) {
string s = *tree + sceneryDir; string s = *tree + sceneryDir;
@@ -1066,7 +1008,7 @@ void SGTerraSync::scheduleDataDir(const std::string& dataDir)
if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) { if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) {
return; return;
} }
_activeTileDirs.insert(dataDir); _activeTileDirs.insert(dataDir);
SyncItem w(dataDir, SyncItem::AIData); SyncItem w(dataDir, SyncItem::AIData);
_svnThread->request( w ); _svnThread->request( w );
@@ -1078,7 +1020,7 @@ bool SGTerraSync::isDataDirPending(const std::string& dataDir) const
if (!_svnThread->_running) { if (!_svnThread->_running) {
return false; return false;
} }
return (_activeTileDirs.find(dataDir) != _activeTileDirs.end()); return (_activeTileDirs.find(dataDir) != _activeTileDirs.end());
} }
-22
View File
@@ -25,13 +25,11 @@
#include "SGSceneFeatures.hxx" #include "SGSceneFeatures.hxx"
#include <osg/Version>
#include <osg/FragmentProgram> #include <osg/FragmentProgram>
#include <osg/VertexProgram> #include <osg/VertexProgram>
#include <osg/Point> #include <osg/Point>
#include <osg/PointSprite> #include <osg/PointSprite>
#include <osg/Texture> #include <osg/Texture>
#include <osg/GLExtensions>
#include <OpenThreads/Mutex> #include <OpenThreads/Mutex>
#include <OpenThreads/ScopedLock> #include <OpenThreads/ScopedLock>
@@ -86,18 +84,12 @@ SGSceneFeatures::setTextureCompression(osg::Texture* texture) const
bool bool
SGSceneFeatures::getHavePointSprites(unsigned contextId) const SGSceneFeatures::getHavePointSprites(unsigned contextId) const
{ {
#if OSG_VERSION_LESS_THAN(3,3,4)
return osg::PointSprite::isPointSpriteSupported(contextId); return osg::PointSprite::isPointSpriteSupported(contextId);
#else
const osg::GLExtensions* ex = osg::GLExtensions::Get(contextId, true);
return ex && ex->isPointSpriteSupported;
#endif
} }
bool bool
SGSceneFeatures::getHaveFragmentPrograms(unsigned contextId) const SGSceneFeatures::getHaveFragmentPrograms(unsigned contextId) const
{ {
#if OSG_VERSION_LESS_THAN(3,3,4)
const osg::FragmentProgram::Extensions* fpe; const osg::FragmentProgram::Extensions* fpe;
fpe = osg::FragmentProgram::getExtensions(contextId, true); fpe = osg::FragmentProgram::getExtensions(contextId, true);
if (!fpe) if (!fpe)
@@ -106,16 +98,11 @@ SGSceneFeatures::getHaveFragmentPrograms(unsigned contextId) const
return false; return false;
return true; return true;
#else
const osg::GLExtensions* ex = osg::GLExtensions::Get(contextId, true);
return ex && ex->isFragmentProgramSupported;
#endif
} }
bool bool
SGSceneFeatures::getHaveVertexPrograms(unsigned contextId) const SGSceneFeatures::getHaveVertexPrograms(unsigned contextId) const
{ {
#if OSG_VERSION_LESS_THAN(3,3,4)
const osg::VertexProgram::Extensions* vpe; const osg::VertexProgram::Extensions* vpe;
vpe = osg::VertexProgram::getExtensions(contextId, true); vpe = osg::VertexProgram::getExtensions(contextId, true);
if (!vpe) if (!vpe)
@@ -124,10 +111,6 @@ SGSceneFeatures::getHaveVertexPrograms(unsigned contextId) const
return false; return false;
return true; return true;
#else
const osg::GLExtensions* ex = osg::GLExtensions::Get(contextId, true);
return ex && ex->isVertexProgramSupported;
#endif
} }
bool bool
@@ -141,7 +124,6 @@ SGSceneFeatures::getHaveShaderPrograms(unsigned contextId) const
bool bool
SGSceneFeatures::getHavePointParameters(unsigned contextId) const SGSceneFeatures::getHavePointParameters(unsigned contextId) const
{ {
#if OSG_VERSION_LESS_THAN(3,3,4)
const osg::Point::Extensions* pe; const osg::Point::Extensions* pe;
pe = osg::Point::getExtensions(contextId, true); pe = osg::Point::getExtensions(contextId, true);
if (!pe) if (!pe)
@@ -149,9 +131,5 @@ SGSceneFeatures::getHavePointParameters(unsigned contextId) const
if (!pe->isPointParametersSupported()) if (!pe->isPointParametersSupported())
return false; return false;
return true; return true;
#else
const osg::GLExtensions* ex = osg::GLExtensions::Get(contextId, true);
return ex && ex->isPointParametersSupported;
#endif
} }
+4 -7
View File
@@ -401,9 +401,8 @@ void SGSampleGroup::set_volume( float vol )
// set the source position and orientation of all managed sounds // set the source position and orientation of all managed sounds
void SGSampleGroup::update_pos_and_orientation() { void SGSampleGroup::update_pos_and_orientation() {
SGVec3d base_position = SGVec3d::fromGeod(_base_pos); SGVec3d position = SGVec3d::fromGeod(_base_pos) - _smgr->get_position();
SGVec3d smgr_position = _smgr->get_position();
SGQuatd hlOr = SGQuatd::fromLonLat(_base_pos); SGQuatd hlOr = SGQuatd::fromLonLat(_base_pos);
SGQuatd ec2body = hlOr*_orientation; SGQuatd ec2body = hlOr*_orientation;
@@ -419,14 +418,12 @@ void SGSampleGroup::update_pos_and_orientation() {
sample->set_master_volume( _volume ); sample->set_master_volume( _volume );
sample->set_orientation( _orientation ); sample->set_orientation( _orientation );
sample->set_rotation( ec2body ); sample->set_rotation( ec2body );
sample->set_position(base_position); sample->set_position( position );
sample->set_velocity( velocity ); sample->set_velocity( velocity );
// Test if a sample is farther away than max distance, if so // Test if a sample is farther away than max distance, if so
// stop the sound playback and free it's source. // stop the sound playback and free it's source.
if (!_tied_to_listener) { if (!_tied_to_listener) {
sample->update_pos_and_orientation();
SGVec3d position = sample->get_position() - smgr_position;
float max2 = sample->get_max_dist() * sample->get_max_dist(); float max2 = sample->get_max_dist() * sample->get_max_dist();
float dist2 = position[0]*position[0] float dist2 = position[0]*position[0]
+ position[1]*position[1] + position[2]*position[2]; + position[1]*position[1] + position[2]*position[2];
@@ -452,7 +449,7 @@ void SGSampleGroup::update_sample_config( SGSoundSample *sample )
} else { } else {
sample->update_pos_and_orientation(); sample->update_pos_and_orientation();
orientation = sample->get_orientation(); orientation = sample->get_orientation();
position = sample->get_position() - _smgr->get_position(); position = sample->get_position();
velocity = sample->get_velocity(); velocity = sample->get_velocity();
} }
+1 -1
View File
@@ -116,7 +116,7 @@ void SampleHistogram::reset ()
this->SampleStatistic::reset (); this->SampleStatistic::reset ();
if (howManyBuckets > 0) if (howManyBuckets > 0)
{ {
for (int i = 0; i < howManyBuckets; i++) for (register int i = 0; i < howManyBuckets; i++)
{ {
bucketCount[i] = 0; bucketCount[i] = 0;
} }
+4 -4
View File
@@ -439,9 +439,9 @@ void StateMachine::initFromPlist(SGPropertyNode* desc, SGPropertyNode* root)
std::string nm = stateDesc->getStringValue("name"); std::string nm = stateDesc->getStringValue("name");
State_ptr st(new State(nm)); State_ptr st(new State(nm));
readBindingList(stateDesc, "enter", root, st->d->_entryBindings); readBindingList(stateDesc, "enter", root, st->d->_updateBindings);
readBindingList(stateDesc, "update", root, st->d->_updateBindings); readBindingList(stateDesc, "exit", root, st->d->_entryBindings);
readBindingList(stateDesc, "exit", root, st->d->_exitBindings); readBindingList(stateDesc, "update", root, st->d->_exitBindings);
addState(st); addState(st);
} // of states iteration } // of states iteration
@@ -456,7 +456,7 @@ void StateMachine::initFromPlist(SGPropertyNode* desc, SGPropertyNode* root)
t->setTriggerCondition(cond); t->setTriggerCondition(cond);
t->setExcludeTarget(tDesc->getBoolValue("exclude-target", true)); t->setExcludeTarget(tDesc->getBoolValue("exclude-target", true));
BOOST_FOREACH(SGPropertyNode* src, tDesc->getChildren("source")) { BOOST_FOREACH(SGPropertyNode* src, desc->getChildren("source")) {
State_ptr srcState = findStateByName(src->getStringValue()); State_ptr srcState = findStateByName(src->getStringValue());
t->addSourceState(srcState); t->addSourceState(srcState);
} }
+1 -4
View File
@@ -58,11 +58,8 @@ void SGEventMgr::unbind()
void SGEventMgr::init() void SGEventMgr::init()
{ {
if (_inited) { if (_inited) {
// protected against duplicate calls here, in case SG_LOG(SG_GENERAL, SG_WARN, "duplicate init of SGEventMgr");
// init ever does something more complex in the future.
return;
} }
_inited = true; _inited = true;
} }
+19 -19
View File
@@ -47,7 +47,7 @@
/* BIG FAT WARNING: NOTICE THAT I HARDCODED ENDIANNES. PLEASE CHANGE THIS */ /* BIG FAT WARNING: NOTICE THAT I HARDCODED ENDIANNES. PLEASE CHANGE THIS */
#ifndef BIG_ENDIAN #ifndef BIG_ENDIAN
#define BIG_ENDIAN 4321 #define BIG_ENDIAN 4321
#endif #endif
@@ -55,13 +55,13 @@
#define LITTLE_ENDIAN 1234 #define LITTLE_ENDIAN 1234
#endif #endif
#ifndef BYTE_ORDER #ifndef BYTE_ORDER
#define BYTE_ORDER LITTLE_ENDIAN #define BYTE_ORDER LITTLE_ENDIAN
#endif #endif
#ifndef BYTE_ORDER #ifndef BYTE_ORDER
#define BYTE_ORDER #define BYTE_ORDER
#endif #endif
/* END OF BIG FAT WARNING */ /* END OF BIG FAT WARNING */
@@ -267,7 +267,7 @@ void show(const char *zone, time_t t, int v)
static char *abbr(struct tm *tmp) static char *abbr(struct tm *tmp)
{ {
char * result; register char * result;
static char nada; static char nada;
if (tmp->tm_isdst != 0 && tmp->tm_isdst != 1) if (tmp->tm_isdst != 0 && tmp->tm_isdst != 1)
@@ -329,21 +329,21 @@ static void fgtzset_internal (int always, const char *tz)
fgtzfile_read (tz); fgtzfile_read (tz);
if (use_fgtzfile) if (use_fgtzfile)
return; return;
// The default behaviour of the original tzset_internal (int always, char* tz) // The default behaviour of the original tzset_internal (int always, char* tz)
// function is to set up a default timezone, in any case file_read() fails // function is to set up a default timezone, in any case file_read() fails
// Currently this leads to problems, because it modifies the system timezone // Currently this leads to problems, because it modifies the system timezone
// and not the local aircraft timezone, contained in FlightGear. I could adapt // and not the local aircraft timezone, contained in FlightGear. I could adapt
// this in future versions of this code, but doubt whether this is what we really // this in future versions of this code, but doubt whether this is what we really
// want. So right now, throw an exception when timezone information reading failed. // want. So right now, throw an exception when timezone information reading failed.
// Guess I'll change that to something like 12 * (FG_LON / 180.0) // Guess I'll change that to something like 12 * (FG_LON / 180.0)
// //
// For now, I'll leave it like this. // For now, I'll leave it like this.
else else
{ {
throw sg_exception("Timezone reading failed"); throw sg_exception("Timezone reading failed");
} }
// this emacs "comment out" function is cool! // this emacs "comment out" function is cool!
// // /* No data file found. Default to UTC if nothing specified. */ // // /* No data file found. Default to UTC if nothing specified. */
// // printf ("1. Current local time = %24s", asctime(localtime(&now))); // // printf ("1. Current local time = %24s", asctime(localtime(&now)));
// if (tz == NULL || *tz == '\0') // if (tz == NULL || *tz == '\0')
@@ -580,7 +580,7 @@ static void fgtzset_internal (int always, const char *tz)
// tzr->computed_for = -1; // tzr->computed_for = -1;
// } // }
// // printf ("10. Current local time = %24s", asctime(localtime(&now))); // // printf ("10. Current local time = %24s", asctime(localtime(&now)));
// //
} }
/************************************************************************/ /************************************************************************/
@@ -627,7 +627,7 @@ static int fgcompute_change (fgtz_rule *rule, int year)
// tz_rule *rule; // tz_rule *rule;
// int year; // int year;
{ {
time_t t; register time_t t;
int y; int y;
if (year != -1 && rule->computed_for == year) if (year != -1 && rule->computed_for == year)
@@ -660,8 +660,8 @@ static int fgcompute_change (fgtz_rule *rule, int year)
case fgtz_rule::M: case fgtz_rule::M:
/* Mm.n.d - Nth "Dth day" of month M. */ /* Mm.n.d - Nth "Dth day" of month M. */
{ {
int i, d, m1, yy0, yy1, yy2, dow; register int i, d, m1, yy0, yy1, yy2, dow;
const unsigned short int *myday = register const unsigned short int *myday =
&mon_yday[isleap (year)][rule->m]; &mon_yday[isleap (year)][rule->m];
/* First add SECSPERDAY for each day in months before M. */ /* First add SECSPERDAY for each day in months before M. */
@@ -707,7 +707,7 @@ static int fgcompute_change (fgtz_rule *rule, int year)
int fgtzfile_compute (time_t timer, int use_localtime, int fgtzfile_compute (time_t timer, int use_localtime,
long int *leap_correct, int *leap_hit) long int *leap_correct, int *leap_hit)
{ {
size_t i; register size_t i;
if (use_localtime) if (use_localtime)
{ {
@@ -788,10 +788,10 @@ void fgtzfile_read (const char *file)
{ {
// static const char default_tzdir[] = TZDIR; // static const char default_tzdir[] = TZDIR;
size_t num_isstd, num_isgmt; size_t num_isstd, num_isgmt;
FILE *f; register FILE *f;
struct tzhead tzhead; struct tzhead tzhead;
size_t chars; size_t chars;
size_t i; register size_t i;
struct ttinfo *info; struct ttinfo *info;
use_fgtzfile = 0; use_fgtzfile = 0;
@@ -1046,8 +1046,8 @@ void offtime (const time_t *t, long int offset, struct tm *tp)
// long int offset; // long int offset;
// struct tm *tp; // struct tm *tp;
{ {
long int days, rem, y; register long int days, rem, y;
const unsigned short int *ip; register const unsigned short int *ip;
days = *t / SECS_PER_DAY; days = *t / SECS_PER_DAY;
rem = *t % SECS_PER_DAY; rem = *t % SECS_PER_DAY;
@@ -1145,7 +1145,7 @@ time_t sgGMTime()
// http://linux.die.net/man/3/timegm // http://linux.die.net/man/3/timegm
// but for the moment we'll assume time(0) on Unix is UTC, and hence we // but for the moment we'll assume time(0) on Unix is UTC, and hence we
// return it directly. // return it directly.
time_t now_sec = time(0); time_t now_sec = time(0);
#if defined(SG_WINDOWS) #if defined(SG_WINDOWS)
struct tm now; struct tm now;
+1 -1
View File
@@ -1 +1 @@
3.6.0 3.4.0