1 // terrasync.cxx -- scenery fetcher
3 // Started by Curtis Olson, November 2002.
5 // Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 // Copyright (C) 2008 Alexander R. Perry <alex.perry@ieee.org>
7 // Copyright (C) 2011 Thorsten Brehm <brehmt@gmail.com>
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 # include <simgear_config.h>
29 #include <simgear/compiler.h>
38 #elif defined(_MSC_VER)
44 #include <stdlib.h> // atoi() atof() abs() system()
45 #include <signal.h> // signal()
53 #include <simgear/compiler.h>
55 #include "terrasync.hxx"
57 #include <simgear/bucket/newbucket.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/strutils.hxx>
60 #include <simgear/threads/SGQueue.hxx>
61 #include <simgear/misc/sg_dir.hxx>
62 #include <simgear/debug/BufferedLogCallback.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/io/HTTPClient.hxx>
65 #include <simgear/io/SVNRepository.hxx>
66 #include <simgear/structure/exception.hxx>
68 static const bool svn_built_in_available = true;
70 using namespace simgear;
73 const char* rsync_cmd =
74 "rsync --verbose --archive --delete --perms --owner --group";
76 const char* svn_options =
79 namespace UpdateInterval
81 // interval in seconds to allow an update to repeat after a successful update (=daily)
82 static const double SuccessfulAttempt = 24*60*60;
83 // interval in seconds to allow another update after a failed attempt (10 minutes)
84 static const double FailedAttempt = 10*60;
87 typedef map<string,time_t> CompletedTiles;
89 ///////////////////////////////////////////////////////////////////////////////
90 // helper functions ///////////////////////////////////////////////////////////
91 ///////////////////////////////////////////////////////////////////////////////
92 string stripPath(string path)
94 // svn doesn't like trailing white-spaces or path separators - strip them!
95 path = simgear::strutils::strip(path);
96 size_t slen = path.length();
98 ((path[slen-1]=='/')||(path[slen-1]=='\\')))
102 return path.substr(0,slen);
105 bool hasWhitespace(string path)
107 return path.find(' ')!=string::npos;
110 ///////////////////////////////////////////////////////////////////////////////
111 // SyncItem ////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
118 Stop = 0, ///< special item indicating to stop the SVNThread
129 Cached, ///< using already cached result
142 SyncItem(string dir, Type ty) :
153 ///////////////////////////////////////////////////////////////////////////////
156 * @brief SyncSlot encapsulates a queue of sync items we will fetch
157 * serially. Multiple slots exist to sync different types of item in
164 isNewDirectory(false),
168 SyncItem currentItem;
170 std::queue<SyncItem> queue;
171 std::auto_ptr<SVNRepository> repository;
173 bool busy; ///< is the slot working or idle
175 unsigned int nextWarnTimeout;
178 static const int SYNC_SLOT_TILES = 0; ///< Terrain and Objects sync
179 static const int SYNC_SLOT_SHARED_DATA = 1; /// shared Models and Airport data
180 static const int SYNC_SLOT_AI_DATA = 2; /// AI traffic and models
181 static const unsigned int NUM_SYNC_SLOTS = 3;
184 * @brief translate a sync item type into one of the available slots.
185 * This provides the scheduling / balancing / prioritising between slots.
187 static unsigned int syncSlotForType(SyncItem::Type ty)
190 case SyncItem::Tile: return SYNC_SLOT_TILES;
191 case SyncItem::SharedModels:
192 case SyncItem::AirportData:
193 return SYNC_SLOT_SHARED_DATA;
194 case SyncItem::AIData:
195 return SYNC_SLOT_AI_DATA;
198 return SYNC_SLOT_SHARED_DATA;
203 ///////////////////////////////////////////////////////////////////////////////
204 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
205 ///////////////////////////////////////////////////////////////////////////////
206 class SGTerraSync::SvnThread : public SGThread
210 virtual ~SvnThread( ) { stop(); }
215 bool isIdle() {return !_busy; }
216 void request(const SyncItem& dir) {waitingTiles.push_front(dir);}
217 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
218 bool hasNewTiles() { return !_freshTiles.empty();}
219 SyncItem getNewTile() { return _freshTiles.pop_front();}
221 void setSvnServer(string server) { _svn_server = stripPath(server);}
222 void setSvnDataServer(string server) { _svn_data_server = stripPath(server);}
224 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
225 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
226 void setLocalDir(string dir) { _local_dir = stripPath(dir);}
227 string getLocalDir() { return _local_dir;}
228 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
229 void setAllowedErrorCount(int errors) {_allowed_errors = errors;}
231 void setCachePath(const SGPath& p) {_persistentCachePath = p;}
232 void setCacheHits(unsigned int hits) {_cache_hits = hits;}
233 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
235 volatile bool _active;
236 volatile bool _running;
238 volatile bool _stalled;
239 volatile int _fail_count;
240 volatile int _updated_tile_count;
241 volatile int _success_count;
242 volatile int _consecutive_errors;
243 volatile int _allowed_errors;
244 volatile int _cache_hits;
245 volatile int _transfer_rate;
249 // external model run and helpers
251 void syncPathExternal(const SyncItem& next);
252 bool runExternalSyncCommand(const char* dir);
254 // internal mode run and helpers
256 void updateSyncSlot(SyncSlot& slot);
258 // commond helpers between both internal and external models
260 bool isPathCached(const SyncItem& next) const;
261 void initCompletedTilesPersistentCache();
262 void writeCompletedTilesPersistentCache() const;
263 void updated(SyncItem item, bool isNewDirectory);
264 void fail(SyncItem failedItem);
268 SyncSlot _syncSlots[NUM_SYNC_SLOTS];
270 volatile bool _is_dirty;
272 SGBlockingDeque <SyncItem> waitingTiles;
273 CompletedTiles _completedTiles;
274 SGBlockingDeque <SyncItem> _freshTiles;
277 string _svn_data_server;
279 string _rsync_server;
281 SGPath _persistentCachePath;
284 SGTerraSync::SvnThread::SvnThread() :
290 _updated_tile_count(0),
292 _consecutive_errors(0),
303 void SGTerraSync::SvnThread::stop()
305 // drop any pending requests
306 waitingTiles.clear();
311 // set stop flag and wake up the thread with an empty request
313 SyncItem w(string(), SyncItem::Stop);
319 bool SGTerraSync::SvnThread::start()
326 SG_LOG(SG_TERRAIN,SG_ALERT,
327 "Cannot start scenery download. Local cache directory is undefined.");
333 SGPath path(_local_dir);
336 SG_LOG(SG_TERRAIN,SG_ALERT,
337 "Cannot start scenery download. Directory '" << _local_dir <<
338 "' does not exist. Set correct directory path or create directory folder.");
344 path.append("version");
347 SG_LOG(SG_TERRAIN,SG_ALERT,
348 "Cannot start scenery download. Directory '" << _local_dir <<
349 "' contains the base package. Use a separate directory.");
355 _use_svn |= _use_built_in;
357 if ((_use_svn)&&(_svn_server==""))
359 SG_LOG(SG_TERRAIN,SG_ALERT,
360 "Cannot start scenery download. Subversion scenery server is undefined.");
365 if ((!_use_svn)&&(_rsync_server==""))
367 SG_LOG(SG_TERRAIN,SG_ALERT,
368 "Cannot start scenery download. Rsync scenery server is undefined.");
375 _updated_tile_count = 0;
377 _consecutive_errors = 0;
384 if (_use_svn && _use_built_in)
385 status = "Using built-in SVN support. ";
388 status = "Using external SVN utility '";
389 status += _svn_command;
394 status = "Using RSYNC. ";
397 // not really an alert - but we want to (always) see this message, so user is
398 // aware we're downloading scenery (and using bandwidth).
399 SG_LOG(SG_TERRAIN,SG_ALERT,
400 "Starting automatic scenery download/synchronization. "
402 << "Directory: '" << _local_dir << "'.");
408 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
411 SGPath localPath( _local_dir );
412 localPath.append( dir );
416 buf << "\"" << _svn_command << "\" "
417 << svn_options << " "
418 << "\"" << _svn_server << "/" << dir << "\" "
419 << "\"" << localPath.str_native() << "\"";
421 buf << rsync_cmd << " "
422 << "\"" << _rsync_server << "/" << dir << "/\" "
423 << "\"" << localPath.str_native() << "/\"";
428 // windows command line parsing is just lovely...
429 // to allow white spaces, the system call needs this:
430 // ""C:\Program Files\something.exe" somearg "some other arg""
431 // Note: whitespace strings quoted by a pair of "" _and_ the
432 // entire string needs to be wrapped by "" too.
433 // The svn url needs forward slashes (/) as a path separator while
434 // the local path needs windows-native backslash as a path separator.
435 command = "\"" + buf.str() + "\"";
439 SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
442 // tbd: does Windows support "popen"?
443 int rc = system( command.c_str() );
445 FILE* pipe = popen( command.c_str(), "r");
447 // wait for external process to finish
454 SG_LOG(SG_TERRAIN,SG_ALERT,
455 "Failed to synchronize directory '" << dir << "', " <<
456 "error code= " << rc);
462 void SGTerraSync::SvnThread::run()
465 initCompletedTilesPersistentCache();
479 void SGTerraSync::SvnThread::runExternal()
483 SyncItem next = waitingTiles.pop_front();
487 if (isPathCached(next)) {
489 SG_LOG(SG_TERRAIN, SG_DEBUG,
490 "Cache hit for: '" << next._dir << "'");
491 next._status = SyncItem::Cached;
492 _freshTiles.push_back(next);
497 syncPathExternal(next);
499 if ((_allowed_errors >= 0)&&
500 (_consecutive_errors >= _allowed_errors))
505 } // of thread running loop
508 void SGTerraSync::SvnThread::syncPathExternal(const SyncItem& next)
511 SGPath path( _local_dir );
512 path.append( next._dir );
513 bool isNewDirectory = !path.exists();
516 if (isNewDirectory) {
517 int rc = path.create_dir( 0755 );
519 SG_LOG(SG_TERRAIN,SG_ALERT,
520 "Cannot create directory '" << path << "', return code = " << rc );
521 throw sg_exception("Cannot create directory for terrasync", path.str());
525 if (!runExternalSyncCommand(next._dir.c_str())) {
526 throw sg_exception("Running external sync command failed");
528 } catch (sg_exception& e) {
534 updated(next, isNewDirectory);
538 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
540 if (slot.repository.get()) {
541 if (slot.repository->isDoingSync()) {
543 if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) {
544 SG_LOG(SG_TERRAIN, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
545 SG_LOG(SG_TERRAIN, SG_INFO, "HTTP status:" << _http.hasActiveRequests());
546 slot.nextWarnTimeout += 10000;
549 return; // easy, still working
553 SVNRepository::ResultCode res = slot.repository->failure();
554 if (res == SVNRepository::SVN_ERROR_NOT_FOUND) {
555 // this is fine, but maybe we should use a different return code
556 // in the future to higher layers can distinguish this case
557 slot.currentItem._status = SyncItem::NotFound;
558 _freshTiles.push_back(slot.currentItem);
560 } else if (res != SVNRepository::SVN_NO_ERROR) {
561 fail(slot.currentItem);
563 updated(slot.currentItem, slot.isNewDirectory);
564 SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
565 << slot.stamp.elapsedMSec() << " msec");
568 // whatever happened, we're done with this repository instance
570 slot.repository.reset();
573 // init and start sync of the next repository
574 if (!slot.queue.empty()) {
575 slot.currentItem = slot.queue.front();
578 SGPath path(_local_dir);
579 path.append(slot.currentItem._dir);
580 slot.isNewDirectory = !path.exists();
581 if (slot.isNewDirectory) {
582 int rc = path.create_dir( 0755 );
584 SG_LOG(SG_TERRAIN,SG_ALERT,
585 "Cannot create directory '" << path << "', return code = " << rc );
586 fail(slot.currentItem);
589 } // of creating directory step
591 string serverUrl(_svn_server);
592 if (slot.currentItem._type == SyncItem::AIData) {
593 serverUrl = _svn_data_server;
596 slot.repository.reset(new SVNRepository(path, &_http));
597 slot.repository->setBaseUrl(serverUrl + "/" + slot.currentItem._dir);
598 slot.repository->update();
600 slot.nextWarnTimeout = 20000;
603 SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
607 void SGTerraSync::SvnThread::runInternal()
611 _transfer_rate = _http.transferRateBytesPerSec();
615 // drain the waiting tiles queue into the sync slot queues.
616 while (!waitingTiles.empty()) {
617 SyncItem next = waitingTiles.pop_front();
618 if (isPathCached(next)) {
620 SG_LOG(SG_TERRAIN, SG_DEBUG, "TerraSync Cache hit for: '" << next._dir << "'");
621 next._status = SyncItem::Cached;
622 _freshTiles.push_back(next);
627 unsigned int slot = syncSlotForType(next._type);
628 _syncSlots[slot].queue.push(next);
631 bool anySlotBusy = false;
632 // update each sync slot in turn
633 for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
634 updateSyncSlot(_syncSlots[slot]);
635 anySlotBusy |= _syncSlots[slot].busy;
639 } // of thread running loop
642 bool SGTerraSync::SvnThread::isPathCached(const SyncItem& next) const
644 CompletedTiles::const_iterator ii = _completedTiles.find( next._dir );
645 if (ii == _completedTiles.end()) {
649 // check if the path still physically exists
650 SGPath p(_local_dir);
656 time_t now = time(0);
657 return (ii->second > now);
660 void SGTerraSync::SvnThread::fail(SyncItem failedItem)
662 time_t now = time(0);
663 _consecutive_errors++;
665 failedItem._status = SyncItem::Failed;
666 _freshTiles.push_back(failedItem);
667 _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
671 void SGTerraSync::SvnThread::updated(SyncItem item, bool isNewDirectory)
673 time_t now = time(0);
674 _consecutive_errors = 0;
676 SG_LOG(SG_TERRAIN,SG_INFO,
677 "Successfully synchronized directory '" << item._dir << "'");
679 item._status = SyncItem::Updated;
680 if (item._type == SyncItem::Tile) {
681 _updated_tile_count++;
684 _freshTiles.push_back(item);
685 _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
687 writeCompletedTilesPersistentCache();
690 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
692 if (!_persistentCachePath.exists()) {
696 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
697 time_t now = time(0);
700 readProperties(_persistentCachePath.str(), cacheRoot);
701 } catch (sg_exception& e) {
702 SG_LOG(SG_TERRAIN, SG_INFO, "corrupted persistent cache, discarding");
706 for (int i=0; i<cacheRoot->nChildren(); ++i) {
707 SGPropertyNode* entry = cacheRoot->getChild(i);
708 string tileName = entry->getStringValue("path");
709 time_t stamp = entry->getIntValue("stamp");
714 _completedTiles[tileName] = stamp;
718 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
721 if (_persistentCachePath.isNull()) {
725 std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
730 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
731 CompletedTiles::const_iterator it = _completedTiles.begin();
732 for (; it != _completedTiles.end(); ++it) {
733 SGPropertyNode* entry = cacheRoot->addChild("entry");
734 entry->setStringValue("path", it->first);
735 entry->setIntValue("stamp", it->second);
738 writeProperties(f, cacheRoot, true /* write_all */);
742 ///////////////////////////////////////////////////////////////////////////////
743 // SGTerraSync ////////////////////////////////////////////////////////////////
744 ///////////////////////////////////////////////////////////////////////////////
745 SGTerraSync::SGTerraSync(SGPropertyNode_ptr root) :
749 _terraRoot(root->getNode("/sim/terrasync",true)),
753 _svnThread = new SvnThread();
754 _log = new BufferedLogCallback(SG_TERRAIN, SG_INFO);
755 _log->truncateAt(255);
757 sglog().addCallback(_log);
760 SGTerraSync::~SGTerraSync()
762 _tiedProperties.Untie();
765 sglog().removeCallback(_log);
769 void SGTerraSync::init()
776 _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
781 void SGTerraSync::reinit()
783 // do not reinit when enabled and we're already up and running
784 if ((_terraRoot->getBoolValue("enabled",false))&&
785 (_svnThread->_active && _svnThread->_running))
792 if (_terraRoot->getBoolValue("enabled",false))
794 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
795 _svnThread->setSvnDataServer(_terraRoot->getStringValue("svn-data-server",""));
796 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
797 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
798 _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
799 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
800 _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
801 _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
802 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
803 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
805 if (_svnThread->start())
807 syncAirportsModels();
808 if (last_lat != NOWHERE && last_lon != NOWHERE)
810 // reschedule most recent position
815 schedulePosition(lat, lon);
820 _stalledNode->setBoolValue(_svnThread->_stalled);
823 void SGTerraSync::bind()
830 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
831 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
832 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
833 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
834 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
835 _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
836 _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
838 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
839 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
840 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
841 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
842 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
843 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
844 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
845 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
846 _stalledNode = _terraRoot->getNode("stalled", true);
847 _stalledNode->setBoolValue(_svnThread->_stalled);
848 _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
851 void SGTerraSync::unbind()
854 _tiedProperties.Untie();
859 void SGTerraSync::update(double)
861 static SGBucket bucket;
862 if (_svnThread->isDirty())
864 if (!_svnThread->_active)
866 if (_svnThread->_stalled)
868 SG_LOG(SG_TERRAIN,SG_ALERT,
869 "Automatic scenery download/synchronization stalled. Too many errors.");
873 // not really an alert - just always show this message
874 SG_LOG(SG_TERRAIN,SG_ALERT,
875 "Automatic scenery download/synchronization has stopped.");
877 _stalledNode->setBoolValue(_svnThread->_stalled);
880 while (_svnThread->hasNewTiles())
882 SyncItem next = _svnThread->getNewTile();
884 if ((next._type == SyncItem::Tile) || (next._type == SyncItem::AIData)) {
885 _activeTileDirs.erase(next._dir);
887 } // of freshly synced items
891 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
893 void SGTerraSync::syncAirportsModels()
895 static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
896 // note "request" method uses LIFO order, i.e. processes most recent request first
897 for( unsigned i = 0; i < strlen(bounds)/2; i++ )
899 for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
902 dir << "Airports/" << synced_other;
903 SyncItem w(dir.str(), SyncItem::AirportData);
904 _svnThread->request( w );
908 SyncItem w("Models", SyncItem::SharedModels);
909 _svnThread->request( w );
913 void SGTerraSync::syncArea( int lat, int lon )
915 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
918 int baselat, baselon;
921 int base = (int)(lat / 10);
922 if ( lat == base * 10 ) {
925 baselat = (base - 1) * 10;
929 baselat = (int)(lat / 10) * 10;
933 int base = (int)(lon / 10);
934 if ( lon == base * 10 ) {
937 baselon = (base - 1) * 10;
941 baselon = (int)(lon / 10) * 10;
947 << EW << setw(3) << abs(baselon) << NS << setw(2) << abs(baselat) << "/"
948 << EW << setw(3) << abs(lon) << NS << setw(2) << abs(lat);
950 syncAreaByPath(dir.str());
953 void SGTerraSync::syncAreaByPath(const std::string& aPath)
955 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
956 for (const char** tree = &terrainobjects[0]; *tree; tree++)
958 std::string dir = string(*tree) + aPath;
959 if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
963 _activeTileDirs.insert(dir);
964 SyncItem w(dir, SyncItem::Tile);
965 _svnThread->request( w );
970 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
972 if ( lat_dir == 0 && lon_dir == 0 ) {
974 // do surrounding 8 1x1 degree areas.
975 for ( int i = lat - 1; i <= lat + 1; ++i ) {
976 for ( int j = lon - 1; j <= lon + 1; ++j ) {
977 if ( i != lat || j != lon ) {
983 if ( lat_dir != 0 ) {
984 syncArea( lat + lat_dir, lon - 1 );
985 syncArea( lat + lat_dir, lon + 1 );
986 syncArea( lat + lat_dir, lon );
988 if ( lon_dir != 0 ) {
989 syncArea( lat - 1, lon + lon_dir );
990 syncArea( lat + 1, lon + lon_dir );
991 syncArea( lat, lon + lon_dir );
995 // do current 1x1 degree area first
996 syncArea( lat, lon );
999 bool SGTerraSync::scheduleTile(const SGBucket& bucket)
1001 std::string basePath = bucket.gen_base_path();
1002 syncAreaByPath(basePath);
1006 bool SGTerraSync::schedulePosition(int lat, int lon)
1010 // Ignore messages where the location does not change
1011 if ( lat != last_lat || lon != last_lon )
1013 if (_svnThread->_running)
1017 if ( last_lat != NOWHERE && last_lon != NOWHERE )
1019 int dist = lat - last_lat;
1022 lat_dir = dist / abs(dist);
1028 dist = lon - last_lon;
1031 lon_dir = dist / abs(dist);
1038 SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
1039 "lat = " << lat << ", lon = " << lon <<
1040 ", lat_dir = " << lat_dir << ", " <<
1041 "lon_dir = " << lon_dir);
1043 syncAreas( lat, lon, lat_dir, lon_dir );
1053 void SGTerraSync::reposition()
1055 last_lat = last_lon = NOWHERE;
1058 bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
1060 if (!_svnThread->_running) {
1064 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
1065 for (const char** tree = &terrainobjects[0]; *tree; tree++) {
1066 string s = *tree + sceneryDir;
1067 if (_activeTileDirs.find(s) != _activeTileDirs.end()) {
1075 void SGTerraSync::scheduleDataDir(const std::string& dataDir)
1077 if (_activeTileDirs.find(dataDir) != _activeTileDirs.end()) {
1081 _activeTileDirs.insert(dataDir);
1082 SyncItem w(dataDir, SyncItem::AIData);
1083 _svnThread->request( w );
1087 bool SGTerraSync::isDataDirPending(const std::string& dataDir) const
1089 return (_activeTileDirs.find(dataDir) != _activeTileDirs.end());