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 // WaitingSyncItem ////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
113 class WaitingSyncItem
118 Stop = 0, ///< special item indicating to stop the SVNThread
128 Cached, ///< using already cached result
141 WaitingSyncItem(string dir, Type ty) :
152 ///////////////////////////////////////////////////////////////////////////////
155 * @brief SyncSlot encapsulates a queue of sync items we will fetch
156 * serially. Multiple slots exist to sync different types of item in
163 isNewDirectory(false),
167 WaitingSyncItem currentItem;
169 std::queue<WaitingSyncItem> queue;
170 std::auto_ptr<SVNRepository> repository;
172 bool busy; ///< is the slot working or idle
174 unsigned int nextWarnTimeout;
177 static const int SYNC_SLOT_TILES = 0; ///< Terrain and Objects sync
178 static const int SYNC_SLOT_SHARED_DATA = 1; /// shared Models and Airport data
179 static const int NUM_SYNC_SLOTS = 2;
182 * @brief translate a sync item type into one of the available slots.
183 * This provides the scheduling / balancing / prioritising between slots.
185 static unsigned int syncSlotForType(WaitingSyncItem::Type ty)
188 case WaitingSyncItem::Tile: return SYNC_SLOT_TILES;
189 case WaitingSyncItem::SharedModels:
190 case WaitingSyncItem::AirportData:
191 return SYNC_SLOT_SHARED_DATA;
193 return SYNC_SLOT_SHARED_DATA;
198 ///////////////////////////////////////////////////////////////////////////////
199 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
200 ///////////////////////////////////////////////////////////////////////////////
201 class SGTerraSync::SvnThread : public SGThread
205 virtual ~SvnThread( ) { stop(); }
210 bool isIdle() {return !_busy; }
211 void request(const WaitingSyncItem& dir) {waitingTiles.push_front(dir);}
212 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
213 bool hasNewTiles() { return !_freshTiles.empty();}
214 WaitingSyncItem getNewTile() { return _freshTiles.pop_front();}
216 void setSvnServer(string server) { _svn_server = stripPath(server);}
217 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
218 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
219 void setLocalDir(string dir) { _local_dir = stripPath(dir);}
220 string getLocalDir() { return _local_dir;}
221 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
222 void setAllowedErrorCount(int errors) {_allowed_errors = errors;}
224 void setCachePath(const SGPath& p) {_persistentCachePath = p;}
225 void setCacheHits(unsigned int hits) {_cache_hits = hits;}
226 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
228 volatile bool _active;
229 volatile bool _running;
231 volatile bool _stalled;
232 volatile int _fail_count;
233 volatile int _updated_tile_count;
234 volatile int _success_count;
235 volatile int _consecutive_errors;
236 volatile int _allowed_errors;
237 volatile int _cache_hits;
238 volatile int _transfer_rate;
242 // external model run and helpers
244 void syncPathExternal(const WaitingSyncItem& next);
245 bool runExternalSyncCommand(const char* dir);
247 // internal mode run and helpers
249 void updateSyncSlot(SyncSlot& slot);
251 // commond helpers between both internal and external models
253 bool isPathCached(const WaitingSyncItem& next) const;
254 void initCompletedTilesPersistentCache();
255 void writeCompletedTilesPersistentCache() const;
256 void updated(WaitingSyncItem item, bool isNewDirectory);
257 void fail(WaitingSyncItem failedItem);
261 SyncSlot _syncSlots[NUM_SYNC_SLOTS];
263 volatile bool _is_dirty;
265 SGBlockingDeque <WaitingSyncItem> waitingTiles;
266 CompletedTiles _completedTiles;
267 SGBlockingDeque <WaitingSyncItem> _freshTiles;
271 string _rsync_server;
273 SGPath _persistentCachePath;
276 SGTerraSync::SvnThread::SvnThread() :
282 _updated_tile_count(0),
284 _consecutive_errors(0),
295 void SGTerraSync::SvnThread::stop()
297 // drop any pending requests
298 waitingTiles.clear();
303 // set stop flag and wake up the thread with an empty request
305 WaitingSyncItem w(string(), WaitingSyncItem::Stop);
311 bool SGTerraSync::SvnThread::start()
318 SG_LOG(SG_TERRAIN,SG_ALERT,
319 "Cannot start scenery download. Local cache directory is undefined.");
325 SGPath path(_local_dir);
328 SG_LOG(SG_TERRAIN,SG_ALERT,
329 "Cannot start scenery download. Directory '" << _local_dir <<
330 "' does not exist. Set correct directory path or create directory folder.");
336 path.append("version");
339 SG_LOG(SG_TERRAIN,SG_ALERT,
340 "Cannot start scenery download. Directory '" << _local_dir <<
341 "' contains the base package. Use a separate directory.");
347 _use_svn |= _use_built_in;
349 if ((_use_svn)&&(_svn_server==""))
351 SG_LOG(SG_TERRAIN,SG_ALERT,
352 "Cannot start scenery download. Subversion scenery server is undefined.");
357 if ((!_use_svn)&&(_rsync_server==""))
359 SG_LOG(SG_TERRAIN,SG_ALERT,
360 "Cannot start scenery download. Rsync scenery server is undefined.");
367 _updated_tile_count = 0;
369 _consecutive_errors = 0;
376 if (_use_svn && _use_built_in)
377 status = "Using built-in SVN support. ";
380 status = "Using external SVN utility '";
381 status += _svn_command;
386 status = "Using RSYNC. ";
389 // not really an alert - but we want to (always) see this message, so user is
390 // aware we're downloading scenery (and using bandwidth).
391 SG_LOG(SG_TERRAIN,SG_ALERT,
392 "Starting automatic scenery download/synchronization. "
394 << "Directory: '" << _local_dir << "'.");
400 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
403 SGPath localPath( _local_dir );
404 localPath.append( dir );
408 buf << "\"" << _svn_command << "\" "
409 << svn_options << " "
410 << "\"" << _svn_server << "/" << dir << "\" "
411 << "\"" << localPath.str_native() << "\"";
413 buf << rsync_cmd << " "
414 << "\"" << _rsync_server << "/" << dir << "/\" "
415 << "\"" << localPath.str_native() << "/\"";
420 // windows command line parsing is just lovely...
421 // to allow white spaces, the system call needs this:
422 // ""C:\Program Files\something.exe" somearg "some other arg""
423 // Note: whitespace strings quoted by a pair of "" _and_ the
424 // entire string needs to be wrapped by "" too.
425 // The svn url needs forward slashes (/) as a path separator while
426 // the local path needs windows-native backslash as a path separator.
427 command = "\"" + buf.str() + "\"";
431 SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
434 // tbd: does Windows support "popen"?
435 int rc = system( command.c_str() );
437 FILE* pipe = popen( command.c_str(), "r");
439 // wait for external process to finish
446 SG_LOG(SG_TERRAIN,SG_ALERT,
447 "Failed to synchronize directory '" << dir << "', " <<
448 "error code= " << rc);
454 void SGTerraSync::SvnThread::run()
457 initCompletedTilesPersistentCache();
471 void SGTerraSync::SvnThread::runExternal()
475 WaitingSyncItem next = waitingTiles.pop_front();
479 if (isPathCached(next)) {
481 SG_LOG(SG_TERRAIN, SG_DEBUG,
482 "Cache hit for: '" << next._dir << "'");
483 next._status = WaitingSyncItem::Cached;
484 _freshTiles.push_back(next);
489 syncPathExternal(next);
491 if ((_allowed_errors >= 0)&&
492 (_consecutive_errors >= _allowed_errors))
497 } // of thread running loop
500 void SGTerraSync::SvnThread::syncPathExternal(const WaitingSyncItem& next)
503 SGPath path( _local_dir );
504 path.append( next._dir );
505 bool isNewDirectory = !path.exists();
508 if (isNewDirectory) {
509 int rc = path.create_dir( 0755 );
511 SG_LOG(SG_TERRAIN,SG_ALERT,
512 "Cannot create directory '" << path << "', return code = " << rc );
513 throw sg_exception("Cannot create directory for terrasync", path.str());
517 if (!runExternalSyncCommand(next._dir.c_str())) {
518 throw sg_exception("Running external sync command failed");
520 } catch (sg_exception& e) {
526 updated(next, isNewDirectory);
530 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
532 if (slot.repository.get()) {
533 if (slot.repository->isDoingSync()) {
535 if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) {
536 SG_LOG(SG_TERRAIN, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
537 SG_LOG(SG_TERRAIN, SG_INFO, "HTTP status:" << _http.hasActiveRequests());
538 slot.nextWarnTimeout += 10000;
541 return; // easy, still working
545 SVNRepository::ResultCode res = slot.repository->failure();
546 if (res == SVNRepository::SVN_ERROR_NOT_FOUND) {
547 // this is fine, but maybe we should use a different return code
548 // in the future to higher layers can distinguish this case
549 slot.currentItem._status = WaitingSyncItem::NotFound;
550 _freshTiles.push_back(slot.currentItem);
552 } else if (res != SVNRepository::SVN_NO_ERROR) {
553 fail(slot.currentItem);
555 updated(slot.currentItem, slot.isNewDirectory);
556 SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
557 << slot.stamp.elapsedMSec() << " msec");
560 // whatever happened, we're done with this repository instance
562 slot.repository.reset();
565 // init and start sync of the next repository
566 if (!slot.queue.empty()) {
567 slot.currentItem = slot.queue.front();
570 SGPath path(_local_dir);
571 path.append(slot.currentItem._dir);
572 slot.isNewDirectory = !path.exists();
573 if (slot.isNewDirectory) {
574 int rc = path.create_dir( 0755 );
576 SG_LOG(SG_TERRAIN,SG_ALERT,
577 "Cannot create directory '" << path << "', return code = " << rc );
578 fail(slot.currentItem);
581 } // of creating directory step
583 slot.repository.reset(new SVNRepository(path, &_http));
584 slot.repository->setBaseUrl(_svn_server + "/" + slot.currentItem._dir);
585 slot.repository->update();
587 slot.nextWarnTimeout = 20000;
590 SG_LOG(SG_TERRAIN, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
594 void SGTerraSync::SvnThread::runInternal()
598 _transfer_rate = _http.transferRateBytesPerSec();
602 // drain the waiting tiles queue into the sync slot queues.
603 while (!waitingTiles.empty()) {
604 WaitingSyncItem next = waitingTiles.pop_front();
605 if (isPathCached(next)) {
607 SG_LOG(SG_TERRAIN, SG_DEBUG, "TerraSync Cache hit for: '" << next._dir << "'");
608 next._status = WaitingSyncItem::Cached;
609 _freshTiles.push_back(next);
614 unsigned int slot = syncSlotForType(next._type);
615 _syncSlots[slot].queue.push(next);
618 bool anySlotBusy = false;
619 // update each sync slot in turn
620 for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
621 updateSyncSlot(_syncSlots[slot]);
622 anySlotBusy |= _syncSlots[slot].busy;
626 } // of thread running loop
629 bool SGTerraSync::SvnThread::isPathCached(const WaitingSyncItem& next) const
631 CompletedTiles::const_iterator ii = _completedTiles.find( next._dir );
632 if (ii == _completedTiles.end()) {
636 // check if the path still physically exists
637 SGPath p(_local_dir);
643 time_t now = time(0);
644 return (ii->second > now);
647 void SGTerraSync::SvnThread::fail(WaitingSyncItem failedItem)
649 time_t now = time(0);
650 _consecutive_errors++;
652 failedItem._status = WaitingSyncItem::Failed;
653 _freshTiles.push_back(failedItem);
654 _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
658 void SGTerraSync::SvnThread::updated(WaitingSyncItem item, bool isNewDirectory)
660 time_t now = time(0);
661 _consecutive_errors = 0;
663 SG_LOG(SG_TERRAIN,SG_INFO,
664 "Successfully synchronized directory '" << item._dir << "'");
666 item._status = WaitingSyncItem::Updated;
667 if (item._type == WaitingSyncItem::Tile) {
668 _updated_tile_count++;
671 _freshTiles.push_back(item);
672 _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
674 writeCompletedTilesPersistentCache();
677 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
679 if (!_persistentCachePath.exists()) {
683 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
684 time_t now = time(0);
687 readProperties(_persistentCachePath.str(), cacheRoot);
688 } catch (sg_exception& e) {
689 SG_LOG(SG_TERRAIN, SG_INFO, "corrupted persistent cache, discarding");
693 for (int i=0; i<cacheRoot->nChildren(); ++i) {
694 SGPropertyNode* entry = cacheRoot->getChild(i);
695 string tileName = entry->getStringValue("path");
696 time_t stamp = entry->getIntValue("stamp");
701 _completedTiles[tileName] = stamp;
705 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
708 if (_persistentCachePath.isNull()) {
712 std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
717 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
718 CompletedTiles::const_iterator it = _completedTiles.begin();
719 for (; it != _completedTiles.end(); ++it) {
720 SGPropertyNode* entry = cacheRoot->addChild("entry");
721 entry->setStringValue("path", it->first);
722 entry->setIntValue("stamp", it->second);
725 writeProperties(f, cacheRoot, true /* write_all */);
729 ///////////////////////////////////////////////////////////////////////////////
730 // SGTerraSync ////////////////////////////////////////////////////////////////
731 ///////////////////////////////////////////////////////////////////////////////
732 SGTerraSync::SGTerraSync(SGPropertyNode_ptr root) :
736 _terraRoot(root->getNode("/sim/terrasync",true)),
740 _svnThread = new SvnThread();
741 _log = new BufferedLogCallback(SG_TERRAIN, SG_INFO);
742 _log->truncateAt(255);
744 sglog().addCallback(_log);
747 SGTerraSync::~SGTerraSync()
749 _tiedProperties.Untie();
752 sglog().removeCallback(_log);
756 void SGTerraSync::init()
763 _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
768 void SGTerraSync::reinit()
770 // do not reinit when enabled and we're already up and running
771 if ((_terraRoot->getBoolValue("enabled",false))&&
772 (_svnThread->_active && _svnThread->_running))
779 if (_terraRoot->getBoolValue("enabled",false))
781 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
782 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
783 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
784 _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
785 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
786 _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
787 _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
788 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
789 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
791 if (_svnThread->start())
793 syncAirportsModels();
794 if (last_lat != NOWHERE && last_lon != NOWHERE)
796 // reschedule most recent position
801 schedulePosition(lat, lon);
806 _stalledNode->setBoolValue(_svnThread->_stalled);
809 void SGTerraSync::bind()
816 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
817 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
818 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
819 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
820 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
821 _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
822 _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
824 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
825 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
826 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
827 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
828 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
829 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
830 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
831 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
832 _stalledNode = _terraRoot->getNode("stalled", true);
833 _stalledNode->setBoolValue(_svnThread->_stalled);
834 _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
837 void SGTerraSync::unbind()
840 _tiedProperties.Untie();
845 void SGTerraSync::update(double)
847 static SGBucket bucket;
848 if (_svnThread->isDirty())
850 if (!_svnThread->_active)
852 if (_svnThread->_stalled)
854 SG_LOG(SG_TERRAIN,SG_ALERT,
855 "Automatic scenery download/synchronization stalled. Too many errors.");
859 // not really an alert - just always show this message
860 SG_LOG(SG_TERRAIN,SG_ALERT,
861 "Automatic scenery download/synchronization has stopped.");
863 _stalledNode->setBoolValue(_svnThread->_stalled);
866 while (_svnThread->hasNewTiles())
868 WaitingSyncItem next = _svnThread->getNewTile();
870 if (next._type == WaitingSyncItem::Tile) {
871 if (_activeTileDirs.find(next._dir) == _activeTileDirs.end()) {
872 SG_LOG(SG_TERRAIN, SG_INFO, "TTTTTTTT: finished tile not found in active set!: " << next._dir);
875 _activeTileDirs.erase(next._dir);
877 } // of freshly synced items
881 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
883 void SGTerraSync::syncAirportsModels()
885 static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
886 // note "request" method uses LIFO order, i.e. processes most recent request first
887 for( unsigned i = 0; i < strlen(bounds)/2; i++ )
889 for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
892 dir << "Airports/" << synced_other;
893 WaitingSyncItem w(dir.str(), WaitingSyncItem::AirportData);
894 _svnThread->request( w );
898 WaitingSyncItem w("Models", WaitingSyncItem::SharedModels);
899 _svnThread->request( w );
903 void SGTerraSync::syncArea( int lat, int lon )
905 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
908 int baselat, baselon;
911 int base = (int)(lat / 10);
912 if ( lat == base * 10 ) {
915 baselat = (base - 1) * 10;
919 baselat = (int)(lat / 10) * 10;
923 int base = (int)(lon / 10);
924 if ( lon == base * 10 ) {
927 baselon = (base - 1) * 10;
931 baselon = (int)(lon / 10) * 10;
937 << EW << setw(3) << abs(baselon) << NS << setw(2) << abs(baselat) << "/"
938 << EW << setw(3) << abs(lon) << NS << setw(2) << abs(lat);
940 syncAreaByPath(dir.str());
943 void SGTerraSync::syncAreaByPath(const std::string& aPath)
945 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
946 for (const char** tree = &terrainobjects[0]; *tree; tree++)
948 std::string dir = string(*tree) + aPath;
949 if (_activeTileDirs.find(dir) != _activeTileDirs.end()) {
953 _activeTileDirs.insert(dir);
954 WaitingSyncItem w(dir, WaitingSyncItem::Tile);
955 _svnThread->request( w );
960 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
962 if ( lat_dir == 0 && lon_dir == 0 ) {
964 // do surrounding 8 1x1 degree areas.
965 for ( int i = lat - 1; i <= lat + 1; ++i ) {
966 for ( int j = lon - 1; j <= lon + 1; ++j ) {
967 if ( i != lat || j != lon ) {
973 if ( lat_dir != 0 ) {
974 syncArea( lat + lat_dir, lon - 1 );
975 syncArea( lat + lat_dir, lon + 1 );
976 syncArea( lat + lat_dir, lon );
978 if ( lon_dir != 0 ) {
979 syncArea( lat - 1, lon + lon_dir );
980 syncArea( lat + 1, lon + lon_dir );
981 syncArea( lat, lon + lon_dir );
985 // do current 1x1 degree area first
986 syncArea( lat, lon );
989 bool SGTerraSync::scheduleTile(const SGBucket& bucket)
991 std::string basePath = bucket.gen_base_path();
992 syncAreaByPath(basePath);
996 bool SGTerraSync::schedulePosition(int lat, int lon)
1000 // Ignore messages where the location does not change
1001 if ( lat != last_lat || lon != last_lon )
1003 if (_svnThread->_running)
1007 if ( last_lat != NOWHERE && last_lon != NOWHERE )
1009 int dist = lat - last_lat;
1012 lat_dir = dist / abs(dist);
1018 dist = lon - last_lon;
1021 lon_dir = dist / abs(dist);
1028 SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
1029 "lat = " << lat << ", lon = " << lon <<
1030 ", lat_dir = " << lat_dir << ", " <<
1031 "lon_dir = " << lon_dir);
1033 syncAreas( lat, lon, lat_dir, lon_dir );
1043 void SGTerraSync::reposition()
1045 last_lat = last_lon = NOWHERE;
1048 bool SGTerraSync::isTileDirPending(const std::string& sceneryDir) const
1050 if (!_svnThread->_running) {
1054 const char* terrainobjects[3] = { "Terrain/", "Objects/", 0 };
1055 for (const char** tree = &terrainobjects[0]; *tree; tree++) {
1056 string s = *tree + sceneryDir;
1057 if (_activeTileDirs.find(s) != _activeTileDirs.end()) {