From 4184740ce811cd1d59bf45c699d3532169396aa0 Mon Sep 17 00:00:00 2001 From: Alexander Bock Date: Fri, 9 Jun 2017 16:09:58 -0400 Subject: [PATCH] Code cleanup --- src/documentation/documentation.cpp | 1 - src/engine/configurationmanager.cpp | 1 - src/engine/downloadmanager.cpp | 107 ++++++------ src/engine/logfactory.cpp | 1 - src/engine/moduleengine.cpp | 5 +- src/engine/openspaceengine.cpp | 26 +-- src/engine/settingsengine.cpp | 19 +- src/engine/syncengine.cpp | 2 +- src/mission/missionmanager.cpp | 1 - src/network/networkengine.cpp | 93 ++++++---- src/network/parallelconnection.cpp | 231 +++++++++++++++---------- src/performance/performancemanager.cpp | 2 - 12 files changed, 269 insertions(+), 220 deletions(-) diff --git a/src/documentation/documentation.cpp b/src/documentation/documentation.cpp index e82cea9388..3fe89f43ce 100644 --- a/src/documentation/documentation.cpp +++ b/src/documentation/documentation.cpp @@ -81,7 +81,6 @@ std::string to_string(openspace::documentation::TestResult::Offense::Reason reas return "Wrong type"; default: throw ghoul::MissingCaseException(); - } } diff --git a/src/engine/configurationmanager.cpp b/src/engine/configurationmanager.cpp index 71c7b32e58..17bb3e8afd 100644 --- a/src/engine/configurationmanager.cpp +++ b/src/engine/configurationmanager.cpp @@ -115,7 +115,6 @@ string ConfigurationManager::findConfiguration(const string& filename) { } // Otherwise, we traverse the directory tree up - Directory nextDirectory = directory.parentDirectory( ghoul::filesystem::Directory::AbsolutePath::Yes ); diff --git a/src/engine/downloadmanager.cpp b/src/engine/downloadmanager.cpp index d1e205788a..1d755a084a 100644 --- a/src/engine/downloadmanager.cpp +++ b/src/engine/downloadmanager.cpp @@ -27,29 +27,24 @@ #include #include #include -#include #include + #include -#include -#include #include +#include +#include +#include #ifdef OPENSPACE_CURL_ENABLED #include #endif -#ifdef WIN32 -#include -#endif - -#define USE_MULTITHREADED_DOWNLOAD - namespace { - const std::string _loggerCat = "DownloadManager"; + const char* _loggerCat = "DownloadManager"; - const std::string RequestIdentifier = "identifier"; - const std::string RequestFileVersion = "file_version"; - const std::string RequestApplicationVersion = "application_version"; + const char* RequestIdentifier = "identifier"; + const char* RequestFileVersion = "file_version"; + const char* RequestApplicationVersion = "application_version"; struct ProgressInformation { std::shared_ptr future; @@ -58,12 +53,11 @@ namespace { }; size_t writeData(void* ptr, size_t size, size_t nmemb, FILE* stream) { - size_t written; - written = fwrite(ptr, size, nmemb, stream); + size_t written = fwrite(ptr, size, nmemb, stream); return written; } - size_t writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp){ + size_t writeMemoryCallback(void *contents, size_t size, size_t nmemb, void* userp) { size_t realsize = size * nmemb; auto mem = static_cast(userp); @@ -71,7 +65,7 @@ namespace { realloc(mem->buffer, mem->size + realsize + 1) ); if (!mem->buffer) { - /* out of memory! */ + // out of memory printf("not enough memory (realloc returned NULL)\n"); return 0; } @@ -83,11 +77,10 @@ namespace { return realsize; } - int xferinfo(void* p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t, - curl_off_t) - { - if (dltotal == 0) + int xferinfo(void* p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t, curl_off_t) { + if (dltotal == 0) { return 0; + } ghoul_assert(p, "Passed progress information is nullptr"); ProgressInformation* i = static_cast(p); @@ -161,8 +154,9 @@ std::shared_ptr DownloadManager::downloadFile( bool failOnError, unsigned int timeout_secs, DownloadFinishedCallback finishedCallback, DownloadProgressCallback progressCallback) { - if (!overrideFile && FileSys.fileExists(file)) + if (!overrideFile && FileSys.fileExists(file)) { return nullptr; + } std::shared_ptr future = std::make_shared(file.filename()); errno = 0; @@ -185,13 +179,8 @@ std::shared_ptr DownloadManager::downloadFile( ); } - auto downloadFunction = [url, - failOnError, - timeout_secs, - finishedCallback, - progressCallback, - future, - fp]() { + auto downloadFunction = [url, failOnError, timeout_secs, finishedCallback, + progressCallback, future, fp]() { CURL* curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); @@ -216,26 +205,28 @@ std::shared_ptr DownloadManager::downloadFile( curl_easy_cleanup(curl); fclose(fp); - if (res == CURLE_OK) + if (res == CURLE_OK) { future->isFinished = true; - else + } + else { future->errorMessage = curl_easy_strerror(res); + } - if (finishedCallback) + if (finishedCallback) { finishedCallback(*future); + } } }; if (_useMultithreadedDownload) { std::thread t = std::thread(downloadFunction); - -#ifdef WIN32 - std::thread::native_handle_type h = t.native_handle(); - SetPriorityClass(h, IDLE_PRIORITY_CLASS); - SetThreadPriority(h, THREAD_PRIORITY_LOWEST); -#else - // TODO: Implement thread priority ---abock -#endif + + using namespace ghoul::thread; + ghoul::thread::setPriority( + t, + ghoul::thread::ThreadPriorityClass::Idle, + ghoul::thread::ThreadPriorityLevel::Lowest + ); t.detach(); } @@ -282,8 +273,8 @@ std::future DownloadManager::fetchFile( getline(ss, extension ,'/'); getline(ss, extension); file.format = extension; - } else{ - LWARNING("Could not get File extension from file downloaded from: " + url); + } else { + LWARNING("Could not get extension from file downloaded from: " + url); } successCallback(file); curl_easy_cleanup(curl); @@ -295,8 +286,10 @@ std::future DownloadManager::fetchFile( // Throw an error and use try-catch around call to future.get() //throw std::runtime_error( err ); - // or set a boolean variable in MemoryFile to determine if it is valid/corrupted or not. - // Return MemoryFile even if it is not valid, and check if it is after future.get() call. + // or set a boolean variable in MemoryFile to determine if it is + // valid/corrupted or not. + // Return MemoryFile even if it is not valid, and check if it is after + // future.get() call. file.corrupted = true; return file; } @@ -305,7 +298,8 @@ std::future DownloadManager::fetchFile( return std::async(std::launch::async, downloadFunction); } -std::vector> DownloadManager::downloadRequestFiles( +std::vector> +DownloadManager::downloadRequestFiles( const std::string& identifier, const ghoul::filesystem::Directory& destination, int version, bool overrideFiles, DownloadFinishedCallback finishedCallback, DownloadProgressCallback progressCallback) @@ -354,8 +348,9 @@ std::vector> DownloadManager::downl 0, [](const FileFuture& f) { LDEBUG("Finished: " << f.filePath); } ); - if (future) + if (future) { futures.push_back(future); + } } isFinished = true; }; @@ -378,7 +373,9 @@ void DownloadManager::downloadRequestFilesAsync(const std::string& identifier, const ghoul::filesystem::Directory& destination, int version, bool overrideFiles, AsyncDownloadFinishedCallback callback) { - auto downloadFunction = [this, identifier, destination, version, overrideFiles, callback](){ + auto downloadFunction = + [this, identifier, destination, version, overrideFiles, callback]() + { std::vector> f = downloadRequestFiles( identifier, destination, @@ -397,8 +394,9 @@ void DownloadManager::downloadRequestFilesAsync(const std::string& identifier, ); t.detach(); } - else + else { downloadFunction(); + } } void DownloadManager::getFileExtension(const std::string& url, @@ -411,20 +409,15 @@ void DownloadManager::getFileExtension(const std::string& url, //USING CURLOPT NOBODY curl_easy_setopt(curl, CURLOPT_NOBODY,1); CURLcode res = curl_easy_perform(curl); - if(CURLE_OK == res) { - char *ct; + if (CURLE_OK == res) { + char* ct; // ask for the content-type res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); - if ((res == CURLE_OK) && ct){ - - if (finishedCallback) - finishedCallback(std::string(ct)); + if ((res == CURLE_OK) && ct && finishedCallback) { + finishedCallback(std::string(ct)); } } -/* else - future->errorMessage = curl_easy_strerror(res);*/ - curl_easy_cleanup(curl); } }; diff --git a/src/engine/logfactory.cpp b/src/engine/logfactory.cpp index 01366f9c21..6097277953 100644 --- a/src/engine/logfactory.cpp +++ b/src/engine/logfactory.cpp @@ -153,7 +153,6 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona logLevel = dictionary.value(keyLogLevel); } - using Append = ghoul::logging::TextLog::Append; using TimeStamping = ghoul::logging::Log::TimeStamping; using DateStamping = ghoul::logging::Log::DateStamping; diff --git a/src/engine/moduleengine.cpp b/src/engine/moduleengine.cpp index 6f85e54c11..0fb80fda46 100644 --- a/src/engine/moduleengine.cpp +++ b/src/engine/moduleengine.cpp @@ -81,7 +81,7 @@ void ModuleEngine::registerModule(std::unique_ptr module) { std::vector ModuleEngine::modules() const { std::vector result; - for (auto& m : _modules) { + for (const std::unique_ptr& m : _modules) { result.push_back(m.get()); } return result; @@ -90,7 +90,7 @@ std::vector ModuleEngine::modules() const { ghoul::systemcapabilities::Version ModuleEngine::requiredOpenGLVersion() const { ghoul::systemcapabilities::Version version = { 0, 0, 0 }; - for (const auto& m : _modules) { + for (const std::unique_ptr& m : _modules) { version = std::max(version, m->requiredOpenGLVersion()); } @@ -108,7 +108,6 @@ scripting::LuaLibrary ModuleEngine::luaLibrary() { "Checks whether a specific module is loaded" } } - }; } diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index e4fe28dfab..34ad268eb3 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -98,6 +98,9 @@ namespace { const int CacheVersion = 1; const int DownloadVersion = 1; + const glm::ivec3 FontAtlasSize{ 1536, 1536, 1 }; + + struct { std::string configurationName; std::string sgctConfigurationName; @@ -341,7 +344,7 @@ void OpenSpaceEngine::create(int argc, char** argv, // After registering the modules, the documentations for the available classes // can be added as well for (OpenSpaceModule* m : _engine->_moduleEngine->modules()) { - for (auto&& doc : m->documentations()) { + for (const documentation::Documentation& doc : m->documentations()) { DocEng.addDocumentation(doc); } } @@ -401,7 +404,6 @@ void OpenSpaceEngine::destroy() { FactoryManager::deinitialize(); SpiceManager::deinitialize(); - ghoul::fontrendering::FontRenderer::deinitialize(); LogManager::deinitialize(); @@ -756,8 +758,7 @@ void OpenSpaceEngine::loadFonts() { ghoul::Dictionary fonts; configurationManager().getValue(ConfigurationManager::KeyFonts, fonts); - glm::ivec3 fontAtlasSize{1024, 1024, 1}; - _fontManager = std::make_unique(fontAtlasSize); + _fontManager = std::make_unique(FontAtlasSize); for (const std::string& key : fonts.keys()) { std::string font = fonts.value(key); @@ -771,14 +772,16 @@ void OpenSpaceEngine::loadFonts() { LINFO("Registering font '" << font << "' with key '" << key << "'"); bool success = _fontManager->registerFontPath(key, font); - if (!success) + if (!success) { LERROR("Error registering font '" << font << "' with key '" << key << "'"); + } } try { bool initSuccess = ghoul::fontrendering::FontRenderer::initialize(); - if (!initSuccess) + if (!initSuccess) { LERROR("Error initializing default font renderer"); + } ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize( _renderEngine->fontResolution() @@ -971,7 +974,6 @@ void OpenSpaceEngine::initializeGL() { LINFO("Initializing Rendering Engine"); - // @CLEANUP: Remove the return statement and replace with exceptions ---abock _renderEngine->initializeGL(); for (const auto& func : _moduleCallbacks.initializeGL) { @@ -980,8 +982,6 @@ void OpenSpaceEngine::initializeGL() { LINFO("Finished initializing OpenGL"); - // If using swapgroups, - LINFO("IsUsingSwapGroups: " << _windowWrapper->isUsingSwapGroups()); LINFO("IsSwapGroupMaster: " << _windowWrapper->isSwapGroupMaster()); @@ -1016,8 +1016,11 @@ void OpenSpaceEngine::preSynchronization() { double dt = _windowWrapper->averageDeltaTime(); _timeManager->preSynchronization(dt); - auto scheduledScripts = _scriptScheduler->progressTo(timeManager().time().j2000Seconds()); - for (auto it = scheduledScripts.first; it != scheduledScripts.second; ++it) { + using Iter = std::vector::const_iterator; + std::pair scheduledScripts = _scriptScheduler->progressTo( + timeManager().time().j2000Seconds() + ); + for (Iter it = scheduledScripts.first; it != scheduledScripts.second; ++it) { _scriptEngine->queueScript( *it, ScriptEngine::RemoteScripting::Yes ); @@ -1030,7 +1033,6 @@ void OpenSpaceEngine::preSynchronization() { _renderEngine->camera()->invalidateCache(); _parallelConnection->preSynchronization(); - } for (const auto& func : _moduleCallbacks.preSync) { diff --git a/src/engine/settingsengine.cpp b/src/engine/settingsengine.cpp index 6e330080bb..999ac1d61e 100644 --- a/src/engine/settingsengine.cpp +++ b/src/engine/settingsengine.cpp @@ -49,11 +49,9 @@ SettingsEngine::SettingsEngine() , _spiceUseExceptions("enableSpiceExceptions", "Enable Spice Exceptions", false) { _spiceUseExceptions.onChange([this] { - if (_spiceUseExceptions) { - SpiceManager::ref().setExceptionHandling(SpiceManager::UseException::Yes); - } else { - SpiceManager::ref().setExceptionHandling(SpiceManager::UseException::No); - } + SpiceManager::ref().setExceptionHandling( + SpiceManager::UseException(_spiceUseExceptions) + ); }); addProperty(_spiceUseExceptions); addProperty(_busyWaitForDecode); @@ -69,13 +67,12 @@ void SettingsEngine::initialize() { const std::vector scenes = ghoul::filesystem::Directory(sceneDir).readFiles(); for (std::size_t i = 0; i < scenes.size(); ++i) { - std::size_t found = scenes[i].find_last_of("/\\"); + const std::size_t found = scenes[i].find_last_of("/\\"); _scenes.addOption(static_cast(i), scenes[i].substr(found + 1)); } // Set interaction to change ConfigurationManager and schedule the load - _scenes.onChange( - [this, sceneDir]() { + _scenes.onChange([this, sceneDir]() { std::string sceneFile = _scenes.getDescriptionByValue(_scenes); OsEng.configurationManager().setValue( ConfigurationManager::KeyConfigScene, sceneFile); @@ -91,15 +88,15 @@ void SettingsEngine::setModules(const std::vector& modules) { } bool SettingsEngine::busyWaitForDecode() { - return _busyWaitForDecode.value(); + return _busyWaitForDecode; } bool SettingsEngine::logSGCTOutOfOrderErrors() { - return _logSGCTOutOfOrderErrors.value(); + return _logSGCTOutOfOrderErrors; } bool SettingsEngine::useDoubleBuffering() { - return _useDoubleBuffering.value(); + return _useDoubleBuffering; } } // namespace openspace diff --git a/src/engine/syncengine.cpp b/src/engine/syncengine.cpp index fc4635b2ba..684669b5f9 100644 --- a/src/engine/syncengine.cpp +++ b/src/engine/syncengine.cpp @@ -87,7 +87,7 @@ void SyncEngine::removeSyncable(Syncable* syncable) { } void SyncEngine::removeSyncables(const std::vector& syncables) { - for (const auto& syncable : syncables) { + for (Syncable* syncable : syncables) { removeSyncable(syncable); } } diff --git a/src/mission/missionmanager.cpp b/src/mission/missionmanager.cpp index fce3d18352..224c894c38 100644 --- a/src/mission/missionmanager.cpp +++ b/src/mission/missionmanager.cpp @@ -38,7 +38,6 @@ MissionManager::MissionManagerException::MissionManagerException(std::string err : ghoul::RuntimeError(std::move(error), "MissionManager") {} - MissionManager::MissionManager() : _currentMission(_missionMap.end()) {} diff --git a/src/network/networkengine.cpp b/src/network/networkengine.cpp index 0d8e559fb7..664551ede7 100644 --- a/src/network/networkengine.cpp +++ b/src/network/networkengine.cpp @@ -23,34 +23,35 @@ ****************************************************************************************/ #include -#include -#include + #include #include +#include +#include #include +#include #include #include #include -#include - namespace { - const std::string _loggerCat = "NetworkEngine"; + const char* _loggerCat = "NetworkEngine"; - const std::string StatusMessageIdentifierName = "StatusMessage"; - const std::string MappingIdentifierIdentifierName = "IdentifierMapping"; - const std::string InitialMessageFinishedIdentifierName = "InitialMessageFinished"; + const char* StatusMessageIdentifierName = "StatusMessage"; + const char* MappingIdentifierIdentifierName = "IdentifierMapping"; + const char* InitialMessageFinishedIdentifierName = "InitialMessageFinished"; const char MessageTypeLuaScript = '0'; const char MessageTypeExternalControlConnected = '1'; -} +} // namespace namespace openspace { NetworkEngine::NetworkEngine() - : _lastAssignedIdentifier(MessageIdentifier(-1)) // -1 is okay as we assign one identifier in this ctor + // -1 is okay as we assign one identifier in this ctor + : _lastAssignedIdentifier(MessageIdentifier(-1)) , _shouldPublishStatusMessage(true) { static_assert( @@ -66,30 +67,34 @@ bool NetworkEngine::handleMessage(const std::string& message) { // The first byte determines the type of message const char type = message[0]; switch (type) { - case MessageTypeLuaScript: // LuaScript - { - std::string script = message.substr(1); - //LINFO("Received Lua Script: '" << script << "'"); - OsEng.scriptEngine().queueScript(script, scripting::ScriptEngine::RemoteScripting::No); - return true; - } - case MessageTypeExternalControlConnected: - { - publishIdentifierMappingMessage(); - std::this_thread::sleep_for(std::chrono::milliseconds(250)); - sendInitialInformation(); - return true; - } - default: - LERROR("Unknown type '" << type << "'"); - return false; - } - + case MessageTypeLuaScript: // LuaScript + { + std::string script = message.substr(1); + OsEng.scriptEngine().queueScript( + script, + scripting::ScriptEngine::RemoteScripting::No + ); + return true; + } + case MessageTypeExternalControlConnected: + { + publishIdentifierMappingMessage(); + std::this_thread::sleep_for(std::chrono::milliseconds(250)); + sendInitialInformation(); + return true; + } + default: + LERROR("Unknown type '" << type << "'"); + return false; + } } void NetworkEngine::publishStatusMessage() { - if (!_shouldPublishStatusMessage || !OsEng.windowWrapper().isExternalControlConnected()) + if (!_shouldPublishStatusMessage || + !OsEng.windowWrapper().isExternalControlConnected()) + { return; + } // Protocol: // 8 bytes: time as a ET double // 24 bytes: time as a UTC string @@ -115,7 +120,10 @@ void NetworkEngine::publishStatusMessage() { std::memmove(buffer.data() + currentLocation, &time, sizeof(time)); currentLocation += sizeof(time); - std::memmove(buffer.data() + currentLocation, timeString.c_str(), timeString.length()); + std::memmove( + buffer.data() + currentLocation, + timeString.c_str(), timeString.length() + ); currentLocation += static_cast(timeString.length()); std::memmove(buffer.data() + currentLocation, &delta, sizeof(delta)); @@ -135,7 +143,10 @@ void NetworkEngine::publishIdentifierMappingMessage() { std::memcpy(buffer.data(), &size, sizeof(uint16_t)); currentWritingPosition += sizeof(uint16_t); for (const std::pair& i : _identifiers) { - std::memcpy(buffer.data() + currentWritingPosition, &(i.second), sizeof(MessageIdentifier)); + std::memcpy( + buffer.data() + currentWritingPosition, + &(i.second), sizeof(MessageIdentifier) + ); currentWritingPosition += sizeof(MessageIdentifier); uint8_t stringSize = static_cast(i.first.size()); std::memcpy(buffer.data() + currentWritingPosition, &stringSize, sizeof(uint8_t)); @@ -150,8 +161,9 @@ void NetworkEngine::publishIdentifierMappingMessage() { NetworkEngine::MessageIdentifier NetworkEngine::identifier(std::string name) { auto i = _identifiers.find(name); - if (i != _identifiers.end()) + if (i != _identifiers.end()) { return i->second; + } else { _lastAssignedIdentifier++; @@ -162,13 +174,16 @@ NetworkEngine::MessageIdentifier NetworkEngine::identifier(std::string name) { } } -void NetworkEngine::publishMessage(MessageIdentifier identifier, std::vector message) { +void NetworkEngine::publishMessage(MessageIdentifier identifier, + std::vector message) +{ _messagesToSend.push_back({ std::move(identifier), std::move(message) }); } void NetworkEngine::sendMessages() { - if (!OsEng.windowWrapper().isExternalControlConnected()) + if (!OsEng.windowWrapper().isExternalControlConnected()) { return; + } for (Message& m : _messagesToSend) { // Protocol: @@ -202,7 +217,9 @@ void NetworkEngine::sendInitialInformation() { std::vector payload = m.body; payload.insert(payload.begin(), identifier.data.begin(), identifier.data.end()); OsEng.windowWrapper().sendMessageToExternalControl(payload); - LINFO("Sent initial message: (s=" << m.body.size() << ") [i=" << identifier.value << "]"); + LINFO("Sent initial message: (s=" << m.body.size() << ")" << + "[i=" << identifier.value << "]" + ); std::this_thread::sleep_for(std::chrono::milliseconds(SleepTime)); } @@ -223,7 +240,9 @@ void NetworkEngine::sendInitialInformation() { _shouldPublishStatusMessage = true; } -void NetworkEngine::setInitialConnectionMessage(MessageIdentifier identifier, std::vector message) { +void NetworkEngine::setInitialConnectionMessage(MessageIdentifier identifier, + std::vector message) +{ // Add check if a MessageIdentifier already exists ---abock _initialConnectionMessages.push_back({std::move(identifier), std::move(message)}); } diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index 85db183e4f..18ef602172 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -62,27 +62,26 @@ #endif #include + +#include #include #include #include #include #include -#include -#include -#include -#include #include +#include +#include #include -//lua functions #include "parallelconnection_lua.inl" namespace { const uint32_t ProtocolVersion = 2; const size_t MaxLatencyDiffs = 64; - const std::string _loggerCat = "ParallelConnection"; -} + const char* _loggerCat = "ParallelConnection"; +} // namespace namespace openspace { @@ -94,8 +93,20 @@ ParallelConnection::ParallelConnection() , _address("address", "Address", "localhost") , _name("name", "Connection name", "Anonymous") , _bufferTime("bufferTime", "Buffer Time", 1, 0.5, 10) - , _timeKeyframeInterval("timeKeyframeInterval", "Time keyframe interval", 0.1f, 0.f, 1.f) - , _cameraKeyframeInterval("cameraKeyframeInterval", "Camera Keyframe interval", 0.1f, 0.f, 1.f) + , _timeKeyframeInterval( + "timeKeyframeInterval", + "Time keyframe interval", + 0.1f, + 0.f, + 1.f + ) + , _cameraKeyframeInterval( + "cameraKeyframeInterval", + "Camera Keyframe interval", + 0.1f, + 0.f, + 1.f + ) , _timeTolerance("timeTolerance", "Time tolerance", 1.f, 0.5f, 5.f) , _lastTimeKeyframeTimestamp(0) , _lastCameraKeyframeTimestamp(0) @@ -127,50 +138,51 @@ ParallelConnection::ParallelConnection() addProperty(_timeTolerance); _connectionEvent = std::make_shared>(); - _handlerThread = std::make_unique(&ParallelConnection::threadManagement, this); + _handlerThread = std::make_unique( + &ParallelConnection::threadManagement, + this + ); } -ParallelConnection::~ParallelConnection(){ - - //signal that a disconnect should occur +ParallelConnection::~ParallelConnection() { + // signal that a disconnect should occur signalDisconnect(); - //signal that execution has stopped + // signal that execution has stopped _isRunning.store(false); - //join handler + // join handler _handlerThread->join(); } -void ParallelConnection::threadManagement(){ +void ParallelConnection::threadManagement() { // The _disconnectCondition.wait(unqlock) stalls // How about moving this out of the thread and into the destructor? ---abock - //while we're still running + // while we're still running while(_isRunning){ - { - //lock disconnect mutex mutex - //not really needed since no data is modified but conditions need a mutex - std::unique_lock disconnectLock(_disconnectMutex); - //wait for a signal to disconnect - _disconnectCondition.wait(disconnectLock, [this]() { return _disconnect.load(); }); + // lock disconnect mutex mutex + // not really needed since no data is modified but conditions need a mutex + std::unique_lock disconnectLock(_disconnectMutex); + // wait for a signal to disconnect + _disconnectCondition.wait( + disconnectLock, + [this]() { return _disconnect.load(); } + ); - //perform actual disconnect - disconnect(); - - } + // perform actual disconnect + disconnect(); } } -void ParallelConnection::signalDisconnect(){ +void ParallelConnection::signalDisconnect() { //signal handler thread to disconnect _disconnect = true; _sendCondition.notify_all(); // Allow send function to terminate. _disconnectCondition.notify_all(); // Unblock thread management thread. } -void ParallelConnection::closeSocket(){ - +void ParallelConnection::closeSocket() { /* Windows shutdown options * SD_RECIEVE @@ -194,36 +206,35 @@ void ParallelConnection::closeSocket(){ _clientSocket = INVALID_SOCKET; } -void ParallelConnection::disconnect(){ - //we're disconnecting - - if (_clientSocket != INVALID_SOCKET){ - - //must be run before trying to join communication threads, else the threads are stuck trying to receive data +void ParallelConnection::disconnect() { + // We're disconnecting + if (_clientSocket != INVALID_SOCKET) { + // Must be run before trying to join communication threads, else the threads are + // stuck trying to receive data closeSocket(); - //tell connection thread to stop trying to connect - _tryConnect.store(false); + // Ttell connection thread to stop trying to connect + _tryConnect = false; - //tell send thread to stop sending and listen thread to stop listenin - _isConnected.store(false); + // Tell send thread to stop sending and listen thread to stop listenin + _isConnected = false; setStatus(Status::Disconnected); - //join connection thread and delete it - if(_connectionThread != nullptr){ + // join connection thread and delete it + if (_connectionThread != nullptr) { _connectionThread->join(); _connectionThread = nullptr; } - //join send thread and delete it - if (_sendThread != nullptr){ + // join send thread and delete it + if (_sendThread != nullptr) { _sendThread->join(); _sendThread = nullptr; } - //join listen thread and delete it - if( _listenThread != nullptr){ + // join listen thread and delete it + if (_listenThread != nullptr) { _listenThread->join(); _listenThread = nullptr; } @@ -233,19 +244,19 @@ void ParallelConnection::disconnect(){ } } -void ParallelConnection::clientConnect(){ - - //we're already connected (or already trying to connect), do nothing (dummy check) - if(_isConnected.load() || _tryConnect.load()){ +void ParallelConnection::clientConnect() { + // We're already connected (or already trying to connect), do nothing (dummy check) + if (_isConnected.load() || _tryConnect.load()) { return; } - if (!initNetworkAPI()){ + if (!initNetworkAPI()) { LERROR("Failed to initialize network API for Parallel Connection"); return; } - struct addrinfo *addresult = NULL, hints; + struct addrinfo* addresult = NULL; + struct addrinfo hints; memset(&hints, 0, sizeof(hints)); @@ -255,33 +266,39 @@ void ParallelConnection::clientConnect(){ hints.ai_flags = AI_PASSIVE; // Resolve the local address and port to be used by the server - int result = getaddrinfo(_address.value().c_str(), _port.value().c_str(), &hints, &addresult); - if (result != 0) - { + int result = getaddrinfo( + _address.value().c_str(), + _port.value().c_str(), + &hints, + &addresult + ); + if (result != 0) { LERROR("Failed to parse hints for Parallel Connection"); return; } - //we're not connected - _isConnected.store(false); + // We're not connected + _isConnected = false; - //we want to try and establish a connection - _tryConnect.store(true); - - //start connection thread - _connectionThread = std::make_unique(&ParallelConnection::establishConnection, this, addresult); + // We want to try and establish a connection + _tryConnect = true; + // Start connection thread + _connectionThread = std::make_unique( + &ParallelConnection::establishConnection, + this, + addresult + ); } -void ParallelConnection::establishConnection(addrinfo *info){ - +void ParallelConnection::establishConnection(addrinfo *info) { _clientSocket = socket(info->ai_family, info->ai_socktype, info->ai_protocol); - if (_clientSocket == INVALID_SOCKET){ + if (_clientSocket == INVALID_SOCKET) { freeaddrinfo(info); LERROR("Failed to create client socket, disconnecting."); - //signal a disconnect + // Signal a disconnect signalDisconnect(); } @@ -289,7 +306,7 @@ void ParallelConnection::establishConnection(addrinfo *info){ int falseFlag = 0; int result; - //set no delay + // Set no delay result = setsockopt( _clientSocket, // socket affected IPPROTO_TCP, // set option at TCP level @@ -298,7 +315,7 @@ void ParallelConnection::establishConnection(addrinfo *info){ sizeof(int) // length of option value ); - //set send timeout + // Set send timeout int timeout = 0; result = setsockopt( _clientSocket, @@ -308,7 +325,7 @@ void ParallelConnection::establishConnection(addrinfo *info){ sizeof(timeout) ); - //set receive timeout + // Set receive timeout result = setsockopt( _clientSocket, SOL_SOCKET, @@ -349,16 +366,19 @@ void ParallelConnection::establishConnection(addrinfo *info){ LINFO("Connection established with server at ip: "<< _address); // We're connected - _isConnected.store(true); + _isConnected = true; // Start sending messages _sendThread = std::make_unique(&ParallelConnection::sendFunc, this); // Start listening for communication - _listenThread = std::make_unique(&ParallelConnection::listenCommunication, this); + _listenThread = std::make_unique( + &ParallelConnection::listenCommunication, + this + ); // We no longer need to try to establish connection - _tryConnect.store(false); + _tryConnect = false; _sendBufferMutex.lock(); _sendBuffer.clear(); @@ -390,10 +410,18 @@ void ParallelConnection::sendAuthentication() { uint32_t passCode = hash(_password.value()); // Write passcode to buffer - buffer.insert(buffer.end(), reinterpret_cast(&passCode), reinterpret_cast(&passCode) + sizeof(uint32_t)); + buffer.insert( + buffer.end(), + reinterpret_cast(&passCode), + reinterpret_cast(&passCode) + sizeof(uint32_t) + ); // Write the length of the nodes name to buffer - buffer.insert(buffer.end(), reinterpret_cast(&nameLength), reinterpret_cast(&nameLength) + sizeof(uint32_t)); + buffer.insert( + buffer.end(), + reinterpret_cast(&nameLength), + reinterpret_cast(&nameLength) + sizeof(uint32_t) + ); // Write this node's name to buffer buffer.insert(buffer.end(), name.begin(), name.end()); @@ -409,18 +437,18 @@ void ParallelConnection::queueInMessage(const Message& message) { void ParallelConnection::handleMessage(const Message& message) { switch (message.type){ - case MessageType::Data: - dataMessageReceived(message.content); - break; - case MessageType::ConnectionStatus: - connectionStatusMessageReceived(message.content); - break; - case MessageType::NConnections: - nConnectionsMessageReceived(message.content); - break; - default: - //unknown message type - break; + case MessageType::Data: + dataMessageReceived(message.content); + break; + case MessageType::ConnectionStatus: + connectionStatusMessageReceived(message.content); + break; + case MessageType::NConnections: + nConnectionsMessageReceived(message.content); + break; + default: + //unknown message type + break; } } @@ -542,7 +570,10 @@ double ParallelConnection::timeTolerance() const { void ParallelConnection::dataMessageReceived(const std::vector& messageContent) { // The type of data message received uint32_t type = *(reinterpret_cast(messageContent.data())); - std::vector buffer(messageContent.begin() + sizeof(uint32_t), messageContent.end()); + std::vector buffer( + messageContent.begin() + sizeof(uint32_t), + messageContent.end() + ); switch (static_cast(type)) { case datamessagestructures::Type::CameraData: { @@ -576,11 +607,16 @@ void ParallelConnection::dataMessageReceived(const std::vector& messageCon datamessagestructures::ScriptMessage sm; sm.deserialize(buffer); - OsEng.scriptEngine().queueScript(sm._script, scripting::ScriptEngine::RemoteScripting::No); + OsEng.scriptEngine().queueScript( + sm._script, + scripting::ScriptEngine::RemoteScripting::No + ); break; } default: { - LERROR("Unidentified data message with identifier " << type << " received in parallel connection."); + LERROR("Unidentified data message with identifier " << type << + " received in parallel connection." + ); break; } } @@ -661,7 +697,8 @@ void ParallelConnection::sendFunc(){ ); if (result == SOCKET_ERROR) { - LERROR("Failed to send message.\nError: " << + LERROR( + "Failed to send message.\nError: " << _ERRNO << " detected in connection, disconnecting." ); signalDisconnect(); @@ -824,7 +861,10 @@ void ParallelConnection::listenCommunication() { // If enough data was received if (nBytesRead <= 0) { if (!_disconnect) { - LERROR("Error " << _ERRNO << " detected in connection when reading header, disconnecting!"); + LERROR( + "Error " << _ERRNO << + " detected in connection when reading header, disconnecting!" + ); signalDisconnect(); } break; @@ -844,7 +884,10 @@ void ParallelConnection::listenCommunication() { uint32_t messageSizeIn = *(ptr++); if (protocolVersionIn != ProtocolVersion) { - LERROR("Protocol versions do not match. Server version: " << protocolVersionIn << ", Client version: " << ProtocolVersion); + LERROR( + "Protocol versions do not match. Server version: " << + protocolVersionIn << ", Client version: " << ProtocolVersion + ); signalDisconnect(); break; } @@ -862,7 +905,9 @@ void ParallelConnection::listenCommunication() { if (nBytesRead <= 0) { if (!_disconnect) { - LERROR("Error " << _ERRNO << " detected in connection when reading message, disconnecting!"); + LERROR( + "Error " << _ERRNO << + " detected in connection when reading message, disconnecting!"); signalDisconnect(); } break; diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index 5945eb1148..df94a1c5f8 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -43,8 +43,6 @@ namespace { // the global memory alive, and 2 bytes to enforce alignment) const size_t GlobalSharedMemorySize = 4; - const int MaximumNumber = 256; - struct GlobalMemory { uint8_t number; uint8_t referenceCount;