Building with clean SGPath API

This commit is contained in:
James Turner
2016-06-22 18:09:47 +01:00
parent 38c8931950
commit f21eac8473
30 changed files with 301 additions and 298 deletions

View File

@@ -227,9 +227,7 @@ std::string SGBucket::gen_base_path() const {
hem, top_lon, pole, top_lat,
hem, main_lon, pole, main_lat);
SGPath path( raw_path );
return path.str();
return raw_path;
}

View File

@@ -36,9 +36,10 @@
#include <simgear/threads/SGQueue.hxx>
#include <simgear/threads/SGGuard.hxx>
#include <simgear/misc/sgstream.hxx>
#include <simgear/misc/sg_path.hxx>
#if defined (SG_WINDOWS)
#if defined (SG_WINDOWS)
// for AllocConsole, OutputDebugString
#include <windows.h>
#endif
@@ -106,10 +107,10 @@ void LogCallback::setLogLevels( sgDebugClass c, sgDebugPriority p )
class FileLogCallback : public simgear::LogCallback
{
public:
FileLogCallback(const std::string& aPath, sgDebugClass c, sgDebugPriority p) :
simgear::LogCallback(c, p),
m_file(aPath.c_str(), std::ios_base::out | std::ios_base::trunc)
FileLogCallback(const SGPath& aPath, sgDebugClass c, sgDebugPriority p) :
simgear::LogCallback(c, p)
{
m_file.open(aPath, std::ios_base::out | std::ios_base::trunc);
}
virtual void operator()(sgDebugClass c, sgDebugPriority p,
@@ -120,7 +121,7 @@ public:
<< ":" << file << ":" << line << ":" << message << std::endl;
}
private:
std::ofstream m_file;
sg_ofstream m_file;
};
class StderrLogCallback : public simgear::LogCallback
@@ -232,7 +233,7 @@ public:
// attach failed, don't install the callback
addStderr = false;
}
if (!isFile) {
// No - OK! now set streams to attached console
freopen("conout$", "w", stdout);
@@ -443,7 +444,7 @@ sglog()
void
logstream::logToFile( const SGPath& aPath, sgDebugClass c, sgDebugPriority p )
{
global_privateLogstream->addCallback(new FileLogCallback(aPath.str(), c, p));
global_privateLogstream->addCallback(new FileLogCallback(aPath, c, p));
}
namespace simgear

View File

@@ -55,12 +55,11 @@ bool SGStarData::load( const SGPath& path ) {
// build the full path name to the stars data base file
SGPath tmp = path;
tmp.append( "stars" );
SG_LOG( SG_ASTRO, SG_INFO, " Loading stars from " << tmp.str() );
SG_LOG( SG_ASTRO, SG_INFO, " Loading stars from " << tmp );
sg_gzifstream in( tmp.str() );
sg_gzifstream in( tmp );
if ( ! in.is_open() ) {
SG_LOG( SG_ASTRO, SG_ALERT, "Cannot open star file: "
<< tmp.str() );
SG_LOG( SG_ASTRO, SG_ALERT, "Cannot open star file: " << tmp );
return false;
}

View File

@@ -224,11 +224,11 @@ public:
std::string url() const
{
if (_relativePath.str().empty()) {
if (_relativePath.empty()) {
return _repository->baseUrl;
}
return _repository->baseUrl + "/" + _relativePath.str();
return _repository->baseUrl + "/" + _relativePath;
}
void dirIndexUpdated(const std::string& hash)
@@ -247,7 +247,7 @@ public:
void failedToUpdate(HTTPRepository::ResultCode status)
{
_state = UpdateFailed;
if (_relativePath.isNull()) {
if (_relativePath.empty()) {
// root dir failed
_repository->failedToGetRootIndex(status);
} else {
@@ -293,9 +293,7 @@ public:
// perform a recursive check.
SG_LOG(SG_TERRASYNC, SG_DEBUG, "file exists hash is good:" << it->file() );
if (c->type == ChildInfo::DirectoryType) {
SGPath p(relativePath());
p.append(it->file());
HTTPDirectory* childDir = _repository->getOrCreateDirectory(p.str());
HTTPDirectory* childDir = childDirectory(it->file());
if (childDir->_state == NotUpdated) {
childDir->_state = Updated;
}
@@ -344,9 +342,7 @@ public:
ChildInfoList::iterator cit;
for (cit = children.begin(); cit != children.end(); ++cit) {
if (cit->type == ChildInfo::DirectoryType) {
SGPath p(relativePath());
p.append(cit->name);
HTTPDirectory* childDir = _repository->getOrCreateDirectory(p.str());
HTTPDirectory* childDir = childDirectory(cit->name);
childDir->markSubtreeAsNeedingUpdate();
}
} // of child iteration
@@ -361,9 +357,7 @@ public:
ChildInfoList::iterator cit;
for (cit = children.begin(); cit != children.end(); ++cit) {
if (cit->type == ChildInfo::DirectoryType) {
SGPath p(relativePath());
p.append(cit->name);
HTTPDirectory* childDir = _repository->getOrCreateDirectory(p.str());
HTTPDirectory* childDir = childDirectory(cit->name);
childDir->markSubtreeAsEnabled();
}
} // of child iteration
@@ -376,11 +370,11 @@ public:
markAsEnabled();
}
if (_relativePath.isNull()) {
if (_relativePath.empty()) {
return;
}
std::string prPath = _relativePath.dir();
std::string prPath = SGPath(_relativePath).dir();
if (prPath.empty()) {
_repository->rootDir->markAncestorChainAsEnabled();
} else {
@@ -403,14 +397,17 @@ public:
ChildInfoList::iterator cit;
for (cit = children.begin(); cit != children.end(); ++cit) {
if (cit->type == ChildInfo::DirectoryType) {
SGPath p(relativePath());
p.append(cit->name);
HTTPDirectory* childDir = _repository->getOrCreateDirectory(p.str());
HTTPDirectory* childDir = childDirectory(cit->name);
childDir->updateIfWaiting(cit->hash, cit->sizeInBytes);
}
} // of child iteration
}
HTTPDirectory* childDirectory(const std::string& name)
{
return _repository->getOrCreateDirectory(relativePath() + "/" + name);
}
void removeOrphans(const string_list& orphans)
{
string_list::const_iterator it;
@@ -444,9 +441,7 @@ public:
if (cit->type == ChildInfo::FileType) {
_repository->updateFile(this, *it, cit->sizeInBytes);
} else {
SGPath p(relativePath());
p.append(*it);
HTTPDirectory* childDir = _repository->getOrCreateDirectory(p.str());
HTTPDirectory* childDir = childDirectory(*it);
if (childDir->_state == DoNotUpdate) {
SG_LOG(SG_TERRASYNC, SG_WARN, "scheduleUpdate, child:" << *it << " is marked do not update so skipping");
continue;
@@ -460,11 +455,11 @@ public:
SGPath absolutePath() const
{
SGPath r(_repository->basePath);
r.append(_relativePath.str());
r.append(_relativePath);
return r;
}
SGPath relativePath() const
std::string relativePath() const
{
return _relativePath;
}
@@ -521,7 +516,7 @@ private:
return false;
}
std::ifstream indexStream( p.c_str(), std::ios::in );
sg_ifstream indexStream(p, std::ios::in );
if ( !indexStream.is_open() ) {
throw sg_io_exception("cannot open dirIndex file", p);
@@ -581,11 +576,9 @@ private:
p.append(name);
bool ok;
SGPath fpath(_relativePath);
fpath.append(name);
std::string fpath = _relativePath + "/" + name;
if (p.isDir()) {
ok = _repository->deleteDirectory(fpath.str());
ok = _repository->deleteDirectory(fpath);
} else {
// remove the hash cache entry
_repository->updatedFileContents(p, std::string());
@@ -608,8 +601,8 @@ private:
return _repository->hashForPath(p);
}
HTTPRepoPrivate* _repository;
SGPath _relativePath; // in URL and file-system space
HTTPRepoPrivate* _repository;
std::string _relativePath; // in URL and file-system space
typedef enum
{
@@ -754,7 +747,7 @@ HTTPRepository::failure() const
virtual void gotBodyData(const char* s, int n)
{
if (!file.get()) {
file.reset(new SGBinaryFile(pathInRepo.str()));
file.reset(new SGBinaryFile(pathInRepo));
if (!file->open(SG_IO_OUT)) {
SG_LOG(SG_TERRASYNC, SG_WARN, "unable to create file " << pathInRepo);
_directory->repository()->http->cancelRequest(this, "Unable to create output file");
@@ -859,9 +852,9 @@ HTTPRepository::failure() const
// dir index data has changed, so write to disk and update
// the hash accordingly
std::ofstream of(pathInRepo().c_str(), std::ios::trunc | std::ios::out);
sg_ofstream of(pathInRepo(), std::ios::trunc | std::ios::out);
if (!of.is_open()) {
throw sg_io_exception("Failed to open directory index file for writing", pathInRepo().c_str());
throw sg_io_exception("Failed to open directory index file for writing", pathInRepo());
}
of.write(body.data(), body.size());
@@ -955,7 +948,7 @@ HTTPRepository::failure() const
class HashEntryWithPath
{
public:
HashEntryWithPath(const std::string& p) : path(p) {}
HashEntryWithPath(const SGPath& p) : path(p.utf8Str()) {}
bool operator()(const HTTPRepoPrivate::HashCacheEntry& entry) const
{ return entry.filePath == path; }
private:
@@ -964,7 +957,7 @@ HTTPRepository::failure() const
std::string HTTPRepoPrivate::hashForPath(const SGPath& p)
{
HashCache::iterator it = std::find_if(hashes.begin(), hashes.end(), HashEntryWithPath(p.str()));
HashCache::iterator it = std::find_if(hashes.begin(), hashes.end(), HashEntryWithPath(p));
if (it != hashes.end()) {
// ensure data on disk hasn't changed.
// we could also use the file type here if we were paranoid
@@ -989,7 +982,7 @@ HTTPRepository::failure() const
sha1_init(&info);
char* buf = static_cast<char*>(malloc(1024 * 1024));
size_t readLen;
SGBinaryFile f(p.str());
SGBinaryFile f(p);
if (!f.open(SG_IO_IN)) {
throw sg_io_exception("Couldn't open file for compute hash", p);
}
@@ -1006,7 +999,7 @@ HTTPRepository::failure() const
void HTTPRepoPrivate::updatedFileContents(const SGPath& p, const std::string& newHash)
{
// remove the existing entry
HashCache::iterator it = std::find_if(hashes.begin(), hashes.end(), HashEntryWithPath(p.str()));
HashCache::iterator it = std::find_if(hashes.begin(), hashes.end(), HashEntryWithPath(p));
if (it != hashes.end()) {
hashes.erase(it);
hashCacheDirty = true;
@@ -1022,7 +1015,7 @@ HTTPRepository::failure() const
p2.set_cached(true);
HashCacheEntry entry;
entry.filePath = p.str();
entry.filePath = p.utf8Str();
entry.hashHex = newHash;
entry.modTime = p2.modTime();
entry.lengthBytes = p2.sizeInBytes();
@@ -1039,8 +1032,7 @@ HTTPRepository::failure() const
SGPath cachePath = basePath;
cachePath.append(".hashes");
std::ofstream stream(cachePath.c_str(),std::ios::out | std::ios::trunc);
sg_ofstream stream(cachePath, std::ios::out | std::ios::trunc);
HashCache::const_iterator it;
for (it = hashes.begin(); it != hashes.end(); ++it) {
stream << it->filePath << ":" << it->modTime << ":"
@@ -1059,7 +1051,7 @@ HTTPRepository::failure() const
return;
}
std::ifstream stream(cachePath.c_str(), std::ios::in);
sg_ifstream stream(cachePath, std::ios::in);
while (!stream.eof()) {
std::string line;
@@ -1070,7 +1062,7 @@ HTTPRepository::failure() const
string_list tokens = simgear::strutils::split( line, ":" );
if( tokens.size() < 4 ) {
SG_LOG(SG_TERRASYNC, SG_WARN, "invalid entry in '" << cachePath.str() << "': '" << line << "' (ignoring line)");
SG_LOG(SG_TERRASYNC, SG_WARN, "invalid entry in '" << cachePath << "': '" << line << "' (ignoring line)");
continue;
}
const std::string nameData = simgear::strutils::strip(tokens[0]);
@@ -1079,7 +1071,7 @@ HTTPRepository::failure() const
const std::string hashData = simgear::strutils::strip(tokens[3]);
if (nameData.empty() || timeData.empty() || sizeData.empty() || hashData.empty() ) {
SG_LOG(SG_TERRASYNC, SG_WARN, "invalid entry in '" << cachePath.str() << "': '" << line << "' (ignoring line)");
SG_LOG(SG_TERRASYNC, SG_WARN, "invalid entry in '" << cachePath << "': '" << line << "' (ignoring line)");
continue;
}
@@ -1097,7 +1089,7 @@ HTTPRepository::failure() const
public:
DirectoryWithPath(const std::string& p) : path(p) {}
bool operator()(const HTTPDirectory* entry) const
{ return entry->relativePath().str() == path; }
{ return entry->relativePath() == path; }
private:
std::string path;
};

View File

@@ -125,115 +125,115 @@ public:
unsigned int get_size() const { return size; }
char *get_ptr() const { return ptr; }
void reset()
{
offset = 0;
}
void resize( unsigned int s )
{
if ( s > size ) {
if ( ptr != NULL ) {
delete [] ptr;
}
if ( size == 0) {
size = 16;
}
while ( size < s ) {
size = size << 1;
}
ptr = new char[size];
}
}
float readInt()
{
unsigned int* p = reinterpret_cast<unsigned int*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint32_t *) p);
}
offset += sizeof(unsigned int);
return *p;
}
SGVec3d readVec3d()
{
double* p = reinterpret_cast<double*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint64_t *) p + 0);
sgEndianSwap((uint64_t *) p + 1);
sgEndianSwap((uint64_t *) p + 2);
}
offset += 3 * sizeof(double);
return SGVec3d(p);
}
float readFloat()
{
float* p = reinterpret_cast<float*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint32_t *) p);
}
offset += sizeof(float);
return *p;
}
SGVec2f readVec2f()
{
float* p = reinterpret_cast<float*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint32_t *) p + 0);
sgEndianSwap((uint32_t *) p + 1);
}
offset += 2 * sizeof(float);
return SGVec2f(p);
}
SGVec3f readVec3f()
{
float* p = reinterpret_cast<float*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint32_t *) p + 0);
sgEndianSwap((uint32_t *) p + 1);
sgEndianSwap((uint32_t *) p + 2);
}
offset += 3 * sizeof(float);
return SGVec3f(p);
}
SGVec4f readVec4f()
{
float* p = reinterpret_cast<float*>(ptr + offset);
if ( sgIsBigEndian() ) {
if ( sgIsBigEndian() ) {
sgEndianSwap((uint32_t *) p + 0);
sgEndianSwap((uint32_t *) p + 1);
sgEndianSwap((uint32_t *) p + 2);
sgEndianSwap((uint32_t *) p + 3);
}
offset += 4 * sizeof(float);
return SGVec4f(p);
}
};
template <class T>
static void read_indices(char* buffer,
static void read_indices(char* buffer,
size_t bytes,
int indexMask,
int vaMask,
int_list& vertices,
int_list& vertices,
int_list& normals,
int_list& colors,
tci_list& texCoords,
@@ -243,7 +243,7 @@ static void read_indices(char* buffer,
const int indexSize = sizeof(T) * std::bitset<32>((int)indexMask).count();
const int vaSize = sizeof(T) * std::bitset<32>((int)vaMask).count();
const int count = bytes / (indexSize + vaSize);
// fix endian-ness of the whole lot, if required
if (sgIsBigEndian()) {
int indices = bytes / sizeof(T);
@@ -252,7 +252,7 @@ static void read_indices(char* buffer,
sgEndianSwap(src++);
}
}
T* src = reinterpret_cast<T*>(buffer);
for (int i=0; i<count; ++i) {
if (indexMask & SG_IDX_VERTICES) vertices.push_back(*src++);
@@ -262,7 +262,7 @@ static void read_indices(char* buffer,
if (indexMask & SG_IDX_TEXCOORDS_1) texCoords[1].push_back(*src++);
if (indexMask & SG_IDX_TEXCOORDS_2) texCoords[2].push_back(*src++);
if (indexMask & SG_IDX_TEXCOORDS_3) texCoords[3].push_back(*src++);
if ( vaMask ) {
if (vaMask & SG_VA_INTEGER_0) vas[0].push_back(*src++);
if (vaMask & SG_VA_INTEGER_1) vas[1].push_back(*src++);
@@ -274,11 +274,11 @@ static void read_indices(char* buffer,
if (vaMask & SG_VA_FLOAT_3) vas[7].push_back(*src++);
}
} // of elements in the index
// WS2.0 fix : toss zero area triangles
if ( ( count == 3 ) && (indexMask & SG_IDX_VERTICES) ) {
if ( (vertices[0] == vertices[1]) ||
(vertices[1] == vertices[2]) ||
if ( (vertices[0] == vertices[1]) ||
(vertices[1] == vertices[2]) ||
(vertices[2] == vertices[0]) ) {
vertices.clear();
}
@@ -306,11 +306,11 @@ void write_indice(gzFile fp, uint32_t value)
template <class T>
void write_indices(gzFile fp,
unsigned char indexMask,
void write_indices(gzFile fp,
unsigned char indexMask,
unsigned int vaMask,
const int_list& vertices,
const int_list& normals,
const int_list& vertices,
const int_list& normals,
const int_list& colors,
const tci_list& texCoords,
const vai_list& vas )
@@ -319,10 +319,10 @@ void write_indices(gzFile fp,
const int indexSize = sizeof(T) * std::bitset<32>((int)indexMask).count();
const int vaSize = sizeof(T) * std::bitset<32>((int)vaMask).count();
sgWriteUInt(fp, (indexSize + vaSize) * count);
for (unsigned int i=0; i < count; ++i) {
write_indice(fp, static_cast<T>(vertices[i]));
if (indexMask & SG_IDX_NORMALS) {
write_indice(fp, static_cast<T>(normals[i]));
}
@@ -341,7 +341,7 @@ void write_indices(gzFile fp,
if (indexMask & SG_IDX_TEXCOORDS_3) {
write_indice(fp, static_cast<T>(texCoords[3][i]));
}
if (vaMask) {
if (vaMask & SG_VA_INTEGER_0) {
write_indice(fp, static_cast<T>(vas[0][i]));
@@ -378,7 +378,7 @@ void SGBinObject::read_object( gzFile fp,
int obj_type,
int nproperties,
int nelements,
group_list& vertices,
group_list& vertices,
group_list& normals,
group_list& colors,
group_tci_list& texCoords,
@@ -399,15 +399,15 @@ void SGBinObject::read_object( gzFile fp,
idx_mask = (char)(SG_IDX_VERTICES | SG_IDX_TEXCOORDS_0);
}
vertex_attrib_mask = 0;
for ( j = 0; j < nproperties; ++j ) {
char prop_type;
sgReadChar( fp, &prop_type );
sgReadUInt( fp, &nbytes );
buf.resize(nbytes);
char *ptr = buf.get_ptr();
switch( prop_type )
{
case SG_MATERIAL:
@@ -418,12 +418,12 @@ void SGBinObject::read_object( gzFile fp,
strncpy( material, ptr, nbytes );
material[nbytes] = '\0';
break;
case SG_INDEX_TYPES:
if (nbytes == 1) {
sgReadChar( fp, (char *)&idx_mask );
sgReadChar( fp, (char *)&idx_mask );
} else {
sgReadBytes( fp, nbytes, ptr );
sgReadBytes( fp, nbytes, ptr );
}
break;
@@ -434,7 +434,7 @@ void SGBinObject::read_object( gzFile fp,
sgReadBytes( fp, nbytes, ptr );
}
break;
default:
sgReadBytes( fp, nbytes, ptr );
SG_LOG(SG_IO, SG_ALERT, "Found UNKNOWN property type with nbytes == " << nbytes << " mask is " << (int)idx_mask );
@@ -445,26 +445,26 @@ void SGBinObject::read_object( gzFile fp,
if ( sgReadError() ) {
throw sg_exception("Error reading object properties");
}
size_t indexCount = std::bitset<32>((int)idx_mask).count();
if (indexCount == 0) {
throw sg_exception("object index mask has no bits set");
}
for ( j = 0; j < nelements; ++j ) {
sgReadUInt( fp, &nbytes );
if ( sgReadError() ) {
throw sg_exception("Error reading element size");
}
buf.resize( nbytes );
char *ptr = buf.get_ptr();
sgReadBytes( fp, nbytes, ptr );
if ( sgReadError() ) {
throw sg_exception("Error reading element bytes");
}
int_list vs;
int_list ns;
int_list cs;
@@ -553,7 +553,7 @@ bool SGBinObject::read_bin( const SGPath& file ) {
sgReadUInt( fp, &header );
if ( ((header & 0xFF000000) >> 24) == 'S' &&
((header & 0x00FF0000) >> 16) == 'G' ) {
// read file version
version = (header & 0x0000FFFF);
} else {
@@ -561,7 +561,7 @@ bool SGBinObject::read_bin( const SGPath& file ) {
gzclose(fp);
throw sg_io_exception("Bad BTG magic/version", sg_location(file));
}
// read creation time
unsigned int foo_calendar_time;
sgReadUInt( fp, &foo_calendar_time );
@@ -592,13 +592,13 @@ bool SGBinObject::read_bin( const SGPath& file ) {
sgReadShort( fp, &v );
nobjects = v;
}
SG_LOG(SG_IO, SG_DEBUG, "SGBinObject::read_bin Total objects to read = " << nobjects);
if ( sgReadError() ) {
throw sg_io_exception("Error reading BTG file header", sg_location(file));
}
// read in objects
for ( i = 0; i < nobjects; ++i ) {
// read object header
@@ -622,14 +622,14 @@ bool SGBinObject::read_bin( const SGPath& file ) {
nelements = v;
}
SG_LOG(SG_IO, SG_DEBUG, "SGBinObject::read_bin object " << i <<
" = " << (int)obj_type << " props = " << nproperties <<
SG_LOG(SG_IO, SG_DEBUG, "SGBinObject::read_bin object " << i <<
" = " << (int)obj_type << " props = " << nproperties <<
" elements = " << nelements);
if ( obj_type == SG_BOUNDING_SPHERE ) {
// read bounding sphere properties
read_properties( fp, nproperties );
// read bounding sphere elements
for ( j = 0; j < nelements; ++j ) {
sgReadUInt( fp, &nbytes );
@@ -689,10 +689,10 @@ bool SGBinObject::read_bin( const SGPath& file ) {
sgReadBytes( fp, nbytes, ptr );
int count = nbytes / 3;
normals.reserve( count );
for ( k = 0; k < count; ++k ) {
SGVec3f normal( (ptr[0]) / 127.5 - 1.0,
(ptr[1]) / 127.5 - 1.0,
(ptr[1]) / 127.5 - 1.0,
(ptr[2]) / 127.5 - 1.0);
normals.push_back(normalize(normal));
ptr += 3;
@@ -718,7 +718,7 @@ bool SGBinObject::read_bin( const SGPath& file ) {
} else if ( obj_type == SG_VA_FLOAT_LIST ) {
// read vertex attribute (float) properties
read_properties( fp, nproperties );
// read vertex attribute list elements
for ( j = 0; j < nelements; ++j ) {
sgReadUInt( fp, &nbytes );
@@ -735,7 +735,7 @@ bool SGBinObject::read_bin( const SGPath& file ) {
} else if ( obj_type == SG_VA_INTEGER_LIST ) {
// read vertex attribute (integer) properties
read_properties( fp, nproperties );
// read vertex attribute list elements
for ( j = 0; j < nelements; ++j ) {
sgReadUInt( fp, &nbytes );
@@ -782,7 +782,7 @@ bool SGBinObject::read_bin( const SGPath& file ) {
sgReadBytes( fp, nbytes, ptr );
}
}
if ( sgReadError() ) {
throw sg_io_exception("Error while reading object", sg_location(file, i));
}
@@ -812,38 +812,38 @@ unsigned int SGBinObject::count_objects(const string_list& materials)
unsigned int start = 0, end = 1;
unsigned int count = materials.size();
string m;
while ( start < count ) {
m = materials[start];
for (end = start+1; (end < count) && (m == materials[end]); ++end) { }
for (end = start+1; (end < count) && (m == materials[end]); ++end) { }
++result;
start = end;
start = end;
}
return result;
}
void SGBinObject::write_objects(gzFile fp, int type,
void SGBinObject::write_objects(gzFile fp, int type,
const group_list& verts,
const group_list& normals,
const group_list& colors,
const group_list& normals,
const group_list& colors,
const group_tci_list& texCoords,
const group_vai_list& vertexAttribs,
const group_vai_list& vertexAttribs,
const string_list& materials)
{
if (verts.empty()) {
return;
}
unsigned int start = 0, end = 1;
string m;
int_list emptyList;
while (start < materials.size()) {
m = materials[start];
// find range of objects with identical material, write out as a single object
for (end = start+1; (end < materials.size()) && (m == materials[end]); ++end) {}
// calc the number of elements
const int count = end - start;
@@ -861,13 +861,13 @@ void SGBinObject::write_objects(gzFile fp, int type,
} else {
write_header(fp, type, 2, count);
}
// properties
// material property
sgWriteChar( fp, (char)SG_MATERIAL ); // property
sgWriteUInt( fp, m.length() ); // nbytes
sgWriteBytes( fp, m.length(), m.c_str() );
// index mask property
unsigned char idx_mask = 0;
if ( !verts.empty() && !verts[start].empty()) idx_mask |= SG_IDX_VERTICES;
@@ -877,7 +877,7 @@ void SGBinObject::write_objects(gzFile fp, int type,
if ( !texCoords.empty() && !texCoords[start][1].empty()) idx_mask |= SG_IDX_TEXCOORDS_1;
if ( !texCoords.empty() && !texCoords[start][2].empty()) idx_mask |= SG_IDX_TEXCOORDS_2;
if ( !texCoords.empty() && !texCoords[start][3].empty()) idx_mask |= SG_IDX_TEXCOORDS_3;
if (idx_mask == 0) {
SG_LOG(SG_IO, SG_ALERT, "SGBinObject::write_objects: object with material:"
<< m << "has no indices set");
@@ -893,28 +893,28 @@ void SGBinObject::write_objects(gzFile fp, int type,
sgWriteUInt( fp, 4 ); // nbytes
sgWriteChar( fp, va_mask );
}
// elements
for (unsigned int i=start; i < end; ++i) {
const int_list& va(verts[i]);
const int_list& na((idx_mask & SG_IDX_NORMALS) ? normals[i] : emptyList);
const int_list& ca((idx_mask & SG_IDX_COLORS) ? colors[i] : emptyList);
// pass the whole texcoord array - we'll figure out which indicies to write
// pass the whole texcoord array - we'll figure out which indicies to write
// in write_indices
const tci_list& tca( texCoords[i] );
// pass the whole vertex array - we'll figure out which indicies to write
// pass the whole vertex array - we'll figure out which indicies to write
// in write_indices
const vai_list& vaa( vertexAttribs[i] );
if (version == 7) {
write_indices<uint16_t>(fp, idx_mask, va_mask, va, na, ca, tca, vaa);
} else {
write_indices<uint32_t>(fp, idx_mask, va_mask, va, na, ca, tca, vaa);
}
}
start = end;
} // of materials iteration
}
@@ -953,25 +953,26 @@ const unsigned int VERSION_7_MATERIAL_LIMIT = 0x7fff;
bool SGBinObject::write_bin_file(const SGPath& file)
{
int i;
SGPath file2(file);
file2.create_dir( 0755 );
gzFile fp;
if ( (fp = gzopen( file.c_str(), "wb9" )) == NULL ) {
std::string localPath = file.local8BitStr();
if ( (fp = gzopen( localPath.c_str(), "wb9" )) == NULL ) {
cout << "ERROR: opening " << file << " for writing!" << endl;
return false;
}
sgClearWriteError();
SG_LOG(SG_IO, SG_DEBUG, "points size = " << pts_v.size()
SG_LOG(SG_IO, SG_DEBUG, "points size = " << pts_v.size()
<< " pt_materials = " << pt_materials.size() );
SG_LOG(SG_IO, SG_DEBUG, "triangles size = " << tris_v.size()
SG_LOG(SG_IO, SG_DEBUG, "triangles size = " << tris_v.size()
<< " tri_materials = " << tri_materials.size() );
SG_LOG(SG_IO, SG_DEBUG, "strips size = " << strips_v.size()
SG_LOG(SG_IO, SG_DEBUG, "strips size = " << strips_v.size()
<< " strip_materials = " << strip_materials.size() );
SG_LOG(SG_IO, SG_DEBUG, "fans size = " << fans_v.size()
SG_LOG(SG_IO, SG_DEBUG, "fans size = " << fans_v.size()
<< " fan_materials = " << fan_materials.size() );
SG_LOG(SG_IO, SG_DEBUG, "nodes = " << wgs84_nodes.size() );
@@ -980,12 +981,12 @@ bool SGBinObject::write_bin_file(const SGPath& file)
SG_LOG(SG_IO, SG_DEBUG, "tex coords = " << texcoords.size() );
version = 10;
bool shortMaterialsRanges =
bool shortMaterialsRanges =
(max_object_size(pt_materials) < VERSION_7_MATERIAL_LIMIT) &&
(max_object_size(fan_materials) < VERSION_7_MATERIAL_LIMIT) &&
(max_object_size(strip_materials) < VERSION_7_MATERIAL_LIMIT) &&
(max_object_size(tri_materials) < VERSION_7_MATERIAL_LIMIT);
if ((wgs84_nodes.size() < 0xffff) &&
(normals.size() < 0xffff) &&
(texcoords.size() < 0xffff) &&
@@ -994,10 +995,10 @@ bool SGBinObject::write_bin_file(const SGPath& file)
}
// write header magic
/** Magic Number for our file format */
#define SG_FILE_MAGIC_NUMBER ( ('S'<<24) + ('G'<<16) + version )
sgWriteUInt( fp, SG_FILE_MAGIC_NUMBER );
time_t calendar_time = time(NULL);
sgWriteLong( fp, (int32_t)calendar_time );
@@ -1015,8 +1016,8 @@ bool SGBinObject::write_bin_file(const SGPath& file)
sgWriteUShort( fp, (uint16_t) nobjects );
} else {
sgWriteInt( fp, nobjects );
}
}
// write bounding sphere
write_header( fp, SG_BOUNDING_SPHERE, 0, 1);
sgWriteUInt( fp, sizeof(double) * 3 + sizeof(float) ); // nbytes
@@ -1060,7 +1061,7 @@ bool SGBinObject::write_bin_file(const SGPath& file)
write_objects(fp, SG_TRIANGLE_FACES, tris_v, tris_n, tris_c, tris_tcs, tris_vas, tri_materials);
write_objects(fp, SG_TRIANGLE_STRIPS, strips_v, strips_n, strips_c, strips_tcs, strips_vas, strip_materials);
write_objects(fp, SG_TRIANGLE_FANS, fans_v, fans_n, fans_c, fans_tcs, fans_vas, fan_materials);
// close the file
gzclose(fp);
@@ -1086,16 +1087,17 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
cout << "Output file = " << file << endl;
FILE *fp;
if ( (fp = fopen( file.c_str(), "w" )) == NULL ) {
std::string path = file.local8BitStr();
if ( (fp = fopen( path.c_str(), "w" )) == NULL ) {
cout << "ERROR: opening " << file << " for writing!" << endl;
return false;
}
cout << "triangles size = " << tris_v.size() << " tri_materials = "
cout << "triangles size = " << tris_v.size() << " tri_materials = "
<< tri_materials.size() << endl;
cout << "strips size = " << strips_v.size() << " strip_materials = "
cout << "strips size = " << strips_v.size() << " strip_materials = "
<< strip_materials.size() << endl;
cout << "fans size = " << fans_v.size() << " fan_materials = "
cout << "fans size = " << fans_v.size() << " fan_materials = "
<< fan_materials.size() << endl;
cout << "points = " << wgs84_nodes.size() << endl;
@@ -1121,7 +1123,7 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
fprintf(fp, "# vertex list\n");
for ( i = 0; i < (int)wgs84_nodes.size(); ++i ) {
SGVec3d p = wgs84_nodes[i] - gbs_center;
fprintf(fp, "v %.5f %.5f %.5f\n", p.x(), p.y(), p.z() );
}
fprintf(fp, "\n");
@@ -1151,7 +1153,7 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
while ( start < (int)tri_materials.size() ) {
// find next group
material = tri_materials[start];
while ( (end < (int)tri_materials.size()) &&
while ( (end < (int)tri_materials.size()) &&
(material == tri_materials[end]) )
{
// cout << "end = " << end << endl;
@@ -1165,10 +1167,10 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
d.expandBy(wgs84_nodes[ tris_v[i][j] ]);
}
}
SGVec3d bs_center = d.getCenter();
double bs_radius = d.getRadius();
// write group headers
fprintf(fp, "\n");
fprintf(fp, "# usemtl %s\n", material.c_str());
@@ -1199,7 +1201,7 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
while ( start < (int)strip_materials.size() ) {
// find next group
material = strip_materials[start];
while ( (end < (int)strip_materials.size()) &&
while ( (end < (int)strip_materials.size()) &&
(material == strip_materials[end]) )
{
// cout << "end = " << end << endl;
@@ -1214,7 +1216,7 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
d.expandBy(wgs84_nodes[ tris_v[i][j] ]);
}
}
SGVec3d bs_center = d.getCenter();
double bs_radius = d.getRadius();
@@ -1232,7 +1234,7 @@ bool SGBinObject::write_ascii( const string& base, const string& name,
}
fprintf(fp, "\n");
}
start = end;
end = start + 1;
}
@@ -1255,7 +1257,7 @@ void SGBinObject::read_properties(gzFile fp, int nproperties)
{
sgSimpleBuffer buf;
uint32_t nbytes;
// read properties
for ( int j = 0; j < nproperties; ++j ) {
char prop_type;
@@ -1272,11 +1274,11 @@ bool SGBinObject::add_point( const SGBinObjectPoint& pt )
{
// add the point info
pt_materials.push_back( pt.material );
pts_v.push_back( pt.v_list );
pts_n.push_back( pt.n_list );
pts_n.push_back( pt.n_list );
pts_c.push_back( pt.c_list );
return true;
}
@@ -1289,6 +1291,6 @@ bool SGBinObject::add_triangle( const SGBinObjectTriangle& tri )
tris_c.push_back( tri.c_list );
tris_tcs.push_back( tri.tc_list );
tris_vas.push_back( tri.va_list );
return true;
}
}

View File

@@ -63,7 +63,7 @@ void test_empty()
bool ok = empty.write_bin_file(path);
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_wgs84_nodes().size(), 0);
@@ -192,7 +192,7 @@ void test_basic()
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_version(), 7); // should be version 7 since indices are < 2^16
COMPARE(rd.get_gbs_center(), center);
@@ -229,7 +229,7 @@ void test_many_tcs()
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_version(), 10); // should be version 10 since indices are > 2^16
COMPARE(rd.get_wgs84_nodes().size(), points.size());
@@ -266,7 +266,7 @@ void test_big()
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_version(), 10); // should be version 10 since indices are > 2^16
COMPARE(rd.get_wgs84_nodes().size(), points.size());
@@ -303,7 +303,7 @@ void test_some_objects()
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_version(), 7); // since we have less than 2^15 tris
COMPARE(rd.get_wgs84_nodes().size(), points.size());
@@ -340,7 +340,7 @@ void test_many_objects()
VERIFY( ok );
SGBinObject rd;
ok = rd.read_bin(path.str()) ;
ok = rd.read_bin(path) ;
VERIFY( ok);
COMPARE(rd.get_version(), 10); // should be version 10 since indices are > 2^16
COMPARE(rd.get_wgs84_nodes().size(), points.size());

View File

@@ -18,6 +18,7 @@
#include <simgear/timing/timestamp.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/misc/sg_dir.hxx>
#include <simgear/misc/sgstream.hxx>
#include <simgear/structure/exception.hxx>
#include <simgear/structure/callback.hxx>
@@ -307,7 +308,7 @@ std::string test_computeHashForPath(const SGPath& p)
char* buf = static_cast<char*>(alloca(1024 * 1024));
size_t readLen;
SGBinaryFile f(p.str());
SGBinaryFile f(p);
f.open(SG_IO_IN);
while ((readLen = f.read(buf, 1024 * 1024)) > 0) {
@@ -370,7 +371,7 @@ void createFile(const SGPath& basePath, const std::string& relPath, int revision
std::string prName = comps.at(comps.size() - 2);
{
std::ofstream f(p.c_str(), std::ios::trunc | std::ios::out);
sg_ofstream f(p, std::ios::trunc | std::ios::out);
f << dataForFile(prName, comps.back(), revision);
}
}
@@ -450,7 +451,7 @@ void testModifyLocalFiles(HTTP::Client* cl)
SGPath modFile(p);
modFile.append("dirB/subdirA/fileBAA");
{
std::ofstream of(modFile.c_str(), std::ios::out | std::ios::trunc);
sg_ofstream of(modFile, std::ios::out | std::ios::trunc);
of << "complete nonsense";
of.close();
}
@@ -901,7 +902,7 @@ int main(int argc, char* argv[])
testServer.disconnectAll();
cl.clearAllConnections();
testPartialUpdateBasic(&cl);
testPartialUpdateExisting(&cl);
testPartialUpdateWidenWhileInProgress(&cl);

View File

@@ -24,7 +24,7 @@ void testTarGz()
SGPath p = SGPath(SRC_DIR);
p.append("test.tar.gz");
SGBinaryFile f(p.str());
SGBinaryFile f(p);
f.open(SG_IO_IN);
uint8_t* buf = (uint8_t*) alloca(8192);
@@ -39,7 +39,7 @@ void testPlainTar()
SGPath p = SGPath(SRC_DIR);
p.append("test2.tar");
SGBinaryFile f(p.str());
SGBinaryFile f(p);
f.open(SG_IO_IN);
uint8_t* buf = (uint8_t*) alloca(8192);

View File

@@ -193,7 +193,7 @@ public:
} else if ((header.typeflag == REGTYPE) || (header.typeflag == AREGTYPE)) {
currentFileSize = ::strtol(header.size, NULL, 8);
bytesRemaining = currentFileSize;
currentFile.reset(new SGBinaryFile(p.str()));
currentFile.reset(new SGBinaryFile(p));
currentFile->open(SG_IO_OUT);
setState(READING_FILE);
} else {

View File

@@ -89,8 +89,8 @@ int main(int argc, char* argv[])
// test basic parsing
SGPath pb("/Foo/bar/something.png");
COMPARE(pb.str(), std::string("/Foo/bar/something.png"));
COMPARE(strcmp(pb.c_str(), "/Foo/bar/something.png"), 0);
COMPARE(pb.utf8Str(), std::string("/Foo/bar/something.png"));
COMPARE(pb.local8BitStr(), std::string("/Foo/bar/something.png"));
COMPARE(pb.dir(), std::string("/Foo/bar"));
COMPARE(pb.file(), std::string("something.png"));
COMPARE(pb.base(), std::string("/Foo/bar/something"));
@@ -101,7 +101,8 @@ int main(int argc, char* argv[])
// relative paths
SGPath ra("where/to/begin.txt");
COMPARE(ra.str(), std::string("where/to/begin.txt"));
COMPARE(ra.utf8Str(), std::string("where/to/begin.txt"));
COMPARE(ra.local8BitStr(), std::string("where/to/begin.txt"));
COMPARE(ra.dir(), std::string("where/to"));
COMPARE(ra.file(), std::string("begin.txt"));
COMPARE(ra.file_base(), std::string("begin"));
@@ -127,34 +128,26 @@ int main(int argc, char* argv[])
// path fixing
SGPath rd("where\\to\\begin.txt");
COMPARE(rd.str(), std::string("where/to/begin.txt"));
COMPARE(rd.utf8Str(), std::string("where/to/begin.txt"));
// test modification
// append
SGPath d1("/usr/local");
SGPath pc = d1;
COMPARE(pc.str(), std::string("/usr/local"));
COMPARE(pc.utf8Str(), std::string("/usr/local"));
pc.append("include");
COMPARE(pc.str(), std::string("/usr/local/include"));
COMPARE(pc.utf8Str(), std::string("/usr/local/include"));
COMPARE(pc.file(), std::string("include"));
// add
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"));
#endif
// concat
SGPath pd = pb;
pd.concat("-1");
COMPARE(pd.str(), std::string("/Foo/bar/something.png-1"));
COMPARE(pd.utf8Str(), std::string("/Foo/bar/something.png-1"));
// create with relative path
SGPath rb(d1, "include/foo");
COMPARE(rb.str(), std::string("/usr/local/include/foo"));
COMPARE(rb.utf8Str(), std::string("/usr/local/include/foo"));
VERIFY(rb.isAbsolute());
// lower-casing of file extensions
@@ -170,12 +163,9 @@ int main(int argc, char* argv[])
COMPARE(extB.lower_extension(), "gz");
COMPARE(extB.complete_lower_extension(), "html.gz");
#ifdef _WIN32
COMPARE(d1.str_native(), std::string("\\usr\\local"));
SGPath winAbs("C:\\Windows\\System32");
COMPARE(winAbs.str(), std::string("C:/Windows/System32"));
#else
COMPARE(d1.str_native(), std::string("/usr/local"));
COMPARE(winAbs.local8BitStr(), std::string("C:/Windows/System32"));
#endif
// paths with only the file components

View File

@@ -66,7 +66,7 @@ Dir::Dir(const SGPath& path) :
}
Dir::Dir(const Dir& rel, const SGPath& relPath) :
_path(rel.file(relPath.str())),
_path(rel.file(relPath.utf8Str())),
_removeOnDestroy(false)
{
_path.set_cached(false); // disable caching, so create/remove work
@@ -115,7 +115,8 @@ Dir Dir::tempDir(const std::string& templ)
// Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
// says exactly six, so that's what I'm going with
p.concat("-XXXXXX");
::snprintf(buf, 1024, "%s", p.c_str());
std::string s = p.local8BitStr();
::snprintf(buf, 1024, "%s", s.c_str());
if (!mkdtemp(buf)) {
SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
return Dir();
@@ -126,7 +127,7 @@ Dir Dir::tempDir(const std::string& templ)
SGPath p(tempnam(0, templ.c_str()));
Dir t(p);
if (!t.create(0700)) {
SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p.str());
SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p);
}
return t;
@@ -146,7 +147,7 @@ PathList Dir::children(int types, const std::string& nameFilter) const
}
#ifdef _WIN32
std::string search(_path.str());
std::string search(_path.local8BitStr());
if (nameFilter.empty()) {
search += "\\*"; // everything
} else {
@@ -159,7 +160,7 @@ PathList Dir::children(int types, const std::string& nameFilter) const
int err = GetLastError();
if (err != ERROR_FILE_NOT_FOUND) {
SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" <<
_path.str() << " with error:" << err);
_path << " with error:" << err);
}
return result;
}
@@ -195,9 +196,10 @@ PathList Dir::children(int types, const std::string& nameFilter) const
FindClose(find);
#else
DIR* dp = opendir(_path.c_str());
std::string ps = _path.local8BitStr();
DIR* dp = opendir(ps.c_str());
if (!dp) {
SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path.str());
SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path);
return result;
}
@@ -270,9 +272,11 @@ PathList Dir::children(int types, const std::string& nameFilter) const
bool Dir::isEmpty() const
{
bool empty= true;
std::string ps = _path.local8BitStr();
#ifdef _WIN32
ps += "\\*";
WIN32_FIND_DATA fData;
HANDLE find = FindFirstFile("\\*", &fData);
HANDLE find = FindFirstFile(ps.c_str(), &fData);
if (find == INVALID_HANDLE_VALUE) {
return true;
}
@@ -293,7 +297,8 @@ bool Dir::isEmpty() const
FindClose(find);
#else
DIR* dp = opendir(_path.c_str());
DIR* dp = opendir(ps.c_str());
if (!dp) {
return true;
}
@@ -351,9 +356,10 @@ bool Dir::create(mode_t mode)
}
// finally, create ourselves
int err = sgMkDir(_path.c_str(), mode);
std::string ps = _path.local8BitStr();
int err = sgMkDir(ps.c_str(), mode);
if (err) {
SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path.str() << ") " << strerror(errno) );
SG_LOG(SG_IO, SG_WARN, "directory creation failed: (" << _path << ") " << strerror(errno) );
}
return (err == 0);
@@ -393,14 +399,15 @@ bool Dir::remove(bool recursive)
return false;
}
} // of recursive deletion
std::string ps = _path.local8BitStr();
#ifdef _WIN32
int err = _rmdir(_path.c_str());
int err = _rmdir(ps.c_str());
#else
int err = rmdir(_path.c_str());
int err = rmdir(ps.c_str());
#endif
if (err) {
SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path.str() << ":" << strerror(errno));
SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path << ":" << strerror(errno));
}
return (err == 0);
}

View File

@@ -27,6 +27,8 @@
#include <simgear_config.h>
#include <simgear/debug/logstream.hxx>
#include <simgear/misc/strutils.hxx>
#include <simgear/misc/sgstream.hxx>
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
@@ -61,6 +63,8 @@ static const char sgSearchPathSep = ':';
// included in the Windows 8.1 SDK
#include "sgversionhelpers.hxx"
#define ENABLE_OLD_PATH_API 1
static SGPath pathForCSIDL(int csidl, const SGPath& def)
{
typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPSTR, int, BOOL);
@@ -143,7 +147,7 @@ static SGPath getXDGDir( const std::string& name,
// path. No other format is supported.
const std::string XDG_ID = "XDG_" + name + "_DIR=\"";
std::ifstream user_dirs_file( user_dirs.c_str() );
sg_ifstream user_dirs_file( user_dirs );
std::string line;
while( std::getline(user_dirs_file, line).good() )
{
@@ -270,7 +274,7 @@ SGPath& SGPath::operator=(const SGPath& p)
SGPath::~SGPath() {
}
#if defined(ENABLE_OLD_PATH_API)
// set path
void SGPath::set( const string& p ) {
path = p;
@@ -278,6 +282,7 @@ void SGPath::set( const string& p ) {
_cached = false;
_rwCached = false;
}
#endif
//------------------------------------------------------------------------------
void SGPath::setPermissionChecker(PermissionChecker validator)
@@ -322,11 +327,12 @@ SGPath SGPath::operator/( const std::string& p ) const
return ret;
}
#if defined(ENABLE_OLD_PATH_API)
//add a new path component to the existing path string
void SGPath::add( const string& p ) {
append( sgSearchPathSep+p );
}
#endif
// concatenate a string to the end of the path without inserting a
// path separator
@@ -356,7 +362,7 @@ string SGPath::file() const
return path;
}
}
// get the directory part of the path.
string SGPath::dir() const {
@@ -373,12 +379,12 @@ string SGPath::base() const
{
string::size_type index = path.rfind(".");
string::size_type lastSep = path.rfind(sgDirPathSep);
// tolerate dots inside directory names
if ((lastSep != string::npos) && (index < lastSep)) {
return path;
}
if (index != string::npos) {
return path.substr(0, index);
} else {
@@ -394,12 +400,12 @@ string SGPath::file_base() const
} else {
++index; // skip past the separator
}
string::size_type firstDot = path.find(".", index);
if (firstDot == string::npos) {
return path.substr(index); // no extensions
}
return path.substr(index, firstDot - index);
}
@@ -427,7 +433,7 @@ string SGPath::complete_lower_extension() const
} else {
++index; // skip past the separator
}
string::size_type firstDot = path.find(".", index);
if ((firstDot != string::npos) && (path.find(sgDirPathSep, firstDot) == string::npos)) {
return boost::to_lower_copy(path.substr(firstDot + 1));
@@ -451,11 +457,11 @@ void SGPath::validate() const
#ifdef _WIN32
struct _stat buf ;
bool remove_trailing = false;
string statPath(path);
string statPath(local8BitStr());
if ((path.length() > 1) && (path.back() == '/')) {
statPath.pop_back();
}
if (_stat(statPath.c_str(), &buf ) < 0) {
_exists = false;
} else {
@@ -478,7 +484,7 @@ void SGPath::validate() const
_modTime = buf.st_mtime;
_size = buf.st_size;
}
#endif
_cached = true;
}
@@ -563,22 +569,24 @@ int SGPath::create_dir(mode_t mode)
unsigned int i = 1;
SGPath dir(absolute ? string( 1, sgDirPathSep ) : "", _permission_checker);
dir.concat( path_elements[0] );
std::string ds = dir.local8BitStr();
#ifdef _WIN32
if ( dir.str().find(':') != string::npos && path_elements.size() >= 2 ) {
if ( ds.find(':') != string::npos && path_elements.size() >= 2 ) {
dir.append( path_elements[1] );
i = 2;
ds = dir.local8BitStr();
}
#endif
struct stat info;
int r;
for(; (r = stat(dir.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
for(; (r = stat(ds.c_str(), &info)) == 0 && i < path_elements.size(); ++i)
dir.append(path_elements[i]);
if( r == 0 )
return 0; // Directory already exists
for(;;)
{
if( sgMkDir(dir.c_str(), mode) )
if( sgMkDir(ds.c_str(), mode) )
{
SG_LOG( SG_IO,
SG_ALERT, "Error creating directory: (" << dir << ")" );
@@ -642,7 +650,7 @@ bool SGPath::isAbsolute() const
if (path.empty()) {
return false;
}
#ifdef _WIN32
// detect '[A-Za-z]:/'
if (path.size() > 2) {
@@ -651,7 +659,7 @@ bool SGPath::isAbsolute() const
}
}
#endif
return (path[0] == sgDirPathSep);
}
@@ -660,6 +668,7 @@ bool SGPath::isNull() const
return path.empty();
}
#if defined(ENABLE_OLD_PATH_API)
std::string SGPath::str_native() const
{
#ifdef _WIN32
@@ -676,6 +685,7 @@ std::string SGPath::str_native() const
return utf8Str();
#endif
}
#endif
//------------------------------------------------------------------------------
bool SGPath::remove()
@@ -687,7 +697,8 @@ bool SGPath::remove()
return false;
}
int err = ::unlink(c_str());
std::string ps = local8BitStr();
int err = ::unlink(ps.c_str());
if( err )
{
SG_LOG( SG_IO, SG_WARN, "file remove failed: (" << *this << ") "
@@ -950,5 +961,3 @@ std::string SGPath::join(const std::vector<SGPath>& paths, const std::string& jo
return r;
}

View File

@@ -66,7 +66,7 @@ namespace nasal
//----------------------------------------------------------------------------
naRef to_nasal_helper(naContext c, const SGPath& path)
{
return to_nasal_helper(c, path.str());
return to_nasal_helper(c, path.utf8Str());
}
//----------------------------------------------------------------------------

View File

@@ -27,6 +27,7 @@
#include <simgear/io/HTTPRequest.hxx>
#include <simgear/io/HTTPClient.hxx>
#include <simgear/misc/sg_dir.hxx>
#include <simgear/misc/sgstream.hxx>
#include <simgear/structure/exception.hxx>
#include <simgear/package/Package.hxx>
#include <simgear/package/Root.hxx>
@@ -159,8 +160,7 @@ protected:
// cache the catalog data, now we have a valid install root
Dir d(m_owner->installRoot());
SGPath p = d.file("catalog.xml");
std::ofstream f(p.c_str(), std::ios::out | std::ios::trunc);
sg_ofstream f(p, std::ios::out | std::ios::trunc);
f.write(m_buffer.data(), m_buffer.size());
f.close();
@@ -207,7 +207,7 @@ CatalogRef Catalog::createFromPath(Root* aRoot, const SGPath& aPath)
SGPropertyNode_ptr props;
try {
props = new SGPropertyNode;
readProperties(xml.str(), props);
readProperties(xml, props);
} catch (sg_exception& ) {
return NULL;
}
@@ -465,7 +465,7 @@ void Catalog::parseTimestamp()
{
SGPath timestampFile = m_installRoot;
timestampFile.append(".timestamp");
std::ifstream f(timestampFile.c_str(), std::ios::in);
sg_ifstream f(timestampFile, std::ios::in);
f >> m_retrievedTime;
}
@@ -473,7 +473,7 @@ void Catalog::writeTimestamp()
{
SGPath timestampFile = m_installRoot;
timestampFile.append(".timestamp");
std::ofstream f(timestampFile.c_str(), std::ios::out | std::ios::trunc);
sg_ofstream f(timestampFile, std::ios::out | std::ios::trunc);
f << m_retrievedTime << std::endl;
}

View File

@@ -46,7 +46,7 @@ std::string readFileIntoString(const SGPath& path)
std::string contents;
size_t readLen;
SGBinaryFile f(path.str());
SGBinaryFile f(path);
if (!f.open(SG_IO_IN)) {
throw sg_io_exception("Couldn't open file", path);
}

View File

@@ -33,6 +33,7 @@
#include <simgear/io/HTTPClient.hxx>
#include <simgear/misc/sg_dir.hxx>
#include <simgear/misc/strutils.hxx>
#include <simgear/misc/sgstream.hxx>
extern "C" {
void fill_memory_filefunc (zlib_filefunc_def*);
@@ -217,7 +218,7 @@ private:
throw sg_io_exception("opening current zip file failed", sg_location(name));
}
std::ofstream outFile;
sg_ofstream outFile;
bool eof = false;
SGPath path(m_extractPath);
path.append(name);
@@ -227,13 +228,13 @@ private:
if (!parentDir.exists()) {
bool ok = parentDir.create(0755);
if (!ok) {
throw sg_io_exception("failed to create directory heirarchy for extraction", path.c_str());
throw sg_io_exception("failed to create directory heirarchy for extraction", path);
}
}
outFile.open(path.c_str(), std::ios::binary | std::ios::trunc | std::ios::out);
outFile.open(path, std::ios::binary | std::ios::trunc | std::ios::out);
if (outFile.fail()) {
throw sg_io_exception("failed to open output file for writing", path.c_str());
throw sg_io_exception("failed to open output file for writing", path);
}
while (!eof) {
@@ -364,7 +365,7 @@ void Install::parseRevision()
return;
}
std::ifstream f(revisionFile.c_str(), std::ios::in);
sg_ifstream f(revisionFile, std::ios::in);
f >> m_revision;
}
@@ -372,7 +373,7 @@ void Install::writeRevisionFile()
{
SGPath revisionFile = m_path;
revisionFile.append(".revision");
std::ofstream f(revisionFile.c_str(), std::ios::out | std::ios::trunc);
sg_ofstream f(revisionFile, std::ios::out | std::ios::trunc);
f << m_revision << std::endl;
}

View File

@@ -149,7 +149,7 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
SGPath tpath("Textures");
tpath.append(tname);
std::string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
std::string fullTexPath = SGModelLib::findDataFile(tpath.local8BitStr(), options);
if (fullTexPath.empty()) {
SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
<< tname << "\" in Textures folders.");
@@ -181,7 +181,7 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
SGPath tpath("Textures");
tpath.append(tname);
std::string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
std::string fullTexPath = SGModelLib::findDataFile(tpath.local8BitStr(), options);
if (fullTexPath.empty()) {
SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
<< tname << "\" in Textures folders.");
@@ -207,7 +207,7 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
SGPath tpath("Textures");
tpath.append("Terrain");
tpath.append("unknown.rgb");
_internal_state st( NULL, tpath.str(), true, options );
_internal_state st( NULL, tpath.local8BitStr(), true, options );
_status.push_back( st );
}
@@ -219,7 +219,7 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
if (! omname.empty()) {
SGPath ompath("Textures");
ompath.append(omname);
std::string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
std::string fullMaskPath = SGModelLib::findDataFile(ompath.local8BitStr(), options);
if (fullMaskPath.empty()) {
SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
@@ -340,7 +340,7 @@ SGMaterial::read_properties(const SGReaderWriterOptions* options,
if (! treeTexPath.empty()) {
SGPath treePath("Textures");
treePath.append(treeTexPath);
tree_texture = SGModelLib::findDataFile(treePath.str(), options);
tree_texture = SGModelLib::findDataFile(treePath.local8BitStr(), options);
if (tree_texture.empty()) {
SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""

View File

@@ -260,7 +260,7 @@ sgLoad3DModel_internal(const SGPath& path,
SGPropertyNode *overlay)
{
if (!path.exists()) {
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path.str() << "\"");
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load file: \"" << path << "\"");
return NULL;
}
@@ -286,7 +286,7 @@ sgLoad3DModel_internal(const SGPath& path,
// Check for an XML wrapper
if (modelpath.extension() == "xml") {
try {
readProperties(modelpath.str(), props);
readProperties(modelpath, props);
} catch (const sg_exception &t) {
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load xml: "
<< t.getFormattedMessage());
@@ -304,7 +304,7 @@ sgLoad3DModel_internal(const SGPath& path,
modelpath = SGModelLib::findDataFile(modelPathStr, NULL, modelDir);
if (modelpath.isNull())
throw sg_io_exception("Model file not found: '" + modelPathStr + "'",
path.str());
path);
if (props->hasValue("/texture-path")) {
string texturePathStr = props->getStringValue("/texture-path");
@@ -313,7 +313,7 @@ sgLoad3DModel_internal(const SGPath& path,
texturepath = SGModelLib::findDataFile(texturePathStr, NULL, modelDir);
if (texturepath.isNull())
throw sg_io_exception("Texture file not found: '" + texturePathStr + "'",
path.str());
path);
}
}
} else {
@@ -333,12 +333,12 @@ sgLoad3DModel_internal(const SGPath& path,
if (!texturepath.extension().empty())
texturepath = texturepath.dir();
options->setDatabasePath(texturepath.str());
options->setDatabasePath(texturepath.local8BitStr());
osgDB::ReaderWriter::ReadResult modelResult;
modelResult = osgDB::readNodeFile(modelpath.str(), options.get());
modelResult = osgDB::readNodeFile(modelpath.local8BitStr(), options.get());
if (!modelResult.validNode())
throw sg_io_exception("Failed to load 3D model:" + modelResult.message(),
modelpath.str());
modelpath);
model = copyModel(modelResult.getNode());
// Add an extra reference to the model stored in the database.
// That is to avoid expiring the object from the cache even if
@@ -362,7 +362,7 @@ sgLoad3DModel_internal(const SGPath& path,
SetNodeMaskVisitor setNodeMaskVisitor(0, simgear::MODELLIGHT_BIT);
model->accept(setNodeMaskVisitor);
}
model->setName(modelpath.str());
model->setName(modelpath.utf8Str());
bool needTransform=false;
// Set up the alignment node if needed
@@ -413,7 +413,7 @@ sgLoad3DModel_internal(const SGPath& path,
bool isInterior = (std::string(sub_props->getStringValue("usage")) == "interior");
bool isAI = (std::string(prop_root->getStringValue("type")) == "AI");
if(isInterior && isAI){
props->addChild("interior-path")->setStringValue(submodelPath.str());
props->addChild("interior-path")->setStringValue(submodelPath.utf8Str());
continue;
}
}
@@ -485,14 +485,14 @@ sgLoad3DModel_internal(const SGPath& path,
std::vector<SGPropertyNode_ptr> particle_nodes;
particle_nodes = props->getChildren("particlesystem");
for (unsigned i = 0; i < particle_nodes.size(); ++i) {
SG_LOG(SG_PARTICLES, SG_DEBUG, "Reading in particle " << i << " from file: " << path.str());
SG_LOG(SG_PARTICLES, SG_DEBUG, "Reading in particle " << i << " from file: " << path);
osg::ref_ptr<SGReaderWriterOptions> options2;
options2 = new SGReaderWriterOptions(*options);
if (i==0) {
if (!texturepath.extension().empty())
texturepath = texturepath.dir();
options2->setDatabasePath(texturepath.str());
options2->setDatabasePath(texturepath.local8BitStr());
}
group->addChild(Particles::appendParticles(particle_nodes[i],
prop_root,
@@ -536,18 +536,18 @@ sgLoad3DModel_internal(const SGPath& path,
/// OSGFIXME: duh, why not only model?????
SGAnimation::animate(group.get(), animation_nodes[i], prop_root,
options.get(), path.str(), i);
options.get(), path.local8BitStr(), i);
}
if (!needTransform && group->getNumChildren() < 2) {
model = group->getChild(0);
group->removeChild(model.get());
if (data.valid())
data->modelLoaded(modelpath.str(), props, model.get());
data->modelLoaded(modelpath.utf8Str(), props, model.get());
return model.release();
}
if (data.valid())
data->modelLoaded(modelpath.str(), props, group.get());
data->modelLoaded(modelpath.utf8Str(), props, group.get());
if (props->hasChild("debug-outfile")) {
std::string outputfile = props->getStringValue("debug-outfile",
"debug-model.osg");

View File

@@ -97,7 +97,7 @@ osg::Node * SGText::appendText(const SGPropertyNode* configNode,
SGPath path("Fonts" );
path.append( configNode->getStringValue( "font", "Helvetica" ));
text->setFont( path.str() );
text->setFont( path.local8BitStr() );
text->setCharacterSize(configNode->getDoubleValue("character-size", 1.0 ),
configNode->getDoubleValue("character-aspect-ratio", 1.0 ));

View File

@@ -47,7 +47,7 @@ SGLoadTexture2D(const SGPath& path,
bool wrapu = true, bool wrapv = true,
int mipmaplevels = -1)
{
return SGLoadTexture2D(true, path.str(), options, wrapu, wrapv,
return SGLoadTexture2D(true, path.local8BitStr(), options, wrapu, wrapv,
mipmaplevels);
}
@@ -57,7 +57,7 @@ SGLoadTexture2D(bool staticTexture, const SGPath& path,
bool wrapu = true, bool wrapv = true,
int mipmaplevels = -1)
{
return SGLoadTexture2D(staticTexture, path.str(), options, wrapu, wrapv,
return SGLoadTexture2D(staticTexture, path.local8BitStr(), options, wrapu, wrapv,
mipmaplevels);
}

View File

@@ -76,7 +76,7 @@ std::string SGModelLib::findDataFile(const std::string& file,
return file;
SGPath p = ResourceManager::instance()->findPath(file, currentPath);
if (p.exists()) {
return p.str();
return p.local8BitStr();
}
// finally hand on to standard OSG behaviour

View File

@@ -78,7 +78,7 @@ SGMakeState(const SGPath &path, const char* colorTexture,
osg::StateSet *stateSet = new osg::StateSet;
osg::ref_ptr<SGReaderWriterOptions> options;
options = SGReaderWriterOptions::fromPath(path.str());
options = SGReaderWriterOptions::fromPath(path.local8BitStr());
stateSet->setTextureAttribute(0, SGLoadTexture2D(colorTexture,
options.get()));
stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);

View File

@@ -76,7 +76,7 @@ SGMoon::build( SGPath path, double moon_size ) {
// set up the orb state
osg::ref_ptr<SGReaderWriterOptions> options;
options = SGReaderWriterOptions::fromPath(path.str());
options = SGReaderWriterOptions::fromPath(path.local8BitStr());
osg::Texture2D* texture = SGLoadTexture2D("moon.png", options.get());
stateSet->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);

View File

@@ -118,7 +118,7 @@ SGNewCloud::SGNewCloud(const SGPath &texture_root, const SGPropertyNode *cld_def
"image"),
texture);
ref_ptr<SGReaderWriterOptions> options;
options = SGReaderWriterOptions::fromPath(texture_root.str());
options = SGReaderWriterOptions::fromPath(texture_root.local8BitStr());
effect = makeEffect(pcloudEffect, true, options.get());
if (effect.valid())
{

View File

@@ -70,7 +70,7 @@ SGSun::build( SGPath path, double sun_size, SGPropertyNode *property_tree_Node )
env_node = property_tree_Node;
osg::ref_ptr<SGReaderWriterOptions> options;
options = SGReaderWriterOptions::fromPath(path.str());
options = SGReaderWriterOptions::fromPath(path.local8BitStr());
// build the ssg scene graph sub tree for the sky and connected
// into the provide scene graph branch
sun_transform = new osg::MatrixTransform;

View File

@@ -221,7 +221,7 @@ struct ReaderWriterSTG::_ModelBin {
SGPath path = filePath;
path.append(".."); path.append(".."); path.append("..");
sharedOptions->getDatabasePathList().push_back(path.str());
sharedOptions->getDatabasePathList().push_back(path.local8BitStr());
// ensure Models directory synced via TerraSync is searched before the copy in
// FG_ROOT, so that updated models can be used.
@@ -346,7 +346,7 @@ struct ReaderWriterSTG::_ModelBin {
_Object obj;
obj._errorLocation = absoluteFileName;
obj._token = token;
obj._name = path.str();
obj._name = path.local8BitStr();
obj._options = staticOptions(filePath, options);
_objectList.push_back(obj);
}
@@ -356,7 +356,7 @@ struct ReaderWriterSTG::_ModelBin {
_Object obj;
obj._errorLocation = absoluteFileName;
obj._token = token;
obj._name = path.str();
obj._name = path.local8BitStr();
obj._options = staticOptions(filePath, options);
_objectList.push_back(obj);
}
@@ -555,13 +555,13 @@ ReaderWriterSTG::readNode(const std::string& fileName, const osgDB::Options* opt
objects.append("Objects");
objects.append(basePath);
objects.append(fileName);
modelBin.read(objects.str(), options);
modelBin.read(objects.local8BitStr(), options);
SGPath terrain(*i);
terrain.append("Terrain");
terrain.append(basePath);
terrain.append(fileName);
modelBin.read(terrain.str(), options);
modelBin.read(terrain.local8BitStr(), options);
}
}

View File

@@ -54,6 +54,7 @@
#include <simgear/bucket/newbucket.hxx>
#include <simgear/misc/sg_path.hxx>
#include <simgear/misc/strutils.hxx>
#include <simgear/misc/sgstream.hxx>
#include <simgear/threads/SGQueue.hxx>
#include <simgear/threads/SGThread.hxx>
#include <simgear/threads/SGGuard.hxx>
@@ -707,7 +708,7 @@ void SGTerraSync::WorkerThread::initCompletedTilesPersistentCache()
time_t now = time(0);
try {
readProperties(_persistentCachePath.str(), cacheRoot);
readProperties(_persistentCachePath, cacheRoot);
} catch (sg_exception& e) {
SG_LOG(SG_TERRASYNC, SG_INFO, "corrupted persistent cache, discarding");
return;
@@ -737,7 +738,7 @@ void SGTerraSync::WorkerThread::writeCompletedTilesPersistentCache() const
return;
}
std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
sg_ofstream f(_persistentCachePath, std::ios::trunc);
if (!f.is_open()) {
return;
}

View File

@@ -372,7 +372,8 @@ ALvoid* loadWAVFromFile(const SGPath& path, unsigned int& format, ALsizei& size,
b.path = path;
gzFile fd;
fd = gzopen(path.c_str(), "rb");
std::string ps = path.local8BitStr();
fd = gzopen(ps.c_str(), "rb");
if (!fd) {
throw sg_io_exception("loadWAVFromFile: unable to open file", path);
}

View File

@@ -121,7 +121,7 @@ SGSoundSample::SGSoundSample(const char *file, const SGPath& currentDir) :
_buffer(SGSoundMgr::NO_BUFFER)
{
SGPath p = simgear::ResourceManager::instance()->findPath(file, currentDir);
_refname = p.str();
_refname = p.utf8Str();
}
// constructor

View File

@@ -87,16 +87,16 @@ void SGTime::init( const SGGeod& location, const SGPath& root, time_t init_time
if (!static_tzContainer.get()) {
SGPath zone( root );
zone.append( "zone.tab" );
SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
<< zone.str() );
static_tzContainer.reset(new SGTimeZoneContainer( zone.c_str() ));
SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: " << zone );
std::string zs = zone.local8BitStr();
static_tzContainer.reset(new SGTimeZoneContainer( zs.c_str() ));
}
SGTimeZone* nearestTz = static_tzContainer->getNearest(location);
SGPath name( root );
name.append( nearestTz->getDescription() );
zonename = name.str();
zonename = name.utf8Str();
SG_LOG( SG_EVENT, SG_DEBUG, "Using zonename = " << zonename );
} else {
zonename.erase();
@@ -235,17 +235,18 @@ void SGTime::updateLocal( const SGGeod& aLocation, const string& root ) {
SGTimeZone* nearestTz = static_tzContainer->getNearest(location);
SGPath zone( root );
zone.append ( nearestTz->getDescription() );
zonename = zone.str();
zonename = zone.utf8Str();
//Avoid troubles when zone.tab hasn't got the right line endings
if (zonename[zonename.size()-1] == '\r')
{
zonename[zonename.size()-1]=0;
zone.set( zonename );
zone = SGPath(zonename);
}
currGMT = sgTimeGetGMT( gmtime(&cur_time) );
aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
std::string zs = zone.local8BitStr();
aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zs.c_str())) );
local_offset = aircraftLocalTime - currGMT;
// cout << "Using " << local_offset << " as local time offset Timezone is "
// << zonename << endl;