diff --git a/.clang_tidy b/.clang_tidy new file mode 100644 index 0000000000..60ff8d9752 --- /dev/null +++ b/.clang_tidy @@ -0,0 +1,85 @@ +Checks: >- + -*, + bugprone-*, + -bugprone-argument-comment, + -bugprone-easily-swappable-parameters, + -bugprone-implicit-widening-of-multiplication-result, + -bugprone-narrowing-conversions, + -bugprone-suspicious-include, + -bugprone-switch-missing-default-case, + -bugprone-unchecked-optional-access, + clang-analyzer-*, + -clang-analyzer-apiModeling*, + -clang-analyzer-osx*, + -clang-analyzer-security.FloatLoopCounter, + -clang-analyzer-webkit*, + cppcoreguidelines-*, + -cppcoreguidelines-avoid-do-while, + -cppcoreguidelines-avoid-magic-numbers, + -cppcoreguidelines-avoid-non-const-global-variables, + -cppcoreguidelines-narrowing-conversions, + -cppcoreguidelines-no-malloc, + -cppcoreguidelines-owning-memory, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -cppcoreguidelines-pro-type-member-init, + -cppcoreguidelines-pro-type-reinterpret-cast, + -cppcoreguidelines-pro-type-static-cast-downcast, + -cppcoreguidelines-pro-type-union-access, + -cppcoreguidelines-pro-type-vararg, + google-*, + -google-objc-*, + -google-build-using-namespace, + -google-default-arguments, + -google-readability-casting, + -google-readability-function-size, + -google-readability-namespace-comments, + -google-explicit-constructor, + -google-runtime-int, + llvm-*, + -llvm-else-after-return, + -llvm-include-order, + -llvm-qualified-auto, + misc-*, + -misc-include-cleaner, + -misc-no-recursion, + modernize-*, + -modernize-raw-string-literal, + -modernize-return-braced-init-list, + -modernize-use-trailing-return-type, + -modernize-use-auto, + performance-*, + -performance-no-int-to-ptr, + readability-*, + -readability-avoid-unconditional-preprocessor-if, + -readability-else-after-return, + -readability-function-cognitive-complexity, + -readability-identifier-length, + -readability-implicit-bool-conversion, + -readability-magic-numbers, + -readability-named-parameter, + -readability-uppercase-literal-suffix, + -readability-use-anyofallof + +CheckOptions: + - key: bugprone-assert-side-effect.AssertMacros + value: ghoul_assert,ghoul_precondition + - key: cppcoreguidelines-rvalue-reference-param-not-moved.AllowPartialMove + value: True + - key: misc-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: True + - key: modernize-loop-convert.UseCxx20ReverseRanges + value: False + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: False + - key: performance-unnecessary-value-param.AllowedTypes + value: glm::vec2;glm::vec3;glm::vec4;glm::ivec2;glm::ivec3;glm::ivec4;glm::dvec2;glm::dvec3;glm::dvec4;glm::uvec2;glm::uvec3;glm::uvec4;glm::mat2;glm::mat3;glm::mat4;glm::mat[2-4]x[2-4];glm::dmat2;glm::dmat3;glm::dmat4;glm::dmat[2-4]x[2-4];glm::quat;glm::dquat + - key: readability-inconsistent-declaration-parameter-name.Strict + value: True + - key: readability-qualified-auto.AddConstToQualified + value: False + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: True + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: True diff --git a/.gitmodules b/.gitmodules index d98a1a3adf..48dc166939 100644 --- a/.gitmodules +++ b/.gitmodules @@ -41,3 +41,6 @@ [submodule "support/doxygen/css"] path = support/doxygen/css url = https://github.com/jothepro/doxygen-awesome-css.git +[submodule "modules/audio/ext/soloud"] + path = modules/audio/ext/soloud + url = https://github.com/jarikomppa/soloud diff --git a/Jenkinsfile b/Jenkinsfile index 69935d0b96..e2d8a59ff7 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -51,16 +51,15 @@ parallel tools: { stage('tools/scm') { deleteDir(); gitHelper.checkoutGit(url, branch, false); - helper.createDirectory('build'); } stage('tools/cppcheck') { sh( - script: 'cppcheck --enable=all --xml --xml-version=2 -i ext --suppressions-list=support/cppcheck/suppressions.txt include modules src tests 2> build/cppcheck.xml', + script: 'cppcheck --enable=all --xml --xml-version=2 -i ext --suppressions-list=support/cppcheck/suppressions.txt include modules src tests 2> cppcheck.xml', label: 'CPPCheck' ) recordIssues( id: 'tools-cppcheck', - tool: cppCheck(pattern: 'build/cppcheck.xml') + tool: cppCheck(pattern: 'cppcheck.xml') ) } cleanWs() diff --git a/apps/OpenSpace-MinVR/main.cpp b/apps/OpenSpace-MinVR/main.cpp index 382d23499e..46357781ca 100644 --- a/apps/OpenSpace-MinVR/main.cpp +++ b/apps/OpenSpace-MinVR/main.cpp @@ -104,7 +104,7 @@ void Handler::onVREvent(const VRDataIndex& eventData) { else { LERRORC( "onVREvent()", - fmt::format("Received an event named {} of unknown type", eventData.getName()) + std::format("Received an event named {} of unknown type", eventData.getName()) ); } @@ -244,7 +244,7 @@ void Handler::onVREvent(const VRDataIndex& eventData) { global::openSpaceEngine.decode(std::move(synchronizationBuffer)); } else { - LERRORC("onVREvent()", fmt::format("Received an event of unknown type {}", type)); + LERRORC("onVREvent()", std::format("Received an event of unknown type {}", type)); } } @@ -372,7 +372,7 @@ int main(int argc, char** argv) { LFATALC("main", "Could not find configuration: " + configurationFilePath); exit(EXIT_FAILURE); } - LINFO(fmt::format("Configuration Path: '{}'", configurationFilePath)); + LINFO(std::format("Configuration Path: '{}'", configurationFilePath)); // Loading configuration from disk LDEBUG("Loading configuration from disk"); diff --git a/apps/OpenSpace/ext/launcher/include/filesystemaccess.h b/apps/OpenSpace/ext/launcher/include/filesystemaccess.h index 61ac0471c4..3113335234 100644 --- a/apps/OpenSpace/ext/launcher/include/filesystemaccess.h +++ b/apps/OpenSpace/ext/launcher/include/filesystemaccess.h @@ -33,7 +33,7 @@ public: * Constructor for filesystemAccess class. * * \param fileExtension The file extensiopn filter used to find files. Only files with - * this extension will be recognized (e.g. '.xml') + * this extension will be recognized (e.g. '.json') * \param hideFileExtensions If `true` then file extensions will be removed from the * listed files in the output * \param useCheckboxes If `true` then the text output format will contain a '0' as @@ -48,14 +48,14 @@ public: * * \param dir The directory from which to start the search from */ - std::string useQtFileSystemModelToTraverseDir(std::string dir, - bool usersAssets = false); + std::string useQtFileSystemModelToTraverseDir(const std::string& dir, + bool userAssets = false); private: - void parseChildDirElements(QFileInfo item, std::string space, int level, - std::vector& dirNames, std::vector& output, + void parseChildDirElements(const QFileInfo& fileInfo, const std::string& space, + int level, std::vector& dirNames, std::vector& output, bool userAssets); - void parseChildFile(std::string res, bool& hasDirHeaderBeenAdded, + void parseChildFile(std::string filename, bool& hasDirHeaderBeenAdded, std::vector& dirNames, std::vector& output); QFileSystemModel _filesystemModel; diff --git a/apps/OpenSpace/ext/launcher/include/launcherwindow.h b/apps/OpenSpace/ext/launcher/include/launcherwindow.h index 6105ce5be1..6a67b1eaff 100644 --- a/apps/OpenSpace/ext/launcher/include/launcherwindow.h +++ b/apps/OpenSpace/ext/launcher/include/launcherwindow.h @@ -96,12 +96,11 @@ private: void editRefusalDialog(const std::string& title, const std::string& msg, const std::string& detailedText); - void populateProfilesList(std::string preset); - void populateWindowConfigsList(std::string preset); + void populateProfilesList(const std::string& preset); + void populateWindowConfigsList(const std::string& preset); void handleReturnFromWindowEditor(const sgct::config::Cluster& cluster, std::filesystem::path savePath, const std::string& saveWindowCfgPath); void onNewWindowConfigSelection(int newIndex); - bool versionCheck(sgct::config::GeneratorVersion& v) const; const std::string _assetPath; const std::string _userAssetPath; diff --git a/apps/OpenSpace/ext/launcher/include/profile/actiondialog.h b/apps/OpenSpace/ext/launcher/include/profile/actiondialog.h index c81263ad8b..e7ec4b81b0 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/actiondialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/actiondialog.h @@ -56,18 +56,18 @@ private: void actionRemove(); void actionSelected(); void actionSaved(); - void clearActionFields(); + void clearActionFields() const; void actionRejected(); void chooseScripts(); - void appendScriptsToTextfield(std::vector scripts); + void appendScriptsToTextfield(const std::vector& scripts) const; openspace::Profile::Keybinding* selectedKeybinding(); void keybindingAdd(); void keybindingRemove(); void keybindingSelected(); - void keybindingActionSelected(int); + void keybindingActionSelected(int) const; void keybindingSaved(); - void clearKeybindingFields(); + void clearKeybindingFields() const; void keybindingRejected(); std::vector* _actions = nullptr; diff --git a/apps/OpenSpace/ext/launcher/include/profile/additionalscriptsdialog.h b/apps/OpenSpace/ext/launcher/include/profile/additionalscriptsdialog.h index 3684ebeb11..3bdfdfd039 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/additionalscriptsdialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/additionalscriptsdialog.h @@ -52,7 +52,7 @@ private: * * \param scripts The scripts to be appended */ - void appendScriptsToTextfield(std::vector scripts); + void appendScriptsToTextfield(const std::vector& scripts); std::vector* _scripts = nullptr; std::vector _scriptsData; diff --git a/apps/OpenSpace/ext/launcher/include/profile/assettreemodel.h b/apps/OpenSpace/ext/launcher/include/profile/assettreemodel.h index 5294617aa3..f3317192e5 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/assettreemodel.h +++ b/apps/OpenSpace/ext/launcher/include/profile/assettreemodel.h @@ -205,7 +205,7 @@ public: * \param index Location of the item to set * \param name The asset name to set */ - void setName(QModelIndex& index, QString name); + void setName(QModelIndex& index, const QString& name); /** * Set state of checked/selected of an item. diff --git a/apps/OpenSpace/ext/launcher/include/profile/cameradialog.h b/apps/OpenSpace/ext/launcher/include/profile/cameradialog.h index 8e2b0b7761..79e20b661e 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/cameradialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/cameradialog.h @@ -56,7 +56,7 @@ private: QWidget* createNavStateWidget(); QWidget* createGeoWidget(); - void addErrorMsg(QString errorDescription); + void addErrorMsg(const QString& errorDescription); bool areRequiredFormsFilledAndValid(); std::optional* _camera = nullptr; diff --git a/apps/OpenSpace/ext/launcher/include/profile/deltatimesdialog.h b/apps/OpenSpace/ext/launcher/include/profile/deltatimesdialog.h index 687a44844f..d6fd44fa1f 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/deltatimesdialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/deltatimesdialog.h @@ -80,7 +80,7 @@ private: */ void transitionEditMode(int index, bool state); - void setLabelForKey(int index, bool editMode, std::string color); + void setLabelForKey(int index, bool editMode, std::string_view color); bool isLineEmpty(int index); std::vector* _deltaTimes = nullptr; diff --git a/apps/OpenSpace/ext/launcher/include/profile/horizonsdialog.h b/apps/OpenSpace/ext/launcher/include/profile/horizonsdialog.h index f08152a286..da4cb49118 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/horizonsdialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/horizonsdialog.h @@ -71,7 +71,7 @@ private: void openSaveAs(); void typeOnChange(int index); - void downloadProgress(int value, int max); + void downloadProgress(int value, int total); void importTimeRange(); void approved(); diff --git a/apps/OpenSpace/ext/launcher/include/profile/modulesdialog.h b/apps/OpenSpace/ext/launcher/include/profile/modulesdialog.h index d1d585fa66..45b232e97b 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/modulesdialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/modulesdialog.h @@ -65,7 +65,6 @@ private: void transitionToEditMode(); void parseSelections(); - QString createOneLineSummary(openspace::Profile::Module m); void transitionFromEditMode(); void editBoxDisabled(bool disabled); bool isLineEmpty(int index) const; diff --git a/apps/OpenSpace/ext/launcher/include/profile/propertiesdialog.h b/apps/OpenSpace/ext/launcher/include/profile/propertiesdialog.h index 819dec642e..a1ae8fc28d 100644 --- a/apps/OpenSpace/ext/launcher/include/profile/propertiesdialog.h +++ b/apps/OpenSpace/ext/launcher/include/profile/propertiesdialog.h @@ -69,7 +69,6 @@ private: void selectLineFromScriptLog(); - QString createOneLineSummary(openspace::Profile::Property p); void transitionFromEditMode(); void editBoxDisabled(bool disabled); bool areRequiredFormsFilled(); diff --git a/apps/OpenSpace/ext/launcher/include/sgctedit/displaywindowunion.h b/apps/OpenSpace/ext/launcher/include/sgctedit/displaywindowunion.h index 16baee258e..2d41e61039 100644 --- a/apps/OpenSpace/ext/launcher/include/sgctedit/displaywindowunion.h +++ b/apps/OpenSpace/ext/launcher/include/sgctedit/displaywindowunion.h @@ -109,7 +109,7 @@ signals: void nWindowsChanged(int newCount); private: - void createWidgets(int nMaxWindows, std::vector monitorResolutions, + void createWidgets(int nMaxWindows, const std::vector& monitorResolutions, std::array windowColors, bool resetToDefault); void showWindows(); diff --git a/apps/OpenSpace/ext/launcher/include/sgctedit/monitorbox.h b/apps/OpenSpace/ext/launcher/include/sgctedit/monitorbox.h index ba4f157285..99e0003fc8 100644 --- a/apps/OpenSpace/ext/launcher/include/sgctedit/monitorbox.h +++ b/apps/OpenSpace/ext/launcher/include/sgctedit/monitorbox.h @@ -66,9 +66,9 @@ public: /** * Called when the number of windows that should be displayed changes. * - * \param newCount The new number of windows included + * \param nWindows The new number of windows included */ - void nWindowsDisplayedChanged(int newCount); + void nWindowsDisplayedChanged(int nWindows); protected: void paintEvent(QPaintEvent* event) override; diff --git a/apps/OpenSpace/ext/launcher/include/sgctedit/sgctedit.h b/apps/OpenSpace/ext/launcher/include/sgctedit/sgctedit.h index b94a469ddd..4db02f5a9b 100644 --- a/apps/OpenSpace/ext/launcher/include/sgctedit/sgctedit.h +++ b/apps/OpenSpace/ext/launcher/include/sgctedit/sgctedit.h @@ -66,7 +66,7 @@ public: * \param configBasePath The path to the folder where default config files reside * \param parent Pointer to parent Qt widget */ - SgctEdit(sgct::config::Cluster& cluster, const std::string& configName, + SgctEdit(sgct::config::Cluster& cluster, std::string configName, std::string& configBasePath, QWidget* parent); /** diff --git a/apps/OpenSpace/ext/launcher/include/sgctedit/windowcontrol.h b/apps/OpenSpace/ext/launcher/include/sgctedit/windowcontrol.h index e3dd260b51..1116a2d7f7 100644 --- a/apps/OpenSpace/ext/launcher/include/sgctedit/windowcontrol.h +++ b/apps/OpenSpace/ext/launcher/include/sgctedit/windowcontrol.h @@ -199,7 +199,7 @@ private: void onSizeYChanged(int newValue); void onOffsetXChanged(int newValue); void onOffsetYChanged(int newValue); - void onProjectionChanged(int newSelection); + void onProjectionChanged(int newSelection) const; void onFullscreenClicked(); void onAspectRatioLockClicked(); void onFovLockClicked(); diff --git a/apps/OpenSpace/ext/launcher/src/filesystemaccess.cpp b/apps/OpenSpace/ext/launcher/src/filesystemaccess.cpp index d0a3d6295b..075280fee9 100644 --- a/apps/OpenSpace/ext/launcher/src/filesystemaccess.cpp +++ b/apps/OpenSpace/ext/launcher/src/filesystemaccess.cpp @@ -31,11 +31,12 @@ FileSystemAccess::FileSystemAccess(std::string fileExtension, , _useCheckboxes(useCheckboxes) {} -std::string FileSystemAccess::useQtFileSystemModelToTraverseDir(std::string dir, - bool userAssets) { +std::string FileSystemAccess::useQtFileSystemModelToTraverseDir(const std::string& dir, + bool userAssets) +{ _filesystemModel.setRootPath(QString::fromStdString(dir)); - QModelIndex index = _filesystemModel.index(_filesystemModel.rootPath()); - QFileInfo fileInfo = _filesystemModel.fileInfo(index); + const QModelIndex index = _filesystemModel.index(_filesystemModel.rootPath()); + const QFileInfo fileInfo = _filesystemModel.fileInfo(index); std::vector dirsNested; std::vector out; parseChildDirElements(fileInfo, "", 0, dirsNested, out, userAssets); @@ -46,32 +47,38 @@ std::string FileSystemAccess::useQtFileSystemModelToTraverseDir(std::string dir, return combined; } -void FileSystemAccess::parseChildDirElements(QFileInfo fileInfo, std::string space, - int level, +void FileSystemAccess::parseChildDirElements(const QFileInfo& fileInfo, + const std::string& space, int level, std::vector& dirNames, std::vector& output, bool userAssets) { - QDir dir(fileInfo.filePath()); + const QDir dir = QDir(fileInfo.filePath()); bool hasDirHeaderBeenAdded = false; - QFileInfoList fileList = dir.entryInfoList(_fileFilterOptions); - for (int i = 0; i < fileList.size(); i++) { - QFileInfo fi = fileList[i]; + const QFileInfoList fileList = dir.entryInfoList(_fileFilterOptions); + for (const QFileInfo& fi : fileList) { std::string res = space + fi.fileName().toStdString(); if (level == 0 && userAssets) { - res = "${USER_ASSETS}/" + res; + res = std::format("${{USER_ASSETS}}/{}", res); } if (fi.isDir()) { dirNames.push_back(res); - parseChildDirElements(fi, (space + " "), level + 1, dirNames, output, userAssets); + parseChildDirElements( + fi, + (space + " "), + level + 1, + dirNames, + output, + userAssets + ); } else { parseChildFile(res, hasDirHeaderBeenAdded, dirNames, output); } } - bool isThisDirAnEmptyDeadEnd = !hasDirHeaderBeenAdded; - if (isThisDirAnEmptyDeadEnd && (dirNames.size() != 0)) { + const bool isThisDirAnEmptyDeadEnd = !hasDirHeaderBeenAdded; + if (isThisDirAnEmptyDeadEnd && !dirNames.empty()) { dirNames.pop_back(); } } @@ -80,12 +87,12 @@ void FileSystemAccess::parseChildFile(std::string filename, bool& hasDirHeaderBe std::vector& dirNames, std::vector& output) { - std::string cbox = (_useCheckboxes) ? "0" : ""; + const std::string cbox = _useCheckboxes ? "0" : ""; if (filename.length() <= _fileExtension.length()) { return; } else { - std::string extension = filename.substr(filename.length() + const std::string extension = filename.substr(filename.length() - _fileExtension.length()); if (extension != _fileExtension) { return; diff --git a/apps/OpenSpace/ext/launcher/src/launcherwindow.cpp b/apps/OpenSpace/ext/launcher/src/launcherwindow.cpp index 00a34e554f..6f4dfce048 100644 --- a/apps/OpenSpace/ext/launcher/src/launcherwindow.cpp +++ b/apps/OpenSpace/ext/launcher/src/launcherwindow.cpp @@ -94,7 +94,7 @@ namespace { SettingsIconSize, SettingsIconSize ); - } // geometry + } // namespace geometry std::optional loadProfileFromFile(QWidget* parent, std::string filename) { // Verify that the file actually exists @@ -102,7 +102,7 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( + QString::fromStdString(std::format( "Could not open profile file '{}'", filename )) ); @@ -117,8 +117,8 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( - "ParsingError exception in {}: {}, {}", + QString::fromStdString(std::format( + "ParsingError exception in '{}': {}, {}", filename, e.component, e.message )) ); @@ -128,8 +128,8 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( - "RuntimeError exception in {}, component {}: {}", + QString::fromStdString(std::format( + "RuntimeError exception in '{}', component {}: {}", filename, e.component, e.message )) ); @@ -153,8 +153,8 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( - "Error writing data to file: '{}' as file is marked hidden", + QString::fromStdString(std::format( + "Error writing data to file '{}' as file is marked hidden", path )) ); @@ -165,8 +165,8 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( - "Error writing data to file: {} ({})", path, e.what() + QString::fromStdString(std::format( + "Error writing data to file '{}': {}", path, e.what() )) ); } @@ -188,12 +188,19 @@ namespace { QMessageBox::critical( parent, "Exception", - QString::fromStdString(fmt::format( - "Error writing data to file: {} ({})", path, e.what() + QString::fromStdString(std::format( + "Error writing data to file '{}': {}", path, e.what() )) ); } } + + bool versionCheck(sgct::config::GeneratorVersion& v) { + return + v.versionCheck(versionMin) || + v == versionLegacy18 || + v == versionLegacy19; + } } // namespace using namespace openspace; @@ -211,14 +218,14 @@ LauncherWindow::LauncherWindow(bool profileEnabled, , _userProfilePath( absPath(globalConfig.pathTokens.at("USER_PROFILES")).string() + '/' ) - , _sgctConfigName(sgctConfigName) + , _sgctConfigName(std::move(sgctConfigName)) { Q_INIT_RESOURCE(resources); qInstallMessageHandler( [](QtMsgType type, const QMessageLogContext&, const QString& msg) { if (type == QtCriticalMsg || type == QtFatalMsg || type == QtSystemMsg) { - std::cerr << msg.toStdString() << std::endl; + std::cerr << msg.toStdString() << '\n'; } } ); @@ -230,7 +237,7 @@ LauncherWindow::LauncherWindow(bool profileEnabled, { QFile file(":/qss/launcher.qss"); file.open(QFile::ReadOnly); - QString styleSheet = QLatin1String(file.readAll()); + const QString styleSheet = QLatin1String(file.readAll()); setStyleSheet(styleSheet); } @@ -244,7 +251,7 @@ LauncherWindow::LauncherWindow(bool profileEnabled, // Trigger currentIndexChanged so the preview file read is performed _windowConfigBox->currentIndexChanged(_windowConfigBox->currentIndex()); - std::filesystem::path p = absPath( + const std::filesystem::path p = absPath( globalConfig.pathTokens.at("SYNC") + "/http/launcher_images" ); if (std::filesystem::exists(p)) { @@ -324,8 +331,8 @@ QWidget* LauncherWindow::createCentralWidget() { editProfileButton, &QPushButton::released, [this]() { const std::string selection = _profileBox->currentText().toStdString(); - int selectedIndex = _profileBox->currentIndex(); - bool isUserProfile = selectedIndex < _userAssetCount; + const int selectedIndex = _profileBox->currentIndex(); + const bool isUserProfile = selectedIndex < _userAssetCount; openProfileEditor(selection, isUserProfile); } ); @@ -349,9 +356,9 @@ QWidget* LauncherWindow::createCentralWidget() { _editWindowButton, &QPushButton::released, [this]() { - std::filesystem::path pathSelected = absPath(selectedWindowConfig()); - bool isUserConfig = isUserConfigSelected(); - std::string fileSelected = pathSelected.generic_string(); + const std::filesystem::path pathSelected = absPath(selectedWindowConfig()); + const bool isUserConfig = isUserConfigSelected(); + const std::string fileSelected = pathSelected.generic_string(); if (std::filesystem::is_regular_file(pathSelected)) { openWindowEditor(fileSelected, isUserConfig); } @@ -446,7 +453,7 @@ void LauncherWindow::setBackgroundImage(const std::string& syncPath) { std::shuffle(files.begin(), files.end(), g); // We know there has to be at least one folder, so it's fine to just pick the first while (!files.empty()) { - std::string p = files.front(); + const std::string& p = files.front(); if (std::filesystem::path(p).extension() == ".png") { // If the top path starts with the png extension, we have found our candidate break; @@ -460,12 +467,12 @@ void LauncherWindow::setBackgroundImage(const std::string& syncPath) { // There better be at least one file left, but just in in case if (!files.empty()) { - std::string image = files.front(); + const std::string& image = files.front(); _backgroundImage->setPixmap(QPixmap(QString::fromStdString(image))); } } -void LauncherWindow::populateProfilesList(std::string preset) { +void LauncherWindow::populateProfilesList(const std::string& preset) { namespace fs = std::filesystem; _profileBox->clear(); @@ -474,7 +481,7 @@ void LauncherWindow::populateProfilesList(std::string preset) { if (!std::filesystem::exists(_profilePath)) { LINFOC( "LauncherWindow", - fmt::format("Could not find profile folder '{}'", _profilePath) + std::format("Could not find profile folder '{}'", _profilePath) ); return; } @@ -497,7 +504,7 @@ void LauncherWindow::populateProfilesList(std::string preset) { } std::sort(profiles.begin(), profiles.end()); for (const fs::directory_entry& profile : profiles) { - std::filesystem::path path = profile.path(); + const std::filesystem::path& path = profile.path(); _profileBox->addItem( QString::fromStdString(path.stem().string()), QString::fromStdString(path.string()) @@ -505,12 +512,14 @@ void LauncherWindow::populateProfilesList(std::string preset) { // Add toooltip std::optional p = loadProfileFromFile(this, path.string()); - int idx = _profileBox->count() - 1; + const int idx = _profileBox->count() - 1; if (p.has_value() && (*p).meta.has_value()) { - const std::optional& d = (*p).meta.value().description; + const std::optional& d = p->meta.value().description; if (d.has_value()) { // Tooltip has to be 'rich text' to linebreak properly - QString tooltip = QString::fromStdString(fmt::format("

{}

", *d)); + const QString tooltip = QString::fromStdString(std::format( + "

{}

", *d + )); _profileBox->setItemData(idx, tooltip, Qt::ToolTipRole); } } @@ -533,7 +542,7 @@ void LauncherWindow::populateProfilesList(std::string preset) { // Add sorted items to list for (const fs::directory_entry& profile : profiles) { - std::filesystem::path path = profile.path(); + const std::filesystem::path& path = profile.path(); _profileBox->addItem( QString::fromStdString(path.stem().string()), QString::fromStdString(path.string()) @@ -541,12 +550,14 @@ void LauncherWindow::populateProfilesList(std::string preset) { // Add toooltip std::optional p = loadProfileFromFile(this, path.string()); - int idx = _profileBox->count() - 1; + const int idx = _profileBox->count() - 1; if (p.has_value() && (*p).meta.has_value()) { - const std::optional& d = (*p).meta.value().description; + const std::optional& d = p->meta.value().description; if (d.has_value()) { // Tooltip has to be 'rich text' to linebreak properly - QString tooltip = QString::fromStdString(fmt::format("

{}

", *d)); + const QString tooltip = QString::fromStdString(std::format( + "

{}

", *d + )); _profileBox->setItemData(idx, tooltip, Qt::ToolTipRole); } } @@ -573,9 +584,8 @@ void LauncherWindow::populateProfilesList(std::string preset) { // Returns 'true' if the file was a configuration file, 'false' otherwise bool handleConfigurationFile(QComboBox& box, const std::filesystem::directory_entry& p) { - const bool isXml = p.path().extension() == ".xml"; const bool isJson = p.path().extension() == ".json"; - if (!isXml && !isJson) { + if (!isJson) { return false; } box.addItem(QString::fromStdString(p.path().filename().string())); @@ -584,29 +594,24 @@ bool handleConfigurationFile(QComboBox& box, const std::filesystem::directory_en if (isJson) { std::string tooltipDescription; try { - sgct::config::Meta meta = sgct::readMeta(p.path().string()); + const sgct::config::Meta meta = sgct::readMeta(p.path().string()); tooltipDescription = meta.description; } catch (const sgct::Error&) { tooltipDescription = "(no description available)"; } if (!tooltipDescription.empty()) { - QString toolTip = QString::fromStdString( - fmt::format("

{}

", tooltipDescription) + const QString toolTip = QString::fromStdString( + std::format("

{}

", tooltipDescription) ); box.setItemData(box.count() - 1, toolTip, Qt::ToolTipRole); } } - // For now, mark the XML configuration files to show that they are deprecated - if (isXml) { - box.setItemData(box.count() - 1, QBrush(Qt::darkYellow), Qt::ForegroundRole); - } - return true; } -void LauncherWindow::populateWindowConfigsList(std::string preset) { +void LauncherWindow::populateWindowConfigsList(const std::string& preset) { namespace fs = std::filesystem; // Disconnect the signal for new window config selection during population process @@ -630,8 +635,6 @@ void LauncherWindow::populateWindowConfigsList(std::string preset) { _userConfigStartingIdx++; _preDefinedConfigStartingIdx++; - bool hasXmlConfig = false; - // Sort files std::vector files; for (const fs::directory_entry& p : fs::directory_iterator(_userConfigPath)) { @@ -639,15 +642,14 @@ void LauncherWindow::populateWindowConfigsList(std::string preset) { } std::sort(files.begin(), files.end()); - // Add all the files with the .xml or .json extension to the dropdown + // Add all the files with the .json extension to the dropdown for (const fs::directory_entry& p : files) { - bool isConfigFile = handleConfigurationFile(*_windowConfigBox, p); + const bool isConfigFile = handleConfigurationFile(*_windowConfigBox, p); if (isConfigFile) { _userConfigCount++; _userConfigStartingIdx++; _preDefinedConfigStartingIdx++; } - hasXmlConfig |= p.path().extension() == ".xml"; } _windowConfigBox->addItem(QString::fromStdString("--- OpenSpace Configurations ---")); model = qobject_cast(_windowConfigBox->model()); @@ -661,36 +663,24 @@ void LauncherWindow::populateWindowConfigsList(std::string preset) { files.push_back(p); } std::sort(files.begin(), files.end()); - // Add all the files with the .xml or .json extension to the dropdown + // Add all the files with the .json extension to the dropdown for (const fs::directory_entry& p : files) { handleConfigurationFile(*_windowConfigBox, p); - hasXmlConfig |= p.path().extension() == ".xml"; } } else { LINFOC( "LauncherWindow", - fmt::format("Could not find config folder '{}'", _configPath) + std::format("Could not find config folder '{}'", _configPath) ); } - if (hasXmlConfig) { - // At least one XML configuration file is present, so we should show the tooltip - // informing the user that files will be deprecated - _windowConfigBox->setToolTip( - "Support for XML-based configuration files will be removed in the next " - "version of OpenSpace. Please convert the files to the new JSON format or " - "run the Node tool at " - "https://github.com/sgct/sgct/tree/master/support/config-converter" - ); - } - - // Always add the .cfg sgct default as first item + // Always add the .cfg SGCT default as first item _windowConfigBox->insertItem( _windowConfigBoxIndexSgctCfgDefault, QString::fromStdString(_sgctConfigName) ); - QString defaultTip = + const QString defaultTip = "

The basic default configuration specified in the .cfg file

"; _windowConfigBox->setItemData( _windowConfigBoxIndexSgctCfgDefault, @@ -700,7 +690,7 @@ void LauncherWindow::populateWindowConfigsList(std::string preset) { // Try to find the requested configuration file and set it as the current one. As we // have support for function-generated configuration files that will not be in the // list we need to add a preset that doesn't exist a file for - const int idx = _windowConfigBox->findText(QString::fromStdString(std::move(preset))); + const int idx = _windowConfigBox->findText(QString::fromStdString(preset)); if (idx != -1) { _windowConfigBox->setCurrentIndex(idx); } @@ -728,8 +718,8 @@ void LauncherWindow::populateWindowConfigsList(std::string preset) { } void LauncherWindow::onNewWindowConfigSelection(int newIndex) { - std::filesystem::path pathSelected = absPath(selectedWindowConfig()); - std::string fileSelected = pathSelected.string(); + const std::filesystem::path pathSelected = absPath(selectedWindowConfig()); + const std::string fileSelected = pathSelected.string(); if (newIndex == _windowConfigBoxIndexSgctCfgDefault) { _editWindowButton->setEnabled(false); _editWindowButton->setToolTip( @@ -739,9 +729,10 @@ void LauncherWindow::onNewWindowConfigSelection(int newIndex) { else if (newIndex >= _preDefinedConfigStartingIdx) { _editWindowButton->setEnabled(false); _editWindowButton->setToolTip( - QString::fromStdString(fmt::format( + QString::fromStdString(std::format( "Cannot edit '{}'\nsince it is one of the configuration " - "files provided in the OpenSpace installation", fileSelected)) + "files provided in the OpenSpace installation", fileSelected + )) ); } else { @@ -750,9 +741,10 @@ void LauncherWindow::onNewWindowConfigSelection(int newIndex) { sgct::readConfigGenerator(fileSelected); if (!versionCheck(previewGenVersion)) { _editWindowButton->setEnabled(false); - _editWindowButton->setToolTip(QString::fromStdString(fmt::format( + _editWindowButton->setToolTip(QString::fromStdString(std::format( "This file does not meet the minimum required version of {}.", - versionMin.versionString()))); + versionMin.versionString() + ))); return; } } @@ -765,10 +757,6 @@ void LauncherWindow::onNewWindowConfigSelection(int newIndex) { } } -bool LauncherWindow::versionCheck(sgct::config::GeneratorVersion& v) const { - return (v.versionCheck(versionMin) || v == versionLegacy18 || v == versionLegacy19); -} - void LauncherWindow::openProfileEditor(const std::string& profile, bool isUserProfile) { std::optional p; std::string saveProfilePath = isUserProfile ? _userProfilePath : _profilePath; @@ -779,13 +767,13 @@ void LauncherWindow::openProfileEditor(const std::string& profile, bool isUserPr else { // Otherwise, we want to load that profile std::string fullProfilePath = saveProfilePath + profile + ".profile"; - p = loadProfileFromFile(this, fullProfilePath); + p = loadProfileFromFile(this, std::move(fullProfilePath)); if (!p.has_value()) { return; } } - ProfileEdit editor( + ProfileEdit editor = ProfileEdit( *p, profile, _assetPath, @@ -799,7 +787,8 @@ void LauncherWindow::openProfileEditor(const std::string& profile, bool isUserPr if (editor.specifiedFilename() != profile) { saveProfilePath = _userProfilePath; } - std::string path = saveProfilePath + editor.specifiedFilename() + ".profile"; + const std::string path = + saveProfilePath + editor.specifiedFilename() + ".profile"; saveProfile(this, path, *p); populateProfilesList(editor.specifiedFilename()); } @@ -862,12 +851,10 @@ void LauncherWindow::openWindowEditor(const std::string& winCfg, bool isUserWinC } catch (const std::runtime_error& e) { //Re-throw an SGCT error exception with the runtime exception message - throw std::runtime_error( - fmt::format( - "Importing of this configuration file failed because of a " - "problem detected in the readConfig function:\n\n{}", e.what() - ) - ); + throw std::runtime_error(std::format( + "Importing of this configuration file failed because of a " + "problem detected in the readConfig function:\n\n{}", e.what() + )); } SgctEdit editor( preview, @@ -887,8 +874,8 @@ void LauncherWindow::openWindowEditor(const std::string& winCfg, bool isUserWinC else { editRefusalDialog( "File Format Version Error", - fmt::format( - "File '{}' does not meet the minimum required version of {}.", + std::format( + "File '{}' does not meet the minimum required version of {}", winCfg, versionMin.versionString() ), "" @@ -898,7 +885,7 @@ void LauncherWindow::openWindowEditor(const std::string& winCfg, bool isUserWinC catch (const std::runtime_error& e) { editRefusalDialog( "Format Validation Error", - fmt::format("Parsing error found in file '{}'", winCfg), + std::format("Parsing error found in file '{}'", winCfg), e.what() ); } @@ -912,8 +899,11 @@ void LauncherWindow::handleReturnFromWindowEditor(const sgct::config::Cluster& c savePath.replace_extension(".json"); saveWindowConfig(this, savePath, cluster); // Truncate path to convert this back to path relative to _userConfigPath - std::string p = std::filesystem::proximate(savePath, saveWindowCfgPath).string(); - populateWindowConfigsList(p); + const std::filesystem::path p = std::filesystem::proximate( + savePath, + saveWindowCfgPath + ); + populateWindowConfigsList(p.string()); } bool LauncherWindow::wasLaunchSelected() const { @@ -926,7 +916,7 @@ std::string LauncherWindow::selectedProfile() const { } std::string LauncherWindow::selectedWindowConfig() const { - int idx = _windowConfigBox->currentIndex(); + const int idx = _windowConfigBox->currentIndex(); if (idx == 0) { return _sgctConfigName; } @@ -939,6 +929,6 @@ std::string LauncherWindow::selectedWindowConfig() const { } bool LauncherWindow::isUserConfigSelected() const { - int selectedIndex = _windowConfigBox->currentIndex(); + const int selectedIndex = _windowConfigBox->currentIndex(); return (selectedIndex <= _userConfigCount); } diff --git a/apps/OpenSpace/ext/launcher/src/profile/actiondialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/actiondialog.cpp index 81745a45ca..f9b7b8d9bd 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/actiondialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/actiondialog.cpp @@ -56,8 +56,8 @@ namespace { void updateListItem(QListWidgetItem* item, const Profile::Keybinding& kb) { ghoul_assert(item, "Item must exist at this point"); - std::string name = fmt::format("{}\t{}", ghoul::to_string(kb.key), kb.action); - item->setText(QString::fromStdString(name)); + const std::string n = std::format("{}\t{}", ghoul::to_string(kb.key), kb.action); + item->setText(QString::fromStdString(n)); } } // namespace @@ -140,9 +140,8 @@ void ActionDialog::createActionWidgets(QGridLayout* layout) { this, &ActionDialog::actionSelected ); - for (size_t i = 0; i < _actionData.size(); ++i) { - const Profile::Action& action = _actionData[i]; - std::string name = action.name.empty() ? action.identifier : action.name; + for (const Profile::Action& action : _actionData) { + const std::string name = action.name.empty() ? action.identifier : action.name; _actionWidgets.list->addItem(new QListWidgetItem(QString::fromStdString(name))); } @@ -161,8 +160,8 @@ void ActionDialog::createActionWidgets(QGridLayout* layout) { _actionWidgets.identifier, &QLineEdit::textEdited, [this]() { // Check if the identifier is legal - std::string identifier = _actionWidgets.identifier->text().toStdString(); - bool isLegal = identifier.find_first_of("\t\n. ") == std::string::npos; + const std::string id = _actionWidgets.identifier->text().toStdString(); + const bool isLegal = id.find_first_of("\t\n. ") == std::string::npos; if (isLegal) { _actionWidgets.infoText->clear(); _actionWidgets.infoText->setHidden(true); @@ -308,10 +307,9 @@ void ActionDialog::createKeyboardWidgets(QGridLayout* layout) { this, &ActionDialog::keybindingSelected ); - for (size_t i = 0; i < _keybindingsData.size(); ++i) { - const Profile::Keybinding& kv = _keybindingsData[i]; + for (const Profile::Keybinding& keybinding : _keybindingsData) { QListWidgetItem* item = new QListWidgetItem; - updateListItem(item, kv); + updateListItem(item, keybinding); _keybindingWidgets.list->addItem(item); } @@ -454,7 +452,7 @@ Profile::Action* ActionDialog::selectedAction() { void ActionDialog::actionAdd() { _actionWidgets.list->addItem(""); - _actionData.push_back(Profile::Action()); + _actionData.emplace_back(); _actionWidgets.list->setCurrentRow(_actionWidgets.list->count() - 1); } @@ -468,15 +466,15 @@ void ActionDialog::actionRemove() { ); // We can't remove an action if it has a keyboard shortcut attached to it - for (size_t i = 0; i < _keybindingsData.size(); ++i) { + for (size_t i = 0; i < _keybindingsData.size(); i++) { const Profile::Keybinding& kb = _keybindingsData[i]; if (kb.action != action->identifier) { continue; } - QMessageBox::StandardButton button = QMessageBox::information( + const QMessageBox::StandardButton button = QMessageBox::information( this, "Remove action", - QString::fromStdString(fmt::format( + QString::fromStdString(std::format( "Action '{}' is used in the keybind '{}' and cannot be removed unless " "the keybind is removed as well. Do you want to remove the keybind as " "well?", @@ -500,7 +498,7 @@ void ActionDialog::actionRemove() { } } - for (size_t i = 0; i < _actionData.size(); ++i) { + for (size_t i = 0; i < _actionData.size(); i++) { if (_actionData[i].identifier == action->identifier) { clearActionFields(); _actionData.erase(_actionData.begin() + i); @@ -563,14 +561,14 @@ void ActionDialog::actionSelected() { } void ActionDialog::actionSaved() { - std::string newIdentifier = _actionWidgets.identifier->text().toStdString(); + const std::string newIdentifier = _actionWidgets.identifier->text().toStdString(); if (newIdentifier.empty()) { QMessageBox::critical(this, "Empty identifier", "Identifier must not be empty"); return; } Profile::Action* action = selectedAction(); - std::string oldIdentifier = action->identifier; + const std::string oldIdentifier = action->identifier; if (oldIdentifier != newIdentifier) { // The identifier is a bit special as we need to make sure that we didn't // accidentally create a duplicate while renaming the currently selected action. @@ -598,13 +596,13 @@ void ActionDialog::actionSaved() { _keybindingWidgets.list->count() == static_cast(_keybindingsData.size()), "The list and data got out of sync" ); - for (int i = 0; i < _keybindingWidgets.list->count(); ++i) { + for (int i = 0; i < _keybindingWidgets.list->count(); i++) { if (_keybindingsData[i].action == oldIdentifier) { _keybindingsData[i].action = newIdentifier; updateListItem(_keybindingWidgets.list->item(i), _keybindingsData[i]); } } - for (int i = 0; i < _keybindingWidgets.action->count(); ++i) { + for (int i = 0; i < _keybindingWidgets.action->count(); i++) { if (_keybindingWidgets.action->itemText(i).toStdString() == oldIdentifier) { _keybindingWidgets.action->setItemText( i, @@ -641,7 +639,7 @@ void ActionDialog::actionSaved() { clearActionFields(); } -void ActionDialog::clearActionFields() { +void ActionDialog::clearActionFields() const { _actionWidgets.list->setCurrentRow(-1); _actionWidgets.identifier->clear(); _actionWidgets.identifier->setEnabled(false); @@ -681,9 +679,10 @@ void ActionDialog::chooseScripts() { d.exec(); } -void ActionDialog::appendScriptsToTextfield(std::vector scripts) { - for (std::string script : scripts) { - _actionWidgets.script->append(QString::fromStdString(std::move(script))); +void ActionDialog::appendScriptsToTextfield(const std::vector& scripts) const +{ + for (const std::string& script : scripts) { + _actionWidgets.script->append(QString::fromStdString(script)); } } @@ -695,7 +694,7 @@ Profile::Keybinding* ActionDialog::selectedKeybinding() { void ActionDialog::keybindingAdd() { _keybindingWidgets.list->addItem(""); - _keybindingsData.push_back(Profile::Keybinding()); + _keybindingsData.emplace_back(); _keybindingWidgets.list->setCurrentRow(_keybindingWidgets.list->count() - 1); } @@ -703,7 +702,7 @@ void ActionDialog::keybindingRemove() { const Profile::Keybinding* keybinding = selectedKeybinding(); ghoul_assert(keybinding, "A keybinding must be selected at this point"); - for (size_t i = 0; i < _keybindingsData.size(); ++i) { + for (size_t i = 0; i < _keybindingsData.size(); i++) { if (_keybindingsData[i].key == keybinding->key && _keybindingsData[i].action == keybinding->action) { @@ -735,7 +734,7 @@ void ActionDialog::keybindingSelected() { hasKeyModifier(keybinding->key.modifier, KeyModifier::Alt) ); - std::string key = ghoul::to_string(keybinding->key.key); + const std::string key = ghoul::to_string(keybinding->key.key); _keybindingWidgets.key->setCurrentText(QString::fromStdString(key)); _keybindingWidgets.key->setEnabled(true); _keybindingWidgets.action->setCurrentText( @@ -773,7 +772,7 @@ void ActionDialog::keybindingSelected() { } } -void ActionDialog::keybindingActionSelected(int) { +void ActionDialog::keybindingActionSelected(int) const { _keybindingWidgets.actionText->setText(_keybindingWidgets.action->currentText()); } @@ -814,7 +813,7 @@ void ActionDialog::keybindingSaved() { clearKeybindingFields(); } -void ActionDialog::clearKeybindingFields() { +void ActionDialog::clearKeybindingFields() const { _keybindingWidgets.list->setCurrentRow(-1); _keybindingWidgets.shiftModifier->setChecked(false); _keybindingWidgets.shiftModifier->setEnabled(false); @@ -832,8 +831,8 @@ void ActionDialog::clearKeybindingFields() { } void ActionDialog::keybindingRejected() { - bool isKeyEmpty = (_keybindingsData.back().key.key == Key::Unknown); - bool isActionEmpty = _keybindingsData.back().action.empty(); + const bool isKeyEmpty = (_keybindingsData.back().key.key == Key::Unknown); + const bool isActionEmpty = _keybindingsData.back().action.empty(); if (isKeyEmpty || isActionEmpty) { delete _keybindingWidgets.list->takeItem(_keybindingWidgets.list->count() - 1); _keybindingsData.erase(_keybindingsData.begin() + _keybindingsData.size() - 1); diff --git a/apps/OpenSpace/ext/launcher/src/profile/additionalscriptsdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/additionalscriptsdialog.cpp index 32638b74a5..e3d8108f58 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/additionalscriptsdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/additionalscriptsdialog.cpp @@ -44,11 +44,12 @@ AdditionalScriptsDialog::AdditionalScriptsDialog(QWidget* parent, setWindowTitle("Additional Scripts"); createWidgets(); - std::string scriptText = std::accumulate( + const std::string scriptText = std::accumulate( _scriptsData.begin(), _scriptsData.end(), - std::string(), [](std::string lhs, std::string rhs) { return lhs + rhs + '\n'; } + std::string(), + [](std::string lhs, const std::string& rhs) { return lhs + rhs + '\n'; } ); - _textScripts->setText(QString::fromStdString(std::move(scriptText))); + _textScripts->setText(QString::fromStdString(scriptText)); _textScripts->moveCursor(QTextCursor::MoveOperation::End); } @@ -109,8 +110,10 @@ void AdditionalScriptsDialog::chooseScripts() { d.exec(); } -void AdditionalScriptsDialog::appendScriptsToTextfield(std::vector scripts) { - for (std::string script : scripts) { - _textScripts->append(QString::fromStdString(std::move(script))); +void AdditionalScriptsDialog::appendScriptsToTextfield( + const std::vector& scripts) +{ + for (const std::string& script : scripts) { + _textScripts->append(QString::fromStdString(script)); } } diff --git a/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp index 387801653f..07d36c74b1 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/assetsdialog.cpp @@ -46,7 +46,7 @@ namespace { QModelIndex idx = model.index(r, 0, parent); if (!model.isAsset(idx)) { - int nChildRows = model.childCount(idx); + const int nChildRows = model.childCount(idx); if (traverseToExpandSelectedItems(tree, model, nChildRows, idx)) { tree.setExpanded(idx, true); isExpanded = true; @@ -63,25 +63,25 @@ namespace { int nRows, const std::string& path) { int startIndex = 0; - std::string token = "${USER_ASSETS}/"; + const std::string token = "${USER_ASSETS}/"; if (path.starts_with(token)) { startIndex = static_cast(token.length()); } const size_t slash = path.find_first_of('/', startIndex); const bool endOfPath = (slash == std::string::npos); - std::string firstDir = endOfPath ? "" : path.substr(0, slash); + const std::string firstDir = endOfPath ? "" : path.substr(0, slash); if (!endOfPath) { - std::string nextPath = (slash == std::string::npos) ? + const std::string nextPath = (slash == std::string::npos) ? path : path.substr(slash + 1); bool foundDirMatch = false; for (int r = 0; r < nRows; r++) { QModelIndex idx = model.index(r, 0, parent); - std::string assetName = model.name(idx).toStdString(); + const std::string assetName = model.name(idx).toStdString(); if (!model.isAsset(idx)) { if (firstDir == assetName) { - int nChildRows = model.childCount(idx); + const int nChildRows = model.childCount(idx); foundDirMatch = true; traverseToFindFilesystemMatch(model, idx, nChildRows, nextPath); break; @@ -104,7 +104,7 @@ namespace { bool foundFileMatch = false; for (int r = 0; r < nRows; r++) { QModelIndex idx = model.index(r, 0, parent); - std::string assetName = model.name(idx).toStdString(); + const std::string assetName = model.name(idx).toStdString(); // Need to check if it actually is an asset to prevent issue #2154 if (model.isAsset(idx) && path == assetName) { foundFileMatch = true; @@ -173,12 +173,12 @@ AssetsDialog::AssetsDialog(QWidget* parent, openspace::Profile* profile, for (const std::string& a : _profile->assets) { - QModelIndex p = _assetTreeModel.index(-1, 0); - int nRows = _assetTreeModel.rowCount(p); + const QModelIndex p = _assetTreeModel.index(-1, 0); + const int nRows = _assetTreeModel.rowCount(p); traverseToFindFilesystemMatch(_assetTreeModel, p, nRows, a); } - int nRows = _assetTreeModel.rowCount(_assetTreeModel.index(-1, 0)); + const int nRows = _assetTreeModel.rowCount(_assetTreeModel.index(-1, 0)); traverseToExpandSelectedItems( *_assetTree, _assetTreeModel, @@ -249,12 +249,12 @@ QString AssetsDialog::createTextSummary() { return ""; } QString summary; - for (size_t i = 0; i < summaryItems.size(); ++i) { - bool existsInFilesystem = summaryItems.at(i)->doesExistInFilesystem(); + for (size_t i = 0; i < summaryItems.size(); i++) { + const bool existsInFilesystem = summaryItems.at(i)->doesExistInFilesystem(); - std::string s = existsInFilesystem ? - fmt::format("{}
", summaryPaths.at(i)) : - fmt::format("{}
", summaryPaths.at(i)); + const std::string s = existsInFilesystem ? + std::format("{}
", summaryPaths.at(i)) : + std::format("{}
", summaryPaths.at(i)); summary += QString::fromStdString(s); } return summary; @@ -316,7 +316,7 @@ void SearchProxyModel::setFilterRegularExpression(const QString& pattern) { bool SearchProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const { - QModelIndex idx = sourceModel()->index(sourceRow, 0, sourceParent); + const QModelIndex idx = sourceModel()->index(sourceRow, 0, sourceParent); return acceptIndex(idx); } @@ -324,13 +324,14 @@ bool SearchProxyModel::acceptIndex(const QModelIndex& idx) const { if (!idx.isValid() || !_regExPattern) { return false; } - QString text = idx.data(Qt::DisplayRole).toString(); - QRegularExpressionMatchIterator matchIterator = _regExPattern->globalMatch(text); - if (matchIterator.hasNext()) { + const QString text = idx.data(Qt::DisplayRole).toString(); + const QRegularExpressionMatchIterator matchIt = _regExPattern->globalMatch(text); + if (matchIt.hasNext()) { return true; } for (int row = 0; row < idx.model()->rowCount(idx); ++row) { - if (acceptIndex(idx.model()->index(row, 0, idx))) { + const bool accept = acceptIndex(idx.model()->index(row, 0, idx)); + if (accept) { return true; } } diff --git a/apps/OpenSpace/ext/launcher/src/profile/assettreeitem.cpp b/apps/OpenSpace/ext/launcher/src/profile/assettreeitem.cpp index 3d571f55d4..15a9b69e08 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/assettreeitem.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/assettreeitem.cpp @@ -121,8 +121,8 @@ bool AssetTreeItem::insertChildren(int position, int count, int columns) { } for (int row = 0; row < count; ++row) { - std::vector data(columns); - AssetTreeItem*item = new AssetTreeItem(data, this); + std::vector data = std::vector(columns); + AssetTreeItem* item = new AssetTreeItem(std::move(data), this); _childItems.insert(_childItems.begin() + position, item); } diff --git a/apps/OpenSpace/ext/launcher/src/profile/assettreemodel.cpp b/apps/OpenSpace/ext/launcher/src/profile/assettreemodel.cpp index 50b24fd755..43aef3688c 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/assettreemodel.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/assettreemodel.cpp @@ -39,9 +39,9 @@ namespace { bool existsInFilesystem = true; }; - int getLevelFromLine(std::string line) { + int getLevelFromLine(const std::string& line) { int level = 0; - for (unsigned int i = 0; i < line.length(); ++i) { + for (unsigned int i = 0; i < line.length(); i++) { if (line.substr(i, 1) == " ") { level++; } @@ -80,14 +80,19 @@ namespace { int nChildInsert = -1; bool continueToNextLine = true; - while (continueToNextLine && elem.line.length() != 0) { - int levelChange = elem.level - level; + while (continueToNextLine && !elem.line.empty()) { + const int levelChange = elem.level - level; if (levelChange == 0) { parent->insertChildren(++nChildInsert, 1, 3); - parent->child(nChildInsert)->setData(0, QString::fromStdString(elem.line)); - bool shouldMakeElemChecked = (elem.checked || !elem.existsInFilesystem); - Qt::CheckState check = (shouldMakeElemChecked) ? Qt::Checked : Qt::Unchecked; + parent->child(nChildInsert)->setData( + 0, + QString::fromStdString(elem.line) + ); + const bool shouldMakeElemChecked = + (elem.checked || !elem.existsInFilesystem); + const Qt::CheckState check = + shouldMakeElemChecked ? Qt::Checked : Qt::Unchecked; parent->child(nChildInsert)->setData(1, check); parent->child(nChildInsert)->setExistsInFilesystem(elem.existsInFilesystem); continueToNextLine = importGetNextLine(elem, iss); @@ -96,7 +101,6 @@ namespace { importInsertItem(iss, parent->child(nChildInsert), elem, level + 1); } else if (levelChange < 0) { - continueToNextLine = false; break; } } @@ -108,14 +112,14 @@ namespace { std::vector& outputItems, std::string pathPrefix) { - std::string itemName = item->data(0).toString().toStdString(); - bool isPathPrefix = ((pathPrefix.length()) == 0 && (itemName == Header1)); + const std::string itemName = item->data(0).toString().toStdString(); + const bool isPathPrefix = ((pathPrefix.length()) == 0 && (itemName == Header1)); if (item->isAsset()) { if (item->isChecked()) { std::string path = pathPrefix + itemName; outputItems.push_back(item); - outputPaths.push_back(path); + outputPaths.push_back(std::move(path)); } } else { @@ -123,7 +127,7 @@ namespace { pathPrefix += itemName; pathPrefix += "/"; } - for (int i = 0; i < item->childCount(); ++i) { + for (int i = 0; i < item->childCount(); i++) { parseChildrenForSelected( item->child(i), outputPaths, @@ -200,7 +204,7 @@ QString AssetTreeModel::name(QModelIndex& index) const { return item(index)->name(); } -void AssetTreeModel::setName(QModelIndex& index, QString name) { +void AssetTreeModel::setName(QModelIndex& index, const QString& name) { item(index)->setData(0, name); } @@ -245,7 +249,7 @@ QModelIndex AssetTreeModel::index(int row, int column, const QModelIndex& parent } QModelIndex AssetTreeModel::parent(int row, int column, const QModelIndex& parent) const { - QModelIndex idx = index(row, column, parent); + const QModelIndex idx = index(row, column, parent); return AssetTreeModel::parent(idx); } diff --git a/apps/OpenSpace/ext/launcher/src/profile/cameradialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/cameradialog.cpp index 5966da0fcc..82e4360098 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/cameradialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/cameradialog.cpp @@ -37,6 +37,7 @@ #include #include #include +#include namespace { constexpr int CameraTypeNode = 0; @@ -47,29 +48,23 @@ namespace { template overloaded(Ts...) -> overloaded; bool inNumericalRange(QLineEdit* le, float min, float max) { - QString s = le->text(); + const QString s = le->text(); bool validConversion = false; - float value = s.toFloat(&validConversion); + const float value = s.toFloat(&validConversion); if (!validConversion) { return false; } - if (value < min || value > max) { - return false; - } - return true; + return (value >= min) && (value <= max); } bool isNumericalLargerThan(QLineEdit* le, float limit) { - QString s = le->text(); + const QString s = le->text(); bool validConversion = false; - float value = s.toFloat(&validConversion); + const float value = s.toFloat(&validConversion); if (!validConversion) { return false; } - if (value > limit) { - return true; - } - return false; + return value > limit; } } // namespace @@ -353,17 +348,17 @@ QWidget* CameraDialog::createNavStateWidget() { connect( loadFile, &QPushButton::clicked, [this]() { - QString file = QFileDialog::getOpenFileName( + const QString file = QFileDialog::getOpenFileName( this, "Select navigate state file" ); - std::ifstream f(file.toStdString()); - std::string contents = std::string( - (std::istreambuf_iterator(f)), + std::ifstream f = std::ifstream(file.toStdString()); + const std::string contents = std::string( + std::istreambuf_iterator(f), std::istreambuf_iterator() ); - nlohmann::json json = nlohmann::json::parse(contents); + const nlohmann::json json = nlohmann::json::parse(contents); using namespace openspace::interaction; NavigationState state = NavigationState(json); @@ -529,7 +524,7 @@ bool CameraDialog::areRequiredFormsFilledAndValid() { return allFormsOk; } -void CameraDialog::addErrorMsg(QString errorDescription) { +void CameraDialog::addErrorMsg(const QString& errorDescription) { QString contents = _errorMsg->text(); if (!contents.isEmpty()) { contents += ", "; @@ -563,7 +558,7 @@ void CameraDialog::approved() { !_navState.upY->text().isEmpty() && !_navState.upZ->text().isEmpty()) { - glm::dvec3 u = glm::dvec3( + const glm::dvec3 u = glm::dvec3( _navState.upX->text().toDouble(), _navState.upY->text().toDouble(), _navState.upZ->text().toDouble() diff --git a/apps/OpenSpace/ext/launcher/src/profile/deltatimesdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/deltatimesdialog.cpp index 850d849f1c..f564dc9257 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/deltatimesdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/deltatimesdialog.cpp @@ -60,7 +60,7 @@ namespace { std::string checkForTimeDescription(int intervalIndex, double value) { double amount = value / TimeIntervals[intervalIndex].secondsPerInterval; - std::string description = fmt::format("{}", amount); + std::string description = std::format("{}", amount); description += " " + TimeIntervals[intervalIndex].intervalName + "/sec"; return description; } @@ -70,9 +70,9 @@ namespace { return ""; } - size_t i; - for (i = 0; i < (TimeIntervals.size() - 1); ++i) { - if (abs(value) >= TimeIntervals[i].secondsPerInterval) { + size_t i = 0; + for (i = 0; i < (TimeIntervals.size() - 1); i++) { + if (std::abs(value) >= TimeIntervals[i].secondsPerInterval) { break; } } @@ -89,7 +89,7 @@ DeltaTimesDialog::DeltaTimesDialog(QWidget* parent, std::vector* deltaTi createWidgets(); for (size_t d = 0; d < _deltaTimesData.size(); ++d) { - std::string summary = createSummaryForDeltaTime(d, true); + const std::string summary = createSummaryForDeltaTime(d, true); _listWidget->addItem(new QListWidgetItem(QString::fromStdString(summary))); } @@ -185,7 +185,7 @@ void DeltaTimesDialog::createWidgets() { std::string DeltaTimesDialog::createSummaryForDeltaTime(size_t idx, bool forListView) { int k = (idx % 10 == 9) ? 0 : idx % 10 + 1; k = (idx == 0) ? 1 : k; - std::string key = std::to_string(k); + const std::string key = std::to_string(k); std::string s; if (idx >= 20) { @@ -202,7 +202,7 @@ std::string DeltaTimesDialog::createSummaryForDeltaTime(size_t idx, bool forList } if (forListView) { - s += fmt::format( + s += std::format( "\t{}\t{}", _deltaTimesData.at(idx), timeDescription(_deltaTimesData.at(idx)) ); } @@ -211,7 +211,7 @@ std::string DeltaTimesDialog::createSummaryForDeltaTime(size_t idx, bool forList void DeltaTimesDialog::listItemSelected() { QListWidgetItem *item = _listWidget->currentItem(); - int index = _listWidget->row(item); + const int index = _listWidget->row(item); if (index < (static_cast(_deltaTimesData.size()) - 1)) { _listWidget->setCurrentRow(index); @@ -229,7 +229,7 @@ void DeltaTimesDialog::listItemSelected() { transitionEditMode(index, true); } -void DeltaTimesDialog::setLabelForKey(int index, bool editMode, std::string color) { +void DeltaTimesDialog::setLabelForKey(int index, bool editMode, std::string_view color) { std::string labelS = "Set Simulation Time Increment for key"; if (index >= static_cast(_deltaTimesData.size())) { index = static_cast(_deltaTimesData.size()) - 1; @@ -237,9 +237,9 @@ void DeltaTimesDialog::setLabelForKey(int index, bool editMode, std::string colo if (editMode) { labelS += " '" + createSummaryForDeltaTime(index, false) + "':"; } - _adjustLabel->setText(QString::fromStdString( - "" + labelS + "" - )); + _adjustLabel->setText(QString::fromStdString(std::format( + "{}", color, labelS + ))); } void DeltaTimesDialog::valueChanged(const QString& text) { @@ -247,9 +247,9 @@ void DeltaTimesDialog::valueChanged(const QString& text) { _errorMsg->setText(""); } else { - int value = text.toDouble(); - if (value != 0) { - _value->setText(QString::fromStdString(timeDescription(text.toDouble()))); + const double value = text.toDouble(); + if (value != 0.0) { + _value->setText(QString::fromStdString(timeDescription(value))); _errorMsg->setText(""); } } @@ -267,7 +267,7 @@ bool DeltaTimesDialog::isLineEmpty(int index) { } void DeltaTimesDialog::addDeltaTimeValue() { - int currentListSize = _listWidget->count(); + const int currentListSize = _listWidget->count(); const QString messageAddValue = " (Enter integer value below & click 'Save')"; if ((currentListSize == 1) && (isLineEmpty(0))) { @@ -292,9 +292,9 @@ void DeltaTimesDialog::addDeltaTimeValue() { void DeltaTimesDialog::saveDeltaTimeValue() { QListWidgetItem* item = _listWidget->currentItem(); if (item && !_deltaTimesData.empty()) { - int index = _listWidget->row(item); + const int index = _listWidget->row(item); _deltaTimesData.at(index) = _seconds->text().toDouble(); - std::string summary = createSummaryForDeltaTime(index, true); + const std::string summary = createSummaryForDeltaTime(index, true); _listWidget->item(index)->setText(QString::fromStdString(summary)); transitionEditMode(index, false); _editModeNewItem = false; @@ -362,7 +362,8 @@ void DeltaTimesDialog::parseSelections() { } } std::vector tempDt; - for (int i = 0; i < (finalNonzeroIndex + 1); ++i) { + tempDt.reserve(finalNonzeroIndex); + for (int i = 0; i < (finalNonzeroIndex + 1); i++) { tempDt.push_back(_deltaTimesData[i]); } *_deltaTimes = std::move(_deltaTimesData); @@ -379,11 +380,13 @@ void DeltaTimesDialog::keyPressEvent(QKeyEvent* evt) { } return; } - else if (evt->key() == Qt::Key_Escape) { + + if (evt->key() == Qt::Key_Escape) { if (_editModeNewItem) { discardDeltaTimeValue(); return; } } + QDialog::keyPressEvent(evt); } diff --git a/apps/OpenSpace/ext/launcher/src/profile/horizonsdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/horizonsdialog.cpp index 92231cb143..e340b5ff50 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/horizonsdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/horizonsdialog.cpp @@ -47,18 +47,8 @@ #include #include -using json = nlohmann::json; -using namespace openspace; - -namespace { - BooleanType(IsDirty); - void styleLabel(QLabel* label, IsDirty isDirty) { - std::string newStyle = isDirty ? "error" : "normal"; - label->setObjectName(QString::fromStdString(newStyle)); - label->style()->unpolish(label); - label->style()->polish(label); - } -} // namespace +//using json = nlohmann::json; +//using namespace openspace; namespace { constexpr std::string_view _loggerCat = "HorizonsDialog"; @@ -72,11 +62,18 @@ namespace { constexpr std::string_view Years = "calendar years"; constexpr std::string_view Unitless = "equal intervals (unitless)"; + BooleanType(IsDirty); + void styleLabel(QLabel* label, IsDirty isDirty) { + const std::string newStyle = isDirty ? "error" : "normal"; + label->setObjectName(QString::fromStdString(newStyle)); + label->style()->unpolish(label); + label->style()->polish(label); + } + int findId(const std::string& match) { // Format: id, other information... std::stringstream str(match); - int id; - + int id = 0; str >> id; return id; } @@ -84,10 +81,12 @@ namespace { HorizonsDialog::HorizonsDialog(QWidget* parent) : QDialog(parent) -{ #ifdef OPENSPACE_MODULE_SPACE_ENABLED - _manager = new QNetworkAccessManager(this); + , _manager(new QNetworkAccessManager(this)) +#endif // OPENSPACE_MODULE_SPACE_ENABLED +{ +#ifdef OPENSPACE_MODULE_SPACE_ENABLED setWindowTitle("Horizons"); createWidgets(); #endif // OPENSPACE_MODULE_SPACE_ENABLED @@ -102,7 +101,7 @@ std::filesystem::path HorizonsDialog::file() const { } void HorizonsDialog::openSaveAs() { - QString filename = QFileDialog::getSaveFileName( + const QString filename = QFileDialog::getSaveFileName( this, "Choose a file path where the generated Horizons file will be saved", QString::fromStdString(absPath("${USER}").string()), @@ -142,8 +141,8 @@ void HorizonsDialog::downloadProgress(int value, int total) { } void HorizonsDialog::importTimeRange() { - QString startStr = QString::fromStdString(_validTimeRange.first); - QString endStr = QString::fromStdString(_validTimeRange.second); + const QString startStr = QString::fromStdString(_validTimeRange.first); + const QString endStr = QString::fromStdString(_validTimeRange.second); QDateTime start = QDateTime::fromString(startStr, "yyyy-MMM-dd T hh:mm"); QDateTime end = QDateTime::fromString(endStr, "yyyy-MMM-dd T hh:mm"); @@ -153,8 +152,8 @@ void HorizonsDialog::importTimeRange() { end = QDateTime::fromString(endStr, "yyyy-MMM-dd T hh:mm:ss"); if (!start.isValid() || !end.isValid()) { - QDate startDate = QDate::fromString(startStr, "yyyy-MMM-dd"); - QDate endDate = QDate::fromString(endStr, "yyyy-MMM-dd"); + const QDate startDate = QDate::fromString(startStr, "yyyy-MMM-dd"); + const QDate endDate = QDate::fromString(endStr, "yyyy-MMM-dd"); if (startDate.isValid() && endDate.isValid()) { _startEdit->setDate(startDate); @@ -165,7 +164,7 @@ void HorizonsDialog::importTimeRange() { } _errorMsg->setText("Could not import time range"); - std::string msg = fmt::format( + const std::string msg = std::format( "Could not import time range '{}' to '{}'", _validTimeRange.first, _validTimeRange.second ); @@ -183,7 +182,7 @@ void HorizonsDialog::importTimeRange() { void HorizonsDialog::approved() { #ifdef OPENSPACE_MODULE_SPACE_ENABLED _downloadLabel->show(); - bool result = handleRequest(); + const bool result = handleRequest(); _downloadLabel->hide(); if (result && std::filesystem::is_regular_file(_horizonsFile.file())) { accept(); @@ -216,7 +215,7 @@ void HorizonsDialog::createWidgets() { _typeCombo = new QComboBox; _typeCombo->setToolTip("Choose Horizons data type"); - QStringList types = { + const QStringList types = { "Vector table", "Observer table" }; @@ -335,7 +334,7 @@ void HorizonsDialog::createWidgets() { _timeTypeCombo = new QComboBox; _timeTypeCombo->setToolTip("Choose unit of the step size"); - QStringList timeTypes = { + const QStringList timeTypes = { Minutes.data(), Hours.data(), Days.data(), @@ -437,9 +436,9 @@ bool HorizonsDialog::isValidInput() { } // Numerical bool couldConvert = false; - int32_t step = _stepEdit->text().toInt(&couldConvert); + const int32_t step = _stepEdit->text().toInt(&couldConvert); if (!couldConvert) { - _errorMsg->setText(QString::fromStdString(fmt::format( + _errorMsg->setText(QString::fromStdString(std::format( "Step size needs to be a number in range 1 to {}", std::numeric_limits::max() ))); @@ -459,7 +458,7 @@ bool HorizonsDialog::isValidInput() { // website as a uint32_t. If step size over 32 bit int is sent, this error message is // received: Cannot read numeric value -- re-enter if (step < 1) { - _errorMsg->setText(QString::fromStdString(fmt::format( + _errorMsg->setText(QString::fromStdString(std::format( "Step size is outside valid range 1 to '{}'", std::numeric_limits::max() ))); @@ -470,7 +469,7 @@ bool HorizonsDialog::isValidInput() { } // Send request synchronously, EventLoop waits until request has finished -json HorizonsDialog::sendRequest(const std::string& url) { +nlohmann::json HorizonsDialog::sendRequest(const std::string& url) { QNetworkRequest request; request.setHeader(QNetworkRequest::UserAgentHeader, "OpenSpace"); request.setUrl(QUrl(QString::fromStdString(url))); @@ -484,13 +483,13 @@ json HorizonsDialog::sendRequest(const std::string& url) { _downloadProgress->show(); QEventLoop loop; - QMetaObject::Connection status = connect( + const QMetaObject::Connection status = connect( reply, &QNetworkReply::finished, &loop, &QEventLoop::quit ); if (!status) { appendLog("Could not connect to Horizons API", HorizonsDialog::LogLevel::Error); - return json(); + return nlohmann::json(); } loop.exec(QEventLoop::ExcludeUserInputEvents); @@ -498,19 +497,20 @@ json HorizonsDialog::sendRequest(const std::string& url) { return handleReply(reply); } -json HorizonsDialog::handleReply(QNetworkReply* reply) { +nlohmann::json HorizonsDialog::handleReply(QNetworkReply* reply) { _downloadProgress->hide(); if (reply->error() != QNetworkReply::NoError) { - QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); + const QVariant statusCode = + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (!checkHttpStatus(statusCode)) { - std::string msg = fmt::format( - "Connection Error '{}' ", reply->errorString().toStdString() + const std::string msg = std::format( + "Connection Error '{}'", reply->errorString().toStdString() ); appendLog(msg, HorizonsDialog::LogLevel::Error); } reply->deleteLater(); - return json(); + return nlohmann::json(); } QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); @@ -519,26 +519,26 @@ json HorizonsDialog::handleReply(QNetworkReply* reply) { redirect = reply->url().resolved(redirect); } - std::string msg = fmt::format( + const std::string msg = std::format( "Redirecting request to '{}'", redirect.toString().toStdString() ); appendLog(msg, HorizonsDialog::LogLevel::Info); return sendRequest(redirect.toString().toStdString()); } - QString answer = reply->readAll(); + const QString answer = reply->readAll(); reply->deleteLater(); if (answer.isEmpty()) { - std::string msg = fmt::format( + const std::string msg = std::format( "Connection Error '{}'", reply->errorString().toStdString() ); appendLog(msg, HorizonsDialog::LogLevel::Error); - return json(); + return nlohmann::json(); } // Convert the answer to a json object and return it - return json::parse(answer.toStdString()); + return nlohmann::json::parse(answer.toStdString()); } bool HorizonsDialog::checkHttpStatus(const QVariant& statusCode) { @@ -547,7 +547,7 @@ bool HorizonsDialog::checkHttpStatus(const QVariant& statusCode) { statusCode.toInt() != static_cast(HorizonsDialog::HTTPCodes::Ok)) { std::string message; - HorizonsDialog::HTTPCodes code = + const HorizonsDialog::HTTPCodes code = static_cast(statusCode.toInt()); switch (code) { @@ -568,7 +568,7 @@ bool HorizonsDialog::checkHttpStatus(const QVariant& statusCode) { "later time"; break; default: - message = fmt::format( + message = std::format( "HTTP status code '{}' was returned", statusCode.toString().toStdString() ); @@ -618,7 +618,8 @@ std::pair HorizonsDialog::readTimeRange() { "Trajectory name" ); - QDateTime start, end; + QDateTime start; + QDateTime end; start = QDateTime::fromString( QString::fromStdString(timeRange.first), "yyyy-MMM-dd T hh:mm" @@ -665,16 +666,16 @@ std::pair HorizonsDialog::readTimeRange() { } else { _errorMsg->setText("Could not parse time range"); - std::string msg = fmt::format( - "Could not read time range '{}' to '{}'", timeRange.first, - timeRange.second + const std::string msg = std::format( + "Could not read time range '{}' to '{}'", + timeRange.first, timeRange.second ); appendLog(msg, LogLevel::Error); } return std::pair(); } else { - std::string msg = fmt::format( + const std::string msg = std::format( "Could not find all time range information. Latest Horizons " "mesage: {}", _latestHorizonsError ); @@ -686,6 +687,8 @@ std::pair HorizonsDialog::readTimeRange() { } bool HorizonsDialog::handleRequest() { + using namespace openspace; + if (!isValidInput()) { return false; } @@ -707,14 +710,14 @@ bool HorizonsDialog::handleRequest() { _validTimeRange = std::pair(); _latestHorizonsError.clear(); - std::string url = constructUrl(); + const std::string url = constructUrl(); _chooseObserverCombo->clear(); _chooseObserverCombo->hide(); _chooseTargetCombo->clear(); _chooseTargetCombo->hide(); - json answer = sendRequest(url); + nlohmann::json answer = sendRequest(url); if (answer.empty()) { _errorMsg->setText("Connection error"); return false; @@ -728,19 +731,18 @@ bool HorizonsDialog::handleRequest() { _horizonsFile = std::move(file); HorizonsResultCode result = isValidHorizonsFile(_horizonsFile.file()); - bool isValid = handleResult(result); - + const bool isValid = handleResult(result); if (!isValid && std::filesystem::is_regular_file(_horizonsFile.file())) { - std::string newName = _horizonsFile.file().filename().stem().string(); + const std::string newName = _horizonsFile.file().filename().stem().string(); - std::filesystem::path oldFile = _horizonsFile.file(); + const std::filesystem::path& oldFile = _horizonsFile.file(); std::filesystem::path newFile = oldFile; newFile.replace_filename(newName + "_error.txt"); std::filesystem::rename(oldFile, newFile); - std::string msg = fmt::format( - "For more information, see the saved error file {}", newFile + const std::string msg = std::format( + "For more information, see the saved error file '{}'", newFile ); appendLog(msg, LogLevel::Info); } @@ -749,8 +751,10 @@ bool HorizonsDialog::handleRequest() { } std::string HorizonsDialog::constructUrl() { + using namespace openspace; + // Construct url for request - HorizonsType type; + HorizonsType type = HorizonsType::Invalid; if (_typeCombo->currentIndex() == 0) { type = HorizonsType::Vector; } @@ -765,7 +769,8 @@ std::string HorizonsDialog::constructUrl() { std::string command; if (_chooseTargetCombo->count() > 0 && _chooseTargetCombo->currentIndex() != 0) { - QVariant t = _chooseTargetCombo->itemData(_chooseTargetCombo->currentIndex()); + const QVariant t = + _chooseTargetCombo->itemData(_chooseTargetCombo->currentIndex()); command = t.toString().toStdString(); _targetName = _chooseTargetCombo->currentText().toStdString(); _targetEdit->setText(QString::fromStdString(command)); @@ -777,9 +782,9 @@ std::string HorizonsDialog::constructUrl() { std::string center; if (_chooseObserverCombo->count() > 0 && _chooseObserverCombo->currentIndex() != 0) { - QVariant observer = + const QVariant observer = _chooseObserverCombo->itemData(_chooseObserverCombo->currentIndex()); - std::string id = observer.toString().toStdString(); + const std::string id = observer.toString().toStdString(); center = "@" + id; _observerName = _chooseObserverCombo->currentText().toStdString(); _centerEdit->setText(QString::fromStdString(id)); @@ -789,13 +794,13 @@ std::string HorizonsDialog::constructUrl() { _observerName = center; } - _startTime = fmt::format( + _startTime = std::format( "{} {}", _startEdit->date().toString("yyyy-MM-dd").toStdString(), _startEdit->time().toString("hh:mm:ss").toStdString() ); - _endTime = fmt::format( + _endTime = std::format( "{} {}", _endEdit->date().toString("yyyy-MM-dd").toStdString(), _endEdit->time().toString("hh:mm:ss").toStdString() @@ -840,7 +845,9 @@ std::string HorizonsDialog::constructUrl() { ); } -openspace::HorizonsFile HorizonsDialog::handleAnswer(json& answer) { +openspace::HorizonsFile HorizonsDialog::handleAnswer(nlohmann::json& answer) { + using namespace openspace; + auto it = answer.find("error"); if (it != answer.end()) { _latestHorizonsError = *it; @@ -860,12 +867,14 @@ openspace::HorizonsFile HorizonsDialog::handleAnswer(json& answer) { } // Create a text file and write reply to it - std::filesystem::path filePath = + const std::filesystem::path filePath = std::filesystem::absolute(_fileEdit->text().toStdString()); auto result = answer.find("result"); if (result == answer.end()) { - std::string msg = fmt::format("Malformed answer recieved '{}'", answer.dump()); + const std::string msg = std::format( + "Malformed answer received '{}'", answer.dump() + ); appendLog(msg, HorizonsDialog::LogLevel::Error); return openspace::HorizonsFile(); } @@ -878,7 +887,7 @@ openspace::HorizonsFile HorizonsDialog::handleAnswer(json& answer) { QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel ); msgBox.setDefaultButton(QMessageBox::Yes); - int ret = msgBox.exec(); + const int ret = msgBox.exec(); switch (ret) { case QMessageBox::Yes: // If yes then continue as normal @@ -900,13 +909,15 @@ openspace::HorizonsFile HorizonsDialog::handleAnswer(json& answer) { } bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { + using namespace openspace; + switch (result) { case HorizonsResultCode::Valid: { // If the request worked then delete the corresponding error file if it exist - std::filesystem::path validFile(_horizonsFile.file()); + std::filesystem::path validFile =_horizonsFile.file(); - std::string errorName = validFile.filename().stem().string(); - std::filesystem::path errorFile = validFile.replace_filename( + const std::string errorName = validFile.filename().stem().string(); + const std::filesystem::path errorFile = validFile.replace_filename( errorName + "_error.txt" ); @@ -918,7 +929,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { case HorizonsResultCode::Empty: { _errorMsg->setText("The horizons file is empty"); if (!_latestHorizonsError.empty()) { - std::string msg = fmt::format( + const std::string msg = std::format( "Latest Horizons error: {}", _latestHorizonsError ); appendLog(msg, LogLevel::Error); @@ -928,7 +939,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::ErrorSize: { - std::string msg = fmt::format( + const std::string msg = std::format( "Time range '{}' to '{}' with step size '{} {}' is too big, try to " "increase the step size and/or decrease the time range", _startTime, _endTime, _stepEdit->text().toStdString(), @@ -952,7 +963,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { std::filesystem::remove(_horizonsFile.file()); break; case HorizonsResultCode::ErrorTimeRange: { - std::string msg = fmt::format( + std::string msg = std::format( "Time range is outside the valid range for target '{}'", _targetName ); appendLog(msg, HorizonsDialog::LogLevel::Error); @@ -962,15 +973,15 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { _validTimeRange = readTimeRange(); if (_validTimeRange.first.empty() || _validTimeRange.second.empty()) { if (!_latestHorizonsError.empty()) { - msg = fmt::format("Latest Horizons error: {}", _latestHorizonsError); + msg = std::format("Latest Horizons error: {}", _latestHorizonsError); appendLog(msg, LogLevel::Error); } break; } - msg = fmt::format( - "Valid time range is '{}' to '{}'", _validTimeRange.first, - _validTimeRange.second + msg = std::format( + "Valid time range is '{}' to '{}'", + _validTimeRange.first, _validTimeRange.second ); appendLog(msg, HorizonsDialog::LogLevel::Info); _importTimeButton->show(); @@ -979,12 +990,12 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::ErrorNoObserver: { - std::string msg = fmt::format( + std::string msg = std::format( "No match was found for observer '{}'", _observerName ); appendLog(msg, HorizonsDialog::LogLevel::Error); - msg = fmt::format( + msg = std::format( "Try to use '@{}' as observer to search for possible matches", _observerName ); @@ -995,7 +1006,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::ErrorObserverTargetSame: { - std::string msg = fmt::format( + const std::string msg = std::format( "The observer '{}' and target '{}' are the same. Please use another " "observer for the current target", _observerName, _targetName ); @@ -1007,7 +1018,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::ErrorNoData: { - std::string msg = fmt::format( + const std::string msg = std::format( "There is not enough data to compute the state of target '{}' in " "relation to the observer '{}' for the time range '{}' to '{}'. Try to " "use another observer for the current target or another time range", @@ -1019,20 +1030,20 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::MultipleObserverStations: { - std::string msg = fmt::format( - "Multiple matching observer stations were found for observer '{}'. ", + std::string msg = std::format( + "Multiple matching observer stations were found for observer '{}'", _observerName ); appendLog(msg, HorizonsDialog::LogLevel::Warning); - msg = fmt::format( + msg = std::format( "Did not find what you were looking for? Use '@{}' as observer to search " "for alternatives", _observerName ); appendLog(msg, HorizonsDialog::LogLevel::Info); styleLabel(_centerLabel, IsDirty::Yes); - std::vector matchingstations = + const std::vector matchingstations = _horizonsFile.parseMatches( "Observatory Name", "Multiple matching stations found" @@ -1043,7 +1054,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { HorizonsDialog::LogLevel::Error ); if (!_latestHorizonsError.empty()) { - msg = fmt::format("Latest Horizons error: {}", _latestHorizonsError); + msg = std::format("Latest Horizons error: {}", _latestHorizonsError); appendLog(msg, LogLevel::Error); } break; @@ -1062,13 +1073,13 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::MultipleObserver: { - std::string msg = fmt::format( + std::string msg = std::format( "Multiple matches were found for observer '{}'", _observerName ); appendLog(msg, HorizonsDialog::LogLevel::Warning); styleLabel(_centerLabel, IsDirty::Yes); - std::vector matchingObservers = + const std::vector matchingObservers = _horizonsFile.parseMatches("Name", "matches", ">MATCH NAME<"); if (matchingObservers.empty()) { appendLog( @@ -1076,9 +1087,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { HorizonsDialog::LogLevel::Error ); if (!_latestHorizonsError.empty()) { - msg = fmt::format( - "Latest Horizons error: {}", _latestHorizonsError - ); + msg = std::format("Latest Horizons error: {}", _latestHorizonsError); appendLog(msg, LogLevel::Error); } break; @@ -1097,12 +1106,12 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { break; } case HorizonsResultCode::ErrorNoTarget: { - std::string msg = fmt::format( + std::string msg = std::format( "No match was found for target '{}'", _targetName ); appendLog(msg, HorizonsDialog::LogLevel::Error); - msg = fmt::format( + msg = std::format( "Try to use '{}*' as target to search for possible matches", _targetName ); appendLog(msg, HorizonsDialog::LogLevel::Info); @@ -1123,13 +1132,13 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { // Format: ID#, Name, Designation, IAU/aliases/other // Line after data: Number of matches = X. Use ID# to make unique selection. - std::string msg = fmt::format( + std::string msg = std::format( "Multiple matches were found for target '{}'", _targetName ); appendLog(msg, HorizonsDialog::LogLevel::Warning); styleLabel(_targetLabel, IsDirty::Yes); - std::vector matchingTargets = + const std::vector matchingTargets = _horizonsFile.parseMatches("Name", "matches", ">MATCH NAME<"); if (matchingTargets.empty()) { appendLog( @@ -1137,7 +1146,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { HorizonsDialog::LogLevel::Error ); if (!_latestHorizonsError.empty()) { - msg = fmt::format("Latest Horizons error: {}", _latestHorizonsError); + msg = std::format("Latest Horizons error: {}", _latestHorizonsError); appendLog(msg, LogLevel::Error); } break; @@ -1158,7 +1167,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { case HorizonsResultCode::UnknownError: { appendLog("Unknown error", LogLevel::Error); if (!_latestHorizonsError.empty()) { - std::string msg = fmt::format( + const std::string msg = std::format( "Latest Horizons error: {}", _latestHorizonsError ); appendLog(msg, LogLevel::Error); @@ -1168,7 +1177,7 @@ bool HorizonsDialog::handleResult(openspace::HorizonsResultCode& result) { } default: { if (!_latestHorizonsError.empty()) { - std::string msg = fmt::format( + const std::string msg = std::format( "Latest Horizons error: {}", _latestHorizonsError ); appendLog(msg, LogLevel::Error); diff --git a/apps/OpenSpace/ext/launcher/src/profile/marknodesdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/marknodesdialog.cpp index 0a955cb781..3c2af72a44 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/marknodesdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/marknodesdialog.cpp @@ -57,9 +57,8 @@ void MarkNodesDialog::createWidgets() { _list->setDragDropMode(QListView::InternalMove); _list->setResizeMode(QListView::Adjust); - for (size_t i = 0; i < _markedNodes->size(); ++i) { - QListWidgetItem* item = - new QListWidgetItem(QString::fromStdString(_markedNodes->at(i))); + for (const std::string& nodes : *_markedNodes) { + QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(nodes)); _list->addItem(item); } layout->addWidget(_list); @@ -100,7 +99,6 @@ void MarkNodesDialog::listItemAdded() { return; } - std::string itemToAdd = _newNode->text().toStdString(); QListWidgetItem* item = new QListWidgetItem(_newNode->text()); _list->addItem(item); @@ -113,14 +111,14 @@ void MarkNodesDialog::listItemAdded() { void MarkNodesDialog::listItemRemove() { QListWidgetItem* item = _list->currentItem(); - int index = _list->row(item); + const int index = _list->row(item); _list->takeItem(index); } void MarkNodesDialog::parseSelections() { std::vector nodes; for (int i = 0; i < _list->count(); i++) { - QString node = _list->item(i)->text(); + const QString node = _list->item(i)->text(); nodes.push_back(node.toStdString()); } *_markedNodes = std::move(nodes); diff --git a/apps/OpenSpace/ext/launcher/src/profile/modulesdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/modulesdialog.cpp index fc5df1fa22..7ccd0487ac 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/modulesdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/modulesdialog.cpp @@ -42,6 +42,26 @@ namespace { .loadedInstruction = std::nullopt, .notLoadedInstruction = std::nullopt }; + + QString createOneLineSummary(Profile::Module m) { + QString summary = QString::fromStdString(m.name); + const bool hasCommandForLoaded = !m.loadedInstruction->empty(); + const bool hasCommandForNotLoaded = !m.notLoadedInstruction->empty(); + + if (hasCommandForLoaded && hasCommandForNotLoaded) { + summary += " (commands set for both loaded & not-loaded conditions)"; + } + else if (hasCommandForLoaded) { + summary += " (command set only for loaded condition)"; + } + else if (hasCommandForNotLoaded) { + summary += " (command set only for NOT loaded condition)"; + } + else { + summary += " (no commands set)"; + } + return summary; + } } // namespace ModulesDialog::ModulesDialog(QWidget* parent, @@ -160,29 +180,9 @@ void ModulesDialog::createWidgets() { } } -QString ModulesDialog::createOneLineSummary(Profile::Module m) { - QString summary = QString::fromStdString(m.name); - bool hasCommandForLoaded = !m.loadedInstruction->empty(); - bool hasCommandForNotLoaded = !m.notLoadedInstruction->empty(); - - if (hasCommandForLoaded && hasCommandForNotLoaded) { - summary += " (commands set for both loaded & not-loaded conditions)"; - } - else if (hasCommandForLoaded) { - summary += " (command set only for loaded condition)"; - } - else if (hasCommandForNotLoaded) { - summary += " (command set only for NOT loaded condition)"; - } - else { - summary += " (no commands set)"; - } - return summary; -} - void ModulesDialog::listItemSelected() { QListWidgetItem* item = _list->currentItem(); - int index = _list->row(item); + const int index = _list->row(item); if (!_moduleData.empty()) { const Profile::Module& m = _moduleData[index]; @@ -211,7 +211,7 @@ bool ModulesDialog::isLineEmpty(int index) const { } void ModulesDialog::listItemAdded() { - int currentListSize = _list->count(); + const int currentListSize = _list->count(); if ((currentListSize == 1) && (isLineEmpty(0))) { // Special case where list is "empty" but really has one line that is blank. @@ -259,7 +259,7 @@ void ModulesDialog::listItemSave() { } QListWidgetItem* item = _list->currentItem(); - int index = _list->row(item); + const int index = _list->row(item); if (!_moduleData.empty()) { _moduleData[index].name = _moduleEdit->text().toStdString(); @@ -290,7 +290,7 @@ void ModulesDialog::listItemRemove() { _list->item(0)->setText(""); } else { - int index = _list->currentRow(); + const int index = _list->currentRow(); if (index >= 0 && index < _list->count()) { delete _list->takeItem(index); if (!_moduleData.empty()) { diff --git a/apps/OpenSpace/ext/launcher/src/profile/profileedit.cpp b/apps/OpenSpace/ext/launcher/src/profile/profileedit.cpp index 6b13a36ef7..6d9abae5e5 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/profileedit.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/profileedit.cpp @@ -51,7 +51,7 @@ using namespace openspace; namespace { - QString labelText(size_t size, QString title) { + QString labelText(size_t size, const QString& title) { QString label; if (size > 0) { label = title + " (" + QString::number(size) + ")"; @@ -74,14 +74,14 @@ namespace { const std::vector& actions) { std::string results; - for (Profile::Keybinding k : keybindings) { + for (const Profile::Keybinding& k : keybindings) { const auto it = std::find_if( actions.cbegin(), actions.cend(), [id = k.action](const Profile::Action& a) { return a.identifier == id; } ); std::string name = it != actions.end() ? it->name : "Unknown action"; - results += fmt::format("{} ({})\n", name, ghoul::to_string(k.key)); + results += std::format("{} ({})\n", name, ghoul::to_string(k.key)); } return results; } @@ -89,7 +89,7 @@ namespace { std::string summarizeProperties(const std::vector& properties) { std::string results; for (openspace::Profile::Property p : properties) { - results += fmt::format("{} = {}\n", p.name, p.value); + results += std::format("{} = {}\n", p.name, p.value); } return results; } @@ -368,10 +368,10 @@ void ProfileEdit::duplicateProfile() { constexpr char Separator = '_'; int version = 0; - if (size_t it = profile.rfind(Separator); it != std::string::npos) { + if (const size_t it = profile.rfind(Separator); it != std::string::npos) { // If the value exists, we have a profile that potentially already has a version // number attached to it - std::string versionStr = profile.substr(it + 1); + const std::string versionStr = profile.substr(it + 1); try { version = std::stoi(versionStr); @@ -392,11 +392,11 @@ void ProfileEdit::duplicateProfile() { while (true) { version++; - std::string candidate = profile + Separator + std::to_string(version); - std::string candidatePath = _profileBasePath + candidate + ".profile"; + const std::string candidate = profile + Separator + std::to_string(version); + const std::string candidatePath = _profileBasePath + candidate + ".profile"; if (!std::filesystem::exists(candidatePath)) { - _profileEdit->setText(QString::fromStdString(std::move(candidate))); + _profileEdit->setText(QString::fromStdString(candidate)); return; } } @@ -489,7 +489,7 @@ void ProfileEdit::approved() { return; } - std::filesystem::path p = fmt::format( + const std::filesystem::path p = std::format( "{}/{}.profile", _builtInProfilesPath, profileName ); if (std::filesystem::exists(p)) { diff --git a/apps/OpenSpace/ext/launcher/src/profile/propertiesdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/propertiesdialog.cpp index 5a92f969b2..3df3f61585 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/propertiesdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/propertiesdialog.cpp @@ -48,6 +48,18 @@ namespace { "", "" }; + + QString createOneLineSummary(const Profile::Property& p) { + QString summary = QString::fromStdString(p.name); + summary += " = "; + summary += QString::fromStdString(p.value); + summary += " (SetPropertyValue"; + if (p.setType == Profile::Property::SetType::SetPropertyValueSingle) { + summary += "Single"; + } + summary += ")"; + return summary; + } } // namespace PropertiesDialog::PropertiesDialog(QWidget* parent, @@ -70,8 +82,8 @@ void PropertiesDialog::createWidgets() { _list, &QListWidget::itemSelectionChanged, this, &PropertiesDialog::listItemSelected ); - for (size_t i = 0; i < _propertyData.size(); ++i) { - _list->addItem(new QListWidgetItem(createOneLineSummary(_propertyData[i]))); + for (const Profile::Property& property : _propertyData) { + _list->addItem(new QListWidgetItem(createOneLineSummary(property))); } layout->addWidget(_list); } @@ -168,24 +180,12 @@ void PropertiesDialog::createWidgets() { } } -QString PropertiesDialog::createOneLineSummary(Profile::Property p) { - QString summary = QString::fromStdString(p.name); - summary += " = "; - summary += QString::fromStdString(p.value); - summary += " (SetPropertyValue"; - if (p.setType == Profile::Property::SetType::SetPropertyValueSingle) { - summary += "Single"; - } - summary += ")"; - return summary; -} - void PropertiesDialog::listItemSelected() { QListWidgetItem* item = _list->currentItem(); - int index = _list->row(item); + const int index = _list->row(item); if (!_propertyData.empty()) { - Profile::Property& p = _propertyData[index]; + const Profile::Property& p = _propertyData[index]; if (p.setType == Profile::Property::SetType::SetPropertyValueSingle) { _commandCombo->setCurrentIndex(0); } @@ -210,7 +210,7 @@ bool PropertiesDialog::isLineEmpty(int index) { } void PropertiesDialog::listItemAdded() { - int currentListSize = _list->count(); + const int currentListSize = _list->count(); if ((currentListSize == 1) && (isLineEmpty(0))) { // Special case where list is "empty" but really has one line that is blank. @@ -242,7 +242,7 @@ void PropertiesDialog::listItemSave() { } QListWidgetItem* item = _list->currentItem(); - int index = _list->row(item); + const int index = _list->row(item); if (!_propertyData.empty()) { if (_commandCombo->currentIndex() == 0) { @@ -300,10 +300,10 @@ void PropertiesDialog::listItemRemove() { _list->item(0)->setText(""); } else { - int index = _list->currentRow(); + const int index = _list->currentRow(); if (index >= 0 && index < _list->count()) { delete _list->takeItem(index); - if (_propertyData.size() > 0) { + if (!_propertyData.empty()) { _propertyData.erase(_propertyData.begin() + index); } } @@ -379,7 +379,7 @@ void PropertiesDialog::selectLineFromScriptLog() { ScriptlogDialog d(this, "openspace.setPropertyValue"); connect( &d, &ScriptlogDialog::scriptsSelected, - [this](std::vector scripts) { + [this](const std::vector& scripts) { for (const std::string& script : scripts) { listItemAdded(); @@ -392,13 +392,13 @@ void PropertiesDialog::selectLineFromScriptLog() { // openspace.setPropertyValue('prop', value); if (text.startsWith("openspace.setPropertyValueSingle")) { _commandCombo->setCurrentIndex(0); - std::string_view prefix = "openspace.setPropertyValueSingle"; + const std::string_view prefix = "openspace.setPropertyValueSingle"; text = text.mid(static_cast(prefix.size()) + 1); // +1 for ( } else { // command == "openspace.setPropertyValue" _commandCombo->setCurrentIndex(1); - std::string_view prefix = "openspace.setPropertyValue"; + const std::string_view prefix = "openspace.setPropertyValue"; text = text.mid(static_cast(prefix.size()) + 1); // +1 for ( } @@ -411,11 +411,10 @@ void PropertiesDialog::selectLineFromScriptLog() { } // Remove the string markers around the property - QString property = textList[0].mid(1, textList[0].size() - 2); + const QString property = textList[0].mid(1, textList[0].size() - 2); textList.removeFirst(); - QString value = textList.join(","); - + const QString value = textList.join(","); _propertyEdit->setText(property.trimmed()); _valueEdit->setText(value.trimmed()); diff --git a/apps/OpenSpace/ext/launcher/src/profile/scriptlogdialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/scriptlogdialog.cpp index ffdefd95d3..2287f48423 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/scriptlogdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/scriptlogdialog.cpp @@ -65,7 +65,7 @@ void ScriptlogDialog::createWidgets() { QGridLayout* layout = new QGridLayout(this); { - QLabel* heading = new QLabel(QString::fromStdString(fmt::format( + QLabel* heading = new QLabel(QString::fromStdString(std::format( "Choose commands from \"{}\"", _scriptLogFile ))); heading->setObjectName("heading"); @@ -76,7 +76,7 @@ void ScriptlogDialog::createWidgets() { connect( open, &QPushButton::clicked, [this, heading]() { - QString file = QFileDialog::getOpenFileName( + const QString file = QFileDialog::getOpenFileName( this, "Select log file", "", @@ -84,7 +84,7 @@ void ScriptlogDialog::createWidgets() { ); _scriptLogFile = file.toStdString(); - heading->setText(QString::fromStdString(fmt::format( + heading->setText(QString::fromStdString(std::format( "Choose commands from \"{}\"", _scriptLogFile ))); loadScriptFile(); @@ -126,7 +126,7 @@ void ScriptlogDialog::createWidgets() { void ScriptlogDialog::loadScriptFile() { _scripts.clear(); - std::string log = absPath(_scriptLogFile).string(); + const std::string log = absPath(_scriptLogFile).string(); QFile file(QString::fromStdString(log)); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); @@ -143,7 +143,7 @@ void ScriptlogDialog::loadScriptFile() { } void ScriptlogDialog::updateScriptList() { - std::string filter = _filter->text().toStdString(); + const std::string filter = _filter->text().toStdString(); QListWidgetItem* curr = _scriptlogList->currentItem(); std::string selection; if (curr) { @@ -152,8 +152,8 @@ void ScriptlogDialog::updateScriptList() { int index = -1; _scriptlogList->clear(); for (const std::string& script : _scripts) { - bool foundDynamic = script.find(filter) != std::string::npos; - bool foundStatic = + const bool foundDynamic = script.find(filter) != std::string::npos; + const bool foundStatic = _fixedFilter.empty() ? true : script.find(_fixedFilter) != std::string::npos; if (foundDynamic && foundStatic) { if (script == selection && index == -1) { diff --git a/apps/OpenSpace/ext/launcher/src/profile/timedialog.cpp b/apps/OpenSpace/ext/launcher/src/profile/timedialog.cpp index d10fd0354b..6aa1998b04 100644 --- a/apps/OpenSpace/ext/launcher/src/profile/timedialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/profile/timedialog.cpp @@ -33,7 +33,7 @@ #include #include #include -#include +#include #include using namespace openspace; @@ -45,7 +45,7 @@ TimeDialog::TimeDialog(QWidget* parent, std::optional* setWindowTitle("Time"); createWidgets(); - QStringList types = { "Absolute", "Relative" }; + const QStringList types = { "Absolute", "Relative" }; _typeCombo->addItems(types); if (_time->has_value()) { _timeData = **_time; @@ -53,7 +53,7 @@ TimeDialog::TimeDialog(QWidget* parent, std::optional* if (_timeData.value.empty()) { _timeData.value = "0d"; } - int len = static_cast(_relativeEdit->text().length()); + const int len = static_cast(_relativeEdit->text().length()); _relativeEdit->setSelection(0, len); } else { @@ -121,8 +121,8 @@ void TimeDialog::createWidgets() { } void TimeDialog::enableAccordingToType(int idx) { - Profile::Time::Type comboIdx = static_cast(idx); - bool setFormatForAbsolute = (comboIdx == Profile::Time::Type::Absolute); + const Profile::Time::Type comboIdx = static_cast(idx); + const bool setFormatForAbsolute = (comboIdx == Profile::Time::Type::Absolute); enableFormatForAbsolute(setFormatForAbsolute); _typeCombo->setCurrentIndex(idx); if (comboIdx == Profile::Time::Type::Relative) { @@ -137,9 +137,13 @@ void TimeDialog::enableAccordingToType(int idx) { } else { _relativeEdit->setText("Relative Time:"); - size_t tIdx = _timeData.value.find_first_of('T', 0); - QString importDate = QString::fromStdString(_timeData.value.substr(0, tIdx)); - QString importTime = QString::fromStdString(_timeData.value.substr(tIdx + 1)); + const size_t tIdx = _timeData.value.find_first_of('T', 0); + const QString importDate = QString::fromStdString( + _timeData.value.substr(0, tIdx) + ); + const QString importTime = QString::fromStdString( + _timeData.value.substr(tIdx + 1) + ); _absoluteEdit->setDate(QDate::fromString(importDate, Qt::DateFormat::ISODate)); _absoluteEdit->setTime(QTime::fromString(importTime)); _relativeEdit->clear(); @@ -171,7 +175,7 @@ void TimeDialog::approved() { else { Profile::Time t; t.type = Profile::Time::Type::Absolute; - t.value = fmt::format( + t.value = std::format( "{}T{}", _absoluteEdit->date().toString("yyyy-MM-dd").toStdString(), _absoluteEdit->time().toString().toStdString() diff --git a/apps/OpenSpace/ext/launcher/src/settingsdialog.cpp b/apps/OpenSpace/ext/launcher/src/settingsdialog.cpp index f9c0eac68a..b82c13c4fd 100644 --- a/apps/OpenSpace/ext/launcher/src/settingsdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/settingsdialog.cpp @@ -35,14 +35,13 @@ #include #include -SettingsDialog::SettingsDialog(openspace::Settings settings, - QWidget* parent) +SettingsDialog::SettingsDialog(openspace::Settings settings, QWidget* parent) : QDialog(parent) - , _currentEdit(settings) + , _currentEdit(std::move(settings)) { setWindowTitle("Settings"); createWidgets(); - loadFromSettings(settings); + loadFromSettings(_currentEdit); // Setting the startup values for the control will have caused the Save button to be // enabled, so we need to manually disable it again here @@ -91,7 +90,7 @@ void SettingsDialog::createWidgets() { _profile, &QLineEdit::textChanged, [this]() { - std::string v = _profile->text().toStdString(); + const std::string v = _profile->text().toStdString(); if (v.empty()) { _currentEdit.profile = std::nullopt; } @@ -147,7 +146,7 @@ void SettingsDialog::createWidgets() { _configuration, &QLineEdit::textChanged, [this]() { - std::string v = _configuration->text().toStdString(); + const std::string v = _configuration->text().toStdString(); if (v.empty()) { _currentEdit.configuration = std::nullopt; } @@ -392,7 +391,7 @@ void SettingsDialog::loadFromSettings(const openspace::Settings& settings) { if (settings.visibility.has_value()) { using Visibility = openspace::properties::Property::Visibility; - Visibility vis = *settings.visibility; + const Visibility vis = *settings.visibility; switch (vis) { case Visibility::NoviceUser: _propertyVisibility->setCurrentText("Novice User"); @@ -417,9 +416,9 @@ void SettingsDialog::loadFromSettings(const openspace::Settings& settings) { } if (settings.layerServer.has_value()) { - openspace::Configuration::LayerServer server = *settings.layerServer; + Configuration::LayerServer server = *settings.layerServer; _layerServer->setCurrentText( - QString::fromStdString(openspace::layerServerToString(server)) + QString::fromStdString(openspace::layerServerToString(std::move(server))) ); } diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/displaywindowunion.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/displaywindowunion.cpp index f651745b98..88961d3c9f 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/displaywindowunion.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/displaywindowunion.cpp @@ -49,12 +49,12 @@ DisplayWindowUnion::DisplayWindowUnion(const std::vector& monitorSizeList } void DisplayWindowUnion::createWidgets(int nMaxWindows, - std::vector monitorResolutions, + const std::vector& monitorResolutions, std::array windowColors, bool resetToDefault) { // Add all window controls (some will be hidden from GUI initially) - for (int i = 0; i < nMaxWindows; ++i) { + for (int i = 0; i < nMaxWindows; i++) { const int monitorNumForThisWindow = (monitorResolutions.size() > 1 && i >= 2) ? 1 : 0; @@ -94,7 +94,7 @@ void DisplayWindowUnion::createWidgets(int nMaxWindows, layoutMonButton->addStretch(1); _addWindowButton = new QPushButton("Add Window"); - _addWindowButton->setToolTip(QString::fromStdString(fmt::format( + _addWindowButton->setToolTip(QString::fromStdString(std::format( "Add a window to the configuration (up to {} windows allowed)", nMaxWindows ))); _addWindowButton->setFocusPolicy(Qt::NoFocus); @@ -114,7 +114,7 @@ void DisplayWindowUnion::createWidgets(int nMaxWindows, QBoxLayout* layoutWindows = new QHBoxLayout; layoutWindows->setContentsMargins(0, 0, 0, 0); layoutWindows->setSpacing(0); - for (int i = 0; i < nMaxWindows; ++i) { + for (int i = 0; i < nMaxWindows; i++) { layoutWindows->addWidget(_windowControl[i]); if (i < (nMaxWindows - 1)) { QFrame* frameForNextWindow = new QFrame; @@ -130,7 +130,7 @@ void DisplayWindowUnion::createWidgets(int nMaxWindows, std::vector DisplayWindowUnion::activeWindowControls() const { std::vector res; res.reserve(_nWindowsDisplayed); - for (unsigned int i = 0; i < _nWindowsDisplayed; ++i) { + for (unsigned int i = 0; i < _nWindowsDisplayed; i++) { res.push_back(_windowControl[i]); } return res; @@ -160,10 +160,10 @@ unsigned int DisplayWindowUnion::numWindowsDisplayed() const { } void DisplayWindowUnion::showWindows() { - for (size_t i = 0; i < _windowControl.size(); ++i) { + for (size_t i = 0; i < _windowControl.size(); i++) { _windowControl[i]->setVisible(i < _nWindowsDisplayed); } - for (size_t i = 0; i < _frameBorderLines.size(); ++i) { + for (size_t i = 0; i < _frameBorderLines.size(); i++) { _frameBorderLines[i]->setVisible(i < (_nWindowsDisplayed - 1)); } _removeWindowButton->setEnabled(_nWindowsDisplayed > 1); diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/monitorbox.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/monitorbox.cpp index 3bde46d3ab..57b1eb7809 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/monitorbox.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/monitorbox.cpp @@ -27,7 +27,7 @@ #include namespace { - constexpr float MarginFractionOfWidgetSize = 0.05f; + constexpr float MarginFractionWidgetSize = 0.05f; constexpr int WindowOpacity = 170; QRectF computeUnion(const std::vector& monitorResolutions) { @@ -48,15 +48,15 @@ MonitorBox::MonitorBox(QRect widgetDims, const std::vector& monitorResolu { setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - QRectF monitorArrangement = computeUnion(monitorResolutions); + const QRectF monitorArrangement = computeUnion(monitorResolutions); const float aspectRatio = monitorArrangement.width() / monitorArrangement.height(); if (aspectRatio > 1.0) { - float borderMargin = 2.f * MarginFractionOfWidgetSize * widgetDims.width(); + const float borderMargin = 2.f * MarginFractionWidgetSize * widgetDims.width(); widgetDims.setHeight(widgetDims.width() / aspectRatio + borderMargin); } else { - float borderMargin = 2.f * MarginFractionOfWidgetSize * widgetDims.height(); + const float borderMargin = 2.f * MarginFractionWidgetSize * widgetDims.height(); widgetDims.setWidth(widgetDims.height() * aspectRatio + borderMargin); } setFixedSize(widgetDims.width(), widgetDims.height()); @@ -68,7 +68,7 @@ MonitorBox::MonitorBox(QRect widgetDims, const std::vector& monitorResolu computeScaledResolutionLandscape(monitorArrangement, monitorResolutions) : computeScaledResolutionPortrait(monitorArrangement, monitorResolutions); - for (size_t i = 0; i < monitorResolutions.size(); ++i) { + for (size_t i = 0; i < monitorResolutions.size(); i++) { _monitorDimensionsScaled.emplace_back( offsets[i].width(), offsets[i].height(), @@ -89,7 +89,7 @@ void MonitorBox::paintEvent(QPaintEvent*) { // // Draw window out-of-bounds region(s) first - for (int i = 0; i < _nWindows; ++i) { + for (int i = 0; i < _nWindows; i++) { painter.setBrush(Qt::BDiagPattern); painter.setPen(QPen(_colorsForWindows[i], 0)); painter.drawRect(_windowRendering[i]); @@ -99,7 +99,7 @@ void MonitorBox::paintEvent(QPaintEvent*) { painter.setPen(QPen(Qt::black, 2)); painter.setBrush(Qt::NoBrush); - for (size_t i = 0; i < _monitorDimensionsScaled.size(); ++i) { + for (size_t i = 0; i < _monitorDimensionsScaled.size(); i++) { const QColor Grey = QColor(0xDD, 0xDD, 0xDD); painter.drawRect(_monitorDimensionsScaled[i]); @@ -107,7 +107,7 @@ void MonitorBox::paintEvent(QPaintEvent*) { if (_monitorDimensionsScaled.size() > 1 && i == 0) { // We only want to render the "Primary" if there are multiple windows - QPointF textPos = QPointF( + const QPointF textPos = QPointF( _monitorDimensionsScaled[i].left() + 4.0, _monitorDimensionsScaled[i].top() + 24.0 ); @@ -120,7 +120,7 @@ void MonitorBox::paintEvent(QPaintEvent*) { // Draw window number(s) first for darker contrast, then window(s) over both // out-of-bounds and monitors - for (int i = 0; i < _nWindows; ++i) { + for (int i = 0; i < _nWindows; i++) { QPointF p = QPointF( _windowRendering[i].left() + 5.0, _windowRendering[i].bottom() - 5.0 @@ -132,7 +132,7 @@ void MonitorBox::paintEvent(QPaintEvent*) { // // Paint window - for (int i = 0; i < _nWindows; ++i) { + for (int i = 0; i < _nWindows; i++) { painter.setPen(QPen(_colorsForWindows[i], 1)); painter.drawRect(_windowRendering[i]); @@ -159,16 +159,16 @@ std::vector MonitorBox::computeScaledResolutionLandscape(QRectF arrangem { std::vector offsets; - float marginWidget = size().width() * MarginFractionOfWidgetSize; - float virtualWidth = size().width() * (1.f - MarginFractionOfWidgetSize * 2.f); + const float margin = size().width() * MarginFractionWidgetSize; + const float virtualWidth = size().width() * (1.f - MarginFractionWidgetSize * 2.f); _monitorScaleFactor = virtualWidth / arrangement.width(); const float aspectRatio = arrangement.width() / arrangement.height(); const float newHeight = virtualWidth / aspectRatio; for (const QRect& res : resolutions) { - float x = marginWidget + (res.x() - arrangement.x()) * _monitorScaleFactor; - float y = marginWidget + (size().height() - newHeight - marginWidget) / 4.f + + const float x = margin + (res.x() - arrangement.x()) * _monitorScaleFactor; + const float y = margin + (size().height() - newHeight - margin) / 4.f + (res.y() - arrangement.y()) * _monitorScaleFactor; offsets.emplace_back(x, y); } @@ -181,17 +181,17 @@ std::vector MonitorBox::computeScaledResolutionPortrait(QRectF arrangeme { std::vector offsets; - float marginWidget = size().height() * MarginFractionOfWidgetSize; - float virtualHeight = size().height() * (1.f - MarginFractionOfWidgetSize * 2.f); + const float marginWidget = size().height() * MarginFractionWidgetSize; + const float virtualHeight = size().height() * (1.f - MarginFractionWidgetSize * 2.f); _monitorScaleFactor = virtualHeight / arrangement.height(); const float aspectRatio = arrangement.width() / arrangement.height(); const float newWidth = virtualHeight * aspectRatio; for (const QRect& res : resolutions) { - float x = marginWidget + (size().width() - newWidth - marginWidget) / 4.f + + const float x = marginWidget + (size().width() - newWidth - marginWidget) / 4.f + (res.x() - arrangement.x()) * _monitorScaleFactor; - float y = marginWidget + (res.y() - arrangement.y()) * _monitorScaleFactor; + const float y = marginWidget + (res.y() - arrangement.y()) * _monitorScaleFactor; offsets.emplace_back(x, y); } diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/orientationdialog.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/orientationdialog.cpp index de2099e26e..d310b51431 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/orientationdialog.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/orientationdialog.cpp @@ -39,7 +39,7 @@ OrientationDialog::OrientationDialog(sgct::quat& orientation, QWidget* parent) QGridLayout* layoutWindow = new QGridLayout(this); { - QString pitchTip = "Pitch or elevation: negative numbers tilt the camera " + const QString pitchTip = "Pitch or elevation: negative numbers tilt the camera " "downwards; positive numbers tilt upwards.\nThe allowed range is [-90, 90]. " "Internally, this corresponds to the x value in the quaternion"; @@ -56,9 +56,9 @@ OrientationDialog::OrientationDialog(sgct::quat& orientation, QWidget* parent) layoutWindow->addWidget(_linePitch, 0, 1); } { - QString rollTip = "Roll or bank: negative numbers rotate the camera counter-" - "clockwise; positive numbers clockwise.\nThe allowed range is [-180, 180]. " - "Internally, this corresponds to the z value in the quaternion"; + const QString rollTip = "Roll or bank: negative numbers rotate the camera " + "counter-clockwise; positive numbers clockwise.\nThe allowed range is " + "[-180, 180]. Internally, this corresponds to the z value in the quaternion"; QLabel* labelRoll = new QLabel("Roll"); labelRoll->setToolTip(rollTip); @@ -73,9 +73,10 @@ OrientationDialog::OrientationDialog(sgct::quat& orientation, QWidget* parent) layoutWindow->addWidget(_lineRoll, 1, 1); } { - QString yawTip = "Yaw, heading, or azimuth: negative numbers pan the camera " - "to the left; positive numbers pan to the\nright. The allowed range is " - "[-360, 360]. Internally, this corresponds to the y value in the quaternion"; + const QString yawTip = "Yaw, heading, or azimuth: negative numbers pan the " + "camera to the left; positive numbers pan to the\nright. The allowed range " + "is [-360, 360]. Internally, this corresponds to the y value in the " + "quaternion"; QLabel* labelYaw = new QLabel; labelYaw ->setText("Yaw"); diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/settingswidget.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/settingswidget.cpp index dc4df89f46..7244a7d961 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/settingswidget.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/settingswidget.cpp @@ -32,13 +32,15 @@ SettingsWidget::SettingsWidget(sgct::quat orientation, QWidget* parent) : QWidget(parent) , _orientationValue(std::move(orientation)) + , _firstWindowGraphicsSelection(new QComboBox) + , _firstWindowSelectionLayout(new QHBoxLayout) + ,_showUiOnFirstWindow(new QCheckBox( + "Show user interface only on first window using graphics:" + )) { QBoxLayout* layout = new QVBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); - _showUiOnFirstWindow = new QCheckBox( - "Show user interface only on first window using graphics:" - ); _showUiOnFirstWindow->setChecked(false); _showUiOnFirstWindow->setEnabled(false); _showUiOnFirstWindow->setToolTip( @@ -48,9 +50,6 @@ SettingsWidget::SettingsWidget(sgct::quat orientation, QWidget* parent) "not show the user interface" ); - _firstWindowSelectionLayout = new QHBoxLayout; - - _firstWindowGraphicsSelection = new QComboBox(); _firstWindowGraphicsSelection->setToolTip( "Select the contents of the first window to match one of the other windows" ); @@ -127,7 +126,7 @@ void SettingsWidget::nWindowsDisplayedChanged(int newCount) { graphicsSelect = std::max(0, graphicsSelect); QList graphicsOptions = {"None (GUI only)"}; - for (int i = CountOneWindow; i <= newCount; ++i) { + for (int i = CountOneWindow; i <= newCount; i++) { graphicsOptions.append("Window " + QString::number(i)); } _firstWindowGraphicsSelection->clear(); diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/sgctedit.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/sgctedit.cpp index 77a5d2db65..0adde4e76c 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/sgctedit.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/sgctedit.cpp @@ -78,20 +78,20 @@ SgctEdit::SgctEdit(QWidget* parent, std::string userConfigPath) createWidgets(createMonitorInfoSet(), 1, true); } -SgctEdit::SgctEdit(sgct::config::Cluster& cluster, const std::string& configName, +SgctEdit::SgctEdit(sgct::config::Cluster& cluster, std::string configName, std::string& configBasePath, QWidget* parent) : QDialog(parent) , _cluster(cluster) , _userConfigPath(configBasePath) - , _configurationFilename(configName) + , _configurationFilename(std::move(configName)) , _didImportValues(true) { setWindowTitle("Window Configuration Editor"); - size_t nWindows = _cluster.nodes.front().windows.size(); + const size_t nWindows = _cluster.nodes.front().windows.size(); std::vector monitorSizes = createMonitorInfoSet(); createWidgets(monitorSizes, static_cast(nWindows), false); - size_t existingWindowsControlSize = _displayWidget->windowControls().size(); - for (size_t i = 0; i < nWindows; ++i) { + const size_t existingWindowsControlSize = _displayWidget->windowControls().size(); + for (size_t i = 0; i < nWindows; i++) { sgct::config::Window& w = _cluster.nodes.front().windows[i]; WindowControl* wCtrl = _displayWidget->windowControls()[i]; if (i < existingWindowsControlSize && wCtrl) { @@ -116,12 +116,7 @@ SgctEdit::SgctEdit(sgct::config::Cluster& cluster, const std::string& configName posY -= monitorSizes[monitorNum].y(); } } - QRectF newDims( - posX, - posY, - w.size.x, - w.size.y - ); + const QRectF newDims = QRectF(posX, posY, w.size.x, w.size.y); wCtrl->setDimensions(newDims); if (w.name.has_value()) { wCtrl->setWindowName(w.name.value()); @@ -144,7 +139,7 @@ void SgctEdit::setupStateOfUiOnFirstWindow(size_t nWindows) { int nGuiRenderTagsFound = 0; _settingsWidget->nWindowsDisplayedChanged(static_cast(nWindows)); - for (size_t i = 0; i < nWindows; ++i) { + for (size_t i = 0; i < nWindows; i++) { sgct::config::Window& w = _cluster.nodes.front().windows[i]; //First window needs to have "GUI" tag if this mode is set if (i == 0) { @@ -156,9 +151,8 @@ void SgctEdit::setupStateOfUiOnFirstWindow(size_t nWindows) { nGuiRenderTagsFound++; } for (int winNum = 0; winNum <= 4; ++winNum) { - std::string tagToLookFor = "GUI_Render_Win" + std::to_string(winNum); - if (std::find(w.tags.begin(), w.tags.end(), tagToLookFor) != w.tags.end()) - { + const std::string searchTag = "GUI_Render_Win" + std::to_string(winNum); + if (std::find(w.tags.begin(), w.tags.end(), searchTag) != w.tags.end()) { graphicsSelectionForFirstWindow = winNum; nGuiRenderTagsFound++; } @@ -195,8 +189,8 @@ void SgctEdit::setupStateOfUiOnFirstWindow(size_t nWindows) { void SgctEdit::setupProjectionTypeInGui(sgct::config::Viewport& vPort, WindowControl* wCtrl) { - std::visit(overloaded{ - [&](sgct::config::CylindricalProjection p) { + std::visit(overloaded { + [&](const sgct::config::CylindricalProjection& p) { if (p.quality && p.heightOffset) { wCtrl->setProjectionCylindrical( *p.quality, @@ -204,7 +198,7 @@ void SgctEdit::setupProjectionTypeInGui(sgct::config::Viewport& vPort, ); } }, - [&](sgct::config::EquirectangularProjection p) { + [&](const sgct::config::EquirectangularProjection& p) { if (p.quality) { wCtrl->setProjectionEquirectangular( *p.quality, @@ -212,7 +206,7 @@ void SgctEdit::setupProjectionTypeInGui(sgct::config::Viewport& vPort, ); } }, - [&](sgct::config::FisheyeProjection p) { + [&](const sgct::config::FisheyeProjection& p) { if (p.quality) { wCtrl->setProjectionFisheye( *p.quality, @@ -220,20 +214,20 @@ void SgctEdit::setupProjectionTypeInGui(sgct::config::Viewport& vPort, ); } }, - [&](sgct::config::PlanarProjection p) { + [&](const sgct::config::PlanarProjection& p) { wCtrl->setProjectionPlanar( (std::abs(p.fov.left) + std::abs(p.fov.right)), (std::abs(p.fov.up) + std::abs(p.fov.down)) ); }, - [&](sgct::config::SphericalMirrorProjection p) { + [&](const sgct::config::SphericalMirrorProjection& p) { if (p.quality) { wCtrl->setProjectionSphericalMirror( *p.quality ); } }, - [&](sgct::config::SpoutOutputProjection p) { + [&](const sgct::config::SpoutOutputProjection& p) { if (p.quality) { if (p.mapping == sgct::config::SpoutOutputProjection::Mapping::Equirectangular) @@ -253,21 +247,21 @@ void SgctEdit::setupProjectionTypeInGui(sgct::config::Viewport& vPort, } } }, - [&](sgct::config::NoProjection) {}, - [&](sgct::config::ProjectionPlane) {}, - [&](sgct::config::SpoutFlatProjection) {} + [&](const sgct::config::NoProjection&) {}, + [&](const sgct::config::ProjectionPlane&) {}, + [&](const sgct::config::SpoutFlatProjection&) {} }, vPort.projection); } std::vector SgctEdit::createMonitorInfoSet() { - QList screens = qApp->screens(); - int nScreensManaged = std::min(static_cast(screens.length()), 4); + const QList screens = qApp->screens(); + const int nScreensManaged = std::min(static_cast(screens.length()), 4); std::vector monitorSizes; for (int s = 0; s < nScreensManaged; ++s) { - QSize size = screens[s]->size(); - QRect geometry = screens[s]->availableGeometry(); - int actualWidth = std::max(size.width(), geometry.width()); - int actualHeight = std::max(size.height(), geometry.height()); + const QSize size = screens[s]->size(); + const QRect geometry = screens[s]->availableGeometry(); + const int actualWidth = std::max(size.width(), geometry.width()); + const int actualHeight = std::max(size.height(), geometry.height()); monitorSizes.emplace_back( geometry.x(), geometry.y(), @@ -318,7 +312,7 @@ void SgctEdit::createWidgets(const std::vector& monitorSizes, monitorBox, &MonitorBox::nWindowsDisplayedChanged ); - for (unsigned int i = 0; i < nWindows; ++i) { + for (unsigned int i = 0; i < nWindows; i++) { _displayWidget->addWindow(); } @@ -394,7 +388,7 @@ std::filesystem::path SgctEdit::saveFilename() const { void SgctEdit::save() { generateConfiguration(); if (hasWindowIssues(_cluster)) { - int ret = QMessageBox::warning( + const int ret = QMessageBox::warning( this, "Window Sizes Incompatible", "Window sizes for multiple windows have to be strictly ordered, meaning that " @@ -414,7 +408,7 @@ void SgctEdit::save() { accept(); } else { - QString fileName = QFileDialog::getSaveFileName( + const QString fileName = QFileDialog::getSaveFileName( this, "Save Window Configuration File", QString::fromStdString(_userConfigPath), @@ -435,7 +429,7 @@ void SgctEdit::save() { void SgctEdit::apply() { generateConfiguration(); if (hasWindowIssues(_cluster)) { - int ret = QMessageBox::warning( + const int ret = QMessageBox::warning( this, "Window Sizes Incompatible", "Window sizes for multiple windows have to be strictly ordered, meaning that " @@ -466,7 +460,7 @@ void SgctEdit::generateConfiguration() { _cluster.scene = sgct::config::Scene(); _cluster.scene->orientation = _settingsWidget->orientation(); if (_cluster.nodes.empty()) { - _cluster.nodes.push_back(sgct::config::Node()); + _cluster.nodes.emplace_back(); } sgct::config::Node& node = _cluster.nodes.back(); @@ -515,12 +509,10 @@ void SgctEdit::generateConfigResizeWindowsAccordingToSelected(sgct::config::Node std::vector windowControls = _displayWidget->activeWindowControls(); for (size_t wIdx = 0; wIdx < windowControls.size(); ++wIdx) { if (node.windows.size() <= wIdx) { - node.windows.push_back(sgct::config::Window()); + node.windows.emplace_back(); } if (windowControls[wIdx]) { - windowControls[wIdx]->generateWindowInformation( - node.windows[wIdx] - ); + windowControls[wIdx]->generateWindowInformation(node.windows[wIdx]); } } while (node.windows.size() > windowControls.size()) { @@ -529,7 +521,7 @@ void SgctEdit::generateConfigResizeWindowsAccordingToSelected(sgct::config::Node } void SgctEdit::generateConfigIndividualWindowSettings(sgct::config::Node& node) { - for (size_t i = 0; i < node.windows.size(); ++i) { + for (size_t i = 0; i < node.windows.size(); i++) { // First apply default settings to each window... node.windows[i].id = static_cast(i); node.windows[i].draw2D = true; @@ -540,20 +532,21 @@ void SgctEdit::generateConfigIndividualWindowSettings(sgct::config::Node& node) // depending on if this is the first window or not if (_settingsWidget->showUiOnFirstWindow()) { if (i == 0) { - node.windows[i].tags.push_back("GUI"); - int selectedGraphics = + node.windows[i].tags.emplace_back("GUI"); + const int selectedGraphics = _settingsWidget->graphicsSelectionForShowUiOnFirstWindow(); if (selectedGraphics == 0) { node.windows[i].viewports.back().isTracked = false; - node.windows[i].tags.push_back("GUI_No_Render"); + node.windows[i].tags.emplace_back("GUI_No_Render"); } else if (selectedGraphics > 0 && selectedGraphics <= static_cast(node.windows.size())) { - node.windows[i].tags.push_back("GUI_Render_Win" + - std::to_string(selectedGraphics)); - //Set first window viewport to mirror the selected window's viewport + node.windows[i].tags.emplace_back( + "GUI_Render_Win" + std::to_string(selectedGraphics) + ); + // Set first window viewport to mirror the selected window's viewport node.windows[i].viewports = node.windows[(selectedGraphics - 1)].viewports; } @@ -577,7 +570,7 @@ void SgctEdit::deleteFromTags(sgct::config::Window& window) { "GUI_Render_Win3", "GUI_Render_Win4" }; - for (std::string_view tag : Tags) { + for (const std::string_view tag : Tags) { window.tags.erase( std::remove(window.tags.begin(), window.tags.end(), tag), window.tags.end() @@ -590,12 +583,12 @@ sgct::config::Cluster SgctEdit::cluster() const { } void SgctEdit::firstWindowGraphicsSelectionChanged(const QString&) { - if (!_settingsWidget) + if (!_settingsWidget) { return; - - int newSetting = _settingsWidget->graphicsSelectionForShowUiOnFirstWindow(); + } if (_settingsWidget->showUiOnFirstWindow()) { + const int newSetting = _settingsWidget->graphicsSelectionForShowUiOnFirstWindow(); _displayWidget->activeWindowControls()[0]->setVisibilityOfProjectionGui( newSetting == 1 ); diff --git a/apps/OpenSpace/ext/launcher/src/sgctedit/windowcontrol.cpp b/apps/OpenSpace/ext/launcher/src/sgctedit/windowcontrol.cpp index 1bf757a41c..40500298f0 100644 --- a/apps/OpenSpace/ext/launcher/src/sgctedit/windowcontrol.cpp +++ b/apps/OpenSpace/ext/launcher/src/sgctedit/windowcontrol.cpp @@ -50,7 +50,7 @@ namespace { "8K (8192)", "16K (16384)", "32K (32768)", "64K (65536)" }; - constexpr int QualityValues[nQualityTypes] = { + constexpr std::array QualityValues = { 256, 512, 1024, 1536, 2048, 4096, 8192, 16384, 32768, 65536 }; @@ -76,7 +76,7 @@ namespace { QList monitorNames(const std::vector& resolutions) { QList monitorNames; for (size_t i = 0; i < resolutions.size(); i++) { - std::string fullName = fmt::format( + const std::string fullName = std::format( "{} ({}x{})", MonitorNames[i], resolutions[i].width(), resolutions[i].height() ); @@ -116,19 +116,19 @@ void WindowControl::createWidgets(const QColor& windowColor) { // *----------*----------*-------*----------*-------*--------*-------*-------* QGridLayout* layout = new QGridLayout(this); - QMargins margins = layout->contentsMargins(); + const QMargins margins = layout->contentsMargins(); layout->setContentsMargins(margins.left(), 0, margins.right(), 0); layout->setColumnStretch(6, 1); layout->setRowStretch(8, 1); _windowNumber = new QLabel("Window " + QString::number(_windowIndex + 1)); - _windowNumber->setStyleSheet(QString::fromStdString(fmt::format( + _windowNumber->setStyleSheet(QString::fromStdString(std::format( "QLabel {{ color : #{:02x}{:02x}{:02x}; }}", windowColor.red(), windowColor.green(), windowColor.blue() ))); layout->addWidget(_windowNumber, 0, 0, 1, 8, Qt::AlignCenter); { - QString tip = "The name for the window (displayed in title bar)"; + const QString tip = "The name for the window (displayed in title bar)"; QLabel* labelName = new QLabel("Name"); labelName->setToolTip(tip); @@ -138,7 +138,7 @@ void WindowControl::createWidgets(const QColor& windowColor) { _windowName->setToolTip(tip); layout->addWidget(_windowName, 1, 1, 1, 7); } - QString tip = "The monitor where this window is located"; + const QString tip = "The monitor where this window is located"; _monitor = new QComboBox; _monitor->addItems(monitorNames(_monitorResolutions)); @@ -370,7 +370,8 @@ QWidget* WindowControl::createPlanarWidget() { layout->addWidget(_planar.labelInfo, 0, 0, 1, 3); _planar.labelFovH = new QLabel("Horizontal FOV"); - QString hfovTip = "The total horizontal field of view of the viewport (degrees)"; + const QString hfovTip = + "The total horizontal field of view of the viewport (degrees)"; _planar.labelFovH->setToolTip(hfovTip); layout->addWidget(_planar.labelFovH, 1, 0); @@ -387,7 +388,7 @@ QWidget* WindowControl::createPlanarWidget() { layout->addWidget(_planar.fovH, 1, 1); _planar.labelFovV = new QLabel("Vertical FOV"); - QString vfovTip = "The total vertical field of view of the viewport (degrees). " + const QString vfovTip = "The total vertical field of view of the viewport (degrees). " "Internally,\nthe values for 'up' & 'down' will each be half this value"; _planar.labelFovV->setToolTip(vfovTip); layout->addWidget(_planar.labelFovV, 2, 0); @@ -445,9 +446,9 @@ QWidget* WindowControl::createFisheyeWidget() { layout->addWidget(_fisheye.labelInfo, 0, 0, 1, 2); _fisheye.labelQuality = new QLabel("Quality"); - QString qualityTip = "Determines the pixel resolution of the projection rendering. " - "The higher resolution,\nthe better the rendering quality, but at the expense of " - "increased rendering times"; + const QString qualityTip = "Determines the pixel resolution of the projection " + "rendering. The higher resolution,\nthe better the rendering quality, but at the " + "expense of increased rendering times"; _fisheye.labelQuality->setToolTip(qualityTip); layout->addWidget(_fisheye.labelQuality, 1, 0); @@ -490,9 +491,9 @@ QWidget* WindowControl::createSphericalMirrorWidget() { layout->addWidget(_sphericalMirror.labelInfo, 0, 0, 1, 2); _sphericalMirror.labelQuality = new QLabel("Quality"); - QString qualityTip = "Determines the pixel resolution of the projection rendering. " - "The higher resolution,\nthe better the rendering quality, but at the expense of " - "increased rendering times"; + const QString qualityTip = "Determines the pixel resolution of the projection " + "rendering. The higher resolution,\nthe better the rendering quality, but at the " + "expense of increased rendering times"; _sphericalMirror.labelQuality->setToolTip(qualityTip); layout->addWidget(_sphericalMirror.labelQuality, 1, 0); @@ -527,9 +528,9 @@ QWidget* WindowControl::createCylindricalWidget() { layout->addWidget(_cylindrical.labelInfo, 0, 0, 1, 2); _cylindrical.labelQuality = new QLabel("Quality"); - QString qualityTip = "Determines the pixel resolution of the projection rendering. " - "The higher resolution,\nthe better the rendering quality, but at the expense of " - "increased rendering times"; + const QString qualityTip = "Determines the pixel resolution of the projection " + "rendering. The higher resolution,\nthe better the rendering quality, but at the " + "expense of increased rendering times"; _cylindrical.labelQuality->setToolTip(qualityTip); layout->addWidget(_cylindrical.labelQuality, 1, 0); @@ -540,10 +541,10 @@ QWidget* WindowControl::createCylindricalWidget() { layout->addWidget(_cylindrical.quality, 1, 1); _cylindrical.labelHeightOffset = new QLabel("Height Offset"); - QString heightTip = "Offsets the height from which the cylindrical projection is " - "generated.\nThis is, in general, only necessary if the user position is offset " - "and\ncountering that offset is desired in order to continue producing\na " - "'standard' cylindrical projection"; + const QString heightTip = "Offsets the height from which the cylindrical projection " + "is generated.\nThis is, in general, only necessary if the user position is " + "offset and\ncountering that offset is desired in order to continue producing\n" + "a 'standard' cylindrical projection"; _cylindrical.labelHeightOffset->setToolTip(heightTip); layout->addWidget(_cylindrical.labelHeightOffset, 2, 0); @@ -580,9 +581,9 @@ QWidget* WindowControl::createEquirectangularWidget() { layout->addWidget(_equirectangular.labelInfo, 0, 0, 1, 2); _equirectangular.labelQuality = new QLabel("Quality"); - QString qualityTip = "Determines the pixel resolution of the projection rendering. " - "The higher resolution,\nthe better the rendering quality, but at the expense of " - "increased rendering times"; + const QString qualityTip = "Determines the pixel resolution of the projection " + "rendering. The higher resolution,\nthe better the rendering quality, but at the " + "expense of increased rendering times"; _equirectangular.labelQuality->setToolTip(qualityTip); layout->addWidget(_equirectangular.labelQuality, 1, 0); @@ -613,9 +614,9 @@ void WindowControl::resetToDefaults() { _windowDimensions = DefaultWindowSizes[_windowIndex]; _offsetX->setValue(_windowDimensions.x()); _offsetY->setValue(_windowDimensions.y()); - float newHeight = + const float newHeight = _monitorResolutions[PrimaryMonitorIdx].height() * IdealScaleVerticalLines; - float newWidth = newHeight * IdealAspectRatio; + const float newWidth = newHeight * IdealAspectRatio; _windowDimensions.setHeight(newHeight); _windowDimensions.setWidth(newWidth); _sizeX->setValue(static_cast(newWidth)); @@ -666,7 +667,7 @@ void WindowControl::setDecorationState(bool hasWindowDecoration) { } sgct::config::Projections WindowControl::generateProjectionInformation() const { - ProjectionIndices type = + const ProjectionIndices type = static_cast(_projectionType->currentIndex()); const bool isSpoutFisheye = @@ -745,7 +746,7 @@ sgct::config::Projections WindowControl::generateProjectionInformation() const { void WindowControl::generateWindowInformation(sgct::config::Window& window) const { window.size = { _sizeX->text().toInt(), _sizeY->text().toInt() }; window.monitor = _monitor->currentIndex(); - QRect resolution = _monitorResolutions[_monitor->currentIndex()]; + const QRect resolution = _monitorResolutions[_monitor->currentIndex()]; window.pos = sgct::ivec2( resolution.x() + _offsetX->text().toInt(), resolution.y() + _offsetY->text().toInt() @@ -839,7 +840,7 @@ void WindowControl::setQualityComboBoxFromLinesResolution(int lines, QComboBox* void WindowControl::onSizeXChanged(int newValue) { _windowDimensions.setWidth(newValue); if (_aspectRatioLocked) { - int updatedHeight = _windowDimensions.width() / _aspectRatioSize; + const int updatedHeight = _windowDimensions.width() / _aspectRatioSize; _sizeY->blockSignals(true); _sizeY->setValue(updatedHeight); _sizeY->blockSignals(false); @@ -854,7 +855,7 @@ void WindowControl::onSizeXChanged(int newValue) { void WindowControl::onSizeYChanged(int newValue) { _windowDimensions.setHeight(newValue); if (_aspectRatioLocked) { - int updatedWidth = _windowDimensions.height() * _aspectRatioSize; + const int updatedWidth = _windowDimensions.height() * _aspectRatioSize; _sizeX->blockSignals(true); _sizeX->setValue(updatedWidth); _sizeX->blockSignals(false); @@ -867,21 +868,21 @@ void WindowControl::onSizeYChanged(int newValue) { } void WindowControl::onOffsetXChanged(int newValue) { - float prevWidth = _windowDimensions.width(); + const float prevWidth = _windowDimensions.width(); _windowDimensions.setX(newValue); _windowDimensions.setWidth(prevWidth); emit windowChanged(_monitor->currentIndex(), _windowIndex, _windowDimensions); } void WindowControl::onOffsetYChanged(int newValue) { - float prevHeight = _windowDimensions.height(); + const float prevHeight = _windowDimensions.height(); _windowDimensions.setY(newValue); _windowDimensions.setHeight(prevHeight); emit windowChanged(_monitor->currentIndex(), _windowIndex, _windowDimensions); } void WindowControl::onFullscreenClicked() { - QRect resolution = _monitorResolutions[_monitor->currentIndex()]; + const QRect resolution = _monitorResolutions[_monitor->currentIndex()]; _offsetX->setValue(0); _offsetY->setValue(0); @@ -890,8 +891,8 @@ void WindowControl::onFullscreenClicked() { _windowDecoration->setChecked(false); } -void WindowControl::onProjectionChanged(int newSelection) { - ProjectionIndices selected = static_cast(newSelection); +void WindowControl::onProjectionChanged(int newSelection) const { + const ProjectionIndices selected = static_cast(newSelection); _planar.widget->setVisible(selected == ProjectionIndices::Planar); _fisheye.widget->setVisible(selected == ProjectionIndices::Fisheye); _sphericalMirror.widget->setVisible(selected == ProjectionIndices::SphericalMirror); @@ -921,8 +922,9 @@ void WindowControl::onFovLockClicked() { } void WindowControl::updatePlanarLockedFov() { - bool landscapeOrientation = (_windowDimensions.width() >= _windowDimensions.height()); - float aspectRatio; + const bool landscapeOrientation = + (_windowDimensions.width() >= _windowDimensions.height()); + float aspectRatio = 0.f; if (landscapeOrientation) { aspectRatio = _windowDimensions.width() / _windowDimensions.height(); } @@ -930,7 +932,7 @@ void WindowControl::updatePlanarLockedFov() { aspectRatio = _windowDimensions.height() / _windowDimensions.width(); } - float adjustedFov = 2.f * atan(aspectRatio * tan(DefaultFovShortEdge + float adjustedFov = 2.f * std::atan(aspectRatio * std::tan(DefaultFovShortEdge * std::numbers::pi_v / 180.f / 2.f)); // Convert to degrees and limit to 180° adjustedFov *= 180.f / std::numbers::pi_v; diff --git a/apps/OpenSpace/ext/sgct b/apps/OpenSpace/ext/sgct index 377de30963..9bcd52ac18 160000 --- a/apps/OpenSpace/ext/sgct +++ b/apps/OpenSpace/ext/sgct @@ -1 +1 @@ -Subproject commit 377de309631d8a1c9b53becd363db0dc8ee76ae6 +Subproject commit 9bcd52ac187bc6ecff7af069b106d07dfc22a9be diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index 6c5d6a5cf3..7bcbbcbaa9 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -140,7 +140,7 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { LINFO(s); } - std::string dumpFile = fmt::format( + std::string dumpFile = std::format( "OpenSpace_{}_{}_{}-{}-{}-{}-{}-{}-{}--{}--{}.dmp", OPENSPACE_VERSION_MAJOR, OPENSPACE_VERSION_MINOR, @@ -155,7 +155,7 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { GetCurrentThreadId() ); - LINFO(fmt::format("Creating dump file: {}", dumpFile)); + LINFO(std::format("Creating dump file: {}", dumpFile)); HANDLE hDumpFile = CreateFileA( dumpFile.c_str(), @@ -198,12 +198,12 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { void checkJoystickStatus() { using namespace interaction; - for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; ++i) { + for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_LAST; i++) { ZoneScopedN("Joystick state"); JoystickInputState& state = global::joystickInputStates->at(i); - int present = glfwJoystickPresent(i); + const int present = glfwJoystickPresent(i); if (present == GLFW_FALSE) { state.isConnected = false; continue; @@ -228,7 +228,7 @@ void checkJoystickStatus() { std::memcpy(state.axes.data(), axes, state.nAxes * sizeof(float)); const unsigned char* buttons = glfwGetJoystickButtons(i, &state.nButtons); - for (int j = 0; j < state.nButtons; ++j) { + for (int j = 0; j < state.nButtons; j++) { const bool currentlyPressed = buttons[j] == GLFW_PRESS; if (currentlyPressed) { @@ -282,8 +282,8 @@ void mainInitFunc(GLFWwindow*) { // We save the startup value of the screenshots just in case we want to add a date // to them later in the RenderEngine std::filesystem::path screenshotPath = absPath("${SCREENSHOTS}"); - FileSys.registerPathToken("${STARTUP_SCREENSHOT}", screenshotPath); sgct::Settings::instance().setCapturePath(screenshotPath.string()); + FileSys.registerPathToken("${STARTUP_SCREENSHOT}", std::move(screenshotPath)); LDEBUG("Initializing OpenSpace Engine started"); global::openSpaceEngine->initialize(); @@ -292,22 +292,22 @@ void mainInitFunc(GLFWwindow*) { #ifndef __APPLE__ // Apparently: "Cocoa: Regular windows do not have icons on macOS" { - std::filesystem::path path = absPath("${DATA}/openspace-icon.png"); - int x; - int y; - int n; + const std::filesystem::path path = absPath("${DATA}/openspace-icon.png"); + int x = 0; + int y = 0; + int n = 0; unsigned char* data = stbi_load(path.string().c_str(), &x, &y, &n, 0); - GLFWimage icons[1]; - icons[0].pixels = data; - icons[0].width = x; - icons[0].height = y; + GLFWimage icon; + icon.pixels = data; + icon.width = x; + icon.height = y; for (const std::unique_ptr& window : Engine::instance().windows()) { - glfwSetWindowIcon(window->windowHandle(), 1, icons); + glfwSetWindowIcon(window->windowHandle(), 1, &icon); } - stbi_image_free(icons[0].pixels); + stbi_image_free(icon.pixels); } #endif // __APPLE__ @@ -340,8 +340,8 @@ void mainInitFunc(GLFWwindow*) { } } - for (size_t i = 0; i < Engine::instance().windows().size(); ++i) { - Window& window = *Engine::instance().windows()[i]; + for (size_t i = 0; i < Engine::instance().windows().size(); i++) { + const Window& window = *Engine::instance().windows()[i]; if (!window.hasTag(SpoutTag)) { continue; } @@ -438,11 +438,7 @@ void mainRenderFunc(const sgct::RenderData& data) { currentDrawResolution = glm::ivec2(data.bufferSize.x, data.bufferSize.y); glm::vec3 pos; - std::memcpy( - glm::value_ptr(pos), - &Engine::instance().defaultUser().posMono().x, - sizeof(vec3) - ); + std::memcpy(glm::value_ptr(pos), &Engine::defaultUser().posMono().x, sizeof(vec3)); glm::mat4 viewMatrix; std::memcpy( @@ -620,14 +616,11 @@ void mainCharCallback(unsigned int codepoint, int modifiers, sgct::Window* windo -void mainDropCallback(int amount, const char** paths) { +void mainDropCallback(const std::vector& paths) { ZoneScoped; - ghoul_assert(amount > 0, "Expected at least one file path"); - ghoul_assert(paths, "expected non-nullptr"); - - for (int i = 0; i < amount; ++i) { - global::openSpaceEngine->handleDragDrop(paths[i]); + for (const std::string_view path : paths) { + global::openSpaceEngine->handleDragDrop(path); } } @@ -753,11 +746,11 @@ void setSgctDelegateFunctions() { const Viewport* viewport = dynamic_cast(currentViewport); if (viewport) { if (viewport->hasSubViewports() && viewport->nonLinearProjection()) { - ivec2 dim = viewport->nonLinearProjection()->cubemapResolution(); + const ivec2 dim = viewport->nonLinearProjection()->cubemapResolution(); return glm::ivec2(dim.x, dim.y); } else { - ivec2 dim = currentWindow->finalFBODimensions(); + const ivec2 dim = currentWindow->finalFBODimensions(); return glm::ivec2(dim.x, dim.y); } } @@ -768,8 +761,8 @@ void setSgctDelegateFunctions() { sgctDelegate.currentViewportSize = []() { ZoneScoped; - if (currentViewport != nullptr) { - vec2 size = currentViewport->size(); + if (currentViewport) { + const vec2 size = currentViewport->size(); return glm::ivec2(size.x, size.y); } return glm::ivec2(-1, -1); @@ -777,9 +770,9 @@ void setSgctDelegateFunctions() { sgctDelegate.currentViewportResolution = []() { ZoneScoped; - if (currentViewport != nullptr) { - ivec2 res = currentWindow->resolution(); - vec2 size = currentViewport->size(); + if (currentViewport) { + const ivec2 res = currentWindow->resolution(); + const vec2 size = currentViewport->size(); return glm::ivec2(size.x * res.x, size.y * res.y); } return glm::ivec2(-1, -1); @@ -787,7 +780,7 @@ void setSgctDelegateFunctions() { sgctDelegate.dpiScaling = []() { ZoneScoped; - vec2 scale = currentWindow->scale(); + const vec2 scale = currentWindow->scale(); return glm::vec2(scale.x, scale.y); }; sgctDelegate.firstWindowResolution = []() { @@ -833,7 +826,7 @@ void setSgctDelegateFunctions() { glfwGetWindowContentScale(dpiWindow->windowHandle(), &scale.x, &scale.y); if (scale.x != scale.y) { - LWARNING(fmt::format( + LWARNING(std::format( "Non-square window scaling detected ({0}x{1}), using {0}x{0} instead", scale.x, scale.y )); @@ -954,10 +947,9 @@ void setSgctDelegateFunctions() { }; sgctDelegate.swapGroupFrameNumber = []() -> uint64_t { ZoneScoped; - - return currentWindow->swapGroupFrameNumber(); + return sgct::Window::swapGroupFrameNumber(); }; - sgctDelegate.setScreenshotFolder = [](std::string path) { + sgctDelegate.setScreenshotFolder = [](std::filesystem::path path) { sgct::Settings::instance().setCapturePath(std::move(path)); }; sgctDelegate.showStatistics = [](bool enabled) { @@ -969,29 +961,30 @@ void setSgctDelegateFunctions() { sgctDelegate.currentNode = []() { return ClusterManager::instance().thisNodeId(); }; - sgctDelegate.mousePositionViewportRelative = [](glm::vec2 mousePosition) { + sgctDelegate.mousePositionViewportRelative = [](const glm::vec2& mousePosition) { for (const std::unique_ptr& window : Engine::instance().windows()) { - if (isGuiWindow(window.get())) { - sgct::ivec2 res = window->resolution(); - for (const std::unique_ptr& viewport : window->viewports()) { - sgct::vec2 pos = viewport->position(); - sgct::vec2 size = viewport->size(); - glm::vec4 bounds = glm::vec4( - pos.x * res.x, - (1.0 - pos.y - size.y) * res.y, - (pos.x + size.x) * res.x, - (1.0 - pos.y) * res.y - ); + if (!isGuiWindow(window.get())) { + continue; + } - if ( - (mousePosition.x >= bounds.x && mousePosition.x <= bounds.z) && - (mousePosition.y >= bounds.y && mousePosition.y <= bounds.w) - ) { - return glm::vec2( - res.x * (mousePosition.x - bounds.x) / (bounds.z - bounds.x), - res.y * (mousePosition.y - bounds.y) / (bounds.w - bounds.y) - ); - } + const sgct::ivec2 res = window->resolution(); + for (const std::unique_ptr& viewport : window->viewports()) { + const sgct::vec2 pos = viewport->position(); + const sgct::vec2 size = viewport->size(); + const glm::vec4 bounds = glm::vec4( + pos.x * res.x, + (1.0 - pos.y - size.y) * res.y, + (pos.x + size.x) * res.x, + (1.0 - pos.y) * res.y + ); + + if ((mousePosition.x >= bounds.x && mousePosition.x <= bounds.z) && + (mousePosition.y >= bounds.y && mousePosition.y <= bounds.w)) + { + return glm::vec2( + res.x * (mousePosition.x - bounds.x) / (bounds.z - bounds.x), + res.y * (mousePosition.y - bounds.y) / (bounds.w - bounds.y) + ); } } } @@ -1003,7 +996,7 @@ void setSgctDelegateFunctions() { void checkCommandLineForSettings(int& argc, char** argv, bool& hasSGCT, bool& hasProfile, std::string& sgctFunctionName) { - for (int i = 1; i < argc; ++i) { + for (int i = 1; i < argc; i++) { const std::string arg = argv[i]; if (arg == "-c" || arg == "--config") { std::string p = ((i + 1) < argc) ? argv[i + 1] : ""; @@ -1011,7 +1004,7 @@ void checkCommandLineForSettings(int& argc, char** argv, bool& hasSGCT, bool& ha const std::string sgctAssignment = "SGCTConfig="; const size_t findSgct = p.find(sgctAssignment); - const size_t findBracket = p.find("}"); + const size_t findBracket = p.find('}'); if (findSgct != std::string::npos) { if (findBracket != std::string::npos) { sgctFunctionName = arg.substr( @@ -1028,17 +1021,17 @@ void checkCommandLineForSettings(int& argc, char** argv, bool& hasSGCT, bool& ha } } -std::string setWindowConfigPresetForGui(const std::string labelFromCfgFile, +std::string setWindowConfigPresetForGui(const std::string& labelFromCfgFile, bool haveCliSGCTConfig) { openspace::Configuration& config = *global::configuration; std::string preset; - bool sgctConfigFileSpecifiedByLuaFunction = !config.sgctConfigNameInitialized.empty(); + const bool sgctCfgFileSpecifiedByLua = !config.sgctConfigNameInitialized.empty(); if (haveCliSGCTConfig) { - preset = fmt::format("{} (from CLI)", config.windowConfiguration); + preset = std::format("{} (from CLI)", config.windowConfiguration); } - else if (sgctConfigFileSpecifiedByLuaFunction) { + else if (sgctCfgFileSpecifiedByLua) { preset = config.sgctConfigNameInitialized + labelFromCfgFile; } else { @@ -1048,7 +1041,7 @@ std::string setWindowConfigPresetForGui(const std::string labelFromCfgFile, } std::string selectedSgctProfileFromLauncher(LauncherWindow& lw, bool hasCliSGCTConfig, - std::string windowConfiguration, + const std::string& windowConfiguration, const std::string& labelFromCfgFile) { std::string config = windowConfiguration; @@ -1063,30 +1056,24 @@ std::string selectedSgctProfileFromLauncher(LauncherWindow& lw, bool hasCliSGCTC } } else { - std::filesystem::path c = absPath(config); + const std::filesystem::path c = absPath(config); std::filesystem::path cj = c; cj.replace_extension(".json"); - std::filesystem::path cx = c; - cx.replace_extension(".xml"); - if (c.extension().empty()) { if (std::filesystem::exists(cj)) { config += ".json"; } - else if (std::filesystem::exists(cx)) { - config += ".xml"; - } else { - throw ghoul::RuntimeError(fmt::format( - "Error loading configuration file {}. File could not be found", + throw ghoul::RuntimeError(std::format( + "Error loading configuration file '{}'. File could not be found", config )); } } else { - // user customzied sgct config + // user customized SGCT config } } global::configuration->windowConfiguration = config; @@ -1098,6 +1085,8 @@ std::string selectedSgctProfileFromLauncher(LauncherWindow& lw, bool hasCliSGCTC int main(int argc, char* argv[]) { + ZoneScoped; + #ifdef OPENSPACE_BREAK_ON_FLOATING_POINT_EXCEPTION _clearfp(); _controlfp(_controlfp(0, 0) & ~(_EM_ZERODIVIDE | _EM_OVERFLOW), _MCW_EM); @@ -1132,7 +1121,7 @@ int main(int argc, char* argv[]) { std::filesystem::current_path() / std::filesystem::path(argv[0]).parent_path(), ghoul::filesystem::FileSystem::Override::Yes ); - LDEBUG(fmt::format("Registering ${{BIN}} to {}", absPath("${BIN}"))); + LDEBUG(std::format("Registering ${{BIN}} to '{}'", absPath("${BIN}"))); // // Parse commandline arguments @@ -1182,7 +1171,7 @@ int main(int argc, char* argv[]) { ); try { - bool showHelp = parser.execute(); + const bool showHelp = parser.execute(); if (showHelp) { std::cout << parser.helpText(); exit(EXIT_SUCCESS); @@ -1216,23 +1205,23 @@ int main(int argc, char* argv[]) { if (!std::filesystem::is_regular_file(configurationFilePath)) { LFATALC( "main", - fmt::format("Could not find configuration {}", configurationFilePath) + std::format("Could not find configuration '{}'", configurationFilePath) ); exit(EXIT_FAILURE); } - LINFO(fmt::format("Configuration Path: {}", configurationFilePath)); + LINFO(std::format("Configuration Path '{}'", configurationFilePath)); // Register the base path as the directory where the configuration file lives std::filesystem::path base = configurationFilePath.parent_path(); - FileSys.registerPathToken("${BASE}", base); + FileSys.registerPathToken("${BASE}", std::move(base)); // The previous incarnation of this was initializing GLFW to get the primary // monitor's resolution, but that had some massive performance implications as // there was some issue with the swap buffer handling inside of GLFW. My // assumption is that GLFW doesn't like being initialized, destroyed, and then // initialized again. Therefore we are using the platform specific functions now - glm::ivec2 size = glm::ivec2(1920, 1080); #ifdef WIN32 + glm::ivec2 size = glm::ivec2(1920, 1080); DEVMODEW dm = { 0 }; dm.dmSize = sizeof(DEVMODEW); BOOL success = EnumDisplaySettingsW(nullptr, ENUM_CURRENT_SETTINGS, &dm); @@ -1240,6 +1229,8 @@ int main(int argc, char* argv[]) { size.x = dm.dmPelsWidth; size.y = dm.dmPelsHeight; } +#else // ^^^^ WIN32 // !WIN32 vvvv + const glm::ivec2 size = glm::ivec2(1920, 1080); #endif // WIN32 // Loading configuration from disk @@ -1276,7 +1267,7 @@ int main(int argc, char* argv[]) { properties::Property::Visibility::Developer; } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Unknown property visibility value '{}'", *commandlineArguments.propertyVisibility )); @@ -1336,27 +1327,27 @@ int main(int argc, char* argv[]) { #endif // __APPLE__ std::string pwd = std::filesystem::current_path().string(); - if (size_t it = pwd.find_first_of("'\"[]"); it != std::string::npos) { + if (const size_t it = pwd.find_first_of("'\"[]"); it != std::string::npos) { QMessageBox::warning( nullptr, "OpenSpace", - QString::fromStdString(fmt::format( + QString::fromStdString(std::format( "The OpenSpace folder is started must not contain any of \"'\", " - "\"\"\", [, or ]. Path is: '{}'. Unexpected errors will occur when " + "\"\"\", [, or ]. Path is: {}. Unexpected errors will occur when " "proceeding to run the software", pwd )) ); } - LauncherWindow win( + LauncherWindow win = LauncherWindow( !commandlineArguments.profile.has_value(), *global::configuration, !commandlineArguments.windowConfig.has_value(), - windowCfgPreset, + std::move(windowCfgPreset), nullptr ); win.show(); - app.exec(); + QApplication::exec(); if (!win.wasLaunchSelected()) { exit(EXIT_SUCCESS); @@ -1384,8 +1375,8 @@ int main(int argc, char* argv[]) { // there was some issue with the swap buffer handling inside of GLFW. My // assumption is that GLFW doesn't like being initialized, destroyed, and then // initialized again. Therefore we are using the platform specific functions now - glm::ivec2 size = glm::ivec2(1920, 1080); #ifdef WIN32 + glm::ivec2 size = glm::ivec2(1920, 1080); DEVMODEW dm = { 0 }; dm.dmSize = sizeof(DEVMODEW); BOOL success = EnumDisplaySettingsW(nullptr, ENUM_CURRENT_SETTINGS, &dm); @@ -1393,6 +1384,8 @@ int main(int argc, char* argv[]) { size.x = dm.dmPelsWidth; size.y = dm.dmPelsHeight; } +#else // ^^^^ WIN32 // !WIN32 vvvv + const glm::ivec2 size = glm::ivec2(1920, 1080); #endif // WIN32 *global::configuration = loadConfigurationFromFile( @@ -1438,7 +1431,7 @@ int main(int argc, char* argv[]) { LDEBUG("Creating SGCT Engine"); std::vector arg(argv + 1, argv + argc); LDEBUG("Parsing commandline arguments"); - sgct::Configuration config = parseArguments(arg); + const sgct::Configuration config = parseArguments(arg); LDEBUG("Loading cluster information"); config::Cluster cluster = loadCluster(absPath(windowConfiguration).string()); @@ -1462,7 +1455,7 @@ int main(int argc, char* argv[]) { Log::instance().setNotifyLevel(Log::Level::Debug); try { - Engine::create(cluster, callbacks, config); + Engine::create(std::move(cluster), std::move(callbacks), config); } catch (const std::runtime_error& e) { LFATALC("main", e.what()); @@ -1512,8 +1505,8 @@ int main(int argc, char* argv[]) { settings.hasStartedBefore = true; if (settings.rememberLastProfile) { - std::filesystem::path p = global::configuration->profile; - std::filesystem::path reducedName = p.filename().replace_extension(); + const std::filesystem::path p = global::configuration->profile; + const std::filesystem::path reducedName = p.filename().replace_extension(); settings.profile = reducedName.string(); } diff --git a/apps/Sync/main.cpp b/apps/Sync/main.cpp index 3a4255997e..d40c84b4ba 100644 --- a/apps/Sync/main.cpp +++ b/apps/Sync/main.cpp @@ -64,7 +64,7 @@ int main(int, char**) { Task& task = *tasks[i].get(); LINFOC( "Sync", - fmt::format( + std::format( "Synchronizing scene {} out of {}: {}", i + 1, tasks.size(), task.description() ) diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 81316a9d04..a3593ea4a9 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -74,12 +74,12 @@ void performTasks(const std::string& path) { LINFO("Task queue has 1 item"); } else { - LINFO(fmt::format("Task queue has {} items", tasks.size())); + LINFO(std::format("Task queue has {} items", tasks.size())); } for (size_t i = 0; i < tasks.size(); i++) { Task& task = *tasks[i].get(); - LINFO(fmt::format( + LINFO(std::format( "Performing task {} out of {}: {}", i + 1, tasks.size(), task.description() )); ProgressBar progressBar(100); @@ -164,7 +164,7 @@ int main(int argc, char** argv) { // If no task file was specified in as argument, run in CLI mode. - LINFO(fmt::format("Task root: {}", absPath("${TASKS}"))); + LINFO(std::format("Task root: {}", absPath("${TASKS}"))); std::filesystem::current_path(absPath("${TASKS}")); std::cout << "TASK > "; diff --git a/data/assets/examples/audio/audio_playback.asset b/data/assets/examples/audio/audio_playback.asset new file mode 100644 index 0000000000..b236dd744d --- /dev/null +++ b/data/assets/examples/audio/audio_playback.asset @@ -0,0 +1,21 @@ +-- Lets first download a file that we can use for our examples. If you have files +-- locally, you can skip this part. +-- The song in the example comes from https://incompetech.com/ which is a fantastic +-- webpage for very high quality royalty-free music +openspace.downloadFile( + "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Arcadia.mp3", + openspace.absPath("${TEMPORARY}/Arcadia.mp3"), + true +) + +local soundName = "Example_Sound_1" + +asset.onInitialize(function() + -- Start playing the song immediately + openspace.audio.playAudio(openspace.absPath("${TEMPORARY}/Arcadia.mp3"), soundName) +end) + +asset.onDeinitialize(function() + -- When we remove this asset, we want to audio to stop playing no matter what + openspace.audio.stopAudio(soundName) +end) diff --git a/data/assets/examples/audio/audio_playback_advanced.asset b/data/assets/examples/audio/audio_playback_advanced.asset new file mode 100644 index 0000000000..7ba43bdb01 --- /dev/null +++ b/data/assets/examples/audio/audio_playback_advanced.asset @@ -0,0 +1,71 @@ +-- Lets first download a file that we can use for our examples. If you have files +-- locally, you can skip this part. +-- The song in the example comes from https://incompetech.com/ which is a fantastic +-- webpage for very high quality royalty-free music +openspace.downloadFile( + "https://incompetech.com/music/royalty-free/mp3-royaltyfree/Sneaky%20Adventure.mp3", + openspace.absPath("${TEMPORARY}/SneakyAdventure.mp3"), + true +) +local soundName = "Advanced_Example_Sound_1" + +local panleft = { + Identifier = "os.examples.PanLeft", + Name = "Example Audio Pan Left", + Command = [[openspace.audio.set3dSourcePosition("Advanced_Example_Sound_1", { -1, 0, 0 })]], + GuiPath = "/Example/Audio" +} + +local pancenter = { + Identifier = "os.examples.PanCenter", + Name = "Example Audio Pan Center", + Command = [[openspace.audio.set3dSourcePosition("Advanced_Example_Sound_1", { 0, 0, 0 })]], + GuiPath = "/Example/Audio" +} + +local panright = { + Identifier = "os.examples.PanRight", + Name = "Example Audio Pan Right", + Command = [[openspace.audio.set3dSourcePosition("Advanced_Example_Sound_1", { 1, 0, 0 })]], + GuiPath = "/Example/Audio" +} + +local lowvolume = { + Identifier = "os.examples.LowVolume", + Name = "Example Audio Volume Low", + Command = [[openspace.audio.setVolume("Advanced_Example_Sound_1", 0.15)]], + GuiPath = "/Example/Audio" +} + +local fullvolume = { + Identifier = "os.examples.FullVolume", + Name = "Example Audio Volume Full", + Command = [[openspace.audio.setVolume("Advanced_Example_Sound_1", 1.0)]], + GuiPath = "/Example/Audio" +} + +asset.onInitialize(function() + -- Start playing the song immediately in 3D. Place the audio straight in front of us + openspace.audio.playAudio3d( + openspace.absPath("${TEMPORARY}/SneakyAdventure.mp3"), + soundName, + { 0.0, 0.0, 0.0 } + ) + + openspace.action.registerAction(panleft) + openspace.action.registerAction(pancenter) + openspace.action.registerAction(panright) + openspace.action.registerAction(lowvolume) + openspace.action.registerAction(fullvolume) +end) + +asset.onDeinitialize(function() + openspace.action.removeAction(fullvolume) + openspace.action.removeAction(lowvolume) + openspace.action.removeAction(panright) + openspace.action.removeAction(pancenter) + openspace.action.removeAction(panleft) + + -- When we remove this asset, we want to audio to stop playing no matter what + openspace.audio.stopAudio(soundName) +end) diff --git a/data/assets/examples/pointclouds/data/dummydata.csv b/data/assets/examples/pointclouds/data/dummydata.csv index e8b698833f..0df526dbac 100644 --- a/data/assets/examples/pointclouds/data/dummydata.csv +++ b/data/assets/examples/pointclouds/data/dummydata.csv @@ -1,3 +1,6 @@ +# A dummy dataset with an xyz position and some random data columns. +# The last two columns has data values with either missing values or +# Nan values (which can be handled seprately when color mapping) x,y,z,a,b,normaldist_withMissing,number_withNan 13428000,26239000,45870000,-3.226548224,33.95773276,-0.357778948,29 14727000,45282000,10832000,45.05941924,-106.0395917,,29 diff --git a/data/assets/examples/pointclouds/data/interpolation_expand.csv b/data/assets/examples/pointclouds/data/interpolation_expand.csv index 3bd9aede78..b0f3e25a9a 100644 --- a/data/assets/examples/pointclouds/data/interpolation_expand.csv +++ b/data/assets/examples/pointclouds/data/interpolation_expand.csv @@ -1,3 +1,12 @@ +# A test dataset for interpolation, where the xyz positions expand outward in each +# time step. There are 10 points per timestep, as illustrated by the time column. +# There are also two columns that may be used for color mapping: +# +# static_value has values that are the same for the correpsonding point in each +# time step +# dynamic_value has values that change for every timestep. The change will be +# reflected in the interpolation +# time,x,y,z,dynamic_value,static_value 0.0,675.0297905065192,1672.6820684730765,-124.14442820502654,1,1 0.0,9.0852354697237,1080.363474597831,266.4506394528842,3,3 diff --git a/data/assets/examples/pointclouds/data/interpolation_randomwalk.csv b/data/assets/examples/pointclouds/data/interpolation_randomwalk.csv index f8681b6d42..09ed368662 100644 --- a/data/assets/examples/pointclouds/data/interpolation_randomwalk.csv +++ b/data/assets/examples/pointclouds/data/interpolation_randomwalk.csv @@ -1,3 +1,5 @@ +# A test dataset for interpolation, where the xyz vary in a random walk patterin +# time step. There are 10 points per timestep, as illustrated by the time column time,x,y,z 0.0,675.0297905065192,1672.6820684730765,-124.14442820502654 0.0,9.0852354697237,1080.363474597831,266.4506394528842 diff --git a/data/assets/examples/pointclouds/data/textured_csv/textured_points.csv b/data/assets/examples/pointclouds/data/textured_csv/textured_points.csv new file mode 100644 index 0000000000..0bf863e4e6 --- /dev/null +++ b/data/assets/examples/pointclouds/data/textured_csv/textured_points.csv @@ -0,0 +1,9 @@ +# A dummy dataset with an xyz position, some random values and an integer value to +# use for texturing the points +# +# The texture mapping from index to file is handled in another file +x,y,z,a,b,texture +13428000,26239000,45870000,-3.226548224,33.95773276,1 +14727000,45282000,10832000,45.05941924,-106.0395917,0 +24999000,28370000,19911000,-70.58906931,154.1851656,2 +26539000,36165000,39582000,-13.3663358,71.79484733,3 diff --git a/data/assets/examples/pointclouds/data/textured_csv/texturemap.tmap b/data/assets/examples/pointclouds/data/textured_csv/texturemap.tmap new file mode 100644 index 0000000000..0a475f8d61 --- /dev/null +++ b/data/assets/examples/pointclouds/data/textured_csv/texturemap.tmap @@ -0,0 +1,8 @@ +# The texture map is a mapping between an index and the name of an image file. +# All the images should be located in the same folder, or the name need to be specified as a path relative +# to a specific folder + +0 test3.jpg +1 test2.jpg +2 test.jpg +3 openspace-horiz-logo.png diff --git a/data/assets/examples/pointclouds/data/textured_speck/textures_points.speck b/data/assets/examples/pointclouds/data/textured_speck/textures_points.speck new file mode 100644 index 0000000000..2e8b763c2c --- /dev/null +++ b/data/assets/examples/pointclouds/data/textured_speck/textures_points.speck @@ -0,0 +1,16 @@ +# A dummy dataset with an xyz position, some random values and an integer value to +# use for texturing the points + +datavar 0 a +datavar 1 b +datavar 2 texture +texturevar 2 # The index of the data column that has the texture data +texture 0 test3.jpg +texture 1 test.jpg +texture 2 test.jpg +texture 3 openspace-horiz-logo.png + +13428000 26239000 45870000 -3.226548224 33.95773276 0 +14727000 45282000 10832000 45.05941924 -106.0395917 2 +24999000 28370000 19911000 -70.58906931 154.1851656 3 +26539000 36165000 39582000 -13.3663358 71.79484733 1 diff --git a/data/assets/examples/pointclouds/multitextured_points.asset b/data/assets/examples/pointclouds/multitextured_points.asset new file mode 100644 index 0000000000..e236893562 --- /dev/null +++ b/data/assets/examples/pointclouds/multitextured_points.asset @@ -0,0 +1,107 @@ +-- CSV +local Test = { + Identifier = "TexturedPointCloudExample_CSV", + Renderable = { + Type = "RenderablePointCloud", + File = asset.resource("data/textured_csv/textured_points.csv"), + DataMapping = { + -- The name of the column in the CSV file that corresponds to the texture (should + -- be an integer) + TextureColumn = "texture", + -- A Texture mapping file that provides information about which value/index + -- corresponds to which texture file + TextureMapFile = asset.resource("data/textured_csv/texturemap.tmap") + }, + Texture = { + -- Where to find the texture files (in this case, in the OpenSpace data folder) + Folder = openspace.absPath("${DATA}") + }, + UseAdditiveBlending = false + }, + GUI = { + Name = "Multi-Textured Points", + Path = "/Example/Point Clouds/Multi-Textured" + } +} + + +-- Interpolated +-- Multi-texturing works also for interpolated point clouds. Here we let the same +-- dataset as used above be interpreted as representing only two points, with a different +-- texture. Note that the textures will be set based on the first two data items and will +-- not be changed during interpolation +local Test_Interpolated = { + Identifier = "TexturedPointCloudExample_Interpolated", + Renderable = { + Type = "RenderableInterpolatedPoints", + File = asset.resource("data/textured_csv/textured_points.csv"), + NumberOfObjects = 2, + DataMapping = { + TextureColumn = "texture", + TextureMapFile = asset.resource("data/textured_csv/texturemap.tmap") + }, + Texture = { + Folder = openspace.absPath("${DATA}") + }, + UseAdditiveBlending = false + }, + GUI = { + Name = "Multi-Textured Points (Interpolation)", + Path = "/Example/Point Clouds/Multi-Textured" + } +} + +-- Speck file (allows storing all data in one single file, including the texture mapping) +-- Note that we disable this scene graph node per default here, as it shows the same +-- information as the CSV version +local Test_Speck = { + Identifier = "TexturedPointCloudExample_Speck", + Renderable = { + Type = "RenderablePointCloud", + Enabled = false, + -- When loading multi-texture information from a speck file, we do not need a + -- DataMapping entry - all information is in the file + File = asset.resource("data/textured_speck/textures_points.speck"), + Texture = { + -- However, we do still need to specify where the textures are located + Folder = openspace.absPath("${DATA}") + }, + UseAdditiveBlending = false + }, + GUI = { + Name = "Multi-Textured Points (Speck file)", + Path = "/Example/Point Clouds/Multi-Textured" + } +} + + +asset.onInitialize(function() + openspace.addSceneGraphNode(Test) + openspace.addSceneGraphNode(Test_Interpolated) + openspace.addSceneGraphNode(Test_Speck) +end) + +asset.onDeinitialize(function() + openspace.removeSceneGraphNode(Test_Speck) + openspace.removeSceneGraphNode(Test_Interpolated) + openspace.removeSceneGraphNode(Test) +end) + +asset.export(Test) +asset.export(Test_Interpolated) +asset.export(Test_Speck) + + +asset.meta = { + Name = "Multi-textured Points", + Version = "1.0", + Description = [[Example of point clouds where multiple textures are used for the points, + based on information in the dataset. The dataset may be either CSV or Speck format. + If CSV is used, additional information must be provided through the DataMapping: 1) + Which column in the dataset that corresponds to the texture, and a separate file that + maps that value to a texture file + ]], + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/examples/pointclouds/points.asset b/data/assets/examples/pointclouds/points.asset index b14f00906e..9129b14046 100644 --- a/data/assets/examples/pointclouds/points.asset +++ b/data/assets/examples/pointclouds/points.asset @@ -100,13 +100,19 @@ local FixedColor_ScaleBasedOnData = { FixedColor = { 0.5, 0.5, 0.0 } }, SizeSettings = { - -- The options for the columns that the points can be scaled by. The first - -- alternative is chosen per default - SizeMapping = { "number_withNan", "a" }, + SizeMapping = { + -- The options for the columns that the points can be scaled by. The first + -- alternative in the list is chosen per default + ParameterOptions = { "a", "b" }, + -- Specify which option we want to use for size mapping at start up. Here we + -- use the last of the provided options rather than the first one, which is + -- otherwise used by default + Parameter = "b" + }, -- Use a slightly smaller scale than above for the base size of the points -- (will decide the size of the smallest point). That way, the points don't -- become too big when scaled by the data parameter - ScaleExponent = 5 + ScaleExponent = 5.0 } }, GUI = { @@ -131,11 +137,13 @@ local Textured = { Renderable = { Type = "RenderablePointCloud", File = asset.resource("data/dummydata.csv"), - -- The path to the texture file. Here we use openspace.absPath so that we can use - -- the ${DATA} token to get the path to a texture in the "OpenSpace/data" folder, - -- but for a file at a relative location it would also work to use asset.resource, - -- like for the data file above - Texture = openspace.absPath("${DATA}/test3.jpg"), + Texture = { + -- The path to the texture file. Here we use openspace.absPath so that we can use + -- the ${DATA} token to get the path to a texture in the "OpenSpace/data" folder, + -- but for a file at a relative location it would also work to use asset.resource, + -- like for the data file above + File = openspace.absPath("${DATA}/test3.jpg"), + }, -- Disable additive blending, so that points will be rendered with their actual color -- and overlapping points will be sorted by depth. This works best when the points -- have an opacity of 1 diff --git a/data/assets/scene/digitaluniverse/2dF.asset b/data/assets/scene/digitaluniverse/2dF.asset index 48441443d8..ff2b40703c 100644 --- a/data/assets/scene/digitaluniverse/2dF.asset +++ b/data/assets/scene/digitaluniverse/2dF.asset @@ -21,7 +21,9 @@ local Object = { Opacity = 1.0, File = speck .. "2dF.speck", Unit = "Mpc", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Coloring = { ColorMapping = { File = speck .. "2dF.cmap", diff --git a/data/assets/scene/digitaluniverse/2mass.asset b/data/assets/scene/digitaluniverse/2mass.asset index daf8dfe6d9..2dc58b4cfe 100644 --- a/data/assets/scene/digitaluniverse/2mass.asset +++ b/data/assets/scene/digitaluniverse/2mass.asset @@ -21,7 +21,9 @@ local Object = { Opacity = 1.0, File = speck .. "2MASS.speck", Unit = "Mpc", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Coloring = { FixedColor = { 1.0, 0.4, 0.2 }, ColorMapping = { diff --git a/data/assets/scene/digitaluniverse/6dF.asset b/data/assets/scene/digitaluniverse/6dF.asset index f3d5528369..248971a60d 100644 --- a/data/assets/scene/digitaluniverse/6dF.asset +++ b/data/assets/scene/digitaluniverse/6dF.asset @@ -21,7 +21,9 @@ local Object = { Opacity = 1.0, File = speck .. "6dF.speck", Unit = "Mpc", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Coloring = { FixedColor = { 1.0, 1.0, 0.0 }, ColorMapping = { diff --git a/data/assets/scene/digitaluniverse/abell.asset b/data/assets/scene/digitaluniverse/abell.asset index 43ef6c6796..793ff0fcb6 100644 --- a/data/assets/scene/digitaluniverse/abell.asset +++ b/data/assets/scene/digitaluniverse/abell.asset @@ -25,6 +25,7 @@ local Object = { Renderable = { Type = "RenderablePointCloud", Enabled = false, + File = speck .. "abell.speck", Labels = { File = speck .. "abell.label", Opacity = 1.0, @@ -39,8 +40,9 @@ local Object = { FixedColor = { 1.0, 0.4, 0.2 }, --ColorMap = speck .. "abell.cmap", -- TODO: Decide whether to add }, - File = speck .. "abell.speck", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Unit = "Mpc", TransformationMatrix = TransformMatrix, SizeSettings = { diff --git a/data/assets/scene/digitaluniverse/deepsky.asset b/data/assets/scene/digitaluniverse/deepsky.asset index 5aa89ea88b..c17f0d6c1f 100644 --- a/data/assets/scene/digitaluniverse/deepsky.asset +++ b/data/assets/scene/digitaluniverse/deepsky.asset @@ -18,6 +18,7 @@ local DeepSkyObjects = { Renderable = { Type = "RenderablePointCloud", Enabled = false, + File = speck .. "dso.speck", Labels = { File = speck .. "dso.label", Color = { 0.1, 0.4, 0.6 }, @@ -29,8 +30,9 @@ local DeepSkyObjects = { Coloring = { FixedColor = { 1.0, 1.0, 0.0 } }, - File = speck .. "dso.speck", - Texture = textures .. "point3.png", + Texture = { + File = textures .. "point3.png", + }, Unit = "pc", --FadeInDistances = { 0.05, 1.0 }, -- Fade in value in the same unit as "Unit" SizeSettings = { diff --git a/data/assets/scene/digitaluniverse/dwarfs.asset b/data/assets/scene/digitaluniverse/dwarfs.asset index fd13e0e4ec..b45473517d 100644 --- a/data/assets/scene/digitaluniverse/dwarfs.asset +++ b/data/assets/scene/digitaluniverse/dwarfs.asset @@ -18,6 +18,7 @@ local Object = { Renderable = { Type = "RenderablePointCloud", Enabled = false, + File = speck .. "dwarfs.speck", Labels = { File = speck .. "dwarfs.label", Color = { 0.5, 0.1, 0.2 }, @@ -26,8 +27,9 @@ local Object = { Unit = "pc" }, Opacity = 1.0, - File = speck .. "dwarfs.speck", - Texture = textures .. "point3.png", + Texture = { + File = textures .. "point3.png", + }, Unit = "pc", Coloring = { FixedColor = { 0.4, 0.0, 0.1 }, diff --git a/data/assets/scene/digitaluniverse/exoplanets.asset b/data/assets/scene/digitaluniverse/exoplanets.asset index c53f3ae27d..43e604ed61 100644 --- a/data/assets/scene/digitaluniverse/exoplanets.asset +++ b/data/assets/scene/digitaluniverse/exoplanets.asset @@ -18,6 +18,7 @@ local Object = { Renderable = { Type = "RenderablePointCloud", Enabled = false, + File = speck .. "expl.speck", Labels = { File = speck .. "expl.label", Color = { 0.3, 0.3, 0.8 }, @@ -26,8 +27,9 @@ local Object = { Unit = "pc" }, Opacity = 1.0, - Texture = textures .. "target-blue.png", - File = speck .. "expl.speck", + Texture = { + File = textures .. "target-blue.png", + }, Unit = "pc", SizeSettings = { ScaleExponent = 16.9, diff --git a/data/assets/scene/digitaluniverse/exoplanets_candidates.asset b/data/assets/scene/digitaluniverse/exoplanets_candidates.asset index e0bb934486..6c95b2e68d 100644 --- a/data/assets/scene/digitaluniverse/exoplanets_candidates.asset +++ b/data/assets/scene/digitaluniverse/exoplanets_candidates.asset @@ -21,7 +21,9 @@ local Object = { Opacity = 0.99, File = speck .. "exoplanet_candidates.speck", Unit = "pc", - Texture = textures .. "halo.png", + Texture = { + File = textures .. "halo.png", + }, Coloring = { FixedColor = { 1.0, 1.0, 0.0 } }, diff --git a/data/assets/scene/digitaluniverse/hdf.asset b/data/assets/scene/digitaluniverse/hdf.asset index 964144e69c..9598b46ba6 100644 --- a/data/assets/scene/digitaluniverse/hdf.asset +++ b/data/assets/scene/digitaluniverse/hdf.asset @@ -27,7 +27,9 @@ local Object = { Enabled = false, Opacity = 1.0, File = HUDFSpeck .. "hudf.speck", - Texture = circle .. "circle.png", + Texture = { + File = circle .. "circle.png", + }, Coloring = { ColorMapping = { File = ColorMap .. "hudf.cmap", diff --git a/data/assets/scene/digitaluniverse/localdwarfs.asset b/data/assets/scene/digitaluniverse/localdwarfs.asset index b09da57150..a9a9022bd6 100644 --- a/data/assets/scene/digitaluniverse/localdwarfs.asset +++ b/data/assets/scene/digitaluniverse/localdwarfs.asset @@ -18,6 +18,8 @@ local Object = { Renderable = { Type = "RenderablePolygonCloud", Enabled = false, + Opacity = 0.3, + File = speck .. "localgroup.speck", Labels = { File = speck .. "localgroup.label", Color = { 0.3, 0.3, 1.0 }, @@ -27,11 +29,6 @@ local Object = { }, Coloring = { FixedColor = { 0.0, 1.0, 0.0 }, - -- @TODO: This one wasn't actually properly used before the point cloud update. - -- All points were mapped to green. Decide if we want it around. - -- @TODO: Also, the cmap is currently not applied correctly, due to speck file - -- not being read properly (it inlcudes more information than just datavar-s). - -- This should be adressed. (2023-12-13, emmbr) ColorMapping = { File = speck .. "localgroup.cmap", ParameterOptions = { @@ -39,8 +36,6 @@ local Object = { } } }, - Opacity = 0.3, - File = speck .. "localgroup.speck", PolygonSides = 12, Unit = "Mpc", SizeSettings = { diff --git a/data/assets/scene/digitaluniverse/obassociations.asset b/data/assets/scene/digitaluniverse/obassociations.asset index fd0610c6f1..3c26a82179 100644 --- a/data/assets/scene/digitaluniverse/obassociations.asset +++ b/data/assets/scene/digitaluniverse/obassociations.asset @@ -36,10 +36,11 @@ local Object = { Opacity = 0.7, File = speck .. "ob.speck", Unit = "pc", - Texture = textures .. "point4.png", PolygonSides = 7, SizeSettings = { - SizeMapping = { "diameter" }, + SizeMapping = { + ParameterOptions = { "diameter" } + }, ScaleExponent = 16.9, MaxSize = 17, EnableMaxSizeControl = true diff --git a/data/assets/scene/digitaluniverse/quasars.asset b/data/assets/scene/digitaluniverse/quasars.asset index 93efec3236..0594ad74c4 100644 --- a/data/assets/scene/digitaluniverse/quasars.asset +++ b/data/assets/scene/digitaluniverse/quasars.asset @@ -27,7 +27,9 @@ local Object = { Enabled = true, Opacity = 0.95, File = speck .. "quasars.speck", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Unit = "Mpc", Fading = { FadeInDistances = { 1000.0, 10000.0 } -- Fade in value in the same unit as "Unit" diff --git a/data/assets/scene/digitaluniverse/sdss.asset b/data/assets/scene/digitaluniverse/sdss.asset index 0ffa195d31..cb3103e1d1 100644 --- a/data/assets/scene/digitaluniverse/sdss.asset +++ b/data/assets/scene/digitaluniverse/sdss.asset @@ -30,7 +30,9 @@ local Object = { } } }, - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Unit = "Mpc", Fading = { FadeInDistances = { 220.0, 650.0 } -- Fade in value in the same unit as "Unit" diff --git a/data/assets/scene/digitaluniverse/superclusters.asset b/data/assets/scene/digitaluniverse/superclusters.asset index 77260619f7..4ec85bc0a0 100644 --- a/data/assets/scene/digitaluniverse/superclusters.asset +++ b/data/assets/scene/digitaluniverse/superclusters.asset @@ -18,6 +18,7 @@ local Object = { Renderable = { Type = "RenderablePointCloud", Enabled = false, + File = speck .. "superclust.speck", Labels = { Enabled = true, File = speck .. "superclust.label", @@ -28,8 +29,9 @@ local Object = { }, DrawElements = false, Opacity = 0.65, - File = speck .. "superclust.speck", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png", + }, Unit = "Mpc", SizeSettings = { ScaleExponent = 23.1, diff --git a/data/assets/scene/digitaluniverse/tully.asset b/data/assets/scene/digitaluniverse/tully.asset index b7739c503d..040c386ae2 100644 --- a/data/assets/scene/digitaluniverse/tully.asset +++ b/data/assets/scene/digitaluniverse/tully.asset @@ -35,7 +35,9 @@ local TullyGalaxies = { }, Opacity = 0.99, File = speck .. "tully.speck", - Texture = textures .. "point3A.png", + Texture = { + File = textures .. "point3A.png" + }, Coloring = { FixedColor = { 1.0, 0.4, 0.2 }, ColorMapping = { diff --git a/data/assets/scene/solarsystem/planets/earth/eclipses/5000_years.asset b/data/assets/scene/solarsystem/planets/earth/eclipses/5000_years.asset new file mode 100644 index 0000000000..ee82c5a4c8 --- /dev/null +++ b/data/assets/scene/solarsystem/planets/earth/eclipses/5000_years.asset @@ -0,0 +1,49 @@ +local globe = asset.require("../earth") + + + +local texturesPath = asset.resource({ + Name = "5000 Years of Total Solar Eclipses", + Type = "HttpSynchronization", + Identifier = "earth_eclipse_5000_years", + Version = 1 +}) + + +local Layer = { + Identifier = "5000_Years_Eclipses", + Name = "5000 Years of Total Solar Eclipses", + Enabled = asset.enabled, + FilePath = texturesPath .. "eclipse_freq_heatmap.tif", + Description = [[ + This is a heatmap showing the density of solar eclipse paths over the Earth during the 5000-year period between 2000 BCE and 3000 CE. It uses the list of eclipses calculated by Fred Espenak and Jean Meeus and published in 2006 as the Five Millennium Canon of Solar Eclipses. The paths of the 3742 eclipses classified in the Canon as either "T" (total) or "H" (hybrid or total-annular) were drawn into a global map with a pixel resolution of 4 minutes (1/15 of a degree) of latitude and longitude. The pixels counted the eclipse paths as they were drawn, and each pixel location ended up experiencing anywhere from one to 35 eclipses. + + For more information visit the NASA's Scientific Visualization Studio that generated this image: https://svs.gsfc.nasa.gov/5222 + + Thanks to Visualizer Ernie Wright and Technical support Ian Jones and Laurence Schuler for this. + + See also the paper by Jean Meeus, The Frequency of Total and Annular Solar Eclipses for a Given Place, JBAA 92, 3 (April 1982), pp 124-126. + ]], + CacheSettings = { Enabled = false } +} + + +asset.onInitialize(function() + openspace.globebrowsing.addLayer(globe.Earth.Identifier, "ColorLayers", Layer) +end) + +asset.onDeinitialize(function() + openspace.globebrowsing.deleteLayer(globe.Earth.Identifier, "ColorLayers", Layer) +end) + +asset.export("layer", Layer) + + +asset.meta = { + Name = "5000 Years of Total Solar Eclipses", + Version = "1.0", + Description = Layer.Description, + Author = "OpenSpace Team", + URL = "https://svs.gsfc.nasa.gov/5222", + License = "NASA" +} diff --git a/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset b/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset index f6a5d79657..a62df31c6f 100644 --- a/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset +++ b/data/assets/scene/solarsystem/planets/earth/satellites/misc/iss.asset @@ -11,6 +11,13 @@ local models = asset.resource({ Version = 3 }) +local kernels = asset.resource({ + Name = "ISS Kernels", + Type = "HttpSynchronization", + Identifier = "iss_kernels", + Version = 1 +}) + local omm = asset.resource({ Name = "Satellite OMM Data (ISS)", Type = "UrlSynchronization", @@ -20,23 +27,22 @@ local omm = asset.resource({ SecondsUntilResync = 24 * 60 * 60 }) +local tle = asset.resource({ + Name = "Satellite TLE Data (ISS)", + Type = "UrlSynchronization", + Identifier = "satellite_tle_data_iss", + Url = "https://www.celestrak.com/NORAD/elements/gp.php?CATNR=25544&FORMAT=tle", + Filename = "ISS.txt", + SecondsUntilResync = 24 * 60 * 60 +}) + local IssPosition = { Identifier = "ISSPosition", Parent = transforms.EarthInertial.Identifier, BoundingSphere = 54.5, -- half the width Transform = { - Translation = { - Type = "GPTranslation", - Observer = transforms.EarthInertial.Identifier, - File = omm .. "ISS.txt", - Format = "OMM" - }, - Rotation = { - Type = "SpiceRotation", - SourceFrame = coreKernels.Frame.Galactic, - DestinationFrame = coreKernels.Frame.J2000 - } + Translation = {}, -- This translation is provided in the onInitialize }, Tag = { "earth_satellite", "ISS" }, GUI = { @@ -51,11 +57,9 @@ local IssModel = { Parent = IssPosition.Identifier, Transform = { Rotation = { - Type = "FixedRotation", - Attached = "ISS", - XAxis = { 0.01, -1.0, 0.56 }, - XAxisOrthogonal = true, - YAxis = transforms.EarthInertial.Identifier + Type = "SpiceRotation", + SourceFrame = "ISS", + DestinationFrame = coreKernels.Frame.J2000 } }, Renderable = { @@ -79,12 +83,7 @@ local IssTrail = { Parent = transforms.EarthInertial.Identifier, Renderable = { Type = "RenderableTrailOrbit", - Translation = { - Type = "GPTranslation", - Observer = transforms.EarthInertial.Identifier, - File = omm .. "ISS.txt", - Format = "OMM" - }, + Translation = {}, -- This translation is provided in the onInitialize RenderBinMode = "PostDeferredTransparent", Color = { 0.9, 0.6715, 0.0 }, Fade = 1.5, @@ -135,19 +134,36 @@ local FocusIss = { } +local kernelFile asset.onInitialize(function() + -- In order to get the orientation of the ISS correctly, we need to have its position + -- available as a SPICE object. We don't want to just convert the TLE file once as we + -- want it to update with every startup. + -- For this reason we convert the TLE file into a type 10 SPICE kernel and since we are + -- already doing that, we can also get a more accurate position for free, too + local translation, kernel = openspace.space.tleToSpiceTranslation(tle .. "ISS.txt") + kernelFile = kernel -- Store the path for the deinitialize function + openspace.spice.loadKernel(kernelFile) + IssPosition.Transform.Translation = translation; + IssTrail.Renderable.Translation = translation; + + openspace.spice.loadKernel(kernels .. "iss.tf") + local i = openspace.space.readKeplerFile(omm .. "ISS.txt", "OMM") IssTrail.Renderable.Period = i[1].Period / (60 * 60 * 24) + openspace.addSceneGraphNode(IssPosition) openspace.addSceneGraphNode(IssModel) openspace.addSceneGraphNode(IssTrail) - openspace.setPropertyValueSingle("Scene.ISS.Rotation.yAxisInvertObject", true) openspace.action.registerAction(FocusIss) end) asset.onDeinitialize(function() + openspace.spice.unloadKernel(kernels .. "iss.tf") + openspace.spice.unloadKernel(kernelFile) + openspace.action.removeAction(FocusIss) openspace.removeSceneGraphNode(IssTrail) @@ -163,7 +179,7 @@ asset.export(IssPosition) asset.meta = { Name = "ISS", - Version = "2.0", + Version = "3.0", Description = [[Model and Trail for ISS. Model from NASA 3D models, trail from Celestrak.]], Author = "OpenSpace Team", diff --git a/data/assets/scene/solarsystem/telescopes/jwst/jwst.asset b/data/assets/scene/solarsystem/telescopes/jwst/jwst.asset index c9649f8ed0..333329a0bd 100644 --- a/data/assets/scene/solarsystem/telescopes/jwst/jwst.asset +++ b/data/assets/scene/solarsystem/telescopes/jwst/jwst.asset @@ -22,15 +22,13 @@ local band = asset.resource({ local LaunchTime = "2021 DEC 25 12:20:00" -local EndTime = "2024 JAN 22 00:00:00" local JWSTBand = { Identifier = "JWSTBand", Parent = transforms.JWSTPosition.Identifier, TimeFrame = { Type = "TimeFrameInterval", - Start = LaunchTime, - End = EndTime + Start = LaunchTime }, Transform = { Rotation = { @@ -65,8 +63,7 @@ local JWSTModel = { Parent = transforms.JWSTRotation.Identifier, TimeFrame = { Type = "TimeFrameInterval", - Start = LaunchTime, - End = EndTime + Start = LaunchTime }, Renderable = { Type = "RenderableModel", @@ -96,8 +93,7 @@ local JWSTFov = { Parent = JWSTModel.Identifier, TimeFrame = { Type = "TimeFrameInterval", - Start = LaunchTime, - End = EndTime + Start = LaunchTime }, Renderable = { Type = "RenderablePrism", @@ -129,8 +125,7 @@ local JWSTLabel = { Parent = transforms.JWSTPosition.Identifier, TimeFrame = { Type = "TimeFrameInterval", - Start = LaunchTime, - End = EndTime + Start = LaunchTime }, Renderable = { Type = "RenderableLabel", diff --git a/data/assets/util/joysticks/any-joystick.asset b/data/assets/util/joysticks/any-joystick.asset index c159d8e859..db699dd070 100644 --- a/data/assets/util/joysticks/any-joystick.asset +++ b/data/assets/util/joysticks/any-joystick.asset @@ -13,6 +13,8 @@ local function addJoystickAsset(joystick) openspace.asset.add("./util/joysticks/xbox") elseif joystick == "Wireless Xbox Controller" then openspace.asset.add("./util/joysticks/xbox-wireless") + elseif joystick == "Microsoft X-Box 360 pad" then + openspace.asset.add("./util/joysticks/microsoft-xbox-360-pad") elseif joystick == "SpaceNavigator" then openspace.asset.add("./util/joysticks/space-mouse-compact") elseif joystick == "SpaceMouse Enterprise" then @@ -74,3 +76,14 @@ asset.onDeinitialize(function() openspace.asset.remove("./util/joysticks/space-mouse-enterprise") end end) + +asset.meta = { + Name = "Joystick controller: Any", + Version = "1.0", + Description = [[ + Checks the name on the connected controllers and adds the cooresponding joystick asset + ]], + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/microsoft-xbox-360-pad.asset b/data/assets/util/joysticks/microsoft-xbox-360-pad.asset new file mode 100644 index 0000000000..c548de7c7f --- /dev/null +++ b/data/assets/util/joysticks/microsoft-xbox-360-pad.asset @@ -0,0 +1,220 @@ +local propertyHelper = asset.require("../property_helper") +local joystickHelper = asset.require("./joystick_helper") + + + +-- Allowed values for the third parameter of bindJoystickAxis: +-- "None" +-- "Orbit X" +-- "Orbit Y" +-- "Zoom" -- both in and out +-- "Zoom In" +-- "Zoom Out" +-- "LocalRoll" +-- "GlobalRoll" +-- "Pan X" +-- "Pan Y" +-- Fourth parameter determines whether the axis should be inverted +-- Fifth parameter determines whether the axis behaves like a joystick or a Trigger. +-- Allowed values are "JoystickLike" and "TriggerLike", the first one is the default +-- Sixth parameters determins if the axis should be "Sticky" or not. +-- The axis values can either go back to 0 when the joystick is released or it can +-- stay at the value it was before the joystick was released. +-- The latter is called a sticky axis, when the values don't go back to 0. +-- Seventh parameter can be used to reverse the camera movement for the axis +-- Eighth parameter is the sensitivity for the axis + +local XBoxController = { + -- Axes + LeftThumbStick = { + LeftRight = 0, + UpDown = 1 + }, + RightThumbStick = { + LeftRight = 3, + UpDown = 4 + }, + LeftTrigger = 2, + RightTrigger = 5, + + -- Buttons + A = 0, + B = 1, + X = 2, + Y = 3, + LB = 4, + RB = 5, + Back = 6, + Start = 7, + LeftStickButton = 9, + RightStickButton = 10, + DPad = { + Up = 11, + Right = 12, + Down = 13, + Left = 14 + } +} + + +asset.onInitialize(function() + local controller = XBoxController + local name = "Microsoft X-Box 360 pad" + + local deadzoneJoysticks = 0.2 + local deadzoneTriggers = 0.05 + openspace.navigation.setAxisDeadZone(name, controller.LeftThumbStick.LeftRight, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.LeftThumbStick.UpDown, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.RightThumbStick.LeftRight, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.RightThumbStick.UpDown, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.LeftTrigger, deadzoneTriggers) + openspace.navigation.setAxisDeadZone(name, controller.RightTrigger, deadzoneTriggers) + + openspace.navigation.bindJoystickAxis(name, controller.LeftThumbStick.LeftRight, "Orbit X") + openspace.navigation.bindJoystickAxis(name, controller.LeftThumbStick.UpDown, "Orbit Y") + openspace.navigation.bindJoystickAxis(name, controller.RightThumbStick.LeftRight, "Pan X", true) + openspace.navigation.bindJoystickAxis(name, controller.RightThumbStick.UpDown, "Pan Y", true) + openspace.navigation.bindJoystickAxis(name, controller.LeftTrigger, "Zoom Out", false, "TriggerLike") + openspace.navigation.bindJoystickAxis(name, controller.RightTrigger, "Zoom In", false, "TriggerLike") + + -- Roll + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Up, + joystickHelper.bindLocalRoll(name, controller.RightThumbStick.LeftRight) .. + "openspace.navigation.bindJoystickAxis('" .. name .. "', " .. controller.RightThumbStick.UpDown .. ", 'None')", + "Switch to roll mode" + ) + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Up, + joystickHelper.unbindRoll(name, controller.RightThumbStick.LeftRight) .. + "openspace.navigation.bindJoystickAxis('" .. name .. "', " .. controller.RightThumbStick.UpDown .. ", 'Pan Y', true)", + "Switch back to normal mode", + "Release" + ) + + -- Switch focus in the interesting nodes menu + openspace.navigation.bindJoystickButton( + name, + controller.LB, + [[ + openspace.navigation.targetPreviousInterestingAnchor() + openspace.navigation.retargetAnchor() + ]], + "Switch target to the previous interesting node" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.RB, + [[ + openspace.navigation.targetNextInterestingAnchor() + openspace.navigation.retargetAnchor() + ]], + "Switch target to the next interesting node" + ) + + -- Toggle Frictions + openspace.navigation.bindJoystickButton( + name, + controller.A, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.RotationalFriction"), + "Toggle rotational friction" + ) + openspace.navigation.bindJoystickButton( + name, + controller.B, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.ZoomFriction"), + "Toggle zoom friction" + ) + openspace.navigation.bindJoystickButton( + name, + controller.Y, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.RollFriction"), + "Toggle roll friction" + ) + + -- Refocus + openspace.navigation.bindJoystickButton( + name, + controller.RightStickButton, + "openspace.navigation.retargetAnchor()", + "Retarget on current focus" + ) + + -- Time + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Left, + "openspace.time.interpolatePreviousDeltaTimeStep()", + "Go backwards in time, faster the more times this button is pressed" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Down, + "openspace.time.interpolateDeltaTime(1)", + "Reset realtime" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Right, + "openspace.time.interpolateNextDeltaTimeStep()", + "Go forwards in time, faster the more times this button is pressed" + ) + + -- Reset Time to yesterday + openspace.navigation.bindJoystickButton( + name, + controller.Back, + [[ + openspace.time.setDeltaTime(1) + local yesterday = openspace.time.advancedTime(openspace.time.currentWallTime(), "-1d") + openspace.time.setTime(yesterday) + ]], + "Reset to yesterday realtime" + ) + + -- Pause + openspace.navigation.bindJoystickButton( + name, + controller.Start, + "openspace.time.togglePause()", + "Pause time simulation" + ) + + -- Open buttons that can be customized + -- X + openspace.navigation.bindJoystickButton( + name, + controller.X, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) + + -- Left Joystick Button + openspace.navigation.bindJoystickButton( + name, + controller.LeftStickButton, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) +end) + +asset.meta = { + Name = "Joystick controller: Microsoft X-Box 360 pad", + Version = "1.0", + Description = "Joystick controller configuration for Microsoft X-Box 360 pad", + Author = [[ + OpenSpace Team & Winston + https://openspacesupport.slack.com/archives/CLMQXJJDQ/p1710388096683769 + ]], + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/ps4.asset b/data/assets/util/joysticks/ps4.asset index 1ca140dfe8..17efac0dfd 100644 --- a/data/assets/util/joysticks/ps4.asset +++ b/data/assets/util/joysticks/ps4.asset @@ -228,3 +228,12 @@ asset.onInitialize(function() "" -- <-- Description of your custom script here (optional) ) end) + +asset.meta = { + Name = "Joystick controller: PS4", + Version = "1.0", + Description = "Joystick controller configuration for PS4", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/ps5.asset b/data/assets/util/joysticks/ps5.asset new file mode 100644 index 0000000000..2320c53bd3 --- /dev/null +++ b/data/assets/util/joysticks/ps5.asset @@ -0,0 +1,252 @@ +local propertyHelper = asset.require("../property_helper") +local joystickHelper = asset.require("./joystick_helper") + + + +-- Allowed values for the third parameter of bindJoystickAxis: +-- "None" +-- "Orbit X" +-- "Orbit Y" +-- "Zoom" -- both in and out +-- "Zoom In" +-- "Zoom Out" +-- "LocalRoll" +-- "GlobalRoll" +-- "Pan X" +-- "Pan Y" +-- Fourth parameter determines whether the axis should be inverted +-- Fifth parameter determines whether the axis behaves like a joystick or a Trigger. +-- Allowed values are "JoystickLike" and "TriggerLike", the first one is the default +-- Sixth parameters determins if the axis should be "Sticky" or not. +-- The axis values can either go back to 0 when the joystick is released or it can +-- stay at the value it was before the joystick was released. +-- The latter is called a sticky axis, when the values don't go back to 0. +-- Seventh parameter can be used to reverse the camera movement for the axis +-- Eighth parameter is the sensitivity for the axis + +local PS5Controller = { + -- Axes + LeftThumbStick = { + LeftRight = 0, + UpDown = 1 + }, + RightThumbStick = { + LeftRight = 2, + UpDown = 5 + }, + L2 = 3, + R2 = 4, + + -- Buttons + Cross = 1, + Circle = 2, + Square = 0, + Triangle = 3, + L1 = 4, + R1 = 5, + L2Press = 6, + R2Press = 7, + Share = 8, + Options = 9, + PS = 12, + LeftStickButton = 10, + RightStickButton = 11, + TouchPad = 13, + Mute = 14, + DPad = { + Up = 15, + Right = 16, + Down = 17, + Left = 18 + } +} + + +asset.onInitialize(function() + local controller = PS5Controller + local name = "DualSense Wireless Controller" + + local deadzoneJoysticks = 0.2 + local deadzoneTriggers = 0.05 + openspace.navigation.setAxisDeadZone(name, controller.LeftThumbStick.LeftRight, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.LeftThumbStick.UpDown, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.RightThumbStick.LeftRight, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.RightThumbStick.UpDown, deadzoneJoysticks) + openspace.navigation.setAxisDeadZone(name, controller.L2, deadzoneTriggers) + openspace.navigation.setAxisDeadZone(name, controller.R2, deadzoneTriggers) + + openspace.navigation.bindJoystickAxis(name, controller.LeftThumbStick.LeftRight, "Orbit X") + openspace.navigation.bindJoystickAxis(name, controller.LeftThumbStick.UpDown, "Orbit Y") + openspace.navigation.bindJoystickAxis(name, controller.RightThumbStick.LeftRight, "Pan X", true) + openspace.navigation.bindJoystickAxis(name, controller.RightThumbStick.UpDown, "Pan Y", true) + openspace.navigation.bindJoystickAxis(name, controller.L2, "Zoom Out", false, "TriggerLike") + openspace.navigation.bindJoystickAxis(name, controller.R2, "Zoom In", false, "TriggerLike") + + -- Roll + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Up, + joystickHelper.bindLocalRoll(name, controller.RightThumbStick.LeftRight) .. + "openspace.navigation.bindJoystickAxis('" .. name .. "', " .. controller.RightThumbStick.UpDown .. ", 'None')", + "Switch to roll mode" + ) + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Up, + joystickHelper.unbindRoll(name, controller.RightThumbStick.LeftRight) .. + "openspace.navigation.bindJoystickAxis('" .. name .. "', " .. controller.RightThumbStick.UpDown .. ", 'Pan Y', true)", + "Switch back to normal mode", + "Release" + ) + + -- Switch focus in the interesting nodes menu + openspace.navigation.bindJoystickButton( + name, + controller.L1, + [[ + openspace.navigation.targetPreviousInterestingAnchor() + openspace.navigation.retargetAnchor() + ]], + "Switch target to the previous interesting node" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.R1, + [[ + openspace.navigation.targetNextInterestingAnchor() + openspace.navigation.retargetAnchor() + ]], + "Switch target to the next interesting node" + ) + + -- Toggle Frictions + openspace.navigation.bindJoystickButton( + name, + controller.Cross, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.RotationalFriction"), + "Toggle rotational friction" + ) + openspace.navigation.bindJoystickButton( + name, + controller.Circle, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.ZoomFriction"), + "Toggle zoom friction" + ) + openspace.navigation.bindJoystickButton( + name, + controller.Triangle, + propertyHelper.invert("NavigationHandler.OrbitalNavigator.Friction.RollFriction"), + "Toggle roll friction" + ) + + -- Refocus + openspace.navigation.bindJoystickButton( + name, + controller.RightStickButton, + "openspace.navigation.retargetAnchor()", + "Retarget on current focus" + ) + + -- Time + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Left, + "openspace.time.interpolatePreviousDeltaTimeStep()", + "Go backwards in time, faster the more times this button is pressed" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Down, + "openspace.time.interpolateDeltaTime(1)", + "Reset realtime" + ) + + openspace.navigation.bindJoystickButton( + name, + controller.DPad.Right, + "openspace.time.interpolateNextDeltaTimeStep()", + "Go forwards in time, faster the more times this button is pressed" + ) + + -- Reset Time to yesterday + openspace.navigation.bindJoystickButton( + name, + controller.Options, + [[ + openspace.time.setDeltaTime(1) + local yesterday = openspace.time.advancedTime(openspace.time.currentWallTime(), "-1d") + openspace.time.setTime(yesterday) + ]], + "Reset to yesterday realtime" + ) + + -- Pause + openspace.navigation.bindJoystickButton( + name, + controller.TouchPad, + "openspace.time.togglePause()", + "Pause time simulation" + ) + + -- Open buttons that can be customized + -- Square + openspace.navigation.bindJoystickButton( + name, + controller.Square, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) + + -- Share button + openspace.navigation.bindJoystickButton( + name, + controller.Share, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) + + -- Left Joystick Button + openspace.navigation.bindJoystickButton( + name, + controller.LeftStickButton, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) + + -- Playstation button + openspace.navigation.bindJoystickButton( + name, + controller.PS, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) + + -- Microphone mute button + openspace.navigation.bindJoystickButton( + name, + controller.Mute, + [[ + -- <-- Copy paste your custom script here + ]], + "" -- <-- Description of your custom script here (optional) + ) +end) + +asset.meta = { + Name = "Joystick controller: PS5", + Version = "1.0", + Description = "Joystick controller configuration for PS5", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/space-mouse-compact-wireless.asset b/data/assets/util/joysticks/space-mouse-compact-wireless.asset index 4352f161ac..3e21752519 100644 --- a/data/assets/util/joysticks/space-mouse-compact-wireless.asset +++ b/data/assets/util/joysticks/space-mouse-compact-wireless.asset @@ -69,3 +69,12 @@ asset.onInitialize(function() "Switch to global roll mode" ) end) + +asset.meta = { + Name = "Joystick controller: SpaceMouse compact wireless", + Version = "1.0", + Description = "Joystick controller configuration for SpaceMouse compact wireless", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/space-mouse-compact.asset b/data/assets/util/joysticks/space-mouse-compact.asset index d6935347e7..14246bf476 100644 --- a/data/assets/util/joysticks/space-mouse-compact.asset +++ b/data/assets/util/joysticks/space-mouse-compact.asset @@ -69,3 +69,12 @@ asset.onInitialize(function() "Switch to global roll mode" ) end) + +asset.meta = { + Name = "Joystick controller: SpaceMouse compact (wired)", + Version = "1.0", + Description = "Joystick controller configuration for SpaceMouse compact (wired)", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/space-mouse-enterprise-wireless.asset b/data/assets/util/joysticks/space-mouse-enterprise-wireless.asset index d84e309d18..4e5695a797 100644 --- a/data/assets/util/joysticks/space-mouse-enterprise-wireless.asset +++ b/data/assets/util/joysticks/space-mouse-enterprise-wireless.asset @@ -63,3 +63,12 @@ asset.onInitialize(function() openspace.navigation.bindJoystickAxis(name, controller.Push.UpDown, "Zoom") openspace.navigation.bindJoystickAxis(name, controller.Tilt.LeftRight, "LocalRoll") end) + +asset.meta = { + Name = "Joystick controller: SpaceMouse enterprise wireless", + Version = "1.0", + Description = "Joystick controller configuration for SpaceMouse enterprise wireless", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/space-mouse-enterprise.asset b/data/assets/util/joysticks/space-mouse-enterprise.asset index b7d7a963c8..d458f23417 100644 --- a/data/assets/util/joysticks/space-mouse-enterprise.asset +++ b/data/assets/util/joysticks/space-mouse-enterprise.asset @@ -63,3 +63,12 @@ asset.onInitialize(function() openspace.navigation.bindJoystickAxis(name, controller.Push.UpDown, "Zoom") openspace.navigation.bindJoystickAxis(name, controller.Tilt.LeftRight, "LocalRoll") end) + +asset.meta = { + Name = "Joystick controller: SpaceMouse enterprise (wired)", + Version = "1.0", + Description = "Joystick controller configuration for SpaceMouse enterprise (wired)", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/xbox-wireless.asset b/data/assets/util/joysticks/xbox-wireless.asset index 5afbb5d82c..754464d484 100644 --- a/data/assets/util/joysticks/xbox-wireless.asset +++ b/data/assets/util/joysticks/xbox-wireless.asset @@ -206,3 +206,12 @@ asset.onInitialize(function() "" -- <-- Description of your custom script here (optional) ) end) + +asset.meta = { + Name = "Joystick controller: Xbox wireless", + Version = "1.0", + Description = "Joystick controller configuration for Xbox wireless", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} diff --git a/data/assets/util/joysticks/xbox.asset b/data/assets/util/joysticks/xbox.asset index 40f01210d4..5041a6a321 100644 --- a/data/assets/util/joysticks/xbox.asset +++ b/data/assets/util/joysticks/xbox.asset @@ -206,3 +206,12 @@ asset.onInitialize(function() "" -- <-- Description of your custom script here (optional) ) end) + +asset.meta = { + Name = "Joystick controller: Xbox (wired)", + Version = "1.0", + Description = "Joystick controller configuration for Xbox (wired)", + Author = "OpenSpace Team", + URL = "http://openspaceproject.com", + License = "MIT license" +} \ No newline at end of file diff --git a/data/assets/util/webgui.asset b/data/assets/util/webgui.asset index eb5ae44c16..e45b8665d5 100644 --- a/data/assets/util/webgui.asset +++ b/data/assets/util/webgui.asset @@ -4,7 +4,7 @@ local guiCustomization = asset.require("customization/gui") -- Select which commit hashes to use for the frontend and backend -local frontendHash = "95683e59c7fa1891e7db7b83e4eeea15f9da11f1" +local frontendHash = "65c0238b8ba931b958cf3cada2ab226c8f1c9880" local frontend = asset.resource({ Identifier = "WebGuiFrontend", diff --git a/ext/ghoul b/ext/ghoul index 2905908df8..c5164de300 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit 2905908df8dc4f6fc025f4f73834819706b3afe0 +Subproject commit c5164de300f56b5034ec94fcefe7e6a6c03e4bfe diff --git a/include/openspace/camera/camera.h b/include/openspace/camera/camera.h index f975b70b23..9fa3bd8ea8 100644 --- a/include/openspace/camera/camera.h +++ b/include/openspace/camera/camera.h @@ -78,7 +78,7 @@ public: void setAtmosphereDimmingFactor(float atmosphereDimmingFactor); // Relative mutators - void rotate(glm::dquat rotation); + void rotate(const glm::dquat& rotation); // Accessors // Remove Vec3 from the name when psc is gone diff --git a/include/openspace/data/csvloader.h b/include/openspace/data/csvloader.h index a6f3734e61..911e2fe3db 100644 --- a/include/openspace/data/csvloader.h +++ b/include/openspace/data/csvloader.h @@ -34,6 +34,9 @@ namespace openspace::dataloader::csv { Dataset loadCsvFile(std::filesystem::path path, std::optional specs = std::nullopt); +std::vector loadTextureMapFile(std::filesystem::path path, + const std::set& texturesInData); + } // namespace openspace::dataloader #endif // __OPENSPACE_CORE___CSVLOADER___H__ diff --git a/include/openspace/data/dataloader.h b/include/openspace/data/dataloader.h index 22101bb691..2296885f25 100644 --- a/include/openspace/data/dataloader.h +++ b/include/openspace/data/dataloader.h @@ -103,8 +103,8 @@ namespace data { Dataset loadFile(std::filesystem::path path, std::optional specs = std::nullopt); - std::optional loadCachedFile(std::filesystem::path path); - void saveCachedFile(const Dataset& dataset, std::filesystem::path path); + std::optional loadCachedFile(const std::filesystem::path& path); + void saveCachedFile(const Dataset& dataset, const std::filesystem::path& path); Dataset loadFileWithCache(std::filesystem::path path, std::optional specs = std::nullopt); @@ -116,8 +116,8 @@ namespace label { Labelset loadFile(std::filesystem::path path, std::optional specs = std::nullopt); - std::optional loadCachedFile(std::filesystem::path path); - void saveCachedFile(const Labelset& labelset, std::filesystem::path path); + std::optional loadCachedFile(const std::filesystem::path& path); + void saveCachedFile(const Labelset& labelset, const std::filesystem::path& path); Labelset loadFileWithCache(std::filesystem::path path); @@ -129,8 +129,8 @@ namespace color { ColorMap loadFile(std::filesystem::path path, std::optional specs = std::nullopt); - std::optional loadCachedFile(std::filesystem::path path); - void saveCachedFile(const ColorMap& colorMap, std::filesystem::path path); + std::optional loadCachedFile(const std::filesystem::path& path); + void saveCachedFile(const ColorMap& colorMap, const std::filesystem::path& path); ColorMap loadFileWithCache(std::filesystem::path path); diff --git a/include/openspace/data/datamapping.h b/include/openspace/data/datamapping.h index 5f2b98beb2..9504a78aab 100644 --- a/include/openspace/data/datamapping.h +++ b/include/openspace/data/datamapping.h @@ -41,10 +41,15 @@ struct DataMapping { bool hasExcludeColumns() const; bool isExcludeColumn(std::string_view column) const; + bool checkIfAllProvidedColumnsExist(const std::vector& columns) const; + std::optional xColumnName; std::optional yColumnName; std::optional zColumnName; std::optional nameColumn; + std::optional textureColumn; + + std::optional textureMap; std::optional missingDataValue; @@ -72,6 +77,8 @@ bool isColumnZ(const std::string& c, const std::optional& mapping); bool isNameColumn(const std::string& c, const std::optional& mapping); +bool isTextureColumn(const std::string& c, const std::optional& mapping); + } // namespace openspace::dataloader #endif // __OPENSPACE_CORE___DATAMAPPING___H__ diff --git a/include/openspace/documentation/verifier.h b/include/openspace/documentation/verifier.h index 20bc2d3a76..8b9d10ee90 100644 --- a/include/openspace/documentation/verifier.h +++ b/include/openspace/documentation/verifier.h @@ -954,7 +954,7 @@ public: * necessary to make the codegen work in all cases without complications there */ OrVerifier(const std::vector>> values); + std::shared_ptr>>& values); /** * Checks whether the \p dictionary contains the \p key and whether this key passes diff --git a/include/openspace/documentation/verifier.inl b/include/openspace/documentation/verifier.inl index 2e10417050..39ebc08663 100644 --- a/include/openspace/documentation/verifier.inl +++ b/include/openspace/documentation/verifier.inl @@ -378,13 +378,13 @@ TestResult InListVerifier::operator()(const ghoul::Dictionary& dict, std::string list = std::accumulate( values.begin() + 1, values.end(), - fmt::format("{}", values.front()), + std::format("{}", values.front()), [](std::string lhs, typename T::Type rhs) { - return fmt::format("{}, {}", lhs, rhs); + return std::format("{}, {}", lhs, rhs); } ); - o.explanation = fmt::format( - "{} not in list of accepted values '{}'", + o.explanation = std::format( + "'{}' not in list of accepted values '{}'", key, list ); r.offenses.push_back(o); diff --git a/include/openspace/engine/configuration.h b/include/openspace/engine/configuration.h index a7d2295deb..7bb5abeacc 100644 --- a/include/openspace/engine/configuration.h +++ b/include/openspace/engine/configuration.h @@ -47,7 +47,7 @@ struct Configuration { ghoul::Dictionary createDictionary(); - std::string windowConfiguration = "${CONFIG}/single.xml"; + std::string windowConfiguration = "${CONFIG}/single.json"; std::string asset; std::string profile; diff --git a/include/openspace/engine/downloadmanager.h b/include/openspace/engine/downloadmanager.h index 7143b4ee61..8549415175 100644 --- a/include/openspace/engine/downloadmanager.h +++ b/include/openspace/engine/downloadmanager.h @@ -104,15 +104,14 @@ public: OverrideFile overrideFile = OverrideFile::Yes, FailOnError failOnError = FailOnError::No, unsigned int timeout_secs = 0, DownloadFinishedCallback finishedCallback = DownloadFinishedCallback(), - DownloadProgressCallback progressCallback = DownloadProgressCallback() - ); + DownloadProgressCallback progressCallback = DownloadProgressCallback()) const; std::future fetchFile(const std::string& url, SuccessCallback successCallback = SuccessCallback(), ErrorCallback errorCallback = ErrorCallback()); - void getFileExtension(const std::string& url, - RequestFinishedCallback finishedCallback = RequestFinishedCallback()); + void fileExtension(const std::string& url, + RequestFinishedCallback finishedCallback = RequestFinishedCallback()) const; private: bool _useMultithreadedDownload; diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index a2ff32ee17..1bee159c44 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -96,12 +96,10 @@ public: void deinitializeGL(); void preSynchronization(); void postSynchronizationPreDraw(); - void viewportChanged(); void render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix); void drawOverlays(); void postDraw(); - void resetPropertyChangeFlags(); void keyboardCallback(Key key, KeyModifier mod, KeyAction action, IsGuiWindow isGuiWindow); void charCallback(unsigned int codepoint, KeyModifier modifier, @@ -118,7 +116,6 @@ public: void decode(std::vector data); properties::Property::Visibility visibility() const; - bool showHiddenSceneGraphNodes() const; void toggleShutdownMode(); Mode currentMode() const; @@ -148,11 +145,9 @@ private: void loadFonts(); void runGlobalCustomizationScripts(); - void resetPropertyChangeFlagsOfSubowners(openspace::properties::PropertyOwner* po); properties::BoolProperty _printEvents; properties::OptionProperty _visibility; - properties::BoolProperty _showHiddenSceneGraphNodes; properties::FloatProperty _fadeOnEnableDuration; properties::BoolProperty _disableAllMouseInputs; diff --git a/include/openspace/engine/windowdelegate.h b/include/openspace/engine/windowdelegate.h index aeb8462bd3..7bfda13217 100644 --- a/include/openspace/engine/windowdelegate.h +++ b/include/openspace/engine/windowdelegate.h @@ -114,7 +114,7 @@ struct WindowDelegate { uint64_t (*swapGroupFrameNumber)() = []() { return uint64_t(0); }; - void (*setScreenshotFolder)(std::string) = [](std::string) {}; + void (*setScreenshotFolder)(std::filesystem::path) = [](std::filesystem::path) {}; void (*showStatistics)(bool) = [](bool) {}; @@ -122,8 +122,8 @@ struct WindowDelegate { int (*currentNode)() = []() { return 0; }; - glm::vec2 (*mousePositionViewportRelative)(glm::vec2 mousePosition) = - [](glm::vec2) { return glm::vec2(0); }; + glm::vec2 (*mousePositionViewportRelative)(const glm::vec2& mousePosition) = + [](const glm::vec2&) { return glm::vec2(0); }; }; } // namespace openspace diff --git a/include/openspace/events/eventengine.h b/include/openspace/events/eventengine.h index a94a87e680..d6f01da10e 100644 --- a/include/openspace/events/eventengine.h +++ b/include/openspace/events/eventengine.h @@ -113,7 +113,7 @@ public: */ void unregisterEventAction(events::Event::Type type, const std::string& identifier, - std::optional filter = std::nullopt); + const std::optional& filter = std::nullopt); /** * Removing registration for a specific event identified by the \p identifier. diff --git a/include/openspace/interaction/camerainteractionstates.h b/include/openspace/interaction/camerainteractionstates.h index d2e267d751..efdceb476a 100644 --- a/include/openspace/interaction/camerainteractionstates.h +++ b/include/openspace/interaction/camerainteractionstates.h @@ -58,7 +58,7 @@ public: * Returns true if any of the velocities are larger than zero, i.e. wether an * interaction happened. */ - bool hasNonZeroVelocities(bool checkOnlyMovement = false); + bool hasNonZeroVelocities(bool checkOnlyMovement = false) const; protected: struct InteractionState { diff --git a/include/openspace/interaction/interpolator.inl b/include/openspace/interaction/interpolator.inl index f1c24eb068..d02bc0ec74 100644 --- a/include/openspace/interaction/interpolator.inl +++ b/include/openspace/interaction/interpolator.inl @@ -59,7 +59,7 @@ void Interpolator::setInterpolationTime(float interpolationTime) { template void Interpolator::step() { _t += _scaledDeltaTime; - _t = glm::clamp(_t, 0.0f, 1.0f); + _t = glm::clamp(_t, 0.f, 1.f); } template diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index c499cdff89..46cc3f6d7b 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -88,14 +88,14 @@ public: void updateStateFromInput( const JoystickInputStates& joystickInputStates, double deltaTime); - void setAxisMapping(std::string joystickName, int axis, AxisType mapping, + void setAxisMapping(const std::string& joystickName, int axis, AxisType mapping, AxisInvert shouldInvert = AxisInvert::No, JoystickType joystickType = JoystickType::JoystickLike, bool isSticky = false, AxisFlip shouldFlip = AxisFlip::No, double sensitivity = 0.0 ); - void setAxisMappingProperty(std::string joystickName, int axis, + void setAxisMappingProperty(const std::string& joystickName, int axis, std::string propertyUri, float min = 0.f, float max = 1.f, AxisInvert shouldInvert = AxisInvert::No, bool isRemote = true ); @@ -196,7 +196,7 @@ from_string(std::string_view string) if (string == "Pan Y") { return T::PanY; } if (string == "Property") { return T::Property; } - throw RuntimeError(fmt::format("Unknown axis type '{}'", string), "Joystick"); + throw RuntimeError(std::format("Unknown axis type '{}'", string), "Joystick"); } template <> @@ -220,7 +220,7 @@ from_string(std::string_view string) if (string == "JoystickLike") { return T::JoystickLike; } if (string == "TriggerLike") { return T::TriggerLike; } - throw RuntimeError(fmt::format("Unknown joystick type '{}'", string), "Joystick"); + throw RuntimeError(std::format("Unknown joystick type '{}'", string), "Joystick"); } } // namespace ghoul diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index 0370470589..9c7a182c3f 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -150,7 +150,7 @@ constexpr openspace::interaction::JoystickAction from_string(std::string_view st if (string == "Repeat") { return openspace::interaction::JoystickAction::Repeat; } if (string == "Release") { return openspace::interaction::JoystickAction::Release; } - throw RuntimeError(fmt::format("Unknown action '{}'", string)); + throw RuntimeError(std::format("Unknown action '{}'", string)); } } // namespace ghoul diff --git a/include/openspace/interaction/keybindingmanager.h b/include/openspace/interaction/keybindingmanager.h index 9e1865b769..3793387719 100644 --- a/include/openspace/interaction/keybindingmanager.h +++ b/include/openspace/interaction/keybindingmanager.h @@ -38,8 +38,6 @@ namespace openspace::interaction { class KeybindingManager { public: - KeybindingManager(); - void resetKeyBindings(); void bindKey(Key key, KeyModifier modifier, std::string action); diff --git a/include/openspace/interaction/mousecamerastates.h b/include/openspace/interaction/mousecamerastates.h index 252d2ecd7e..6015a2e495 100644 --- a/include/openspace/interaction/mousecamerastates.h +++ b/include/openspace/interaction/mousecamerastates.h @@ -36,8 +36,8 @@ class MouseCameraStates : public CameraInteractionStates { public: MouseCameraStates(double sensitivity, double velocityScaleFactor); - void updateStateFromInput(const MouseInputState& mouseinputState, - const KeyboardInputState& keyboardinputState, double deltaTime); + void updateStateFromInput(const MouseInputState& mouseState, + const KeyboardInputState& keyboardState, double deltaTime); void setInvertMouseButton(bool value); diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index da587cd4ef..1adfbce109 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -101,7 +101,7 @@ public: SessionRecording(); SessionRecording(bool isGlobal); - ~SessionRecording() override; + ~SessionRecording() override = default; /** * Used to de-initialize the session recording feature. Any recording or playback @@ -282,9 +282,9 @@ public: * Used to trigger a save of a script to the recording file, but only if a recording * is currently in progress. * - * \param scriptToSave String of the Lua command to be saved + * \param script String of the Lua command to be saved */ - void saveScriptKeyframeToTimeline(std::string scriptToSave); + void saveScriptKeyframeToTimeline(std::string script); /** * \return The Lua library that contains all Lua functions available to affect the @@ -305,7 +305,7 @@ public: * * \param callback Function handle for the callback */ - void removeStateChangeCallback(CallbackHandle callback); + void removeStateChangeCallback(CallbackHandle handle); /** * Provides list of available playback files. @@ -338,7 +338,7 @@ public: * \return `true` if data read has no errors */ bool readCameraKeyframeAscii(Timestamps& times, - datamessagestructures::CameraKeyframe& kf, std::string currentParsingLine, + datamessagestructures::CameraKeyframe& kf, const std::string& currentParsingLine, int lineN); /** @@ -365,7 +365,7 @@ public: * \return `true` if data read has no errors */ bool readTimeKeyframeAscii(Timestamps& times, - datamessagestructures::TimeKeyframe& kf, std::string currentParsingLine, + datamessagestructures::TimeKeyframe& kf, const std::string& currentParsingLine, int lineN); /** @@ -394,7 +394,7 @@ public: * \return `true` if data read has no errors */ bool readScriptKeyframeAscii(Timestamps& times, - datamessagestructures::ScriptMessage& kf, std::string currentParsingLine, + datamessagestructures::ScriptMessage& kf, const std::string& currentParsingLine, int lineN); /** @@ -482,7 +482,7 @@ public: * \param readLen_chars Number of characters to be read, which may be the expected * length of the header line, or an arbitrary number of characters within it */ - static std::string readHeaderElement(std::ifstream& stream, size_t readLen_chars); + static std::string readHeaderElement(std::ifstream& stream, size_t readLenChars); /** * Reads header information from a session recording file. @@ -491,7 +491,7 @@ public: * \param readLen_chars Number of characters to be read, which may be the expected * length of the header line, or an arbitrary number of characters within it */ - static std::string readHeaderElement(std::stringstream& stream, size_t readLen_chars); + static std::string readHeaderElement(std::stringstream& stream, size_t readLenChars); /** * Writes a header to a binary recording file buffer. @@ -520,7 +520,7 @@ public: * \param entry The ASCII string version of the keyframe (any type) * \param file `std::ofstream` object to write to */ - static void saveKeyframeToFile(std::string entry, std::ofstream& file); + static void saveKeyframeToFile(const std::string& entry, std::ofstream& file); /** * Checks if a specified recording file ends with a particular file extension. @@ -528,7 +528,8 @@ public: * \param filename The name of the file to record to * \param extension The file extension to check for */ - static bool hasFileExtension(std::string filename, std::string extension); + static bool hasFileExtension(const std::string& filename, + const std::string& extension); /** * Converts file format of a session recording file to the current format version @@ -589,7 +590,8 @@ public: * * \return pathname of the converted version of the file */ - std::string determineConversionOutFilename(const std::string filename, DataMode mode); + std::string determineConversionOutFilename(const std::string& filename, + DataMode mode); protected: properties::BoolProperty _renderPlaybackInformation; @@ -612,7 +614,7 @@ protected: double _timestampPlaybackStarted_application = 0.0; double _timestampPlaybackStarted_simulation = 0.0; double _timestampApplicationStarted_simulation = 0.0; - bool hasCameraChangedFromPrev(datamessagestructures::CameraKeyframe kfNew); + bool hasCameraChangedFromPrev(const datamessagestructures::CameraKeyframe& kfNew); double appropriateTimestamp(Timestamps t3stamps); double equivalentSimulationTime(double timeOs, double timeRec, double timeSim); double equivalentApplicationTime(double timeOs, double timeRec, double timeSim); @@ -620,7 +622,7 @@ protected: void recordCurrentTimeRate(); bool handleRecordingFile(std::string filenameIn); static bool isPath(std::string& filename); - void removeTrailingPathSlashes(std::string& filename); + void removeTrailingPathSlashes(std::string& filename) const; bool playbackCamera(); bool playbackTimeChange(); bool playbackScript(); @@ -629,10 +631,10 @@ protected: void handlePlaybackEnd(); bool findFirstCameraKeyframeInTimeline(); - Timestamps generateCurrentTimestamp3(double keyframeTime); + Timestamps generateCurrentTimestamp3(double keyframeTime) const; static void saveStringToFile(const std::string& s, unsigned char* kfBuffer, size_t& idx, std::ofstream& file); - static void saveKeyframeToFileBinary(unsigned char* bufferSource, size_t size, + static void saveKeyframeToFileBinary(unsigned char* buffer, size_t size, std::ofstream& file); bool addKeyframe(Timestamps t3stamps, @@ -675,7 +677,6 @@ protected: bool isPropertyAllowedForBaseline(const std::string& propString); unsigned int findIndexOfLastCameraKeyframeInTimeline(); bool doesTimelineEntryContainCamera(unsigned int index) const; - bool doesStartWithSubstring(const std::string& s, const std::string& matchSubstr); void trimCommandsFromScriptIfFound(std::string& script); void replaceCommandsFromScriptIfFound(std::string& script); @@ -689,20 +690,21 @@ protected: bool convertEntries(std::string& inFilename, std::stringstream& inStream, DataMode mode, int lineNum, std::ofstream& outFile); virtual bool convertCamera(std::stringstream& inStream, DataMode mode, int lineNum, - std::string& inputLine, std::ofstream& outFile, unsigned char* buff); + std::string& inputLine, std::ofstream& outFile, unsigned char* buffer); virtual bool convertTimeChange(std::stringstream& inStream, DataMode mode, - int lineNum, std::string& inputLine, std::ofstream& outFile, unsigned char* buff); + int lineNum, std::string& inputLine, std::ofstream& outFile, + unsigned char* buffer); virtual bool convertScript(std::stringstream& inStream, DataMode mode, int lineNum, - std::string& inputLine, std::ofstream& outFile, unsigned char* buff); - DataMode readModeFromHeader(std::string filename); + std::string& inputLine, std::ofstream& outFile, unsigned char* buffer); + DataMode readModeFromHeader(const std::string& filename); void readPlaybackHeader_stream(std::stringstream& conversionInStream, std::string& version, DataMode& mode); void populateListofLoadedSceneGraphNodes(); void checkIfScriptUsesScenegraphNode(std::string s); - bool checkForScenegraphNodeAccessScene(std::string& s); + bool checkForScenegraphNodeAccessScene(const std::string& s); bool checkForScenegraphNodeAccessNav(std::string& navTerm); - std::string extractScenegraphNodeFromScene(std::string& s); + std::string extractScenegraphNodeFromScene(const std::string& s); bool checkIfInitialFocusNodeIsLoaded(unsigned int firstCamIndex); std::string isolateTermFromQuotes(std::string s); void eraseSpacesFromString(std::string& s); diff --git a/include/openspace/interaction/tasks/convertrecformattask.h b/include/openspace/interaction/tasks/convertrecformattask.h index ddc1167934..be519c99f2 100644 --- a/include/openspace/interaction/tasks/convertrecformattask.h +++ b/include/openspace/interaction/tasks/convertrecformattask.h @@ -51,7 +51,6 @@ private: void convertToAscii(); void convertToBinary(); void determineFormatType(); - std::string addFileSuffix(const std::string& filePath, const std::string& suffix); std::filesystem::path _inFilePath; std::filesystem::path _outFilePath; std::ifstream _iFile; diff --git a/include/openspace/navigation/keyframenavigator.h b/include/openspace/navigation/keyframenavigator.h index 237a167eac..c9e2b8153d 100644 --- a/include/openspace/navigation/keyframenavigator.h +++ b/include/openspace/navigation/keyframenavigator.h @@ -69,8 +69,8 @@ public: * \return true only if a new future keyframe is available to set camera pose */ bool updateCamera(Camera& camera, bool ignoreFutureKeyframes); - static bool updateCamera(Camera* camera, const CameraPose prevPose, - const CameraPose nextPose, double t, bool ignoreFutureKeyframes); + static bool updateCamera(Camera* camera, const CameraPose& prevPose, + const CameraPose& nextPose, double t, bool ignoreFutureKeyframes); Timeline& timeline(); void addKeyframe(double timestamp, KeyframeNavigator::CameraPose pose); diff --git a/include/openspace/navigation/navigationhandler.h b/include/openspace/navigation/navigationhandler.h index 54f3068d31..3069ec0b1c 100644 --- a/include/openspace/navigation/navigationhandler.h +++ b/include/openspace/navigation/navigationhandler.h @@ -143,9 +143,9 @@ public: NavigationState navigationState(const SceneGraphNode& referenceFrame) const; void saveNavigationState(const std::filesystem::path& filepath, - const std::string& referenceFrameIdentifier); + const std::string& referenceFrameIdentifier) const; - void loadNavigationState(const std::string& filepath); + void loadNavigationState(const std::string& filepath, bool useTimeStamp); /** * Set camera state from a provided navigation state next frame. The actual position diff --git a/include/openspace/navigation/navigationstate.h b/include/openspace/navigation/navigationstate.h index 864e014d0a..cc4dc376a3 100644 --- a/include/openspace/navigation/navigationstate.h +++ b/include/openspace/navigation/navigationstate.h @@ -41,7 +41,8 @@ struct NavigationState { explicit NavigationState(const nlohmann::json& json); NavigationState(std::string anchor, std::string aim, std::string referenceFrame, glm::dvec3 position, std::optional up = std::nullopt, - double yaw = 0.0, double pitch = 0.0); + double yaw = 0.0, double pitch = 0.0, + std::optional timestamp = std::nullopt); CameraPose cameraPose() const; ghoul::Dictionary dictionary() const; @@ -55,6 +56,8 @@ struct NavigationState { std::optional up; double yaw = 0.0; double pitch = 0.0; + + std::optional timestamp; }; } // namespace openspace::interaction diff --git a/include/openspace/navigation/orbitalnavigator.h b/include/openspace/navigation/orbitalnavigator.h index 4da4639bc7..c5f1cd05ee 100644 --- a/include/openspace/navigation/orbitalnavigator.h +++ b/include/openspace/navigation/orbitalnavigator.h @@ -274,8 +274,8 @@ private: * from the global to the current total rotation so that * `cameraRotation = globalRotation * localRotation`. */ - CameraRotationDecomposition decomposeCameraRotationSurface(const CameraPose pose, - const SceneGraphNode& reference); + CameraRotationDecomposition decomposeCameraRotationSurface( + const CameraPose& cameraPose, const SceneGraphNode& reference); /** * Decomposes the camera's rotation in to a global and a local rotation defined by @@ -285,22 +285,23 @@ private: * The local rotation defines the differential from the global to the current total * rotation so that `cameraRotation = globalRotation * localRotation`. */ - CameraRotationDecomposition decomposeCameraRotation(const CameraPose pose, - glm::dvec3 reference); + CameraRotationDecomposition decomposeCameraRotation(const CameraPose& cameraPose, + const glm::dvec3& reference); /** * Composes a pair of global and local rotations into a quaternion that can be used as * the world rotation for a camera. */ - glm::dquat composeCameraRotation(const CameraRotationDecomposition& composition); + glm::dquat composeCameraRotation( + const CameraRotationDecomposition& decomposition) const; /** * Moves and rotates the camera around the anchor node in order to maintain the screen * space position of the aim node. Also interpolates to the aim node, when retargeting * the aim. */ - CameraPose followAim(CameraPose pose, glm::dvec3 cameraToAnchor, - Displacement anchorToAim); + CameraPose followAim(CameraPose pose, const glm::dvec3& cameraToAnchor, + const Displacement& anchorToAim); /** * Perform a camera roll on the local camera rotation. @@ -325,8 +326,8 @@ private: glm::dquat interpolateLocalRotation(double deltaTime, const glm::dquat& localCameraRotation); - Displacement interpolateRetargetAim(double deltaTime, CameraPose pose, - glm::dvec3 cameraToAnchor, Displacement anchorToAim); + Displacement interpolateRetargetAim(double deltaTime, const CameraPose& pose, + const glm::dvec3& prevCameraToAnchor, Displacement anchorToAim); double interpolateCameraToSurfaceDistance(double deltaTime, double currentDistance, double targetDistance); @@ -354,12 +355,12 @@ private: /** * Adds rotation to the camera position so that it follows the rotation of the anchor - * node defined by the differential \p anchorNodeRotationDiff. + * node defined by the differential \p focusNodeRotationDiff. * * \return A position updated with the rotation defined by \p anchorNodeRotationDiff */ glm::dvec3 followAnchorNodeRotation(const glm::dvec3& cameraPosition, - const glm::dvec3& objectPosition, const glm::dquat& anchorNodeRotationDiff) const; + const glm::dvec3& objectPosition, const glm::dquat& focusNodeRotationDiff) const; /** * Updates the global rotation so that it points towards the anchor node. @@ -367,7 +368,7 @@ private: * \return A global rotation quaternion defining a rotation towards the anchor node */ glm::dquat rotateGlobally(const glm::dquat& globalCameraRotation, - const glm::dquat& aimNodeRotationDiff, + const glm::dquat& focusNodeRotationDiff, const SurfacePositionHandle& positionHandle) const; /** @@ -410,12 +411,6 @@ private: glm::dvec3 cameraToSurfaceVector(const glm::dvec3& cameraPos, const glm::dvec3& centerPos, const SurfacePositionHandle& posHandle); - /** - * Calculates a SurfacePositionHandle given a camera position in world space. - */ - SurfacePositionHandle calculateSurfacePositionHandle(const SceneGraphNode& node, - const glm::dvec3& cameraPositionWorldSpace) const; - void resetIdleBehavior(); /** @@ -451,7 +446,7 @@ private: * \param position The position of the camera. Will be changed by the function * \param globalRotation The camera's global rotation. Will be changed by the function */ - void orbitAroundAxis(const glm::dvec3 axis, double angle, glm::dvec3& position, + void orbitAroundAxis(const glm::dvec3& axis, double angle, glm::dvec3& position, glm::dquat& globalRotation); double rotationSpeedScaleFromCameraHeight(const glm::dvec3& cameraPosition, diff --git a/include/openspace/navigation/pathcurve.h b/include/openspace/navigation/pathcurve.h index 4cda795d06..c5aea40b02 100644 --- a/include/openspace/navigation/pathcurve.h +++ b/include/openspace/navigation/pathcurve.h @@ -36,11 +36,11 @@ class Waypoint; class PathCurve { public: struct InsufficientPrecisionError : public ghoul::RuntimeError { - explicit InsufficientPrecisionError(std::string msg); + explicit InsufficientPrecisionError(std::string error); }; struct TooShortPathError : public ghoul::RuntimeError { - explicit TooShortPathError(std::string msg); + explicit TooShortPathError(std::string error); }; virtual ~PathCurve() = 0; diff --git a/include/openspace/navigation/pathnavigator.h b/include/openspace/navigation/pathnavigator.h index 83ced28727..c2db18ff0e 100644 --- a/include/openspace/navigation/pathnavigator.h +++ b/include/openspace/navigation/pathnavigator.h @@ -105,7 +105,7 @@ private: */ void findRelevantNodes(); - void removeRollRotation(CameraPose& pose); + void removeRollRotation(CameraPose& pose) const; std::unique_ptr _currentPath = nullptr; bool _isPlaying = false; diff --git a/include/openspace/navigation/waypoint.h b/include/openspace/navigation/waypoint.h index 373cb07804..a6cdb9d30e 100644 --- a/include/openspace/navigation/waypoint.h +++ b/include/openspace/navigation/waypoint.h @@ -39,7 +39,7 @@ struct NavigationState; class Waypoint { public: Waypoint() = default; - Waypoint(const glm::dvec3& pos, const glm::dquat& rot, const std::string& ref); + Waypoint(const glm::dvec3& pos, const glm::dquat& rot, std::string ref); explicit Waypoint(const NavigationState& ns); CameraPose pose() const; @@ -92,7 +92,7 @@ struct NodeCameraStateSpec { * \return The computed WayPoint */ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec, - std::optional startPoint = std::nullopt, bool useLinear = false); + const std::optional& startPoint = std::nullopt, bool useLinear = false); } // namespace openspace::interaction diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index ff20ee9425..0cbc6281b0 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -49,8 +49,8 @@ struct CameraKeyframe { CameraKeyframe(const std::vector& buffer) { deserialize(buffer); } - CameraKeyframe(glm::dvec3&& pos, glm::dquat&& rot, std::string&& focusNode, - bool&& followNodeRot, float&& scale) + CameraKeyframe(glm::dvec3 pos, glm::dquat rot, std::string focusNode, + bool followNodeRot, float scale) : _position(pos) , _rotation(rot) , _followNodeRotation(followNodeRot) @@ -407,7 +407,7 @@ struct ScriptMessage { if (buffer.size() != (sizeof(uint32_t) + len)) { LERRORC( "ParallelPeer", - fmt::format( + std::format( "Received buffer with wrong size. Expected {} got {}", len, buffer.size() ) @@ -467,7 +467,7 @@ struct ScriptMessage { } std::string tmpReadbackScript; _script.erase(); - for (int i = 0; i < numScriptLines; ++i) { + for (int i = 0; i < numScriptLines; i++) { std::getline(iss, tmpReadbackScript); size_t start = tmpReadbackScript.find_first_not_of(" "); tmpReadbackScript = tmpReadbackScript.substr(start); diff --git a/include/openspace/network/parallelconnection.h b/include/openspace/network/parallelconnection.h index a633f3ab89..60f67b7172 100644 --- a/include/openspace/network/parallelconnection.h +++ b/include/openspace/network/parallelconnection.h @@ -61,7 +61,7 @@ public: struct DataMessage { DataMessage() = default; - DataMessage(datamessagestructures::Type t, double timestamp, std::vector c); + DataMessage(datamessagestructures::Type t, double time, std::vector c); datamessagestructures::Type type; double timestamp; @@ -70,7 +70,7 @@ public: class ConnectionLostError : public ghoul::RuntimeError { public: - explicit ConnectionLostError(bool shouldLogError = true); + explicit ConnectionLostError(bool shouldLogError_ = true); bool shouldLogError; }; diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index ce87cd47b0..284b821e35 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -110,7 +110,7 @@ void NumericalProperty::setExponent(float exponent) { if (!isValidRange(_minimumValue, _maximumValue)) { LWARNINGC( "NumericalProperty: setExponent", - fmt::format( + std::format( "Setting exponent for properties with negative values in " "[min, max] range is not yet supported. Property: {}", this->fullyQualifiedIdentifier() diff --git a/include/openspace/properties/selectionproperty.h b/include/openspace/properties/selectionproperty.h index 225fb6f69e..99363069dc 100644 --- a/include/openspace/properties/selectionproperty.h +++ b/include/openspace/properties/selectionproperty.h @@ -122,7 +122,7 @@ protected: private: void sortOptions(); - bool removeInvalidKeys(std::set& keys); + bool removeInvalidKeys(std::set& keys) const; std::string generateAdditionalJsonDescription() const override; diff --git a/include/openspace/rendering/colormappingcomponent.h b/include/openspace/rendering/colormappingcomponent.h index 6443a46975..fb7881819e 100644 --- a/include/openspace/rendering/colormappingcomponent.h +++ b/include/openspace/rendering/colormappingcomponent.h @@ -22,8 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ -#ifndef __OPENSPACE_CORE___COLORMAPCOMPONENT___H__ -#define __OPENSPACE_CORE___COLORMAPCOMPONENT___H__ +#ifndef __OPENSPACE_CORE___COLORMAPPINGCOMPONENT___H__ +#define __OPENSPACE_CORE___COLORMAPPINGCOMPONENT___H__ #include @@ -74,7 +74,7 @@ public: static documentation::Documentation Documentation(); - glm::vec4 colorFromColorMap(float value) const; + glm::vec4 colorFromColorMap(float valueToColorFrom) const; properties::BoolProperty enabled; properties::BoolProperty invert; @@ -120,4 +120,4 @@ private: } // namespace openspace -#endif // __OPENSPACE_CORE___COLORMAPCOMPONENT___H__ +#endif // __OPENSPACE_CORE___COLORMAPPINGCOMPONENT___H__ diff --git a/include/openspace/rendering/dashboarditem.h b/include/openspace/rendering/dashboarditem.h index 6c278ae8a4..1f8c4ef72c 100644 --- a/include/openspace/rendering/dashboarditem.h +++ b/include/openspace/rendering/dashboarditem.h @@ -41,7 +41,7 @@ public: static documentation::Documentation Documentation(); static std::unique_ptr createFromDictionary( - ghoul::Dictionary dictionary + const ghoul::Dictionary& dictionary ); DashboardItem(const ghoul::Dictionary& dictionary); diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 8e6fbe075e..1fae1d86ef 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -156,9 +156,7 @@ public: void setResolution(glm::ivec2 res); void setHDRExposure(float hdrExposure); void setGamma(float gamma); - void setHue(float hue); - void setValue(float value); - void setSaturation(float sat); + void setHueValueSaturation(float hue, float value, float saturation); void enableFXAA(bool enable); void setDisableHDR(bool disable); @@ -193,7 +191,7 @@ private: void resolveMSAA(float blackoutFactor); void applyTMO(float blackoutFactor, const glm::ivec4& viewport); void applyFXAA(const glm::ivec4& viewport); - void updateDownscaleTextures(); + void updateDownscaleTextures() const; void updateExitVolumeTextures(); void writeDownscaledVolume(const glm::ivec4& viewport); diff --git a/include/openspace/rendering/helper.h b/include/openspace/rendering/helper.h index c66f132a84..29146c70fb 100644 --- a/include/openspace/rendering/helper.h +++ b/include/openspace/rendering/helper.h @@ -146,12 +146,12 @@ VertexXYZ convertToXYZ(const Vertex& v); std::vector convert(std::vector v); std::vector createRing(int nSegments, float radius, - glm::vec4 colors = glm::vec4(1.f)); + const glm::vec4& colors = glm::vec4(1.f)); std::vector createRingXYZ(int nSegments, float radius); VertexIndexListCombo -createSphere(int nSegments, glm::vec3 radii, glm::vec4 colors = glm::vec4(1.f)); +createSphere(int nSegments, glm::vec3 radii, const glm::vec4& colors = glm::vec4(1.f)); VertexIndexListCombo createCylinder(unsigned int nSegments, float radius, float height); diff --git a/include/openspace/rendering/luaconsole.h b/include/openspace/rendering/luaconsole.h index e9913bf4dd..efce7f5a9b 100644 --- a/include/openspace/rendering/luaconsole.h +++ b/include/openspace/rendering/luaconsole.h @@ -46,7 +46,7 @@ namespace openspace { class LuaConsole : public properties::PropertyOwner { public: LuaConsole(); - ~LuaConsole() override; + ~LuaConsole() override = default; void initialize(); void deinitialize(); @@ -62,8 +62,7 @@ public: private: void parallelConnectionChanged(const ParallelConnection::Status& status); - - void addToCommand(std::string c); + void addToCommand(const std::string& c); properties::BoolProperty _isVisible; properties::BoolProperty _shouldBeSynchronized; diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index 542304e3b1..747c58852e 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -71,7 +71,7 @@ public: }; static ghoul::mm_unique_ptr createFromDictionary( - ghoul::Dictionary dictionary); + const ghoul::Dictionary& dictionary); Renderable(const ghoul::Dictionary& dictionary, RenderableSettings settings = RenderableSettings()); @@ -175,7 +175,7 @@ protected: * \return The resulting model view transformation matrix in double precision */ glm::dmat4 calcModelViewTransform(const RenderData& data, - std::optional modelTransform = std::nullopt) const; + const std::optional& modelTransform = std::nullopt) const; /** * Calculates the model view projection transformation matrix with the given data and @@ -189,7 +189,7 @@ protected: * precision */ glm::dmat4 calcModelViewProjectionTransform(const RenderData& data, - std::optional modelTransform = std::nullopt) const; + const std::optional& modelTransform = std::nullopt) const; /** * Calculates the model, model view, and the model view projection transformation diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index d25ad372c3..f4806efd97 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -103,11 +103,12 @@ public: std::unique_ptr buildRenderProgram( const std::string& name, const std::filesystem::path& vsPath, - std::filesystem::path fsPath, ghoul::Dictionary data = ghoul::Dictionary()); + const std::filesystem::path& fsPath, + ghoul::Dictionary data = ghoul::Dictionary()); std::unique_ptr buildRenderProgram( const std::string& name, const std::filesystem::path& vsPath, - std::filesystem::path fsPath, const std::filesystem::path& csPath, + const std::filesystem::path& fsPath, const std::filesystem::path& csPath, ghoul::Dictionary data = ghoul::Dictionary()); void removeRenderProgram(ghoul::opengl::ProgramObject* program); @@ -164,7 +165,7 @@ private: void renderVersionInformation(); void renderCameraInformation(); void renderShutdownInformation(float timer, float fullTime); - void renderDashboard(); + void renderDashboard() const; float combinedBlackoutFactor() const; Camera* _camera = nullptr; diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index 916c060b60..bdba579e20 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -82,7 +82,7 @@ public: glm::vec2 screenSpaceDimensions(); glm::vec2 upperRightCornerScreenSpace(); glm::vec2 lowerLeftCornerScreenSpace(); - bool isIntersecting(glm::vec2 coord); + bool isIntersecting(const glm::vec2& coord); void translate(glm::vec2 translation, glm::vec2 position); void setCartesianPosition(const glm::vec3& position); void setRaeFromCartesianPosition(const glm::vec3& position); @@ -102,13 +102,13 @@ protected: glm::vec3 raeToCartesian(const glm::vec3& rae) const; glm::vec3 cartesianToRae(const glm::vec3& cartesian) const; - void draw(glm::mat4 modelTransform, float blackoutFactor); + void draw(const glm::mat4& modelTransform, float blackoutFactor); virtual void bindTexture() = 0; virtual void unbindTexture(); - glm::vec3 sphericalToRae(glm::vec3 spherical) const; - glm::vec3 raeToSpherical(glm::vec3 rae) const; + glm::vec3 sphericalToRae(const glm::vec3& spherical) const; + glm::vec3 raeToSpherical(const glm::vec3& rae) const; glm::vec3 cartesianToSpherical(const glm::vec3& cartesian) const; glm::vec3 sphericalToCartesian(glm::vec3 spherical) const; glm::vec3 sanitizeSphericalCoordinates(glm::vec3 spherical) const; diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index da9575ae51..25949e67d9 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -136,15 +136,11 @@ public: float downscaleRender() const; private: - /** - * Maximum number of integration steps to be executed by the volume integrator. - */ + /// Maximum number of integration steps to be executed by the volume integrator int _rayCastMaxSteps = 1000; - /** - * Enable and set the downscale rendering of the volume. Used to improve performance. - */ - float _downscaleRenderConst = 1.0f; + /// Enable and set the downscale rendering of the volume. Used to improve performance + float _downscaleRenderConst = 1.f; }; } // namespace openspace diff --git a/include/openspace/scene/asset.h b/include/openspace/scene/asset.h index e59027b18e..5e35c9e148 100644 --- a/include/openspace/scene/asset.h +++ b/include/openspace/scene/asset.h @@ -215,14 +215,14 @@ public: void deinitialize(); /** - * Marks the passed \p child as being required by this Asset. If the \p child is - * already required by this asset, this function does nothing. + * Marks the passed \p dependency as being required by this Asset. If the + * \p dependency is already required by this asset, this function does nothing. * - * \param child The asset that is required by this asset + * \param dependency The asset that is required by this asset * - * \pre \p child must not be nullptr + * \pre \p dependency must not be nullptr */ - void require(Asset* child); + void require(Asset* dependency); /** * Returns `true` if the loading of the Asset has failed in any way so that diff --git a/include/openspace/scene/assetmanager.h b/include/openspace/scene/assetmanager.h index 0410b82382..88ee16636d 100644 --- a/include/openspace/scene/assetmanager.h +++ b/include/openspace/scene/assetmanager.h @@ -83,7 +83,7 @@ public: */ void update(); - scripting::LuaLibrary luaLibrary(); + static scripting::LuaLibrary luaLibrary(); /** * Returns all assets that have been loaded by the AssetManager. The order of the diff --git a/include/openspace/scene/profile.h b/include/openspace/scene/profile.h index 13ca783062..f745be9aed 100644 --- a/include/openspace/scene/profile.h +++ b/include/openspace/scene/profile.h @@ -46,7 +46,7 @@ public: struct ParsingError : public ghoul::RuntimeError { enum class Severity { Info, Warning, Error }; - explicit ParsingError(Severity severity, std::string msg); + explicit ParsingError(Severity severity_, std::string msg); Severity severity; }; diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index 7625abdf07..e7c10db589 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -241,7 +241,7 @@ public: * \return Vector of Property objs containing property names that matched the regex */ std::vector propertiesMatchingRegex( - std::string propertyString); + const std::string& propertyString); /** * Returns a list of all unique tags that are used in the currently loaded scene. @@ -305,7 +305,6 @@ private: * Update dependencies. */ void updateNodeRegistry(); - std::chrono::steady_clock::time_point currentTimeForInterpolation(); void sortTopologically(); std::unique_ptr _camera; @@ -313,7 +312,7 @@ private: std::vector _circularNodes; std::unordered_map _nodesByIdentifier; bool _dirtyNodeRegistry = false; - SceneGraphNode _rootDummy; + SceneGraphNode _rootNode; std::unique_ptr _initializer; std::string _profilePropertyName; bool _valueIsTable = false; diff --git a/include/openspace/scene/scenegraphnode.h b/include/openspace/scene/scenegraphnode.h index 390e5455bf..dc269e07e8 100644 --- a/include/openspace/scene/scenegraphnode.h +++ b/include/openspace/scene/scenegraphnode.h @@ -74,7 +74,6 @@ public: BooleanType(UpdateScene); - static constexpr const char* RootNodeIdentifier = "Root"; static constexpr std::string_view KeyIdentifier = "Identifier"; static constexpr std::string_view KeyParentName = "Parent"; static constexpr std::string_view KeyDependencies = "Dependencies"; @@ -141,7 +140,7 @@ public: bool supportsDirectInteraction() const; - SceneGraphNode* childNode(const std::string& identifier); + SceneGraphNode* childNode(const std::string& id); const Renderable* renderable() const; Renderable* renderable(); @@ -156,7 +155,7 @@ private: glm::dmat3 calculateWorldRotation() const; glm::dvec3 calculateWorldScale() const; void computeScreenSpaceData(RenderData& newData); - void renderDebugSphere(const Camera& camera, double size, glm::vec4 color); + void renderDebugSphere(const Camera& camera, double size, const glm::vec4& color); std::atomic _state = State::Loaded; std::vector> _children; diff --git a/include/openspace/scripting/scriptengine.h b/include/openspace/scripting/scriptengine.h index ba9140186e..7041c7514c 100644 --- a/include/openspace/scripting/scriptengine.h +++ b/include/openspace/scripting/scriptengine.h @@ -83,7 +83,8 @@ public: void addLibrary(LuaLibrary library); bool hasLibrary(const std::string& name); - bool runScript(const std::string& script, ScriptCallback callback = ScriptCallback()); + bool runScript(const std::string& script, + const ScriptCallback& callback = ScriptCallback()); bool runScriptFile(const std::filesystem::path& filename); virtual void preSync(bool isMaster) override; @@ -92,7 +93,8 @@ public: virtual void postSync(bool isMaster) override; void queueScript(std::string script, ShouldBeSynchronized shouldBeSynchronized, - ShouldSendToRemote shouldSendToRemote, ScriptCallback cb = ScriptCallback()); + ShouldSendToRemote shouldSendToRemote, + ScriptCallback callback = ScriptCallback()); std::vector allLuaFunctions() const; const std::vector& allLuaLibraries() const; diff --git a/include/openspace/util/blockplaneintersectiongeometry.h b/include/openspace/util/blockplaneintersectiongeometry.h index d8e5e353d9..f2f7706e17 100644 --- a/include/openspace/util/blockplaneintersectiongeometry.h +++ b/include/openspace/util/blockplaneintersectiongeometry.h @@ -42,7 +42,7 @@ public: void render(); void setBlockSize(glm::vec3 size); - void setPlane(glm::vec3 normal, float distance); + void setPlane(const glm::vec3& normal, float distance); private: void updateVertices(); diff --git a/include/openspace/util/boxgeometry.h b/include/openspace/util/boxgeometry.h index 7ce4d836d5..75139b2ea0 100644 --- a/include/openspace/util/boxgeometry.h +++ b/include/openspace/util/boxgeometry.h @@ -37,7 +37,7 @@ public: ~BoxGeometry(); bool initialize(); - void render(); + void render() const; GLuint _vaoId = 0; GLuint _vBufferId = 0; diff --git a/include/openspace/util/collisionhelper.h b/include/openspace/util/collisionhelper.h index 55758fbcfc..edcf09a47f 100644 --- a/include/openspace/util/collisionhelper.h +++ b/include/openspace/util/collisionhelper.h @@ -45,8 +45,8 @@ namespace openspace::collision { * \return True if the line between \p p1 and \p p2 intersects the sphere given by * \p r and \p center, and false otherwise */ -bool lineSphereIntersection(glm::dvec3 p1, glm::dvec3 p2, glm::dvec3 center, - double r, glm::dvec3& intersectionPoint); +bool lineSphereIntersection(const glm::dvec3& p1, const glm::dvec3& p2, + const glm::dvec3& center, double r, glm::dvec3& intersectionPoint); /** * Check if the point \p p is inside of the sphere defined by radius \p r and center diff --git a/include/openspace/util/distanceconversion.h b/include/openspace/util/distanceconversion.h index 11a2dd196a..d968f94845 100644 --- a/include/openspace/util/distanceconversion.h +++ b/include/openspace/util/distanceconversion.h @@ -218,7 +218,7 @@ constexpr DistanceUnit distanceUnitFromString(std::string_view unitName) { found = i; break; } - ++i; + i++; } i = 0; @@ -227,7 +227,7 @@ constexpr DistanceUnit distanceUnitFromString(std::string_view unitName) { found = i; break; } - ++i; + i++; } diff --git a/include/openspace/util/factorymanager.h b/include/openspace/util/factorymanager.h index ca9184833f..69af7fc621 100644 --- a/include/openspace/util/factorymanager.h +++ b/include/openspace/util/factorymanager.h @@ -100,7 +100,7 @@ public: * * \tparam Factory The type for which a factory should be created and added * \param name A user-readable name for the registered factory - * * + * * \pre \p name must not be empty */ template diff --git a/include/openspace/util/histogram.h b/include/openspace/util/histogram.h index 67e1f26d7a..63e2cdbf62 100644 --- a/include/openspace/util/histogram.h +++ b/include/openspace/util/histogram.h @@ -51,7 +51,7 @@ public: * \param repeat How many times you want to insert it * \return Returns `true` if succesful insertion, otherwise return `false` */ - bool add(float value, float repeat = 1.0f); + bool add(float value, float repeat = 1.f); bool add(const Histogram& histogram); bool addRectangle(float lowBin, float highBin, float value); @@ -69,7 +69,7 @@ public: std::vector getBinaryData() const; float highestBinValue(bool equalized, int overBins=0); - float binWidth(); + float binWidth() const; void changeRange(float minValue, float maxValue); diff --git a/include/openspace/util/json_helper.inl b/include/openspace/util/json_helper.inl index 62a2511c1c..62a4c96f9b 100644 --- a/include/openspace/util/json_helper.inl +++ b/include/openspace/util/json_helper.inl @@ -72,21 +72,21 @@ std::string formatJson(T value) { } else if constexpr (internal::isGlmVector()) { std::string values; - for (glm::length_t i = 0; i < ghoul::glm_components::value; ++i) { + for (glm::length_t i = 0; i < ghoul::glm_components::value; i++) { values += std::to_string(value[i]) + ','; } values.pop_back(); - return fmt::format("[{}]", values); + return std::format("[{}]", values); } else if constexpr (internal::isGlmMatrix()) { std::string values; - for (glm::length_t i = 0; i < T::type::row_type::length(); ++i) { - for (glm::length_t j = 0; j < T::type::col_type::length(); ++j) { + for (glm::length_t i = 0; i < T::type::row_type::length(); i++) { + for (glm::length_t j = 0; j < T::type::col_type::length(); j++) { values += std::to_string(value[i][j]) + ','; } } values.pop_back(); - return fmt::format("[{}]", values); + return std::format("[{}]", values); } else { static_assert(sizeof(T) == 0, "JSON formatting of type T not implemented"); diff --git a/include/openspace/util/keys.h b/include/openspace/util/keys.h index fef5f98832..3c03b701cf 100644 --- a/include/openspace/util/keys.h +++ b/include/openspace/util/keys.h @@ -400,7 +400,7 @@ constexpr inline bool isKeypadKey(Key key) noexcept { key == Key::KeypadDivide; } -KeyWithModifier stringToKey(std::string str); +KeyWithModifier stringToKey(const std::string& str); std::string keyToString(KeyWithModifier keyWithModifier); // @TODO (abock, 2021-08-12) This function should die @@ -430,7 +430,7 @@ template <> std::string to_string(const openspace::KeyModifier& mod); template <> -std::string to_string(const openspace::KeyWithModifier& key); +std::string to_string(const openspace::KeyWithModifier& keyMod); } // namespace ghoul diff --git a/include/openspace/util/planegeometry.h b/include/openspace/util/planegeometry.h index 7f05480ff1..398214ee4d 100644 --- a/include/openspace/util/planegeometry.h +++ b/include/openspace/util/planegeometry.h @@ -39,7 +39,7 @@ public: void initialize(); void deinitialize(); - void render(); + void render() const; void updateSize(const glm::vec2& size); void updateSize(const float size); diff --git a/include/openspace/util/sphere.h b/include/openspace/util/sphere.h index f8c8529d8f..cf23199e82 100644 --- a/include/openspace/util/sphere.h +++ b/include/openspace/util/sphere.h @@ -39,7 +39,7 @@ public: bool initialize(); - void render(); + void render() const; //private: struct Vertex { diff --git a/include/openspace/util/spicemanager.h b/include/openspace/util/spicemanager.h index 5c2a362275..bd01734f9d 100644 --- a/include/openspace/util/spicemanager.h +++ b/include/openspace/util/spicemanager.h @@ -524,7 +524,7 @@ public: * specific spacecraft * \pre \p craft must not be empty */ - double spacecraftClockToET(const std::string& craft, double craftTicks); + double spacecraftClockToET(const std::string& craft, double craftTicks) const; /** * Converts the \p timeString representing a date to a double precision value @@ -578,7 +578,7 @@ public: timout_c(ephemerisTime, format, bufferSize, outBuf); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error converting ephemeris time '{}' to date with format '{}'", ephemerisTime, format )); @@ -1122,6 +1122,12 @@ private: */ void loadLeapSecondsSpiceKernel(); + /** + * Loads pre defined geophysical constants kernel (geophysical.ker) + */ + void loadGeophysicalConstantsKernel(); + + /// A list of all loaded kernels std::vector _loadedKernels; diff --git a/include/openspace/util/syncbuffer.h b/include/openspace/util/syncbuffer.h index b0160bbc46..16fe46215a 100644 --- a/include/openspace/util/syncbuffer.h +++ b/include/openspace/util/syncbuffer.h @@ -36,7 +36,7 @@ class SyncBuffer { public: SyncBuffer(size_t n); - ~SyncBuffer(); + ~SyncBuffer() = default; void encode(const std::string& s); diff --git a/include/openspace/util/taskloader.h b/include/openspace/util/taskloader.h index 6bdee46d17..752fee1329 100644 --- a/include/openspace/util/taskloader.h +++ b/include/openspace/util/taskloader.h @@ -38,7 +38,7 @@ class Task; class TaskLoader { public: std::vector> tasksFromDictionary( - const ghoul::Dictionary& tasksDictionary); + const ghoul::Dictionary& dictionary); std::vector> tasksFromFile(const std::string& path); }; diff --git a/include/openspace/util/time.h b/include/openspace/util/time.h index e9a1cbda30..5af42816b7 100644 --- a/include/openspace/util/time.h +++ b/include/openspace/util/time.h @@ -166,7 +166,7 @@ public: * (M)onths, and (y)ears as units and an optional - sign to move backwards in time. * The return value is in the form of an ISO 8601 date string. */ - static std::string advancedTime(std::string base, std::string change); + static std::string advancedTime(const std::string& base, std::string change); /** * Returns the Lua library that contains all Lua functions available to change the diff --git a/include/openspace/util/timeconversion.h b/include/openspace/util/timeconversion.h index b09dbcb4fd..2fa2bbdb63 100644 --- a/include/openspace/util/timeconversion.h +++ b/include/openspace/util/timeconversion.h @@ -144,7 +144,7 @@ constexpr TimeUnit timeUnitFromString(std::string_view unitName) { found = i; break; } - ++i; + i++; } i = 0; @@ -153,7 +153,7 @@ constexpr TimeUnit timeUnitFromString(std::string_view unitName) { found = i; break; } - ++i; + i++; } if (found != -1) { diff --git a/include/openspace/util/timeline.h b/include/openspace/util/timeline.h index 39c9a10c76..fb6c29aba5 100644 --- a/include/openspace/util/timeline.h +++ b/include/openspace/util/timeline.h @@ -35,6 +35,8 @@ namespace openspace { * Base class for keyframes. */ struct KeyframeBase { + KeyframeBase(size_t id_, double timestamp_); + size_t id; double timestamp; }; diff --git a/include/openspace/util/timeline.inl b/include/openspace/util/timeline.inl index ea047bc48e..df9f1fe4a9 100644 --- a/include/openspace/util/timeline.inl +++ b/include/openspace/util/timeline.inl @@ -26,7 +26,7 @@ namespace openspace { template Keyframe::Keyframe(size_t i, double t, T d) - : KeyframeBase{ i, t } + : KeyframeBase(i, t) , data(std::move(d)) {} diff --git a/include/openspace/util/timemanager.h b/include/openspace/util/timemanager.h index e0a5265db4..da1775b6a7 100644 --- a/include/openspace/util/timemanager.h +++ b/include/openspace/util/timemanager.h @@ -98,8 +98,8 @@ public: void interpolateTime(double targetTime, double durationSeconds); void interpolateTimeRelative(double delta, double durationSeconds); - void interpolateDeltaTime(double targetDeltaTime, double durationSeconds); - void interpolatePause(bool pause, double durationSeconds); + void interpolateDeltaTime(double newDeltaTime, double interpolationDuration); + void interpolatePause(bool pause, double interpolationDuration); std::optional nextDeltaTimeStep(); std::optional previousDeltaTimeStep(); @@ -110,7 +110,7 @@ public: void interpolateNextDeltaTimeStep(double durationSeconds); void interpolatePreviousDeltaTimeStep(double durationSeconds); - void addKeyframe(double timestamp, TimeKeyframeData kf); + void addKeyframe(double timestamp, TimeKeyframeData time); void removeKeyframesBefore(double timestamp, bool inclusive = false); void removeKeyframesAfter(double timestamp, bool inclusive = false); diff --git a/include/openspace/util/touch.h b/include/openspace/util/touch.h index 9b4773810d..7697a6077b 100644 --- a/include/openspace/util/touch.h +++ b/include/openspace/util/touch.h @@ -39,7 +39,7 @@ namespace openspace { */ struct TouchInput { TouchInput(size_t touchDeviceId, size_t fingerId, float x, float y, double timestamp); - glm::vec2 screenCoordinates(glm::vec2 resolution) const; + glm::vec2 screenCoordinates(const glm::vec2& resolution) const; glm::vec2 currentWindowCoordinates() const; bool isMoving() const; float distanceToPos(float otherX, float otherY) const; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 9f5ee33b0d..0bcf5b29e5 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -112,14 +112,14 @@ namespace { } } - bool isAtmosphereInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position, + bool isAtmosphereInFrustum(const glm::dmat4& mv, const glm::dvec3& position, double radius) { // Frustum Planes - glm::dvec3 col1 = glm::dvec3(MVMatrix[0][0], MVMatrix[1][0], MVMatrix[2][0]); - glm::dvec3 col2 = glm::dvec3(MVMatrix[0][1], MVMatrix[1][1], MVMatrix[2][1]); - glm::dvec3 col3 = glm::dvec3(MVMatrix[0][2], MVMatrix[1][2], MVMatrix[2][2]); - glm::dvec3 col4 = glm::dvec3(MVMatrix[0][3], MVMatrix[1][3], MVMatrix[2][3]); + const glm::dvec3 col1 = glm::dvec3(mv[0][0], mv[1][0], mv[2][0]); + const glm::dvec3 col2 = glm::dvec3(mv[0][1], mv[1][1], mv[2][1]); + const glm::dvec3 col3 = glm::dvec3(mv[0][2], mv[1][2], mv[2][2]); + const glm::dvec3 col4 = glm::dvec3(mv[0][3], mv[1][3], mv[2][3]); glm::dvec3 leftNormal = col4 + col1; glm::dvec3 rightNormal = col4 - col1; @@ -129,11 +129,11 @@ namespace { glm::dvec3 farNormal = col4 - col3; // Plane Distances - double leftDistance = MVMatrix[3][3] + MVMatrix[3][0]; - double rightDistance = MVMatrix[3][3] - MVMatrix[3][0]; - double bottomDistance = MVMatrix[3][3] + MVMatrix[3][1]; - double topDistance = MVMatrix[3][3] - MVMatrix[3][1]; - double nearDistance = MVMatrix[3][3] + MVMatrix[3][2]; + double leftDistance = mv[3][3] + mv[3][0]; + double rightDistance = mv[3][3] - mv[3][0]; + double bottomDistance = mv[3][3] + mv[3][1]; + double topDistance = mv[3][3] - mv[3][1]; + double nearDistance = mv[3][3] + mv[3][2]; // Normalize Planes const double invLeftMag = 1.0 / glm::length(leftNormal); @@ -159,20 +159,18 @@ namespace { const double invFarMag = 1.0 / glm::length(farNormal); farNormal *= invFarMag; - if (((glm::dot(leftNormal, position) + leftDistance) < -radius) || + const bool outsideFrustum = + (((glm::dot(leftNormal, position) + leftDistance) < -radius) || ((glm::dot(rightNormal, position) + rightDistance) < -radius) || ((glm::dot(bottomNormal, position) + bottomDistance) < -radius) || ((glm::dot(topNormal, position) + topDistance) < -radius) || - ((glm::dot(nearNormal, position) + nearDistance) < -radius)) - // The far plane testing is disabled because the atm has no depth. - { - return false; - } - return true; + ((glm::dot(nearNormal, position) + nearDistance) < -radius)); + + return !outsideFrustum; } GLuint createTexture(const glm::ivec2& size, std::string_view name) { - GLuint t; + GLuint t = 0; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_2D, t); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -201,7 +199,7 @@ namespace { GLuint createTexture(const glm::ivec3& size, std::string_view name, int components) { ghoul_assert(components == 3 || components == 4, "Only 3-4 components supported"); - GLuint t; + GLuint t = 0; glGenTextures(1, &t); glBindTexture(GL_TEXTURE_3D, t); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -270,7 +268,7 @@ void AtmosphereDeferredcaster::deinitialize() { void AtmosphereDeferredcaster::update(const UpdateData&) {} -float AtmosphereDeferredcaster::eclipseShadow(glm::dvec3 position) { +float AtmosphereDeferredcaster::eclipseShadow(const glm::dvec3& position) { // This code is copied from the atmosphere deferred fragment shader // It is used to calculate the eclipse shadow if (_shadowDataArrayCache.empty() || !_shadowDataArrayCache.front().isShadowing) { @@ -284,13 +282,13 @@ float AtmosphereDeferredcaster::eclipseShadow(glm::dvec3 position) { dot(positionToCaster, sourceToCaster) * sourceToCaster; const glm::dvec3 positionToShadow = positionToCaster - casterShadow; - float distanceToShadow = static_cast(length(positionToShadow)); - double shadowLength = length(casterShadow); + const float distanceToShadow = static_cast(length(positionToShadow)); + const double shadowLength = length(casterShadow); - float radiusPenumbra = static_cast( + const float radiusPenumbra = static_cast( shadow.radiusCaster * (shadowLength + shadow.penumbra) / shadow.penumbra ); - float radiusUmbra = static_cast( + const float radiusUmbra = static_cast( shadow.radiusCaster * (shadow.umbra - shadowLength) / shadow.umbra ); @@ -301,7 +299,8 @@ float AtmosphereDeferredcaster::eclipseShadow(glm::dvec3 position) { } else { // Smooth the shadow with the butterworth function - return sqrt(radiusUmbra / (radiusUmbra + pow(distanceToShadow, 4.f))); + const float s = radiusUmbra / (radiusUmbra + std::pow(distanceToShadow, 4.f)); + return std::sqrt(s); } } else if (distanceToShadow < radiusPenumbra) { // In penumbra - partially shaded part @@ -313,14 +312,16 @@ float AtmosphereDeferredcaster::eclipseShadow(glm::dvec3 position) { } void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const DeferredcastData&, - ghoul::opengl::ProgramObject& prg) + ghoul::opengl::ProgramObject& program) { ZoneScoped; TracyGpuZone("Atmosphere preRaycast"); // Atmosphere Frustum Culling - glm::dvec3 tPlanetPos = glm::dvec3(_modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0)); + const glm::dvec3 tPlanetPos = glm::dvec3( + _modelTransform * glm::dvec4(0.0, 0.0, 0.0, 1.0) + ); const double distance = glm::distance(tPlanetPos, data.camera.eyePositionVec3()); // Radius is in KM @@ -329,58 +330,60 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const Deferred ); // Number of planet radii to use as distance threshold for culling - prg.setUniform(_uniformCache.cullAtmosphere, 1); + program.setUniform(_uniformCache.cullAtmosphere, 1); constexpr double DistanceCullingRadii = 5000; - glm::dmat4 MV = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * + const glm::dmat4 MV = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * data.camera.combinedViewMatrix(); if (distance <= scaledRadius * DistanceCullingRadii && isAtmosphereInFrustum(MV, tPlanetPos, scaledRadius + ATM_EPS)) { - prg.setUniform(_uniformCache.cullAtmosphere, 0); - prg.setUniform(_uniformCache.opacity, _opacity); - prg.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); - prg.setUniform(_uniformCache.Rt, _atmosphereRadius); - prg.setUniform(_uniformCache.groundRadianceEmission, _groundRadianceEmission); - prg.setUniform(_uniformCache.HR, _rayleighHeightScale); - prg.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); - prg.setUniform(_uniformCache.HM, _mieHeightScale); - prg.setUniform(_uniformCache.betaMieExtinction, _mieExtinctionCoeff); - prg.setUniform(_uniformCache.mieG, _miePhaseConstant); - prg.setUniform(_uniformCache.sunRadiance, _sunRadianceIntensity); - prg.setUniform(_uniformCache.ozoneLayerEnabled, _ozoneEnabled); - prg.setUniform(_uniformCache.HO, _ozoneHeightScale); - prg.setUniform(_uniformCache.betaOzoneExtinction, _ozoneExtinctionCoeff); - prg.setUniform(_uniformCache.SAMPLES_R, _rSamples); - prg.setUniform(_uniformCache.SAMPLES_MU, _muSamples); - prg.setUniform(_uniformCache.SAMPLES_MU_S, _muSSamples); - prg.setUniform(_uniformCache.SAMPLES_NU, _nuSamples); + program.setUniform(_uniformCache.cullAtmosphere, 0); + program.setUniform(_uniformCache.opacity, _opacity); + program.setUniform(_uniformCache.Rg, _atmospherePlanetRadius); + program.setUniform(_uniformCache.Rt, _atmosphereRadius); + program.setUniform(_uniformCache.groundRadianceEmission, _groundRadianceEmission); + program.setUniform(_uniformCache.HR, _rayleighHeightScale); + program.setUniform(_uniformCache.betaRayleigh, _rayleighScatteringCoeff); + program.setUniform(_uniformCache.HM, _mieHeightScale); + program.setUniform(_uniformCache.betaMieExtinction, _mieExtinctionCoeff); + program.setUniform(_uniformCache.mieG, _miePhaseConstant); + program.setUniform(_uniformCache.sunRadiance, _sunRadianceIntensity); + program.setUniform(_uniformCache.ozoneLayerEnabled, _ozoneEnabled); + program.setUniform(_uniformCache.HO, _ozoneHeightScale); + program.setUniform(_uniformCache.betaOzoneExtinction, _ozoneExtinctionCoeff); + program.setUniform(_uniformCache.SAMPLES_R, _rSamples); + program.setUniform(_uniformCache.SAMPLES_MU, _muSamples); + program.setUniform(_uniformCache.SAMPLES_MU_S, _muSSamples); + program.setUniform(_uniformCache.SAMPLES_NU, _nuSamples); // We expose the value as degrees, but the shader wants radians - prg.setUniform(_uniformCache.sunAngularSize, glm::radians(_sunAngularSize)); + program.setUniform(_uniformCache.sunAngularSize, glm::radians(_sunAngularSize)); // Object Space - glm::dmat4 invModelMatrix = glm::inverse(_modelTransform); - prg.setUniform(_uniformCache.inverseModelTransformMatrix, invModelMatrix); - prg.setUniform(_uniformCache.modelTransformMatrix, _modelTransform); + const glm::dmat4 invModelMatrix = glm::inverse(_modelTransform); + program.setUniform(_uniformCache.inverseModelTransformMatrix, invModelMatrix); + program.setUniform(_uniformCache.modelTransformMatrix, _modelTransform); - glm::dmat4 viewToWorldMatrix = glm::inverse(data.camera.combinedViewMatrix()); + const glm::dmat4 viewToWorld = glm::inverse(data.camera.combinedViewMatrix()); // Eye Space to World Space - prg.setUniform(_uniformCache.viewToWorldMatrix, viewToWorldMatrix); + program.setUniform(_uniformCache.viewToWorldMatrix, viewToWorld); // Projection to Eye Space - glm::dmat4 dInvProj = glm::inverse(glm::dmat4(data.camera.projectionMatrix())); + const glm::dmat4 dInvProj = glm::inverse( + glm::dmat4(data.camera.projectionMatrix()) + ); - glm::dmat4 invWholePipeline = invModelMatrix * viewToWorldMatrix * dInvProj; + const glm::dmat4 invWholePipeline = invModelMatrix * viewToWorld * dInvProj; - prg.setUniform(_uniformCache.projectionToModelTransform, invWholePipeline); + program.setUniform(_uniformCache.projectionToModelTransform, invWholePipeline); - glm::dvec4 camPosObjCoords = + const glm::dvec4 camPosObjCoords = invModelMatrix * glm::dvec4(data.camera.eyePositionVec3(), 1.0); - prg.setUniform(_uniformCache.camPosObj, glm::dvec3(camPosObjCoords)); + program.setUniform(_uniformCache.camPosObj, glm::dvec3(camPosObjCoords)); SceneGraphNode* node = sceneGraph()->sceneGraphNode("Sun"); - glm::dvec3 sunPosWorld = node ? node->worldPosition() : glm::dvec3(0.0); + const glm::dvec3 sunPosWorld = node ? node->worldPosition() : glm::dvec3(0.0); glm::dvec3 sunPosObj; // Sun following camera position @@ -393,14 +396,14 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const Deferred } // Sun Position in Object Space - prg.setUniform(_uniformCache.sunDirectionObj, glm::normalize(sunPosObj)); + program.setUniform(_uniformCache.sunDirectionObj, glm::normalize(sunPosObj)); // Shadow calculations.. _shadowDataArrayCache.clear(); for (ShadowConfiguration& shadowConf : _shadowConfArray) { // TO REMEMBER: all distances and lengths in world coordinates are in // meters!!! We need to move this to view space... - double lt; + double lt = 0.0; glm::dvec3 sourcePos = SpiceManager::ref().targetPosition( shadowConf.source.first, "SSB", @@ -437,26 +440,27 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const Deferred return; } - double sourceScale = std::max(glm::compMax(sourceNode->scale()), 1.0); - double casterScale = std::max(glm::compMax(casterNode->scale()), 1.0); - double actualSourceRadius = shadowConf.source.second * sourceScale; - double actualCasterRadius = shadowConf.caster.second * casterScale; + const double sourceScale = std::max(glm::compMax(sourceNode->scale()), 1.0); + const double casterScale = std::max(glm::compMax(casterNode->scale()), 1.0); + const double actualSourceRadius = shadowConf.source.second * sourceScale; + const double actualCasterRadius = shadowConf.caster.second * casterScale; // First we determine if the caster is shadowing the current planet // (all calculations in World Coordinates): - glm::dvec3 planetCasterVec = casterPos - data.modelTransform.translation; - glm::dvec3 sourceCasterVec = casterPos - sourcePos; - double scLength = glm::length(sourceCasterVec); - glm::dvec3 planetCasterProj = + const glm::dvec3 planetCasterVec = + casterPos - data.modelTransform.translation; + const glm::dvec3 sourceCasterVec = casterPos - sourcePos; + const double scLength = glm::length(sourceCasterVec); + const glm::dvec3 planetCasterProj = (glm::dot(planetCasterVec, sourceCasterVec) / (scLength * scLength)) * sourceCasterVec; - double dTest = glm::length(planetCasterVec - planetCasterProj); - double xpTest = actualCasterRadius * scLength / + const double dTest = glm::length(planetCasterVec - planetCasterProj); + const double xpTest = actualCasterRadius * scLength / (actualSourceRadius + actualCasterRadius); - double rpTest = actualCasterRadius * + const double rpTest = actualCasterRadius * (glm::length(planetCasterProj) + xpTest) / xpTest; - double casterDistSun = glm::length(casterPos - sunPosWorld); - double planetDistSun = glm::length( + const double casterDistSun = glm::length(casterPos - sunPosWorld); + const double planetDistSun = glm::length( data.modelTransform.translation - sunPosWorld ); @@ -484,38 +488,41 @@ void AtmosphereDeferredcaster::preRaycast(const RenderData& data, const Deferred unsigned int counter = 0; for (const ShadowRenderingStruct& sd : _shadowDataArrayCache) { // Add the counter - char* bf = fmt::format_to(_uniformNameBuffer + 16, "{}", counter); + char* bf = std::format_to(_uniformNameBuffer + 16, "{}", counter); std::strcpy(bf, "].isShadowing\0"); - prg.setUniform(_uniformNameBuffer, sd.isShadowing); + program.setUniform(_uniformNameBuffer, sd.isShadowing); if (sd.isShadowing) { std::strcpy(bf, "].xp\0"); - prg.setUniform(_uniformNameBuffer, sd.penumbra); + program.setUniform(_uniformNameBuffer, sd.penumbra); std::strcpy(bf, "].xu\0"); - prg.setUniform(_uniformNameBuffer, sd.umbra); + program.setUniform(_uniformNameBuffer, sd.umbra); std::strcpy(bf, "].rc\0"); - prg.setUniform(_uniformNameBuffer, sd.radiusCaster); + program.setUniform(_uniformNameBuffer, sd.radiusCaster); std::strcpy(bf, "].sourceCasterVec\0"); - prg.setUniform(_uniformNameBuffer, sd.sourceCasterVec); + program.setUniform(_uniformNameBuffer, sd.sourceCasterVec); std::strcpy(bf, "].casterPositionVec\0"); - prg.setUniform(_uniformNameBuffer, sd.casterPositionVec); + program.setUniform(_uniformNameBuffer, sd.casterPositionVec); } counter++; } - prg.setUniform(_uniformCache.hardShadows, _hardShadowsEnabled); + program.setUniform(_uniformCache.hardShadows, _hardShadowsEnabled); } _transmittanceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _transmittanceTableTexture); - prg.setUniform(_uniformCache.transmittanceTexture, _transmittanceTableTextureUnit); + program.setUniform( + _uniformCache.transmittanceTexture, + _transmittanceTableTextureUnit + ); _irradianceTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_2D, _irradianceTableTexture); - prg.setUniform(_uniformCache.irradianceTexture, _irradianceTableTextureUnit); + program.setUniform(_uniformCache.irradianceTexture, _irradianceTableTextureUnit); _inScatteringTableTextureUnit.activate(); glBindTexture(GL_TEXTURE_3D, _inScatteringTableTexture); - prg.setUniform(_uniformCache.inscatterTexture, _inScatteringTableTextureUnit); + program.setUniform(_uniformCache.inscatterTexture, _inScatteringTableTextureUnit); } void AtmosphereDeferredcaster::postRaycast(const RenderData&, const DeferredcastData&, @@ -619,8 +626,8 @@ void AtmosphereDeferredcaster::calculateTransmittance() { program->setUniform("HO", _ozoneHeightScale); program->setUniform("betaOzoneExtinction", _ozoneExtinctionCoeff); - constexpr float Black[] = { 0.f, 0.f, 0.f, 0.f }; - glClearBufferfv(GL_COLOR, 0, Black); + constexpr glm::vec4 Black = glm::vec4(0.f, 0.f, 0.f, 0.f); + glClearBufferfv(GL_COLOR, 0, glm::value_ptr(Black)); glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile("transmittance_texture.ppm", _transmittanceTableSize); @@ -631,7 +638,7 @@ void AtmosphereDeferredcaster::calculateTransmittance() { GLuint AtmosphereDeferredcaster::calculateDeltaE() { ZoneScoped; - GLuint deltaE = createTexture(_deltaETableSize, "DeltaE"); + const GLuint deltaE = createTexture(_deltaETableSize, "DeltaE"); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaE, 0); glViewport(0, 0, _deltaETableSize.x, _deltaETableSize.y); using ProgramObject = ghoul::opengl::ProgramObject; @@ -660,12 +667,12 @@ GLuint AtmosphereDeferredcaster::calculateDeltaE() { std::pair AtmosphereDeferredcaster::calculateDeltaS() { ZoneScoped; - GLuint deltaSRayleigh = createTexture(_textureSize, "DeltaS Rayleigh", 3); + const GLuint deltaSRayleigh = createTexture(_textureSize, "DeltaS Rayleigh", 3); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, deltaSRayleigh, 0); - GLuint deltaSMie = createTexture(_textureSize, "DeltaS Mie", 3); + const GLuint deltaSMie = createTexture(_textureSize, "DeltaS Mie", 3); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, deltaSMie, 0); - GLenum colorBuffers[2] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - glDrawBuffers(2, colorBuffers); + std::array colorBuffers = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; + glDrawBuffers(2, colorBuffers.data()); glViewport(0, 0, _textureSize.x, _textureSize.y); using ProgramObject = ghoul::opengl::ProgramObject; std::unique_ptr program = ProgramObject::Build( @@ -704,8 +711,8 @@ std::pair AtmosphereDeferredcaster::calculateDeltaS() { ); } glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); + const std::array drawBuffers = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, drawBuffers.data()); program->deactivate(); return { deltaSRayleigh, deltaSMie }; @@ -835,7 +842,7 @@ void AtmosphereDeferredcaster::calculateDeltaJ(int scatteringOrder, } if (_saveCalculationTextures) { saveTextureFile( - fmt::format("deltaJ_texture-scattering_order-{}.ppm", scatteringOrder), + std::format("deltaJ_texture-scattering_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } @@ -875,7 +882,7 @@ void AtmosphereDeferredcaster::calculateDeltaE(int scatteringOrder, glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile( - fmt::format("deltaE_texture-scattering_order-{}.ppm", scatteringOrder), + std::format("deltaE_texture-scattering_order-{}.ppm", scatteringOrder), _deltaETableSize ); } @@ -915,7 +922,7 @@ void AtmosphereDeferredcaster::calculateDeltaS(int scatteringOrder, } if (_saveCalculationTextures) { saveTextureFile( - fmt::format("deltaS_texture-scattering_order-{}.ppm", scatteringOrder), + std::format("deltaS_texture-scattering_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } @@ -946,7 +953,7 @@ void AtmosphereDeferredcaster::calculateIrradiance(int scatteringOrder, glDrawArrays(GL_TRIANGLES, 0, 6); if (_saveCalculationTextures) { saveTextureFile( - fmt::format("irradianceTable_order-{}.ppm", scatteringOrder), + std::format("irradianceTable_order-{}.ppm", scatteringOrder), _deltaETableSize ); } @@ -954,8 +961,8 @@ void AtmosphereDeferredcaster::calculateIrradiance(int scatteringOrder, } void AtmosphereDeferredcaster::calculateInscattering(int scatteringOrder, - ghoul::opengl::ProgramObject& prg, - GLuint deltaSRayleigh) + ghoul::opengl::ProgramObject& program, + GLuint deltaSRayleigh) { ZoneScoped; @@ -967,27 +974,27 @@ void AtmosphereDeferredcaster::calculateInscattering(int scatteringOrder, 0 ); glViewport(0, 0, _textureSize.x, _textureSize.y); - prg.activate(); + program.activate(); ghoul::opengl::TextureUnit unit; unit.activate(); glBindTexture(GL_TEXTURE_3D, deltaSRayleigh); - prg.setUniform("deltaSTexture", unit); - prg.setUniform("SAMPLES_MU_S", _muSSamples); - prg.setUniform("SAMPLES_NU", _nuSamples); - prg.setUniform("SAMPLES_MU", _muSamples); - prg.setUniform("SAMPLES_R", _rSamples); + program.setUniform("deltaSTexture", unit); + program.setUniform("SAMPLES_MU_S", _muSSamples); + program.setUniform("SAMPLES_NU", _nuSamples); + program.setUniform("SAMPLES_MU", _muSamples); + program.setUniform("SAMPLES_R", _rSamples); for (int layer = 0; layer < _rSamples; ++layer) { - prg.setUniform("layer", layer); + program.setUniform("layer", layer); glDrawArrays(GL_TRIANGLES, 0, 6); } if (_saveCalculationTextures) { saveTextureFile( - fmt::format("inscatteringTable_order-{}.ppm", scatteringOrder), + std::format("inscatteringTable_order-{}.ppm", scatteringOrder), glm::ivec2(_textureSize) ); } - prg.deactivate(); + program.deactivate(); } void AtmosphereDeferredcaster::calculateAtmosphereParameters() { @@ -1025,38 +1032,38 @@ void AtmosphereDeferredcaster::calculateAtmosphereParameters() { // Saves current FBO first - GLint defaultFBO; + GLint defaultFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - GLint viewport[4]; - global::renderEngine->openglStateCache().viewport(viewport); + std::array viewport; + global::renderEngine->openglStateCache().viewport(viewport.data()); // Creates the FBO for the calculations - GLuint calcFBO; + GLuint calcFBO = 0; glGenFramebuffers(1, &calcFBO); glBindFramebuffer(GL_FRAMEBUFFER, calcFBO); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); + std::array drawBuffers = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, drawBuffers.data()); // Prepare for rendering/calculations - GLuint quadVao; + GLuint quadVao = 0; glGenVertexArrays(1, &quadVao); glBindVertexArray(quadVao); - GLuint quadVbo; + GLuint quadVbo = 0; glGenBuffers(1, &quadVbo); glBindBuffer(GL_ARRAY_BUFFER, quadVbo); - const GLfloat VertexData[] = { - // x y z + constexpr std::array VertexData = { + // x y -1.f, -1.f, - 1.f, 1.f, + 1.f, 1.f, -1.f, 1.f, -1.f, -1.f, - 1.f, -1.f, - 1.f, 1.f, + 1.f, -1.f, + 1.f, 1.f, }; - glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); @@ -1068,7 +1075,7 @@ void AtmosphereDeferredcaster::calculateAtmosphereParameters() { calculateTransmittance(); // line 2 in algorithm 4.1 - GLuint deltaETable = calculateDeltaE(); + const GLuint deltaETable = calculateDeltaE(); // line 3 in algorithm 4.1 auto [deltaSRayleighTable, deltaSMieTable] = calculateDeltaS(); @@ -1079,7 +1086,7 @@ void AtmosphereDeferredcaster::calculateAtmosphereParameters() { // line 5 in algorithm 4.1 calculateInscattering(deltaSRayleighTable, deltaSMieTable); - GLuint deltaJTable = createTexture(_textureSize, "DeltaJ", 3); + const GLuint deltaJTable = createTexture(_textureSize, "DeltaJ", 3); // loop in line 6 in algorithm 4.1 for (int scatteringOrder = 2; scatteringOrder <= 4; ++scatteringOrder) { @@ -1141,7 +1148,7 @@ void AtmosphereDeferredcaster::calculateAtmosphereParameters() { // Restores system state glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - global::renderEngine->openglStateCache().setViewportState(viewport); + global::renderEngine->openglStateCache().setViewportState(viewport.data()); glDeleteBuffers(1, &quadVbo); glDeleteVertexArrays(1, &quadVao); glDeleteFramebuffers(1, &calcFBO); @@ -1150,7 +1157,8 @@ void AtmosphereDeferredcaster::calculateAtmosphereParameters() { LDEBUG("Ended precalculations for Atmosphere effects"); } -void AtmosphereDeferredcaster::step3DTexture(ghoul::opengl::ProgramObject& prg, int layer) +void AtmosphereDeferredcaster::step3DTexture(ghoul::opengl::ProgramObject& prg, + int layer) const { // See OpenGL redbook 8th Edition page 556 for Layered Rendering const float planet2 = _atmospherePlanetRadius * _atmospherePlanetRadius; diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index bbe7f6b28a..89e80d075f 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -75,7 +75,7 @@ public: void initializeCachedVariables(ghoul::opengl::ProgramObject& program) override; void update(const UpdateData&) override; - float eclipseShadow(glm::dvec3 position); + float eclipseShadow(const glm::dvec3& position); void calculateAtmosphereParameters(); @@ -93,7 +93,7 @@ public: void setHardShadows(bool enabled); private: - void step3DTexture(ghoul::opengl::ProgramObject& prg, int layer); + void step3DTexture(ghoul::opengl::ProgramObject& prg, int layer) const; void calculateTransmittance(); GLuint calculateDeltaE(); diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index f24c758ec6..fa189f8542 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include namespace { constexpr float KM_TO_M = 1000.f; @@ -466,11 +466,11 @@ glm::dmat4 RenderableAtmosphere::computeModelTransformMatrix(const TransformData glm::scale(glm::dmat4(1.0), glm::dvec3(data.scale)); } -void RenderableAtmosphere::render(const RenderData& data, RendererTasks& renderTask) { +void RenderableAtmosphere::render(const RenderData& data, RendererTasks& rendererTask) { ZoneScoped; - DeferredcasterTask task{ _deferredcaster.get(), data }; - renderTask.deferredcasterTasks.push_back(task); + DeferredcasterTask task = { _deferredcaster.get(), data }; + rendererTask.deferredcasterTasks.push_back(std::move(task)); } void RenderableAtmosphere::update(const UpdateData& data) { @@ -484,7 +484,7 @@ void RenderableAtmosphere::update(const UpdateData& data) { } glm::dmat4 modelTransform = computeModelTransformMatrix(data.modelTransform); - _deferredcaster->setModelTransform(modelTransform); + _deferredcaster->setModelTransform(std::move(modelTransform)); _deferredcaster->setOpacity(opacity()); _deferredcaster->update(data); setDimmingCoefficient(computeModelTransformMatrix(data.modelTransform)); @@ -525,17 +525,17 @@ void RenderableAtmosphere::setDimmingCoefficient(const glm::dmat4& modelTransfor const glm::dvec3 normalUnderCamera = glm::normalize(cameraPos - planetPos); const glm::dvec3 vecToSun = glm::normalize(-planetPos); - float cameraDistance = static_cast(glm::distance(planetPos, cameraPos)); - float cameraSunAngle = static_cast( + const float cameraDistance = static_cast(glm::distance(planetPos, cameraPos)); + const float cameraSunAngle = static_cast( glm::degrees(glm::acos(glm::dot(vecToSun, normalUnderCamera)) )); - float sunsetEnd = _atmosphereDimmingSunsetAngle.value().y; + const float sunsetEnd = _atmosphereDimmingSunsetAngle.value().y; // If cameraSunAngle is more than 90 degrees, we are in shaded part of globe - bool cameraIsInSun = cameraSunAngle <= sunsetEnd; + const bool cameraIsInSun = cameraSunAngle <= sunsetEnd; // Atmosphere height is in KM - float atmosphereEdge = KM_TO_M * (_planetRadius + _atmosphereHeight); - bool cameraIsInAtmosphere = cameraDistance < atmosphereEdge; + const float atmosphereEdge = KM_TO_M * (_planetRadius + _atmosphereHeight); + const bool cameraIsInAtmosphere = cameraDistance < atmosphereEdge; // Don't fade if camera is not in the sunny part of an atmosphere if (!cameraIsInAtmosphere || !cameraIsInSun) { @@ -543,17 +543,18 @@ void RenderableAtmosphere::setDimmingCoefficient(const glm::dmat4& modelTransfor } // Else we need to fade the objects // Height of the atmosphere where the objects will be faded - float atmosphereFadingHeight = KM_TO_M * _atmosphereDimmingHeight * _atmosphereHeight; - float atmosphereInnerEdge = atmosphereEdge - atmosphereFadingHeight; - bool cameraIsInFadingRegion = cameraDistance > atmosphereInnerEdge; + const float atmosphereFadingHeight = + KM_TO_M * _atmosphereDimmingHeight * _atmosphereHeight; + const float atmosphereInnerEdge = atmosphereEdge - atmosphereFadingHeight; + const bool cameraIsInFadingRegion = cameraDistance > atmosphereInnerEdge; // Check if camera is in sunset - float sunsetStart = _atmosphereDimmingSunsetAngle.value().x; - bool cameraIsInSunset = cameraSunAngle > sunsetStart && cameraIsInSun; + const float sunsetStart = _atmosphereDimmingSunsetAngle.value().x; + const bool cameraIsInSunset = cameraSunAngle > sunsetStart && cameraIsInSun; // See if we are inside of an eclipse shadow float eclipseShadow = _deferredcaster->eclipseShadow(cameraPos); - bool cameraIsInEclipse = std::abs(eclipseShadow - 1.f) > glm::epsilon(); + const bool cameraIsInEclipse = std::abs(eclipseShadow - 1.f) > glm::epsilon(); // Invert shadow and multiply with itself to make it more narrow eclipseShadow = std::pow(1.f - eclipseShadow, 2.f); float atmosphereDimming = 0.f; @@ -566,8 +567,8 @@ void RenderableAtmosphere::setDimmingCoefficient(const glm::dmat4& modelTransfor else if (cameraIsInFadingRegion && cameraIsInEclipse) { // Fade with regards to altitude & eclipse shadow // Fading - linear interpolation - float fading = (cameraDistance - atmosphereInnerEdge) / - atmosphereFadingHeight; + const float fading = + (cameraDistance - atmosphereInnerEdge) / atmosphereFadingHeight; atmosphereDimming = std::clamp(eclipseShadow + fading, 0.f, 1.f); } else if (cameraIsInFadingRegion) { diff --git a/modules/atmosphere/shaders/inScattering_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_calc_fs.glsl index 6981419721..3280280d2e 100644 --- a/modules/atmosphere/shaders/inScattering_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_calc_fs.glsl @@ -103,7 +103,7 @@ void inscatter(float r, float mu, float muSun, float nu, out vec3 S_R, out vec3 vec3 S_Ri; vec3 S_Mi; integrand(r, mu, muSun, nu, 0.0, S_Ri, S_Mi); - for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { + for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; i++) { float yj = float(i) * dy; vec3 S_Rj; vec3 S_Mj; diff --git a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl index e0388ebe2d..753df9fa4d 100644 --- a/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/inScattering_sup_calc_fs.glsl @@ -68,7 +68,7 @@ vec3 inscatter(float r, float mu, float muSun, float nu) { // In order to solve the integral from equation (11) we use the trapezoidal rule: // Integral(f(y)dy)(from a to b) = ((b-a)/2n_steps)*(Sum(f(y_i+1)+f(y_i))) // where y_i+1 = y_j - for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { + for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; i++) { float y_j = float(i) * dy; vec3 inScatteringRadiance_j = integrand(r, mu, muSun, nu, y_j); inScatteringRadiance += (inScatteringRadiance_i + inScatteringRadiance_j) / 2.0 * dy; diff --git a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl index 6a793c7ed5..3fe343ba7c 100644 --- a/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl +++ b/modules/atmosphere/shaders/irradiance_sup_calc_fs.glsl @@ -60,9 +60,9 @@ void main() { // In order to solve the integral from equation (15) we use the trapezoidal rule: // Integral(f(y)dy)(from a to b) = ((b-a)/2n_steps)*(Sum(f(y_i+1)+f(y_i))) vec3 irradianceE = vec3(0.0); - for (int iphi = 0; iphi < IRRADIANCE_INTEGRAL_SAMPLES; ++iphi) { + for (int iphi = 0; iphi < IRRADIANCE_INTEGRAL_SAMPLES; iphi++) { float phi = (float(iphi) + 0.5) * stepPhi; - for (int itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES; ++itheta) { + for (int itheta = 0; itheta < IRRADIANCE_INTEGRAL_SAMPLES; itheta++) { float theta = (float(itheta) + 0.5) * stepTheta; // spherical coordinates: dw = dtheta*dphi*sin(theta)*rho^2 // rho = 1, we are integrating over a unit sphere diff --git a/modules/atmosphere/shaders/transmittance_calc_fs.glsl b/modules/atmosphere/shaders/transmittance_calc_fs.glsl index 23dc23a282..76f3599956 100644 --- a/modules/atmosphere/shaders/transmittance_calc_fs.glsl +++ b/modules/atmosphere/shaders/transmittance_calc_fs.glsl @@ -69,7 +69,7 @@ float opticalDepth(float r, float mu, float H) { float y_i = exp(-(r - Rg) / H); float accumulation = 0.0; - for (int i = 1; i <= TRANSMITTANCE_STEPS; ++i) { + for (int i = 1; i <= TRANSMITTANCE_STEPS; i++) { float x_i = float(i) * deltaStep; // cosine law for triangles: y_i^2 = a^2 + b^2 - 2abcos(alpha) // In this case, a = r, b = x_i and cos(alpha) = cos(PI-zenithView) = mu diff --git a/modules/audio/CMakeLists.txt b/modules/audio/CMakeLists.txt new file mode 100644 index 0000000000..76129785b6 --- /dev/null +++ b/modules/audio/CMakeLists.txt @@ -0,0 +1,58 @@ +########################################################################################## +# # +# OpenSpace # +# # +# Copyright (c) 2014-2023 # +# # +# Permission is hereby granted, free of charge, to any person obtaining a copy of this # +# software and associated documentation files (the "Software"), to deal in the Software # +# without restriction, including without limitation the rights to use, copy, modify, # +# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # +# permit persons to whom the Software is furnished to do so, subject to the following # +# conditions: # +# # +# The above copyright notice and this permission notice shall be included in all copies # +# or substantial portions of the Software. # +# # +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # +# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # +# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # +# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE # +# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # +########################################################################################## + +include(${PROJECT_SOURCE_DIR}/support/cmake/module_definition.cmake) + +set(HEADER_FILES + audiomodule.h +) +source_group("Header Files" FILES ${HEADER_FILES}) + +set(SOURCE_FILES + audiomodule.cpp + audiomodule_lua.inl +) +source_group("Source Files" FILES ${SOURCE_FILES}) + +create_new_module( + "Audio" + audio_module + STATIC + ${HEADER_FILES} ${SOURCE_FILES} ${SHADER_FILES} +) + +begin_dependency("SoLoud") +set(SOLOUD_BACKEND_SDL2 OFF CACHE BOOL "") +if (WIN32) + set(SOLOUD_BACKEND_WINMM ON CACHE BOOL "") +elseif (UNIX) + set(SOLOUD_BACKEND_ALSA ON CACHE BOOL "") +endif () +add_subdirectory(ext/soloud/contrib) + +# Unfortunately, the soloud cmake tarket doesn't set the include directories correctly +target_include_directories(openspace-module-audio SYSTEM PRIVATE ext/soloud/include) +target_link_libraries(openspace-module-audio PRIVATE soloud) +set_property(TARGET soloud PROPERTY FOLDER "External") +end_dependency("SoLoud") diff --git a/modules/audio/audiomodule.cpp b/modules/audio/audiomodule.cpp new file mode 100644 index 0000000000..7af25633e8 --- /dev/null +++ b/modules/audio/audiomodule.cpp @@ -0,0 +1,409 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2024 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include + +#include "audiomodule_lua.inl" + +#include +#include + +namespace { + constexpr std::string_view _loggerCat = "AudioModule"; + + struct [[codegen::Dictionary(AudioModule)]] Parameters { + // Sets the maximum number of simultaneous channels that can be played back by the + // audio subsystem. If this value is not specified, it defaults to 128. + std::optional maxNumberOfChannels [[codegen::greater(0)]]; + }; + +#include "audiomodule_codegen.cpp" +} // namespace + +namespace openspace { + +AudioModule::AudioModule() + : OpenSpaceModule(Name) + , _engine(std::make_unique()) +{} + +AudioModule::~AudioModule() {} + +void AudioModule::internalInitialize(const ghoul::Dictionary& dictionary) { + const Parameters p = codegen::bake(dictionary); + + LDEBUG(fmt::format("Initializing SoLoud version: {}", SOLOUD_VERSION)); + + _engine->init(); + _engine->setGlobalVolume(0.5f); + const int nChannels = p.maxNumberOfChannels.value_or(16); + _engine->setMaxActiveVoiceCount(static_cast(nChannels)); + + global::callback::postDraw->emplace_back([this]() { + if (!_sounds.empty()) { + _engine->update3dAudio(); + } + }); + + LDEBUG(fmt::format("Audio backend: {}", _engine->getBackendString())); + LDEBUG(fmt::format("Number of channels: {}", _engine->getBackendChannels())); +} + +void AudioModule::internalDeinitializeGL() { + ghoul_assert(_engine, "No audio engine loaded"); + + _sounds.clear(); + _engine->deinit(); + _engine = nullptr; +} + +std::unique_ptr AudioModule::loadSound(const std::filesystem::path& path) { + ghoul_assert(_engine, "No audio engine loaded"); + + std::unique_ptr sound = std::make_unique(); + const std::string p = path.string(); + SoLoud::result res = sound->load(p.c_str()); + if (res != 0) { + throw ghoul::RuntimeError(fmt::format( + "Error loading sound from {}. {}: {}", + path, static_cast(res), _engine->getErrorString(res) + )); + } + + // While we are loading a sound, we also want to do a little garbage collection on our + // internal data structure to remove the songs that someone has loaded at some point + // and that have since organically stopped. In general, this should only happen if the + // song was started without looping and has ended + for (auto it = _sounds.begin(); it != _sounds.end();) { + if (!isPlaying(it->first)) { + // We have found one of the candidates + LDEBUG(fmt::format("Removing song {} as it has ended", it->first)); + _sounds.erase(it); + // It is easier to just reset the iterator to the beginning than deal with the + // off-by-one error when deleting the last element in the list and the + // subsequent crash + it = _sounds.begin(); + } + else { + it++; + } + } + + return sound; +} + +void AudioModule::playAudio(const std::filesystem::path& path, std::string identifier, + ShouldLoop loop) +{ + ghoul_assert(_engine, "No audio engine loaded"); + if (_sounds.find(identifier) != _sounds.end()) { + LERROR(fmt::format("Sound with name '{}' already played", identifier)); + return; + } + + std::unique_ptr sound = loadSound(path); + sound->setLooping(loop); + SoLoud::handle handle = _engine->playBackground(*sound); + + ghoul_assert(_sounds.find(identifier) == _sounds.end(), "Handle already used"); + _sounds[identifier] = { + .sound = std::move(sound), + .handle = handle + }; +} + +void AudioModule::playAudio3d(const std::filesystem::path& path, std::string identifier, + const glm::vec3& position, ShouldLoop loop) +{ + ghoul_assert(_engine, "No audio engine loaded"); + if (_sounds.find(identifier) != _sounds.end()) { + LERROR(fmt::format("Sound with name '{}' already played", identifier)); + return; + } + + std::unique_ptr sound = loadSound(path); + sound->setLooping(loop); + SoLoud::handle handle = _engine->play3d(*sound, position.x, position.y, position.z); + + _sounds[identifier] = { + .sound = std::move(sound), + .handle = handle + }; +} + +void AudioModule::stopAudio(const std::string& identifier) { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + _engine->stop(it->second.handle); + _sounds.erase(it); + } +} + +void AudioModule::stopAll() { + ghoul_assert(_engine, "No audio engine loaded"); + + _engine->stopAll(); + _sounds.clear(); +} + +void AudioModule::pauseAll() const { + for (const std::pair& sound : _sounds) { + pauseAudio(sound.first); + } +} + +void AudioModule::resumeAll() const { + for (const std::pair& sound : _sounds) { + resumeAudio(sound.first); + } +} + +void AudioModule::playAllFromStart() const { + for (const std::pair& sound : _sounds) { + _engine->seek(sound.second.handle, 0.f); + } + resumeAll(); +} + +bool AudioModule::isPlaying(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + return _engine->isValidVoiceHandle(it->second.handle); + } + else { + return false; + } +} + +void AudioModule::pauseAudio(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + _engine->setPause(it->second.handle, true); + } +} + +void AudioModule::resumeAudio(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + _engine->setPause(it->second.handle, false); + } +} + +bool AudioModule::isPaused(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + const bool isPaused = _engine->getPause(it->second.handle); + return isPaused; + } + else { + return true; + } +} + +void AudioModule::setLooping(const std::string& identifier, ShouldLoop loop) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + _engine->setLooping(it->second.handle, loop); + } +} + +AudioModule::ShouldLoop AudioModule::isLooping(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + return _engine->getLooping(it->second.handle) ? ShouldLoop::Yes : ShouldLoop::No; + } + else { + return ShouldLoop::No; + } +} + +void AudioModule::setVolume(const std::string& identifier, float volume, float fade) const +{ + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it == _sounds.end()) { + return; + } + + // We clamp the volume level between [0, 1] to not accidentally blow any speakers + volume = glm::clamp(volume, 0.f, 1.f); + if (fade == 0.f) { + _engine->setVolume(it->second.handle, volume); + } + else { + _engine->fadeVolume(it->second.handle, volume, fade); + } +} + +float AudioModule::volume(const std::string& identifier) const { + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + const float volume = _engine->getVolume(it->second.handle); + return volume; + } + else { + return 0.f; + } +} + +void AudioModule::set3dSourcePosition(const std::string& identifier, + const glm::vec3& position) const +{ + ghoul_assert(_engine, "No audio engine loaded"); + + auto it = _sounds.find(identifier); + if (it != _sounds.end()) { + _engine->set3dSourcePosition( + it->second.handle, + position.x, position.y, position.z + ); + } +} + +std::vector AudioModule::currentlyPlaying() const { + // This function is *technically* not the ones that are playing, but that ones that we + // are keeping track of. So we still have songs in our internal data structure that + // were started as not-looping and that have ended playing. We need to filter them out + // here. + // The alternative would be to have a periodic garbage collection running, but that + // feels worse. We are doing the garbage collection in the two playAudio functions + // instead, since we have to do some work their either way + + std::vector res; + res.reserve(_sounds.size()); + for (const std::pair& sound : _sounds) { + if (isPlaying(sound.first)) { + res.push_back(sound.first); + } + } + return res; +} + +void AudioModule::setGlobalVolume(float volume, float fade) const { + ghoul_assert(_engine, "No audio engine loaded"); + + // We clamp the volume level between [0, 1] to not accidentally blow any speakers + volume = glm::clamp(volume, 0.f, 1.f); + if (fade == 0.f) { + _engine->setGlobalVolume(volume); + } + else { + _engine->fadeGlobalVolume(volume, fade); + } +} + +float AudioModule::globalVolume() const { + ghoul_assert(_engine, "No audio engine loaded"); + return _engine->getGlobalVolume(); +} + +void AudioModule::set3dListenerParameters(const std::optional& position, + const std::optional& lookAt, + const std::optional& up) const +{ + ghoul_assert(_engine, "No audio engine loaded"); + + if (position.has_value()) { + _engine->set3dListenerPosition(position->x, position->y, position->z); + } + if (lookAt.has_value()) { + _engine->set3dListenerAt(lookAt->x, lookAt->y, lookAt->z); + } + if (up.has_value()) { + _engine->set3dListenerUp(up->x, up->y, up->z); + } +} + +void AudioModule::setSpeakerPosition(int channel, const glm::vec3& position) const { + ghoul_assert(_engine, "No audio engine loaded"); + _engine->setSpeakerPosition(channel, position.x, position.y, position.z); +} + +glm::vec3 AudioModule::speakerPosition(int channel) const { + ghoul_assert(_engine, "No audio engine loaded"); + + float x = 0.f; + float y = 0.f; + float z = 0.f; + _engine->getSpeakerPosition(channel, x, y, z); + return glm::vec3(x, y, z); +} + +std::vector AudioModule::documentations() const { + return { + }; +} + +scripting::LuaLibrary AudioModule::luaLibrary() const { + return { + "audio", + { + codegen::lua::PlayAudio, + codegen::lua::PlayAudio3d, + codegen::lua::StopAudio, + codegen::lua::StopAll, + codegen::lua::PauseAll, + codegen::lua::ResumeAll, + codegen::lua::PlayAllFromStart, + codegen::lua::IsPlaying, + codegen::lua::PauseAudio, + codegen::lua::ResumeAudio, + codegen::lua::IsPaused, + codegen::lua::SetLooping, + codegen::lua::IsLooping, + codegen::lua::SetVolume, + codegen::lua::Volume, + codegen::lua::Set3dSourcePosition, + codegen::lua::CurrentlyPlaying, + codegen::lua::SetGlobalVolume, + codegen::lua::GlobalVolume, + codegen::lua::Set3dListenerPosition, + codegen::lua::SetSpeakerPosition, + codegen::lua::SpeakerPosition + } + }; +} + +} // namespace openspace diff --git a/modules/audio/audiomodule.h b/modules/audio/audiomodule.h new file mode 100644 index 0000000000..18f5deecee --- /dev/null +++ b/modules/audio/audiomodule.h @@ -0,0 +1,315 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2024 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_SPACE___AUDIOMODULE___H__ +#define __OPENSPACE_MODULE_SPACE___AUDIOMODULE___H__ + +#include + +#include +#include +#include + +namespace SoLoud { + class Soloud; + class Wav; +} // namespace SoLoud + +namespace openspace { + +class AudioModule : public OpenSpaceModule { +public: + constexpr static const char* Name = "Audio"; + + AudioModule(); + ~AudioModule() override; + std::vector documentations() const override; + + scripting::LuaLibrary luaLibrary() const override; + + BooleanType(ShouldLoop); + + /** + * Starts playing the audio file located and the provided \p path. The \p loop + * parameter determines whether the file is only played once, or on a loop. The sound + * is later referred to by the \p identifier name. The audio file will be played in + * "background" mode, which means that each channel will be played at full volume. To + * play a video using spatial audio, use the #playAudio3d function instead. + * + * \param path The audio file that should be played + * \param identifier The name for the sound that is used to refer to the sound + * \param loop If `Yes` then the song will be played in a loop until the program is + * closed or the playing is stopped through the #stopAudio function + */ + void playAudio(const std::filesystem::path& path, std::string identifier, + ShouldLoop loop); + + /** + * Starts playing the audio file located and the provided \p path. The \p loop + * parameter determines whether the file is only played once, or on a loop. The sound + * is later referred to by the \p identifier name. The \p position parameter + * determines the spatial location of the sound in a meter-based coordinate system. + * The position of the listener is (0,0,0) with the forward direction along the +y + * axis. This means that the "left" channel in a stereo setting is towards -x and the + * "right" channel towards x. This default value can be customized through the + * #set3dListenerParameters function. If you want to play a video without spatial + * audio, use the #playAudio function instead. + * + * \param path The audio file that should be played + * \param identifier The name for the sound that is used to refer to the sound + * \param position The position of the audio file in the 3D environment + * \param loop If `Yes` then the song will be played in a loop until the program is + * closed or the playing is stopped through the #stopAudio function + */ + void playAudio3d(const std::filesystem::path& path, std::string identifier, + const glm::vec3& position, ShouldLoop loop); + + /** + * Stops the audio referenced by the \p identifier. The \p identifier must be a name + * for a sound that was started through the #playAudio or #playAudio3d functions. + * After this function, the \p identifier can not be used for any other function + * anymore except for #playAudio or #playAudio3d to start a new sound. + * + * \param identifier The identifier to the track that should be stopped + */ + void stopAudio(const std::string& identifier); + + /** + * Stops all currently playing tracks. After this function, none of the identifiers + * used to previously play a sound a valid any longer, but can still be used by the + * #playAudio or #playAudio3d functions to start a new sound. + * This function behaves the same way as if manually calling #stopAudio on all of the + * sounds that have been started. + */ + void stopAll(); + + /** + * Pauses the playback for all sounds, while keeping them valid. This function behaves + * the same as if calling #pauseAudio on all of the sounds that are currently playing. + */ + void pauseAll() const; + + /** + * Resumes the playback for all sounds that have been paused. Please note that this + * will also resume the playback for the sounds that have been manually paused, not + * just those that were paused through the #pauseAll function. + */ + void resumeAll() const; + + /** + * Takes all of the sounds that are currently registers, unpauses them and plays them + * from their starting points + */ + void playAllFromStart() const; + + /** + * Returns whether the track referred to by the \p identifier is currently playing. A + * volume of 0 is still considered to be playing. The \p identifier must be a name for + * a sound that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `true` if the track is currently playing, `false` otherwise + */ + bool isPlaying(const std::string& identifier) const; + + /** + * Pauses the playback of the track referred to by the \p identifier. The playback can + * later be resumed through the #resumeAudio function. Trying to pause an already + * paused track will not do anything, but is valid. The \p identifier must be a name + * for a sound that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + */ + void pauseAudio(const std::string& identifier) const; + + /** + * Resumes the playback of a track that was previously paused through the #pauseAudio + * function. Trying to resume an already playing track will not do anything, but is + * valid. The \p identifier must be a name for a sound that was started through the + * #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + */ + void resumeAudio(const std::string& identifier) const; + + /** + * Returns whether the track refered to by the \p identifier is currently playing or + * paused. If it was be paused through a previous call to #pauseAudio, this function + * will return `true`. If it has just been created or resumed through a call to + * #resumeAudio, it will return `false`. The \p identifier must be a name for a sound + * that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `true` if the track is currently paused, `false` if it is playing + */ + bool isPaused(const std::string& identifier) const; + + /** + * Controls whether the track referred to by the \p identifier should be looping or + * just be played once. If a track is converted to not looping, it will finish playing + * until the end of the file. The \p identifier must be a name for a sound that was + * started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \param loop If `Yes` then the song will be played in a loop until the program is + * closed or the playing is stopped through the #stopAudio function + */ + void setLooping(const std::string& identifier, ShouldLoop loop) const; + + /** + * Returns whether the track referred to by the \p identifier is set to be looping or + * whether it should played only once. The \p identifier must be a name for a sound + * that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `Yes` if the track is looping, `No` otherwise + */ + ShouldLoop isLooping(const std::string& identifier) const; + + /** + * Sets the volume of the track referred to by \p identifier to the new \p volume. The + * volume should be a number bigger than 0, where 1 is the maximum volume level. + * The \p fade controls whether the volume change should be immediately (if + * it is 0) or over how many seconds it should change. The default is for it to change + * over 500 ms. The \p identifier must be a name for a sound that was started through + * the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \param volume The new volume level. Must be greater or equal to 0 + * \param fade How much time the fade from the current volume to the new volume should + * take + */ + void setVolume(const std::string& identifier, float volume, float fade = 0.5f) const; + + /** + * Returns the volume for the track referred to by the \p handle. The number returned + * will be greater or equal to 0. The \p identifier must be a name for a sound that + * was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return The volume for the track referred to by the \p handle, which will be + * greater or equal to 0 + */ + float volume(const std::string& identifier) const; + + /** + * Updates the 3D position of a track started through the #playAudio3d function. See + * that function and the #set3dListenerParameters function for a complete description. + * The \p identifier must be a name for a sound that was started through the + * #playAudio3d function. + * + * \param handle A valid handle for a track started through the #playAudio3d function + * \param position The new position from which the track originates + */ + void set3dSourcePosition(const std::string& identifier, + const glm::vec3& position) const; + + /** + * Returns the list of all tracks that are currently playing. + * + * \return The list of all tracks that are currently playing + */ + std::vector currentlyPlaying() const; + + /** + * Sets the global volume for all track referred to the new \p volume. The total + * for each track is the global volume set by this function multiplied with the volume + * for the specific track set through the #setVolume function. The default value for + * the global volume is 0.5. The volume should be a number bigger than 0, where 1 is + * the maximum volume level. The \p fade controls whether the volume change should be + * immediately (if it is 0) or over how many seconds it should change. The default is + * for it to change over 500 ms. + * + * \param volume The new volume level. Must be greater or equal to 0 + * \param fade How much time the fade from the current volume to the new volume should + * take + */ + void setGlobalVolume(float volume, float fade = 0.5f) const; + + /** + * Returns the global volume for all track. The number returned will be greater or + * equal to 0. + * + * \return The global volume + */ + float globalVolume() const; + + /** + * Sets the position and orientation of the listener. This new position is + * automatically used to adjust the relative position of all 3D tracks. Each parameter + * to this function call is optional and if a value is omitted, the currently set + * value continues to be used instead. The coordinate system for the tracks and the + * listener is a meter-based coordinate system. + * + * \param position The position of the listener. + * \param lookAt The direction vector of the forward direction + * \param up The up-vector of the coordinate system + */ + void set3dListenerParameters(const std::optional& position, + const std::optional& lookAt = std::nullopt, + const std::optional& up = std::nullopt) const; + + /** + * Sets the position of the speaker for the provided \p channel to the provided + * \position. In general, this is considered an advanced feature to accommodate + * non-standard audio environments. + * + * \param channel The channel whose speaker's position should be changed + * \param position The new position for the speaker + */ + void setSpeakerPosition(int channel, const glm::vec3& position) const; + + /** + * Returns the position for the speaker of the provided \p channel. + * \return The position for the speaker of the provided \p channel + */ + glm::vec3 speakerPosition(int channel) const; + +private: + struct Info { + std::unique_ptr sound; + unsigned int handle = 0; + }; + + void internalInitialize(const ghoul::Dictionary&) override; + void internalDeinitializeGL() override; + + /** + * Loads the sound at the provided \p path as an audio source and returns the pointer + * to it. The sound has only been loaded and no other attributes have changed. + * + * \param path The path to the audio file on disk that should be loaded + * \return The SoLoud::Wav object of the loaded file + * \throw ghoul::RuntimeError If the \p path is not a loadable audio file + */ + std::unique_ptr loadSound(const std::filesystem::path& path); + + std::unique_ptr _engine = nullptr; + + std::map _sounds; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_SPACE___AUDIOMODULE___H__ diff --git a/modules/audio/audiomodule_lua.inl b/modules/audio/audiomodule_lua.inl new file mode 100644 index 0000000000..79a1b524f3 --- /dev/null +++ b/modules/audio/audiomodule_lua.inl @@ -0,0 +1,354 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2024 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +namespace { + +/** + * Starts playing the audio file located and the provided \p path. The \p loop parameter + * determines whether the file is only played once, or on a loop. The sound is later + * referred to by the \p identifier name. The audio file will be played in "background" + * mode, which means that each channel will be played at full volume. To play a video + * using spatial audio, use the #playAudio3d function instead. + * + * \param path The audio file that should be played + * \param identifier The name for the sound that is used to refer to the sound + * \param loop If `Yes` then the song will be played in a loop until the program is closed + * or the playing is stopped through the #stopAudio function + */ +[[codegen::luawrap]] void playAudio(std::filesystem::path path, std::string identifier, + bool shouldLoop = true) +{ + using namespace openspace; + + global::moduleEngine->module()->playAudio( + path, + std::move(identifier), + AudioModule::ShouldLoop(shouldLoop) + ); +} + +/** + * Starts playing the audio file located and the provided \p path. The \p loop parameter + * determines whether the file is only played once, or on a loop. The sound is later + * referred to by the \p identifier name. The \p position parameter determines the spatial + * location of the sound in a meter-based coordinate system. The position of the listener + * is (0,0,0) with the forward direction along the +y axis. This means that the "left" + * channel in a stereo setting is towards -x and the "right" channel towards x. This + * default value can be customized through the #set3dListenerParameters function. If you + * want to play a video without spatial audio, use the #playAudio function instead. + * + * \param path The audio file that should be played + * \param identifier The name for the sound that is used to refer to the sound + * \param position The position of the audio file in the 3D environment + * \param loop If `Yes` then the song will be played in a loop until the program is closed + * or the playing is stopped through the #stopAudio function + */ +[[codegen::luawrap]] void playAudio3d(std::filesystem::path path, std::string identifier, + glm::vec3 position, bool shouldLoop = true) +{ + using namespace openspace; + + global::moduleEngine->module()->playAudio3d( + path, + std::move(identifier), + position, + AudioModule::ShouldLoop(shouldLoop) + ); +} + +/** + * Stops the audio referenced by the \p identifier. The \p identifier must be a name for a + * sound that was started through the #playAudio or #playAudio3d functions. After this + * function, the \p identifier can not be used for any other function anymore except for + * #playAudio or #playAudio3d to start a new sound. + * + * \param identifier The identifier to the track that should be stopped + */ +[[codegen::luawrap]] void stopAudio(std::string identifier) { + using namespace openspace; + global::moduleEngine->module()->stopAudio(identifier); +} + +/** + * Stops all currently playing tracks. After this function, none of the identifiers used + * to previously play a sound a valid any longer, but can still be used by the #playAudio + * or #playAudio3d functions to start a new sound. This function behaves the same way as + * if manually calling #stopAudio on all of the sounds that have been started. + */ +[[codegen::luawrap]] void stopAll() { + using namespace openspace; + global::moduleEngine->module()->stopAll(); +} + +/** + * Pauses the playback for all sounds, while keeping them valid. This function behaves the + * same as if calling #pauseAudio on all of the sounds that are currently playing. + */ +[[codegen::luawrap]] void pauseAll() { + using namespace openspace; + global::moduleEngine->module()->pauseAll(); +} + +/** + * Resumes the playback for all sounds that have been paused. Please note that this will + * also resume the playback for the sounds that have been manually paused, not just those + * that were paused through the #pauseAll function. + */ +[[codegen::luawrap]] void resumeAll() { + using namespace openspace; + global::moduleEngine->module()->resumeAll(); +} + +/** + * Takes all of the sounds that are currently registers, unpauses them and plays them + * from their starting points + */ +[[codegen::luawrap]] void playAllFromStart() { + using namespace openspace; + global::moduleEngine->module()->playAllFromStart(); +} + +/** + * Returns whether the track referred to by the \p identifier is currently playing. A + * volume of 0 is still considered to be playing. The \p identifier must be a name for a + * sound that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `true` if the track is currently playing, `false` otherwise + */ +[[codegen::luawrap]] bool isPlaying(std::string identifier) { + using namespace openspace; + return global::moduleEngine->module()->isPlaying(identifier); +} + +/** + * Pauses the playback of the track referred to by the \p identifier. The playback can + * later be resumed through the #resumeAudio function. Trying to pause an already paused + * track will not do anything, but is valid. The \p identifier must be a name for a sound + * that was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + */ +[[codegen::luawrap]] void pauseAudio(std::string identifier) { + using namespace openspace; + global::moduleEngine->module()->pauseAudio(identifier); +} + +/** + * Returns whether the track refered to by the \p identifier is currently playing or + * paused. If it was be paused through a previous call to #pauseAudio, this function will + * return `true`. If it has just been created or resumed through a call to #resumeAudio, + * it will return `false`. The \p identifier must be a name for a sound that was started + * through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `true` if the track is currently paused, `false` if it is playing + */ +[[codegen::luawrap]] bool isPaused(std::string identifier) { + using namespace openspace; + return global::moduleEngine->module()->isPaused(identifier); +} + +/** + * Resumes the playback of a track that was previously paused through the #pauseAudio + * function. Trying to resume an already playing track will not do anything, but is valid. + * The \p identifier must be a name for a sound that was started through the #playAudio or + * #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + */ +[[codegen::luawrap]] void resumeAudio(std::string identifier) { + using namespace openspace; + global::moduleEngine->module()->resumeAudio(identifier); +} + +/** + * Controls whether the track referred to by the \p identifier should be looping or just + * be played once. If a track is converted to not looping, it will finish playing until + * the end of the file. The \p identifier must be a name for a sound that was started + * through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \param loop If `Yes` then the song will be played in a loop until the program is closed + * or the playing is stopped through the #stopAudio function + */ +[[codegen::luawrap]] void setLooping(std::string identifier, bool shouldLoop) { + using namespace openspace; + global::moduleEngine->module()->setLooping( + identifier, + AudioModule::ShouldLoop(shouldLoop) + ); +} + +/** + * Returns whether the track referred to by the \p identifier is set to be looping or + * whether it should played only once. The \p identifier must be a name for a sound that + * was started through the #playAudio or #playAudio3d functions. + * + * \param identifier The identifier to the track that should be stopped + * \return `Yes` if the track is looping, `No` otherwise + */ +[[codegen::luawrap]] bool isLooping(std::string identifier) { + using namespace openspace; + return global::moduleEngine->module()->isLooping(identifier); +} + +/** + * Sets the volume of the track referred to by \p handle to the new \p volume. The volume + * should be a number bigger than 0, where 1 is the maximum volume level. The \p fade + * controls whether the volume change should be immediately (if it is 0) or over how many + * seconds it should change. The default is for it to change over 500 ms. + * + * \param handle The handle to the track whose volume should be changed + * \param volume The new volume level. Must be greater or equal to 0 + * \param fade How much time the fade from the current volume to the new volume should + * take + */ +[[codegen::luawrap]] void setVolume(std::string identifier, float volume, + float fade = 0.5f) +{ + using namespace openspace; + global::moduleEngine->module()->setVolume(identifier, volume, fade); +} + +/** + * Returns the volume for the track referred to by the \p handle. The number returned will + * be greater or equal to 0. + * + * \return The volume for the track referred to by the \p handle, which will be + * greater or equal to 0 + */ +[[codegen::luawrap]] float volume(std::string identifier) { + using namespace openspace; + return global::moduleEngine->module()->volume(identifier); +} + +/** + * Updates the 3D position of a track started through the #playAudio3d function. See that + * function and the #set3dListenerParameters function for a complete description. The + * \p identifier must be a name for a sound that was started through the #playAudio3d + * function. + * + * \param handle A valid handle for a track started through the #playAudio3d function + * \param position The new position from which the track originates + */ +[[codegen::luawrap]] void set3dSourcePosition(std::string identifier, + glm::vec3 position) +{ + using namespace openspace; + global::moduleEngine->module()->set3dSourcePosition( + identifier, + position + ); +} + +/** + * Returns the list of all tracks that are currently playing. + * + * \return The list of all tracks that are currently playing + */ +[[codegen::luawrap]] std::vector currentlyPlaying() { + using namespace openspace; + return global::moduleEngine->module()->currentlyPlaying(); +} + +/** + * Sets the global volume for all track referred to the new \p volume. The total for each + * track is the global volume set by this function multiplied with the volume for the + * specific track set through the #setVolume function. The default value for the global + * volume is 0.5. The volume should be a number bigger than 0, where 1 is the maximum + * volume level. The \p fade controls whether the volume change should be immediately (if + * it is 0) or over how many seconds it should change. The default is for it to change + * over 500 ms. + * + * \param volume The new volume level. Must be greater or equal to 0 + * \param fade How much time the fade from the current volume to the new volume should + * take + */ +[[codegen::luawrap]] void setGlobalVolume(float volume, float fade = 0.5f) { + using namespace openspace; + global::moduleEngine->module()->setGlobalVolume(volume, fade); +} + +/** + * Returns the global volume for all track. The number returned will be greater or equal + * to 0. + * + * \return The global volume + */ +[[codegen::luawrap]] float globalVolume() { + using namespace openspace; + return global::moduleEngine->module()->globalVolume(); +} + +/** + * Sets the position and orientation of the listener. This new position is automatically + * used to adjust the relative position of all 3D tracks. Each parameter to this function + * call is optional and if a value is omitted, the currently set value continues to be + * used instead. The coordinate system for the tracks and the listener is a meter-based + * coordinate system. + * + * \param position The position of the listener. + * \param lookAt The direction vector of the forward direction + * \param up The up-vector of the coordinate system + */ +[[codegen::luawrap]] void set3dListenerPosition(glm::vec3 position, + std::optional lookAt, + std::optional up) +{ + using namespace openspace; + global::moduleEngine->module()->set3dListenerParameters( + position, + lookAt, + up + ); +} + +/** + * Sets the position of the speaker for the provided \p channel to the provided + * \p position. In general, this is considered an advanced feature to accommodate + * non-standard audio environments. + * + * \param channel The channel whose speaker's position should be changed + * \param position The new position for the speaker + */ +[[codegen::luawrap]] void setSpeakerPosition(int handle, glm::vec3 position) { + using namespace openspace; + global::moduleEngine->module()->setSpeakerPosition(handle, position); +} + +/** + * Returns the position for the speaker of the provided \p channel. + * \return The position for the speaker of the provided \p channel + */ +[[codegen::luawrap]] glm::vec3 speakerPosition(int handle) { + using namespace openspace; + return global::moduleEngine->module()->speakerPosition(handle); +} + +#include "audiomodule_lua_codegen.cpp" + +} // namespace diff --git a/modules/audio/ext/soloud b/modules/audio/ext/soloud new file mode 160000 index 0000000000..1157475881 --- /dev/null +++ b/modules/audio/ext/soloud @@ -0,0 +1 @@ +Subproject commit 1157475881da0d7f76102578255b937c7d4e8f57 diff --git a/modules/base/CMakeLists.txt b/modules/base/CMakeLists.txt index e3168b3272..53ad712da3 100644 --- a/modules/base/CMakeLists.txt +++ b/modules/base/CMakeLists.txt @@ -47,6 +47,7 @@ set(HEADER_FILES rendering/pointcloud/renderableinterpolatedpoints.h rendering/pointcloud/renderablepointcloud.h rendering/pointcloud/renderablepolygoncloud.h + rendering/pointcloud/sizemappingcomponent.h rendering/renderablecartesianaxes.h rendering/renderabledisc.h rendering/renderablelabel.h @@ -109,6 +110,7 @@ set(SOURCE_FILES rendering/pointcloud/renderableinterpolatedpoints.cpp rendering/pointcloud/renderablepointcloud.cpp rendering/pointcloud/renderablepolygoncloud.cpp + rendering/pointcloud/sizemappingcomponent.cpp rendering/renderablecartesianaxes.cpp rendering/renderabledisc.cpp rendering/renderablelabel.cpp diff --git a/modules/base/basemodule.cpp b/modules/base/basemodule.cpp index 9dc5c9e9b4..011cce0547 100644 --- a/modules/base/basemodule.cpp +++ b/modules/base/basemodule.cpp @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -251,6 +252,8 @@ std::vector BaseModule::documentations() const { RenderableTrailOrbit::Documentation(), RenderableTrailTrajectory::Documentation(), + SizeMappingComponent::Documentation(), + ScreenSpaceDashboard::Documentation(), ScreenSpaceFramebuffer::Documentation(), ScreenSpaceImageLocal::Documentation(), diff --git a/modules/base/dashboard/dashboarditemangle.cpp b/modules/base/dashboard/dashboarditemangle.cpp index eac1046265..4a59cbdd66 100644 --- a/modules/base/dashboard/dashboarditemangle.cpp +++ b/modules/base/dashboard/dashboarditemangle.cpp @@ -257,9 +257,56 @@ DashboardItemAngle::DashboardItemAngle(const ghoul::Dictionary& dictionary) _buffer.resize(128); } -std::pair DashboardItemAngle::positionAndLabel( - Component& comp) const -{ +void DashboardItemAngle::render(glm::vec2& penPosition) { + ZoneScoped; + + std::pair sourceInfo = positionAndLabel(_source); + std::pair referenceInfo = positionAndLabel(_reference); + std::pair destinationInfo = positionAndLabel(_destination); + + const glm::dvec3 a = referenceInfo.first - sourceInfo.first; + const glm::dvec3 b = destinationInfo.first - sourceInfo.first; + + std::fill(_buffer.begin(), _buffer.end(), char(0)); + if (glm::length(a) == 0.0 || glm::length(b) == 0) { + char* end = std::format_to( + _buffer.data(), + "Could not compute angle at {} between {} and {}", + sourceInfo.second, destinationInfo.second, referenceInfo.second + ); + const std::string_view text = std::string_view( + _buffer.data(), + end - _buffer.data() + ); + RenderFont(*_font, penPosition, text); + penPosition.y -= _font->height(); + } + else { + const double angle = glm::degrees( + glm::acos(glm::dot(a, b) / (glm::length(a) * glm::length(b))) + ); + + char* end = std::format_to( + _buffer.data(), + "Angle at {} between {} and {}: {} degrees", + sourceInfo.second, destinationInfo.second, referenceInfo.second, angle + ); + const std::string_view text = std::string_view( + _buffer.data(), end - _buffer.data() + ); + RenderFont(*_font, penPosition, text); + penPosition.y -= _font->height(); + } +} + +glm::vec2 DashboardItemAngle::size() const { + ZoneScoped; + + constexpr double Angle = 120; + return _font->boundingBox("Angle: " + std::to_string(Angle)); +} + +std::pair DashboardItemAngle::positionAndLabel(Component& comp) { if (comp.type == Type::Node) { if (!comp.node) { comp.node = global::renderEngine->scene()->sceneGraphNode(comp.nodeName); @@ -293,48 +340,4 @@ std::pair DashboardItemAngle::positionAndLabel( } } -void DashboardItemAngle::render(glm::vec2& penPosition) { - ZoneScoped; - - std::pair sourceInfo = positionAndLabel(_source); - std::pair referenceInfo = positionAndLabel(_reference); - std::pair destinationInfo = positionAndLabel(_destination); - - const glm::dvec3 a = referenceInfo.first - sourceInfo.first; - const glm::dvec3 b = destinationInfo.first - sourceInfo.first; - - std::fill(_buffer.begin(), _buffer.end(), char(0)); - if (glm::length(a) == 0.0 || glm::length(b) == 0) { - char* end = fmt::format_to( - _buffer.data(), - "Could not compute angle at {} between {} and {}", - sourceInfo.second, destinationInfo.second, referenceInfo.second - ); - std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); - RenderFont(*_font, penPosition, text); - penPosition.y -= _font->height(); - } - else { - const double angle = glm::degrees( - glm::acos(glm::dot(a, b) / (glm::length(a) * glm::length(b))) - ); - - char* end = fmt::format_to( - _buffer.data(), - "Angle at {} between {} and {}: {} degrees", - sourceInfo.second, destinationInfo.second, referenceInfo.second, angle - ); - std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); - RenderFont(*_font, penPosition, text); - penPosition.y -= _font->height(); - } -} - -glm::vec2 DashboardItemAngle::size() const { - ZoneScoped; - - constexpr double Angle = 120; - return _font->boundingBox("Angle: " + std::to_string(Angle)); -} - } // namespace openspace diff --git a/modules/base/dashboard/dashboarditemangle.h b/modules/base/dashboard/dashboarditemangle.h index c92b6edd71..1e44bbdf55 100644 --- a/modules/base/dashboard/dashboarditemangle.h +++ b/modules/base/dashboard/dashboarditemangle.h @@ -55,7 +55,7 @@ private: SceneGraphNode* node; }; - std::pair positionAndLabel(Component& comp) const; + static std::pair positionAndLabel(Component& comp); Component _source; Component _reference; diff --git a/modules/base/dashboard/dashboarditemdate.cpp b/modules/base/dashboard/dashboarditemdate.cpp index 2a9d6574b9..f2fe23b3a3 100644 --- a/modules/base/dashboard/dashboarditemdate.cpp +++ b/modules/base/dashboard/dashboarditemdate.cpp @@ -97,10 +97,11 @@ void DashboardItemDate::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_formatString.value()), time) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_formatString.value(), std::make_format_args(time)) ); } - catch (const fmt::format_error&) { + catch (const std::format_error&) { LERRORC("DashboardItemDate", "Illegal format string"); } penPosition.y -= _font->height(); @@ -110,7 +111,10 @@ glm::vec2 DashboardItemDate::size() const { ZoneScoped; std::string_view time = global::timeManager->time().UTC(); - return _font->boundingBox(fmt::format(fmt::runtime(_formatString.value()), time)); + // @CPP26(abock): This can be replaced with std::runtime_format + return _font->boundingBox( + std::vformat(_formatString.value(), std::make_format_args(time)) + ); } } // namespace openspace diff --git a/modules/base/dashboard/dashboarditemdistance.cpp b/modules/base/dashboard/dashboarditemdistance.cpp index 08d83464bd..b3dcf73d25 100644 --- a/modules/base/dashboard/dashboarditemdistance.cpp +++ b/modules/base/dashboard/dashboarditemdistance.cpp @@ -266,7 +266,7 @@ DashboardItemDistance::DashboardItemDistance(const ghoul::Dictionary& dictionary }); addProperty(_doSimplification); - for (DistanceUnit u : DistanceUnits) { + for (const DistanceUnit u : DistanceUnits) { _requestedUnit.addOption( static_cast(u), std::string(nameForDistanceUnit(u)) @@ -274,7 +274,7 @@ DashboardItemDistance::DashboardItemDistance(const ghoul::Dictionary& dictionary } _requestedUnit = static_cast(DistanceUnit::Meter); if (p.requestedUnit.has_value()) { - DistanceUnit unit = distanceUnitFromString(p.requestedUnit->c_str()); + const DistanceUnit unit = distanceUnitFromString(*p.requestedUnit); _requestedUnit = static_cast(unit); } _requestedUnit.setVisibility(properties::Property::Visibility::Hidden); @@ -323,9 +323,9 @@ std::pair DashboardItemDistance::positionAndLabel( const glm::dvec3 thisPos = mainComp.node->worldPosition(); const glm::dvec3 dir = glm::normalize(otherPos - thisPos); - glm::dvec3 dirLength = dir * glm::dvec3(mainComp.node->boundingSphere()); + const glm::dvec3 dirLen = dir * glm::dvec3(mainComp.node->boundingSphere()); - return { thisPos + dirLength, "surface of " + mainComp.node->guiName() }; + return { thisPos + dirLen, "surface of " + mainComp.node->guiName() }; } case Type::Focus: { const SceneGraphNode* anchor = @@ -369,16 +369,22 @@ void DashboardItemDistance::render(glm::vec2& penPosition) { std::fill(_buffer.begin(), _buffer.end(), char(0)); try { - char* end = fmt::format_to( + // @CPP26(abock): This can be replaced with std::runtime_format + char* end = std::vformat_to( _buffer.data(), - fmt::runtime(_formatString.value()), - sourceInfo.second, destinationInfo.second, dist.first, dist.second + _formatString.value(), + std::make_format_args( + sourceInfo.second, + destinationInfo.second, + dist.first, + dist.second + ) ); - std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); - RenderFont(*_font, penPosition, text); + const std::string_view t = std::string_view(_buffer.data(), end - _buffer.data()); + RenderFont(*_font, penPosition, t); } - catch (const fmt::format_error&) { + catch (const std::format_error&) { LERRORC("DashboardItemDate", "Illegal format string"); } penPosition.y -= _font->height(); @@ -393,13 +399,13 @@ glm::vec2 DashboardItemDistance::size() const { dist = simplifyDistance(d); } else { - DistanceUnit unit = static_cast(_requestedUnit.value()); - double convertedD = convertMeters(d, unit); + const DistanceUnit unit = static_cast(_requestedUnit.value()); + const double convertedD = convertMeters(d, unit); dist = std::pair(convertedD, nameForDistanceUnit(unit, convertedD != 1.0)); } return _font->boundingBox( - fmt::format("Distance from focus: {} {}", dist.first, dist.second) + std::format("Distance from focus: {} {}", dist.first, dist.second) ); } diff --git a/modules/base/dashboard/dashboarditemelapsedtime.cpp b/modules/base/dashboard/dashboarditemelapsedtime.cpp index adf5ee5216..9e231f8840 100644 --- a/modules/base/dashboard/dashboarditemelapsedtime.cpp +++ b/modules/base/dashboard/dashboarditemelapsedtime.cpp @@ -127,11 +127,11 @@ DashboardItemElapsedTime::DashboardItemElapsedTime(const ghoul::Dictionary& dict _simplifyTime = p.simplifyTime.value_or(_simplifyTime); addProperty(_simplifyTime); - for (TimeUnit u : TimeUnits) { + for (const TimeUnit u : TimeUnits) { _lowestTimeUnit.addOption(static_cast(u), std::string(nameForTimeUnit(u))); } _lowestTimeUnit = static_cast(TimeUnit::Second); - TimeUnit u = codegen::map( + const TimeUnit u = codegen::map( p.lowestTimeUnit.value_or(Parameters::TimeUnit::Second) ); _lowestTimeUnit = static_cast(u); @@ -141,19 +141,19 @@ DashboardItemElapsedTime::DashboardItemElapsedTime(const ghoul::Dictionary& dict void DashboardItemElapsedTime::render(glm::vec2& penPosition) { ZoneScoped; - double delta = global::timeManager->time().j2000Seconds() - _referenceJ2000; + const double delta = global::timeManager->time().j2000Seconds() - _referenceJ2000; if (_simplifyTime) { using namespace std::chrono; - TimeUnit lowestTime = TimeUnit(_lowestTimeUnit.value()); - std::string_view lowestUnitS = nameForTimeUnit(lowestTime, false); - std::string_view lowestUnitP = nameForTimeUnit(lowestTime, true); + const TimeUnit lowestTime = TimeUnit(_lowestTimeUnit.value()); + const std::string_view lowestUnitS = nameForTimeUnit(lowestTime, false); + const std::string_view lowestUnitP = nameForTimeUnit(lowestTime, true); - std::vector> ts = splitTime(delta); + const std::vector> ts = splitTime(delta); std::string time; for (const std::pair& t : ts) { - time += fmt::format("{} {} ", t.first, t.second); + time += std::format("{} {} ", t.first, t.second); if (t.second == lowestUnitS || t.second == lowestUnitP) { // We have reached the lowest unit the user was interested in break; @@ -166,15 +166,17 @@ void DashboardItemElapsedTime::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_formatString.value()), time) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_formatString.value(), std::make_format_args(time)) ); } else { - std::string time = fmt::format("{} s", delta); + std::string time = std::format("{} s", delta); RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_formatString.value()), time) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_formatString.value(), std::make_format_args(time)) ); } @@ -185,7 +187,10 @@ glm::vec2 DashboardItemElapsedTime::size() const { ZoneScoped; const double delta = global::timeManager->time().j2000Seconds() - _referenceJ2000; - return _font->boundingBox(fmt::format(fmt::runtime(_formatString.value()), delta)); + // @CPP26(abock): This can be replaced with std::runtime_format + return _font->boundingBox( + std::vformat(_formatString.value(), std::make_format_args(delta)) + ); } } // namespace openspace diff --git a/modules/base/dashboard/dashboarditemframerate.cpp b/modules/base/dashboard/dashboarditemframerate.cpp index a55c171eb5..279c9e200b 100644 --- a/modules/base/dashboard/dashboarditemframerate.cpp +++ b/modules/base/dashboard/dashboarditemframerate.cpp @@ -62,7 +62,7 @@ namespace { }; [[ nodiscard ]] char* formatDt(std::vector& buffer) { - return fmt::format_to( + return std::format_to( buffer.data(), "Avg. Frametime: {:.2f} ms\0", openspace::global::windowDelegate->averageDeltaTime() * 1000.0 @@ -73,7 +73,7 @@ namespace { double minFrametimeCache, double maxFrametimeCache) { - return fmt::format_to( + return std::format_to( buffer.data(), "Last frametimes between: {:.2f} and {:.2f} ms\n" "Overall between: {:.2f} and {:.2f} ms\0", @@ -85,7 +85,7 @@ namespace { } [[ nodiscard ]] char* formatDtStandardDeviation(std::vector& buffer) { - return fmt::format_to( + return std::format_to( buffer.data(), "Frametime standard deviation : {:.2f} ms\0", openspace::global::windowDelegate->deltaTimeStandardDeviation() * 1000.0 @@ -93,7 +93,7 @@ namespace { } [[ nodiscard ]] char* formatDtCoefficientOfVariation(std::vector& buffer) { - return fmt::format_to( + return std::format_to( buffer.data(), "Frametime coefficient of variation : {:.2f} %\0", openspace::global::windowDelegate->deltaTimeStandardDeviation() / @@ -102,7 +102,7 @@ namespace { } [[ nodiscard ]] char* formatFps(std::vector& buffer) { - return fmt::format_to( + return std::format_to( buffer.data(), "FPS: {:3.2f}\0", 1.0 / openspace::global::windowDelegate->deltaTime() @@ -110,7 +110,7 @@ namespace { } [[ nodiscard ]] char* formatAverageFps(std::vector& buffer) { - return fmt::format_to( + return std::format_to( buffer.data(), "Avg. FPS: {:3.2f}\0", 1.0 / openspace::global::windowDelegate->averageDeltaTime() @@ -223,7 +223,7 @@ void DashboardItemFramerate::render(glm::vec2& penPosition) { global::windowDelegate->maxDeltaTime() * 1000.0 ); - FrametimeType frametimeType = FrametimeType(_frametimeType.value()); + const FrametimeType frametimeType = FrametimeType(_frametimeType.value()); std::fill(_buffer.begin(), _buffer.end(), char(0)); char* end = format( @@ -232,15 +232,16 @@ void DashboardItemFramerate::render(glm::vec2& penPosition) { _minDeltaTimeCache, _maxDeltaTimeCache ); - std::string_view output = std::string_view(_buffer.data(), end - _buffer.data()); + const std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); - int nLines = output.empty() ? 0 : - static_cast((std::count(output.begin(), output.end(), '\n') + 1)); + const int nLines = text.empty() ? + 0 : + static_cast((std::count(text.begin(), text.end(), '\n') + 1)); ghoul::fontrendering::FontRenderer::defaultRenderer().render( *_font, penPosition, - output + text ); penPosition.y -= _font->height() * static_cast(nLines); } @@ -250,13 +251,13 @@ glm::vec2 DashboardItemFramerate::size() const { const FrametimeType t = FrametimeType(_frametimeType.value()); char* end = format(_buffer, t, _minDeltaTimeCache, _maxDeltaTimeCache); - std::string_view output = std::string_view(_buffer.data(), end - _buffer.data()); + const std::string_view res = std::string_view(_buffer.data(), end - _buffer.data()); - if (output.empty()) { + if (res.empty()) { return { 0.f, 0.f }; } - return _font->boundingBox(output); + return _font->boundingBox(res); } } // namespace openspace diff --git a/modules/base/dashboard/dashboarditeminputstate.cpp b/modules/base/dashboard/dashboarditeminputstate.cpp index 206fa6865e..ed28511707 100644 --- a/modules/base/dashboard/dashboarditeminputstate.cpp +++ b/modules/base/dashboard/dashboarditeminputstate.cpp @@ -135,12 +135,12 @@ void DashboardItemInputState::render(glm::vec2& penPosition) { if (_showKeyboard) { if (global::navigationHandler->disabledKeybindings()) { if (_showWhenDisabled) { - text.push_back("Keyboard shortcuts disabled"); + text.emplace_back("Keyboard shortcuts disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Keyboard shortcuts enabled"); + text.emplace_back("Keyboard shortcuts enabled"); } } } @@ -148,12 +148,12 @@ void DashboardItemInputState::render(glm::vec2& penPosition) { if (_showMouse) { if (global::navigationHandler->disabledMouse()) { if (_showWhenDisabled) { - text.push_back("Mouse input disabled"); + text.emplace_back("Mouse input disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Mouse input enabled"); + text.emplace_back("Mouse input enabled"); } } } @@ -161,18 +161,18 @@ void DashboardItemInputState::render(glm::vec2& penPosition) { if (_showJoystick) { if (global::navigationHandler->disabledJoystick()) { if (_showWhenDisabled) { - text.push_back("Joystick input disabled"); + text.emplace_back("Joystick input disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Joystick input enabled"); + text.emplace_back("Joystick input enabled"); } } } if (!text.empty()) { - std::string t = ghoul::join(std::move(text), "\n"); + const std::string t = ghoul::join(std::move(text), "\n"); RenderFont(*_font, penPosition, t); penPosition.y -= _font->height(); } @@ -185,12 +185,12 @@ glm::vec2 DashboardItemInputState::size() const { if (_showKeyboard) { if (global::navigationHandler->disabledKeybindings()) { if (_showWhenDisabled) { - text.push_back("Keyboard shortcuts disabled"); + text.emplace_back("Keyboard shortcuts disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Keyboard shortcuts enabled"); + text.emplace_back("Keyboard shortcuts enabled"); } } } @@ -198,12 +198,12 @@ glm::vec2 DashboardItemInputState::size() const { if (_showMouse) { if (global::navigationHandler->disabledMouse()) { if (_showWhenDisabled) { - text.push_back("Mouse input disabled"); + text.emplace_back("Mouse input disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Mouse input disabled"); + text.emplace_back("Mouse input disabled"); } } } @@ -211,18 +211,18 @@ glm::vec2 DashboardItemInputState::size() const { if (_showJoystick) { if (global::navigationHandler->disabledJoystick()) { if (_showWhenDisabled) { - text.push_back("Joystick input disabled"); + text.emplace_back("Joystick input disabled"); } } else { if (_showWhenEnabled) { - text.push_back("Joystick input disabled"); + text.emplace_back("Joystick input disabled"); } } } if (!text.empty()) { - std::string t = ghoul::join(std::move(text), "\n"); + const std::string t = ghoul::join(std::move(text), "\n"); return _font->boundingBox(t); } else { diff --git a/modules/base/dashboard/dashboarditemmission.cpp b/modules/base/dashboard/dashboarditemmission.cpp index 41291ea85b..bd6c589e5d 100644 --- a/modules/base/dashboard/dashboarditemmission.cpp +++ b/modules/base/dashboard/dashboarditemmission.cpp @@ -72,7 +72,7 @@ void DashboardItemMission::render(glm::vec2& penPosition) { if (!global::missionManager->hasCurrentMission()) { return; } - double currentTime = global::timeManager->time().j2000Seconds(); + const double currentTime = global::timeManager->time().j2000Seconds(); const Mission& mission = global::missionManager->currentMission(); if (mission.phases().empty()) { @@ -99,7 +99,7 @@ void DashboardItemMission::render(glm::vec2& penPosition) { penPosition.y -= _font->height(); RenderFont(*_font, penPosition, title, missionProgressColor); double remaining = phase.timeRange().end - currentTime; - float t = static_cast( + const float t = static_cast( 1.0 - remaining / phase.timeRange().duration() ); std::string progress = progressToStr(25, t); @@ -107,7 +107,7 @@ void DashboardItemMission::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format("{:.0f} s {:s} {:.1f} %", remaining, progress, t * 100), + std::format("{:.0f} s {:s} {:.1f} %", remaining, progress, t * 100), missionProgressColor ); } @@ -119,18 +119,18 @@ void DashboardItemMission::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format("{:.0f} s", remaining), + std::format("{:.0f} s", remaining), nextMissionColor ); } - bool showAllPhases = false; + constexpr bool ShowAllPhases = false; using PhaseWithDepth = std::pair; std::stack S; constexpr int PixelIndentation = 20; - S.push({ &mission, 0 }); + S.emplace(&mission, 0); while (!S.empty()) { const MissionPhase* phase = S.top().first; const int depth = S.top().second; @@ -148,7 +148,7 @@ void DashboardItemMission::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format( + std::format( "{:s} {:s} {:.1f} %", phase->name(),progress,t * 100 ), @@ -169,15 +169,13 @@ void DashboardItemMission::render(glm::vec2& penPosition) { } penPosition.x -= depth * PixelIndentation; - if (isCurrentPhase || showAllPhases) { + if (isCurrentPhase || ShowAllPhases) { // phases are sorted increasingly by start time, and will be // popped last-in-first-out from the stack, so add them in // reversed order. - int indexLastPhase = static_cast( - phase->phases().size() - ) - 1; + const int indexLastPhase = static_cast(phase->phases().size()) - 1; for (int i = indexLastPhase; 0 <= i; --i) { - S.push({ &phase->phases()[i], depth + 1 }); + S.emplace(&phase->phases()[i], depth + 1); } } } diff --git a/modules/base/dashboard/dashboarditemparallelconnection.cpp b/modules/base/dashboard/dashboarditemparallelconnection.cpp index f021da65ce..7e475b2e14 100644 --- a/modules/base/dashboard/dashboarditemparallelconnection.cpp +++ b/modules/base/dashboard/dashboarditemparallelconnection.cpp @@ -68,8 +68,8 @@ void DashboardItemParallelConnection::render(glm::vec2& penPosition) { connectionInfo = (nClients == 1) ? - fmt::format(Singular, nClients) : - fmt::format(Plural, nClients); + std::format(Singular, nClients) : + std::format(Plural, nClients); } else if (status == ParallelConnection::Status::ClientWithHost) { nClients--; @@ -86,11 +86,11 @@ void DashboardItemParallelConnection::render(glm::vec2& penPosition) { if (nClients > 2) { constexpr std::string_view Plural = "You and {} more clients are tuned in"; - connectionInfo += fmt::format(Plural, nClients - 1); + connectionInfo += std::format(Plural, nClients - 1); } else if (nClients == 2) { constexpr std::string_view Singular = "You and {} more client are tuned in"; - connectionInfo += fmt::format(Singular, nClients - 1); + connectionInfo += std::format(Singular, nClients - 1); } else if (nClients == 1) { connectionInfo += "You are the only client"; @@ -108,8 +108,8 @@ void DashboardItemParallelConnection::render(glm::vec2& penPosition) { glm::vec2 DashboardItemParallelConnection::size() const { ZoneScoped; - ParallelConnection::Status status = global::parallelPeer->status(); - size_t nConnections = global::parallelPeer->nConnections(); + const ParallelConnection::Status status = global::parallelPeer->status(); + const size_t nConnections = global::parallelPeer->nConnections(); const std::string& hostName = global::parallelPeer->hostName(); std::string connectionInfo; @@ -120,7 +120,7 @@ glm::vec2 DashboardItemParallelConnection::size() const { connectionInfo = "Hosting session with 1 client"; } else { - connectionInfo = fmt::format("Hosting session with {} clients", nClients); + connectionInfo = std::format("Hosting session with {} clients", nClients); } } else if (status == ParallelConnection::Status::ClientWithHost) { @@ -137,11 +137,11 @@ glm::vec2 DashboardItemParallelConnection::size() const { connectionInfo += "\n"; if (nClients > 2) { constexpr std::string_view Plural = "You and {} more clients are tuned in"; - connectionInfo += fmt::format(Plural, nClients); + connectionInfo += std::format(Plural, nClients); } else if (nClients == 2) { constexpr std::string_view Singular = "You and {} more client are tuned in"; - connectionInfo += fmt::format(Singular, nClients - 1); + connectionInfo += std::format(Singular, nClients - 1); } else if (nClients == 1) { connectionInfo += "You are the only client"; diff --git a/modules/base/dashboard/dashboarditempropertyvalue.cpp b/modules/base/dashboard/dashboarditempropertyvalue.cpp index 7ffea7cb35..49f48920a5 100644 --- a/modules/base/dashboard/dashboarditempropertyvalue.cpp +++ b/modules/base/dashboard/dashboarditempropertyvalue.cpp @@ -118,13 +118,14 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { } if (_property) { - std::string_view type = _property->className(); + const std::string_view type = _property->className(); if (type == "DoubleProperty") { double value = static_cast(_property)->value(); RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } else if (type == "FloatProperty") { @@ -132,7 +133,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } else if (type == "IntProperty") { @@ -140,7 +142,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } else if (type == "LongProperty") { @@ -148,7 +151,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } else if (type == "ShortProperty") { @@ -156,7 +160,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } else if (type == "UIntProperty") { @@ -164,7 +169,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v)) ); } else if (type == "ULongProperty") { @@ -172,7 +178,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v)) ); } else if (type == "UShortProperty") { @@ -181,7 +188,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v)) ); } else if (type == "DVec2Property") { @@ -189,7 +197,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y)) ); } else if (type == "DVec3Property") { @@ -197,7 +206,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y, v.z)) ); } else if (type == "DVec4Property") { @@ -205,7 +215,11 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z, v.w) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _displayString.value(), + std::make_format_args(v.x, v.y, v.z, v.w) + ) ); } else if (type == "IVec2Property") { @@ -213,7 +227,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y)) ); } else if (type == "IVec3Property") { @@ -221,7 +236,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y, v.z)) ); } else if (type == "IVec4Property") { @@ -229,7 +245,11 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z, v.w) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _displayString.value(), + std::make_format_args(v.x, v.y, v.z, v.w) + ) ); } else if (type == "UVec2Property") { @@ -237,7 +257,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y)) ); } else if (type == "UVec3Property") { @@ -245,7 +266,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y, v.z)) ); } else if (type == "UVec4Property") { @@ -253,7 +275,11 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z, v.w) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _displayString.value(), + std::make_format_args(v.x, v.y, v.z, v.w) + ) ); } else if (type == "Vec2Property") { @@ -261,7 +287,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y)) ); } else if (type == "Vec3Property") { @@ -269,7 +296,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(v.x, v.y, v.z)) ); } else if (type == "Vec4Property") { @@ -277,7 +305,11 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), v.x, v.y, v.z, v.w) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _displayString.value(), + std::make_format_args(v.x, v.y, v.z, v.w) + ) ); } else { @@ -287,7 +319,8 @@ void DashboardItemPropertyValue::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(fmt::runtime(_displayString.value()), value) + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat(_displayString.value(), std::make_format_args(value)) ); } diff --git a/modules/base/dashboard/dashboarditemsimulationincrement.cpp b/modules/base/dashboard/dashboarditemsimulationincrement.cpp index ae5313ed56..3707c7ce08 100644 --- a/modules/base/dashboard/dashboarditemsimulationincrement.cpp +++ b/modules/base/dashboard/dashboarditemsimulationincrement.cpp @@ -138,12 +138,12 @@ DashboardItemSimulationIncrement::DashboardItemSimulationIncrement( }); addProperty(_doSimplification); - for (TimeUnit u : TimeUnits) { + for (const TimeUnit u : TimeUnits) { _requestedUnit.addOption(static_cast(u), std::string(nameForTimeUnit(u))); } _requestedUnit = static_cast(TimeUnit::Second); if (p.requestedUnit.has_value()) { - TimeUnit unit = timeUnitFromString(p.requestedUnit->c_str()); + const TimeUnit unit = timeUnitFromString(*p.requestedUnit); _requestedUnit = static_cast(unit); } _requestedUnit.setVisibility(properties::Property::Visibility::Hidden); @@ -195,11 +195,14 @@ void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format( - fmt::runtime(_transitionFormat.value()), - targetDeltaTime.first, targetDeltaTime.second, - pauseText, - currentDeltaTime.first, currentDeltaTime.second + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _transitionFormat.value(), + std::make_format_args( + targetDeltaTime.first, targetDeltaTime.second, + pauseText, + currentDeltaTime.first, currentDeltaTime.second + ) ) ); } @@ -207,14 +210,19 @@ void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format( - fmt::runtime(_regularFormat.value()), - targetDeltaTime.first, targetDeltaTime.second, pauseText + // @CPP26(abock): This can be replaced with std::runtime_format + std::vformat( + _regularFormat.value(), + std::make_format_args( + targetDeltaTime.first, + targetDeltaTime.second, + pauseText + ) ) ); } } - catch (const fmt::format_error&) { + catch (const std::format_error&) { LERRORC("DashboardItemDate", "Illegal format string"); } penPosition.y -= _font->height(); @@ -223,14 +231,14 @@ void DashboardItemSimulationIncrement::render(glm::vec2& penPosition) { glm::vec2 DashboardItemSimulationIncrement::size() const { ZoneScoped; - double t = global::timeManager->targetDeltaTime(); + const double t = global::timeManager->targetDeltaTime(); std::pair deltaTime; if (_doSimplification) { deltaTime = simplifyTime(t); } else { - TimeUnit unit = static_cast(_requestedUnit.value()); - double convertedT = convertTime(t, TimeUnit::Second, unit); + const TimeUnit unit = static_cast(_requestedUnit.value()); + const double convertedT = convertTime(t, TimeUnit::Second, unit); deltaTime = std::pair( convertedT, std::string(nameForTimeUnit(unit, convertedT != 1.0)) @@ -238,7 +246,7 @@ glm::vec2 DashboardItemSimulationIncrement::size() const { } return _font->boundingBox( - fmt::format( + std::format( "Simulation increment: {:.1f} {:s} / second", deltaTime.first, deltaTime.second ) diff --git a/modules/base/dashboard/dashboarditemvelocity.cpp b/modules/base/dashboard/dashboarditemvelocity.cpp index 5f975b12e2..bea74ca374 100644 --- a/modules/base/dashboard/dashboarditemvelocity.cpp +++ b/modules/base/dashboard/dashboarditemvelocity.cpp @@ -106,7 +106,7 @@ DashboardItemVelocity::DashboardItemVelocity(const ghoul::Dictionary& dictionary }); addProperty(_doSimplification); - for (DistanceUnit u : DistanceUnits) { + for (const DistanceUnit u : DistanceUnits) { _requestedUnit.addOption( static_cast(u), std::string(nameForDistanceUnit(u)) @@ -114,7 +114,7 @@ DashboardItemVelocity::DashboardItemVelocity(const ghoul::Dictionary& dictionary } _requestedUnit = static_cast(DistanceUnit::Meter); if (p.requestedUnit.has_value()) { - DistanceUnit unit = distanceUnitFromString(p.requestedUnit->c_str()); + const DistanceUnit unit = distanceUnitFromString(*p.requestedUnit); _requestedUnit = static_cast(unit); } _requestedUnit.setVisibility(properties::Property::Visibility::Hidden); @@ -145,9 +145,7 @@ void DashboardItemVelocity::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format( - "Camera velocity: {:.4f} {}/s", dist.first, dist.second - ) + std::format("Camera velocity: {:.4f} {}/s", dist.first, dist.second) ); penPosition.y -= _font->height(); @@ -163,13 +161,13 @@ glm::vec2 DashboardItemVelocity::size() const { dist = simplifyDistance(d); } else { - DistanceUnit unit = static_cast(_requestedUnit.value()); - double convertedD = convertMeters(d, unit); + const DistanceUnit unit = static_cast(_requestedUnit.value()); + const double convertedD = convertMeters(d, unit); dist = std::pair(convertedD, nameForDistanceUnit(unit, convertedD != 1.0)); } return _font->boundingBox( - fmt::format("Camera velocity: {} {}/s", dist.first, dist.second) + std::format("Camera velocity: {} {}/s", dist.first, dist.second) ); } diff --git a/modules/base/rendering/grids/renderableboxgrid.cpp b/modules/base/rendering/grids/renderableboxgrid.cpp index 14056eb28c..d53632c94f 100644 --- a/modules/base/rendering/grids/renderableboxgrid.cpp +++ b/modules/base/rendering/grids/renderableboxgrid.cpp @@ -58,7 +58,7 @@ namespace { openspace::properties::Property::Visibility::AdvancedUser }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the grid" @@ -210,7 +210,7 @@ void RenderableBoxGrid::render(const RenderData& data, RendererTasks&){ ); if (orthoRight == glm::vec3(0.0)) { - glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) diff --git a/modules/base/rendering/grids/renderablegrid.cpp b/modules/base/rendering/grids/renderablegrid.cpp index 4e7586cc7b..ba03ab9f00 100644 --- a/modules/base/rendering/grids/renderablegrid.cpp +++ b/modules/base/rendering/grids/renderablegrid.cpp @@ -92,7 +92,7 @@ namespace { openspace::properties::Property::Visibility::User }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the grid" @@ -262,7 +262,7 @@ void RenderableGrid::render(const RenderData& data, RendererTasks&){ ); if (orthoRight == glm::vec3(0.0)) { - glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) @@ -336,8 +336,8 @@ void RenderableGrid::update(const UpdateData&) { // If the number of segments are uneven the center won't be completly centered const glm::uvec2 center = glm::uvec2(nSegments.x / 2.f, nSegments.y / 2.f); - for (unsigned int i = 0; i < nSegments.x; ++i) { - for (unsigned int j = 0; j < nSegments.y; ++j) { + for (unsigned int i = 0; i < nSegments.x; i++) { + for (unsigned int j = 0; j < nSegments.y; j++) { const double y0 = -halfSize.y + j * step.y; const double y1 = y0 + step.y; @@ -347,8 +347,8 @@ void RenderableGrid::update(const UpdateData&) { // Line in y direction bool shouldHighlight = false; if (_highlightRate.value().x != 0) { - int dist = abs(static_cast(i) - static_cast(center.x)); - int rest = dist % _highlightRate.value().x; + const int dist = abs(static_cast(i) - static_cast(center.x)); + const int rest = dist % _highlightRate.value().x; shouldHighlight = rest == 0; } @@ -364,8 +364,8 @@ void RenderableGrid::update(const UpdateData&) { // Line in x direction shouldHighlight = false; if (_highlightRate.value().y != 0) { - int dist = abs(static_cast(j) - static_cast(center.y)); - int rest = dist % _highlightRate.value().y; + const int dist = abs(static_cast(j) - static_cast(center.y)); + const int rest = dist % _highlightRate.value().y; shouldHighlight = abs(rest) == 0; } @@ -381,15 +381,17 @@ void RenderableGrid::update(const UpdateData&) { } // last x row - for (unsigned int i = 0; i < nSegments.x; ++i) { + for (unsigned int i = 0; i < nSegments.x; i++) { const double x0 = -halfSize.x + i * step.x; const double x1 = x0 + step.x; bool shouldHighlight = false; if (_highlightRate.value().y != 0) { - int dist = abs(static_cast(nSegments.y) - static_cast(center.y)); - int rest = dist % _highlightRate.value().y; - shouldHighlight = abs(rest) == 0; + const int dist = std::abs( + static_cast(nSegments.y) - static_cast(center.y) + ); + const int rest = dist % _highlightRate.value().y; + shouldHighlight = std::abs(rest) == 0; } if (shouldHighlight) { @@ -403,15 +405,17 @@ void RenderableGrid::update(const UpdateData&) { } // last y col - for (unsigned int j = 0; j < nSegments.y; ++j) { + for (unsigned int j = 0; j < nSegments.y; j++) { const double y0 = -halfSize.y + j * step.y; const double y1 = y0 + step.y; bool shouldHighlight = false; if (_highlightRate.value().x != 0) { - int dist = abs(static_cast(nSegments.x) - static_cast(center.x)); - int rest = dist % _highlightRate.value().x; - shouldHighlight = abs(rest) == 0; + const int dist = std::abs( + static_cast(nSegments.x) - static_cast(center.x) + ); + const int rest = dist % _highlightRate.value().x; + shouldHighlight = std::abs(rest) == 0; } if (shouldHighlight) { _highlightArray.push_back({ halfSize.x, y0, 0.0 }); diff --git a/modules/base/rendering/grids/renderableradialgrid.cpp b/modules/base/rendering/grids/renderableradialgrid.cpp index 1d3b1f408e..1449533ff7 100644 --- a/modules/base/rendering/grids/renderableradialgrid.cpp +++ b/modules/base/rendering/grids/renderableradialgrid.cpp @@ -80,7 +80,7 @@ namespace { openspace::properties::Property::Visibility::User }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the grid" @@ -217,7 +217,7 @@ void RenderableRadialGrid::render(const RenderData& data, RendererTasks&) { glEnable(GL_LINE_SMOOTH); glDepthMask(false); - for (GeometryData& c : _circles) { + for (const GeometryData& c : _circles) { c.render(); } @@ -243,7 +243,7 @@ void RenderableRadialGrid::render(const RenderData& data, RendererTasks&) { ); if (orthoRight == glm::vec3(0.0)) { - glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) @@ -279,8 +279,8 @@ void RenderableRadialGrid::update(const UpdateData&) { std::vector vertices = rendering::helper::createRing(nSegments, radius); - _circles.push_back(GeometryData(GL_LINE_STRIP)); - _circles.back().varray = rendering::helper::convert(vertices); + _circles.emplace_back(GL_LINE_STRIP); + _circles.back().varray = rendering::helper::convert(std::move(vertices)); _circles.back().update(); }; @@ -289,7 +289,7 @@ void RenderableRadialGrid::update(const UpdateData&) { addRing(_circleSegments, innerRadius); } - for (int i = 0; i < nRadialSegments; ++i) { + for (int i = 0; i < nRadialSegments; i++) { const float ri = static_cast(i + 1) * deltaRadius + innerRadius; addRing(_circleSegments, ri); } @@ -308,7 +308,7 @@ void RenderableRadialGrid::update(const UpdateData&) { std::vector innerVertices = rendering::helper::createRing(nLines, innerRadius); - for (int i = 0; i < nLines; ++i) { + for (int i = 0; i < nLines; i++) { const rendering::helper::VertexXYZ vOut = rendering::helper::convertToXYZ(outerVertices[i]); @@ -339,7 +339,10 @@ RenderableRadialGrid::GeometryData::GeometryData(GLenum renderMode) } RenderableRadialGrid::GeometryData::GeometryData(GeometryData&& other) noexcept { - if (this == &other) return; + if (this == &other) { + return; + } + vao = other.vao; vbo = other.vbo; varray = std::move(other.varray); @@ -372,7 +375,7 @@ RenderableRadialGrid::GeometryData::~GeometryData() { vbo = 0; } -void RenderableRadialGrid::GeometryData::update() { +void RenderableRadialGrid::GeometryData::update() const { glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData( @@ -392,7 +395,7 @@ void RenderableRadialGrid::GeometryData::update() { ); } -void RenderableRadialGrid::GeometryData::render() { +void RenderableRadialGrid::GeometryData::render() const { glBindVertexArray(vao); glDrawArrays(mode, 0, static_cast(varray.size())); glBindVertexArray(0); diff --git a/modules/base/rendering/grids/renderableradialgrid.h b/modules/base/rendering/grids/renderableradialgrid.h index fbb0f9140f..0abc486631 100644 --- a/modules/base/rendering/grids/renderableradialgrid.h +++ b/modules/base/rendering/grids/renderableradialgrid.h @@ -66,8 +66,8 @@ protected: GeometryData& operator=(GeometryData&& other) noexcept; ~GeometryData(); - void update(); - void render(); + void update() const; + void render() const; std::vector varray; GLuint vao = 0; diff --git a/modules/base/rendering/grids/renderablesphericalgrid.cpp b/modules/base/rendering/grids/renderablesphericalgrid.cpp index 7d4d6b3d44..809bf737f9 100644 --- a/modules/base/rendering/grids/renderablesphericalgrid.cpp +++ b/modules/base/rendering/grids/renderablesphericalgrid.cpp @@ -61,7 +61,7 @@ namespace { openspace::properties::Property::Visibility::NoviceUser }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the grid" @@ -228,7 +228,7 @@ void RenderableSphericalGrid::render(const RenderData& data, RendererTasks&){ ); if (orthoRight == glm::vec3(0.0)) { - glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) @@ -242,87 +242,89 @@ void RenderableSphericalGrid::render(const RenderData& data, RendererTasks&){ } void RenderableSphericalGrid::update(const UpdateData&) { - if (_gridIsDirty) { - _isize = 6 * _segments * _segments; - _vsize = (_segments + 1) * (_segments + 1); - _varray.resize(_vsize); - Vertex v = { 0.f, 0.f, 0.f }; - std::fill(_varray.begin(), _varray.end(), v); - _iarray.resize(_isize); - std::fill(_iarray.begin(), _iarray.end(), 0); - - int nr = 0; - const float fsegments = static_cast(_segments); - - for (int nSegment = 0; nSegment <= _segments; ++nSegment) { - // define an extra vertex around the y-axis due to texture mapping - for (int j = 0; j <= _segments; j++) { - const float fi = static_cast(nSegment); - const float fj = static_cast(j); - - // inclination angle (north to south) - const float theta = fi * glm::pi() / fsegments * 2.f; // 0 -> PI - - // azimuth angle (east to west) - const float phi = fj * glm::pi() * 2.0f / fsegments; // 0 -> 2*PI - - const float x = sin(phi) * sin(theta); // - const float y = cos(theta); // up - const float z = cos(phi) * sin(theta); // - - glm::vec3 normal = glm::vec3(x, y, z); - if (!(x == 0.f && y == 0.f && z == 0.f)) { - normal = glm::normalize(normal); - } - - glm::vec4 tmp(x, y, z, 1.f); - glm::mat4 rot = glm::rotate( - glm::mat4(1.f), - glm::half_pi(), - glm::vec3(1.f, 0.f, 0.f) - ); - tmp = glm::vec4(glm::dmat4(rot) * glm::dvec4(tmp)); - - for (int i = 0; i < 3; i++) { - _varray[nr].location[i] = tmp[i]; - } - ++nr; - } - } - nr = 0; - // define indices for all triangles - for (int i = 1; i <= _segments; ++i) { - for (int j = 0; j < _segments; ++j) { - const int t = _segments + 1; - _iarray[nr] = t * (i - 1) + j + 0; ++nr; - _iarray[nr] = t * (i + 0) + j + 0; ++nr; - _iarray[nr] = t * (i + 0) + j + 1; ++nr; - _iarray[nr] = t * (i - 1) + j + 1; ++nr; - _iarray[nr] = t * (i - 1) + j + 0; ++nr; - } - } - - glBindVertexArray(_vaoID); - glBindBuffer(GL_ARRAY_BUFFER, _vBufferID); - glBufferData( - GL_ARRAY_BUFFER, - _vsize * sizeof(Vertex), - _varray.data(), - GL_STATIC_DRAW - ); - - glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); - glBufferData( - GL_ELEMENT_ARRAY_BUFFER, - _isize * sizeof(int), - _iarray.data(), - GL_STATIC_DRAW - ); - - _gridIsDirty = false; + if (!_gridIsDirty) { + return; } + + _isize = 6 * _segments * _segments; + _vsize = (_segments + 1) * (_segments + 1); + _varray.resize(_vsize); + constexpr Vertex v = { 0.f, 0.f, 0.f }; + std::fill(_varray.begin(), _varray.end(), v); + _iarray.resize(_isize); + std::fill(_iarray.begin(), _iarray.end(), 0); + + int nr = 0; + const float fsegments = static_cast(_segments); + + for (int nSegment = 0; nSegment <= _segments; ++nSegment) { + // define an extra vertex around the y-axis due to texture mapping + for (int j = 0; j <= _segments; j++) { + const float fi = static_cast(nSegment); + const float fj = static_cast(j); + + // inclination angle (north to south) + const float theta = fi * glm::pi() / fsegments * 2.f; // 0 -> PI + + // azimuth angle (east to west) + const float phi = fj * glm::pi() * 2.0f / fsegments; // 0 -> 2*PI + + const float x = std::sin(phi) * std::sin(theta); // + const float y = std::cos(theta); // up + const float z = std::cos(phi) * std::sin(theta); // + + glm::vec3 normal = glm::vec3(x, y, z); + if (x != 0.f || y != 0.f || z != 0.f) { + normal = glm::normalize(normal); + } + + glm::vec4 tmp(x, y, z, 1.f); + const glm::mat4 rot = glm::rotate( + glm::mat4(1.f), + glm::half_pi(), + glm::vec3(1.f, 0.f, 0.f) + ); + tmp = glm::vec4(glm::dmat4(rot) * glm::dvec4(tmp)); + + for (int i = 0; i < 3; i++) { + _varray[nr].location[i] = tmp[i]; + } + ++nr; + } + } + nr = 0; + // define indices for all triangles + for (int i = 1; i <= _segments; i++) { + for (int j = 0; j < _segments; j++) { + const int t = _segments + 1; + _iarray[nr] = t * (i - 1) + j + 0; ++nr; + _iarray[nr] = t * (i + 0) + j + 0; ++nr; + _iarray[nr] = t * (i + 0) + j + 1; ++nr; + _iarray[nr] = t * (i - 1) + j + 1; ++nr; + _iarray[nr] = t * (i - 1) + j + 0; ++nr; + } + } + + glBindVertexArray(_vaoID); + glBindBuffer(GL_ARRAY_BUFFER, _vBufferID); + glBufferData( + GL_ARRAY_BUFFER, + _vsize * sizeof(Vertex), + _varray.data(), + GL_STATIC_DRAW + ); + + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), nullptr); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); + glBufferData( + GL_ELEMENT_ARRAY_BUFFER, + _isize * sizeof(int), + _iarray.data(), + GL_STATIC_DRAW + ); + + _gridIsDirty = false; } } // namespace openspace diff --git a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp index 6b8b5daab9..138bc24391 100644 --- a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp +++ b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.cpp @@ -130,6 +130,10 @@ namespace { // the first set of positions for the objects, the next N rows to the second set of // positions, and so on. The number of objects in the dataset must be specified in the // asset. + // + // MultiTexture: + // Note that if using multiple textures for the points based on values in the dataset, + // the used texture will be decided based on the first N set of points. struct [[codegen::Dictionary(RenderableInterpolatedPoints)]] Parameters { // The number of objects to read from the dataset. Every N:th datapoint will // be interpreted as the same point, but at a different step in the interpolation @@ -177,7 +181,7 @@ RenderableInterpolatedPoints::Interpolation::Interpolation() addProperty(value); auto triggerInterpolation = [](std::string_view identifier, float v, float d) { - std::string script = fmt::format( + std::string script = std::format( "openspace.setPropertyValueSingle(\"{}\", {}, {})", identifier, v, d ); @@ -271,10 +275,10 @@ RenderableInterpolatedPoints::RenderableInterpolatedPoints( // corresponded to if (_nDataPoints % nObjects != 0) { - LERROR(fmt::format( + LERROR(std::format( "Mismatch between provided number of data entries and the specified number " - "of points. Expected the number of entries in the data file {} to be evenly " - "divisible by the number of points", _dataFile + "of points. Expected the number of entries in the data file '{}' to be " + "evenly divisible by the number of points", _dataFile )); } @@ -306,11 +310,12 @@ void RenderableInterpolatedPoints::initializeShadersAndGlExtras() { _program = BaseModule::ProgramObjectManager.request( "RenderablePointCloud_Interpolated", []() { + std::filesystem::path path = absPath("${MODULE_BASE}/shaders/pointcloud/"); return global::renderEngine->buildRenderProgram( "RenderablePointCloud_Interpolated", - absPath("${MODULE_BASE}/shaders/pointcloud/billboardpoint_interpolated_vs.glsl"), - absPath("${MODULE_BASE}/shaders/pointcloud/billboardpoint_fs.glsl"), - absPath("${MODULE_BASE}/shaders/pointcloud/billboardpoint_gs.glsl") + path / "billboardpoint_interpolated_vs.glsl", + path / "billboardpoint_fs.glsl", + path / "billboardpoint_gs.glsl" ); } ); @@ -328,13 +333,12 @@ void RenderableInterpolatedPoints::deinitializeShaders() { _program = nullptr; } -void RenderableInterpolatedPoints::bindDataForPointRendering() { - RenderablePointCloud::bindDataForPointRendering(); - +void RenderableInterpolatedPoints::setExtraUniforms() { float t0 = computeCurrentLowerValue(); float t = glm::clamp(_interpolation.value - t0, 0.f, 1.f); + _program->setUniform("interpolationValue", t); - _program->setUniform("useSpline", _interpolation.useSpline); + _program->setUniform("useSpline", useSplineInterpolation()); } void RenderableInterpolatedPoints::preUpdate() { @@ -346,113 +350,106 @@ void RenderableInterpolatedPoints::preUpdate() { int RenderableInterpolatedPoints::nAttributesPerPoint() const { int n = RenderablePointCloud::nAttributesPerPoint(); - // Need twice as much information as the regular points - n *= 2; - if (_interpolation.useSpline) { + + // Always at least three extra position values (xyz) + n += 3; + if (useSplineInterpolation()) { // Use two more positions (xyz) n += 2 * 3; } + // And potentially some more color and size data + n += _hasColorMapFile ? 1 : 0; + n += _hasDatavarSize ? 1 : 0; + return n; } -std::vector RenderableInterpolatedPoints::createDataSlice() { - ZoneScoped; +bool RenderableInterpolatedPoints::useSplineInterpolation() const { + return _interpolation.useSpline && _interpolation.nSteps > 1; +} - if (_dataset.entries.empty()) { - return std::vector(); +void RenderableInterpolatedPoints::addPositionDataForPoint(unsigned int index, + std::vector& result, + double& maxRadius) const +{ + using namespace dataloader; + auto [firstIndex, secondIndex] = interpolationIndices(index); + + const Dataset::Entry& e0 = _dataset.entries[firstIndex]; + const Dataset::Entry& e1 = _dataset.entries[secondIndex]; + + glm::dvec3 position0 = transformedPosition(e0); + glm::dvec3 position1 = transformedPosition(e1); + + const double r = glm::max(glm::length(position0), glm::length(position1)); + maxRadius = glm::max(maxRadius, r); + + for (int j = 0; j < 3; ++j) { + result.push_back(static_cast(position0[j])); } - std::vector result; - result.reserve(nAttributesPerPoint() * _nDataPoints); + for (int j = 0; j < 3; ++j) { + result.push_back(static_cast(position1[j])); + } - // Find the information we need for the interpolation and to identify the points, - // and make sure these result in valid indices in all cases - float t0 = computeCurrentLowerValue(); - float t1 = t0 + 1.f; - t1 = glm::clamp(t1, 0.f, _interpolation.value.maxValue()); - unsigned int t0Index = static_cast(t0); - unsigned int t1Index = static_cast(t1); + if (useSplineInterpolation()) { + // Compute the extra positions, before and after the other ones. But make sure + // we do not overflow the allowed bound for the current interpolation step + int beforeIndex = glm::max(static_cast(firstIndex - _nDataPoints), 0); + int maxT = static_cast(_interpolation.value.maxValue() - 1.f); + int maxAllowedindex = maxT * _nDataPoints + index; + int afterIndex = glm::min( + static_cast(secondIndex + _nDataPoints), + maxAllowedindex + ); + + const Dataset::Entry& e00 = _dataset.entries[beforeIndex]; + const Dataset::Entry& e11 = _dataset.entries[afterIndex]; + glm::dvec3 positionBefore = transformedPosition(e00); + glm::dvec3 positionAfter = transformedPosition(e11); + + for (int j = 0; j < 3; ++j) { + result.push_back(static_cast(positionBefore[j])); + } + + for (int j = 0; j < 3; ++j) { + result.push_back(static_cast(positionAfter[j])); + } + } +} + +void RenderableInterpolatedPoints::addColorAndSizeDataForPoint(unsigned int index, + std::vector& result) const +{ + using namespace dataloader; + auto [firstIndex, secondIndex] = interpolationIndices(index); + const Dataset::Entry& e0 = _dataset.entries[firstIndex]; + const Dataset::Entry& e1 = _dataset.entries[secondIndex]; - // What datavar is in use for the index color int colorParamIndex = currentColorParameterIndex(); - - // What datavar is in use for the size scaling (if present) - int sizeParamIndex = currentSizeParameterIndex(); - - double maxRadius = 0.0; - - for (unsigned int i = 0; i < _nDataPoints; i++) { - using namespace dataloader; - const Dataset::Entry& e0 = _dataset.entries[t0Index * _nDataPoints + i]; - const Dataset::Entry& e1 = _dataset.entries[t1Index * _nDataPoints + i]; - glm::dvec3 position0 = transformedPosition(e0); - glm::dvec3 position1 = transformedPosition(e1); - - const double r = glm::max(glm::length(position0), glm::length(position1)); - maxRadius = glm::max(maxRadius, r); - - // Positions - for (int j = 0; j < 3; ++j) { - result.push_back(static_cast(position0[j])); - } - - for (int j = 0; j < 3; ++j) { - result.push_back(static_cast(position1[j])); - } - - if (_interpolation.useSpline && _interpolation.nSteps > 1) { - // Compute the extra positions, before and after the other ones - unsigned int beforeIndex = static_cast( - glm::max(t0 - 1.f, 0.f) - ); - unsigned int afterIndex = static_cast( - glm::min(t1 + 1.f, _interpolation.value.maxValue() - 1.f) - ); - - const Dataset::Entry& e00 = _dataset.entries[beforeIndex * _nDataPoints + i]; - const Dataset::Entry& e11 = _dataset.entries[afterIndex * _nDataPoints + i]; - glm::dvec3 positionBefore = transformedPosition(e00); - glm::dvec3 positionAfter = transformedPosition(e11); - - for (int j = 0; j < 3; ++j) { - result.push_back(static_cast(positionBefore[j])); - } - - for (int j = 0; j < 3; ++j) { - result.push_back(static_cast(positionAfter[j])); - } - } - - // Colors - if (_hasColorMapFile) { - result.push_back(e0.data[colorParamIndex]); - result.push_back(e1.data[colorParamIndex]); - } - - // Size data - if (_hasDatavarSize) { - // @TODO: Consider more detailed control over the scaling. Currently the value - // is multiplied with the value as is. Should have similar mapping properties - // as the color mapping - result.push_back(e0.data[sizeParamIndex]); - result.push_back(e1.data[sizeParamIndex]); - } - - // @TODO: Also need to update label positions, if we have created labels from the dataset - // And make sure these are created from only the first set of points.. + if (_hasColorMapFile && colorParamIndex >= 0) { + result.push_back(e0.data[colorParamIndex]); + result.push_back(e1.data[colorParamIndex]); + } + + int sizeParamIndex = currentSizeParameterIndex(); + if (_hasDatavarSize && sizeParamIndex >= 0) { + // @TODO: Consider more detailed control over the scaling. Currently the value + // is multiplied with the value as is. Should have similar mapping properties + // as the color mapping + result.push_back(e0.data[sizeParamIndex]); + result.push_back(e1.data[sizeParamIndex]); } - setBoundingSphere(maxRadius); - return result; } void RenderableInterpolatedPoints::initializeBufferData() { if (_vao == 0) { glGenVertexArrays(1, &_vao); - LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); + LDEBUG(std::format("Generating Vertex Array id '{}'", _vao)); } if (_vbo == 0) { glGenBuffers(1, &_vbo); - LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); + LDEBUG(std::format("Generating Vertex Buffer Object id '{}'", _vbo)); } const int attibutesPerPoint = nAttributesPerPoint(); @@ -463,40 +460,28 @@ void RenderableInterpolatedPoints::initializeBufferData() { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, bufferSize, nullptr, GL_DYNAMIC_DRAW); - int attributeOffset = 0; + int offset = 0; - auto addFloatAttribute = [&](const std::string& name, GLint nValues) { - GLint attrib = _program->attributeLocation(name); - glEnableVertexAttribArray(attrib); - glVertexAttribPointer( - attrib, - nValues, - GL_FLOAT, - GL_FALSE, - attibutesPerPoint * sizeof(float), - (attributeOffset > 0) ? - reinterpret_cast(attributeOffset * sizeof(float)) : - nullptr - ); - attributeOffset += nValues; - }; + offset = bufferVertexAttribute("in_position0", 3, attibutesPerPoint, offset); + offset = bufferVertexAttribute("in_position1", 3, attibutesPerPoint, offset); - addFloatAttribute("in_position0", 3); - addFloatAttribute("in_position1", 3); - - if (_interpolation.useSpline) { - addFloatAttribute("in_position_before", 3); - addFloatAttribute("in_position_after", 3); + if (useSplineInterpolation()) { + offset = bufferVertexAttribute("in_position_before", 3, attibutesPerPoint, offset); + offset = bufferVertexAttribute("in_position_after", 3, attibutesPerPoint, offset); } if (_hasColorMapFile) { - addFloatAttribute("in_colorParameter0", 1); - addFloatAttribute("in_colorParameter1", 1); + offset = bufferVertexAttribute("in_colorParameter0", 1, attibutesPerPoint, offset); + offset = bufferVertexAttribute("in_colorParameter1", 1, attibutesPerPoint, offset); } if (_hasDatavarSize) { - addFloatAttribute("in_scalingParameter0", 1); - addFloatAttribute("in_scalingParameter1", 1); + offset = bufferVertexAttribute("in_scalingParameter0", 1, attibutesPerPoint, offset); + offset = bufferVertexAttribute("in_scalingParameter1", 1, attibutesPerPoint, offset); + } + + if (_hasSpriteTexture) { + offset = bufferVertexAttribute("in_textureLayer", 1, attibutesPerPoint, offset); } glBindVertexArray(0); @@ -541,4 +526,25 @@ float RenderableInterpolatedPoints::computeCurrentLowerValue() const { return t0; } +float RenderableInterpolatedPoints::computeCurrentUpperValue() const { + float t0 = computeCurrentLowerValue(); + float t1 = t0 + 1.f; + t1 = glm::clamp(t1, 0.f, _interpolation.value.maxValue()); + return t1; +} + +std::pair +RenderableInterpolatedPoints::interpolationIndices(unsigned int index) const +{ + float t0 = computeCurrentLowerValue(); + float t1 = computeCurrentUpperValue(); + unsigned int t0Index = static_cast(t0); + unsigned int t1Index = static_cast(t1); + + size_t lower = size_t(t0Index * _nDataPoints + index); + size_t upper = size_t(t1Index * _nDataPoints + index); + + return { lower, upper }; +} + } // namespace openspace diff --git a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.h b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.h index 27b238fa74..8ead53ad92 100644 --- a/modules/base/rendering/pointcloud/renderableinterpolatedpoints.h +++ b/modules/base/rendering/pointcloud/renderableinterpolatedpoints.h @@ -52,20 +52,34 @@ public: protected: void initializeShadersAndGlExtras() override; void deinitializeShaders() override; - void bindDataForPointRendering() override; + void setExtraUniforms() override; void preUpdate() override; int nAttributesPerPoint() const override; + bool useSplineInterpolation() const; + /** - * Create the data slice to use for rendering the points. Compared to the regular - * point cloud, the data slice for an interpolated set of points will have to be - * recreated when the interpolation value changes, and will only include a subset of - * the points in the entire dataset + * Create the rendering data for the positions for the point with the given index + * and append that to the result. Compared to the base class, this class may require + * 2-4 positions, depending on if * spline interpolation is used or not. * - * \return The dataslice to use for rendering the points + * The values are computed based on the current interpolation value. + * + * Also, compute the maxRadius to use for setting the bounding sphere. */ - std::vector createDataSlice() override; + void addPositionDataForPoint(unsigned int index, std::vector& result, + double& maxRadius) const override; + + /** + * Create the rendering data for the color and size data for the point with the given + * index and append that to the result. Compared to the base class, this class require + * 2 values per data value, to use for interpolation. + * + * The values are computed based on the current interpolation value. + */ + void addColorAndSizeDataForPoint(unsigned int index, + std::vector& result) const override; void initializeBufferData(); void updateBufferData() override; @@ -73,6 +87,8 @@ protected: private: bool isAtKnot() const; float computeCurrentLowerValue() const; + float computeCurrentUpperValue() const; + std::pair interpolationIndices(unsigned int index) const; struct Interpolation : public properties::PropertyOwner { Interpolation(); diff --git a/modules/base/rendering/pointcloud/renderablepointcloud.cpp b/modules/base/rendering/pointcloud/renderablepointcloud.cpp index 03376aaf8e..f2ab0ff57c 100644 --- a/modules/base/rendering/pointcloud/renderablepointcloud.cpp +++ b/modules/base/rendering/pointcloud/renderablepointcloud.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -55,14 +56,15 @@ namespace { constexpr std::string_view _loggerCat = "RenderablePointCloud"; - constexpr std::array UniformNames = { + constexpr std::array UniformNames = { "cameraViewMatrix", "projectionMatrix", "modelMatrix", "cameraPosition", "cameraLookUp", "renderOption", "maxAngularSize", "color", "opacity", "scaleExponent", "scaleFactor", "up", "right", "fadeInValue", "hasSpriteTexture", "spriteTexture", "useColorMap", "colorMapTexture", "cmapRangeMin", "cmapRangeMax", "nanColor", "useNanColor", "hideOutsideRange", "enableMaxSizeControl", "aboveRangeColor", "useAboveRangeColor", "belowRangeColor", "useBelowRangeColor", - "hasDvarScaling", "enableOutline", "outlineColor", "outlineWeight" + "hasDvarScaling", "dvarScaleFactor", "enableOutline", "outlineColor", + "outlineWeight", "aspectRatioScale" }; enum RenderOption { @@ -70,18 +72,55 @@ namespace { PositionNormal }; - constexpr openspace::properties::Property::PropertyInfo SpriteTextureInfo = { - "Texture", - "Point Sprite Texture", - "The path to the texture that should be used as the point sprite", + constexpr openspace::properties::Property::PropertyInfo TextureEnabledInfo = { + "Enabled", + "Enabled", + "If true, use a provided sprite texture to render the point. If false, draw " + "the points using the default point shape.", openspace::properties::Property::Visibility::AdvancedUser }; - constexpr openspace::properties::Property::PropertyInfo UseSpriteTextureInfo = { - "UseTexture", - "Use Texture", - "If true, use the provided sprite texture to render the point. If false, draw " - "the points using the default point shape.", + constexpr openspace::properties::Property::PropertyInfo AllowTextureCompressionInfo = + { + "AllowCompression", + "Allow Compression", + "If true, the textures will be compressed to preserve graphics card memory. This " + "is enabled per default, but may lead to visible artefacts for certain images, " + "especially up close. Set this to false to disable any hardware compression of " + "the textures, and represent each color channel with 8 bits.", + openspace::properties::Property::Visibility::AdvancedUser + }; + + constexpr openspace::properties::Property::PropertyInfo UseAlphaInfo = { + "UseAlphaChannel", + "Use Alpha Channel", + "If true, include transparency information in the loaded textures, if there " + "is any. If false, all loaded textures will be converted to RGB format. \n" + "This setting can be used if you have textures with transparency, but do not " + "need the transparency information. This may be the case when using additive " + "blending, for example. Converting the files to RGB on load may then reduce the " + "memory footprint and/or lead to some optimization in terms of rendering speed.", + openspace::properties::Property::Visibility::AdvancedUser + }; + + constexpr openspace::properties::Property::PropertyInfo SpriteTextureInfo = { + "File", + "Point Sprite Texture File", + "The path to the texture that should be used as the point sprite. Note that if " + "multiple textures option is set in the asset, by providing a texture folder, " + "this value will be ignored.", + openspace::properties::Property::Visibility::AdvancedUser + }; + + constexpr openspace::properties::Property::PropertyInfo TextureModeInfo = { + "TextureMode", + "Texture Mode", + "This tells which texture mode is being used for this renderable. There are " + "three different texture modes: 1) One single sprite texture used for all " + "points, 2) Multiple textures, that are mapped to the points based on a column " + "in the dataset, and 3) Other, which is used for specific subtypes where the " + "texture is internally controlled by the renderable and can't be set from a " + "file (such as the RenderablePolygonCloud).", openspace::properties::Property::Visibility::AdvancedUser }; @@ -101,7 +140,7 @@ namespace { openspace::properties::Property::Visibility::NoviceUser }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the points. If no label file is provided, the labels will be " @@ -282,7 +321,7 @@ namespace { struct [[codegen::Dictionary(RenderablePointCloud)]] Parameters { // The path to the data file that contains information about the point to be // rendered. Can be either a CSV or SPECK file - std::optional file; + std::optional file; // If true (default), the loaded dataset will be cached so that it can be loaded // faster at a later time. This does however mean that any updates to the values @@ -296,11 +335,29 @@ namespace { std::optional dataMapping [[codegen::reference("dataloader_datamapping")]]; - // [[codegen::verbatim(SpriteTextureInfo.description)]] - std::optional texture; + struct Texture { + // [[codegen::verbatim(TextureEnabledInfo.description)]] + std::optional enabled; - // [[codegen::verbatim(UseSpriteTextureInfo.description)]] - std::optional useTexture; + // [[codegen::verbatim(SpriteTextureInfo.description)]] + std::optional file; + + // The folder where the textures are located when using multiple different + // textures to render the points. Setting this value means that multiple + // textures shall be used and any single sprite texture file is ignored. + // + // Note that the textures can be any format, but rendering efficiency will + // be best if using textures with the exact same resolution. + std::optional folder [[codegen::directory()]]; + + // [[codegen::verbatim(AllowTextureCompressionInfo.description)]] + std::optional allowCompression; + + // [[codegen::verbatim(UseAlphaInfo.description)]] + std::optional useAlphaChannel; + }; + // Settings related to the texturing of the points + std::optional texture; // [[codegen::verbatim(DrawElementsInfo.description)]] std::optional drawElements; @@ -333,9 +390,9 @@ namespace { [[codegen::reference("labelscomponent")]]; struct SizeSettings { - // A list specifying all parameters that may be used for size mapping, i.e. - // scaling the points based on the provided data columns - std::optional> sizeMapping; + // Settings related to scaling the points based on data + std::optional sizeMapping + [[codegen::reference("base_sizemappingcomponent")]]; // [[codegen::verbatim(ScaleExponentInfo.description)]] std::optional scaleExponent; @@ -420,14 +477,10 @@ RenderablePointCloud::SizeSettings::SizeSettings(const ghoul::Dictionary& dictio maxAngularSize = settings.maxSize.value_or(maxAngularSize); if (settings.sizeMapping.has_value()) { - std::vector opts = *settings.sizeMapping; - for (size_t i = 0; i < opts.size(); ++i) { - // Note that options are added in order - sizeMapping.parameterOption.addOption(static_cast(i), opts[i]); - } - sizeMapping.enabled = true; - - addPropertySubOwner(sizeMapping); + sizeMapping = std::make_unique( + *settings.sizeMapping + ); + addPropertySubOwner(sizeMapping.get()); } } @@ -437,18 +490,6 @@ RenderablePointCloud::SizeSettings::SizeSettings(const ghoul::Dictionary& dictio addProperty(maxAngularSize); } -RenderablePointCloud::SizeSettings::SizeMapping::SizeMapping() - : properties::PropertyOwner({ "SizeMapping", "Size Mapping", "" }) - , enabled(SizeMappingEnabledInfo, false) - , parameterOption( - SizeMappingOptionInfo, - properties::OptionProperty::DisplayType::Dropdown - ) -{ - addProperty(enabled); - addProperty(parameterOption); -} - RenderablePointCloud::ColorSettings::ColorSettings(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "Coloring", "Coloring", "" }) , pointColor(PointColorInfo, glm::vec3(1.f), glm::vec3(0.f), glm::vec3(1.f)) @@ -485,6 +526,23 @@ RenderablePointCloud::ColorSettings::ColorSettings(const ghoul::Dictionary& dict addProperty(outlineWeight); } +RenderablePointCloud::Texture::Texture() + : properties::PropertyOwner({ "Texture", "Texture", "" }) + , enabled(TextureEnabledInfo, true) + , allowCompression(AllowTextureCompressionInfo, true) + , useAlphaChannel(UseAlphaInfo, true) + , spriteTexturePath(SpriteTextureInfo) + , inputMode(TextureModeInfo) +{ + addProperty(enabled); + addProperty(allowCompression); + addProperty(useAlphaChannel); + addProperty(spriteTexturePath); + + inputMode.setReadOnly(true); + addProperty(inputMode); +} + RenderablePointCloud::Fading::Fading(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "Fading", "Fading", "" }) , enabled(EnableDistanceFadeInfo, false) @@ -520,8 +578,6 @@ RenderablePointCloud::Fading::Fading(const ghoul::Dictionary& dictionary) RenderablePointCloud::RenderablePointCloud(const ghoul::Dictionary& dictionary) : Renderable(dictionary) - , _spriteTexturePath(SpriteTextureInfo) - , _useSpriteTexture(UseSpriteTextureInfo, true) , _drawElements(DrawElementsInfo, true) , _useAdditiveBlending(UseAdditiveBlendingInfo, true) , _renderOption(RenderOptionInfo, properties::OptionProperty::DisplayType::Dropdown) @@ -567,22 +623,46 @@ RenderablePointCloud::RenderablePointCloud(const ghoul::Dictionary& dictionary) _unit = DistanceUnit::Meter; } - _spriteTexturePath.onChange([this]() { _spriteTextureIsDirty = true; }); - addProperty(_spriteTexturePath); - - _useSpriteTexture = p.useTexture.value_or(_useSpriteTexture); - addProperty(_useSpriteTexture); + addPropertySubOwner(_texture); if (p.texture.has_value()) { - _spriteTexturePath = absPath(*p.texture).string(); + const Parameters::Texture t = *p.texture; + + // Read texture information. Multi-texture is prioritized over single-texture + if (t.folder.has_value()) { + _textureMode = TextureInputMode::Multi; + _hasSpriteTexture = true; + _texturesDirectory = absPath(*t.folder).string(); + + if (t.file.has_value()) { + LWARNING(std::format( + "Both a single texture File and multi-texture Folder was provided. " + "The folder '{}' has priority and the single texture with the " + "following path will be ignored: '{}'", *t.folder, *t.file + )); + } + + _texture.removeProperty(_texture.spriteTexturePath); + } + else if (t.file.has_value()) { + _textureMode = TextureInputMode::Single; + _hasSpriteTexture = true; + _texture.spriteTexturePath = absPath(*t.file).string(); + _texture.spriteTexturePath.onChange([this]() { _spriteTextureIsDirty = true; }); + } + + _texture.enabled = t.enabled.value_or(_texture.enabled); + _texture.allowCompression = t.allowCompression.value_or(_texture.allowCompression); + _texture.useAlphaChannel = t.useAlphaChannel.value_or(_texture.useAlphaChannel); } - _hasSpriteTexture = p.texture.has_value(); + _texture.allowCompression.onChange([this]() { _spriteTextureIsDirty = true; }); + _texture.useAlphaChannel.onChange([this]() { _spriteTextureIsDirty = true; }); _transformationMatrix = p.transformationMatrix.value_or(_transformationMatrix); if (p.sizeSettings.has_value() && p.sizeSettings->sizeMapping.has_value()) { - _sizeSettings.sizeMapping.parameterOption.onChange( + _sizeSettings.sizeMapping->parameterOption.onChange( [this]() { _dataIsDirty = true; } ); _hasDatavarSize = true; @@ -642,7 +722,7 @@ RenderablePointCloud::RenderablePointCloud(const ghoul::Dictionary& dictionary) if (p.labels.has_value()) { if (!p.labels->hasKey("File") && _hasDataFile) { - // Load the labelset from the dataset if no file was included + // Load the labelset from the dataset if no label file was included _labels = std::make_unique(*p.labels, _dataset, _unit); } else { @@ -651,7 +731,7 @@ RenderablePointCloud::RenderablePointCloud(const ghoul::Dictionary& dictionary) _hasLabels = true; addPropertySubOwner(_labels.get()); - // Fading of the labels should also depend on the fading of the renderable + // Fading of the labels should depend on the fading of the renderable _labels->setParentFadeable(this); } @@ -661,8 +741,6 @@ RenderablePointCloud::RenderablePointCloud(const ghoul::Dictionary& dictionary) bool RenderablePointCloud::isReady() const { bool isReady = _program; - - // If we have labels, they also need to be loaded if (_hasLabels) { isReady = isReady && _labels->isReady(); } @@ -672,6 +750,20 @@ bool RenderablePointCloud::isReady() const { void RenderablePointCloud::initialize() { ZoneScoped; + switch (_textureMode) { + case TextureInputMode::Single: + _texture.inputMode = "Single Sprite Texture"; + break; + case TextureInputMode::Multi: + _texture.inputMode = "Multipe Textures / Data-based"; + break; + case TextureInputMode::Other: + _texture.inputMode = "Other"; + break; + default: + break; + } + if (_hasDataFile && _hasColorMapFile) { _colorSettings.colorMapping->initialize(_dataset); } @@ -687,6 +779,22 @@ void RenderablePointCloud::initializeGL() { initializeShadersAndGlExtras(); ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); + + if (_hasSpriteTexture) { + switch (_textureMode) { + case TextureInputMode::Single: + initializeSingleTexture(); + break; + case TextureInputMode::Multi: + initializeMultiTextures(); + break; + case TextureInputMode::Other: + initializeCustomTexture(); + break; + default: + break; + } + } } void RenderablePointCloud::deinitializeGL() { @@ -697,8 +805,7 @@ void RenderablePointCloud::deinitializeGL() { deinitializeShaders(); - BaseModule::TextureManager.release(_spriteTexture); - _spriteTexture = nullptr; + clearTextureDataStructures(); } void RenderablePointCloud::initializeShadersAndGlExtras() { @@ -725,9 +832,210 @@ void RenderablePointCloud::deinitializeShaders() { _program = nullptr; } -void RenderablePointCloud::bindTextureForRendering() const { - if (_spriteTexture) { - _spriteTexture->bind(); +void RenderablePointCloud::initializeCustomTexture() {} + +void RenderablePointCloud::initializeSingleTexture() { + if (_texture.spriteTexturePath.value().empty()) { + return; + } + + std::filesystem::path p = absPath(_texture.spriteTexturePath); + + if (!std::filesystem::is_regular_file(p)) { + throw ghoul::RuntimeError(std::format( + "Could not find image file '{}'", p + )); + } + + loadTexture(p, 0); + generateArrayTextures(); +} + +void RenderablePointCloud::initializeMultiTextures() { + for (const dataloader::Dataset::Texture& tex : _dataset.textures) { + std::filesystem::path path = _texturesDirectory / tex.file; + + if (!std::filesystem::is_regular_file(path)) { + throw ghoul::RuntimeError(std::format( + "Could not find image file '{}'", path + )); + } + loadTexture(path, tex.index); + } + + generateArrayTextures(); +} + +void RenderablePointCloud::clearTextureDataStructures() { + _textures.clear(); + _textureNameToIndex.clear(); + _indexInDataToTextureIndex.clear(); + _textureMapByFormat.clear(); + // Unload texture arrays from GPU memory + for (const TextureArrayInfo& arrayInfo : _textureArrays) { + glDeleteTextures(1, &arrayInfo.renderId); + } + _textureArrays.clear(); + _textureIndexToArrayMap.clear(); +} + +void RenderablePointCloud::loadTexture(const std::filesystem::path& path, int index) { + if (path.empty()) { + return; + } + + std::string filename = path.filename().string(); + auto search = _textureNameToIndex.find(filename); + if (search != _textureNameToIndex.end()) { + // The texture has already been loaded. Find the index + size_t indexInTextureArray = _textureNameToIndex[filename]; + _indexInDataToTextureIndex[index] = indexInTextureArray; + return; + } + + std::unique_ptr t = + ghoul::io::TextureReader::ref().loadTexture(path.string(), 2); + + bool useAlpha = (t->numberOfChannels() > 3) && _texture.useAlphaChannel; + + if (t) { + LINFOC("RenderablePlanesCloud", std::format("Loaded texture {}", path)); + // Do not upload the loaded texture to the GPU, we just want it to hold the data. + // However, convert textures make sure they all use the same format + ghoul::opengl::Texture::Format targetFormat = glFormat(useAlpha); + convertTextureFormat(*t, targetFormat); + } + else { + throw ghoul::RuntimeError(std::format( + "Could not find image file {}", path + )); + } + + TextureFormat format = { + .resolution = glm::uvec2(t->width(), t->height()), + .useAlpha = useAlpha + }; + + size_t indexInTextureArray = _textures.size(); + _textures.push_back(std::move(t)); + _textureNameToIndex[filename] = indexInTextureArray; + _textureMapByFormat[format].push_back(indexInTextureArray); + _indexInDataToTextureIndex[index] = indexInTextureArray; +} + +void RenderablePointCloud::initAndAllocateTextureArray(unsigned int textureId, + glm::uvec2 resolution, + size_t nLayers, + bool useAlpha) +{ + float w = static_cast(resolution.x); + float h = static_cast(resolution.y); + glm::vec2 aspectScale = w > h ? glm::vec2(1.f, h / w) : glm::vec2(w / h, 1.f); + + _textureArrays.push_back({ + .renderId = textureId, + .aspectRatioScale = aspectScale + }); + + gl::GLenum internalFormat = internalGlFormat(useAlpha); + gl::GLenum format = gl::GLenum(glFormat(useAlpha)); + + // Create storage for the texture + // The nicer way would be to use glTexStorage3D, but that is only available in OpenGl + // 4.2 and above + glTexImage3D( + GL_TEXTURE_2D_ARRAY, + 0, + internalFormat, + resolution.x, + resolution.y, + static_cast(nLayers), + 0, + format, + GL_UNSIGNED_BYTE, + nullptr + ); + + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +} + +void RenderablePointCloud::fillAndUploadTextureLayer(unsigned int arrayIndex, + unsigned int layer, + size_t textureIndex, + glm::uvec2 resolution, + bool useAlpha, + const void* pixelData) +{ + gl::GLenum format = gl::GLenum(glFormat(useAlpha)); + + glTexSubImage3D( + GL_TEXTURE_2D_ARRAY, + 0, // Mipmap number + 0, // xoffset + 0, // yoffset + gl::GLint(layer), // zoffset + gl::GLsizei(resolution.x), // width + gl::GLsizei(resolution.y), // height + 1, // depth + format, + GL_UNSIGNED_BYTE, // type + pixelData + ); + + // Keep track of which layer in which texture array corresponds to the texture with + // this index, so we can use it when generating vertex data + _textureIndexToArrayMap[textureIndex] = { + .arrayId = arrayIndex, + .layer = layer + }; +} + +void RenderablePointCloud::generateArrayTextures() { + using Entry = std::pair>; + unsigned int arrayIndex = 0; + for (const Entry& e : _textureMapByFormat) { + glm::uvec2 res = e.first.resolution; + bool useAlpha = e.first.useAlpha; + std::vector textureListIndices = e.second; + size_t nLayers = textureListIndices.size(); + + // Generate an array texture storage + unsigned int id = 0; + glGenTextures(1, &id); + glBindTexture(GL_TEXTURE_2D_ARRAY, id); + + initAndAllocateTextureArray(id, res, nLayers, useAlpha); + + // Fill that storage with the data from the individual textures + unsigned int layer = 0; + for (const size_t& i : textureListIndices) { + ghoul::opengl::Texture* texture = _textures[i].get(); + fillAndUploadTextureLayer(arrayIndex, layer, i, res, useAlpha, texture->pixelData()); + layer++; + + // At this point we don't need the keep the texture data around anymore. If + // the textures need updating, we will reload them from file + texture->purgeFromRAM(); + } + + int nMaxTextureLayers = 0; + glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &nMaxTextureLayers); + if (static_cast(layer) > nMaxTextureLayers) { + LERROR(std::format( + "Too many layers bound in the same texture array. Found {} textures with " + "resolution {}x{} pixels. Max supported is {}.", + layer, res.x, res.y, nMaxTextureLayers + )); + // @TODO: Should we split the array up? Do we think this will ever become + // a problem? + } + + glBindTexture(GL_TEXTURE_2D_ARRAY, 0); + + arrayIndex++; } } @@ -759,7 +1067,54 @@ float RenderablePointCloud::computeDistanceFadeValue(const RenderData& data) con return fadeValue * funcValue; } -void RenderablePointCloud::bindDataForPointRendering() { +void RenderablePointCloud::setExtraUniforms() {} + +void RenderablePointCloud::renderBillboards(const RenderData& data, + const glm::dmat4& modelMatrix, + const glm::dvec3& orthoRight, + const glm::dvec3& orthoUp, + float fadeInVariable) +{ + if (!_hasDataFile || _dataset.entries.empty()) { + return; + } + + glEnablei(GL_BLEND, 0); + + if (_useAdditiveBlending) { + glDepthMask(false); + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + } + else { + // Normal blending, with transparency + glDepthMask(true); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + + _program->activate(); + + _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); + _program->setUniform( + _uniformCache.cameraLookup, + glm::vec3(data.camera.lookUpVectorWorldSpace()) + ); + _program->setUniform(_uniformCache.renderOption, _renderOption.value()); + _program->setUniform(_uniformCache.modelMatrix, modelMatrix); + + _program->setUniform( + _uniformCache.cameraViewMatrix, + data.camera.combinedViewMatrix() + ); + + _program->setUniform( + _uniformCache.projectionMatrix, + glm::dmat4(data.camera.projectionMatrix()) + ); + + _program->setUniform(_uniformCache.up, glm::vec3(orthoUp)); + _program->setUniform(_uniformCache.right, glm::vec3(orthoRight)); + _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); + _program->setUniform(_uniformCache.renderOption, _renderOption.value()); _program->setUniform(_uniformCache.opacity, opacity()); @@ -770,16 +1125,17 @@ void RenderablePointCloud::bindDataForPointRendering() { _sizeSettings.useMaxSizeControl ); _program->setUniform(_uniformCache.maxAngularSize, _sizeSettings.maxAngularSize); - _program->setUniform(_uniformCache.hasDvarScaling, _sizeSettings.sizeMapping.enabled); - bool useTexture = _hasSpriteTexture && _useSpriteTexture; - _program->setUniform(_uniformCache.hasSpriteTexture, useTexture); + bool useSizeMapping = _hasDatavarSize && _sizeSettings.sizeMapping && + _sizeSettings.sizeMapping->enabled; - ghoul::opengl::TextureUnit spriteTextureUnit; - _program->setUniform(_uniformCache.spriteTexture, spriteTextureUnit); - if (useTexture) { - spriteTextureUnit.activate(); - bindTextureForRendering(); + _program->setUniform(_uniformCache.hasDvarScaling, useSizeMapping); + + if (useSizeMapping) { + _program->setUniform( + _uniformCache.dvarScaleFactor, + _sizeSettings.sizeMapping->scaleFactor + ); } _program->setUniform(_uniformCache.color, _colorSettings.pointColor); @@ -834,58 +1190,38 @@ void RenderablePointCloud::bindDataForPointRendering() { _colorSettings.colorMapping->useBelowRangeColor ); } -} -void RenderablePointCloud::renderBillboards(const RenderData& data, - const glm::dmat4& modelMatrix, - const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, - float fadeInVariable) -{ - if (!_hasDataFile || _dataset.entries.empty()) { - return; - } + bool useTexture = _hasSpriteTexture && _texture.enabled; + _program->setUniform(_uniformCache.hasSpriteTexture, useTexture); - glEnablei(GL_BLEND, 0); + ghoul::opengl::TextureUnit spriteTextureUnit; + _program->setUniform(_uniformCache.spriteTexture, spriteTextureUnit); - if (_useAdditiveBlending) { - glDepthMask(false); - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - } - else { - // Normal blending, with transparency - glDepthMask(true); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - - _program->activate(); - - _program->setUniform(_uniformCache.cameraPos, data.camera.positionVec3()); - _program->setUniform( - _uniformCache.cameraLookup, - glm::vec3(data.camera.lookUpVectorWorldSpace()) - ); - _program->setUniform(_uniformCache.renderOption, _renderOption.value()); - _program->setUniform(_uniformCache.modelMatrix, modelMatrix); - - _program->setUniform( - _uniformCache.cameraViewMatrix, - data.camera.combinedViewMatrix() - ); - - _program->setUniform( - _uniformCache.projectionMatrix, - glm::dmat4(data.camera.projectionMatrix()) - ); - - _program->setUniform(_uniformCache.up, glm::vec3(orthoUp)); - _program->setUniform(_uniformCache.right, glm::vec3(orthoRight)); - _program->setUniform(_uniformCache.fadeInValue, fadeInVariable); - - bindDataForPointRendering(); + setExtraUniforms(); glBindVertexArray(_vao); - glDrawArrays(GL_POINTS, 0, static_cast(_nDataPoints)); + + if (useTexture && !_textureArrays.empty()) { + spriteTextureUnit.activate(); + for (const TextureArrayInfo& arrayInfo : _textureArrays) { + _program->setUniform( + _uniformCache.aspectRatioScale, + arrayInfo.aspectRatioScale + ); + glBindTexture(GL_TEXTURE_2D_ARRAY, arrayInfo.renderId); + glDrawArrays( + GL_POINTS, + arrayInfo.startOffset, + static_cast(arrayInfo.nPoints) + ); + } + glBindTexture(GL_TEXTURE_2D_ARRAY, 0); + } + else { + _program->setUniform(_uniformCache.aspectRatioScale, glm::vec2(1.f)); + glDrawArrays(GL_POINTS, 0, static_cast(_nDataPoints)); + } + glBindVertexArray(0); _program->deactivate(); @@ -940,13 +1276,13 @@ void RenderablePointCloud::update(const UpdateData&) { _colorSettings.colorMapping->update(_dataset); } - if (_dataIsDirty) { - updateBufferData(); - } - if (_spriteTextureIsDirty) { updateSpriteTexture(); } + + if (_dataIsDirty) { + updateBufferData(); + } } glm::dvec3 RenderablePointCloud::transformedPosition( @@ -961,9 +1297,27 @@ int RenderablePointCloud::nAttributesPerPoint() const { int n = 3; // position n += _hasColorMapFile ? 1 : 0; n += _hasDatavarSize ? 1 : 0; + n += _hasSpriteTexture ? 1 : 0; // texture id return n; } +int RenderablePointCloud::bufferVertexAttribute(const std::string& name, GLint nValues, + int nAttributesPerPoint, int offset) const +{ + GLint attrib = _program->attributeLocation(name); + glEnableVertexAttribArray(attrib); + glVertexAttribPointer( + attrib, + nValues, + GL_FLOAT, + GL_FALSE, + nAttributesPerPoint * sizeof(float), + reinterpret_cast(offset * sizeof(float)) + ); + + return offset + nValues; +} + void RenderablePointCloud::updateBufferData() { if (!_hasDataFile || _dataset.entries.empty()) { return; @@ -979,11 +1333,11 @@ void RenderablePointCloud::updateBufferData() { if (_vao == 0) { glGenVertexArrays(1, &_vao); - LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); + LDEBUG(std::format("Generating Vertex Array id '{}'", _vao)); } if (_vbo == 0) { glGenBuffers(1, &_vbo); - LDEBUG(fmt::format("Generating Vertex Buffer Object id '{}'", _vbo)); + LDEBUG(std::format("Generating Vertex Buffer Object id '{}'", _vbo)); } glBindVertexArray(_vao); @@ -991,46 +1345,20 @@ void RenderablePointCloud::updateBufferData() { glBufferData(GL_ARRAY_BUFFER, size * sizeof(float), slice.data(), GL_STATIC_DRAW); const int attibutesPerPoint = nAttributesPerPoint(); - int attributeOffset = 0; + int offset = 0; - GLint positionAttrib = _program->attributeLocation("in_position"); - glEnableVertexAttribArray(positionAttrib); - glVertexAttribPointer( - positionAttrib, - 3, - GL_FLOAT, - GL_FALSE, - attibutesPerPoint * sizeof(float), - nullptr - ); - attributeOffset += 3; + offset = bufferVertexAttribute("in_position", 3, attibutesPerPoint, offset); if (_hasColorMapFile) { - GLint colorParamAttrib = _program->attributeLocation("in_colorParameter"); - glEnableVertexAttribArray(colorParamAttrib); - glVertexAttribPointer( - colorParamAttrib, - 1, - GL_FLOAT, - GL_FALSE, - attibutesPerPoint * sizeof(float), - reinterpret_cast(attributeOffset * sizeof(float)) - ); - attributeOffset += 1; + offset = bufferVertexAttribute("in_colorParameter", 1, attibutesPerPoint, offset); } if (_hasDatavarSize) { - GLint scalingAttrib = _program->attributeLocation("in_scalingParameter"); - glEnableVertexAttribArray(scalingAttrib); - glVertexAttribPointer( - scalingAttrib, - 1, - GL_FLOAT, - GL_FALSE, - attibutesPerPoint * sizeof(float), - reinterpret_cast(attributeOffset * sizeof(float)) - ); - attributeOffset += 1; + offset = bufferVertexAttribute("in_scalingParameter", 1, attibutesPerPoint, offset); + } + + if (_hasSpriteTexture) { + offset = bufferVertexAttribute("in_textureLayer", 1, attibutesPerPoint, offset); } glBindVertexArray(0); @@ -1039,8 +1367,7 @@ void RenderablePointCloud::updateBufferData() { } void RenderablePointCloud::updateSpriteTexture() { - bool shouldUpdate = _hasSpriteTexture && _spriteTextureIsDirty && - !_spriteTexturePath.value().empty(); + bool shouldUpdate = _hasSpriteTexture && _spriteTextureIsDirty; if (!shouldUpdate) { return; @@ -1049,26 +1376,34 @@ void RenderablePointCloud::updateSpriteTexture() { ZoneScopedN("Sprite texture"); TracyGpuZone("Sprite texture"); - ghoul::opengl::Texture* texture = _spriteTexture; + clearTextureDataStructures(); - unsigned int hash = ghoul::hashCRC32File(_spriteTexturePath); + // We also have to update the dataset, to update the texture array offsets + _dataIsDirty = true; - _spriteTexture = BaseModule::TextureManager.request( - std::to_string(hash), - [path = _spriteTexturePath]() -> std::unique_ptr { - std::filesystem::path p = absPath(path); - LINFO(fmt::format("Loaded texture from {}", p)); - std::unique_ptr t = - ghoul::io::TextureReader::ref().loadTexture(p.string(), 2); - t->uploadTexture(); - t->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap); - t->purgeFromRAM(); - return t; - } - ); - - BaseModule::TextureManager.release(texture); + // Always set the is-dirty flag, even if the loading fails, as to not try to reload + // the texture without the input file being changed _spriteTextureIsDirty = false; + + switch (_textureMode) { + case TextureInputMode::Single: + initializeSingleTexture(); + // Note that these are usually set when the data slice initialized. However, + // we want to avoid reinitializing the data, and here we know that all points + // will be rendered using the same texture array and hence the data can stay fixed + _textureArrays.front().nPoints = _nDataPoints; + _textureArrays.front().startOffset = 0; + _dataIsDirty = false; + break; + case TextureInputMode::Multi: + initializeMultiTextures(); + break; + case TextureInputMode::Other: + initializeCustomTexture(); + break; + default: + break; + } } int RenderablePointCloud::currentColorParameterIndex() const { @@ -1084,7 +1419,7 @@ int RenderablePointCloud::currentColorParameterIndex() const { int RenderablePointCloud::currentSizeParameterIndex() const { const properties::OptionProperty& property = - _sizeSettings.sizeMapping.parameterOption; + _sizeSettings.sizeMapping->parameterOption; if (!_hasDatavarSize || property.options().empty()) { return 0; @@ -1093,6 +1428,41 @@ int RenderablePointCloud::currentSizeParameterIndex() const { return _dataset.index(property.option().description); } +void RenderablePointCloud::addPositionDataForPoint(unsigned int index, + std::vector& result, + double& maxRadius) const +{ + const dataloader::Dataset::Entry& e = _dataset.entries[index]; + glm::dvec3 position = transformedPosition(e); + const double r = glm::length(position); + + // Add values to result + for (int j = 0; j < 3; ++j) { + result.push_back(static_cast(position[j])); + } + + maxRadius = std::max(maxRadius, r); +} + +void RenderablePointCloud::addColorAndSizeDataForPoint(unsigned int index, + std::vector& result) const +{ + const dataloader::Dataset::Entry& e = _dataset.entries[index]; + + int colorParamIndex = currentColorParameterIndex(); + if (_hasColorMapFile && colorParamIndex >= 0) { + result.push_back(e.data[colorParamIndex]); + } + + int sizeParamIndex = currentSizeParameterIndex(); + if (_hasDatavarSize && sizeParamIndex >= 0) { + // @TODO: Consider more detailed control over the scaling. Currently the value + // is multiplied with the value as is. Should have similar mapping properties + // as the color mapping + result.push_back(e.data[sizeParamIndex]); + } +} + std::vector RenderablePointCloud::createDataSlice() { ZoneScoped; @@ -1100,43 +1470,100 @@ std::vector RenderablePointCloud::createDataSlice() { return std::vector(); } - std::vector result; - result.reserve(nAttributesPerPoint() * _dataset.entries.size()); - - // What datavar is in use for the index color - int colorParamIndex = currentColorParameterIndex(); - - // What datavar is in use for the size scaling (if present) - int sizeParamIndex = currentSizeParameterIndex(); + // What datavar is the texture, if any + int textureIdIndex = _dataset.textureDataIndex; double maxRadius = 0.0; - for (const dataloader::Dataset::Entry& e : _dataset.entries) { - glm::dvec3 position = transformedPosition(e); + // One sub-array per texture array, since each of these will correspond to a separate + // draw call. We need at least one sub result array + std::vector> subResults = std::vector>( + !_textureArrays.empty() ? _textureArrays.size() : 1 + ); - const double r = glm::length(position); - maxRadius = std::max(maxRadius, r); + // Reserve enough space for all points in each for now + for (std::vector& subres : subResults) { + subres.reserve(nAttributesPerPoint() * _dataset.entries.size()); + } - // Positions - for (int j = 0; j < 3; ++j) { - result.push_back(static_cast(position[j])); + for (unsigned int i = 0; i < _nDataPoints; i++) { + const dataloader::Dataset::Entry& e = _dataset.entries[i]; + + unsigned int subresultIndex = 0; + float textureLayer = 0.f; + + bool useMultiTexture = (_textureMode == TextureInputMode::Multi) && + (textureIdIndex >= 0); + + if (_hasSpriteTexture && useMultiTexture) { + int texId = static_cast(e.data[textureIdIndex]); + size_t texIndex = _indexInDataToTextureIndex[texId]; + textureLayer = static_cast( + _textureIndexToArrayMap[texIndex].layer + ); + subresultIndex = _textureIndexToArrayMap[texIndex].arrayId; } - // Colors - if (_hasColorMapFile && colorParamIndex > -1) { - result.push_back(e.data[colorParamIndex]); - } + std::vector& subArrayToUse = subResults[subresultIndex]; - // Size data - if (_hasDatavarSize && sizeParamIndex > -1) { - // @TODO: Consider more detailed control over the scaling. Currently the value - // is multiplied with the value as is. Should have similar mapping properties - // as the color mapping - result.push_back(e.data[sizeParamIndex]); + // Add position, color and size data (subclasses may compute these differently) + addPositionDataForPoint(i, subArrayToUse, maxRadius); + addColorAndSizeDataForPoint(i, subArrayToUse); + + // Texture layer + if (_hasSpriteTexture) { + subArrayToUse.push_back(static_cast(textureLayer)); } } + + for (std::vector& subres : subResults) { + subres.shrink_to_fit(); + } + + // Combine subresults, which should be in same order as texture arrays + std::vector result; + result.reserve(nAttributesPerPoint() * _dataset.entries.size()); + size_t vertexCount = 0; + for (size_t i = 0; i < subResults.size(); ++i) { + result.insert(result.end(), subResults[i].begin(), subResults[i].end()); + int nVertices = static_cast(subResults[i].size()) / nAttributesPerPoint(); + if (!_textureArrays.empty()) { + _textureArrays[i].nPoints = nVertices; + _textureArrays[i].startOffset = static_cast(vertexCount); + } + vertexCount += nVertices; + } + result.shrink_to_fit(); + setBoundingSphere(maxRadius); return result; } + +gl::GLenum RenderablePointCloud::internalGlFormat(bool useAlpha) const { + if (useAlpha) { + return _texture.allowCompression ? GL_COMPRESSED_RGBA_S3TC_DXT5_EXT : GL_RGBA8; + } + else { + return _texture.allowCompression ? GL_COMPRESSED_RGB_S3TC_DXT1_EXT : GL_RGB8; + } +} + +ghoul::opengl::Texture::Format RenderablePointCloud::glFormat(bool useAlpha) const { + using Texture = ghoul::opengl::Texture; + return useAlpha ? Texture::Format::RGBA : Texture::Format::RGB; +} + +bool operator==(const TextureFormat& l, const TextureFormat& r) { + return (l.resolution == r.resolution) && (l.useAlpha == r.useAlpha); +} + +size_t TextureFormatHash::operator()(const TextureFormat& k) const { + size_t res = 0; + res += static_cast(k.resolution.x) << 32; + res += static_cast(k.resolution.y) << 16; + res += k.useAlpha ? 0 : 1; + return res; +} + } // namespace openspace diff --git a/modules/base/rendering/pointcloud/renderablepointcloud.h b/modules/base/rendering/pointcloud/renderablepointcloud.h index c1ec0b0be5..05e2cf3a65 100644 --- a/modules/base/rendering/pointcloud/renderablepointcloud.h +++ b/modules/base/rendering/pointcloud/renderablepointcloud.h @@ -27,6 +27,7 @@ #include +#include #include #include #include @@ -52,6 +53,16 @@ namespace openspace { namespace documentation { struct Documentation; } +struct TextureFormat { + glm::uvec2 resolution; + bool useAlpha = false; + + friend bool operator==(const TextureFormat& l, const TextureFormat& r); +}; +struct TextureFormatHash { + size_t operator()(const TextureFormat& k) const; +}; + /** * This class describes a point cloud renderable that can be used to draw billboraded * points based on a data file with 3D positions. Alternatively the points can also @@ -74,15 +85,30 @@ public: static documentation::Documentation Documentation(); protected: + enum class TextureInputMode { + Single = 0, + Multi, + Other // For subclasses that need to handle their own texture + }; + virtual void initializeShadersAndGlExtras(); virtual void deinitializeShaders(); - virtual void bindDataForPointRendering(); + virtual void setExtraUniforms(); virtual void preUpdate(); glm::dvec3 transformedPosition(const dataloader::Dataset::Entry& e) const; virtual int nAttributesPerPoint() const; + /** + * Helper function to buffer the vertex attribute with the given name and number + * of values. Assumes that the value is a float value. + * + * Returns the updated offset after this attribute is added + */ + int bufferVertexAttribute(const std::string& name, GLint nValues, + int nAttributesPerPoint, int offset) const; + virtual void updateBufferData(); void updateSpriteTexture(); @@ -91,17 +117,42 @@ protected: /// Find the index of the currently chosen size parameter in the dataset int currentSizeParameterIndex() const; - virtual std::vector createDataSlice(); + virtual void addPositionDataForPoint(unsigned int index, std::vector& result, + double& maxRadius) const; + virtual void addColorAndSizeDataForPoint(unsigned int index, + std::vector& result) const; - virtual void bindTextureForRendering() const; + std::vector createDataSlice(); + + /** + * A function that subclasses could override to initialize their own textures to + * use for rendering, when the `_textureMode` is set to Other + */ + virtual void initializeCustomTexture(); + void initializeSingleTexture(); + void initializeMultiTextures(); + void clearTextureDataStructures(); + + void loadTexture(const std::filesystem::path& path, int index); + + void initAndAllocateTextureArray(unsigned int textureId, + glm::uvec2 resolution, size_t nLayers, bool useAlpha); + + void fillAndUploadTextureLayer(unsigned int arrayindex, unsigned int layer, + size_t textureIndex, glm::uvec2 resolution, bool useAlpha, const void* pixelData); + + void generateArrayTextures(); float computeDistanceFadeValue(const RenderData& data) const; void renderBillboards(const RenderData& data, const glm::dmat4& modelMatrix, const glm::dvec3& orthoRight, const glm::dvec3& orthoUp, float fadeInVariable); + gl::GLenum internalGlFormat(bool useAlpha) const; + ghoul::opengl::Texture::Format glFormat(bool useAlpha) const; + bool _dataIsDirty = true; - bool _spriteTextureIsDirty = true; + bool _spriteTextureIsDirty = false; bool _cmapIsDirty = true; bool _hasSpriteTexture = false; @@ -113,12 +164,7 @@ protected: struct SizeSettings : properties::PropertyOwner { explicit SizeSettings(const ghoul::Dictionary& dictionary); - struct SizeMapping : properties::PropertyOwner { - SizeMapping(); - properties::BoolProperty enabled; - properties::OptionProperty parameterOption; - }; - SizeMapping sizeMapping; + std::unique_ptr sizeMapping; properties::FloatProperty scaleExponent; properties::FloatProperty scaleFactor; @@ -146,9 +192,6 @@ protected: }; Fading _fading; - properties::BoolProperty _useSpriteTexture; - properties::StringProperty _spriteTexturePath; - properties::BoolProperty _useAdditiveBlending; properties::BoolProperty _drawElements; @@ -156,7 +199,18 @@ protected: properties::UIntProperty _nDataPoints; - ghoul::opengl::Texture* _spriteTexture = nullptr; + struct Texture : properties::PropertyOwner { + Texture(); + properties::BoolProperty enabled; + properties::BoolProperty allowCompression; + properties::BoolProperty useAlphaChannel; + properties::StringProperty spriteTexturePath; + properties::StringProperty inputMode; + }; + Texture _texture; + TextureInputMode _textureMode = TextureInputMode::Single; + std::filesystem::path _texturesDirectory; + ghoul::opengl::ProgramObject* _program = nullptr; UniformCache( @@ -165,7 +219,8 @@ protected: right, fadeInValue, hasSpriteTexture, spriteTexture, useColormap, colorMapTexture, cmapRangeMin, cmapRangeMax, nanColor, useNanColor, hideOutsideRange, enableMaxSizeControl, aboveRangeColor, useAboveRangeColor, belowRangeColor, - useBelowRangeColor, hasDvarScaling, enableOutline, outlineColor, outlineWeight + useBelowRangeColor, hasDvarScaling, dvarScaleFactor, enableOutline, outlineColor, + outlineWeight, aspectRatioScale ) _uniformCache; std::string _dataFile; @@ -181,6 +236,33 @@ protected: GLuint _vao = 0; GLuint _vbo = 0; + + // List of (unique) loaded textures. The other maps refer to the index in this vector + std::vector> _textures; + std::unordered_map _textureNameToIndex; + + // Texture index in dataset to index in vector of textures + std::unordered_map _indexInDataToTextureIndex; + + // Resolution/format to index in textures vector (used to generate one texture + // array per unique format) + std::unordered_map, TextureFormatHash> + _textureMapByFormat; + + // One per resolution above + struct TextureArrayInfo { + GLuint renderId; + GLint startOffset = -1; + int nPoints = -1; + glm::vec2 aspectRatioScale = glm::vec2(1.f); + }; + std::vector _textureArrays; + + struct TextureId { + unsigned int arrayId; + unsigned int layer; + }; + std::unordered_map _textureIndexToArrayMap; }; } // namespace openspace diff --git a/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp b/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp index 9797bce49c..8b165d9529 100644 --- a/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp +++ b/modules/base/rendering/pointcloud/renderablepolygoncloud.cpp @@ -38,8 +38,9 @@ namespace { // A RenderablePolygonCloud is a RenderablePointCloud where the shape of the points // is a uniform polygon with a given number of sides instead of a texture. For // instance, PolygonSides = 5 results in the points being rendered as pentagons. - // Note that while this renderable inherits the texture property from - // RenderablePointCloud, any added texture value will be ignored in favor of the + // + // Note that while this renderable inherits the texture component from + // RenderablePointCloud, any added texture information will be ignored in favor of the // polygon shape. // // See documentation of RenderablePointCloud for details on the other parts of the @@ -70,15 +71,11 @@ RenderablePolygonCloud::RenderablePolygonCloud(const ghoul::Dictionary& dictiona _nPolygonSides = p.polygonSides.value_or(_nPolygonSides); // The texture to use for the rendering will be generated in initializeGl. Make sure - // we use it in the rnedering + // we use it in the rendering _hasSpriteTexture = true; -} -void RenderablePolygonCloud::initializeGL() { - ZoneScoped; - - RenderablePointCloud::initializeGL(); - createPolygonTexture(); + _textureMode = TextureInputMode::Other; + removePropertySubOwner(_texture); } void RenderablePolygonCloud::deinitializeGL() { @@ -92,16 +89,24 @@ void RenderablePolygonCloud::deinitializeGL() { RenderablePointCloud::deinitializeGL(); } -void RenderablePolygonCloud::bindTextureForRendering() const { - glBindTexture(GL_TEXTURE_2D, _pTexture); -} - -void RenderablePolygonCloud::createPolygonTexture() { +void RenderablePolygonCloud::initializeCustomTexture() { ZoneScoped; + if (_textureIsInitialized) { + LWARNING("RenderablePolygonCloud texture cannot be updated during runtime"); + return; + } + LDEBUG("Creating Polygon Texture"); constexpr gl::GLsizei TexSize = 512; + // We don't use the helper function for the format and internal format here, + // as we don't want the compression to be used for the polygon texture and we + // always want alpha. This is also why we do not need to update the texture + bool useAlpha = true; + gl::GLenum format = gl::GLenum(glFormat(useAlpha)); + gl::GLenum internalFormat = GL_RGBA8; + glGenTextures(1, &_pTexture); glBindTexture(GL_TEXTURE_2D, _pTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -113,16 +118,35 @@ void RenderablePolygonCloud::createPolygonTexture() { glTexImage2D( GL_TEXTURE_2D, 0, - GL_RGBA8, + internalFormat, TexSize, TexSize, 0, - GL_RGBA, - GL_BYTE, + format, + GL_UNSIGNED_BYTE, nullptr ); renderToTexture(_pTexture, TexSize, TexSize); + + // Download the data and use it to intialize the data we need to rendering. + // Allocate memory: N channels, with one byte each + constexpr unsigned int nChannels = 4; + unsigned int arraySize = TexSize * TexSize * nChannels; + std::vector pixelData; + pixelData.resize(arraySize); + glBindTexture(GL_TEXTURE_2D, _pTexture); + glGetTexImage(GL_TEXTURE_2D, 0, format, GL_UNSIGNED_BYTE, pixelData.data()); + + // Create array from data, size and format + unsigned int id = 0; + glGenTextures(1, &id); + glBindTexture(GL_TEXTURE_2D_ARRAY, id); + initAndAllocateTextureArray(id, glm::uvec2(TexSize), 1, useAlpha); + fillAndUploadTextureLayer(0, 0, 0, glm::uvec2(TexSize), useAlpha, pixelData.data()); + glBindTexture(GL_TEXTURE_2D_ARRAY, 0); + + _textureIsInitialized = true; } void RenderablePolygonCloud::renderToTexture(GLuint textureToRenderTo, @@ -131,16 +155,16 @@ void RenderablePolygonCloud::renderToTexture(GLuint textureToRenderTo, LDEBUG("Rendering to Texture"); // Saves initial Application's OpenGL State - GLint defaultFBO; - GLint viewport[4]; + GLint defaultFBO = 0; + std::array viewport; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - glGetIntegerv(GL_VIEWPORT, viewport); + glGetIntegerv(GL_VIEWPORT, viewport.data()); GLuint textureFBO; glGenFramebuffers(1, &textureFBO); glBindFramebuffer(GL_FRAMEBUFFER, textureFBO); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); + const GLenum drawBuffers = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); @@ -191,7 +215,6 @@ void RenderablePolygonCloud::renderPolygonGeometry(GLuint vao) { glClearBufferfv(GL_COLOR, 0, glm::value_ptr(Black)); program->setUniform("sides", _nPolygonSides); - program->setUniform("polygonColor", _colorSettings.pointColor); glBindVertexArray(vao); glDrawArrays(GL_POINTS, 0, 1); diff --git a/modules/base/rendering/pointcloud/renderablepolygoncloud.h b/modules/base/rendering/pointcloud/renderablepolygoncloud.h index 745f16b0ac..9af0282401 100644 --- a/modules/base/rendering/pointcloud/renderablepolygoncloud.h +++ b/modules/base/rendering/pointcloud/renderablepolygoncloud.h @@ -44,25 +44,24 @@ public: explicit RenderablePolygonCloud(const ghoul::Dictionary& dictionary); ~RenderablePolygonCloud() override = default; - void initializeGL() override; void deinitializeGL() override; static documentation::Documentation Documentation(); private: - void createPolygonTexture(); + void initializeCustomTexture() override; void renderToTexture(GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight); void renderPolygonGeometry(GLuint vao); - void bindTextureForRendering() const override; - int _nPolygonSides = 3; GLuint _pTexture = 0; GLuint _polygonVao = 0; GLuint _polygonVbo = 0; + + bool _textureIsInitialized = false; }; } // namespace openspace diff --git a/modules/base/rendering/pointcloud/sizemappingcomponent.cpp b/modules/base/rendering/pointcloud/sizemappingcomponent.cpp new file mode 100644 index 0000000000..df57fc143c --- /dev/null +++ b/modules/base/rendering/pointcloud/sizemappingcomponent.cpp @@ -0,0 +1,131 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2024 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include + +namespace { + constexpr std::string_view _loggerCat = "SizeMapping"; + + constexpr openspace::properties::Property::PropertyInfo EnabledInfo = { + "Enabled", + "Size Mapping Enabled", + "If this value is set to 'true' and at least one column was loaded as an option " + "for size mapping, the chosen data column will be used to scale the size of the " + "points. The first option in the list is selected per default.", + openspace::properties::Property::Visibility::NoviceUser + }; + + constexpr openspace::properties::Property::PropertyInfo OptionInfo = { + "Parameter", + "Parameter Option", + "This value determines which parameter is used for scaling of the point. The " + "parameter value will be used as a multiplicative factor to scale the size of " + "the points. Note that they may however still be scaled by max size adjustment " + "effects.", + openspace::properties::Property::Visibility::AdvancedUser + }; + + constexpr openspace::properties::Property::PropertyInfo ScaleFactorInfo = { + "ScaleFactor", + "Scale Factor", + "This value is a multiplicative factor that is applied to the data values that " + "are used to scale the points, when size mapping is applied.", + openspace::properties::Property::Visibility::AdvancedUser + }; + + struct [[codegen::Dictionary(SizeMappingComponent)]] Parameters { + // [[codegen::verbatim(EnabledInfo.description)]] + std::optional enabled; + + // A list specifying all parameters that may be used for size mapping, i.e. + // scaling the points based on the provided data columns + std::optional> parameterOptions; + + // [[codegen::verbatim(OptionInfo.description)]] + std::optional parameter; + + // [[codegen::verbatim(ScaleFactorInfo.description)]] + std::optional scaleFactor; + }; +#include "sizemappingcomponent_codegen.cpp" +} // namespace + +namespace openspace { + +documentation::Documentation SizeMappingComponent::Documentation() { + return codegen::doc("base_sizemappingcomponent"); +} + +SizeMappingComponent::SizeMappingComponent() + : properties::PropertyOwner({ "SizeMapping", "Size Mapping", "" }) + , enabled(EnabledInfo, true) + , parameterOption( + OptionInfo, + properties::OptionProperty::DisplayType::Dropdown + ) + , scaleFactor(ScaleFactorInfo, 1.f, 0.f, 1000.f) +{ + addProperty(enabled); + addProperty(parameterOption); + addProperty(scaleFactor); +} + +SizeMappingComponent::SizeMappingComponent(const ghoul::Dictionary& dictionary) + : SizeMappingComponent() +{ + const Parameters p = codegen::bake(dictionary); + + enabled = p.enabled.value_or(enabled); + + int indexOfProvidedOption = -1; + + if (p.parameterOptions.has_value()) { + std::vector opts = *p.parameterOptions; + for (size_t i = 0; i < opts.size(); ++i) { + // Note that options are added in order + parameterOption.addOption(static_cast(i), opts[i]); + + if (p.parameter.has_value() && *p.parameter == opts[i]) { + indexOfProvidedOption = i; + } + } + } + + if (indexOfProvidedOption >= 0) { + parameterOption = indexOfProvidedOption; + } + else if (p.parameter.has_value()) { + LERROR(std::format( + "Error when reading Parameter. Could not find provided parameter '{}' in " + "list of parameter options. Using default.", *p.parameter + )); + } + + scaleFactor = p.scaleFactor.value_or(scaleFactor); +} + +} // namespace openspace diff --git a/modules/base/rendering/pointcloud/sizemappingcomponent.h b/modules/base/rendering/pointcloud/sizemappingcomponent.h new file mode 100644 index 0000000000..800436a09f --- /dev/null +++ b/modules/base/rendering/pointcloud/sizemappingcomponent.h @@ -0,0 +1,56 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2024 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_BASE___SIZEMAPPINGCOMPONENT___H__ +#define __OPENSPACE_MODULE_BASE___SIZEMAPPINGCOMPONENT___H__ + +#include + +#include +#include +#include + +namespace openspace { + +namespace documentation { struct Documentation; } + +/** + * This is a component that can be used to hold parameters and properties for scaling + * point cloud points (or other data-based entities) based a parameter in a dataset. + */ +struct SizeMappingComponent : public properties::PropertyOwner { + SizeMappingComponent(); + explicit SizeMappingComponent(const ghoul::Dictionary& dictionary); + ~SizeMappingComponent() override = default; + + static documentation::Documentation Documentation(); + + properties::BoolProperty enabled; + properties::OptionProperty parameterOption; + properties::FloatProperty scaleFactor; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_BASE___SIZEMAPPINGCOMPONENT___H__ diff --git a/modules/base/rendering/renderablelabel.cpp b/modules/base/rendering/renderablelabel.cpp index d57d43d25c..a73fdf0611 100644 --- a/modules/base/rendering/renderablelabel.cpp +++ b/modules/base/rendering/renderablelabel.cpp @@ -403,30 +403,32 @@ void RenderableLabel::render(const RenderData& data, RendererTasks&) { float fadeInVariable = 1.f; if (_enableFadingEffect) { - float distanceNodeToCamera = static_cast( + const float distanceNodeToCamera = static_cast( glm::distance(data.camera.positionVec3(), data.modelTransform.translation) ); fadeInVariable = computeFadeFactor(distanceNodeToCamera); } - glm::dmat4 modelMatrix(1.0); + const glm::dmat4 modelMatrix = glm::dmat4(1.0); const glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform(data, modelMatrix); - glm::dvec3 cameraViewDirectionWorld = -data.camera.viewDirectionWorldSpace(); - glm::dvec3 cameraUpDirectionWorld = data.camera.lookUpVectorWorldSpace(); + const glm::dvec3 cameraViewDirectionWorld = -data.camera.viewDirectionWorldSpace(); + const glm::dvec3 cameraUpDirectionWorld = data.camera.lookUpVectorWorldSpace(); glm::dvec3 orthoRight = glm::normalize( glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld) ); if (orthoRight == glm::dvec3(0.0)) { - glm::dvec3 otherVector( + const glm::dvec3 otherVector = glm::dvec3( cameraUpDirectionWorld.y, cameraUpDirectionWorld.x, cameraUpDirectionWorld.z ); orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirectionWorld)); } - glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirectionWorld, orthoRight)); + const glm::dvec3 orthoUp = glm::normalize( + glm::cross(cameraViewDirectionWorld, orthoRight) + ); renderLabels(data, modelViewProjectionTransform, orthoRight, orthoUp, fadeInVariable); @@ -464,7 +466,7 @@ void RenderableLabel::renderLabels(const RenderData& data, labelInfo.enableFalseDepth = false; // We don't use spice rotation and scale - glm::vec3 transformedPos( + const glm::vec3 transformedPos = glm::vec3( _transformationMatrix * glm::dvec4(data.modelTransform.translation, 1.0) ); @@ -478,25 +480,25 @@ void RenderableLabel::renderLabels(const RenderData& data, } float RenderableLabel::computeFadeFactor(float distanceNodeToCamera) const { - float distanceUnit = unit(_fadeUnitOption); + const float distanceUnit = unit(_fadeUnitOption); - float x = distanceNodeToCamera; - float startX = _fadeDistances.value().x * distanceUnit; - float endX = _fadeDistances.value().y * distanceUnit; + const float x = distanceNodeToCamera; + const float startX = _fadeDistances.value().x * distanceUnit; + const float endX = _fadeDistances.value().y * distanceUnit; // The distances over which the fading should happen - float fadingStartDistance = _fadeWidths.value().x * distanceUnit; - float fadingEndDistance = _fadeWidths.value().y * distanceUnit; + const float fadingStartDistance = _fadeWidths.value().x * distanceUnit; + const float fadingEndDistance = _fadeWidths.value().y * distanceUnit; if (x <= startX) { - float f1 = 1.f - (startX - x) / fadingStartDistance; + const float f1 = 1.f - (startX - x) / fadingStartDistance; return std::clamp(f1, 0.f, 1.f); } else if (x > startX && x < endX) { return 1.f; // not faded } else { // x >= endX - float f2 = 1.f - (x - endX) / fadingEndDistance; + const float f2 = 1.f - (x - endX) / fadingEndDistance; return std::clamp(f2, 0.f, 1.f); } } diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index 141361da84..8ef6682a6b 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -69,12 +69,6 @@ namespace { constexpr glm::vec4 PosBufferClearVal = glm::vec4(1e32, 1e32, 1e32, 1.f); - const GLenum ColorAttachmentArray[3] = { - GL_COLOR_ATTACHMENT0, - GL_COLOR_ATTACHMENT1, - GL_COLOR_ATTACHMENT2, - }; - constexpr std::array UniformNames = { "modelViewTransform", "projectionTransform", "normalTransform", "meshTransform", "meshNormalTransform", "ambientIntensity", "diffuseIntensity", @@ -363,16 +357,16 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) _file = absPath(p.geometryFile.string()); if (!std::filesystem::exists(_file)) { - throw ghoul::RuntimeError(fmt::format("Cannot find model file {}", _file)); + throw ghoul::RuntimeError(std::format("Cannot find model file '{}'", _file)); } _invertModelScale = p.invertModelScale.value_or(_invertModelScale); if (p.modelScale.has_value()) { if (std::holds_alternative(*p.modelScale)) { - Parameters::ScaleUnit scaleUnit = + const Parameters::ScaleUnit scaleUnit = std::get(*p.modelScale); - DistanceUnit distanceUnit = codegen::map(scaleUnit); + const DistanceUnit distanceUnit = codegen::map(scaleUnit); _modelScale = toMeter(distanceUnit); } else if (std::holds_alternative(*p.modelScale)) { @@ -400,9 +394,9 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) *p.animationTimeScale )) { - Parameters::AnimationTimeUnit animationTimeUnit = + const Parameters::AnimationTimeUnit animationTimeUnit = std::get(*p.animationTimeScale); - TimeUnit timeUnit = codegen::map(animationTimeUnit); + const TimeUnit timeUnit = codegen::map(animationTimeUnit); _animationTimeScale = static_cast( convertTime(1.0, timeUnit, TimeUnit::Second) @@ -448,7 +442,7 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) } if (p.lightSources.has_value()) { - std::vector lightsources = *p.lightSources; + const std::vector lightsources = *p.lightSources; for (const ghoul::Dictionary& lsDictionary : lightsources) { std::unique_ptr lightSource = @@ -475,7 +469,9 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) _modelScale.onChange([this]() { if (!_geometry) { - LWARNING(fmt::format("Cannot set scale for model {}; not loaded yet", _file)); + LWARNING(std::format( + "Cannot set scale for model '{}': not loaded yet", _file + )); return; } @@ -491,21 +487,21 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) _enableAnimation.onChange([this]() { if (!_modelHasAnimation) { - LWARNING(fmt::format( - "Cannot enable animation for model {}; it does not have any", _file + LWARNING(std::format( + "Cannot enable animation for model '{}': it does not have any", _file )); } else if (_enableAnimation && _animationStart.empty()) { - LWARNING(fmt::format( - "Cannot enable animation for model {}; it does not have a start time", + LWARNING(std::format( + "Cannot enable animation for model '{}': it does not have a start time", _file )); _enableAnimation = false; } else { if (!_geometry) { - LWARNING(fmt::format( - "Cannot enable animation for model {}; not loaded yet", _file + LWARNING(std::format( + "Cannot enable animation for model '{}': not loaded yet", _file )); return; } @@ -564,14 +560,14 @@ void RenderableModel::initializeGL() { if (!_modelHasAnimation) { if (!_animationStart.empty()) { - LWARNING(fmt::format( - "Animation start time given to model {} without animation", _file + LWARNING(std::format( + "Animation start time given to model '{}' without animation", _file )); } if (_enableAnimation) { - LWARNING(fmt::format( - "Cannot enable animation for model {}; it does not have any", _file + LWARNING(std::format( + "Cannot enable animation for model '{}': it does not have any", _file )); _enableAnimation = false; } @@ -580,14 +576,14 @@ void RenderableModel::initializeGL() { } else { if (_enableAnimation && _animationStart.empty()) { - LWARNING(fmt::format( - "Cannot enable animation for model {}; it does not have a start time", + LWARNING(std::format( + "Cannot enable animation for model '{}': it does not have a start time", _file )); } else if (!_enableAnimation) { - LINFO(fmt::format( - "Model {} with deactivated animation was found. The animation can be " + LINFO(std::format( + "Model '{}' with deactivated animation was found. The animation can be " "activated by entering a start time in the asset file", _file )); } @@ -607,11 +603,11 @@ void RenderableModel::initializeGL() { _program = BaseModule::ProgramObjectManager.request( program, [this, program]() -> std::unique_ptr { - std::filesystem::path vs = + const std::filesystem::path vs = _vertexShaderPath.empty() ? absPath("${MODULE_BASE}/shaders/model_vs.glsl") : std::filesystem::path(_vertexShaderPath); - std::filesystem::path fs = + const std::filesystem::path fs = _fragmentShaderPath.empty() ? absPath("${MODULE_BASE}/shaders/model_fs.glsl") : std::filesystem::path(_fragmentShaderPath); @@ -630,9 +626,9 @@ void RenderableModel::initializeGL() { _quadProgram = BaseModule::ProgramObjectManager.request( "ModelOpacityProgram", [&]() -> std::unique_ptr { - std::filesystem::path vs = + const std::filesystem::path vs = absPath("${MODULE_BASE}/shaders/modelOpacity_vs.glsl"); - std::filesystem::path fs = + const std::filesystem::path fs = absPath("${MODULE_BASE}/shaders/modelOpacity_fs.glsl"); return global::renderEngine->buildRenderProgram( @@ -649,7 +645,7 @@ void RenderableModel::initializeGL() { ); // Screen quad VAO - const GLfloat quadVertices[] = { + constexpr std::array QuadVtx = { // x y s t -1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, @@ -665,7 +661,7 @@ void RenderableModel::initializeGL() { glGenBuffers(1, &_quadVbo); glBindBuffer(GL_ARRAY_BUFFER, _quadVbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(QuadVtx), QuadVtx.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(1); @@ -713,7 +709,7 @@ void RenderableModel::initializeGL() { } // Check status - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + const GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framebuffer is not complete"); } @@ -835,7 +831,7 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { glm::mat4(modelViewTransform) ); - glm::dmat4 normalTransform = glm::transpose(glm::inverse(modelViewTransform)); + const glm::dmat4 normalTransform = glm::transpose(glm::inverse(modelViewTransform)); _program->setUniform( _uniformCache.normalTransform, @@ -893,7 +889,7 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { } else { // Prepare framebuffer - GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); + const GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); glBindFramebuffer(GL_FRAMEBUFFER, _framebuffer); // Re-bind first texture to use the currently not used Ping-Pong texture in the @@ -905,12 +901,17 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { 0 ); // Check status - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + const GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framebuffer is not complete"); } - glDrawBuffers(3, ColorAttachmentArray); + constexpr std::array ColorAttachmentArray = { + GL_COLOR_ATTACHMENT0, + GL_COLOR_ATTACHMENT1, + GL_COLOR_ATTACHMENT2, + }; + glDrawBuffers(3, ColorAttachmentArray.data()); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearBufferfv(GL_COLOR, 1, glm::value_ptr(PosBufferClearVal)); @@ -985,8 +986,8 @@ void RenderableModel::render(const RenderData& data, RendererTasks&) { glm::vec2(global::windowDelegate->currentDrawBufferResolution()) ); - GLint vp[4] = { 0 }; - global::renderEngine->openglStateCache().viewport(vp); + std::array vp = {}; + global::renderEngine->openglStateCache().viewport(vp.data()); glm::ivec4 viewport = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); _quadProgram->setUniform( _uniformOpacityCache.viewport, @@ -1047,9 +1048,9 @@ void RenderableModel::update(const UpdateData& data) { if (_geometry->hasAnimation() && !_animationStart.empty()) { double relativeTime = 0.0; - double now = data.time.j2000Seconds(); - double startTime = data.time.convertTime(_animationStart); - double duration = _geometry->animationDuration(); + const double now = data.time.j2000Seconds(); + const double startTime = Time::convertTime(_animationStart); + const double duration = _geometry->animationDuration(); // The animation works in a time range 0 to duration where 0 in the animation is // the given _animationStart time in OpenSpace. The time in OpenSpace then has to diff --git a/modules/base/rendering/renderablenodearrow.cpp b/modules/base/rendering/renderablenodearrow.cpp index 77103a9955..43a37c69fd 100644 --- a/modules/base/rendering/renderablenodearrow.cpp +++ b/modules/base/rendering/renderablenodearrow.cpp @@ -228,7 +228,7 @@ namespace { SceneGraphNode* startNode = sceneGraphNode(nodeName); if (!startNode) { - LERROR(fmt::format("Could not find start node '{}'", nodeName)); + LERROR(std::format("Could not find start node '{}'", nodeName)); return; } const double boundingSphere = startNode->boundingSphere(); @@ -242,7 +242,7 @@ namespace { else { // Recompute distance (previous value was in meters) if (boundingSphere < std::numeric_limits::epsilon()) { - LERROR(fmt::format( + LERROR(std::format( "Start node '{}' has invalid bounding sphere", nodeName )); return; @@ -383,20 +383,21 @@ void RenderableNodeArrow::updateShapeTransforms(const RenderData& data) { SceneGraphNode* endNode = sceneGraphNode(_end); if (!startNode) { - LERROR(fmt::format("Could not find start node '{}'", _start.value())); + LERROR(std::format("Could not find start node '{}'", _start.value())); return; } if (!endNode) { - LERROR(fmt::format("Could not find end node '{}'", _end.value())); + LERROR(std::format("Could not find end node '{}'", _end.value())); return; } const double boundingSphere = startNode->boundingSphere(); - bool hasNoBoundingSphere = boundingSphere < std::numeric_limits::epsilon(); + const bool hasNoBoundingSphere = + boundingSphere < std::numeric_limits::epsilon(); if (hasNoBoundingSphere && (_useRelativeLength || _useRelativeOffset)) { - LERROR(fmt::format( + LERROR(std::format( "Node '{}' has no valid bounding sphere. Can not use relative values", _end.value() )); @@ -420,8 +421,8 @@ void RenderableNodeArrow::updateShapeTransforms(const RenderData& data) { ); // Update the position based on the arrowDirection of the nodes - glm::dvec3 startNodePos = startNode->worldPosition(); - glm::dvec3 endNodePos = endNode->worldPosition(); + const glm::dvec3 startNodePos = startNode->worldPosition(); + const glm::dvec3 endNodePos = endNode->worldPosition(); glm::dvec3 arrowDirection = glm::normalize(endNodePos - startNodePos); glm::dvec3 startPos = glm::dvec3(startNodePos + offset * arrowDirection); @@ -432,26 +433,26 @@ void RenderableNodeArrow::updateShapeTransforms(const RenderData& data) { arrowDirection *= -1.0; } - double coneLength = _arrowHeadSize * length; - double cylinderLength = length - coneLength; - double arrowHeadWidth = _width * _arrowHeadWidthFactor; + const double coneLength = _arrowHeadSize * length; + const double cylinderLength = length - coneLength; + const double arrowHeadWidth = _width * _arrowHeadWidthFactor; // Create transformation matrices to reshape to size and position _cylinderTranslation = glm::translate(glm::dmat4(1.0), startPos); - glm::dvec3 cylinderScale = glm::dvec3( + const glm::dvec3 cylinderScale = glm::dvec3( s * glm::dvec4(_width, _width, cylinderLength, 0.0) ); _cylinderScale = glm::scale(glm::dmat4(1.0), cylinderScale); // Adapt arrow head start to scaled size - glm::dvec3 arrowHeadStartPos = startPos + cylinderScale.z * arrowDirection; + const glm::dvec3 arrowHeadStartPos = startPos + cylinderScale.z * arrowDirection; _coneTranslation = glm::translate(glm::dmat4(1.0), arrowHeadStartPos); - glm::dvec3 coneScale = glm::dvec3(arrowHeadWidth, arrowHeadWidth, coneLength); + const glm::dvec3 coneScale = glm::dvec3(arrowHeadWidth, arrowHeadWidth, coneLength); _coneScale = s * glm::scale(glm::dmat4(1.0), coneScale); // Rotation to point at the end node - glm::quat rotQuat = glm::rotation(glm::dvec3(0.0, 0.0, 1.0), arrowDirection); + const glm::quat rotQuat = glm::rotation(glm::dvec3(0.0, 0.0, 1.0), arrowDirection); _pointDirectionRotation = glm::dmat4(glm::toMat4(rotQuat)); } diff --git a/modules/base/rendering/renderablenodeline.cpp b/modules/base/rendering/renderablenodeline.cpp index 68f6ebc97d..b48f8b04d1 100644 --- a/modules/base/rendering/renderablenodeline.cpp +++ b/modules/base/rendering/renderablenodeline.cpp @@ -111,7 +111,7 @@ namespace { if (nav.anchorNode()) { anchorNodePos = nav.anchorNode()->worldPosition(); } - glm::dvec3 diffPos = worldPos - anchorNodePos; + const glm::dvec3 diffPos = worldPos - anchorNodePos; return diffPos; } @@ -181,11 +181,10 @@ RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) if (!node || node->boundingSphere() > 0.0) { return; } - LWARNING(fmt::format( - "Setting StartOffset for node line '{}': " - "Trying to use relative offsets for start node '{}' that has no " - "bounding sphere. This will result in no offset. Use direct " - "values by setting UseRelativeOffsets to false", + LWARNING(std::format( + "Setting StartOffset for node line '{}': Trying to use relative offsets " + "for start node '{}' that has no bounding sphere. This will result in no " + "offset. Use direct values by setting UseRelativeOffsets to false", parent()->identifier(), _start.value() )); } @@ -199,11 +198,10 @@ RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) if (!node || node->boundingSphere() > 0.0) { return; } - LWARNING(fmt::format( - "Setting EndOffset for node line '{}': " - "Trying to use relative offsets for end node '{}' that has no " - "bounding sphere. This will result in no offset. Use direct " - "values by setting UseRelativeOffsets to false", + LWARNING(std::format( + "Setting EndOffset for node line '{}': Trying to use relative offsets " + "for end node '{}' that has no bounding sphere. This will result in no " + "offset. Use direct values by setting UseRelativeOffsets to false", parent()->identifier(), _end.value() )); } @@ -215,7 +213,7 @@ RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) SceneGraphNode* endNode = global::renderEngine->scene()->sceneGraphNode(_end); if (!startNode) { - LERROR(fmt::format( + LERROR(std::format( "Error when recomputing node line offsets for scene graph node '{}'. " "Could not find start node '{}'", parent()->identifier(), _start.value() )); @@ -223,7 +221,7 @@ RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) } if (!endNode) { - LERROR(fmt::format( + LERROR(std::format( "Error when recomputing node line offsets for scene graph node '{}'. " "Could not find end node '{}'", parent()->identifier(), _end.value() )); @@ -232,8 +230,8 @@ RenderableNodeLine::RenderableNodeLine(const ghoul::Dictionary& dictionary) if (_useRelativeOffsets) { // Recompute previous offsets to relative values - double startBs = startNode->boundingSphere(); - double endBs = endNode->boundingSphere(); + const double startBs = startNode->boundingSphere(); + const double endBs = endNode->boundingSphere(); _startOffset = static_cast(startBs > 0.0 ? _startOffset / startBs : 0.0); _endOffset = @@ -275,12 +273,14 @@ void RenderableNodeLine::initializeGL() { glGenVertexArrays(1, &_vaoId); glGenBuffers(1, &_vBufferId); - bindGL(); + glBindVertexArray(_vaoId); + glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); glVertexAttribPointer(_locVertex, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); glEnableVertexAttribArray(_locVertex); - unbindGL(); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); } void RenderableNodeLine::deinitializeGL() { @@ -305,27 +305,17 @@ bool RenderableNodeLine::isReady() const { return ready; } -void RenderableNodeLine::unbindGL() { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); -} - -void RenderableNodeLine::bindGL() { - glBindVertexArray(_vaoId); - glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); -} - void RenderableNodeLine::updateVertexData() { SceneGraphNode* startNode = global::renderEngine->scene()->sceneGraphNode(_start); SceneGraphNode* endNode = global::renderEngine->scene()->sceneGraphNode(_end); if (!startNode) { - LERROR(fmt::format("Could not find start node '{}'", _start.value())); + LERROR(std::format("Could not find start node '{}'", _start.value())); return; } if (!endNode) { - LERROR(fmt::format("Could not find end node '{}'", _end.value())); + LERROR(std::format("Could not find end node '{}'", _end.value())); return; } @@ -344,9 +334,9 @@ void RenderableNodeLine::updateVertexData() { } // Compute line positions - glm::dvec3 dir = glm::normalize(_endPos - _startPos); - glm::dvec3 startPos = _startPos + startOffset * dir; - glm::dvec3 endPos = _endPos - endOffset * dir; + const glm::dvec3 dir = glm::normalize(_endPos - _startPos); + const glm::dvec3 startPos = _startPos + startOffset * dir; + const glm::dvec3 endPos = _endPos - endOffset * dir; _vertexArray.push_back(static_cast(startPos.x)); _vertexArray.push_back(static_cast(startPos.y)); @@ -356,7 +346,8 @@ void RenderableNodeLine::updateVertexData() { _vertexArray.push_back(static_cast(endPos.y)); _vertexArray.push_back(static_cast(endPos.z)); - bindGL(); + glBindVertexArray(_vaoId); + glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); glBufferData( GL_ARRAY_BUFFER, _vertexArray.size() * sizeof(float), @@ -367,7 +358,8 @@ void RenderableNodeLine::updateVertexData() { // update vertex attributes glVertexAttribPointer(_locVertex, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); - unbindGL(); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); } void RenderableNodeLine::update(const UpdateData&) { @@ -401,11 +393,13 @@ void RenderableNodeLine::render(const RenderData& data, RendererTasks&) { glLineWidth(_lineWidth); // Bind and draw - bindGL(); + glBindVertexArray(_vaoId); + glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); glDrawArrays(GL_LINES, 0, 2); // Restore GL State - unbindGL(); + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); _program->deactivate(); global::renderEngine->openglStateCache().resetBlendState(); global::renderEngine->openglStateCache().resetLineState(); diff --git a/modules/base/rendering/renderablenodeline.h b/modules/base/rendering/renderablenodeline.h index 65a0694692..7160dd96bb 100644 --- a/modules/base/rendering/renderablenodeline.h +++ b/modules/base/rendering/renderablenodeline.h @@ -65,9 +65,6 @@ private: void update(const UpdateData& data) override; void render(const RenderData& data, RendererTasks& rendererTask) override; - void unbindGL(); - void bindGL(); - ghoul::opengl::ProgramObject* _program; /// The vertex attribute location for position /// must correlate to layout location in vertex shader diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index cf5285f1c4..9baf51f932 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -156,7 +156,7 @@ RenderablePlane::RenderablePlane(const ghoul::Dictionary& dictionary) { static_cast(BlendMode::Additive), "Additive"} }); _blendMode.onChange([this]() { - BlendMode m = static_cast(_blendMode.value()); + const BlendMode m = static_cast(_blendMode.value()); switch (m) { case BlendMode::Normal: setRenderBinFromOpacity(); @@ -244,17 +244,17 @@ void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->setUniform(_uniformCache.mirrorBackside, _mirrorBackside); - glm::dvec3 objectPositionWorld = glm::dvec3( + const glm::dvec3 objPosWorld = glm::dvec3( glm::translate( glm::dmat4(1.0), data.modelTransform.translation) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); - glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - objectPositionWorld); - glm::dvec3 newRight = glm::normalize( + const glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - objPosWorld); + const glm::dvec3 newRight = glm::normalize( glm::cross(data.camera.lookUpVectorWorldSpace(), normal) ); - glm::dvec3 newUp = glm::cross(normal, newRight); + const glm::dvec3 newUp = glm::cross(normal, newRight); glm::dmat4 cameraOrientedRotation = glm::dmat4(1.0); cameraOrientedRotation[0] = glm::dvec4(newRight, 0.0); @@ -283,7 +283,7 @@ void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->setUniform(_uniformCache.multiplyColor, _multiplyColor); - bool additiveBlending = (_blendMode == static_cast(BlendMode::Additive)); + const bool additiveBlending = (_blendMode == static_cast(BlendMode::Additive)); if (additiveBlending) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); @@ -322,7 +322,7 @@ void RenderablePlane::update(const UpdateData&) { void RenderablePlane::createPlane() { const GLfloat sizeX = _size.value().x; const GLfloat sizeY = _size.value().y; - const GLfloat vertexData[] = { + const std::array vertexData = { // x y z w s t -sizeX, -sizeY, 0.f, 0.f, 0.f, 0.f, sizeX, sizeY, 0.f, 0.f, 1.f, 1.f, @@ -334,7 +334,7 @@ void RenderablePlane::createPlane() { glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); diff --git a/modules/base/rendering/renderableplaneimagelocal.cpp b/modules/base/rendering/renderableplaneimagelocal.cpp index 6114da3d5d..9066e74764 100644 --- a/modules/base/rendering/renderableplaneimagelocal.cpp +++ b/modules/base/rendering/renderableplaneimagelocal.cpp @@ -102,15 +102,15 @@ RenderablePlaneImageLocal::RenderablePlaneImageLocal(const ghoul::Dictionary& di } // Shape the plane based on the aspect ration of the image - glm::vec2 textureDim = glm::vec2(_texture->dimensions()); + const glm::vec2 textureDim = glm::vec2(_texture->dimensions()); if (_textureDimensions != textureDim) { - float aspectRatio = textureDim.x / textureDim.y; - float planeAspectRatio = _size.value().x / _size.value().y; + const float aspectRatio = textureDim.x / textureDim.y; + const float planeAspectRatio = _size.value().x / _size.value().y; if (std::abs(planeAspectRatio - aspectRatio) > std::numeric_limits::epsilon()) { - glm::vec2 newSize = + const glm::vec2 newSize = aspectRatio > 0.f ? glm::vec2(_size.value().x * aspectRatio, _size.value().y) : glm::vec2(_size.value().x, _size.value().y * aspectRatio); @@ -162,7 +162,7 @@ void RenderablePlaneImageLocal::loadTexture() { if (!_texturePath.value().empty()) { ghoul::opengl::Texture* t = _texture; - unsigned int hash = ghoul::hashCRC32File(_texturePath); + const unsigned int hash = ghoul::hashCRC32File(_texturePath); _texture = BaseModule::TextureManager.request( std::to_string(hash), @@ -175,7 +175,7 @@ void RenderablePlaneImageLocal::loadTexture() { LDEBUGC( "RenderablePlaneImageLocal", - fmt::format("Loaded texture from {}", absPath(path)) + std::format("Loaded texture from '{}'", absPath(path)) ); texture->uploadTexture(); texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); @@ -195,15 +195,15 @@ void RenderablePlaneImageLocal::loadTexture() { } // Shape the plane based on the aspect ration of the image - glm::vec2 textureDim = glm::vec2(_texture->dimensions()); + const glm::vec2 textureDim = glm::vec2(_texture->dimensions()); if (_textureDimensions != textureDim) { - float aspectRatio = textureDim.x / textureDim.y; - float planeAspectRatio = _size.value().x / _size.value().y; + const float aspectRatio = textureDim.x / textureDim.y; + const float planeAspectRatio = _size.value().x / _size.value().y; if (std::abs(planeAspectRatio - aspectRatio) > std::numeric_limits::epsilon()) { - glm::vec2 newSize = + const glm::vec2 newSize = aspectRatio > 0.f ? glm::vec2(_size.value().x * aspectRatio, _size.value().y) : glm::vec2(_size.value().x, _size.value().y * aspectRatio); diff --git a/modules/base/rendering/renderableplaneimageonline.cpp b/modules/base/rendering/renderableplaneimageonline.cpp index cb662f70a5..142542c671 100644 --- a/modules/base/rendering/renderableplaneimageonline.cpp +++ b/modules/base/rendering/renderableplaneimageonline.cpp @@ -77,19 +77,18 @@ RenderablePlaneImageOnline::RenderablePlaneImageOnline( } // Shape the plane based on the aspect ration of the image - glm::vec2 textureDim = glm::vec2(_texture->dimensions()); + const glm::vec2 textureDim = glm::vec2(_texture->dimensions()); if (_textureDimensions != textureDim) { - float aspectRatio = textureDim.x / textureDim.y; - float planeAspectRatio = _size.value().x / _size.value().y; + const float aspectRatio = textureDim.x / textureDim.y; + const float planeAspectRatio = _size.value().x / _size.value().y; if (std::abs(planeAspectRatio - aspectRatio) > std::numeric_limits::epsilon()) { - glm::vec2 newSize = + _size = aspectRatio > 0.f ? glm::vec2(_size.value().x * aspectRatio, _size.value().y) : glm::vec2(_size.value().x, _size.value().y * aspectRatio); - _size = newSize; } _textureDimensions = textureDim; @@ -129,12 +128,12 @@ void RenderablePlaneImageOnline::update(const UpdateData& data) { } if (_imageFuture.valid() && DownloadManager::futureReady(_imageFuture)) { - DownloadManager::MemoryFile imageFile = _imageFuture.get(); + const DownloadManager::MemoryFile imageFile = _imageFuture.get(); if (imageFile.corrupted) { LERRORC( "ScreenSpaceImageOnline", - fmt::format("Error loading image from URL '{}'", _texturePath.value()) + std::format("Error loading image from URL '{}'", _texturePath.value()) ); return; } @@ -165,19 +164,18 @@ void RenderablePlaneImageOnline::update(const UpdateData& data) { } // Shape the plane based on the aspect ration of the image - glm::vec2 textureDim = glm::vec2(_texture->dimensions()); + const glm::vec2 textureDim = glm::vec2(_texture->dimensions()); if (_textureDimensions != textureDim) { - float aspectRatio = textureDim.x / textureDim.y; - float planeAspectRatio = _size.value().x / _size.value().y; + const float aspectRatio = textureDim.x / textureDim.y; + const float planeAspectRatio = _size.value().x / _size.value().y; if (std::abs(planeAspectRatio - aspectRatio) > std::numeric_limits::epsilon()) { - glm::vec2 newSize = + _size = aspectRatio > 0.f ? glm::vec2(_size.value().x * aspectRatio, _size.value().y) : glm::vec2(_size.value().x, _size.value().y * aspectRatio); - _size = newSize; } _textureDimensions = textureDim; diff --git a/modules/base/rendering/renderableplanetimevaryingimage.cpp b/modules/base/rendering/renderableplanetimevaryingimage.cpp index 01059789bf..ed6dc0e92a 100644 --- a/modules/base/rendering/renderableplanetimevaryingimage.cpp +++ b/modules/base/rendering/renderableplanetimevaryingimage.cpp @@ -96,8 +96,8 @@ RenderablePlaneTimeVaryingImage::RenderablePlaneTimeVaryingImage( _sourceFolder = p.sourceFolder; if (!std::filesystem::is_directory(absPath(_sourceFolder))) { - LERROR(fmt::format( - "Time varying image, {} is not a valid directory", + LERROR(std::format( + "Time varying image, '{}' is not a valid directory", _sourceFolder.value() )); } @@ -131,7 +131,7 @@ RenderablePlaneTimeVaryingImage::RenderablePlaneTimeVaryingImage( void RenderablePlaneTimeVaryingImage::initialize() { RenderablePlane::initialize(); - bool success = extractMandatoryInfoFromDictionary(); + const bool success = extractMandatoryInfoFromDictionary(); if (!success) { return; } @@ -143,7 +143,7 @@ void RenderablePlaneTimeVaryingImage::initializeGL() { RenderablePlane::initializeGL(); _textureFiles.resize(_sourceFiles.size()); - for (size_t i = 0; i < _sourceFiles.size(); ++i) { + for (size_t i = 0; i < _sourceFiles.size(); i++) { _textureFiles[i] = ghoul::io::TextureReader::ref().loadTexture( absPath(_sourceFiles[i]).string(), 2 @@ -162,7 +162,7 @@ bool RenderablePlaneTimeVaryingImage::extractMandatoryInfoFromDictionary() { // Ensure that the source folder exists and then extract // the files with the same extension as namespace fs = std::filesystem; - fs::path sourceFolder = absPath(_sourceFolder); + const fs::path sourceFolder = absPath(_sourceFolder); // Extract all file paths from the provided folder _sourceFiles.clear(); namespace fs = std::filesystem; @@ -174,8 +174,8 @@ bool RenderablePlaneTimeVaryingImage::extractMandatoryInfoFromDictionary() { std::sort(_sourceFiles.begin(), _sourceFiles.end()); // Ensure that there are available and valid source files left if (_sourceFiles.empty()) { - LERROR(fmt::format( - "{}: Plane sequence filepath {} was empty", + LERROR(std::format( + "{}: Plane sequence filepath '{}' was empty", _identifier, _sourceFolder.value() )); return false; @@ -206,8 +206,8 @@ void RenderablePlaneTimeVaryingImage::update(const UpdateData& data) { } bool needsUpdate = false; const double currentTime = data.time.j2000Seconds(); - bool isInInterval = (currentTime >= _startTimes[0]) && - (currentTime < _sequenceEndTime); + const bool isInInterval = (currentTime >= _startTimes[0]) && + (currentTime < _sequenceEndTime); if (isInInterval) { const size_t nextIdx = _activeTriggerTimeIndex + 1; if ( @@ -268,7 +268,7 @@ int RenderablePlaneTimeVaryingImage::updateActiveTriggerTimeIndex( auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime); if (iter != _startTimes.end()) { if (iter != _startTimes.begin()) { - std::ptrdiff_t idx = std::distance(_startTimes.begin(), iter); + const std::ptrdiff_t idx = std::distance(_startTimes.begin(), iter); activeIndex = static_cast(idx) - 1; } else { diff --git a/modules/base/rendering/renderableplanetimevaryingimage.h b/modules/base/rendering/renderableplanetimevaryingimage.h index adb667868b..8afde80dc2 100644 --- a/modules/base/rendering/renderableplanetimevaryingimage.h +++ b/modules/base/rendering/renderableplanetimevaryingimage.h @@ -57,7 +57,7 @@ private: ghoul::opengl::Texture* loadTexture() const; void extractTriggerTimesFromFileNames(); bool extractMandatoryInfoFromDictionary(); - int updateActiveTriggerTimeIndex(double currenttime) const; + int updateActiveTriggerTimeIndex(double currentTime) const; void computeSequenceEndTime(); // If there's just one state it should never disappear diff --git a/modules/base/rendering/renderableprism.cpp b/modules/base/rendering/renderableprism.cpp index 1f1b63b4e4..9bac9b2a3d 100644 --- a/modules/base/rendering/renderableprism.cpp +++ b/modules/base/rendering/renderableprism.cpp @@ -230,9 +230,9 @@ void RenderablePrism::updateVertexData() { std::vector unitVerticesLines = createRingXYZ(_nLines.value(), 1.f); // Put base vertices into array - for (int j = 0; j < _nShapeSegments; ++j) { - float ux = unitVertices[j].xyz[0]; - float uy = unitVertices[j].xyz[1]; + for (int j = 0; j < _nShapeSegments; j++) { + const float ux = unitVertices[j].xyz[0]; + const float uy = unitVertices[j].xyz[1]; _vertexArray.push_back(ux * _baseRadius); // x _vertexArray.push_back(uy * _baseRadius); // y @@ -240,9 +240,9 @@ void RenderablePrism::updateVertexData() { } // Put top shape vertices into array - for (int j = 0; j < _nShapeSegments; ++j) { - float ux = unitVertices[j].xyz[0]; - float uy = unitVertices[j].xyz[1]; + for (int j = 0; j < _nShapeSegments; j++) { + const float ux = unitVertices[j].xyz[0]; + const float uy = unitVertices[j].xyz[1]; _vertexArray.push_back(ux * _radius); // x _vertexArray.push_back(uy * _radius); // y @@ -263,9 +263,9 @@ void RenderablePrism::updateVertexData() { _vertexArray.push_back(_length); } else { - for (int j = 0; j < _nLines; ++j) { - float ux = unitVerticesLines[j].xyz[0]; - float uy = unitVerticesLines[j].xyz[1]; + for (int j = 0; j < _nLines; j++) { + const float ux = unitVerticesLines[j].xyz[0]; + const float uy = unitVerticesLines[j].xyz[1]; // Base _vertexArray.push_back(ux * _baseRadius); // x @@ -284,7 +284,7 @@ void RenderablePrism::updateVertexData() { _nShapeSegments.value() <= std::numeric_limits::max(), "Too many shape segments" ); - for (uint8_t i = 0; i < _nShapeSegments; ++i) { + for (uint8_t i = 0; i < _nShapeSegments; i++) { _indexArray.push_back(i); } @@ -292,12 +292,12 @@ void RenderablePrism::updateVertexData() { _indexArray.push_back(255); // Indices for Top shape - for (int i = _nShapeSegments; i < 2 * _nShapeSegments; ++i) { + for (int i = _nShapeSegments; i < 2 * _nShapeSegments; i++) { _indexArray.push_back(static_cast(i)); } // Indices for connecting lines - for (int i = 0, k = 0; i < _nLines; ++i, k += 2) { + for (int i = 0, k = 0; i < _nLines; i++, k += 2) { // Reset _indexArray.push_back(255); diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index fba2b8627f..ac8b2db74b 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -233,7 +233,7 @@ void RenderableSphere::deinitializeGL() { } void RenderableSphere::render(const RenderData& data, RendererTasks&) { - Orientation orientation = static_cast(_orientation.value()); + const Orientation orientation = static_cast(_orientation.value()); // Activate shader using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; @@ -242,7 +242,7 @@ void RenderableSphere::render(const RenderData& data, RendererTasks&) { auto [modelTransform, modelViewTransform, modelViewProjectionTransform] = calcAllTransforms(data); - glm::dmat3 modelRotation = glm::dmat3(data.modelTransform.rotation); + const glm::dmat3 modelRotation = glm::dmat3(data.modelTransform.rotation); _shader->setUniform(_uniformCache.modelViewTransform, glm::mat4(modelViewTransform)); _shader->setUniform( @@ -250,7 +250,7 @@ void RenderableSphere::render(const RenderData& data, RendererTasks&) { glm::mat4(modelViewProjectionTransform) ); - glm::mat3 modelViewRotation = glm::mat3( + const glm::mat3 modelViewRotation = glm::mat3( glm::dmat3(data.camera.viewRotationMatrix()) * modelRotation ); _shader->setUniform(_uniformCache.modelViewRotation, modelViewRotation); diff --git a/modules/base/rendering/renderablesphereimagelocal.cpp b/modules/base/rendering/renderablesphereimagelocal.cpp index 92b9441935..7740aa4ab0 100644 --- a/modules/base/rendering/renderablesphereimagelocal.cpp +++ b/modules/base/rendering/renderablesphereimagelocal.cpp @@ -117,14 +117,14 @@ void RenderableSphereImageLocal::loadTexture() { if (!texture) { LWARNINGC( "RenderableSphereImageLocal", - fmt::format("Could not load texture from {}", absPath(_texturePath)) + std::format("Could not load texture from '{}'", absPath(_texturePath)) ); return; } LDEBUGC( "RenderableSphereImageLocal", - fmt::format("Loaded texture from {}", absPath(_texturePath)) + std::format("Loaded texture from '{}'", absPath(_texturePath)) ); texture->uploadTexture(); texture->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); diff --git a/modules/base/rendering/renderablesphereimageonline.cpp b/modules/base/rendering/renderablesphereimageonline.cpp index b1d64dc0ec..bf2757bdc1 100644 --- a/modules/base/rendering/renderablesphereimageonline.cpp +++ b/modules/base/rendering/renderablesphereimageonline.cpp @@ -43,6 +43,28 @@ namespace { openspace::properties::Property::Visibility::User }; + std::future downloadImageToMemory( + const std::string& url) + { + using namespace openspace; + + return global::downloadManager->fetchFile( + url, + [url](const DownloadManager::MemoryFile&) { + LDEBUGC( + "RenderableSphereImageOnline", + std::format("Download to memory finished for image '{}'", url) + ); + }, + [url](const std::string& err) { + LDEBUGC( + "RenderableSphereImageOnline", + std::format("Download to memory failed for image '{}': {}", url, err) + ); + } + ); + } + struct [[codegen::Dictionary(RenderableSphere)]] Parameters { // [[codegen::verbatim(TextureInfo.description)]] std::string url [[codegen::key("URL")]]; @@ -93,12 +115,12 @@ void RenderableSphereImageOnline::update(const UpdateData& data) { } if (_imageFuture.valid() && DownloadManager::futureReady(_imageFuture)) { - DownloadManager::MemoryFile imageFile = _imageFuture.get(); + const DownloadManager::MemoryFile imageFile = _imageFuture.get(); if (imageFile.corrupted) { LERRORC( "RenderableSphereImageOnline", - fmt::format("Error loading image from URL '{}'", _textureUrl.value()) + std::format("Error loading image from URL '{}'", _textureUrl.value()) ); return; } @@ -141,24 +163,4 @@ void RenderableSphereImageOnline::bindTexture() { } } -std::future -RenderableSphereImageOnline::downloadImageToMemory(const std::string& url) -{ - return global::downloadManager->fetchFile( - url, - [url](const DownloadManager::MemoryFile&) { - LDEBUGC( - "RenderableSphereImageOnline", - fmt::format("Download to memory finished for image '{}'", url) - ); - }, - [url](const std::string& err) { - LDEBUGC( - "RenderableSphereImageOnline", - fmt::format("Download to memory failed for image '{}': {}", url, err) - ); - } - ); -} - } // namespace openspace diff --git a/modules/base/rendering/renderablesphereimageonline.h b/modules/base/rendering/renderablesphereimageonline.h index ed256d0719..c98102e39b 100644 --- a/modules/base/rendering/renderablesphereimageonline.h +++ b/modules/base/rendering/renderablesphereimageonline.h @@ -52,9 +52,6 @@ protected: void bindTexture() override; private: - std::future downloadImageToMemory( - const std::string& url); - properties::StringProperty _textureUrl; std::future _imageFuture; diff --git a/modules/base/rendering/renderabletimevaryingsphere.cpp b/modules/base/rendering/renderabletimevaryingsphere.cpp index 8cde614fad..affa8e718d 100644 --- a/modules/base/rendering/renderabletimevaryingsphere.cpp +++ b/modules/base/rendering/renderabletimevaryingsphere.cpp @@ -105,7 +105,7 @@ void RenderableTimeVaryingSphere::extractMandatoryInfoFromSourceFolder() { // Ensure that the source folder exists and then extract // the files with the same extension as namespace fs = std::filesystem; - fs::path sourceFolder = absPath(_textureSourcePath); + const fs::path sourceFolder = absPath(_textureSourcePath); if (!std::filesystem::is_directory(sourceFolder)) { throw ghoul::RuntimeError( "Source folder for RenderableTimeVaryingSphere is not a valid directory" @@ -118,8 +118,8 @@ void RenderableTimeVaryingSphere::extractMandatoryInfoFromSourceFolder() { if (!e.is_regular_file()) { continue; } - std::string filePath = e.path().string(); - double time = extractTriggerTimeFromFileName(filePath); + const std::string filePath = e.path().string(); + const double time = extractTriggerTimeFromFileName(filePath); std::unique_ptr t = ghoul::io::TextureReader::ref().loadTexture(filePath, 2); @@ -194,7 +194,7 @@ void RenderableTimeVaryingSphere::updateActiveTriggerTimeIndex(double currentTim ); if (iter != _files.end()) { if (iter != _files.begin()) { - ptrdiff_t idx = std::distance(_files.begin(), iter); + const ptrdiff_t idx = std::distance(_files.begin(), iter); _activeTriggerTimeIndex = static_cast(idx - 1); } else { diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index f8a65ad83d..bc4c69ac27 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -291,7 +291,7 @@ void RenderableTrail::internalRender(bool renderLines, bool renderPoints, // We pass in the model view transformation matrix as double in order to maintain // high precision for vertices; especially for the trails, a high vertex precision // is necessary as they are usually far away from their reference - glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform); + const glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform); _programObject->setUniform( _uniformCache.modelView, modelViewTransform * info._localTransform @@ -317,8 +317,8 @@ void RenderableTrail::internalRender(bool renderLines, bool renderPoints, _programObject->setUniform(_uniformCache.nVertices, nVertices); #if !defined(__APPLE__) - GLint viewport[4]; - global::renderEngine->openglStateCache().viewport(viewport); + std::array viewport; + global::renderEngine->openglStateCache().viewport(viewport.data()); _programObject->setUniform( _uniformCache.viewport, static_cast(viewport[0]), @@ -392,7 +392,7 @@ void RenderableTrail::render(const RenderData& data, RendererTasks&) { _programObject->activate(); _programObject->setUniform(_uniformCache.opacity, opacity()); - glm::dmat4 modelTransform = calcModelTransform(data); + const glm::dmat4 modelTransform = calcModelTransform(data); _programObject->setUniform(_uniformCache.projection, data.camera.projectionMatrix()); @@ -418,7 +418,7 @@ void RenderableTrail::render(const RenderData& data, RendererTasks&) { #ifdef __APPLE__ glLineWidth(1); #else - glLineWidth(ceil((2.f * 1.f + _appearance.lineWidth) * std::sqrt(2.f))); + glLineWidth(std::ceil((2.f * 1.f + _appearance.lineWidth) * std::sqrt(2.f))); #endif } if (renderPoints) { diff --git a/modules/base/rendering/renderabletrailorbit.cpp b/modules/base/rendering/renderabletrailorbit.cpp index 81db88850c..58b8dd168a 100644 --- a/modules/base/rendering/renderabletrailorbit.cpp +++ b/modules/base/rendering/renderabletrailorbit.cpp @@ -354,7 +354,7 @@ RenderableTrailOrbit::UpdateReport RenderableTrailOrbit::updateTrails( } using namespace std::chrono; - double periodSeconds = _period * duration_cast(hours(24)).count(); + const double periodSeconds = _period * duration_cast(hours(24)).count(); const double secondsPerPoint = periodSeconds / (_resolution - 1); // How much time has passed since the last permanent point const double delta = data.time.j2000Seconds() - _lastPointTime; @@ -387,7 +387,7 @@ RenderableTrailOrbit::UpdateReport RenderableTrailOrbit::updateTrails( return { false, true, UpdateReport::All }; } - for (int i = 0; i < nNewPoints; ++i) { + for (int i = 0; i < nNewPoints; i++) { _lastPointTime += secondsPerPoint; // Get the new permanent point and write it into the (previously) floating @@ -427,7 +427,7 @@ RenderableTrailOrbit::UpdateReport RenderableTrailOrbit::updateTrails( return { false, true, UpdateReport::All }; } - for (int i = 0; i < nNewPoints; ++i) { + for (int i = 0; i < nNewPoints; i++) { _firstPointTime -= secondsPerPoint; // Get the new permanent point and write it into the (previously) floating @@ -478,7 +478,7 @@ void RenderableTrailOrbit::fullSweep(double time) { const double periodSeconds = _period * duration_cast(hours(24)).count(); const double secondsPerPoint = periodSeconds / (_resolution - 1); // starting at 1 because the first position is a floating current one - for (int i = 1; i < _resolution; ++i) { + for (int i = 1; i < _resolution; i++) { const glm::vec3 p = _translation->position({ {}, Time(time), Time(0.0) }); _vertexArray[i] = { p.x, p.y, p.z }; diff --git a/modules/base/rendering/renderabletrailtrajectory.cpp b/modules/base/rendering/renderabletrailtrajectory.cpp index 4021811678..fe694d2fac 100644 --- a/modules/base/rendering/renderabletrailtrajectory.cpp +++ b/modules/base/rendering/renderabletrailtrajectory.cpp @@ -211,7 +211,7 @@ void RenderableTrailTrajectory::update(const UpdateData& data) { // Convert the start and end time from string representations to J2000 seconds _start = SpiceManager::ref().ephemerisTimeFromDate(_startTime); _end = SpiceManager::ref().ephemerisTimeFromDate(_endTime); - double timespan = _end - _start; + const double timespan = _end - _start; _totalSampleInterval = _sampleInterval / _timeStampSubsamplingFactor; @@ -234,12 +234,12 @@ void RenderableTrailTrajectory::update(const UpdateData& data) { } // Calculate sweeping range for this iteration - unsigned int startIndex = _sweepIteration * _sweepChunkSize; - unsigned int nextIndex = (_sweepIteration + 1) * _sweepChunkSize; - unsigned int stopIndex = std::min(nextIndex, _numberOfVertices); + const unsigned int startIndex = _sweepIteration * _sweepChunkSize; + const unsigned int nextIndex = (_sweepIteration + 1) * _sweepChunkSize; + const unsigned int stopIndex = std::min(nextIndex, _numberOfVertices); // Calculate all vertex positions - for (unsigned int i = startIndex; i < stopIndex; ++i) { + for (unsigned int i = startIndex; i < stopIndex; i++) { const glm::vec3 p = _translation->position({ {}, Time(_start + i * _totalSampleInterval), @@ -331,7 +331,7 @@ void RenderableTrailTrajectory::update(const UpdateData& data) { ghoul_assert(_primaryRenderInformation.count > 0, "No vertices available"); // Copy the last valid location - glm::dvec3 v0( + const glm::dvec3 v0 = glm::dvec3( _vertexArray[_primaryRenderInformation.count - 1].x, _vertexArray[_primaryRenderInformation.count - 1].y, _vertexArray[_primaryRenderInformation.count - 1].z @@ -339,7 +339,7 @@ void RenderableTrailTrajectory::update(const UpdateData& data) { // And get the current location of the object const glm::dvec3 p = _translation->position(data); - const glm::dvec3 v1 = { p.x, p.y, p.z }; + const glm::dvec3 v1 = glm::dvec3(p.x, p.y, p.z); // Comptue the difference between the points in double precision const glm::dvec3 p0 = v0 - v1; diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index e34166e976..81380c5ede 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -80,7 +80,7 @@ ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictiona setGuiName("ScreenSpaceFramebuffer " + std::to_string(iIdentifier)); } - glm::vec2 resolution = global::windowDelegate->currentDrawBufferResolution(); + const glm::vec2 resolution = global::windowDelegate->currentDrawBufferResolution(); addProperty(_size); _size = glm::vec4(0.f, 0.f, resolution.x, resolution.y); } @@ -113,18 +113,18 @@ void ScreenSpaceFramebuffer::render(float blackoutFactor) { const float yratio = resolution.y / (size.w - size.y); if (!_renderFunctions.empty()) { - GLint viewport[4]; + std::array viewport; //glGetIntegerv(GL_VIEWPORT, viewport); - global::renderEngine->openglStateCache().viewport(viewport); + global::renderEngine->openglStateCache().viewport(viewport.data()); glViewport( static_cast(-size.x * xratio), static_cast(-size.y * yratio), static_cast(resolution.x * xratio), static_cast(resolution.y * yratio) ); - global::renderEngine->openglStateCache().setViewportState(viewport); + global::renderEngine->openglStateCache().setViewportState(viewport.data()); - GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); + const GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); _framebuffer->activate(); glClearColor(0.f, 0.f, 0.f, 0.f); @@ -173,7 +173,7 @@ void ScreenSpaceFramebuffer::removeAllRenderFunctions() { } void ScreenSpaceFramebuffer::createFramebuffer() { - glm::vec2 resolution = global::windowDelegate->currentDrawBufferResolution(); + const glm::vec2 resolution = global::windowDelegate->currentDrawBufferResolution(); _framebuffer = std::make_unique(); _framebuffer->activate(); diff --git a/modules/base/rendering/screenspaceimagelocal.cpp b/modules/base/rendering/screenspaceimagelocal.cpp index bda85bc416..504f6db33f 100644 --- a/modules/base/rendering/screenspaceimagelocal.cpp +++ b/modules/base/rendering/screenspaceimagelocal.cpp @@ -85,8 +85,8 @@ ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary if (!std::filesystem::is_regular_file(absPath(_texturePath))) { LWARNINGC( "ScreenSpaceImageLocal", - fmt::format( - "Image {} did not exist for {}", _texturePath.value(), _identifier + std::format( + "Image '{}' did not exist for '{}'", _texturePath.value(), _identifier ) ); } @@ -103,7 +103,9 @@ ScreenSpaceImageLocal::ScreenSpaceImageLocal(const ghoul::Dictionary& dictionary else { LWARNINGC( "ScreenSpaceImageLocal", - fmt::format("Image {} did not exist for {}", *p.texturePath, _identifier) + std::format( + "Image '{}' did not exist for '{}'", *p.texturePath, _identifier + ) ); } } diff --git a/modules/base/rendering/screenspaceimageonline.cpp b/modules/base/rendering/screenspaceimageonline.cpp index a972aca94d..a7b6ac55dc 100644 --- a/modules/base/rendering/screenspaceimageonline.cpp +++ b/modules/base/rendering/screenspaceimageonline.cpp @@ -105,12 +105,12 @@ void ScreenSpaceImageOnline::update() { } if (_imageFuture.valid() && DownloadManager::futureReady(_imageFuture)) { - DownloadManager::MemoryFile imageFile = _imageFuture.get(); + const DownloadManager::MemoryFile imageFile = _imageFuture.get(); if (imageFile.corrupted) { LERRORC( "ScreenSpaceImageOnline", - fmt::format("Error loading image from URL '{}'", _texturePath.value()) + std::format("Error loading image from URL '{}'", _texturePath.value()) ); return; } diff --git a/modules/base/rotation/constantrotation.cpp b/modules/base/rotation/constantrotation.cpp index 9a33d17c59..fb965c088c 100644 --- a/modules/base/rotation/constantrotation.cpp +++ b/modules/base/rotation/constantrotation.cpp @@ -102,7 +102,7 @@ glm::dmat3 ConstantRotation::matrix(const UpdateData& data) const { _accumulatedRotation += glm::tau(); } - glm::dquat q = glm::angleAxis(_accumulatedRotation, _rotationAxis.value()); + const glm::dquat q = glm::angleAxis(_accumulatedRotation, _rotationAxis.value()); return glm::toMat3(q); } diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp index fc083d8eca..a176e16cca 100644 --- a/modules/base/rotation/fixedrotation.cpp +++ b/modules/base/rotation/fixedrotation.cpp @@ -294,6 +294,7 @@ FixedRotation::FixedRotation(const ghoul::Dictionary& dictionary) nullptr } , _attachedObject(AttachedInfo, "") + , _constructorDictionary(dictionary) { // We check the Dictionary here in order to detect the errors early codegen::bake(dictionary); @@ -304,8 +305,6 @@ FixedRotation::FixedRotation(const ghoul::Dictionary& dictionary) "FixedRotation" ); - _constructorDictionary = dictionary; - setPropertyGroupName("global", "Global"); setPropertyGroupName("xAxis", "X Axis"); setPropertyGroupName("yAxis", "Y Axis"); @@ -501,7 +500,7 @@ bool FixedRotation::initialize() { } void FixedRotation::update(const UpdateData& data) { - bool anyAxisIsObjectType = ( + const bool anyAxisIsObjectType = ( _xAxis.type == Axis::Type::Object || _yAxis.type == Axis::Type::Object || _zAxis.type == Axis::Type::Object @@ -531,7 +530,7 @@ glm::dmat3 FixedRotation::matrix(const UpdateData&) const { { LWARNINGC( "FixedRotation", - fmt::format( + std::format( "Near-collinear vectors detected: " "x ({}, {}, {}) y ({}, {}, {}) z ({}, {}, {})", x.x, x.y, x.z, y.x, y.y, y.z, z.x, z.y, z.z @@ -561,7 +560,7 @@ glm::vec3 FixedRotation::xAxis() const { if (dir == glm::dvec3(0.0)) { dir = glm::dvec3(1.0, 0.0, 0.0); } - glm::vec3 dirNorm = glm::vec3(glm::normalize(dir)); + const glm::vec3 dirNorm = glm::vec3(glm::normalize(dir)); return _xAxis.invertObject ? -dirNorm : dirNorm; } else { @@ -613,7 +612,7 @@ glm::vec3 FixedRotation::yAxis() const { return glm::vec3(0.f, 1.f, 0.f); case Axis::Type::Object: if (_yAxis.node && _attachedNode) { - glm::vec3 dir = glm::vec3(glm::normalize( + const glm::vec3 dir = glm::vec3(glm::normalize( // @TODO(abock): This should be changed to be in the coordinate system // of the attached node // same with xAxis and zAxis ofc _yAxis.node->worldPosition() - _attachedNode->worldPosition() @@ -669,7 +668,7 @@ glm::vec3 FixedRotation::zAxis() const { return glm::vec3(0.f, 0.f, 1.f); case Axis::Type::Object: if (_zAxis.node && _attachedNode) { - glm::vec3 dir = glm::vec3(glm::normalize( + const glm::vec3 dir = glm::vec3(glm::normalize( _zAxis.node->worldPosition() - _attachedNode->worldPosition() )); return _zAxis.invertObject ? -dir : dir; diff --git a/modules/base/rotation/luarotation.cpp b/modules/base/rotation/luarotation.cpp index 648475cb6f..b7937c1eac 100644 --- a/modules/base/rotation/luarotation.cpp +++ b/modules/base/rotation/luarotation.cpp @@ -89,7 +89,7 @@ glm::dmat3 LuaRotation::matrix(const UpdateData& data) const { if (!isFunction) { LERRORC( "LuaRotation", - fmt::format( + std::format( "Script '{}' does not have a function 'rotation'", _luaScriptFile.value() ) ); @@ -108,20 +108,20 @@ glm::dmat3 LuaRotation::matrix(const UpdateData& data) const { ghoul::lua::push(_state, duration_cast(now.time_since_epoch()).count()); // Execute the scaling function - int success = lua_pcall(_state, 2, 9, 0); + const int success = lua_pcall(_state, 2, 9, 0); if (success != 0) { LERRORC( "LuaScale", - fmt::format("Error executing 'rotation': {}", lua_tostring(_state, -1)) + std::format("Error executing 'rotation': {}", lua_tostring(_state, -1)) ); } - double values[9]; - for (int i = 0; i < 9; ++i) { + std::array values; + for (int i = 0; i < 9; i++) { values[i] = luaL_checknumber(_state, -1 - i); } - return glm::make_mat3(values); + return glm::make_mat3(values.data()); } } // namespace openspace diff --git a/modules/base/rotation/staticrotation.cpp b/modules/base/rotation/staticrotation.cpp index fbe008f3ce..bf4ed3a55d 100644 --- a/modules/base/rotation/staticrotation.cpp +++ b/modules/base/rotation/staticrotation.cpp @@ -42,7 +42,7 @@ namespace { // Inspired by: https://www.learnopencv.com/rotation-matrix-to-euler-angles/ glm::dvec3 rotationMatrixToEulerAngles(glm::dmat4 mat) { const double sy = glm::sqrt(mat[0][0] * mat[0][0] + mat[0][1] * mat[0][1]); - bool singular = sy < 1e-6; + const bool singular = (sy < 1e-6); glm::dvec3 res; if (singular) { @@ -95,7 +95,7 @@ StaticRotation::StaticRotation(const ghoul::Dictionary& dictionary) : StaticRota _eulerRotation = std::get(p.rotation); } else if (std::holds_alternative(p.rotation)) { - glm::dvec4 data = std::get(p.rotation); + const glm::dvec4 data = std::get(p.rotation); _eulerRotation = rotationMatrixToEulerAngles( glm::mat3_cast(glm::dquat(data.w, data.x, data.y, data.z)) ); diff --git a/modules/base/scale/luascale.cpp b/modules/base/scale/luascale.cpp index 466467db4d..5a0e994fd6 100644 --- a/modules/base/scale/luascale.cpp +++ b/modules/base/scale/luascale.cpp @@ -87,7 +87,7 @@ glm::dvec3 LuaScale::scaleValue(const UpdateData& data) const { if (!isFunction) { LERRORC( "LuaScale", - fmt::format( + std::format( "Script '{}' does not have a function 'scale'", _luaScriptFile.value() ) ); @@ -110,7 +110,7 @@ glm::dvec3 LuaScale::scaleValue(const UpdateData& data) const { if (success != 0) { LERRORC( "LuaScale", - fmt::format("Error executing 'scale': {}", lua_tostring(_state, -1)) + std::format("Error executing 'scale': {}", lua_tostring(_state, -1)) ); } diff --git a/modules/base/shaders/model_fs.glsl b/modules/base/shaders/model_fs.glsl index 79f6f9dc69..c15de3dc49 100644 --- a/modules/base/shaders/model_fs.glsl +++ b/modules/base/shaders/model_fs.glsl @@ -139,7 +139,7 @@ Fragment getFragment() { vec3 viewDirection = normalize(vs_positionCameraSpace.xyz); - for (int i = 0; i < nLightSources; ++i) { + for (int i = 0; i < nLightSources; i++) { // Diffuse light vec3 lightDirection = lightDirectionsViewSpace[i]; float diffuseFactor = max(dot(normal, lightDirection), 0.0); diff --git a/modules/base/shaders/pointcloud/billboardpoint_fs.glsl b/modules/base/shaders/pointcloud/billboardpoint_fs.glsl index 629d1ff7a3..3e69bd8913 100644 --- a/modules/base/shaders/pointcloud/billboardpoint_fs.glsl +++ b/modules/base/shaders/pointcloud/billboardpoint_fs.glsl @@ -28,6 +28,7 @@ flat in float gs_colorParameter; flat in float vs_screenSpaceDepth; flat in vec4 vs_positionViewSpace; in vec2 texCoord; +flat in int layer; uniform float opacity; uniform vec3 color; @@ -42,7 +43,7 @@ uniform vec4 belowRangeColor; uniform bool useBelowRangeColor; uniform bool hasSpriteTexture; -uniform sampler2D spriteTexture; +uniform sampler2DArray spriteTexture; uniform bool useColorMap; uniform sampler1D colorMapTexture; @@ -85,23 +86,19 @@ Fragment getFragment() { // Moving the origin to the center and calculating the length float lengthFromCenter = length((texCoord - vec2(0.5)) * 2.0); - if (!hasSpriteTexture) { - if (lengthFromCenter > 1.0) { - discard; - } + if (!hasSpriteTexture && (lengthFromCenter > 1.0)) { + discard; } - vec4 fullColor = vec4(1.0); + vec4 fullColor = glm::vec4(color, 1.0); if (useColorMap) { fullColor = sampleColorMap(gs_colorParameter); } - else { - fullColor.rgb = color; - } if (hasSpriteTexture) { - fullColor *= texture(spriteTexture, texCoord); - } else if (enableOutline && (lengthFromCenter > (1.0 - outlineWeight))) { + fullColor *= texture(spriteTexture, vec3(texCoord, layer)); + } + else if (enableOutline && (lengthFromCenter > (1.0 - outlineWeight))) { fullColor.rgb = outlineColor; } diff --git a/modules/base/shaders/pointcloud/billboardpoint_gs.glsl b/modules/base/shaders/pointcloud/billboardpoint_gs.glsl index 87f9d5eca3..a3114b8dd9 100644 --- a/modules/base/shaders/pointcloud/billboardpoint_gs.glsl +++ b/modules/base/shaders/pointcloud/billboardpoint_gs.glsl @@ -27,12 +27,14 @@ #include "PowerScaling/powerScalingMath.hglsl" layout(points) in; +flat in float textureLayer[]; flat in float colorParameter[]; flat in float scalingParameter[]; layout(triangle_strip, max_vertices = 4) out; flat out float gs_colorParameter; out vec2 texCoord; +flat out int layer; flat out float vs_screenSpaceDepth; flat out vec4 vs_positionViewSpace; @@ -45,6 +47,7 @@ uniform dmat4 projectionMatrix; uniform dmat4 modelMatrix; uniform bool enableMaxSizeControl; uniform bool hasDvarScaling; +uniform float dvarScaleFactor; // RenderOption: CameraViewDirection uniform vec3 up; @@ -58,6 +61,8 @@ uniform vec3 cameraLookUp; // The max size is an angle, in degrees, for the diameter uniform float maxAngularSize; +uniform vec2 aspectRatioScale; + const vec2 corners[4] = vec2[4]( vec2(0.0, 0.0), vec2(1.0, 0.0), @@ -70,13 +75,14 @@ const int RenderOptionCameraPositionNormal = 1; void main() { vec4 pos = gl_in[0].gl_Position; + layer = int(textureLayer[0]); gs_colorParameter = colorParameter[0]; dvec4 dpos = modelMatrix * dvec4(dvec3(pos.xyz), 1.0); float scaleMultiply = pow(10.0, scaleExponent); if (hasDvarScaling) { - scaleMultiply *= scalingParameter[0]; + scaleMultiply *= scalingParameter[0] * dvarScaleFactor; } vec3 scaledRight = vec3(0.0); @@ -116,9 +122,9 @@ void main() { dmat4 cameraViewProjectionMatrix = projectionMatrix * cameraViewMatrix; vec4 dposClip = vec4(cameraViewProjectionMatrix * dpos); - vec4 scaledRightClip = scaleFactor * + vec4 scaledRightClip = scaleFactor * aspectRatioScale.x * vec4(cameraViewProjectionMatrix * dvec4(scaledRight, 0.0)); - vec4 scaledUpClip = scaleFactor * + vec4 scaledUpClip = scaleFactor * aspectRatioScale.y * vec4(cameraViewProjectionMatrix * dvec4(scaledUp, 0.0)); vec4 dposViewSpace= vec4(cameraViewMatrix * dpos); diff --git a/modules/base/shaders/pointcloud/billboardpoint_interpolated_vs.glsl b/modules/base/shaders/pointcloud/billboardpoint_interpolated_vs.glsl index 88b558620a..a6a3407f2e 100644 --- a/modules/base/shaders/pointcloud/billboardpoint_interpolated_vs.glsl +++ b/modules/base/shaders/pointcloud/billboardpoint_interpolated_vs.glsl @@ -38,9 +38,12 @@ in float in_colorParameter1; in float in_scalingParameter0; in float in_scalingParameter1; +in float in_textureLayer; + uniform bool useSpline; uniform float interpolationValue; +flat out float textureLayer; flat out float colorParameter; flat out float scalingParameter; @@ -87,5 +90,7 @@ void main() { ); } + textureLayer = in_textureLayer; + gl_Position = vec4(position, 1.0); } diff --git a/modules/base/shaders/pointcloud/billboardpoint_vs.glsl b/modules/base/shaders/pointcloud/billboardpoint_vs.glsl index 476a994e11..2a1e661ba5 100644 --- a/modules/base/shaders/pointcloud/billboardpoint_vs.glsl +++ b/modules/base/shaders/pointcloud/billboardpoint_vs.glsl @@ -27,13 +27,16 @@ #include "PowerScaling/powerScaling_vs.hglsl" in vec3 in_position; +in float in_textureLayer; in float in_colorParameter; in float in_scalingParameter; +flat out float textureLayer; flat out float colorParameter; flat out float scalingParameter; void main() { + textureLayer = in_textureLayer; colorParameter = in_colorParameter; scalingParameter = in_scalingParameter; gl_Position = vec4(in_position, 1.0); diff --git a/modules/base/shaders/polygon_fs.glsl b/modules/base/shaders/polygon_fs.glsl index 495bdc6232..7f44e3fd7d 100644 --- a/modules/base/shaders/polygon_fs.glsl +++ b/modules/base/shaders/polygon_fs.glsl @@ -26,9 +26,6 @@ out vec4 finalColor; -uniform vec3 polygonColor; - - void main() { - finalColor = vec4(polygonColor, 1.0); + finalColor = vec4(1.0); } diff --git a/modules/base/timeframe/timeframeunion.cpp b/modules/base/timeframe/timeframeunion.cpp index 367155a8e9..de9335ab76 100644 --- a/modules/base/timeframe/timeframeunion.cpp +++ b/modules/base/timeframe/timeframeunion.cpp @@ -63,18 +63,16 @@ bool TimeFrameUnion::isActive(const Time& time) const { return false; } -TimeFrameUnion::TimeFrameUnion(const ghoul::Dictionary& dictionary) - : TimeFrame() -{ +TimeFrameUnion::TimeFrameUnion(const ghoul::Dictionary& dictionary) { // I don't know how we can actually help the reference attribute properly. Since the // Parameter list only contains the monostate, there is no need to actually create // the object here codegen::bake(dictionary); - ghoul::Dictionary frames = + const ghoul::Dictionary frames = dictionary.value(TimeFramesInfo.identifier); - for (std::string_view k : frames.keys()) { + for (const std::string_view k : frames.keys()) { const ghoul::Dictionary& subDictionary = frames.value(k); _timeFrames.push_back(TimeFrame::createFromDictionary(subDictionary)); TimeFrame& subFrame = *_timeFrames.back(); diff --git a/modules/base/translation/luatranslation.cpp b/modules/base/translation/luatranslation.cpp index c97424af4a..986135f156 100644 --- a/modules/base/translation/luatranslation.cpp +++ b/modules/base/translation/luatranslation.cpp @@ -91,7 +91,7 @@ glm::dvec3 LuaTranslation::position(const UpdateData& data) const { if (!isFunction) { LERRORC( "LuaScale", - fmt::format( + std::format( "Script '{}' does not have a function 'translation'", _luaScriptFile.value() ) @@ -115,16 +115,15 @@ glm::dvec3 LuaTranslation::position(const UpdateData& data) const { if (success != 0) { LERRORC( "LuaScale", - fmt::format("Error executing 'translation': {}", lua_tostring(_state, -1)) + std::format("Error executing 'translation': {}", lua_tostring(_state, -1)) ); } - double values[3]; - for (int i = 1; i <= 3; ++i) { + glm::vec3 values; + for (int i = 1; i <= 3; i++) { values[i - 1] = ghoul::lua::value(_state, i); } - - return glm::make_vec3(values); + return values; } } // namespace openspace diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index 3aab3b311f..944bde0782 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -102,7 +102,7 @@ void CefWebGuiModule::startOrStopGui() { const bool isMaster = global::windowDelegate->isMaster(); if (_enabled && isMaster) { - LDEBUGC("WebBrowser", fmt::format("Loading GUI from {}", _url.value())); + LDEBUGC("WebBrowser", std::format("Loading GUI from '{}'", _url.value())); if (!_instance) { _instance = std::make_unique( @@ -140,8 +140,7 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) WebBrowserModule* webBrowserModule = global::moduleEngine->module(); - bool available = webBrowserModule && webBrowserModule->isEnabled(); - + const bool available = webBrowserModule && webBrowserModule->isEnabled(); if (!available) { return; } @@ -232,7 +231,7 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) if (isGuiWindow && isMaster && _instance) { if (global::windowDelegate->windowHasResized() || _instance->_shouldReshape) { - glm::ivec2 csws = global::windowDelegate->guiWindowResolution(); + const glm::ivec2 csws = global::windowDelegate->guiWindowResolution(); _instance->reshape(static_cast( static_cast(csws) * global::windowDelegate->dpiScaling() )); diff --git a/modules/cefwebgui/src/guirenderhandler.cpp b/modules/cefwebgui/src/guirenderhandler.cpp index e13f66c8d1..4853fcc30a 100644 --- a/modules/cefwebgui/src/guirenderhandler.cpp +++ b/modules/cefwebgui/src/guirenderhandler.cpp @@ -43,11 +43,11 @@ GUIRenderHandler::GUIRenderHandler() { absPath("${MODULE_CEFWEBGUI}/shaders/gui_vs.glsl"), absPath("${MODULE_CEFWEBGUI}/shaders/gui_fs.glsl") ); - float data[] = { - -1.0f, -1.0f, -1.0f, - 1.0f, 1.0f, -1.0f, - 1.0f, -1.0f, -1.0f, - 1.0f, 1.0f, 1.0f + constexpr std::array Vtx = { + -1.f, -1.f, -1.f, + 1.f, 1.f, -1.f, + 1.f, -1.f, -1.f, + 1.f, 1.f, 1.f }; glGenVertexArrays(1, &_vao); @@ -55,7 +55,7 @@ GUIRenderHandler::GUIRenderHandler() { glGenBuffers(1, &_vbo); glGenTextures(1, &_texture); glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, Vtx.size() * sizeof(float), Vtx.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); diff --git a/modules/debugging/debuggingmodule_lua.inl b/modules/debugging/debuggingmodule_lua.inl index ac83715d8a..06d543cc1e 100644 --- a/modules/debugging/debuggingmodule_lua.inl +++ b/modules/debugging/debuggingmodule_lua.inl @@ -56,7 +56,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); // Parent node. Note that we only render one path at a time, so remove the previously // rendered one, if any - std::string addParentScript = fmt::format( + std::string addParentScript = std::format( "if openspace.hasSceneGraphNode('{0}') then " "openspace.removeSceneGraphNode('{0}') " "end " @@ -82,7 +82,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); // Create node lines between the positions auto pointIdentifier = [](int i) { - return fmt::format("Point_{}", i); + return std::format("Point_{}", i); }; auto addPoint = [](const std::string& id, glm::dvec3 p) { @@ -98,7 +98,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); "}"; global::scriptEngine->queueScript( - fmt::format("openspace.addSceneGraphNode({})", pointNode), + std::format("openspace.addSceneGraphNode({})", pointNode), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -108,7 +108,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); const glm::vec3& color, float lineWidth) { const std::string lineNode = "{" - "Identifier = '" + fmt::format("Line{}", id1) + "'," + "Identifier = '" + std::format("Line{}", id1) + "'," "Parent = '" + RenderedPathIdentifier + "'," "Renderable = {" "Enabled = true," @@ -121,7 +121,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); "}"; global::scriptEngine->queueScript( - fmt::format("openspace.addSceneGraphNode({})", lineNode), + std::format("openspace.addSceneGraphNode({})", lineNode), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -133,7 +133,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); { const glm::dvec3 dir = glm::normalize(p.rotation * glm::dvec3(0.0, 0.0, -1.0)); const glm::dvec3 pointPosition = p.position + lineLength * dir; - const std::string id = fmt::format("{}_orientation", pointId); + const std::string id = std::format("{}_orientation", pointId); addPoint(id, pointPosition); addLineBetweenPoints(id, pointId, OrientationLineColor, 2.f); @@ -159,7 +159,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); [[codegen::luawrap]] void removeRenderedCameraPath() { using namespace openspace; global::scriptEngine->queueScript( - fmt::format("openspace.removeSceneGraphNode('{}');", RenderedPathIdentifier), + std::format("openspace.removeSceneGraphNode('{}');", RenderedPathIdentifier), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -183,7 +183,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); // Parent node. Note that we only render one set of points at a time, so remove any // previously rendered ones - std::string addParentScript = fmt::format( + std::string addParentScript = std::format( "if openspace.hasSceneGraphNode('{0}') then " "openspace.removeSceneGraphNode('{0}') " "end " @@ -200,7 +200,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); const std::vector points = currentPath->controlPoints(); const std::string guiPath = - fmt::format("{}/Camera Path Control Points", DebuggingGuiPath); + std::format("{}/Camera Path Control Points", DebuggingGuiPath); const char* colorTexturePath = "openspace.absPath(" "openspace.createSingleColorImage('point_color', { 0.0, 1.0, 0.0 })" @@ -230,7 +230,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); "}"; global::scriptEngine->queueScript( - fmt::format("openspace.addSceneGraphNode({})", node), + std::format("openspace.addSceneGraphNode({})", node), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -241,7 +241,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); [[codegen::luawrap]] void removePathControlPoints() { using namespace openspace; global::scriptEngine->queueScript( - fmt::format("openspace.removeSceneGraphNode('{}');", RenderedPointsIdentifier), + std::format("openspace.removeSceneGraphNode('{}');", RenderedPointsIdentifier), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -297,7 +297,7 @@ constexpr glm::vec3 OrientationLineColor = glm::vec3(0.0, 1.0, 1.0); "}"; global::scriptEngine->queueScript( - fmt::format("openspace.addSceneGraphNode({});", axes), + std::format("openspace.addSceneGraphNode({});", axes), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index 366682d8b2..6b48b6b2f3 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -73,12 +73,12 @@ void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum m } // Generate a vao, vertex array object (keeping track of pointers to vbo) - GLuint _vaoID; + GLuint _vaoID = 0; glGenVertexArrays(1, &_vaoID); ghoul_assert(_vaoID != 0, "Could not generate vertex arrays"); // Generate a vbo, vertex buffer object (storeing actual data) - GLuint _vertexBufferID; + GLuint _vertexBufferID = 0; glGenBuffers(1, &_vertexBufferID); ghoul_assert(_vertexBufferID != 0, "Could not create vertex buffer"); @@ -91,7 +91,7 @@ void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum m glBufferData( GL_ARRAY_BUFFER, clippingSpacePoints.size() * sizeof(clippingSpacePoints[0]), - &clippingSpacePoints[0], + clippingSpacePoints.data(), GL_STATIC_DRAW); diff --git a/modules/debugging/rendering/renderabledebugplane.cpp b/modules/debugging/rendering/renderabledebugplane.cpp index 541d1e6fff..906d21f5bc 100644 --- a/modules/debugging/rendering/renderabledebugplane.cpp +++ b/modules/debugging/rendering/renderabledebugplane.cpp @@ -227,7 +227,7 @@ void RenderableDebugPlane::createPlane() { // ============================ const GLfloat size = _size; - const GLfloat vertexData[] = { + const std::array vertexData = { // x y z w s t -size, -size, 0.f, 0.f, 0.f, 0.f, size, size, 0.f, 0.f, 1.f, 1.f, @@ -239,7 +239,7 @@ void RenderableDebugPlane::createPlane() { glBindVertexArray(_quad); // bind array glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer - glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glEnableVertexAttribArray(1); diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index 6037e07b95..4a81521c28 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -203,7 +203,6 @@ RenderableDUMeshes::RenderableDUMeshes(const ghoul::Dictionary& dictionary) addProperty(Fadeable::_opacity); _speckFile = absPath(p.file).string(); - _hasSpeckFile = true; _drawElements.onChange([this]() { _hasSpeckFile = !_hasSpeckFile; }); addProperty(_drawElements); @@ -255,7 +254,7 @@ RenderableDUMeshes::RenderableDUMeshes(const ghoul::Dictionary& dictionary) if (p.meshColor.has_value()) { std::vector ops = *p.meshColor; - for (size_t i = 0; i < ops.size(); ++i) { + for (size_t i = 0; i < ops.size(); i++) { _meshColorMap.insert({ static_cast(i) + 1, ops[i] }); } } @@ -267,7 +266,7 @@ bool RenderableDUMeshes::isReady() const { } void RenderableDUMeshes::initialize() { - bool success = loadData(); + const bool success = loadData(); if (!success) { throw ghoul::RuntimeError("Error loading data"); } @@ -304,7 +303,7 @@ void RenderableDUMeshes::initializeGL() { void RenderableDUMeshes::deinitializeGL() { for (const std::pair& pair : _renderingMeshesMap) { - for (int i = 0; i < pair.second.numU; ++i) { + for (int i = 0; i < pair.second.numU; i++) { glDeleteVertexArrays(1, &pair.second.vaoArray[i]); glDeleteBuffers(1, &pair.second.vboArray[i]); } @@ -336,7 +335,7 @@ void RenderableDUMeshes::renderMeshes(const RenderData&, for (const std::pair& pair : _renderingMeshesMap) { _program->setUniform(_uniformCache.color, _meshColorMap[pair.second.colorIndex]); - for (size_t i = 0; i < pair.second.vaoArray.size(); ++i) { + for (size_t i = 0; i < pair.second.vaoArray.size(); i++) { glBindVertexArray(pair.second.vaoArray[i]); switch (pair.second.style) { case Solid: @@ -368,22 +367,23 @@ void RenderableDUMeshes::renderLabels(const RenderData& data, const glm::vec3& orthoRight, const glm::vec3& orthoUp) { - float scale = static_cast(toMeter(_unit)); + const float scale = static_cast(toMeter(_unit)); - ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo; - labelInfo.orthoRight = orthoRight; - labelInfo.orthoUp = orthoUp; - labelInfo.minSize = _textMinMaxSize.value().x; - labelInfo.maxSize = _textMinMaxSize.value().y; - labelInfo.cameraPos = data.camera.positionVec3(); - labelInfo.cameraLookUp = data.camera.lookUpVectorWorldSpace(); - labelInfo.renderType = _renderOption; - labelInfo.mvpMatrix = modelViewProjectionMatrix; - labelInfo.scale = pow(10.f, _textSize); - labelInfo.enableDepth = true; - labelInfo.enableFalseDepth = false; + const ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo = { + .enableDepth = true, + .enableFalseDepth = false, + .scale = std::pow(10.f, _textSize), + .renderType = _renderOption, + .minSize = _textMinMaxSize.value().x, + .maxSize = _textMinMaxSize.value().y, + .mvpMatrix = modelViewProjectionMatrix, + .orthoRight = orthoRight, + .orthoUp = orthoUp, + .cameraPos = data.camera.positionVec3(), + .cameraLookUp = data.camera.lookUpVectorWorldSpace() + }; - glm::vec4 textColor = glm::vec4(glm::vec3(_textColor), _textOpacity); + const glm::vec4 textColor = glm::vec4(glm::vec3(_textColor), _textOpacity); for (const dataloader::Labelset::Entry& e : _labelset.entries) { glm::vec3 scaledPos(e.position); @@ -415,14 +415,14 @@ void RenderableDUMeshes::render(const RenderData& data, RendererTasks&) { const glm::dmat4 worldToModelTransform = glm::inverse(modelMatrix); glm::vec3 orthoRight = glm::normalize( - glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) + glm::vec3(worldToModelTransform * glm::vec4(right, 0.f)) ); if (orthoRight == glm::vec3(0.0)) { - glm::vec3 otherVector(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( - glm::vec3(worldToModelTransform * glm::vec4(right, 0.0)) + glm::vec3(worldToModelTransform * glm::vec4(right, 0.f)) ); } @@ -448,14 +448,14 @@ void RenderableDUMeshes::update(const UpdateData&) { bool RenderableDUMeshes::loadData() { bool success = false; if (_hasSpeckFile) { - LINFO(fmt::format("Loading Speck file {}", std::filesystem::path(_speckFile))); + LINFO(std::format("Loading Speck file '{}'", _speckFile)); success = readSpeckFile(); if (!success) { return false; } } - std::string labelFile = _labelFile; + const std::string labelFile = _labelFile; if (!labelFile.empty()) { _labelset = dataloader::label::loadFileWithCache(_labelFile); } @@ -466,9 +466,7 @@ bool RenderableDUMeshes::loadData() { bool RenderableDUMeshes::readSpeckFile() { std::ifstream file(_speckFile); if (!file.good()) { - LERROR(fmt::format( - "Failed to open Speck file {}", std::filesystem::path(_speckFile) - )); + LERROR(std::format("Failed to open Speck file '{}'", _speckFile)); return false; } @@ -498,7 +496,7 @@ bool RenderableDUMeshes::readSpeckFile() { continue; } - std::size_t found = line.find("mesh"); + const size_t found = line.find("mesh"); if (found == std::string::npos) { continue; } @@ -563,23 +561,23 @@ bool RenderableDUMeshes::readSpeckFile() { // Try to read three values for the position glm::vec3 pos; bool success = true; - for (int i = 0; i < 3; ++i) { - GLfloat value; + for (int i = 0; i < 3; i++) { + GLfloat value = 0.f; lineData >> value; - bool errorReading = lineData.rdstate() & std::ifstream::failbit; + const bool errorReading = lineData.rdstate() & std::ifstream::failbit; if (errorReading) { success = false; break; } - GLfloat scaledValue = value * scale; + const GLfloat scaledValue = value * scale; pos[i] = scaledValue; mesh.vertices.push_back(scaledValue); } if (!success) { - LERROR(fmt::format( - "Failed reading position on line {} of mesh {} in file: '{}'. " + LERROR(std::format( + "Failed reading position on line {} of mesh {} in file '{}'. " "Stopped reading mesh data", l, meshIndex, _speckFile )); break; @@ -592,7 +590,7 @@ bool RenderableDUMeshes::readSpeckFile() { // OLD CODE: // (2022-03-23, emmbr) None of our files included texture coordinates, // and if they would they would still not be used by the shader - //for (int i = 0; i < 7; ++i) { + //for (int i = 0; i < 7; i++) { // GLfloat value; // lineData >> value; // bool errorReading = lineData.rdstate() & std::ifstream::failbit; @@ -626,12 +624,12 @@ void RenderableDUMeshes::createMeshes() { LDEBUG("Creating planes"); for (std::pair& p : _renderingMeshesMap) { - for (int i = 0; i < p.second.numU; ++i) { - GLuint vao; + for (int i = 0; i < p.second.numU; i++) { + GLuint vao = 0; glGenVertexArrays(1, &vao); p.second.vaoArray.push_back(vao); - GLuint vbo; + GLuint vbo = 0; glGenBuffers(1, &vbo); p.second.vboArray.push_back(vbo); @@ -641,7 +639,7 @@ void RenderableDUMeshes::createMeshes() { glBufferData( GL_ARRAY_BUFFER, p.second.vertices.size() * sizeof(GLfloat), - &p.second.vertices[0], + p.second.vertices.data(), GL_STATIC_DRAW ); // in_position @@ -685,12 +683,12 @@ void RenderableDUMeshes::createMeshes() { // Grid: we need columns if (p.second.numU > 1) { - for (int i = 0; i < p.second.numV; ++i) { - GLuint cvao; + for (int i = 0; i < p.second.numV; i++) { + GLuint cvao = 0; glGenVertexArrays(1, &cvao); p.second.vaoArray.push_back(cvao); - GLuint cvbo; + GLuint cvbo = 0; glGenBuffers(1, &cvbo); p.second.vboArray.push_back(cvbo); @@ -699,7 +697,7 @@ void RenderableDUMeshes::createMeshes() { glBufferData( GL_ARRAY_BUFFER, p.second.vertices.size() * sizeof(GLfloat), - &p.second.vertices[0], + p.second.vertices.data(), GL_STATIC_DRAW ); // in_position diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.h b/modules/digitaluniverse/rendering/renderabledumeshes.h index 9204a87f51..d24962ffa9 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.h +++ b/modules/digitaluniverse/rendering/renderabledumeshes.h @@ -103,7 +103,7 @@ private: bool loadData(); bool readSpeckFile(); - bool _hasSpeckFile = false; + bool _hasSpeckFile = true; bool _dataIsDirty = true; bool _textColorIsDirty = true; bool _hasLabel = false; diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.cpp b/modules/digitaluniverse/rendering/renderableplanescloud.cpp index 7c4a801dc0..4316e1876d 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.cpp +++ b/modules/digitaluniverse/rendering/renderableplanescloud.cpp @@ -507,7 +507,7 @@ void RenderablePlanesCloud::loadTextures() { } else { // We can't really recover from this as it would crash during rendering anyway - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find image file '{}'", tex.file )); } @@ -516,14 +516,14 @@ void RenderablePlanesCloud::loadTextures() { ghoul::io::TextureReader::ref().loadTexture(path.string(), 2); if (t) { - LINFOC("RenderablePlanesCloud", fmt::format("Loaded texture {}", path)); + LINFOC("RenderablePlanesCloud", std::format("Loaded texture '{}'", path)); t->uploadTexture(); t->setFilter(ghoul::opengl::Texture::FilterMode::LinearMipMap); t->purgeFromRAM(); } else { // Same here, we won't be able to recover from this nullptr - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find image file '{}'", tex.file )); } @@ -587,7 +587,7 @@ void RenderablePlanesCloud::createPlanes() { glm::vec4 vertex2 = transformedPos - u + v; glm::vec4 vertex4 = transformedPos + u - v; - for (int i = 0; i < 3; ++i) { + for (int i = 0; i < 3; i++) { maxSize = std::max(maxSize, vertex0[i]); maxSize = std::max(maxSize, vertex1[i]); maxSize = std::max(maxSize, vertex2[i]); @@ -613,7 +613,7 @@ void RenderablePlanesCloud::createPlanes() { std::unordered_map::iterator found = _planesMap.find(textureIndex); if (found != _planesMap.end()) { - for (int i = 0; i < PlanesVertexDataSize; ++i) { + for (int i = 0; i < PlanesVertexDataSize; i++) { found->second.planesCoordinates.push_back(VertexData[i]); } found->second.numberOfPlanes++; @@ -624,7 +624,7 @@ void RenderablePlanesCloud::createPlanes() { glGenVertexArrays(1, &pA.vao); glGenBuffers(1, &pA.vbo); pA.numberOfPlanes = 1; - for (int i = 0; i < PlanesVertexDataSize; ++i) { + for (int i = 0; i < PlanesVertexDataSize; i++) { pA.planesCoordinates.push_back(VertexData[i]); } _planesMap.insert(std::pair(textureIndex, pA)); diff --git a/modules/exoplanets/exoplanetshelper.cpp b/modules/exoplanets/exoplanetshelper.cpp index 130e1581e4..c4c3ebc9d4 100644 --- a/modules/exoplanets/exoplanetshelper.cpp +++ b/modules/exoplanets/exoplanetshelper.cpp @@ -48,11 +48,11 @@ bool isValidPosition(const glm::vec3& pos) { } bool hasSufficientData(const ExoplanetDataEntry& p) { - const glm::vec3 starPosition{ p.positionX , p.positionY, p.positionZ }; + const glm::vec3 starPosition = glm::vec3(p.positionX, p.positionY, p.positionZ); - bool validStarPosition = isValidPosition(starPosition); - bool hasSemiMajorAxis = !std::isnan(p.a); - bool hasOrbitalPeriod = !std::isnan(p.per); + const bool validStarPosition = isValidPosition(starPosition); + const bool hasSemiMajorAxis = !std::isnan(p.a); + const bool hasOrbitalPeriod = !std::isnan(p.per); return validStarPosition && hasSemiMajorAxis && hasOrbitalPeriod; } @@ -64,8 +64,8 @@ glm::vec3 computeStarColor(float bv) { std::ifstream colorMap(absPath(bvColormapPath), std::ios::in); if (!colorMap.good()) { - LERROR(fmt::format( - "Failed to open colormap data file: {}", absPath(bvColormapPath) + LERROR(std::format( + "Failed to open colormap data file '{}'", absPath(bvColormapPath) )); return glm::vec3(0.f); } @@ -81,7 +81,7 @@ glm::vec3 computeStarColor(float bv) { // The first line is the width of the image, i.e number of values std::istringstream ss(line); - int nValues; + int nValues = 0; ss >> nValues; // Find the line matching the input B-V value (B-V is in [-0.4,2.0]) @@ -90,13 +90,11 @@ glm::vec3 computeStarColor(float bv) { for (int i = 0; i < t + 1; i++) { std::getline(colorMap, color); } - colorMap.close(); std::istringstream colorStream(color); - float r, g, b; - colorStream >> r >> g >> b; - - return glm::vec3(r, g, b); + glm::vec3 rgb; + colorStream >> rgb.r >> rgb.g >> rgb.b; + return rgb; } glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom, float omega) { @@ -117,7 +115,7 @@ glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom, float omega) { return orbitPlaneRotation; } -glm::dmat3 computeSystemRotation(glm::dvec3 starPosition) { +glm::dmat3 computeSystemRotation(const glm::dvec3& starPosition) { const glm::dvec3 sunPosition = glm::dvec3(0.0, 0.0, 0.0); const glm::dvec3 starToSunVec = glm::normalize(sunPosition - starPosition); const glm::dvec3 galacticNorth = glm::dvec3(0.0, 0.0, 1.0); @@ -135,7 +133,7 @@ glm::dmat3 computeSystemRotation(glm::dvec3 starPosition) { celestialNorth, starToSunVec )); - glm::dvec3 northProjected = glm::normalize( + const glm::dvec3 northProjected = glm::normalize( celestialNorth - (celestialAngle / glm::length(starToSunVec)) * starToSunVec ); diff --git a/modules/exoplanets/exoplanetshelper.h b/modules/exoplanets/exoplanetshelper.h index f08f4746b1..9af3a0c0d4 100644 --- a/modules/exoplanets/exoplanetshelper.h +++ b/modules/exoplanets/exoplanetshelper.h @@ -164,7 +164,7 @@ glm::dmat4 computeOrbitPlaneRotationMatrix(float i, float bigom = 180.f, * Rotate the original coordinate system (where x is pointing to First Point of Aries) so * that x is pointing from star to the Sun. */ -glm::dmat3 computeSystemRotation(glm::dvec3 starPosition); +glm::dmat3 computeSystemRotation(const glm::dvec3& starPosition); void sanitizeNameString(std::string& s); diff --git a/modules/exoplanets/exoplanetsmodule.cpp b/modules/exoplanets/exoplanetsmodule.cpp index e713c95154..d26ad79e7a 100644 --- a/modules/exoplanets/exoplanetsmodule.cpp +++ b/modules/exoplanets/exoplanetsmodule.cpp @@ -268,7 +268,7 @@ std::string ExoplanetsModule::exoplanetsDataPath() const { ghoul_assert(hasDataFiles(), "Data files not loaded"); return absPath( - fmt::format("{}/{}", _exoplanetsDataFolder.value(), ExoplanetsDataFileName) + std::format("{}/{}", _exoplanetsDataFolder.value(), ExoplanetsDataFileName) ).string(); } @@ -276,14 +276,14 @@ std::string ExoplanetsModule::lookUpTablePath() const { ghoul_assert(hasDataFiles(), "Data files not loaded"); return absPath( - fmt::format("{}/{}", _exoplanetsDataFolder.value(), LookupTableFileName) + std::format("{}/{}", _exoplanetsDataFolder.value(), LookupTableFileName) ).string(); } std::string ExoplanetsModule::teffToBvConversionFilePath() const { ghoul_assert(hasDataFiles(), "Data files not loaded"); - return absPath(fmt::format( + return absPath(std::format( "{}/{}", _exoplanetsDataFolder.value(), TeffToBvConversionFileName )).string(); } diff --git a/modules/exoplanets/exoplanetsmodule_lua.inl b/modules/exoplanets/exoplanetsmodule_lua.inl index 4d78edbf45..7ae1e275ee 100644 --- a/modules/exoplanets/exoplanetsmodule_lua.inl +++ b/modules/exoplanets/exoplanetsmodule_lua.inl @@ -53,14 +53,14 @@ openspace::exoplanets::ExoplanetSystem findExoplanetSystemInData( const std::string binPath = module->exoplanetsDataPath(); std::ifstream data(absPath(binPath), std::ios::in | std::ios::binary); if (!data.good()) { - LERROR(fmt::format("Failed to open exoplanets data file: '{}'", binPath)); + LERROR(std::format("Failed to open exoplanets data file '{}'", binPath)); return ExoplanetSystem(); } const std::string lutPath = module->lookUpTablePath(); std::ifstream lut(absPath(lutPath)); if (!lut.good()) { - LERROR(fmt::format("Failed to open exoplanets look-up table: '{}'", lutPath)); + LERROR(std::format("Failed to open exoplanets look-up table '{}'", lutPath)); return ExoplanetSystem(); } @@ -90,7 +90,7 @@ openspace::exoplanets::ExoplanetSystem findExoplanetSystemInData( sanitizeNameString(name); if (!hasSufficientData(p)) { - LWARNING(fmt::format("Insufficient data for exoplanet: '{}'", name)); + LWARNING(std::format("Insufficient data for exoplanet '{}'", name)); continue; } @@ -115,11 +115,11 @@ void createExoplanetSystem(const std::string& starName, std::string sanitizedStarName = starName; sanitizeNameString(sanitizedStarName); - const std::string guiPath = fmt::format("{}{}", ExoplanetsGuiPath, sanitizedStarName); + const std::string guiPath = std::format("{}{}", ExoplanetsGuiPath, sanitizedStarName); SceneGraphNode* existingStarNode = sceneGraphNode(starIdentifier); if (existingStarNode) { - LERROR(fmt::format( + LERROR(std::format( "Adding of exoplanet system '{}' failed. The system has already been added", starName )); @@ -128,8 +128,8 @@ void createExoplanetSystem(const std::string& starName, const glm::vec3 starPosInParsec = system.starData.position; if (!isValidPosition(starPosInParsec)) { - LERROR(fmt::format( - "Insufficient data available for exoplanet system: '{}'. Could not determine " + LERROR(std::format( + "Insufficient data available for exoplanet system '{}'. Could not determine " "star position", starName )); return; @@ -560,14 +560,14 @@ std::vector hostStarsWithSufficientData() { const std::string lutPath = module->lookUpTablePath(); std::ifstream lookupTableFile(absPath(lutPath)); if (!lookupTableFile.good()) { - LERROR(fmt::format("Failed to open lookup table file '{}'", lutPath)); + LERROR(std::format("Failed to open lookup table file '{}'", lutPath)); return {}; } const std::string binPath = module->exoplanetsDataPath(); std::ifstream data(absPath(binPath), std::ios::in | std::ios::binary); if (!data.good()) { - LERROR(fmt::format("Failed to open data file '{}'", binPath)); + LERROR(std::format("Failed to open data file '{}'", binPath)); return {}; } @@ -634,7 +634,7 @@ std::vector hostStarsWithSufficientData() { findExoplanetSystemInData(starName); if (systemData.planetsData.empty()) { - LERROR(fmt::format("Exoplanet system '{}' could not be found", starName)); + LERROR(std::format("Exoplanet system '{}' could not be found", starName)); return; } @@ -685,13 +685,13 @@ listOfExoplanetsDeprecated() std::vector names = hostStarsWithSufficientData(); std::string output; - for (auto it = names.begin(); it != names.end(); ++it) { - output += *it + ", "; + for (const std::string& name : names) { + output += name + ", "; } output.pop_back(); output.pop_back(); - LINFO(fmt::format( + LINFO(std::format( "There is data available for the following {} exoplanet systems: {}", names.size(), output )); @@ -707,7 +707,8 @@ listOfExoplanetsDeprecated() * * We recommend downloading the file from the Exoplanet Archive's Composite data table, * where multiple sources are combined into one row per planet. - * https://exoplanetarchive.ipac.caltech.edu/cgi-bin/TblView/nph-tblView?app=ExoTbls&config=PSCompPars + * https://exoplanetarchive.ipac.caltech.edu + * /cgi-bin/TblView/nph-tblView?app=ExoTbls&config=PSCompPars * * Please remember to include all columns in the file download, as missing data columns * may lead to an incomplete visualization. @@ -723,7 +724,7 @@ listOfExoplanetsDeprecated() std::ifstream inputDataFile(csvFile); if (!inputDataFile.good()) { - LERROR(fmt::format("Failed to open input file {}", csvFile)); + LERROR(std::format("Failed to open input file '{}'", csvFile)); return; } @@ -745,11 +746,11 @@ listOfExoplanetsDeprecated() module->teffToBvConversionFilePath() ); - LINFO(fmt::format("Reading data for planet: '{}' ", planetData.name)); + LINFO(std::format("Reading data for planet '{}'", planetData.name)); if (!hasSufficientData(planetData.dataEntry)) { - LWARNING(fmt::format( - "Insufficient data for exoplanet: '{}'", planetData.name + LWARNING(std::format( + "Insufficient data for exoplanet '{}'", planetData.name )); continue; } @@ -784,8 +785,8 @@ listOfExoplanetsDeprecated() createExoplanetSystem(hostName, data); } - LINFO(fmt::format( - "Read data for {} exoplanet systems from CSV file: '{}'. Please wait until " + LINFO(std::format( + "Read data for {} exoplanet systems from CSV file: {}. Please wait until " "they are all finished initializing. You may have to reload the user interface.", hostNameToSystemDataMap.size(), csvFile )); diff --git a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp index 746b422d91..a6b13e56d1 100644 --- a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp +++ b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.cpp @@ -100,8 +100,8 @@ ExoplanetsDataPreparationTask::ExoplanetsDataPreparationTask( } std::string ExoplanetsDataPreparationTask::description() { - return fmt::format( - "Extract data about exoplanets from file {} and write as bin to {}. The data " + return std::format( + "Extract data about exoplanets from file '{}' and write as bin to '{}'. The data " "file should be a csv version of the Planetary Systems Composite Data from the " "NASA exoplanets archive (https://exoplanetarchive.ipac.caltech.edu/)", _inputDataPath, _outputBinPath @@ -113,7 +113,7 @@ void ExoplanetsDataPreparationTask::perform( { std::ifstream inputDataFile(_inputDataPath); if (!inputDataFile.good()) { - LERROR(fmt::format("Failed to open input file {}", _inputDataPath)); + LERROR(std::format("Failed to open input file '{}'", _inputDataPath)); return; } @@ -121,7 +121,7 @@ void ExoplanetsDataPreparationTask::perform( std::ofstream lutFile(_outputLutPath); if (!binFile.good()) { - LERROR(fmt::format("Error when writing to {}",_outputBinPath)); + LERROR(std::format("Error when writing to '{}'",_outputBinPath)); if (!std::filesystem::is_directory(_outputBinPath.parent_path())) { LERROR("Output directory does not exist"); } @@ -129,7 +129,7 @@ void ExoplanetsDataPreparationTask::perform( } if (!lutFile.good()) { - LERROR(fmt::format("Error when writing to {}", _outputLutPath)); + LERROR(std::format("Error when writing to '{}'", _outputLutPath)); if (!std::filesystem::is_directory(_outputLutPath.parent_path())) { LERROR("Output directory does not exist"); } @@ -141,7 +141,7 @@ void ExoplanetsDataPreparationTask::perform( // Read until the first line contaning the column names, and save them for // later access - std::vector columnNames = readFirstDataRow(inputDataFile); + const std::vector columnNames = readFirstDataRow(inputDataFile); // Read total number of items int total = 0; @@ -156,7 +156,7 @@ void ExoplanetsDataPreparationTask::perform( // containing the data names, again readFirstDataRow(inputDataFile); - LINFO(fmt::format("Loading {} exoplanets", total)); + LINFO(std::format("Loading {} exoplanets", total)); int exoplanetCount = 0; while (std::getline(inputDataFile, row)) { @@ -171,9 +171,9 @@ void ExoplanetsDataPreparationTask::perform( ); // Create look-up table - long pos = static_cast(binFile.tellp()); - std::string planetName = planetData.host + " " + planetData.component; - lutFile << planetName << "," << pos << std::endl; + const long pos = static_cast(binFile.tellp()); + const std::string planetName = planetData.host + " " + planetData.component; + lutFile << planetName << "," << pos << '\n'; binFile.write( reinterpret_cast(&planetData.dataEntry), @@ -191,7 +191,7 @@ ExoplanetsDataPreparationTask::readFirstDataRow(std::ifstream& file) // Read past any comments and empty lines while (std::getline(file, line)) { - bool shouldSkip = line.empty() || line[0] == '#'; + const bool shouldSkip = line.empty() || line[0] == '#'; if (!shouldSkip) { break; } @@ -209,10 +209,10 @@ ExoplanetsDataPreparationTask::readFirstDataRow(std::ifstream& file) } ExoplanetsDataPreparationTask::PlanetData -ExoplanetsDataPreparationTask::parseDataRow(std::string row, +ExoplanetsDataPreparationTask::parseDataRow(const std::string& row, const std::vector& columnNames, - std::filesystem::path positionSourceFile, - std::filesystem::path bvFromTeffConversionFile) + const std::filesystem::path& positionSourceFile, + const std::filesystem::path& bvFromTeffConversionFile) { auto readFloatData = [](const std::string& str) -> float { #ifdef WIN32 @@ -224,7 +224,7 @@ ExoplanetsDataPreparationTask::parseDataRow(std::string row, return std::numeric_limits::quiet_NaN(); #else // clang is missing float support for std::from_chars - return !str.empty() ? std::stof(str.c_str(), nullptr) : NAN; + return !str.empty() ? std::stof(str, nullptr) : NAN; #endif }; @@ -238,12 +238,12 @@ ExoplanetsDataPreparationTask::parseDataRow(std::string row, return std::numeric_limits::quiet_NaN(); #else // clang is missing double support for std::from_chars - return !str.empty() ? std::stod(str.c_str(), nullptr) : NAN; + return !str.empty() ? std::stod(str, nullptr) : NAN; #endif }; auto readIntegerData = [](const std::string& str) -> int { - int result; + int result = 0; auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result); if (ec == std::errc()) { return result; @@ -391,15 +391,15 @@ ExoplanetsDataPreparationTask::parseDataRow(std::string row, } // Star luminosity else if (column == "st_lum") { - float dataInLogSolar = readFloatData(data); + const float dataInLogSolar = readFloatData(data); p.luminosity = static_cast(std::pow(10, dataInLogSolar)); } else if (column == "st_lumerr1") { - float dataInLogSolar = readFloatData(data); + const float dataInLogSolar = readFloatData(data); p.luminosityUpper = static_cast(std::pow(10, dataInLogSolar)); } else if (column == "st_lumerr2") { - float dataInLogSolar = readFloatData(data); + const float dataInLogSolar = readFloatData(data); p.luminosityLower = static_cast(-std::pow(10, dataInLogSolar)); } // Is the planet orbiting a binary system? @@ -422,12 +422,12 @@ ExoplanetsDataPreparationTask::parseDataRow(std::string row, p.bigOmegaUpper = std::numeric_limits::quiet_NaN(); p.bigOmegaLower = std::numeric_limits::quiet_NaN(); - bool foundPositionFromSpeck = !std::isnan(p.positionX); - bool hasDistance = !std::isnan(distanceInParsec); - bool hasIcrsCoords = !std::isnan(ra) && !std::isnan(dec) && hasDistance; + const bool foundPositionFromSpeck = !std::isnan(p.positionX); + const bool hasDistance = !std::isnan(distanceInParsec); + const bool hasIcrsCoords = !std::isnan(ra) && !std::isnan(dec) && hasDistance; if (!foundPositionFromSpeck && hasIcrsCoords) { - glm::dvec3 pos = icrsToGalacticCartesian(ra, dec, distanceInParsec); + const glm::dvec3 pos = icrsToGalacticCartesian(ra, dec, distanceInParsec); p.positionX = static_cast(pos.x); p.positionY = static_cast(pos.y); p.positionZ = static_cast(pos.z); @@ -453,12 +453,12 @@ glm::vec3 ExoplanetsDataPreparationTask::starPosition(const std::string& starNam std::ifstream exoplanetsFile(sourceFile); if (!exoplanetsFile) { - LERROR(fmt::format("Error opening file {}", sourceFile)); + LERROR(std::format("Error opening file '{}'", sourceFile)); } std::string line; while (std::getline(exoplanetsFile, line)) { - bool shouldSkipLine = ( + const bool shouldSkipLine = ( line.empty() || line[0] == '#' || line.substr(0, 7) == "datavar" || line.substr(0, 10) == "texturevar" || line.substr(0, 7) == "texture" ); @@ -478,11 +478,11 @@ glm::vec3 ExoplanetsDataPreparationTask::starPosition(const std::string& starNam if (name == starName) { std::stringstream dataStream(data); std::getline(dataStream, coord, ' '); - position[0] = std::stof(coord.c_str(), nullptr); + position[0] = std::stof(coord, nullptr); std::getline(dataStream, coord, ' '); - position[1] = std::stof(coord.c_str(), nullptr); + position[1] = std::stof(coord, nullptr); std::getline(dataStream, coord, ' '); - position[2] = std::stof(coord.c_str(), nullptr); + position[2] = std::stof(coord, nullptr); break; } } @@ -499,7 +499,7 @@ float ExoplanetsDataPreparationTask::bvFromTeff(float teff, std::ifstream teffToBvFile(conversionFile); if (!teffToBvFile.good()) { - LERROR(fmt::format("Failed to open file {}", conversionFile)); + LERROR(std::format("Failed to open file '{}'", conversionFile)); return std::numeric_limits::quiet_NaN(); } @@ -509,7 +509,7 @@ float ExoplanetsDataPreparationTask::bvFromTeff(float teff, float bvUpper = 0.f; float bvLower = 0.f; float teffLower = 0.f; - float teffUpper; + float teffUpper = 0.f; std::string row; while (std::getline(teffToBvFile, row)) { std::istringstream lineStream(row); @@ -518,8 +518,8 @@ float ExoplanetsDataPreparationTask::bvFromTeff(float teff, std::string bvString; std::getline(lineStream, bvString); - float teffCurrent = std::stof(teffString.c_str(), nullptr); - float bvCurrent = std::stof(bvString.c_str(), nullptr); + const float teffCurrent = std::stof(teffString, nullptr); + const float bvCurrent = std::stof(bvString, nullptr); if (teff > teffCurrent) { teffLower = teffCurrent; @@ -532,8 +532,8 @@ float ExoplanetsDataPreparationTask::bvFromTeff(float teff, bv = 2.f; } else { - float bvDiff = (bvUpper - bvLower); - float teffDiff = (teffUpper - teffLower); + const float bvDiff = (bvUpper - bvLower); + const float teffDiff = (teffUpper - teffLower); bv = ((bvDiff * (teff - teffLower)) / teffDiff) + bvLower; } break; diff --git a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.h b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.h index d604472fb1..2a0fc765e6 100644 --- a/modules/exoplanets/tasks/exoplanetsdatapreparationtask.h +++ b/modules/exoplanets/tasks/exoplanetsdatapreparationtask.h @@ -77,10 +77,10 @@ public: * * /sa https://exoplanetarchive.ipac.caltech.edu/ */ - static PlanetData parseDataRow(std::string row, + static PlanetData parseDataRow(const std::string& row, const std::vector& columnNames, - std::filesystem::path positionSourceFile, - std::filesystem::path bvFromTeffConversionFile); + const std::filesystem::path& positionSourceFile, + const std::filesystem::path& bvFromTeffConversionFile); private: std::filesystem::path _inputDataPath; diff --git a/modules/fieldlines/rendering/renderablefieldlines.cpp b/modules/fieldlines/rendering/renderablefieldlines.cpp index 919310d3e6..f9a019110f 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.cpp +++ b/modules/fieldlines/rendering/renderablefieldlines.cpp @@ -125,21 +125,21 @@ RenderableFieldlines::RenderableFieldlines(const ghoul::Dictionary& dictionary) setIdentifier(identifier); if (!dictionary.hasValue(KeyVectorField)) { - LERROR(fmt::format("Renderable does not contain a key for '{}'", KeyVectorField)); + LERROR(std::format("Renderable does not contain a key for '{}'", KeyVectorField)); } else { _vectorFieldInfo = dictionary.value(KeyVectorField); } if (!dictionary.hasValue(KeyFieldlines)) { - LERROR(fmt::format("Renderable does not contain a key for '{}'", KeyFieldlines)); + LERROR(std::format("Renderable does not contain a key for '{}'", KeyFieldlines)); } else { _fieldlineInfo = dictionary.value(KeyFieldlines); } if (!dictionary.hasValue(KeySeedPoints)) { - LERROR(fmt::format("Renderable does not contain a key for '{}'", KeySeedPoints)); + LERROR(std::format("Renderable does not contain a key for '{}'", KeySeedPoints)); } else { _seedPointsInfo = dictionary.value(KeySeedPoints); @@ -292,7 +292,7 @@ void RenderableFieldlines::update(const UpdateData&) { int prevEnd = 0; std::vector vertexData; // Arrange data for glMultiDrawArrays - for (size_t j = 0; j < fieldlines.size(); ++j) { + for (size_t j = 0; j < fieldlines.size(); j++) { _lineStart.push_back(prevEnd); _lineCount.push_back(static_cast(fieldlines[j].size())); prevEnd = prevEnd + static_cast(fieldlines[j].size()); @@ -302,7 +302,7 @@ void RenderableFieldlines::update(const UpdateData&) { fieldlines[j].end() ); } - LDEBUG(fmt::format("Number of vertices: {}", vertexData.size())); + LDEBUG(std::format("Number of vertices: {}", vertexData.size())); if (_fieldlineVAO == 0) { glGenVertexArrays(1, &_fieldlineVAO); @@ -363,11 +363,11 @@ void RenderableFieldlines::loadSeedPoints() { } void RenderableFieldlines::loadSeedPointsFromFile() { - LINFO(fmt::format("Reading seed points from '{}'", _seedPointSourceFile.value())); + LINFO(std::format("Reading seed points from '{}'", _seedPointSourceFile.value())); std::ifstream seedFile(_seedPointSourceFile); if (!seedFile.good()) - LERROR(fmt::format( + LERROR(std::format( "Could not open seed points file '{}'", _seedPointSourceFile.value() )); else { @@ -393,7 +393,7 @@ void RenderableFieldlines::loadSeedPointsFromTable() { ghoul::Dictionary seedpointsDictionary = _seedPointsInfo.value(KeySeedPointsType); for (std::string_view index : seedpointsDictionary.keys()) { - std::string key = fmt::format("{}.{}", KeySeedPointsTable, index); + std::string key = std::format("{}.{}", KeySeedPointsTable, index); // (2020-12-31, abock) Looks to me as if this should be seedpointsDictionary if (_fieldlineInfo.hasValue(key)) { glm::dvec3 seedPos = _fieldlineInfo.value(key); @@ -404,8 +404,8 @@ void RenderableFieldlines::loadSeedPointsFromTable() { std::vector RenderableFieldlines::generateFieldlines() { if (!_vectorFieldInfo.hasValue(KeyVectorFieldType)) { - LERROR(fmt::format( - "{} does not contain a '{}' key", KeyVectorField, KeyVectorFieldType + LERROR(std::format( + "'{}' does not contain a '{}' key", KeyVectorField, KeyVectorFieldType )); return {}; } @@ -415,7 +415,7 @@ std::vector RenderableFieldlines::generateFieldlines return generateFieldlinesVolumeKameleon(); } else { - LERROR(fmt::format( + LERROR(std::format( "{}.{} does not name a valid type", KeyVectorField, KeyVectorFieldType )); return {}; @@ -426,14 +426,14 @@ std::vector RenderableFieldlines::generateFieldlinesVolumeKameleon() { if (!_vectorFieldInfo.hasValue(KeyVectorFieldVolumeModel)) { - LERROR(fmt::format("{} does not name a model", KeyVectorField)); + LERROR(std::format("'{}' does not name a model", KeyVectorField)); return {}; } std::string model = _vectorFieldInfo.value(KeyVectorFieldVolumeModel); if (!_vectorFieldInfo.hasValue(KeyVectorFieldFile)) { - LERROR(fmt::format("{} does not name a file", KeyVectorField)); + LERROR(std::format("'{}' does not name a file", KeyVectorField)); return {}; } std::string fileName = _vectorFieldInfo.value(KeyVectorFieldFile); @@ -443,7 +443,7 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() if (model != VectorFieldKameleonModelBATSRUS) { //modelType = KameleonWrapper::Model::BATSRUS; //else { - LERROR(fmt::format( + LERROR(std::format( "{}.{} model '{}' not supported", KeyVectorField, KeyVectorFieldVolumeModel, model )); @@ -463,7 +463,7 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() (_vectorFieldInfo.value(v1) == VectorFieldKameleonVariableLorentz); if (!threeVariables && !lorentzForce) { - LERROR(fmt::format("'{}' does not name variables", KeyVectorField)); + LERROR(std::format("'{}' does not name variables", KeyVectorField)); return {}; } diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index a40f28615d..f24d90322c 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -369,7 +369,7 @@ RenderableFieldlinesSequence::RenderableFieldlinesSequence( } else { _tracingVariable = "b"; // Magnetic field variable as default - LWARNING(fmt::format( + LWARNING(std::format( "No tracing variable, using default '{}'", _tracingVariable )); } @@ -388,9 +388,8 @@ RenderableFieldlinesSequence::RenderableFieldlinesSequence( // the files with the same extension as fileTypeString std::filesystem::path sourcePath = p.sourceFolder; if (!std::filesystem::is_directory(sourcePath)) { - LERROR(fmt::format( - "FieldlinesSequence {} is not a valid directory", - sourcePath.string() + LERROR(std::format( + "FieldlinesSequence '{}' is not a valid directory", sourcePath )); } @@ -421,8 +420,8 @@ RenderableFieldlinesSequence::RenderableFieldlinesSequence( // Ensure that there are available and valid source files left if (_sourceFiles.empty()) { - LERROR(fmt::format( - "{} contains no {} files", sourcePath.string(), fileTypeString + LERROR(std::format( + "'{}' contains no {} files", sourcePath.string(), fileTypeString )); } _extraVars = p.extraVariables.value_or(_extraVars); @@ -491,8 +490,8 @@ RenderableFieldlinesSequence::RenderableFieldlinesSequence( _outputFolderPath = p.outputFolder.value_or(_outputFolderPath); if (!_outputFolderPath.empty() && !std::filesystem::is_directory(_outputFolderPath)) { _outputFolderPath.clear(); - LERROR(fmt::format( - "The specified output path: '{}', does not exist", _outputFolderPath + LERROR(std::format( + "The specified output path '{}' does not exist", _outputFolderPath )); } @@ -618,7 +617,7 @@ void RenderableFieldlinesSequence::loadOsflsStatesIntoRAM() { } } else { - LWARNING(fmt::format("Failed to load state from: {}", filePath)); + LWARNING(std::format("Failed to load state from '{}'", filePath)); } } } @@ -674,7 +673,7 @@ void RenderableFieldlinesSequence::setupProperties() { // the given sequence have the same extra quantities const size_t nExtraQuantities = _states[0].nExtraQuantities(); const std::vector& extraNamesVec = _states[0].extraQuantityNames(); - for (int i = 0; i < static_cast(nExtraQuantities); ++i) { + for (int i = 0; i < static_cast(nExtraQuantities); i++) { _colorQuantity.addOption(i, extraNamesVec[i]); _maskingQuantity.addOption(i, extraNamesVec[i]); } @@ -852,8 +851,8 @@ std::unordered_map> std::unordered_map> outMap; if (!std::filesystem::is_directory(filePath)) { - LERROR(fmt::format( - "The specified seed point directory: '{}' does not exist", filePath + LERROR(std::format( + "The specified seed point directory '{}' does not exist", filePath )); return outMap; } @@ -869,12 +868,12 @@ std::unordered_map> std::ifstream seedFile(seedFilePath); if (!seedFile.good()) { - LERROR(fmt::format("Could not open seed points file '{}'", seedFilePath)); + LERROR(std::format("Could not open seed points file '{}'", seedFilePath)); outMap.clear(); return {}; } - LDEBUG(fmt::format("Reading seed points from file '{}'", seedFilePath)); + LDEBUG(std::format("Reading seed points from file '{}'", seedFilePath)); std::string line; std::vector outVec; while (std::getline(seedFile, line)) { @@ -887,7 +886,7 @@ std::unordered_map> } if (outVec.empty()) { - LERROR(fmt::format("Found no seed points in: {}", seedFilePath)); + LERROR(std::format("Found no seed points in '{}'", seedFilePath)); outMap.clear(); return {}; } diff --git a/modules/fieldlinessequence/util/fieldlinesstate.cpp b/modules/fieldlinessequence/util/fieldlinesstate.cpp index 6645783fe3..e4e746b62b 100644 --- a/modules/fieldlinessequence/util/fieldlinesstate.cpp +++ b/modules/fieldlinessequence/util/fieldlinesstate.cpp @@ -122,7 +122,7 @@ bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { allNamesInOne.assign(buffer.data(), byteSizeAllNames); size_t offset = 0; - for (size_t i = 0; i < nExtras; ++i) { + for (size_t i = 0; i < nExtras; i++) { auto endOfVarName = allNamesInOne.find('\0', offset); endOfVarName -= offset; const std::string varName = allNamesInOne.substr(offset, endOfVarName); @@ -140,7 +140,7 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, std::ifstream ifs(pathToJsonFile); if (!ifs.is_open()) { - LERROR(fmt::format("FAILED TO OPEN FILE: {}", pathToJsonFile)); + LERROR(std::format("Failed to open file '{}'", pathToJsonFile)); return false; } @@ -172,7 +172,7 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, return false; } - for (size_t i = nPosComponents ; i < nVariables ; ++i) { + for (size_t i = nPosComponents; i < nVariables; i++) { _extraQuantityNames.push_back(variableNameVec[i]); } } @@ -188,7 +188,7 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, const std::vector>& jData = (*lineIter)[sTrace][sData]; const size_t nPoints = jData.size(); - for (size_t j = 0; j < nPoints; ++j) { + for (size_t j = 0; j < nPoints; j++) { const std::vector& variables = jData[j]; // Expects the x, y and z variables to be stored first! @@ -205,7 +205,7 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, // Add the extra quantites. Stored in the same array as the x,y,z variables. // Hence index of the first extra quantity = 3 - for (size_t xtraIdx = 3, k = 0 ; k < nExtras; ++k, ++xtraIdx) { + for (size_t xtraIdx = 3, k = 0; k < nExtras; k++, xtraIdx++) { _extraQuantities[k].push_back(variables[xtraIdx]); } } @@ -252,7 +252,7 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { std::ofstream ofs(absPath + fileName, std::ofstream::binary | std::ofstream::trunc); if (!ofs.is_open()) { - LERROR(fmt::format( + LERROR(std::format( "Failed to save state to binary file: {}{}", absPath, fileName )); return; @@ -326,12 +326,12 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { const char* ext = ".json"; std::ofstream ofs(absPath + ext, std::ofstream::trunc); if (!ofs.is_open()) { - LERROR(fmt::format( + LERROR(std::format( "Failed to save state to json file at location: {}{}", absPath, ext )); return; } - LINFO(fmt::format("Saving fieldline state to: {}{}", absPath, ext)); + LINFO(std::format("Saving fieldline state to: {}{}", absPath, ext)); json jColumns = { "x", "y", "z" }; for (const std::string& s : _extraQuantityNames) { @@ -371,7 +371,7 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { const int indentationSpaces = 2; ofs << std::setw(indentationSpaces) << jFile << std::endl; - LINFO(fmt::format("Saved fieldline state to: {}{}", absPath, ext)); + LINFO(std::format("Saved fieldline state to: {}{}", absPath, ext)); } void FieldlinesState::setModel(fls::Model m) { diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp index 6c73961192..86741017dd 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp @@ -243,7 +243,7 @@ void addExtraQuantities(ccmc::Kameleon* kameleon, state.appendToExtra(i, val); } // Calculate and store the magnitudes! - for (size_t i = 0; i < nXtraMagnitudes; ++i) { + for (size_t i = 0; i < nXtraMagnitudes; i++) { const size_t idx = i*3; const float x = interpolator->interpolate(extraMagVars[idx] , p.x, p.y, p.z); @@ -292,7 +292,7 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, // Load the existing SCALAR variables into kameleon. // Remove non-existing variables from vector - for (int i = 0; i < static_cast(extraScalarVars.size()); ++i) { + for (int i = 0; i < static_cast(extraScalarVars.size()); i++) { std::string& str = extraScalarVars[i]; bool success = kameleon->doesVariableExist(str) && kameleon->loadVariable(str); if (!success && @@ -311,7 +311,7 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, str = TAsPOverRho; } if (!success) { - LWARNING(fmt::format("Failed to load extra variable: '{}'. Ignoring", str)); + LWARNING(std::format("Failed to load extra variable '{}'. Ignoring", str)); extraScalarVars.erase(extraScalarVars.begin() + i); --i; } @@ -349,9 +349,9 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, name = JParallelB; } if (!success) { - LWARNING(fmt::format( - "Failed to load at least one of the magnitude variables: {}, {}, {}. " - "Removing ability to store corresponding magnitude", + LWARNING(std::format( + "Failed to load at least one of the magnitude variables: '{}', '{}', " + "'{}'. Removing ability to store corresponding magnitude", s1, s2, s3 )); extraMagVars.erase( @@ -368,7 +368,7 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, else { // WRONG NUMBER OF MAGNITUDE VARIABLES.. REMOVE ALL! extraMagVars.clear(); - LWARNING(fmt::format( + LWARNING(std::format( "Wrong number of variables provided for storing magnitudes. Expects multiple " "of 3 but {} are provided", extraMagVars.size() diff --git a/modules/fitsfilereader/include/fitsfilereader.h b/modules/fitsfilereader/include/fitsfilereader.h index 3875cf27c6..0b2e2ae086 100644 --- a/modules/fitsfilereader/include/fitsfilereader.h +++ b/modules/fitsfilereader/include/fitsfilereader.h @@ -106,9 +106,10 @@ private: bool isPrimaryHDU(); template - const std::shared_ptr> readImageInternal(CCfits::PHDU& image); + std::shared_ptr> readImageInternal(CCfits::PHDU& image); + template - const std::shared_ptr> readImageInternal(CCfits::ExtHDU& image); + std::shared_ptr> readImageInternal(CCfits::ExtHDU& image); mutable std::mutex _mutex; }; diff --git a/modules/fitsfilereader/src/fitsfilereader.cpp b/modules/fitsfilereader/src/fitsfilereader.cpp index fa90651c72..ae905c3940 100644 --- a/modules/fitsfilereader/src/fitsfilereader.cpp +++ b/modules/fitsfilereader/src/fitsfilereader.cpp @@ -52,8 +52,9 @@ namespace { namespace openspace { -FitsFileReader::FitsFileReader(bool verboseMode) { - _verboseMode = verboseMode; +FitsFileReader::FitsFileReader(bool verboseMode) + : _verboseMode(verboseMode) +{ FITS::setVerboseMode(_verboseMode); } @@ -146,26 +147,26 @@ std::shared_ptr> FitsFileReader::readTable(const std::filesystem::p { // We need to lock reading when using multithreads because CCfits can't handle // multiple I/O drivers. - std::lock_guard g(_mutex); + const std::lock_guard g(_mutex); try { _infile = std::make_unique(path.string(), Read, readAll); // Make sure FITS file is not a Primary HDU Object (aka an image). if (!isPrimaryHDU()) { - ExtHDU& table = _infile->extension(hduIdx); - int numCols = static_cast(columnNames.size()); - int numRowsInTable = static_cast(table.rows()); + const ExtHDU& table = _infile->extension(hduIdx); + const int numCols = static_cast(columnNames.size()); + const int numRowsInTable = static_cast(table.rows()); std::unordered_map> contents; //LINFO("Read file: " + _infile->name()); - int firstRow = std::max(startRow, 1); + const int firstRow = std::max(startRow, 1); if (endRow < firstRow) { endRow = numRowsInTable; } - for (int i = 0; i < numCols; ++i) { + for (int i = 0; i < numCols; i++) { std::vector columnData; //LINFO("Read column: " + columnNames[i]); table.column(columnNames[i]).read(columnData, firstRow, endRow); @@ -180,11 +181,11 @@ std::shared_ptr> FitsFileReader::readTable(const std::filesystem::p .name = table.name() }; - return std::make_shared>(loadedTable); + return std::make_shared>(std::move(loadedTable)); } } catch (FitsException& e) { - LERROR(fmt::format( + LERROR(std::format( "Could not read FITS table from file '{}'. Make sure it's not an image file", e.message() )); @@ -238,8 +239,8 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, } LINFO(allNames); - // Read columns from FITS file. If rows aren't specified then full table will be read. - std::shared_ptr> table = readTable( + // Read columns from FITS file. If rows aren't specified then full table will be read + const std::shared_ptr> table = readTable( filePath, allColumnNames, firstRow, @@ -247,25 +248,25 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, ); if (!table) { - throw ghoul::RuntimeError(fmt::format("Failed to open Fits file {}", filePath)); + throw ghoul::RuntimeError(std::format("Failed to open Fits file '{}'", filePath)); } int nStars = table->readRows - firstRow + 1; int nNullArr = 0; - int nColumnsRead = static_cast(allColumnNames.size()); - int defaultCols = 17; // Number of columns that are copied by predefined code. + const int nColumnsRead = static_cast(allColumnNames.size()); + const int defaultCols = 17; // Number of columns that are copied by predefined code if (nColumnsRead != defaultCols) { LINFO("Additional columns will be read! Consider add column in code for " "significant speedup"); } // Declare how many values to save per star - nValuesPerStar = nColumnsRead + 1; // +1 for B-V color value. + nValuesPerStar = nColumnsRead + 1; // +1 for B-V color value - // Copy columns to local variables. + // Copy columns to local variables std::unordered_map>& tableContent = table->contents; - // Default render parameters! + // Default render parameters std::vector posXcol = std::move(tableContent[allColumnNames[0]]); std::vector posYcol = std::move(tableContent[allColumnNames[1]]); std::vector posZcol = std::move(tableContent[allColumnNames[2]]); @@ -288,7 +289,7 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, std::vector tycho_v_err = std::move(tableContent[allColumnNames[16]]); // Construct data array. OBS: ORDERING IS IMPORTANT! This is where slicing happens. - for (int i = 0; i < nStars * multiplier; ++i) { + for (int i = 0; i < nStars * multiplier; i++) { std::vector values(nValuesPerStar); size_t idx = 0; @@ -345,7 +346,7 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, values[idx++] = vecData[i]; } - for (int j = 0; j < nValuesPerStar; ++j) { + for (int j = 0; j < nValuesPerStar; j++) { // The astronomers in Vienna use -999 as default value. Change it to 0. if (values[j] == -999) { values[j] = 0.f; @@ -384,7 +385,7 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, auto table = readTable(filePath, allColumnNames, firstRow, lastRow); if (!table) { - throw ghoul::RuntimeError(fmt::format("Failed to open Fits file '{}'", filePath)); + throw ghoul::RuntimeError(std::format("Failed to open Fits file '{}'", filePath)); } int nStars = table->readRows - firstRow + 1; @@ -413,7 +414,7 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, std::vector radial_vel = std::move(tableContent[allColumnNames[8]]); // Construct data array. OBS: ORDERING IS IMPORTANT! This is where slicing happens. - for (int i = 0; i < nStars; ++i) { + for (int i = 0; i < nStars; i++) { std::vector values(nValuesPerStar); size_t idx = 0; @@ -516,8 +517,8 @@ std::vector FitsFileReader::readFitsFile(std::filesystem::path filePath, fullData.insert(fullData.end(), values.begin(), values.end()); }*/ - LINFO(fmt::format("{} out of {} read stars were null arrays", nNullArr, nStars)); - LINFO(fmt::format("Multiplier: {}", multiplier)); + LINFO(std::format("{} out of {} read stars were null arrays", nNullArr, nStars)); + LINFO(std::format("Multiplier: {}", multiplier)); return fullData; } @@ -530,7 +531,7 @@ std::vector FitsFileReader::readSpeckFile(const std::filesystem::path& fi std::ifstream fileStream(filePath); if (!fileStream.good()) { - LERROR(fmt::format("Failed to open Speck file {}", filePath)); + LERROR(std::format("Failed to open Speck file '{}'", filePath)); return fullData; } @@ -543,7 +544,7 @@ std::vector FitsFileReader::readSpeckFile(const std::filesystem::path& fi // (signaled by the keywords 'datavar', 'texturevar', 'texture' and 'maxcomment') std::string line; while (true) { - std::streampos position = fileStream.tellg(); + const std::streampos position = fileStream.tellg(); std::getline(fileStream, line); if (line.empty() || line[0] == '#') { @@ -601,14 +602,14 @@ std::vector FitsFileReader::readSpeckFile(const std::filesystem::path& fi std::stringstream str(line); // Read values. - for (int i = 0; i < nValuesPerStar; ++i) { + for (int i = 0; i < nValuesPerStar; i++) { str >> readValues[i]; } // Check if star is a nullArray. bool nullArray = true; - for (float f : readValues) { - if (f != 0.0) { + for (const float f : readValues) { + if (f != 0.f) { nullArray = false; break; } @@ -648,7 +649,7 @@ std::vector FitsFileReader::readSpeckFile(const std::filesystem::path& fi } while (!fileStream.eof()); - LINFO(fmt::format("{} out of {} read stars were null arrays", nNullArr, nStars)); + LINFO(std::format("{} out of {} read stars were null arrays", nNullArr, nStars)); return fullData; } @@ -656,7 +657,7 @@ std::vector FitsFileReader::readSpeckFile(const std::filesystem::path& fi // This is pretty annoying, the read method is not derived from the HDU class // in CCfits - need to explicitly cast to the sub classes to access read template -const std::shared_ptr> FitsFileReader::readImageInternal(ExtHDU& image) { +std::shared_ptr> FitsFileReader::readImageInternal(ExtHDU& image) { try { std::valarray contents; image.read(contents); @@ -666,14 +667,15 @@ const std::shared_ptr> FitsFileReader::readImageInternal(ExtHDU& im .height = image.axis(1) }; return std::make_shared>(im); - } catch (const FitsException& e){ + } + catch (const FitsException& e) { LERROR("Could not read FITS image EXTHDU. " + e.message()); } return nullptr; } template -const std::shared_ptr> FitsFileReader::readImageInternal(PHDU& image) { +std::shared_ptr> FitsFileReader::readImageInternal(PHDU& image) { try { std::valarray contents; image.read(contents); @@ -683,7 +685,8 @@ const std::shared_ptr> FitsFileReader::readImageInternal(PHDU& imag .height = image.axis(1) }; return std::make_shared>(im); - } catch (const FitsException& e){ + } + catch (const FitsException& e) { LERROR("Could not read FITS image PHDU. " + e.message()); } return nullptr; diff --git a/modules/gaia/rendering/octreeculler.cpp b/modules/gaia/rendering/octreeculler.cpp index dff3d8dc70..e417b13366 100644 --- a/modules/gaia/rendering/octreeculler.cpp +++ b/modules/gaia/rendering/octreeculler.cpp @@ -72,9 +72,10 @@ void OctreeCuller::createNodeBounds(const std::vector& corners, // Create a bounding box in clipping space from node boundaries. _nodeBounds = globebrowsing::AABB3(); - for (size_t i = 0; i < 8; ++i) { - glm::dvec4 cornerClippingSpace = mvp * corners[i]; - glm::dvec4 ndc = (1.f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace; + for (size_t i = 0; i < 8; i++) { + const glm::dvec4 cornerClippingSpace = mvp * corners[i]; + const glm::dvec4 ndc = + (1.f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace; expand(_nodeBounds, glm::dvec3(ndc)); } } diff --git a/modules/gaia/rendering/octreemanager.cpp b/modules/gaia/rendering/octreemanager.cpp index 6a58b3bbf0..b8c8ea8e8b 100644 --- a/modules/gaia/rendering/octreemanager.cpp +++ b/modules/gaia/rendering/octreemanager.cpp @@ -34,6 +34,25 @@ namespace { constexpr std::string_view _loggerCat = "OctreeManager"; + + /** + * \return the correct index of child node. Maps [1,1,1] to 0 and [-1,-1,-1] to 7 + */ + size_t childIndex(float posX, float posY, float posZ, float origX = 0.f, + float origY = 0.f, float origZ = 0.f) + { + size_t index = 0; + if (posX < origX) { + index += 1; + } + if (posY < origY) { + index += 2; + } + if (posZ < origZ) { + index += 4; + } + return index; + } } // namespace namespace openspace { @@ -48,7 +67,7 @@ void OctreeManager::initOctree(long long cpuRamBudget, int maxDist, int maxStars _root = std::make_shared(); _root->octreePositionIndex = 8; - // Initialize the culler. The NDC.z of the comparing corners are always -1 or 1. + // Initialize the culler. The NDC.z of the comparing corners are always -1 or 1 globebrowsing::AABB3 box; box.min = glm::vec3(-1.f, -1.f, 0.f); box.max = glm::vec3(1.f, 1.f, 100.f); @@ -56,7 +75,7 @@ void OctreeManager::initOctree(long long cpuRamBudget, int maxDist, int maxStars _removedKeysInPrevCall = std::set(); _leastRecentlyFetchedNodes = std::queue(); - // Reset default values when rebuilding the Octree during runtime. + // Reset default values when rebuilding the Octree during runtime _numInnerNodes = 0; _numLeafNodes = 0; _totalDepth = 0; @@ -72,36 +91,36 @@ void OctreeManager::initOctree(long long cpuRamBudget, int maxDist, int maxStars MAX_STARS_PER_NODE = static_cast(maxStarsPerNode); } - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { _numLeafNodes++; - _root->Children[i] = std::make_shared(); - _root->Children[i]->posData = std::vector(); - _root->Children[i]->colData = std::vector(); - _root->Children[i]->velData = std::vector(); - _root->Children[i]->magOrder = std::vector>(); - _root->Children[i]->isLeaf = true; - _root->Children[i]->isLoaded = false; - _root->Children[i]->hasLoadedDescendant = false; - _root->Children[i]->bufferIndex = DEFAULT_INDEX; - _root->Children[i]->octreePositionIndex = 80 + i; - _root->Children[i]->numStars = 0; - _root->Children[i]->halfDimension = MAX_DIST / 2.f; - _root->Children[i]->originX = (i % 2 == 0) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; - _root->Children[i]->originY = (i % 4 < 2) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; - _root->Children[i]->originZ = (i < 4) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; + _root->children[i] = std::make_shared(); + _root->children[i]->posData = std::vector(); + _root->children[i]->colData = std::vector(); + _root->children[i]->velData = std::vector(); + _root->children[i]->magOrder = std::vector>(); + _root->children[i]->isLeaf = true; + _root->children[i]->isLoaded = false; + _root->children[i]->hasLoadedDescendant = false; + _root->children[i]->bufferIndex = DEFAULT_INDEX; + _root->children[i]->octreePositionIndex = 80 + i; + _root->children[i]->numStars = 0; + _root->children[i]->halfDimension = MAX_DIST / 2.f; + _root->children[i]->originX = (i % 2 == 0) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; + _root->children[i]->originY = (i % 4 < 2) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; + _root->children[i]->originZ = (i < 4) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; } } void OctreeManager::initBufferIndexStack(long long maxNodes, bool useVBO, bool datasetFitInMemory) { - // Clear stack if we've used it before. + // Clear stack if we've used it before _biggestChunkIndexInUse = 0; _freeSpotsInBuffer = std::stack(); _rebuildBuffer = true; @@ -117,18 +136,18 @@ void OctreeManager::initBufferIndexStack(long long maxNodes, bool useVBO, } void OctreeManager::insert(const std::vector& starValues) { - size_t index = getChildIndex(starValues[0], starValues[1], starValues[2]); + const size_t index = childIndex(starValues[0], starValues[1], starValues[2]); - insertInNode(*_root->Children[index], starValues); + insertInNode(*_root->children[index], starValues); } void OctreeManager::sliceLodData(size_t branchIndex) { if (branchIndex != 8) { - sliceNodeLodCache(*_root->Children[branchIndex]); + sliceNodeLodCache(*_root->children[branchIndex]); } else { - for (int i = 0; i < 7; ++i) { - sliceNodeLodCache(*_root->Children[i]); + for (int i = 0; i < 7; i++) { + sliceNodeLodCache(*_root->children[i]); } } } @@ -136,14 +155,14 @@ void OctreeManager::sliceLodData(size_t branchIndex) { void OctreeManager::printStarsPerNode() const { std::string accumulatedString; - for (int i = 0; i < 8; ++i) { - std::string prefix = "{" + std::to_string(i); - accumulatedString += printStarsPerNode(*_root->Children[i], prefix); + for (int i = 0; i < 8; i++) { + const std::string prefix = "{" + std::to_string(i); + accumulatedString += printStarsPerNode(*_root->children[i], prefix); } - LINFO(fmt::format("Number of stars per node: \n{}", accumulatedString)); - LINFO(fmt::format("Number of leaf nodes: {}", std::to_string(_numLeafNodes))); - LINFO(fmt::format("Number of inner nodes: {}", std::to_string(_numInnerNodes))); - LINFO(fmt::format("Depth of tree: {}", std::to_string(_totalDepth))); + LINFO(std::format("Number of stars per node: \n{}", accumulatedString)); + LINFO(std::format("Number of leaf nodes: {}", std::to_string(_numLeafNodes))); + LINFO(std::format("Number of inner nodes: {}", std::to_string(_numInnerNodes))); + LINFO(std::format("Depth of tree: {}", std::to_string(_totalDepth))); } void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, @@ -152,23 +171,23 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, { // If entire dataset fits in RAM then load the entire dataset asynchronously now. - // Nodes will be rendered when they've been made available. + // Nodes will be rendered when they've been made available if (_datasetFitInMemory) { - // Only traverse Octree once! + // Only traverse Octree once if (_parentNodeOfCamera == 8) { // Fetch first layer of children fetchChildrenNodes(*_root, 0); - for (int i = 0; i < 8; ++i) { - // Check so branch doesn't have a single layer. - if (_root->Children[i]->isLeaf) { + for (const std::shared_ptr& child : _root->children) { + // Check so branch doesn't have a single layer + if (child->isLeaf) { continue; } // Use multithreading to load files and detach thread from main execution // so it can execute independently. Thread will be destroyed when - // finished! - std::thread([this, n = _root->Children[i]]() { + // finished + std::thread([this, n = child]() { fetchChildrenNodes(*n, -1); }).detach(); } @@ -177,15 +196,13 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, return; } - // Get leaf node in which the camera resides. - glm::vec3 fCameraPos = static_cast( - cameraPos / (1000.0 * distanceconstants::Parsec) - ); - size_t idx = getChildIndex(fCameraPos.x, fCameraPos.y, fCameraPos.z); - std::shared_ptr node = _root->Children[idx]; + // Get leaf node in which the camera resides + const glm::vec3 fCameraPos = cameraPos / (1000.0 * distanceconstants::Parsec); + size_t idx = childIndex(fCameraPos.x, fCameraPos.y, fCameraPos.z); + std::shared_ptr node = _root->children[idx]; while (!node->isLeaf) { - idx = getChildIndex( + idx = childIndex( fCameraPos.x, fCameraPos.y, fCameraPos.z, @@ -193,25 +210,25 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, node->originY, node->originZ ); - node = node->Children[idx]; + node = node->children[idx]; } - unsigned long long leafId = node->octreePositionIndex; - unsigned long long firstParentId = leafId / 10; + const unsigned long long leafId = node->octreePositionIndex; + const unsigned long long firstParentId = leafId / 10; - // Return early if camera resides in the same first parent as before! - // Otherwise camera has moved and may need to load more nodes! + // Return early if camera resides in the same first parent as before. + // Otherwise camera has moved and may need to load more nodes if (_parentNodeOfCamera == firstParentId) { return; } _parentNodeOfCamera = firstParentId; // Each parent level may be root, make sure to propagate it in that case! - unsigned long long secondParentId = (firstParentId == 8) ? 8 : leafId / 100; - unsigned long long thirdParentId = (secondParentId == 8) ? 8 : leafId / 1000; - unsigned long long fourthParentId = (thirdParentId == 8) ? 8 : leafId / 10000; - unsigned long long fifthParentId = (fourthParentId == 8) ? 8 : leafId / 100000; + const unsigned long long secondParentId = (firstParentId == 8) ? 8 : leafId / 100; + const unsigned long long thirdParentId = (secondParentId == 8) ? 8 : leafId / 1000; + const unsigned long long fourthParentId = (thirdParentId == 8) ? 8 : leafId / 10000; + const unsigned long long fifthParentId = (fourthParentId == 8) ? 8 : leafId / 100000; - // Get the number of levels to fetch from user input. + // Get the number of levels to fetch from user input int additionalLevelsToFetch = additionalNodes.y; // Get more descendants when closer to root. @@ -219,11 +236,11 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, additionalLevelsToFetch++; } - // Get the 3^3 closest parents and load all their (eventual) children. + // Get the 3^3 closest parents and load all their (eventual) children for (int x = -1; x <= 1; x += 1) { for (int y = -2; y <= 2; y += 2) { for (int z = -4; z <= 4; z += 4) { - // Fetch all stars the 216 closest leaf nodes. + // Fetch all stars the 216 closest leaf nodes findAndFetchNeighborNode( firstParentId, x, @@ -231,7 +248,7 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, z, additionalLevelsToFetch ); - // Fetch LOD stars from 208 parents one and two layer(s) up. + // Fetch LOD stars from 208 parents one and two layer(s) up if (x != 0 || y != 0 || z != 0) { if (additionalNodes.x > 0) { findAndFetchNeighborNode( @@ -274,14 +291,14 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, } } - // Check if we should remove any nodes from RAM. - long long tenthOfRamBudget = _maxCpuRamBudget / 10; + // Check if we should remove any nodes from RAM + const long long tenthOfRamBudget = _maxCpuRamBudget / 10; if (_cpuRamBudget < tenthOfRamBudget) { - long long bytesToTenthOfRam = tenthOfRamBudget - _cpuRamBudget; + const long long bytesToTenthOfRam = tenthOfRamBudget - _cpuRamBudget; size_t nNodesToRemove = static_cast(bytesToTenthOfRam / chunkSizeInBytes); std::vector nodesToRemove; while (nNodesToRemove > 0) { - // Dequeue nodes that were least recently fetched by findAndFetchNeighborNode. + // Dequeue nodes that were least recently fetched by findAndFetchNeighborNode nodesToRemove.push_back(_leastRecentlyFetchedNodes.front()); _leastRecentlyFetchedNodes.pop(); nNodesToRemove--; @@ -299,7 +316,7 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i unsigned long long parentId = firstParentId; std::stack indexStack; - // Fetch first layer children if we're already at root. + // Fetch first layer children if we're already at root if (parentId == 8) { fetchChildrenNodes(*_root, 0); return; @@ -312,7 +329,7 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i int dy = (nodeIndex % 4 < 2) ? 2 : -2; int dz = (nodeIndex < 4) ? 4 : -4; - // Determine if we need to switch any side (find a higher common parent). + // Determine if we need to switch any side (find a higher common parent) bool needToSwitchX = (x == dx); bool needToSwitchY = (y == dy); bool needToSwitchZ = (z == dz); @@ -327,7 +344,7 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i z = -z; } - // Update node index and store it at the back of our stack. + // Update node index and store it at the back of our stack nodeIndex += x + y + z; indexStack.push(nodeIndex); parentId /= 10; @@ -364,29 +381,29 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i } // Take care of edge cases. If we got to the root but still need to switch to a - // common parent then no neighbor exists in that direction. + // common parent then no neighbor exists in that direction if (needToSwitchX || needToSwitchY || needToSwitchZ) { return; } - // Continue to root if we didn't reach it. + // Continue to root if we didn't reach it while (parentId != 8) { nodeIndex = parentId % 10; indexStack.push(nodeIndex); parentId /= 10; } - // Traverse to that parent node (as long as such a child exists!). + // Traverse to that parent node (as long as such a child exists!) std::shared_ptr node = _root; - while (!indexStack.empty() && !node->Children[indexStack.top()]->isLeaf) { - node = node->Children[indexStack.top()]; + while (!indexStack.empty() && !node->children[indexStack.top()]->isLeaf) { + node = node->children[indexStack.top()]; node->hasLoadedDescendant = true; indexStack.pop(); } // Fetch all children nodes from found parent. Use multithreading to load files // asynchronously! Detach thread from main execution so it can execute independently. - // Thread will then be destroyed when it has finished! + // Thread will then be destroyed when it has finished std::thread([this, node, additionalLevelsToFetch]() { fetchChildrenNodes(*node, additionalLevelsToFetch); }).detach(); @@ -402,30 +419,30 @@ std::map> OctreeManager::traverseData(const glm::dmat4& bool innerRebuild = false; _minTotalPixelsLod = lodPixelThreshold; - // Reclaim indices from previous render call. + // Reclaim indices from previous render call for (auto removedKey = _removedKeysInPrevCall.rbegin(); removedKey != _removedKeysInPrevCall.rend(); ++removedKey) { - // Uses a reverse loop to try to decrease the biggest chunk. + // Uses a reverse loop to try to decrease the biggest chunk if (*removedKey == static_cast(_biggestChunkIndexInUse) - 1) { _biggestChunkIndexInUse = *removedKey; - LDEBUG(fmt::format( + LDEBUG(std::format( "Decreased size to: {} Free Spots in VBO: {}", _biggestChunkIndexInUse, _freeSpotsInBuffer.size() )); } _freeSpotsInBuffer.push(*removedKey); } - // Clear cache of removed keys before next render call. + // Clear cache of removed keys before next render call if (!_removedKeysInPrevCall.empty()) { _removedKeysInPrevCall.clear(); } - // Rebuild VBO from scratch if we're not using most of it but have a high max index. + // Rebuild VBO from scratch if we're not using most of it but have a high max index if ((_biggestChunkIndexInUse > _maxStackSize * 4 / 5) && (_freeSpotsInBuffer.size() > _maxStackSize * 5 / 6)) { - LDEBUG(fmt::format( + LDEBUG(std::format( "Rebuilding VBO. Biggest Chunk: {} 4/5: {} FreeSpotsInVBO: {} 5/6: {}", _biggestChunkIndexInUse, _maxStackSize * 4 / 5, _freeSpotsInBuffer.size(), _maxStackSize * 5 / 6 @@ -434,26 +451,26 @@ std::map> OctreeManager::traverseData(const glm::dmat4& innerRebuild = true; } - // Check if entire tree is too small to see, and if so remove it. + // Check if entire tree is too small to see, and if so remove it std::vector corners(8); - float fMaxDist = static_cast(MAX_DIST); - for (int i = 0; i < 8; ++i) { - float x = (i % 2 == 0) ? fMaxDist : -fMaxDist; - float y = (i % 4 < 2) ? fMaxDist : -fMaxDist; - float z = (i < 4) ? fMaxDist : -fMaxDist; - glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; + const float fMaxDist = static_cast(MAX_DIST); + for (int i = 0; i < 8; i++) { + const float x = (i % 2 == 0) ? fMaxDist : -fMaxDist; + const float y = (i % 4 < 2) ? fMaxDist : -fMaxDist; + const float z = (i < 4) ? fMaxDist : -fMaxDist; + const glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; corners[i] = glm::dvec4(pos, 1.0); } if (!_culler->isVisible(corners, mvp)) { return renderData; } - glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); - float totalPixels = nodeSize.x * nodeSize.y; + const glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); + const float totalPixels = nodeSize.x * nodeSize.y; if (totalPixels < _minTotalPixelsLod * 2) { - // Remove LOD from first layer of children. - for (int i = 0; i < 8; ++i) { + // Remove LOD from first layer of children + for (const std::shared_ptr& child : _root->children) { std::map> tmpData = removeNodeFromCache( - *_root->Children[i], + *child, deltaStars ); renderData.insert(tmpData.begin(), tmpData.end()); @@ -461,13 +478,13 @@ std::map> OctreeManager::traverseData(const glm::dmat4& return renderData; } - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { if (i < _traversedBranchesInRenderCall) { continue; } std::map> tmpData = checkNodeIntersection( - *_root->Children[i], + *_root->children[i], mvp, screenSize, deltaStars, @@ -475,44 +492,42 @@ std::map> OctreeManager::traverseData(const glm::dmat4& ); // Avoid freezing when switching render mode for large datasets by only fetching - // one branch at a time when rebuilding buffer. + // one branch at a time when rebuilding buffer if (_rebuildBuffer) { - //renderData = std::move(tmpData); _traversedBranchesInRenderCall++; - //break; } // Observe that if there exists identical keys in renderData then those values in - // tmpData will be ignored! Thus we store the removed keys until next render call! + // tmpData will be ignored! Thus we store the removed keys until next render call renderData.insert(tmpData.begin(), tmpData.end()); } if (_rebuildBuffer) { if (_useVBO) { - // We need to overwrite bigger indices that had data before! No need for SSBO. + // We need to overwrite bigger indices that had data before! No need for SSBO std::map> idxToRemove; - for (int idx : _removedKeysInPrevCall) { + for (const int idx : _removedKeysInPrevCall) { idxToRemove[idx] = std::vector(); } // This will only insert indices that doesn't already exist in map - // (i.e. > biggestIdx). + // (i.e. > biggestIdx) renderData.insert(idxToRemove.begin(), idxToRemove.end()); } if (innerRebuild) { deltaStars = 0; } - // Clear potential removed keys for both VBO and SSBO! + // Clear potential removed keys for both VBO and SSBO _removedKeysInPrevCall.clear(); - LDEBUG(fmt::format( + LDEBUG(std::format( "After rebuilding branch {} - Biggest chunk: {} Free spots in buffer: {}", _traversedBranchesInRenderCall, _biggestChunkIndexInUse, _freeSpotsInBuffer.size() )); - // End rebuild when all branches has been fetched. + // End rebuild when all branches has been fetched if (_traversedBranchesInRenderCall == 8) { _rebuildBuffer = false; _traversedBranchesInRenderCall = 0; @@ -524,21 +539,21 @@ std::map> OctreeManager::traverseData(const glm::dmat4& std::vector OctreeManager::getAllData(gaia::RenderMode mode) { std::vector fullData; - for (size_t i = 0; i < 8; ++i) { - std::vector tmpData = getNodeData(*_root->Children[i], mode); + for (const std::shared_ptr& child : _root->children) { + std::vector tmpData = getNodeData(*child, mode); fullData.insert(fullData.end(), tmpData.begin(), tmpData.end()); } return fullData; } void OctreeManager::clearAllData(int branchIndex) { - // Don't clear everything if not needed. + // Don't clear everything if not needed if (branchIndex != -1) { - clearNodeData(*_root->Children[branchIndex]); + clearNodeData(*_root->children[branchIndex]); } else { - for (size_t i = 0; i < 8; ++i) { - clearNodeData(*_root->Children[i]); + for (const std::shared_ptr& child : _root->children) { + clearNodeData(*child); } } } @@ -551,16 +566,16 @@ void OctreeManager::writeToFile(std::ofstream& outFileStream, bool writeData) { ); outFileStream.write(reinterpret_cast(&MAX_DIST), sizeof(int32_t)); - // Use pre-traversal (Morton code / Z-order). - for (size_t i = 0; i < 8; ++i) { - writeNodeToFile(outFileStream, *_root->Children[i], writeData); + // Use pre-traversal (Morton code / Z-order) + for (const std::shared_ptr& child : _root->children) { + writeNodeToFile(outFileStream, *child, writeData); } } void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, const OctreeNode& node, bool writeData) { - // Write node structure. + // Write node structure bool isLeaf = node.isLeaf; int32_t numStars = static_cast(node.numStars); outFileStream.write(reinterpret_cast(&isLeaf), sizeof(bool)); @@ -572,7 +587,7 @@ void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, const OctreeNo nodeData.insert(nodeData.end(), node.colData.begin(), node.colData.end()); nodeData.insert(nodeData.end(), node.velData.begin(), node.velData.end()); int32_t nDataSize = static_cast(nodeData.size()); - size_t nBytes = nDataSize * sizeof(nodeData[0]); + const size_t nBytes = nDataSize * sizeof(float); outFileStream.write(reinterpret_cast(&nDataSize), sizeof(int32_t)); if (nDataSize > 0) { @@ -580,10 +595,10 @@ void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, const OctreeNo } } - // Write children to file (in Morton order) if we're in an inner node. + // Write children to file (in Morton order) if we're in an inner node if (!node.isLeaf) { - for (size_t i = 0; i < 8; ++i) { - writeNodeToFile(outFileStream, *node.Children[i], writeData); + for (const std::shared_ptr& child : node.children) { + writeNodeToFile(outFileStream, *child, writeData); } } } @@ -592,9 +607,9 @@ int OctreeManager::readFromFile(std::ifstream& inFileStream, bool readData, const std::string& folderPath) { int nStarsRead = 0; - int oldMaxdist = static_cast(MAX_DIST); + const int oldMaxdist = static_cast(MAX_DIST); - // If we're not reading data then we need to stream from files later on. + // If we're not reading data then we need to stream from files later on _streamOctree = !readData; if (_streamOctree) { _streamFolderPath = folderPath; @@ -605,24 +620,24 @@ int OctreeManager::readFromFile(std::ifstream& inFileStream, bool readData, inFileStream.read(reinterpret_cast(&MAX_STARS_PER_NODE), sizeof(int32_t)); inFileStream.read(reinterpret_cast(&MAX_DIST), sizeof(int32_t)); - LDEBUG(fmt::format( + LDEBUG(std::format( "Max stars per node in read Octree: {} - Radius of root layer: {}", MAX_STARS_PER_NODE, MAX_DIST )); - // Octree Manager root halfDistance must be updated before any nodes are created! + // Octree Manager root halfDistance must be updated before any nodes are created if (static_cast(MAX_DIST) != oldMaxdist) { - for (size_t i = 0; i < 8; ++i) { - _root->Children[i]->halfDimension = MAX_DIST / 2.f; - _root->Children[i]->originX = (i % 2 == 0) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; - _root->Children[i]->originY = (i % 4 < 2) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; - _root->Children[i]->originZ = (i < 4) ? - _root->Children[i]->halfDimension : - -_root->Children[i]->halfDimension; + for (size_t i = 0; i < 8; i++) { + _root->children[i]->halfDimension = MAX_DIST / 2.f; + _root->children[i]->originX = (i % 2 == 0) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; + _root->children[i]->originY = (i % 4 < 2) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; + _root->children[i]->originZ = (i < 4) ? + _root->children[i]->halfDimension : + -_root->children[i]->halfDimension; } } @@ -630,9 +645,9 @@ int OctreeManager::readFromFile(std::ifstream& inFileStream, bool readData, LERROR("Read file doesn't have the same structure of render parameters"); } - // Use the same technique to construct octree from file. - for (size_t i = 0; i < 8; ++i) { - nStarsRead += readNodeFromFile(inFileStream, *_root->Children[i], readData); + // Use the same technique to construct octree from file + for (const std::shared_ptr& child : _root->children) { + nStarsRead += readNodeFromFile(inFileStream, *child, readData); } return nStarsRead; } @@ -641,7 +656,7 @@ int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, OctreeNode& nod bool readData) { // Read node structure. - bool isLeaf; + bool isLeaf = false; int32_t numStars = 0; inFileStream.read(reinterpret_cast(&isLeaf), sizeof(bool)); @@ -656,45 +671,45 @@ int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, OctreeNode& nod inFileStream.read(reinterpret_cast(&nDataSize), sizeof(int32_t)); if (nDataSize > 0) { - std::vector fetchedData(nDataSize, 0.0f); - size_t nBytes = nDataSize * sizeof(fetchedData[0]); + std::vector fetchedData(nDataSize, 0.f); + const size_t nBytes = nDataSize * sizeof(float); - inFileStream.read(reinterpret_cast(&fetchedData[0]), nBytes); + inFileStream.read(reinterpret_cast(fetchedData.data()), nBytes); - int starsInNode = static_cast(nDataSize / _valuesPerStar); - auto posEnd = fetchedData.begin() + (starsInNode * POS_SIZE); - auto colEnd = posEnd + (starsInNode * COL_SIZE); - auto velEnd = colEnd + (starsInNode * VEL_SIZE); + const int starsInNode = static_cast(nDataSize / _valuesPerStar); + const auto posEnd = fetchedData.begin() + (starsInNode * POS_SIZE); + const auto colEnd = posEnd + (starsInNode * COL_SIZE); + const auto velEnd = colEnd + (starsInNode * VEL_SIZE); node.posData = std::vector(fetchedData.begin(), posEnd); node.colData = std::vector(posEnd, colEnd); node.velData = std::vector(colEnd, velEnd); } } - // Create children if we're in an inner node and read from the corresponding nodes. + // Create children if we're in an inner node and read from the corresponding nodes if (!node.isLeaf) { numStars = 0; createNodeChildren(node); - for (size_t i = 0; i < 8; ++i) { - numStars += readNodeFromFile(inFileStream, *node.Children[i], readData); + for (const std::shared_ptr& child : node.children) { + numStars += readNodeFromFile(inFileStream, *child, readData); } } - // Return the number of stars in the entire branch, no need to check children. + // Return the number of stars in the entire branch, no need to check children return numStars; } void OctreeManager::writeToMultipleFiles(const std::string& outFolderPath, size_t branchIndex) { - // Write entire branch to disc, with one file per node. - std::string outFilePrefix = outFolderPath + std::to_string(branchIndex); - // More threads doesn't make it much faster, disk speed still the limiter. - writeNodeToMultipleFiles(outFilePrefix, *_root->Children[branchIndex], false); + // Write entire branch to disc, with one file per node + const std::string outFilePrefix = outFolderPath + std::to_string(branchIndex); + // More threads doesn't make it much faster, disk speed still the limiter + writeNodeToMultipleFiles(outFilePrefix, *_root->children[branchIndex], false); // Clear all data in branch. - LINFO(fmt::format("Clear all data from branch {} in octree", branchIndex)); - clearNodeData(*_root->Children[branchIndex]); + LINFO(std::format("Clear all data from branch {} in octree", branchIndex)); + clearNodeData(*_root->children[branchIndex]); } void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, @@ -704,8 +719,8 @@ void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, std::vector nodeData = node.posData; nodeData.insert(nodeData.end(), node.colData.begin(), node.colData.end()); nodeData.insert(nodeData.end(), node.velData.begin(), node.velData.end()); - int32_t nDataSize = static_cast(nodeData.size()); - size_t nBytes = nDataSize * sizeof(nodeData[0]); + const int32_t nDataSize = static_cast(nodeData.size()); + const size_t nBytes = nDataSize * sizeof(nodeData[0]); // Only open output stream if we have any values to write. if (nDataSize > 0) { @@ -723,26 +738,26 @@ void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, outFileStream.close(); } else { - LERROR(fmt::format("Error opening file: {} as output data file", outPath)); + LERROR(std::format("Error opening file '{}' as output data file", outPath)); } } - // Recursively write children to file (in Morton order) if we're in an inner node. + // Recursively write children to file (in Morton order) if we're in an inner node if (!node.isLeaf) { std::vector writeThreads(8); - for (size_t i = 0; i < 8; ++i) { - std::string newOutFilePrefix = outFilePrefix + std::to_string(i); + for (size_t i = 0; i < 8; i++) { + const std::string newOutFilePrefix = outFilePrefix + std::to_string(i); if (threadWrites) { - // Divide writing to new threads to speed up the process. + // Divide writing to new threads to speed up the process std::thread t( - [this, newOutFilePrefix, n = node.Children[i]]() { + [this, newOutFilePrefix, n = node.children[i]]() { writeNodeToMultipleFiles(newOutFilePrefix, *n, false); } ); writeThreads[i] = std::move(t); } else { - writeNodeToMultipleFiles(newOutFilePrefix, *node.Children[i], false); + writeNodeToMultipleFiles(newOutFilePrefix, *node.children[i], false); } } if (threadWrites) { @@ -757,62 +772,61 @@ void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, void OctreeManager::fetchChildrenNodes(OctreeNode& parentNode, int additionalLevelsToFetch) { - // Lock node to make sure nobody else are trying to load the same children. - std::lock_guard lock(parentNode.loadingLock); + // Lock node to make sure nobody else are trying to load the same children + const std::lock_guard lock(parentNode.loadingLock); - for (int i = 0; i < 8; ++i) { + for (const std::shared_ptr& child : parentNode.children) { // Fetch node data if we're streaming and it doesn't exist in RAM yet. // (As long as there is any RAM budget left and node actually has any data!) - if (!parentNode.Children[i]->isLoaded && - (parentNode.Children[i]->numStars > 0) && - _cpuRamBudget > static_cast(parentNode.Children[i]->numStars - * (POS_SIZE + COL_SIZE + VEL_SIZE) * 4)) + if (!child->isLoaded && (child->numStars > 0) && + _cpuRamBudget > static_cast(child->numStars + * (POS_SIZE + COL_SIZE + VEL_SIZE) * 4)) { - fetchNodeDataFromFile(*parentNode.Children[i]); + fetchNodeDataFromFile(*child); } - // Fetch all Children's Children if recursive is set to true! - if (additionalLevelsToFetch != 0 && !parentNode.Children[i]->isLeaf) { - fetchChildrenNodes(*parentNode.Children[i], --additionalLevelsToFetch); + // Fetch all Children's Children if recursive is set to true + if (additionalLevelsToFetch != 0 && !child->isLeaf) { + fetchChildrenNodes(*child, --additionalLevelsToFetch); } } } void OctreeManager::fetchNodeDataFromFile(OctreeNode& node) { - // Remove root ID ("8") from index before loading file. + // Remove root ID ("8") from index before loading file std::string posId = std::to_string(node.octreePositionIndex); posId.erase(posId.begin()); - std::string inFilePath = _streamFolderPath + posId + BINARY_SUFFIX; + const std::string inFilePath = _streamFolderPath + posId + BINARY_SUFFIX; std::ifstream inFileStream(inFilePath, std::ifstream::binary); // LINFO("Fetch node data file: " + inFilePath); if (inFileStream.good()) { - // Read node data. + // Read node data int32_t nDataSize = 0; - // Octree knows if we have any data in this node = it exists. + // Octree knows if we have any data in this node = it exists // Otherwise don't call this function! inFileStream.read(reinterpret_cast(&nDataSize), sizeof(int32_t)); std::vector readData(nDataSize, 0.f); - int nBytes = nDataSize * sizeof(readData[0]); + const int nBytes = nDataSize * sizeof(float); if (nDataSize > 0) { - inFileStream.read(reinterpret_cast(&readData[0]), nBytes); + inFileStream.read(reinterpret_cast(readData.data()), nBytes); } - int starsInNode = static_cast(nDataSize / _valuesPerStar); - auto posEnd = readData.begin() + (starsInNode * POS_SIZE); - auto colEnd = posEnd + (starsInNode * COL_SIZE); - auto velEnd = colEnd + (starsInNode * VEL_SIZE); + const int starsInNode = static_cast(nDataSize / _valuesPerStar); + const auto posEnd = readData.begin() + (starsInNode * POS_SIZE); + const auto colEnd = posEnd + (starsInNode * COL_SIZE); + const auto velEnd = colEnd + (starsInNode * VEL_SIZE); node.posData = std::vector(readData.begin(), posEnd); node.colData = std::vector(posEnd, colEnd); node.velData = std::vector(colEnd, velEnd); - // Keep track of nodes that are loaded and update CPU RAM budget. + // Keep track of nodes that are loaded and update CPU RAM budget node.isLoaded = true; if (!_datasetFitInMemory) { - std::lock_guard g(_leastRecentlyFetchedNodesMutex); + const std::lock_guard g(_leastRecentlyFetchedNodesMutex); _leastRecentlyFetchedNodes.push(node.octreePositionIndex); } _cpuRamBudget -= nBytes; @@ -830,7 +844,7 @@ void OctreeManager::removeNodesFromRam( for (unsigned long long nodePosIndex : nodesToRemove) { std::stack indexStack; while (nodePosIndex != 8) { - int nodeIndex = nodePosIndex % 10; + const int nodeIndex = nodePosIndex % 10; indexStack.push(nodeIndex); nodePosIndex /= 10; } @@ -840,7 +854,7 @@ void OctreeManager::removeNodesFromRam( std::vector> ancestors; while (!indexStack.empty()) { ancestors.push_back(node); - node = node->Children[indexStack.top()]; + node = node->children[indexStack.top()]; indexStack.pop(); } removeNode(*node); @@ -850,13 +864,13 @@ void OctreeManager::removeNodesFromRam( } void OctreeManager::removeNode(OctreeNode& node) { - // Lock node to make sure nobody else is trying to access it while removing. - std::lock_guard lock(node.loadingLock); + // Lock node to make sure nobody else is trying to access it while removing + const std::lock_guard lock(node.loadingLock); - int nBytes = static_cast( + const int nBytes = static_cast( node.numStars * _valuesPerStar * sizeof(node.posData[0]) ); - // Keep track of which nodes that are loaded and update CPU RAM budget. + // Keep track of which nodes that are loaded and update CPU RAM budget node.isLoaded = false; _cpuRamBudget += nBytes; @@ -874,27 +888,27 @@ void OctreeManager::propagateUnloadedNodes( { std::shared_ptr parentNode = ancestorNodes.back(); while (parentNode->octreePositionIndex != 8) { - // Check if any children of inner node is still loaded, or has loaded descendants. - if (parentNode->Children[0]->isLoaded || parentNode->Children[1]->isLoaded || - parentNode->Children[2]->isLoaded || parentNode->Children[3]->isLoaded || - parentNode->Children[4]->isLoaded || parentNode->Children[5]->isLoaded || - parentNode->Children[6]->isLoaded || parentNode->Children[7]->isLoaded || - parentNode->Children[0]->hasLoadedDescendant || - parentNode->Children[1]->hasLoadedDescendant || - parentNode->Children[2]->hasLoadedDescendant || - parentNode->Children[3]->hasLoadedDescendant || - parentNode->Children[4]->hasLoadedDescendant || - parentNode->Children[5]->hasLoadedDescendant || - parentNode->Children[6]->hasLoadedDescendant || - parentNode->Children[7]->hasLoadedDescendant) + // Check if any children of inner node is still loaded, or has loaded descendants + if (parentNode->children[0]->isLoaded || parentNode->children[1]->isLoaded || + parentNode->children[2]->isLoaded || parentNode->children[3]->isLoaded || + parentNode->children[4]->isLoaded || parentNode->children[5]->isLoaded || + parentNode->children[6]->isLoaded || parentNode->children[7]->isLoaded || + parentNode->children[0]->hasLoadedDescendant || + parentNode->children[1]->hasLoadedDescendant || + parentNode->children[2]->hasLoadedDescendant || + parentNode->children[3]->hasLoadedDescendant || + parentNode->children[4]->hasLoadedDescendant || + parentNode->children[5]->hasLoadedDescendant || + parentNode->children[6]->hasLoadedDescendant || + parentNode->children[7]->hasLoadedDescendant) { return; } - // Else all children has been unloaded and we can update parent flag. + // Else all children has been unloaded and we can update parent flag parentNode->hasLoadedDescendant = false; // LINFO("Removed ancestor: " + std::to_string(parentNode->octreePositionIndex)); - // Propagate change upwards. + // Propagate change upwards ancestorNodes.pop_back(); parentNode = ancestorNodes.back(); } @@ -940,27 +954,11 @@ bool OctreeManager::isRebuildOngoing() const { return _rebuildBuffer; } -size_t OctreeManager::getChildIndex(float posX, float posY, float posZ, float origX, - float origY, float origZ) -{ - size_t index = 0; - if (posX < origX) { - index += 1; - } - if (posY < origY) { - index += 2; - } - if (posZ < origZ) { - index += 4; - } - return index; -} - bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& starValues, int depth) { if (node.isLeaf && node.numStars < MAX_STARS_PER_NODE) { - // Node is a leaf and it's not yet full -> insert star. + // Node is a leaf and it's not yet full -> insert star storeStarData(node, starValues); if (depth > static_cast(_totalDepth)) { @@ -970,10 +968,10 @@ bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& sta } else if (node.isLeaf) { // Too many stars in leaf node, subdivide into 8 new nodes. - // Create children and clean up parent. + // Create children and clean up parent createNodeChildren(node); - // Distribute stars from parent node into children. + // Distribute stars from parent node into children for (size_t n = 0; n < MAX_STARS_PER_NODE; ++n) { // Position data. auto posBegin = node.posData.begin() + n * POS_SIZE; @@ -988,8 +986,8 @@ bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& sta auto velEnd = velBegin + VEL_SIZE; tmpValues.insert(tmpValues.end(), velBegin, velEnd); - // Find out which child that will inherit the data and store it. - size_t index = getChildIndex( + // Find out which child that will inherit the data and store it + const size_t index = childIndex( tmpValues[0], tmpValues[1], tmpValues[2], @@ -997,17 +995,17 @@ bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& sta node.originY, node.originZ ); - insertInNode(*node.Children[index], tmpValues, depth); + insertInNode(*node.children[index], tmpValues, depth); } // Sort magnitudes in inner node. - // (The last value will be used as comparison for what to store in LOD cache.) + // (The last value will be used as comparison for what to store in LOD cache) std::sort(node.magOrder.begin(), node.magOrder.end()); } // Node is an inner node, keep recursion going. - // This will also take care of the new star when a subdivision has taken place. - size_t index = getChildIndex( + // This will also take care of the new star when a subdivision has taken place + const size_t index = childIndex( starValues[0], starValues[1], starValues[2], @@ -1022,11 +1020,11 @@ bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& sta storeStarData(node, starValues); } - return insertInNode(*node.Children[index], starValues, ++depth); + return insertInNode(*node.children[index], starValues, ++depth); } void OctreeManager::sliceNodeLodCache(OctreeNode& node) { - // Slice stored LOD data in inner nodes. + // Slice stored LOD data in inner nodes if (!node.isLeaf) { // Sort by magnitude. Inverse relation (i.e. a lower magnitude means a brighter // star!) @@ -1036,7 +1034,7 @@ void OctreeManager::sliceNodeLodCache(OctreeNode& node) { std::vector tmpPos; std::vector tmpCol; std::vector tmpVel; - // Ordered map contain the MAX_STARS_PER_NODE brightest stars in all children! + // Ordered map contain the MAX_STARS_PER_NODE brightest stars in all children for (auto const& [absMag, placement] : node.magOrder) { auto posBegin = node.posData.begin() + placement * POS_SIZE; auto colBegin = node.colData.begin() + placement * COL_SIZE; @@ -1050,22 +1048,23 @@ void OctreeManager::sliceNodeLodCache(OctreeNode& node) { node.velData = std::move(tmpVel); node.numStars = node.magOrder.size(); // = MAX_STARS_PER_NODE - for (int i = 0; i < 8; ++i) { - sliceNodeLodCache(*node.Children[i]); + for (const std::shared_ptr& child : node.children) { + sliceNodeLodCache(*child); } } } -void OctreeManager::storeStarData(OctreeNode& node, const std::vector& starValues) +void OctreeManager::storeStarData(OctreeNode& node, + const std::vector& starValues) const { // Insert star data at the back of vectors and store a vector with pairs consisting of - // star magnitude and insert index for later sorting and slicing of LOD cache. - float mag = starValues[POS_SIZE]; + // star magnitude and insert index for later sorting and slicing of LOD cache + const float mag = starValues[POS_SIZE]; node.magOrder.insert(node.magOrder.end(), std::make_pair(mag, node.numStars)); node.numStars++; // If LOD is growing too large then sort it and resize to [chunk size] to avoid too - // much RAM usage and increase threshold for adding new stars. + // much RAM usage and increase threshold for adding new stars if (node.magOrder.size() > MAX_STARS_PER_NODE * 2) { std::sort(node.magOrder.begin(), node.magOrder.end()); node.magOrder.resize(MAX_STARS_PER_NODE); @@ -1082,17 +1081,17 @@ std::string OctreeManager::printStarsPerNode(const OctreeNode& node, const std::string& prefix) const { - // Print both inner and leaf nodes. + // Print both inner and leaf nodes auto str = prefix + "} : " + std::to_string(node.numStars); if (node.isLeaf) { return str + " - [Leaf] \n"; } else { - str += fmt::format("LOD: {} - [Parent]\n", node.posData.size() / POS_SIZE); - for (int i = 0; i < 8; ++i) { + str += std::format("LOD: {} - [Parent]\n", node.posData.size() / POS_SIZE); + for (int i = 0; i < 8; i++) { auto pref = prefix + "->" + std::to_string(i); - str += printStarsPerNode(*node.Children[i], pref); + str += printStarsPerNode(*node.children[i], pref); } return str; } @@ -1106,9 +1105,9 @@ std::map> OctreeManager::checkNodeIntersection(OctreeNod { std::map> fetchedData; - // Calculate the corners of the node. + // Calculate the corners of the node std::vector corners(8); - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 8; i++) { const float x = (i % 2 == 0) ? node.originX + node.halfDimension : node.originX - node.halfDimension; @@ -1118,14 +1117,14 @@ std::map> OctreeManager::checkNodeIntersection(OctreeNod const float z = (i < 4) ? node.originZ + node.halfDimension : node.originZ - node.halfDimension; - glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; + const glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; corners[i] = glm::dvec4(pos, 1.0); } - // Check if node is visible from camera. If not then return early. + // Check if node is visible from camera. If not then return early if (!(_culler->isVisible(corners, mvp))) { // Check if this node or any of its children existed in cache previously. - // If so, then remove them from cache and add those indices to stack. + // If so, then remove them from cache and add those indices to stack fetchedData = removeNodeFromCache(node, deltaStars); return fetchedData; } @@ -1141,28 +1140,28 @@ std::map> OctreeManager::checkNodeIntersection(OctreeNod // Take care of inner nodes. if (!(node.isLeaf)) { - glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); - float totalPixels = nodeSize.x * nodeSize.y; + const glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); + const float totalPixels = nodeSize.x * nodeSize.y; // Check if we should return any LOD cache data. If we're streaming a big dataset // from files and inner node is visible and loaded, then it should be rendered // (as long as it doesn't have loaded children because then we should traverse to - // lowest loaded level and render it instead)! + // lowest loaded level and render it instead) if ((totalPixels < _minTotalPixelsLod) || (_streamOctree && !_datasetFitInMemory && node.isLoaded && !node.hasLoadedDescendant)) { // Get correct insert index from stack if node didn't exist already. Otherwise - // we will overwrite the old data. Key merging is not a problem here. + // we will overwrite the old data. Key merging is not a problem here if ((node.bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { - // Return empty if we couldn't claim a buffer stream index. + // Return empty if we couldn't claim a buffer stream index if (!updateBufferIndex(node)) { return fetchedData; } // We're in an inner node, remove indices from potential children in cache - for (int i = 0; i < 8; ++i) { + for (const std::shared_ptr& child : node.children) { std::map> tmpData = removeNodeFromCache( - *node.Children[i], + *child, deltaStars ); fetchedData.insert(tmpData.begin(), tmpData.end()); @@ -1178,11 +1177,11 @@ std::map> OctreeManager::checkNodeIntersection(OctreeNod return fetchedData; } } - // Return node data if node is a leaf. + // Return node data if node is a leaf else { - // If node already is in cache then skip it, otherwise store it. + // If node already is in cache then skip it, otherwise store it if ((node.bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { - // Return empty if we couldn't claim a buffer stream index. + // Return empty if we couldn't claim a buffer stream index if (!updateBufferIndex(node)) { return fetchedData; } @@ -1198,15 +1197,15 @@ std::map> OctreeManager::checkNodeIntersection(OctreeNod } // We're in a big, visible inner node -> remove it from cache if it existed. - // But not its children -> set recursive check to false. + // But not its children -> set recursive check to false fetchedData = removeNodeFromCache(node, deltaStars, false); // Recursively check if children should be rendered. - for (size_t i = 0; i < 8; ++i) { + for (const std::shared_ptr& child : node.children) { // Observe that if there exists identical keys in fetchedData then those values in - // tmpData will be ignored! Thus we store the removed keys until next render call! + // tmpData will be ignored! Thus we store the removed keys until next render call std::map> tmpData = checkNodeIntersection( - *node.Children[i], + *child, mvp, screenSize, deltaStars, @@ -1223,28 +1222,27 @@ std::map> OctreeManager::removeNodeFromCache(OctreeNode& { std::map> keysToRemove; - // If we're in rebuilding mode then there is no need to remove any nodes. - //if (_rebuildBuffer) return keysToRemove; + // If we're in rebuilding mode then there is no need to remove any nodes - // Check if this node was rendered == had a specified index. + // Check if this node was rendered == had a specified index if (node.bufferIndex != DEFAULT_INDEX) { - // Reclaim that index. We need to wait until next render call to use it again! + // Reclaim that index. We need to wait until next render call to use it again _removedKeysInPrevCall.insert(node.bufferIndex); - // Insert dummy node at offset index that should be removed from render. + // Insert dummy node at offset index that should be removed from render keysToRemove[node.bufferIndex] = std::vector(); - // Reset index and adjust stars removed this frame. + // Reset index and adjust stars removed this frame node.bufferIndex = DEFAULT_INDEX; deltaStars -= static_cast(node.numStars); } - // Check children recursively if we're in an inner node. + // Check children recursively if we're in an inner node if (!(node.isLeaf) && recursive) { - for (int i = 0; i < 8; ++i) { + for (const std::shared_ptr& child : node.children) { std::map> tmpData = removeNodeFromCache( - *node.Children[i], + *child, deltaStars ); keysToRemove.insert(tmpData.begin(), tmpData.end()); @@ -1256,74 +1254,71 @@ std::map> OctreeManager::removeNodeFromCache(OctreeNode& std::vector OctreeManager::getNodeData(const OctreeNode& node, gaia::RenderMode mode) { - // Return node data if node is a leaf. + // Return node data if node is a leaf if (node.isLeaf) { int dStars = 0; return constructInsertData(node, mode, dStars); } - // If we're not in a leaf, get data from all children recursively. + // If we're not in a leaf, get data from all children recursively std::vector nodeData; - for (size_t i = 0; i < 8; ++i) { - std::vector tmpData = getNodeData(*node.Children[i], mode); + for (const std::shared_ptr& child : node.children) { + std::vector tmpData = getNodeData(*child, mode); nodeData.insert(nodeData.end(), tmpData.begin(), tmpData.end()); } return nodeData; } void OctreeManager::clearNodeData(OctreeNode& node) { - // Clear data and its allocated memory. + // Clear data and its allocated memory node.posData.clear(); - node.posData.shrink_to_fit(); node.colData.clear(); - node.colData.shrink_to_fit(); node.velData.clear(); - node.velData.shrink_to_fit(); - // Clear magnitudes as well! + // Clear magnitudes as well //std::vector>().swap(node->magOrder); node.magOrder.clear(); if (!node.isLeaf) { - // Remove data from all children recursively. - for (size_t i = 0; i < 8; ++i) { - clearNodeData(*node.Children[i]); + // Remove data from all children recursively + for (const std::shared_ptr& child : node.children) { + clearNodeData(*child); } } } void OctreeManager::createNodeChildren(OctreeNode& node) { - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { _numLeafNodes++; - node.Children[i] = std::make_shared(); - node.Children[i]->isLeaf = true; - node.Children[i]->isLoaded = false; - node.Children[i]->hasLoadedDescendant = false; - node.Children[i]->bufferIndex = DEFAULT_INDEX; - node.Children[i]->octreePositionIndex = (node.octreePositionIndex * 10) + i; - node.Children[i]->numStars = 0; - node.Children[i]->posData = std::vector(); - node.Children[i]->colData = std::vector(); - node.Children[i]->velData = std::vector(); - node.Children[i]->magOrder = std::vector>(); - node.Children[i]->halfDimension = node.halfDimension / 2.f; + node.children[i] = std::make_shared(); + node.children[i]->isLeaf = true; + node.children[i]->isLoaded = false; + node.children[i]->hasLoadedDescendant = false; + node.children[i]->bufferIndex = DEFAULT_INDEX; + node.children[i]->octreePositionIndex = (node.octreePositionIndex * 10) + i; + node.children[i]->numStars = 0; + node.children[i]->posData = std::vector(); + node.children[i]->colData = std::vector(); + node.children[i]->velData = std::vector(); + node.children[i]->magOrder = std::vector>(); + node.children[i]->halfDimension = node.halfDimension / 2.f; - // Calculate new origin. - node.Children[i]->originX = node.originX; - node.Children[i]->originX += (i % 2 == 0) ? - node.Children[i]->halfDimension : - -node.Children[i]->halfDimension; - node.Children[i]->originY = node.originY; - node.Children[i]->originY += (i % 4 < 2) ? - node.Children[i]->halfDimension : - -node.Children[i]->halfDimension; - node.Children[i]->originZ = node.originZ; - node.Children[i]->originZ += (i < 4) ? - node.Children[i]->halfDimension : - -node.Children[i]->halfDimension; + // Calculate new origin + node.children[i]->originX = node.originX; + node.children[i]->originX += (i % 2 == 0) ? + node.children[i]->halfDimension : + -node.children[i]->halfDimension; + node.children[i]->originY = node.originY; + node.children[i]->originY += (i % 4 < 2) ? + node.children[i]->halfDimension : + -node.children[i]->halfDimension; + node.children[i]->originZ = node.originZ; + node.children[i]->originZ += (i < 4) ? + node.children[i]->halfDimension : + -node.children[i]->halfDimension; } - // Clean up parent. + // Clean up parent node.isLeaf = false; _numLeafNodes--; _numInnerNodes++; @@ -1331,26 +1326,26 @@ void OctreeManager::createNodeChildren(OctreeNode& node) { bool OctreeManager::updateBufferIndex(OctreeNode& node) { if (node.bufferIndex != DEFAULT_INDEX) { - // If we're rebuilding Buffer Index Cache then store indices to overwrite later. + // If we're rebuilding Buffer Index Cache then store indices to overwrite later _removedKeysInPrevCall.insert(node.bufferIndex); } - // Make sure node isn't loading/unloading as we're checking isLoaded flag. - std::lock_guard lock(node.loadingLock); + // Make sure node isn't loading/unloading as we're checking isLoaded flag + const std::lock_guard lock(node.loadingLock); // Return false if there are no more spots in our buffer, or if we're streaming and - // node isn't loaded yet, or if node doesn't have any stars. + // node isn't loaded yet, or if node doesn't have any stars if (_freeSpotsInBuffer.empty() || (_streamOctree && !node.isLoaded) || node.numStars == 0) { return false; } - // Get correct insert index from stack. + // Get correct insert index from stack node.bufferIndex = _freeSpotsInBuffer.top(); _freeSpotsInBuffer.pop(); - // Keep track of how many chunks are in use (ceiling). + // Keep track of how many chunks are in use (ceiling) if (_freeSpotsInBuffer.empty()) { _biggestChunkIndexInUse++; } @@ -1362,15 +1357,15 @@ bool OctreeManager::updateBufferIndex(OctreeNode& node) { std::vector OctreeManager::constructInsertData(const OctreeNode& node, gaia::RenderMode mode, - int& deltaStars) + int& deltaStars) const { - // Return early if node doesn't contain any stars! + // Return early if node doesn't contain any stars if (node.numStars == 0) { return std::vector(); } - // Fill chunk by appending zeroes to data so we overwrite possible earlier values. - // And more importantly so our attribute pointers knows where to read! + // Fill chunk by appending zeroes to data so we overwrite possible earlier values + // And more importantly so our attribute pointers knows where to read auto insertData = std::vector(node.posData.begin(), node.posData.end()); if (_useVBO) { insertData.resize(POS_SIZE * MAX_STARS_PER_NODE, 0.f); @@ -1390,7 +1385,7 @@ std::vector OctreeManager::constructInsertData(const OctreeNode& node, } } - // Update deltaStars. + // Update deltaStars deltaStars += static_cast(node.numStars); return insertData; } diff --git a/modules/gaia/rendering/octreemanager.h b/modules/gaia/rendering/octreemanager.h index 23fa61e2a9..05a56a5908 100644 --- a/modules/gaia/rendering/octreemanager.h +++ b/modules/gaia/rendering/octreemanager.h @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -41,7 +42,7 @@ class OctreeCuller; class OctreeManager { public: struct OctreeNode { - std::shared_ptr Children[8]; + std::array, 8> children; std::vector posData; std::vector colData; std::vector velData; @@ -201,12 +202,6 @@ private: const int DEFAULT_INDEX = -1; const std::string BINARY_SUFFIX = ".bin"; - /** - * \return the correct index of child node. Maps [1,1,1] to 0 and [-1,-1,-1] to 7. - */ - size_t getChildIndex(float posX, float posY, float posZ, float origX = 0.f, - float origY = 0.f, float origZ = 0.f); - /** * Private help function for `insert()`. Inserts star into node if leaf and * numStars < MAX_STARS_PER_NODE. If a leaf goes above the threshold it is subdivided @@ -228,7 +223,7 @@ private: * Private help function for `insertInNode()`. Stores star data in node and * keeps track of the brightest stars all children. */ - void storeStarData(OctreeNode& node, const std::vector& starValues); + void storeStarData(OctreeNode& node, const std::vector& starValues) const; /** * Private help function for `printStarsPerNode()`. @@ -301,7 +296,7 @@ private: * \return the data to be inserted */ std::vector constructInsertData(const OctreeNode& node, - gaia::RenderMode mode, int& deltaStars); + gaia::RenderMode mode, int& deltaStars) const; /** * Write a node to outFileStream. diff --git a/modules/gaia/rendering/renderablegaiastars.cpp b/modules/gaia/rendering/renderablegaiastars.cpp index b7175d4b21..c345b1f5f0 100644 --- a/modules/gaia/rendering/renderablegaiastars.cpp +++ b/modules/gaia/rendering/renderablegaiastars.cpp @@ -511,7 +511,7 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) _dataIsDirty = true; } else { - LWARNING(fmt::format("File not found: {}", _filePath.value())); + LWARNING(std::format("File not found: {}", _filePath.value())); } }); addProperty(_filePath); @@ -597,7 +597,7 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) if (_ssboData != 0) { glDeleteBuffers(1, &_ssboData); glGenBuffers(1, &_ssboData); - LDEBUG(fmt::format( + LDEBUG(std::format( "Re-generating Data Shader Storage Buffer Object id '{}'", _ssboData )); } @@ -606,7 +606,7 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) // available to always be consistant with previous call(s). GLint nDedicatedVidMemoryInKB = 0; glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &nDedicatedVidMemoryInKB); - float dedicatedVidMem = static_cast( + const float dedicatedVidMem = static_cast( static_cast(nDedicatedVidMemoryInKB) * 1024 ); @@ -648,17 +648,17 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) addProperty(_lastRow); if (p.columnNames.has_value()) { - ghoul::Dictionary tmpDict = dictionary.value( + const ghoul::Dictionary tmpDict = dictionary.value( ColumnNamesInfo.identifier ); // Ugly fix for ASCII sorting when there are more columns read than 10. std::set intKeys; - for (std::string_view key : tmpDict.keys()) { + for (const std::string_view key : tmpDict.keys()) { intKeys.insert(std::stoi(std::string(key))); } - for (int key : intKeys) { + for (const int key : intKeys) { _columnNames.push_back(tmpDict.value(std::to_string(key))); } @@ -876,13 +876,13 @@ void RenderableGaiaStars::initializeGL() { &nCurrentAvailMemoryInKB ); - LDEBUG(fmt::format( + LDEBUG(std::format( "nDedicatedVidMemoryKB: {} - nTotalMemoryKB: {} - nCurrentAvailMemoryKB: {}", nDedicatedVidMemoryInKB, nTotalMemoryInKB, nCurrentAvailMemoryInKB )); // Set ceiling for video memory to use in streaming. - float dedicatedVidMem = static_cast( + const float dedicatedVidMem = static_cast( static_cast(nDedicatedVidMemoryInKB) * 1024 ); // TODO: Need to fix what happens if we can't query! For now use 2 GB by default. @@ -891,15 +891,15 @@ void RenderableGaiaStars::initializeGL() { 2147483648; // Set ceiling for how much of the installed CPU RAM to use for streaming - long long installedRam = static_cast(CpuCap.installedMainMemory()) * - 1024 * 1024; + const long long installedRam = + static_cast(CpuCap.installedMainMemory()) * 1024 * 1024; // TODO: What to do if we can't query? As for now we use 4 GB by default. _cpuRamBudgetInBytes = installedRam > 0 ? static_cast(static_cast(installedRam) * _maxCpuMemoryPercent) : 4294967296; _cpuRamBudgetProperty.setMaxValue(static_cast(_cpuRamBudgetInBytes)); - LDEBUG(fmt::format( + LDEBUG(std::format( "GPU Memory Budget (bytes): {} - CPU RAM Budget (bytes): {}", _gpuMemoryBudgetInBytes, _cpuRamBudgetInBytes )); @@ -958,18 +958,18 @@ void RenderableGaiaStars::deinitializeGL() { void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { checkGlErrors("Before render"); - // Save current FBO. - GLint defaultFbo; + // Save current FBO + GLint defaultFbo = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFbo); - glm::dmat4 model = calcModelTransform(data); + const glm::dmat4 model = calcModelTransform(data); - float viewScaling = data.camera.scaling(); - glm::dmat4 view = data.camera.combinedViewMatrix(); - glm::dmat4 projection = data.camera.projectionMatrix(); + const float viewScaling = data.camera.scaling(); + const glm::dmat4 view = data.camera.combinedViewMatrix(); + const glm::dmat4 projection = data.camera.projectionMatrix(); - glm::dmat4 modelViewProjMat = calcModelViewProjectionTransform(data, model); - glm::vec2 screenSize = glm::vec2(global::renderEngine->renderingResolution()); + const glm::dmat4 modelViewProjMat = calcModelViewProjectionTransform(data, model); + const glm::vec2 screenSize = glm::vec2(global::renderEngine->renderingResolution()); // Wait until camera has stabilized before we traverse the Octree/stream from files. const double rotationDiff = std::abs(length(_previousCameraRotation) - @@ -985,8 +985,8 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Update which nodes that are stored in memory as the camera moves around // (if streaming) if (_fileReaderOption == gaia::FileReaderOption::StreamOctree) { - glm::dvec3 cameraPos = data.camera.positionVec3(); - size_t chunkSizeBytes = _chunkSize * sizeof(GLfloat); + const glm::dvec3 cameraPos = data.camera.positionVec3(); + const size_t chunkSizeBytes = _chunkSize * sizeof(GLfloat); _octreeManager.fetchSurroundingNodes(cameraPos, chunkSizeBytes, _additionalNodes); // Update CPU Budget property. @@ -996,7 +996,7 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Traverse Octree and build a map with new nodes to render, uses mvp matrix to decide const int renderOption = _renderMode; int deltaStars = 0; - std::map> updateData = _octreeManager.traverseData( + const std::map> updateData = _octreeManager.traverseData( modelViewProjMat, screenSize, deltaStars, @@ -1011,9 +1011,9 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Update GPU Stream Budget property. _gpuStreamBudgetProperty = static_cast(_octreeManager.numFreeSpotsInBuffer()); - int nChunksToRender = static_cast(_octreeManager.biggestChunkIndexInUse()); - int maxStarsPerNode = static_cast(_octreeManager.maxStarsPerNode()); - int valuesPerStar = static_cast(_nRenderValuesPerStar); + const int nChunksToRender = static_cast(_octreeManager.biggestChunkIndexInUse()); + const int maxStarsPerNode = static_cast(_octreeManager.maxStarsPerNode()); + const int valuesPerStar = static_cast(_nRenderValuesPerStar); // Switch rendering technique depending on user-defined shader option. const int shaderOption = _shaderOption; @@ -1025,7 +1025,7 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { //------------------------ RENDER WITH SSBO --------------------------- // Update SSBO Index array with accumulated stars in all chunks. glBindBuffer(GL_SHADER_STORAGE_BUFFER, _ssboIdx); - int lastValue = _accumulatedIndices.back(); + const int lastValue = _accumulatedIndices.back(); _accumulatedIndices.resize(nChunksToRender + 1, lastValue); // Update vector with accumulated indices. @@ -1037,12 +1037,13 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { continue; } - int newValue = static_cast(subData.size() / _nRenderValuesPerStar) + - _accumulatedIndices[offset]; - int changeInValue = newValue - _accumulatedIndices[offset + 1]; + const int newValue = + static_cast(subData.size() / _nRenderValuesPerStar) + + _accumulatedIndices[offset]; + const int changeInValue = newValue - _accumulatedIndices[offset + 1]; _accumulatedIndices[offset + 1] = newValue; // Propagate change. - for (int i = offset + 1; i < nChunksToRender; ++i) { + for (int i = offset + 1; i < nChunksToRender; i++) { _accumulatedIndices[i + 1] += changeInValue; } } @@ -1053,7 +1054,7 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { _nRenderedStars = _nStarsToRender; } - size_t indexBufferSize = _accumulatedIndices.size() * sizeof(GLint); + const size_t indexBufferSize = _accumulatedIndices.size() * sizeof(GLint); // Update SSBO Index (stars per chunk). glBufferData( @@ -1099,9 +1100,10 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Always update Position VBO. glBindBuffer(GL_ARRAY_BUFFER, _vboPos); - float posMemoryShare = static_cast(PositionSize) / _nRenderValuesPerStar; - size_t posChunkSize = maxStarsPerNode * PositionSize; - long long posStreamingBudget = static_cast( + const float posMemoryShare = + static_cast(PositionSize) / _nRenderValuesPerStar; + const size_t posChunkSize = maxStarsPerNode * PositionSize; + const long long posStreamingBudget = static_cast( _maxStreamingBudgetInBytes * posMemoryShare ); @@ -1132,9 +1134,10 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Update Color VBO if render option is 'Color' or 'Motion'. if (renderOption != gaia::RenderMode::Static) { glBindBuffer(GL_ARRAY_BUFFER, _vboCol); - float colMemoryShare = static_cast(ColorSize) / _nRenderValuesPerStar; - size_t colChunkSize = maxStarsPerNode * ColorSize; - long long colStreamingBudget = static_cast( + const float colMemoryShare = + static_cast(ColorSize) / _nRenderValuesPerStar; + const size_t colChunkSize = maxStarsPerNode * ColorSize; + const long long colStreamingBudget = static_cast( _maxStreamingBudgetInBytes * colMemoryShare ); @@ -1163,10 +1166,10 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { // Update Velocity VBO if specified. if (renderOption == gaia::RenderMode::Motion) { glBindBuffer(GL_ARRAY_BUFFER, _vboVel); - float velMemoryShare = static_cast(VelocitySize) / + const float velMemoryShare = static_cast(VelocitySize) / _nRenderValuesPerStar; - size_t velChunkSize = maxStarsPerNode * VelocitySize; - long long velStreamingBudget = static_cast( + const size_t velChunkSize = maxStarsPerNode * VelocitySize; + const long long velStreamingBudget = static_cast( _maxStreamingBudgetInBytes * velMemoryShare ); @@ -1357,7 +1360,7 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { void RenderableGaiaStars::checkGlErrors(const std::string& identifier) const { if (_reportGlErrors) { - GLenum error = glGetError(); + const GLenum error = glGetError(); if (error != GL_NO_ERROR) { switch (error) { case GL_INVALID_ENUM: @@ -1395,7 +1398,7 @@ void RenderableGaiaStars::update(const UpdateData&) { if (_dataIsDirty) { LDEBUG("Regenerating data"); // Reload data file. This may reconstruct the Octree as well. - bool success = readDataFile(); + const bool success = readDataFile(); if (!success) { throw ghoul::RuntimeError("Error loading Gaia Star data"); } @@ -1695,10 +1698,10 @@ void RenderableGaiaStars::update(const UpdateData&) { } case gaia::ShaderOption::BillboardSSBO: case gaia::ShaderOption::BillboardVBO: { - std::filesystem::path vs = absPath( + const std::filesystem::path vs = absPath( "${MODULE_GAIA}/shaders/gaia_tonemapping_vs.glsl" ); - std::filesystem::path fs = absPath( + const std::filesystem::path fs = absPath( "${MODULE_GAIA}/shaders/gaia_tonemapping_billboard_fs.glsl" ); std::unique_ptr programTM = @@ -1732,8 +1735,8 @@ void RenderableGaiaStars::update(const UpdateData&) { // Calculate memory budgets. _chunkSize = _octreeManager.maxStarsPerNode() * _nRenderValuesPerStar; - long long totalChunkSizeInBytes = _octreeManager.totalNodes() * - _chunkSize * sizeof(GLfloat); + const long long totalChunkSizeInBytes = + _octreeManager.totalNodes() * _chunkSize * sizeof(GLfloat); _maxStreamingBudgetInBytes = std::min( totalChunkSizeInBytes, _gpuMemoryBudgetInBytes @@ -1742,7 +1745,7 @@ void RenderableGaiaStars::update(const UpdateData&) { (_chunkSize * sizeof(GLfloat)); _gpuStreamBudgetProperty.setMaxValue(static_cast(maxNodesInStream)); - bool datasetFitInMemory = + const bool datasetFitInMemory = static_cast(_totalDatasetSizeInBytes) < (_cpuRamBudgetInBytes * 0.9f); if (!datasetFitInMemory && !hasProperty(&_additionalNodes)) { @@ -1752,7 +1755,7 @@ void RenderableGaiaStars::update(const UpdateData&) { removeProperty(_additionalNodes); } - LDEBUG(fmt::format( + LDEBUG(std::format( "Chunk size: {} - Max streaming budget (bytes): {} - Max nodes in stream: {}", _chunkSize, _maxStreamingBudgetInBytes, maxNodesInStream )); @@ -1777,17 +1780,17 @@ void RenderableGaiaStars::update(const UpdateData&) { // Generate SSBO Buffers and bind them. if (_vaoEmpty == 0) { glGenVertexArrays(1, &_vaoEmpty); - LDEBUG(fmt::format("Generating Empty Vertex Array id '{}'", _vaoEmpty)); + LDEBUG(std::format("Generating Empty Vertex Array id '{}'", _vaoEmpty)); } if (_ssboIdx == 0) { glGenBuffers(1, &_ssboIdx); - LDEBUG(fmt::format( + LDEBUG(std::format( "Generating Index Shader Storage Buffer Object id '{}'", _ssboIdx )); } if (_ssboData == 0) { glGenBuffers(1, &_ssboData); - LDEBUG(fmt::format( + LDEBUG(std::format( "Generating Data Shader Storage Buffer Object id '{}'", _ssboData )); } @@ -1867,23 +1870,23 @@ void RenderableGaiaStars::update(const UpdateData&) { // Generate VAO and VBOs if (_vao == 0) { glGenVertexArrays(1, &_vao); - LDEBUG(fmt::format("Generating Vertex Array id '{}'", _vao)); + LDEBUG(std::format("Generating Vertex Array id '{}'", _vao)); } if (_vboPos == 0) { glGenBuffers(1, &_vboPos); - LDEBUG(fmt::format( + LDEBUG(std::format( "Generating Position Vertex Buffer Object id '{}'", _vboPos )); } if (_vboCol == 0) { glGenBuffers(1, &_vboCol); - LDEBUG(fmt::format( + LDEBUG(std::format( "Generating Color Vertex Buffer Object id '{}'", _vboCol )); } if (_vboVel == 0) { glGenBuffers(1, &_vboVel); - LDEBUG(fmt::format( + LDEBUG(std::format( "Generating Velocity Vertex Buffer Object id '{}'", _vboVel )); } @@ -1894,11 +1897,11 @@ void RenderableGaiaStars::update(const UpdateData&) { switch (renderOption) { case gaia::RenderMode::Static: { glBindBuffer(GL_ARRAY_BUFFER, _vboPos); - GLint positionAttrib = _program->attributeLocation("in_position"); - glEnableVertexAttribArray(positionAttrib); + const GLint position = _program->attributeLocation("in_position"); + glEnableVertexAttribArray(position); glVertexAttribPointer( - positionAttrib, + position, PositionSize, GL_FLOAT, GL_FALSE, @@ -1910,11 +1913,11 @@ void RenderableGaiaStars::update(const UpdateData&) { } case gaia::RenderMode::Color: { glBindBuffer(GL_ARRAY_BUFFER, _vboPos); - GLint positionAttrib = _program->attributeLocation("in_position"); - glEnableVertexAttribArray(positionAttrib); + const GLint position = _program->attributeLocation("in_position"); + glEnableVertexAttribArray(position); glVertexAttribPointer( - positionAttrib, + position, PositionSize, GL_FLOAT, GL_FALSE, @@ -1923,11 +1926,11 @@ void RenderableGaiaStars::update(const UpdateData&) { ); glBindBuffer(GL_ARRAY_BUFFER, _vboCol); - GLint brightnessAttrib = _program->attributeLocation("in_brightness"); - glEnableVertexAttribArray(brightnessAttrib); + const GLint brightness = _program->attributeLocation("in_brightness"); + glEnableVertexAttribArray(brightness); glVertexAttribPointer( - brightnessAttrib, + brightness, ColorSize, GL_FLOAT, GL_FALSE, @@ -1938,11 +1941,11 @@ void RenderableGaiaStars::update(const UpdateData&) { } case gaia::RenderMode::Motion: { glBindBuffer(GL_ARRAY_BUFFER, _vboPos); - GLint positionAttrib = _program->attributeLocation("in_position"); - glEnableVertexAttribArray(positionAttrib); + const GLint position = _program->attributeLocation("in_position"); + glEnableVertexAttribArray(position); glVertexAttribPointer( - positionAttrib, + position, PositionSize, GL_FLOAT, GL_FALSE, @@ -1951,11 +1954,11 @@ void RenderableGaiaStars::update(const UpdateData&) { ); glBindBuffer(GL_ARRAY_BUFFER, _vboCol); - GLint brightnessAttrib = _program->attributeLocation("in_brightness"); - glEnableVertexAttribArray(brightnessAttrib); + const GLint brightness = _program->attributeLocation("in_brightness"); + glEnableVertexAttribArray(brightness); glVertexAttribPointer( - brightnessAttrib, + brightness, ColorSize, GL_FLOAT, GL_FALSE, @@ -1964,11 +1967,11 @@ void RenderableGaiaStars::update(const UpdateData&) { ); glBindBuffer(GL_ARRAY_BUFFER, _vboVel); - GLint velocityAttrib = _program->attributeLocation("in_velocity"); - glEnableVertexAttribArray(velocityAttrib); + const GLint velocity = _program->attributeLocation("in_velocity"); + glEnableVertexAttribArray(velocity); glVertexAttribPointer( - velocityAttrib, + velocity, VelocitySize, GL_FLOAT, GL_FALSE, @@ -2009,11 +2012,11 @@ void RenderableGaiaStars::update(const UpdateData&) { // Generate VAO and VBO for Quad. if (_vaoQuad == 0) { glGenVertexArrays(1, &_vaoQuad); - LDEBUG(fmt::format("Generating Quad Vertex Array id '{}'", _vaoQuad)); + LDEBUG(std::format("Generating Quad Vertex Array id '{}'", _vaoQuad)); } if (_vboQuad == 0) { glGenBuffers(1, &_vboQuad); - LDEBUG(fmt::format("Generating Quad Vertex Buffer Object id '{}'", _vboQuad)); + LDEBUG(std::format("Generating Quad Vertex Buffer Object id '{}'", _vboQuad)); } // Bind VBO and VAO for Quad rendering. @@ -2021,23 +2024,23 @@ void RenderableGaiaStars::update(const UpdateData&) { glBindBuffer(GL_ARRAY_BUFFER, _vboQuad); // Quad for fullscreen. - static constexpr GLfloat vbo_quad_data[] = { - -1.0f, -1.0f, 0.0f, - 1.0f, -1.0f, 0.0f, - -1.0f, 1.0f, 0.0f, - -1.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 0.0f, - 1.0f, 1.0f, 0.0f, + constexpr std::array VboQuadData = { + -1.f, -1.f, 0.f, + 1.f, -1.f, 0.f, + -1.f, 1.f, 0.f, + -1.f, 1.f, 0.f, + 1.f, -1.f, 0.f, + 1.f, 1.f, 0.f, }; glBufferData( GL_ARRAY_BUFFER, - sizeof(vbo_quad_data), - vbo_quad_data, + sizeof(VboQuadData), + VboQuadData.data(), GL_STATIC_DRAW ); - GLint tmPositionAttrib = _programTM->attributeLocation("in_position"); + const GLint tmPositionAttrib = _programTM->attributeLocation("in_position"); glEnableVertexAttribArray(tmPositionAttrib); glVertexAttribPointer( tmPositionAttrib, @@ -2055,11 +2058,13 @@ void RenderableGaiaStars::update(const UpdateData&) { // Generate Framebuffer Object and Texture. if (_fbo == 0) { glGenFramebuffers(1, &_fbo); - LDEBUG(fmt::format("Generating Framebuffer Object id '{}'", _fbo)); + LDEBUG(std::format("Generating Framebuffer Object id '{}'", _fbo)); } if (!_fboTexture) { // Generate a new texture and attach it to our FBO. - glm::vec2 screenSize = glm::vec2(global::renderEngine->renderingResolution()); + const glm::vec2 screenSize = glm::vec2( + global::renderEngine->renderingResolution() + ); _fboTexture = std::make_unique( glm::uvec3(screenSize, 1), GL_TEXTURE_2D, @@ -2079,8 +2084,8 @@ void RenderableGaiaStars::update(const UpdateData&) { *_fboTexture, 0 ); - GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, textureBuffers); + const GLenum textureBuffer = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &textureBuffer); // Check that our framebuffer is ok. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { @@ -2101,8 +2106,8 @@ void RenderableGaiaStars::update(const UpdateData&) { ); if (_pointSpreadFunctionTexture) { - LDEBUG(fmt::format( - "Loaded texture from {}", absPath(_pointSpreadFunctionTexturePath) + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_pointSpreadFunctionTexturePath) )); _pointSpreadFunctionTexture->uploadTexture(); } @@ -2129,7 +2134,9 @@ void RenderableGaiaStars::update(const UpdateData&) { 1 ); if (_colorTexture) { - LDEBUG(fmt::format("Loaded texture from {}", absPath(_colorTexturePath))); + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_colorTexturePath) + )); _colorTexture->uploadTexture(); } @@ -2142,8 +2149,10 @@ void RenderableGaiaStars::update(const UpdateData&) { } if (global::windowDelegate->windowHasResized()) { - // Update FBO texture resolution if we haven't already. - glm::vec2 screenSize = glm::vec2(global::renderEngine->renderingResolution()); + // Update FBO texture resolution if we haven't already + const glm::vec2 screenSize = glm::vec2( + global::renderEngine->renderingResolution() + ); const bool hasChanged = glm::any( glm::notEqual(_fboTexture->dimensions(), glm::uvec3(screenSize, 1)) ); @@ -2167,8 +2176,8 @@ void RenderableGaiaStars::update(const UpdateData&) { *_fboTexture, 0 ); - GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, textureBuffers); + const GLenum textureBuffer = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &textureBuffer); // Check that our framebuffer is ok. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { @@ -2186,7 +2195,7 @@ bool RenderableGaiaStars::readDataFile() { _octreeManager.initOctree(_cpuRamBudgetInBytes); std::filesystem::path file = absPath(_filePath.value()); - LINFO(fmt::format("Loading data file: {}", file)); + LINFO(std::format("Loading data file '{}'", file)); switch (fileReaderOption) { case gaia::FileReaderOption::Fits: @@ -2216,7 +2225,7 @@ bool RenderableGaiaStars::readDataFile() { //_octreeManager->printStarsPerNode(); _nRenderedStars.setMaxValue(nReadStars); - LINFO(fmt::format("Dataset contains a total of {} stars", nReadStars)); + LINFO(std::format("Dataset contains a total of {} stars", nReadStars)); _totalDatasetSizeInBytes = nReadStars * (PositionSize + ColorSize + VelocitySize) * 4; return nReadStars > 0; @@ -2236,10 +2245,9 @@ int RenderableGaiaStars::readFitsFile(const std::filesystem::path& filePath) { // Insert stars into octree. for (size_t i = 0; i < fullData.size(); i += nReadValuesPerStar) { - auto first = fullData.begin() + i; - auto last = fullData.begin() + i + nReadValuesPerStar; - std::vector starValues(first, last); - + const auto first = fullData.begin() + i; + const auto last = fullData.begin() + i + nReadValuesPerStar; + const std::vector starValues(first, last); _octreeManager.insert(starValues); } _octreeManager.sliceLodData(); @@ -2256,8 +2264,7 @@ int RenderableGaiaStars::readSpeckFile(const std::filesystem::path& filePath) { for (size_t i = 0; i < fullData.size(); i += nReadValuesPerStar) { auto first = fullData.begin() + i; auto last = fullData.begin() + i + nReadValuesPerStar; - std::vector starValues(first, last); - + const std::vector starValues = std::vector(first, last); _octreeManager.insert(starValues); } _octreeManager.sliceLodData(); @@ -2272,7 +2279,7 @@ int RenderableGaiaStars::readBinaryRawFile(const std::filesystem::path& filePath if (fileStream.good()) { int32_t nValues = 0; int32_t nReadValuesPerStar = 0; - int renderValues = 8; + const int renderValues = 8; fileStream.read(reinterpret_cast(&nValues), sizeof(int32_t)); fileStream.read(reinterpret_cast(&nReadValuesPerStar), sizeof(int32_t)); @@ -2286,7 +2293,7 @@ int RenderableGaiaStars::readBinaryRawFile(const std::filesystem::path& filePath for (size_t i = 0; i < fullData.size(); i += nReadValuesPerStar) { auto first = fullData.begin() + i; auto last = fullData.begin() + i + renderValues; - std::vector starValues(first, last); + const std::vector starValues(first, last); _octreeManager.insert(starValues); } @@ -2296,7 +2303,7 @@ int RenderableGaiaStars::readBinaryRawFile(const std::filesystem::path& filePath fileStream.close(); } else { - LERROR(fmt::format( + LERROR(std::format( "Error opening file '{}' for loading raw binary file", filePath )); return nReadStars; @@ -2314,7 +2321,7 @@ int RenderableGaiaStars::readBinaryOctreeFile(const std::filesystem::path& fileP fileStream.close(); } else { - LERROR(fmt::format( + LERROR(std::format( "Error opening file '{}' for loading binary Octree file", filePath )); return nReadStars; @@ -2335,7 +2342,7 @@ int RenderableGaiaStars::readBinaryOctreeStructureFile( fileStream.close(); } else { - LERROR(fmt::format( + LERROR(std::format( "Error opening file '{}' for loading binary Octree file", indexFile )); return nReadStars; diff --git a/modules/gaia/shaders/gaia_point_fs.glsl b/modules/gaia/shaders/gaia_point_fs.glsl index 1096e6894d..0dc7b66d58 100644 --- a/modules/gaia/shaders/gaia_point_fs.glsl +++ b/modules/gaia/shaders/gaia_point_fs.glsl @@ -95,5 +95,5 @@ void main() { //color *= ratio * ratioMultiplier; } - outColor = vec4(color, 1.0f); + outColor = vec4(color, 1.0); } diff --git a/modules/gaia/shaders/gaia_ssbo_vs.glsl b/modules/gaia/shaders/gaia_ssbo_vs.glsl index c9af489f34..faa139202d 100644 --- a/modules/gaia/shaders/gaia_ssbo_vs.glsl +++ b/modules/gaia/shaders/gaia_ssbo_vs.glsl @@ -130,8 +130,8 @@ void main() { // Check if we should filter this star by magnitude or color if ((abs(gMagThreshold.x - gMagThreshold.y) < EPS && abs(gMagThreshold.x - in_brightness.x) < EPS) || - (abs(gMagThreshold.x - 20.0f) > EPS && in_brightness.x < gMagThreshold.x) || - (abs(gMagThreshold.y - 20.0f) > EPS && in_brightness.x > gMagThreshold.y) || + (abs(gMagThreshold.x - 20.0) > EPS && in_brightness.x < gMagThreshold.x) || + (abs(gMagThreshold.y - 20.0) > EPS && in_brightness.x > gMagThreshold.y) || (abs(bpRpThreshold.x - bpRpThreshold.y) < EPS && abs(bpRpThreshold.x - in_brightness.y) < EPS) || (abs(bpRpThreshold.x) > EPS && in_brightness.y < bpRpThreshold.x) || (abs(bpRpThreshold.y) > EPS && in_brightness.y > bpRpThreshold.y)) @@ -169,7 +169,7 @@ void main() { // Apply camera transforms dvec4 viewPosition = view * model * objectPosition; - vec4 sunPosition = vec4(view * model * dvec4(0.0f, 0.0f, 0.0f, 1.0f)); + vec4 sunPosition = vec4(view * model * dvec4(0.0, 0.0, 0.0, 1.0)); vs_starDistFromSun = safeLength(objectPosition); vs_cameraDistFromSun = safeLength(sunPosition); diff --git a/modules/gaia/shaders/gaia_tonemapping_point_fs.glsl b/modules/gaia/shaders/gaia_tonemapping_point_fs.glsl index 63d2a9f0e4..37c7c907a8 100644 --- a/modules/gaia/shaders/gaia_tonemapping_point_fs.glsl +++ b/modules/gaia/shaders/gaia_tonemapping_point_fs.glsl @@ -162,7 +162,7 @@ Fragment getFragment() { discard; } - color = vec4(intensity, 1.0f); + color = vec4(intensity, 1.0); // Use the following to check for any intensity at all. //color = (length(intensity.rgb) > 0.001) ? vec4(1.0) : vec4(0.0); diff --git a/modules/gaia/shaders/gaia_vbo_vs.glsl b/modules/gaia/shaders/gaia_vbo_vs.glsl index 492fd86aee..19ccf6e1d5 100644 --- a/modules/gaia/shaders/gaia_vbo_vs.glsl +++ b/modules/gaia/shaders/gaia_vbo_vs.glsl @@ -69,8 +69,8 @@ void main() { && abs(length(in_position) - distThreshold.y) < EPS) || (renderOption != RENDEROPTION_STATIC && ( (abs(gMagThreshold.x - gMagThreshold.y) < EPS && abs(gMagThreshold.x - in_brightness.x) < EPS) || - (abs(gMagThreshold.x - 20.0f) > EPS && in_brightness.x < gMagThreshold.x) || - (abs(gMagThreshold.y - 20.0f) > EPS && in_brightness.x > gMagThreshold.y) || + (abs(gMagThreshold.x - 20.0) > EPS && in_brightness.x < gMagThreshold.x) || + (abs(gMagThreshold.y - 20.0) > EPS && in_brightness.x > gMagThreshold.y) || (abs(bpRpThreshold.x - bpRpThreshold.y) < EPS && abs(bpRpThreshold.x - in_brightness.y) < EPS) || (abs(bpRpThreshold.x) > EPS && in_brightness.y < bpRpThreshold.x) || (abs(bpRpThreshold.y) > EPS && in_brightness.y > bpRpThreshold.y)))) @@ -104,7 +104,7 @@ void main() { // Apply camera transforms. dvec4 viewPosition = view * model * objectPosition; - vec4 sunPosition = vec4(view * model * vec4(0.0f, 0.0f, 0.0f, 1.0f)); + vec4 sunPosition = vec4(view * model * vec4(0.0, 0.0, 0.0, 1.0)); vs_starDistFromSun = safeLength(objectPosition); vs_cameraDistFromSun = safeLength(sunPosition); diff --git a/modules/gaia/tasks/constructoctreetask.cpp b/modules/gaia/tasks/constructoctreetask.cpp index 52df7a11a6..338d788617 100644 --- a/modules/gaia/tasks/constructoctreetask.cpp +++ b/modules/gaia/tasks/constructoctreetask.cpp @@ -295,9 +295,9 @@ ConstructOctreeTask::ConstructOctreeTask(const ghoul::Dictionary& dictionary) { } std::string ConstructOctreeTask::description() { - return fmt::format( - "Read bin file (or files in folder): {} and write octree data file (or files) " - "into: {}", _inFileOrFolderPath, _outFileOrFolderPath + return std::format( + "Read bin file (or files in folder) '{}' and write octree data file (or files) " + "into '{}'", _inFileOrFolderPath, _outFileOrFolderPath ); } @@ -325,9 +325,9 @@ void ConstructOctreeTask::constructOctreeFromSingleFile( _octreeManager->initOctree(0, _maxDist, _maxStarsPerNode); - LINFO(fmt::format("Reading data file: {}", _inFileOrFolderPath)); + LINFO(std::format("Reading data file '{}'", _inFileOrFolderPath)); - LINFO(fmt::format( + LINFO(std::format( "MAX DIST: {} - MAX STARS PER NODE: {}", _octreeManager->maxDist(), _octreeManager->maxStarsPerNode() )); @@ -390,8 +390,8 @@ void ConstructOctreeTask::constructOctreeFromSingleFile( for (size_t i = 0; i < fullData.size(); i += nValuesPerStar) { auto first = fullData.begin() + i; auto last = fullData.begin() + i + nValuesPerStar; - std::vector filterValues(first, last); - std::vector renderValues(first, first + RENDER_VALUES); + const std::vector filterValues(first, last); + const std::vector renderValues(first, first + RENDER_VALUES); // Filter data by parameters. if (checkAllFilters(filterValues)) { @@ -405,16 +405,16 @@ void ConstructOctreeTask::constructOctreeFromSingleFile( inFileStream.close(); } else { - LERROR(fmt::format( - "Error opening file {} for loading preprocessed file", _inFileOrFolderPath + LERROR(std::format( + "Error opening file '{}' for loading preprocessed file", _inFileOrFolderPath )); } - LINFO(fmt::format("{} of {} read stars were filtered", nFilteredStars, nTotalStars)); + LINFO(std::format("{} of {} read stars were filtered", nFilteredStars, nTotalStars)); // Slice LOD data before writing to files. _octreeManager->sliceLodData(); - LINFO(fmt::format("Writing octree to: {}", _outFileOrFolderPath)); + LINFO(std::format("Writing octree to '{}'", _outFileOrFolderPath)); std::ofstream outFileStream(_outFileOrFolderPath, std::ofstream::binary); if (outFileStream.good()) { if (nValues == 0) { @@ -425,8 +425,8 @@ void ConstructOctreeTask::constructOctreeFromSingleFile( outFileStream.close(); } else { - LERROR(fmt::format( - "Error opening file: {} as output data file", _outFileOrFolderPath + LERROR(std::format( + "Error opening file '{}' as output data file", _outFileOrFolderPath )); } } @@ -468,18 +468,18 @@ void ConstructOctreeTask::constructOctreeFromFolder( _indexOctreeManager->initOctree(0, _maxDist, _maxStarsPerNode); - float processOneFile = 1.f / allInputFiles.size(); + const float processOneFile = 1.f / allInputFiles.size(); - LINFO(fmt::format( + LINFO(std::format( "MAX DIST: {} - MAX STARS PER NODE: {}", _indexOctreeManager->maxDist(), _indexOctreeManager->maxStarsPerNode() )); - for (size_t idx = 0; idx < allInputFiles.size(); ++idx) { + for (size_t idx = 0; idx < allInputFiles.size(); idx++) { std::filesystem::path inFilePath = allInputFiles[idx]; int nStarsInfile = 0; - LINFO(fmt::format("Reading data file: {}", inFilePath)); + LINFO(std::format("Reading data file '{}'", inFilePath)); std::ifstream inFileStream(inFilePath, std::ifstream::binary); if (inFileStream.good()) { @@ -506,7 +506,7 @@ void ConstructOctreeTask::constructOctreeFromFolder( //} // If all filters passed then insert render values into Octree. - std::vector renderValues( + const std::vector renderValues( filterValues.begin(), filterValues.begin() + RENDER_VALUES ); @@ -536,8 +536,8 @@ void ConstructOctreeTask::constructOctreeFromFolder( inFileStream.close(); } else { - LERROR(fmt::format( - "Error opening file {} for loading preprocessed file", inFilePath + LERROR(std::format( + "Error opening file '{}' for loading preprocessed file", inFilePath )); } @@ -548,8 +548,8 @@ void ConstructOctreeTask::constructOctreeFromFolder( progressCallback((idx + 1) * processOneFile); nStars += nStarsInfile; - LINFO(fmt::format("Writing {} stars to octree files", nStarsInfile)); - LINFO(fmt::format( + LINFO(std::format("Writing {} stars to octree files", nStarsInfile)); + LINFO(std::format( "Number leaf nodes: {}\n Number inner nodes: {}\n Total depth of tree: {}", _indexOctreeManager->numLeafNodes(), _indexOctreeManager->numInnerNodes(), @@ -567,7 +567,7 @@ void ConstructOctreeTask::constructOctreeFromFolder( writeThreads[idx] = std::move(t); } - LINFO(fmt::format( + LINFO(std::format( "A total of {} stars were read from files and distributed into {} total nodes", nStars, _indexOctreeManager->totalNodes() )); @@ -591,7 +591,7 @@ void ConstructOctreeTask::constructOctreeFromFolder( // " - 5000kPc is " + std::to_string(starsOutside5000)); // Write index file of Octree structure. - std::filesystem::path indexFileOutPath = fmt::format( + std::filesystem::path indexFileOutPath = std::format( "{}/index.bin", _outFileOrFolderPath.string() ); std::ofstream outFileStream(indexFileOutPath, std::ofstream::binary); @@ -602,13 +602,13 @@ void ConstructOctreeTask::constructOctreeFromFolder( outFileStream.close(); } else { - LERROR(fmt::format( - "Error opening file: {} as index output file", indexFileOutPath + LERROR(std::format( + "Error opening file '{}' as index output file", indexFileOutPath )); } // Make sure all threads are done. - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 8; i++) { writeThreads[i].join(); } } @@ -646,10 +646,11 @@ bool ConstructOctreeTask::filterStar(const glm::vec2& range, float filterValue, { // Return true if star should be filtered away, i.e. if min = max = filterValue or // if filterValue < min (when min != 0.0) or filterValue > max (when max != 0.0). - return (fabs(range.x - range.y) < FLT_EPSILON && - fabs(range.x - filterValue) < FLT_EPSILON) || - (fabs(range.x - normValue) > FLT_EPSILON && filterValue < range.x) || - (fabs(range.y - normValue) > FLT_EPSILON && filterValue > range.y); + constexpr float eps = std::numeric_limits::epsilon(); + return (std::abs(range.x - range.y) < eps && + std::abs(range.x - filterValue) < eps) || + (std::abs(range.x - normValue) > eps && filterValue < range.x) || + (std::abs(range.y - normValue) > eps && filterValue > range.y); } documentation::Documentation ConstructOctreeTask::Documentation() { diff --git a/modules/gaia/tasks/readfilejob.cpp b/modules/gaia/tasks/readfilejob.cpp index 0aeb5d4252..34e4760bd9 100644 --- a/modules/gaia/tasks/readfilejob.cpp +++ b/modules/gaia/tasks/readfilejob.cpp @@ -50,7 +50,7 @@ ReadFileJob::ReadFileJob(std::string filePath, std::vector allColum void ReadFileJob::execute() { // Read columns from FITS file. If rows aren't specified then full table will be read. - std::shared_ptr> table = _fitsFileReader->readTable( + const std::shared_ptr> table = _fitsFileReader->readTable( _inFilePath, _allColumns, _firstRow, @@ -59,13 +59,13 @@ void ReadFileJob::execute() { if (!table) { throw ghoul::RuntimeError( - fmt::format("Failed to open Fits file '{}'", _inFilePath + std::format("Failed to open Fits file '{}'", _inFilePath )); } - int nStars = table->readRows - _firstRow + 1; + const int nStars = table->readRows - _firstRow + 1; - size_t nColumnsRead = _allColumns.size(); + const size_t nColumnsRead = _allColumns.size(); if (nColumnsRead != _nDefaultCols) { LINFO( "Additional columns will be read! Consider add column in code for " @@ -100,7 +100,7 @@ void ReadFileJob::execute() { // Construct data array. OBS: ORDERING IS IMPORTANT! This is where slicing happens. - for (int i = 0; i < nStars; ++i) { + for (int i = 0; i < nStars; i++) { std::vector values(_nValuesPerStar); size_t idx = 0; @@ -139,7 +139,7 @@ void ReadFileJob::execute() { */ // Convert ICRS Equatorial Ra and Dec to Galactic latitude and longitude. - glm::mat3 aPrimG = glm::mat3( + const glm::mat3 aPrimG = glm::mat3( // Col 0 glm::vec3(-0.0548755604162154, 0.4941094278755837, -0.8676661490190047), // Col 1 @@ -147,12 +147,12 @@ void ReadFileJob::execute() { // Col 2 glm::vec3(-0.4838350155487132, 0.7469822444972189, 0.4559837761750669) ); - glm::vec3 rICRS = glm::vec3( - cos(glm::radians(ra[i])) * cos(glm::radians(dec[i])), - sin(glm::radians(ra[i])) * cos(glm::radians(dec[i])), - sin(glm::radians(dec[i])) + const glm::vec3 rICRS = glm::vec3( + std::cos(glm::radians(ra[i])) * std::cos(glm::radians(dec[i])), + std::sin(glm::radians(ra[i])) * std::cos(glm::radians(dec[i])), + std::sin(glm::radians(dec[i])) ); - glm::vec3 rGal = aPrimG * rICRS; + const glm::vec3 rGal = aPrimG * rICRS; values[idx++] = radiusInKiloParsec * rGal.x; // Pos X values[idx++] = radiusInKiloParsec * rGal.y; // Pos Y values[idx++] = radiusInKiloParsec * rGal.z; // Pos Z @@ -180,27 +180,27 @@ void ReadFileJob::execute() { } // Convert Proper Motion from ICRS [Ra,Dec] to Galactic Tanget Vector [l,b]. - glm::vec3 uICRS = glm::vec3( - -sin(glm::radians(ra[i])) * pmra[i] - - cos(glm::radians(ra[i])) * sin(glm::radians(dec[i])) * pmdec[i], - cos(glm::radians(ra[i])) * pmra[i] - - sin(glm::radians(ra[i])) * sin(glm::radians(dec[i])) * pmdec[i], - cos(glm::radians(dec[i])) * pmdec[i] + const glm::vec3 uICRS = glm::vec3( + -std::sin(glm::radians(ra[i])) * pmra[i] - + std::cos(glm::radians(ra[i])) * std::sin(glm::radians(dec[i])) * pmdec[i], + std::cos(glm::radians(ra[i])) * pmra[i] - + std::sin(glm::radians(ra[i])) * std::sin(glm::radians(dec[i])) * pmdec[i], + std::cos(glm::radians(dec[i])) * pmdec[i] ); - glm::vec3 pmVecGal = aPrimG * uICRS; + const glm::vec3 pmVecGal = aPrimG * uICRS; // Convert to Tangential vector [m/s] from Proper Motion vector [mas/yr] - float tanVelX = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.x; - float tanVelY = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.y; - float tanVelZ = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.z; + const float tanVelX = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.x; + const float tanVelY = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.y; + const float tanVelZ = 1000.f * 4.74f * radiusInKiloParsec * pmVecGal.z; // Calculate True Space Velocity [m/s] if we have the radial velocity if (!std::isnan(radial_vel[i])) { // Calculate Radial Velocity in the direction of the star. // radial_vel is given in [km/s] -> convert to [m/s]. - float radVelX = 1000.f * radial_vel[i] * rGal.x; - float radVelY = 1000.f * radial_vel[i] * rGal.y; - float radVelZ = 1000.f * radial_vel[i] * rGal.z; + const float radVelX = 1000.f * radial_vel[i] * rGal.x; + const float radVelY = 1000.f * radial_vel[i] * rGal.y; + const float radVelZ = 1000.f * radial_vel[i] * rGal.z; // Use Pythagoras theorem for the final Space Velocity [m/s]. values[idx++] = static_cast( @@ -264,4 +264,4 @@ std::vector> ReadFileJob::product() { return _octants; } -} // namespace openspace::gaiamission +} // namespace openspace::gaia diff --git a/modules/gaia/tasks/readfitstask.cpp b/modules/gaia/tasks/readfitstask.cpp index cf978b3b94..dcad2ef70c 100644 --- a/modules/gaia/tasks/readfitstask.cpp +++ b/modules/gaia/tasks/readfitstask.cpp @@ -90,26 +90,27 @@ ReadFitsTask::ReadFitsTask(const ghoul::Dictionary& dictionary) { _lastRow = p.lastRow.value_or(_lastRow); if (p.filterColumnNames.has_value()) { - ghoul::Dictionary d = dictionary.value(KeyFilterColumnNames); + const ghoul::Dictionary d = + dictionary.value(KeyFilterColumnNames); // Ugly fix for ASCII sorting when there are more columns read than 10. std::set intKeys; - for (std::string_view key : d.keys()) { + for (const std::string_view key : d.keys()) { intKeys.insert(std::stoi(std::string(key))); } - for (int key : intKeys) { + for (const int key : intKeys) { _filterColumnNames.push_back(d.value(std::to_string(key))); } } } std::string ReadFitsTask::description() { - return fmt::format( - "Read the specified fits file (or all fits files in specified folder): {}\n and " - "write raw star data into: {}\nAll columns required for default rendering and " - "filtering parameters will always be read but user can define additional filter " - "columns to read", _inFileOrFolderPath, _outFileOrFolderPath + return std::format( + "Read the specified fits file (or all fits files in specified folder): '{}'\n " + "and write raw star data into: '{}'\nAll columns required for default rendering " + "and filtering parameters will always be read but user can define additional " + "filter columns to read", _inFileOrFolderPath, _outFileOrFolderPath ); } @@ -143,7 +144,9 @@ void ReadFitsTask::readSingleFitsFile(const Task::ProgressCallback& progressCall std::ofstream outFileStream(_outFileOrFolderPath, std::ofstream::binary); if (outFileStream.good()) { int32_t nValues = static_cast(fullData.size()); - LINFO(fmt::format("Writing {} values to file {}", nValues, _outFileOrFolderPath)); + LINFO(std::format( + "Writing {} values to file '{}'", nValues, _outFileOrFolderPath + )); LINFO("Number of values per star: " + std::to_string(nValuesPerStar)); if (nValues == 0) { @@ -158,14 +161,14 @@ void ReadFitsTask::readSingleFitsFile(const Task::ProgressCallback& progressCall sizeof(int32_t) ); - size_t nBytes = nValues * sizeof(fullData[0]); + const size_t nBytes = nValues * sizeof(fullData[0]); outFileStream.write(reinterpret_cast(fullData.data()), nBytes); outFileStream.close(); } else { - LERROR(fmt::format( - "Error opening file: {} as output data file", _outFileOrFolderPath + LERROR(std::format( + "Error opening file '{}' as output data file", _outFileOrFolderPath )); } } @@ -178,12 +181,14 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { _firstRow = std::max(_firstRow, 1); - // Create Threadpool and JobManager. + // Create Threadpool and JobManager LINFO("Threads in pool: " + std::to_string(_threadsToUse)); ThreadPool threadPool(_threadsToUse); - ConcurrentJobManager>> jobManager(threadPool); + ConcurrentJobManager>> jobManager( + std::move(threadPool) + ); - // Get all files in specified folder. + // Get all files in specified folder std::vector allInputFiles; if (std::filesystem::is_directory(_inFileOrFolderPath)) { namespace fs = std::filesystem; @@ -194,12 +199,12 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { } } - size_t nInputFiles = allInputFiles.size(); + const size_t nInputFiles = allInputFiles.size(); LINFO("Files to read: " + std::to_string(nInputFiles)); - // Define what columns to read. + // Define what columns to read _allColumnNames.clear(); - // Read in the order of table in file. + // Read in the order of table in file std::vector defaultColumnNames = { "ra", "ra_error", @@ -239,13 +244,13 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { LINFO(allNames); // Declare how many values to save for each star. - int32_t nValuesPerStar = 24; - size_t nDefaultColumns = defaultColumnNames.size(); + constexpr int32_t NValuesPerStar = 24; + const size_t nDefaultColumns = defaultColumnNames.size(); auto fitsFileReader = std::make_shared(false); // Divide all files into ReadFilejobs and then delegate them onto several threads! while (!allInputFiles.empty()) { - std::filesystem::path fileToRead = allInputFiles.back(); + const std::filesystem::path fileToRead = allInputFiles.back(); allInputFiles.erase(allInputFiles.end() - 1); // Add reading of file to jobmanager, which will distribute it to our threadpool. @@ -255,7 +260,7 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { _firstRow, _lastRow, nDefaultColumns, - nValuesPerStar, + NValuesPerStar, fitsFileReader ); jobManager.enqueueJob(readFileJob); @@ -271,7 +276,7 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { finishedJobs++; - for (int i = 0; i < 8; ++i) { + for (int i = 0; i < 8; i++) { // Add read values to global octant and check if it's time to write! octants[i].insert( octants[i].end(), @@ -286,7 +291,7 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { octants[i], i, isFirstWrite, - nValuesPerStar + NValuesPerStar ); octants[i].clear(); @@ -295,26 +300,24 @@ void ReadFitsTask::readAllFitsFilesFromFolder(const Task::ProgressCallback&) { } } } - LINFO(fmt::format("A total of {} stars were written to binary files", totalStars)); + LINFO(std::format("A total of {} stars were written to binary files", totalStars)); } int ReadFitsTask::writeOctantToFile(const std::vector& octantData, int index, std::vector& isFirstWrite, int nValuesPerStar) { - std::string outPath = fmt::format( - "{}octant_{}.bin", _outFileOrFolderPath.string(), index - ); + std::string outPath = std::format("{}octant_{}.bin", _outFileOrFolderPath, index); std::ofstream fileStream(outPath, std::ofstream::binary | std::ofstream::app); if (fileStream.good()) { int32_t nValues = static_cast(octantData.size()); - LINFO("Write " + std::to_string(nValues) + " values to " + outPath); + LINFO(std::format("Write {} values to {}", nValues, outPath)); if (nValues == 0) { LERROR("Error writing file - No values were read from file"); } // If this is the first write then write number of values per star! if (isFirstWrite[index]) { - LINFO("First write for Octant_" + std::to_string(index)); + LINFO(std::format("First write for Octant_{}", index)); fileStream.write( reinterpret_cast(&nValuesPerStar), sizeof(int32_t) @@ -322,7 +325,7 @@ int ReadFitsTask::writeOctantToFile(const std::vector& octantData, int in isFirstWrite[index] = false; } - size_t nBytes = nValues * sizeof(octantData[0]); + const size_t nBytes = nValues * sizeof(octantData[0]); fileStream.write(reinterpret_cast(octantData.data()), nBytes); fileStream.close(); @@ -331,7 +334,7 @@ int ReadFitsTask::writeOctantToFile(const std::vector& octantData, int in return nValues / nValuesPerStar; } else { - LERROR(fmt::format("Error opening file: {} as output data file", outPath)); + LERROR(std::format("Error opening file '{}' as output data file", outPath)); return 0; } } diff --git a/modules/gaia/tasks/readspecktask.cpp b/modules/gaia/tasks/readspecktask.cpp index 228730e21c..915368c986 100644 --- a/modules/gaia/tasks/readspecktask.cpp +++ b/modules/gaia/tasks/readspecktask.cpp @@ -59,8 +59,9 @@ ReadSpeckTask::ReadSpeckTask(const ghoul::Dictionary& dictionary) { } std::string ReadSpeckTask::description() { - return fmt::format( - "Read speck file {} and write raw star data into {}", _inFilePath, _outFilePath + return std::format( + "Read speck file '{}' and write raw star data into '{}'", + _inFilePath, _outFilePath ); } @@ -71,7 +72,7 @@ void ReadSpeckTask::perform(const Task::ProgressCallback& onProgress) { FitsFileReader fileReader(false); std::vector fullData = fileReader.readSpeckFile( - _inFilePath.string(), + _inFilePath, nRenderValues ); @@ -88,13 +89,13 @@ void ReadSpeckTask::perform(const Task::ProgressCallback& onProgress) { fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); fileStream.write(reinterpret_cast(&nRenderValues), sizeof(int32_t)); - size_t nBytes = nValues * sizeof(fullData[0]); + const size_t nBytes = nValues * sizeof(fullData[0]); fileStream.write(reinterpret_cast(fullData.data()), nBytes); fileStream.close(); } else { - LERROR(fmt::format("Error opening file: {} as output data file", _outFilePath)); + LERROR(std::format("Error opening file '{}' as output data file", _outFilePath)); } onProgress(1.f); diff --git a/modules/galaxy/rendering/galaxyraycaster.cpp b/modules/galaxy/rendering/galaxyraycaster.cpp index d57644f180..a550a98eef 100644 --- a/modules/galaxy/rendering/galaxyraycaster.cpp +++ b/modules/galaxy/rendering/galaxyraycaster.cpp @@ -44,7 +44,7 @@ namespace { namespace openspace { GalaxyRaycaster::GalaxyRaycaster(ghoul::opengl::Texture& texture, - std::optional raycastingShader) + const std::optional& raycastingShader) : _boundingBox(glm::vec3(1.f)) , _texture(texture) , _textureUnit(nullptr) @@ -90,7 +90,7 @@ void GalaxyRaycaster::renderExitPoints(const RenderData& data, } glm::dmat4 GalaxyRaycaster::modelViewTransform(const RenderData& data) { - glm::dmat4 modelTransform = + const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * @@ -132,7 +132,7 @@ void GalaxyRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramObje } bool GalaxyRaycaster::isCameraInside(const RenderData& data, glm::vec3& localPosition) { - glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * + const glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * glm::vec4(0.f, 0.f, 0.f, 1.f); localPosition = (glm::vec3(modelPos) + glm::vec3(0.5f)); @@ -163,7 +163,7 @@ void GalaxyRaycaster::setAspect(const glm::vec3& aspect) { } void GalaxyRaycaster::setModelTransform(glm::mat4 transform) { - _modelTransform = transform; + _modelTransform = std::move(transform); } void GalaxyRaycaster::setOpacityCoefficient(float opacityCoefficient) { diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index 559d476208..25da69373b 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -46,7 +46,7 @@ struct RaycastData; class GalaxyRaycaster : public VolumeRaycaster { public: GalaxyRaycaster(ghoul::opengl::Texture& texture, - std::optional raycastingShader = std::nullopt); + const std::optional& raycastingShader = std::nullopt); ~GalaxyRaycaster() override = default; void initialize(); diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 1e4b162861..32ab56f184 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -222,7 +222,7 @@ namespace { std::ofstream fileStream(file, std::ofstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for save cache file", file)); + LERROR(std::format("Error opening file '{}' for save cache file", file)); return; } @@ -265,13 +265,13 @@ RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) , _volumeRenderingEnabled(VolumeRenderingEnabledInfo, true) , _starRenderingEnabled(StarRenderingEnabledInfo, true) , _stepSize(StepSizeInfo, 0.01f, 0.001f, 0.05f, 0.001f) - , _absorptionMultiply(AbsorptionMultiplyInfo, 40.f, 0.f, 200.0f) - , _emissionMultiply(EmissionMultiplyInfo, 200.f, 0.f, 1000.0f) + , _absorptionMultiply(AbsorptionMultiplyInfo, 40.f, 0.f, 200.f) + , _emissionMultiply(EmissionMultiplyInfo, 200.f, 0.f, 1000.f) , _starRenderingMethod( StarRenderingMethodInfo, properties::OptionProperty::DisplayType::Dropdown ) - , _enabledPointsRatio(EnabledPointsRatioInfo, 0.5f, 0.01f, 1.0f) + , _enabledPointsRatio(EnabledPointsRatioInfo, 0.5f, 0.01f, 1.f) , _rotation( RotationInfo, glm::vec3(0.f), @@ -345,8 +345,8 @@ RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) void RenderableGalaxy::initialize() { ZoneScoped; - // Aspect is currently hardcoded to cubic voxels. - glm::vec3 d = _volumeDimensions; + // Aspect is currently hardcoded to cubic voxels + const glm::vec3 d = _volumeDimensions; _aspect = d / glm::compMax(d); // The volume @@ -361,8 +361,8 @@ void RenderableGalaxy::initialize() { ); const bool hasCachedFile = std::filesystem::is_regular_file(cachedPointsFile); if (hasCachedFile) { - LINFO(fmt::format("Cached file {} used for galaxy point file {}", - cachedPointsFile, std::filesystem::path(_pointsFilename) + LINFO(std::format("Cached file '{}' used for galaxy point file '{}'", + cachedPointsFile, _pointsFilename )); Result res = loadCachedFile(cachedPointsFile); @@ -459,8 +459,8 @@ void RenderableGalaxy::initializeGL() { ); if (_pointSpreadFunctionTexture) { - LDEBUG(fmt::format( - "Loaded texture from {}", absPath(_pointSpreadFunctionTexturePath) + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_pointSpreadFunctionTexturePath) )); _pointSpreadFunctionTexture->uploadTexture(); } @@ -548,7 +548,7 @@ void RenderableGalaxy::update(const UpdateData& data) { transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0.f, 1.f, 0.f)); transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0.f, 0.f, 1.f)); - glm::mat4 volumeTransform = glm::scale(transform, _volumeSize); + const glm::mat4 volumeTransform = glm::scale(transform, _volumeSize); _pointTransform = transform; _raycaster->setDownscaleRender(_downScaleVolumeRendering); @@ -564,7 +564,7 @@ void RenderableGalaxy::update(const UpdateData& data) { void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { // Render the volume if (_raycaster && _volumeRenderingEnabled) { - RaycasterTask task { _raycaster.get(), data }; + const RaycasterTask task { _raycaster.get(), data }; const glm::vec3 position = data.camera.positionVec3(); const float length = safeLength(position); @@ -608,7 +608,7 @@ void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { } } - if (!(_starRenderingEnabled && _opacityCoefficient > 0.f)) { + if (!_starRenderingEnabled || _opacityCoefficient <= 0.f) { return; } @@ -631,7 +631,7 @@ void RenderableGalaxy::renderPoints(const RenderData& data) { _pointsProgram->activate(); - glm::dmat4 rotMatrix = glm::rotate( + const glm::dmat4 rotMatrix = glm::rotate( glm::dmat4(1.0), glm::pi(), glm::dvec3(1.0, 0.0, 0.0)) * @@ -639,11 +639,12 @@ void RenderableGalaxy::renderPoints(const RenderData& data) { glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) ); - AlternativeTransform altTransform; - altTransform.rotation = glm::dmat4(data.modelTransform.rotation) * rotMatrix; - glm::dmat4 modelTransform = calcModelTransform(data, altTransform); + const AlternativeTransform altTransform = { + .rotation = glm::dmat4(data.modelTransform.rotation) * rotMatrix + }; + const glm::dmat4 modelTransform = calcModelTransform(data, altTransform); - glm::dmat4 cameraViewProjectionMatrix = + const glm::dmat4 cameraViewProjectionMatrix = glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix(); _pointsProgram->setUniform(_uniformCachePoints.modelMatrix, modelTransform); @@ -652,7 +653,7 @@ void RenderableGalaxy::renderPoints(const RenderData& data) { cameraViewProjectionMatrix ); - glm::dvec3 eyePosition = glm::dvec3( + const glm::dvec3 eyePosition = glm::dvec3( glm::inverse(data.camera.combinedViewMatrix()) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); @@ -681,7 +682,7 @@ void RenderableGalaxy::renderBillboards(const RenderData& data) { _billboardsProgram->activate(); - glm::dmat4 rotMatrix = glm::rotate( + const glm::dmat4 rotMatrix = glm::rotate( glm::dmat4(1.0), glm::pi(), glm::dvec3(1.0, 0.0, 0.0)) * @@ -689,11 +690,12 @@ void RenderableGalaxy::renderBillboards(const RenderData& data) { glm::rotate(glm::dmat4(1.0), 4.45741, glm::dvec3(0.0, 0.0, 1.0) ); - AlternativeTransform altTransform; - altTransform.rotation = glm::dmat4(data.modelTransform.rotation) * rotMatrix; - glm::dmat4 modelTransform = calcModelTransform(data, altTransform); + const AlternativeTransform altTransform = { + .rotation = glm::dmat4(data.modelTransform.rotation) * rotMatrix + }; + const glm::dmat4 modelTransform = calcModelTransform(data, altTransform); - glm::dmat4 cameraViewProjectionMatrix = + const glm::dmat4 cameraViewProjectionMatrix = glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix(); _billboardsProgram->setUniform(_uniformCacheBillboards.modelMatrix, modelTransform); @@ -702,13 +704,13 @@ void RenderableGalaxy::renderBillboards(const RenderData& data) { cameraViewProjectionMatrix ); - glm::dvec3 eyePosition = glm::dvec3( + const glm::dvec3 eyePosition = glm::dvec3( glm::inverse(data.camera.combinedViewMatrix()) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); _billboardsProgram->setUniform(_uniformCacheBillboards.eyePosition, eyePosition); - glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); + const glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); _billboardsProgram->setUniform(_uniformCacheBillboards.cameraUp, cameraUp); ghoul::opengl::TextureUnit psfUnit; @@ -728,11 +730,7 @@ void RenderableGalaxy::renderBillboards(const RenderData& data) { } RenderableGalaxy::Result RenderableGalaxy::loadPointFile() { - std::vector pointPositions; - std::vector pointColors; - int64_t nPoints; - - std::ifstream pointFile(_pointsFilename, std::ios::in); + std::ifstream pointFile = std::ifstream(_pointsFilename, std::ios::in); // Read header for OFF (Object File Format) std::string line; @@ -741,17 +739,26 @@ RenderableGalaxy::Result RenderableGalaxy::loadPointFile() { // Read point count std::getline(pointFile, line); std::istringstream iss(line); + int64_t nPoints = 0; iss >> nPoints; // Prepare point reading _nPoints = static_cast(nPoints); + std::vector pointPositions; + std::vector pointColors; // Read points for (size_t i = 0; i < static_cast(_nPoints * _enabledPointsRatio.maxValue()) + 1; - ++i) + i++) { - float x, y, z, r, g, b, a; + float x = 0.f; + float y = 0.f; + float z = 0.f; + float r = 0.f; + float g = 0.f; + float b = 0.f; + float a = 0.f; std::getline(pointFile, line); std::istringstream issp(line); issp >> x >> y >> z >> r >> g >> b >> a; @@ -774,28 +781,28 @@ RenderableGalaxy::Result RenderableGalaxy::loadPointFile() { RenderableGalaxy::Result RenderableGalaxy::loadCachedFile( const std::filesystem::path& file) { - std::ifstream fileStream(file, std::ifstream::binary); + std::ifstream fileStream = std::ifstream(file, std::ifstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for loading cache file", file)); + LERROR(std::format("Error opening file '{}' for loading cache file", file)); return { false, {}, {} }; } - int8_t cacheVersion; + int8_t cacheVersion = 0; fileStream.read(reinterpret_cast(&cacheVersion), sizeof(int8_t)); if (cacheVersion != CurrentCacheVersion) { - LINFO(fmt::format("Removing cache file {} as the version changed", file)); + LINFO(std::format("Removing cache file '{}' as the version changed", file)); return { false, {}, {} }; } - int64_t nPoints; + int64_t nPoints = 0; fileStream.read(reinterpret_cast(&nPoints), sizeof(int64_t)); _nPoints = static_cast(nPoints); - float enabledPointsRatio; + float enabledPointsRatio = false; fileStream.read(reinterpret_cast(&enabledPointsRatio), sizeof(float)); _enabledPointsRatio = enabledPointsRatio; - uint64_t nPositions; + uint64_t nPositions = 0; fileStream.read(reinterpret_cast(&nPositions), sizeof(uint64_t)); std::vector positions; positions.resize(nPositions); @@ -804,7 +811,7 @@ RenderableGalaxy::Result RenderableGalaxy::loadCachedFile( nPositions * sizeof(glm::vec3) ); - uint64_t nColors; + uint64_t nColors = 0; fileStream.read(reinterpret_cast(&nColors), sizeof(uint64_t)); std::vector colors; colors.resize(nColors); diff --git a/modules/galaxy/tasks/milkywayconversiontask.cpp b/modules/galaxy/tasks/milkywayconversiontask.cpp index a03b838d9f..b199db45be 100644 --- a/modules/galaxy/tasks/milkywayconversiontask.cpp +++ b/modules/galaxy/tasks/milkywayconversiontask.cpp @@ -27,11 +27,7 @@ #include #include #include -#include - -#include #include - #include namespace { @@ -45,10 +41,7 @@ namespace { namespace openspace { -MilkywayConversionTask::MilkywayConversionTask(const ghoul::Dictionary& dictionary) - : _inFirstIndex(0) - , _inNSlices(0) -{ +MilkywayConversionTask::MilkywayConversionTask(const ghoul::Dictionary& dictionary) { if (dictionary.hasKey(KeyInFilenamePrefix)) { _inFilenamePrefix = dictionary.value(KeyInFilenamePrefix); } @@ -92,17 +85,16 @@ void MilkywayConversionTask::perform(const Task::ProgressCallback& onProgress) { const glm::vec3 resolutionRatio = static_cast(sliceReader.dimensions()) / static_cast(rawWriter.dimensions()); - VolumeSampler>> sampler( + const VolumeSampler>> sampler( &sliceReader, resolutionRatio ); - std::function(glm::ivec3)> sampleFunction = - [resolutionRatio, sampler](glm::ivec3 outCoord) { - const glm::vec3 inCoord = ((glm::vec3(outCoord) + glm::vec3(0.5f)) * - resolutionRatio) - glm::vec3(0.5f); - const glm::tvec4 value = sampler.sample(inCoord); - return value; - }; + auto sampleFunction = [resolutionRatio, sampler](const glm::ivec3& outCoord) { + const glm::vec3 inCoord = + ((glm::vec3(outCoord) + glm::vec3(0.5f)) * resolutionRatio) - glm::vec3(0.5f); + const glm::tvec4 value = sampler.sample(inCoord); + return value; + }; rawWriter.write(sampleFunction, onProgress); } diff --git a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp index 93affdf86e..62dd447acc 100644 --- a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp +++ b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp @@ -50,22 +50,22 @@ void MilkywayPointsConversionTask::perform(const Task::ProgressCallback& progres std::ofstream out(_outFilename, std::ios::out | std::ios::binary); std::string format; - int64_t nPoints; + int64_t nPoints = 0; in >> format >> nPoints; - size_t nFloats = nPoints * 7; + const size_t nFloats = nPoints * 7; std::vector pointData(nFloats); - float x; - float y; - float z; - float r; - float g; - float b; - float a; + float x = 0.f; + float y = 0.f; + float z = 0.f; + float r = 0.f; + float g = 0.f; + float b = 0.f; + float a = 0.f; - for (int64_t i = 0; i < nPoints; ++i) { + for (int64_t i = 0; i < nPoints; i++) { in >> x >> y >> z >> r >> g >> b >> a; if (in.good()) { pointData[i * 7 + 0] = x; diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index c1aeefcced..934d855f1b 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -136,11 +136,11 @@ namespace { int currentLayerNumber = -1; Layer currentLayer; - for (int i = 0; i < nSubdatasets; ++i) { + for (int i = 0; i < nSubdatasets; i++) { int iDataset = -1; std::array IdentifierBuffer; std::fill(IdentifierBuffer.begin(), IdentifierBuffer.end(), '\0'); - int ret = sscanf( + const int ret = sscanf( subDatasets[i], "SUBDATASET_%i_%255[^=]", &iDataset, @@ -181,7 +181,6 @@ namespace { } struct [[codegen::Dictionary(GlobeBrowsingModule)]] Parameters { - // [[codegen::verbatim(TileCacheSizeInfo.description)]] std::optional tileCacheSize; @@ -230,10 +229,13 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { _hasDefaultGeoPointTexture = true; } else { - LWARNINGC("GlobeBrowsingModule", fmt::format( - "The provided texture file {} for the default geo point texture " - "does not exist", path - )); + LWARNINGC( + "GlobeBrowsingModule", + std::format( + "The provided texture file '{}' for the default geo point texture " + "does not exist", path + ) + ); } }); @@ -424,8 +426,8 @@ glm::dvec3 GlobeBrowsingModule::geoPosition() const { posHandle.centerToReferenceSurface ); - double lat = glm::degrees(geo2.lat); - double lon = glm::degrees(geo2.lon); + const double lat = glm::degrees(geo2.lat); + const double lon = glm::degrees(geo2.lon); double altitude = glm::length( cameraPositionModelSpace - posHandle.centerToReferenceSurface @@ -442,7 +444,7 @@ glm::dvec3 GlobeBrowsingModule::geoPosition() const { void GlobeBrowsingModule::goToChunk(const globebrowsing::RenderableGlobe& globe, const globebrowsing::TileIndex& ti, - glm::vec2 uv, bool doResetCameraDirection) + const glm::vec2& uv, bool doResetCameraDirection) { using namespace globebrowsing; @@ -489,6 +491,7 @@ void GlobeBrowsingModule::goToGeodetic2(const globebrowsing::RenderableGlobe& gl SceneGraphNode* globeSceneGraphNode = dynamic_cast(globe.owner()); if (!globeSceneGraphNode) { LERROR("Error when going to Geodetic2"); + return; } const glm::dmat4 inverseModelTransform = glm::inverse( @@ -634,7 +637,7 @@ GlobeBrowsingModule::urlInfo(const std::string& globe) const { const auto range = _urlList.equal_range(globe); std::vector res; - for (auto i = range.first; i != range.second; ++i) { + for (auto i = range.first; i != range.second; i++) { res.emplace_back(i->second); } return res; @@ -648,7 +651,7 @@ bool GlobeBrowsingModule::isMRFCachingEnabled() const { return _mrfCacheEnabled; } -const std::string GlobeBrowsingModule::mrfCacheLocation() const { +std::string GlobeBrowsingModule::mrfCacheLocation() const { return _mrfCacheLocation; } diff --git a/modules/globebrowsing/globebrowsingmodule.h b/modules/globebrowsing/globebrowsingmodule.h index 21da668fb5..429c09741f 100644 --- a/modules/globebrowsing/globebrowsingmodule.h +++ b/modules/globebrowsing/globebrowsingmodule.h @@ -93,7 +93,7 @@ public: void removeWMSServer(const std::string& name); bool isMRFCachingEnabled() const; - const std::string mrfCacheLocation() const; + std::string mrfCacheLocation() const; bool hasDefaultGeoPointTexture() const; std::string_view defaultGeoPointTexture() const; @@ -103,7 +103,8 @@ protected: private: void goToChunk(const globebrowsing::RenderableGlobe& globe, - const globebrowsing::TileIndex& ti, glm::vec2 uv, bool doResetCameraDirection); + const globebrowsing::TileIndex& ti, const glm::vec2& uv, + bool doResetCameraDirection); void goToGeodetic2(const globebrowsing::RenderableGlobe& globe, globebrowsing::Geodetic2 geo2, bool doResetCameraDirection); diff --git a/modules/globebrowsing/globebrowsingmodule_lua.inl b/modules/globebrowsing/globebrowsingmodule_lua.inl index 1a01cd7ff7..fbf03fff1a 100644 --- a/modules/globebrowsing/globebrowsingmodule_lua.inl +++ b/modules/globebrowsing/globebrowsingmodule_lua.inl @@ -191,7 +191,7 @@ namespace { SceneGraphNode* n = sceneGraphNode(globeIdentifier); if (!n) { - throw ghoul::lua::LuaError(fmt::format("Unknown globe: {}", globeIdentifier)); + throw ghoul::lua::LuaError(std::format("Unknown globe '{}'", globeIdentifier)); } RenderableGlobe* globe = dynamic_cast(n->renderable()); @@ -201,7 +201,7 @@ namespace { layers::Group::ID group = ghoul::from_string(layerGroup); if (group == layers::Group::ID::Unknown) { - throw ghoul::lua::LuaError(fmt::format("Unknown layer group: {}", layerGroup)); + throw ghoul::lua::LuaError(std::format("Unknown layer group '{}'", layerGroup)); } LayerGroup& lg = globe->layerManager().layerGroup(group); @@ -225,7 +225,7 @@ namespace { } ); if (it == layers.cend()) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Could not find source layer '{}'", std::get(source) )); } @@ -245,7 +245,7 @@ namespace { } ); if (it == layers.cend()) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Could not find destination layer '{}'", std::get(source) )); } @@ -582,7 +582,7 @@ geoPositionForCameraDeprecated(bool useEyePosition = false) std::vector res; res.reserve(cap.size()); - for (size_t i = 0; i < cap.size(); ++i) { + for (size_t i = 0; i < cap.size(); i++) { ghoul::Dictionary c; c.setValue("Name", cap[i].name); c.setValue("URL", cap[i].url); @@ -668,8 +668,8 @@ geoPositionForCameraDeprecated(bool useEyePosition = false) std::filesystem::path path = absPath(filename); if (!std::filesystem::is_regular_file(path)) { - throw ghoul::lua::LuaError(fmt::format( - "Could not find the provided file: '{}'", filename + throw ghoul::lua::LuaError(std::format( + "Could not find the provided file '{}'", filename )); } @@ -677,8 +677,8 @@ geoPositionForCameraDeprecated(bool useEyePosition = false) extension = ghoul::toLowerCase(extension); if (extension != ".geojson" && extension != ".json") { - throw ghoul::lua::LuaError(fmt::format( - "Unexpected file type: '{}'. Expected '.geojson' or '.json' file", filename + throw ghoul::lua::LuaError(std::format( + "Unexpected file type '{}'. Expected '.geojson' or '.json' file", filename )); } diff --git a/modules/globebrowsing/shaders/geojson_fs.glsl b/modules/globebrowsing/shaders/geojson_fs.glsl index 97c8bbc0c8..00461563a0 100644 --- a/modules/globebrowsing/shaders/geojson_fs.glsl +++ b/modules/globebrowsing/shaders/geojson_fs.glsl @@ -57,7 +57,7 @@ Fragment getFragment() { // Ambient color vec3 shadedColor = ambientIntensity * color; - for (int i = 0; i < nLightSources; ++i) { + for (int i = 0; i < nLightSources; i++) { vec3 l = lightDirectionsViewSpace[i]; // Diffuse diff --git a/modules/globebrowsing/src/asynctiledataprovider.cpp b/modules/globebrowsing/src/asynctiledataprovider.cpp index 815e2031ed..39df0e623e 100644 --- a/modules/globebrowsing/src/asynctiledataprovider.cpp +++ b/modules/globebrowsing/src/asynctiledataprovider.cpp @@ -113,7 +113,7 @@ bool AsyncTileDataProvider::satisfiesEnqueueCriteria(const TileIndex& tileIndex) } void AsyncTileDataProvider::endUnfinishedJobs() { - std::vector unfinishedJobs = + const std::vector unfinishedJobs = _concurrentJobManager.keysToUnfinishedJobs(); for (const TileIndex::TileHashKey& unfinishedJob : unfinishedJobs) { // When erasing the job before @@ -122,7 +122,7 @@ void AsyncTileDataProvider::endUnfinishedJobs() { } void AsyncTileDataProvider::endEnqueuedJobs() { - std::vector enqueuedJobs = + const std::vector enqueuedJobs = _concurrentJobManager.keysToEnqueuedJobs(); for (const TileIndex::TileHashKey& enqueuedJob : enqueuedJobs) { // When erasing the job before @@ -141,7 +141,7 @@ void AsyncTileDataProvider::update() { // Only allow resetting if there are no jobs currently running if (_enqueuedTileRequests.empty()) { performReset(ResetRawTileDataReader::Yes); - LINFO(fmt::format("Tile data reader '{}' reset successfully", _name)); + LINFO(std::format("Tile data reader '{}' reset successfully", _name)); } break; case ResetMode::ShouldResetAllButRawTileDataReader: @@ -150,7 +150,7 @@ void AsyncTileDataProvider::update() { // Only allow resetting if there are no jobs currently running if (_enqueuedTileRequests.empty()) { performReset(ResetRawTileDataReader::No); - LINFO(fmt::format("Tile data reader '{}' reset successfully", _name)); + LINFO(std::format("Tile data reader '{}' reset successfully", _name)); } break; case ResetMode::ShouldBeDeleted: @@ -172,7 +172,7 @@ void AsyncTileDataProvider::reset() { // we need to wait until _enqueuedTileRequests is empty before finishing up. _resetMode = ResetMode::ShouldResetAll; endEnqueuedJobs(); - LINFO(fmt::format("Prepairing for resetting of tile reader '{}'", _name)); + LINFO(std::format("Prepairing for resetting of tile reader '{}'", _name)); } void AsyncTileDataProvider::prepareToBeDeleted() { @@ -180,7 +180,7 @@ void AsyncTileDataProvider::prepareToBeDeleted() { endEnqueuedJobs(); } -bool AsyncTileDataProvider::shouldBeDeleted() { +bool AsyncTileDataProvider::shouldBeDeleted() const { return _shouldBeDeleted; } diff --git a/modules/globebrowsing/src/asynctiledataprovider.h b/modules/globebrowsing/src/asynctiledataprovider.h index 4b5b36c06d..f9de5e2fe0 100644 --- a/modules/globebrowsing/src/asynctiledataprovider.h +++ b/modules/globebrowsing/src/asynctiledataprovider.h @@ -65,7 +65,7 @@ public: void reset(); void prepareToBeDeleted(); - bool shouldBeDeleted(); + bool shouldBeDeleted() const; const RawTileDataReader& rawTileDataReader() const; float noDataValueAsFloat() const; diff --git a/modules/globebrowsing/src/dashboarditemglobelocation.cpp b/modules/globebrowsing/src/dashboarditemglobelocation.cpp index 2abbfd5c9b..740e15d10f 100644 --- a/modules/globebrowsing/src/dashboarditemglobelocation.cpp +++ b/modules/globebrowsing/src/dashboarditemglobelocation.cpp @@ -92,14 +92,14 @@ DashboardItemGlobeLocation::DashboardItemGlobeLocation( auto updateFormatString = [this]() { switch (_displayFormat.value()) { case static_cast(DisplayFormat::DecimalDegrees): - _formatString = fmt::format( + _formatString = std::format( "Position: {{:03.{0}f}}, {{:03.{0}f}} " "Altitude: {{:03.{0}f}} {{}}", _significantDigits.value() ); break; case static_cast(DisplayFormat::DegreeMinuteSeconds): - _formatString = fmt::format( + _formatString = std::format( "Position: {{}}d {{}}' {{:03.{0}f}}\" {{}}, " "{{}}d {{}}' {{:03.{0}f}}\" {{}} " "Altitude: {{:03.{0}f}} {{}}", @@ -145,10 +145,10 @@ void DashboardItemGlobeLocation::render(glm::vec2& penPosition) { GlobeBrowsingModule* module = global::moduleEngine->module(); - glm::dvec3 position = module->geoPosition(); + const glm::dvec3 position = module->geoPosition(); double lat = position.x; double lon = position.y; - double altitude = position.z; + const double altitude = position.z; std::pair dist = simplifyDistance(altitude); @@ -157,9 +157,11 @@ void DashboardItemGlobeLocation::render(glm::vec2& penPosition) { switch (_displayFormat.value()) { case static_cast(DisplayFormat::DecimalDegrees): { - end = fmt::format_to( + // @CPP26(abock): This can be replaced with std::runtime_format + end = std::vformat_to( _buffer.data(), - fmt::runtime(_formatString), lat, lon, dist.first, dist.second + _formatString, + std::make_format_args(lat, lon, dist.first, dist.second) ); break; } @@ -184,20 +186,22 @@ void DashboardItemGlobeLocation::render(glm::vec2& penPosition) { const double lonSec = lonMinRemainder * 60.f; - end = fmt::format_to( + // @CPP26(abock): This can be replaced with std::runtime_format + end = std::vformat_to( _buffer.data(), - fmt::runtime(_formatString), - latDeg, latMin, latSec, isNorth ? "N" : "S", - lonDeg, lonMin, lonSec, isEast ? "E" : "W", - dist.first, dist.second + _formatString, + std::make_format_args( + latDeg, latMin, latSec, isNorth ? "N" : "S", + lonDeg, lonMin, lonSec, isEast ? "E" : "W", + dist.first, dist.second + ) ); break; } } - std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); - + const std::string_view text = std::string_view(_buffer.data(), end - _buffer.data()); RenderFont(*_font, penPosition, text); penPosition.y -= _font->height(); } @@ -206,7 +210,7 @@ glm::vec2 DashboardItemGlobeLocation::size() const { ZoneScoped; return _font->boundingBox( - fmt::format("Position: {}, {} Altitude: {}", 1.f, 1.f, 1.f) + std::format("Position: {}, {} Altitude: {}", 1.f, 1.f, 1.f) ); } diff --git a/modules/globebrowsing/src/ellipsoid.cpp b/modules/globebrowsing/src/ellipsoid.cpp index 152ea404bc..49bd8537bf 100644 --- a/modules/globebrowsing/src/ellipsoid.cpp +++ b/modules/globebrowsing/src/ellipsoid.cpp @@ -35,7 +35,7 @@ namespace { namespace openspace::globebrowsing { -Ellipsoid::Ellipsoid(glm::dvec3 radii) : _radii(radii) { +Ellipsoid::Ellipsoid(glm::dvec3 radii) : _radii(std::move(radii)) { updateInternalCache(); } @@ -66,7 +66,7 @@ glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { double s = 0.0; double dSdA = 1.0; - double epsilon = 1e-10; + constexpr double Epsilon = 1e-10; size_t nIterations = 0; do { @@ -81,7 +81,7 @@ glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { dSdA = -2.0 * glm::dot(p2 / (_cached.radiiToTheFourth * d3), glm::dvec3(1.0)); ++nIterations; } - while (std::abs(s) > epsilon && nIterations < MaxIterations); + while (std::abs(s) > Epsilon && nIterations < MaxIterations); return p / d; } diff --git a/modules/globebrowsing/src/gdalwrapper.cpp b/modules/globebrowsing/src/gdalwrapper.cpp index 06d547b825..3bb7c0093d 100644 --- a/modules/globebrowsing/src/gdalwrapper.cpp +++ b/modules/globebrowsing/src/gdalwrapper.cpp @@ -140,13 +140,13 @@ void GdalWrapper::setGdalProxyConfiguration() { const std::string proxy = address + ":" + std::to_string(port); CPLSetConfigOption("GDAL_HTTP_PROXY", proxy.c_str()); - LDEBUG(fmt::format("Using proxy server {}", proxy)); + LDEBUG(std::format("Using proxy server '{}'", proxy)); if (!user.empty() && !password.empty()) { - std::string userPwd = user + ":" + password; + const std::string userPwd = user + ":" + password; CPLSetConfigOption("GDAL_HTTP_PROXYUSERPWD", userPwd.c_str()); CPLSetConfigOption("GDAL_HTTP_PROXYAUTH", auth.c_str()); - LDEBUG(fmt::format("Using authentication method: {}", auth)); + LDEBUG(std::format("Using authentication method: {}", auth)); } } } diff --git a/modules/globebrowsing/src/geodeticpatch.cpp b/modules/globebrowsing/src/geodeticpatch.cpp index dec6b77720..86f3d4c3bf 100644 --- a/modules/globebrowsing/src/geodeticpatch.cpp +++ b/modules/globebrowsing/src/geodeticpatch.cpp @@ -154,8 +154,8 @@ Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { // --> Just clamping pointLat would be clamp(330, -10, 10) = 10 // WRONG! // Instead, if we first normalize 330 deg around 0, we get -30 deg // --> clamp(-30, -10, 10) = -10 // CORRECT! - double pointLat = normalizedAngleAround(p.lat, _center.lat); - double pointLon = normalizedAngleAround(p.lon, _center.lon); + const double pointLat = normalizedAngleAround(p.lat, _center.lat); + const double pointLon = normalizedAngleAround(p.lon, _center.lon); return { glm::clamp(pointLat, minLat(), maxLat()), @@ -219,8 +219,8 @@ Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { // Normalize point with respect to center. This is done because the point // will later be clamped. See LatLonPatch::clamp(const LatLon&) for explanation - double pointLat = normalizedAngleAround(p.lat, _center.lat); - double pointLon = normalizedAngleAround(p.lon, _center.lon); + const double pointLat = normalizedAngleAround(p.lat, _center.lat); + const double pointLon = normalizedAngleAround(p.lon, _center.lon); // Calculate the longitud difference between center and point. We normalize around // zero because we want the "shortest distance" difference, i.e the difference diff --git a/modules/globebrowsing/src/geojson/geojsoncomponent.cpp b/modules/globebrowsing/src/geojson/geojsoncomponent.cpp index 7abd7f820f..cd86bac7f8 100644 --- a/modules/globebrowsing/src/geojson/geojsoncomponent.cpp +++ b/modules/globebrowsing/src/geojson/geojsoncomponent.cpp @@ -250,7 +250,7 @@ documentation::Documentation GeoJsonComponent::Documentation() { GeoJsonComponent::SubFeatureProps::SubFeatureProps( properties::PropertyOwner::PropertyOwnerInfo info) - : properties::PropertyOwner(info) + : properties::PropertyOwner(std::move(info)) , enabled(EnabledInfo, true) , centroidLatLong( CentroidCoordinateInfo, @@ -362,14 +362,14 @@ GeoJsonComponent::GeoJsonComponent(const ghoul::Dictionary& dictionary, addPropertySubOwner(_defaultProperties); _defaultProperties.pointTexture.onChange([this]() { - std::filesystem::path texturePath = _defaultProperties.pointTexture.value(); + const std::filesystem::path texturePath = _defaultProperties.pointTexture.value(); // Not ethat an empty texture is also valid => use default texture from module if (std::filesystem::is_regular_file(texturePath) || texturePath.empty()) { _textureIsDirty = true; } else { - LERROR(fmt::format( - "Provided texture file does not exist: '{}'", + LERROR(std::format( + "Provided texture file does not exist: {}", _defaultProperties.pointTexture.value() )); } @@ -424,7 +424,7 @@ GeoJsonComponent::GeoJsonComponent(const ghoul::Dictionary& dictionary, readFile(); if (p.lightSources.has_value()) { - std::vector lightsources = *p.lightSources; + const std::vector lightsources = *p.lightSources; for (const ghoul::Dictionary& lsDictionary : lightsources) { std::unique_ptr lightSource = @@ -497,7 +497,7 @@ void GeoJsonComponent::deinitializeGL() { } bool GeoJsonComponent::isReady() const { - bool isReady = std::all_of( + const bool isReady = std::all_of( std::begin(_geometryFeatures), std::end(_geometryFeatures), std::mem_fn(&GlobeGeometryFeature::isReady) @@ -537,7 +537,7 @@ void GeoJsonComponent::render(const RenderData& data) { // Do two render passes, to properly render opacity of overlaying objects for (int renderPass = 0; renderPass < 2; ++renderPass) { - for (size_t i = 0; i < _geometryFeatures.size(); ++i) { + for (size_t i = 0; i < _geometryFeatures.size(); i++) { if (_features[i]->enabled && _features[i]->isVisible()) { _geometryFeatures[i].render( data, @@ -567,9 +567,9 @@ void GeoJsonComponent::update() { return; } - glm::vec3 offsets = glm::vec3(_latLongOffset.value(), _heightOffset); + const glm::vec3 offsets = glm::vec3(_latLongOffset.value(), _heightOffset); - for (size_t i = 0; i < _geometryFeatures.size(); ++i) { + for (size_t i = 0; i < _geometryFeatures.size(); i++) { if (!_features[i]->enabled) { continue; } @@ -594,32 +594,30 @@ void GeoJsonComponent::readFile() { std::ifstream file(_geoJsonFile); if (!file.good()) { - LERROR(fmt::format("Failed to open GeoJSON file: {}", _geoJsonFile.value())); + LERROR(std::format("Failed to open GeoJSON file: {}", _geoJsonFile.value())); return; } _geometryFeatures.clear(); - std::string content( - (std::istreambuf_iterator(file)), - (std::istreambuf_iterator()) + const std::string content = std::string( + std::istreambuf_iterator(file), + std::istreambuf_iterator() ); // Parse GeoJSON string into GeoJSON objects - using namespace geos::io; - GeoJSONReader reader; - try { - GeoJSONFeatureCollection fc = reader.readFeatures(content); + const geos::io::GeoJSONReader reader; + const geos::io::GeoJSONFeatureCollection fc = reader.readFeatures(content); int count = 1; - for (const GeoJSONFeature& feature : fc.getFeatures()) { + for (const geos::io::GeoJSONFeature& feature : fc.getFeatures()) { parseSingleFeature(feature, count); count++; } if (_geometryFeatures.empty()) { - LWARNING(fmt::format( + LWARNING(std::format( "No GeoJson features could be successfully created for GeoJson layer " "with identifier '{}'. Disabling layer.", identifier() )); @@ -627,9 +625,9 @@ void GeoJsonComponent::readFile() { } } catch (const geos::util::GEOSException& e) { - LERROR(fmt::format( + LERROR(std::format( "Error creating GeoJson layer with identifier '{}'. Problem reading " - "GeoJson file '{}'. Error: '{}'", identifier(), _geoJsonFile.value(), e.what() + "GeoJson file '{}'. Error: {}", identifier(), _geoJsonFile.value(), e.what() )); } @@ -648,7 +646,7 @@ void GeoJsonComponent::parseSingleFeature(const geos::io::GeoJSONFeature& featur std::vector geomsToAdd; if (!geom) { // Null geometry => no geometries to add - LWARNING(fmt::format( + LWARNING(std::format( "Feature {} in GeoJson file '{}' is a null geometry and will not be loaded", indexInFile, _geoJsonFile.value() )); @@ -659,9 +657,9 @@ void GeoJsonComponent::parseSingleFeature(const geos::io::GeoJSONFeature& featur geomsToAdd = { geom }; } else { - size_t nGeom = geom->getNumGeometries(); + const size_t nGeom = geom->getNumGeometries(); geomsToAdd.reserve(nGeom); - for (size_t i = 0; i < nGeom; ++i) { + for (size_t i = 0; i < nGeom; i++) { const geos::geom::Geometry* subGeometry = geom->getGeometryN(i); if (subGeometry) { geomsToAdd.push_back(subGeometry); @@ -685,12 +683,12 @@ void GeoJsonComponent::parseSingleFeature(const geos::io::GeoJSONFeature& featur // If there is already an owner with that name as an identifier, make a // unique one if (_featuresPropertyOwner.hasPropertySubOwner(identifier)) { - identifier = fmt::format("Feature{}-", index, identifier); + identifier = std::format("Feature{}-", index, identifier); } - properties::PropertyOwner::PropertyOwnerInfo info = { - identifier, - name + const properties::PropertyOwner::PropertyOwnerInfo info = { + std::move(identifier), + std::move(name) // @TODO: Use description from file, if any }; _features.push_back(std::make_unique(info)); @@ -700,7 +698,7 @@ void GeoJsonComponent::parseSingleFeature(const geos::io::GeoJSONFeature& featur _featuresPropertyOwner.addPropertySubOwner(_features.back().get()); } catch (const ghoul::RuntimeError& error) { - LERROR(fmt::format( + LERROR(std::format( "Error creating GeoJson layer with identifier '{}'. Problem reading " "feature {} in GeoJson file '{}'.", identifier(), indexInFile, _geoJsonFile.value() @@ -720,7 +718,7 @@ void GeoJsonComponent::addMetaPropertiesToFeature(SubFeatureProps& feature, int // but on Windows it returns // geos::geom::CoordinateXY auto centroidCoord = *centroid->getCoordinate(); - glm::vec2 centroidLatLong = glm::vec2(centroidCoord.y, centroidCoord.x); + const glm::vec2 centroidLatLong = glm::vec2(centroidCoord.y, centroidCoord.x); feature.centroidLatLong = centroidLatLong; std::unique_ptr boundingbox = geometry->getEnvelope(); @@ -750,12 +748,12 @@ void GeoJsonComponent::addMetaPropertiesToFeature(SubFeatureProps& feature, int feature.boundingboxLatLong = boundingboxLatLong; // Compute the diagonal distance of the bounding box - Geodetic2 pos0 = { + const Geodetic2 pos0 = { glm::radians(boundingboxLatLong.x), glm::radians(boundingboxLatLong.y) }; - Geodetic2 pos1 = { + const Geodetic2 pos1 = { glm::radians(boundingboxLatLong.z), glm::radians(boundingboxLatLong.w) }; @@ -800,12 +798,12 @@ void GeoJsonComponent::computeMainFeatureMetaPropeties() { _centerLatLong = 0.5f * (bboxLowerCorner + bboxUpperCorner); // Compute the diagonal distance (size) of the bounding box - Geodetic2 pos0 = { + const Geodetic2 pos0 = { glm::radians(bboxLowerCorner.x), glm::radians(bboxLowerCorner.y) }; - Geodetic2 pos1 = { + const Geodetic2 pos1 = { glm::radians(bboxUpperCorner.x), glm::radians(bboxUpperCorner.y) }; @@ -837,8 +835,8 @@ void GeoJsonComponent::flyToFeature(std::optional index) const { float lon = centroidLon + _latLongOffset.value().y; global::scriptEngine->queueScript( - fmt::format( - "openspace.globebrowsing.flyToGeo(\"{}\", {}, {}, {})", + std::format( + "openspace.globebrowsing.flyToGeo([[{}]], {}, {}, {})", _globeNode.owner()->identifier(), lat, lon, d ), scripting::ScriptEngine::ShouldBeSynchronized::Yes, @@ -848,8 +846,8 @@ void GeoJsonComponent::flyToFeature(std::optional index) const { void GeoJsonComponent::triggerDeletion() const { global::scriptEngine->queueScript( - fmt::format( - "openspace.globebrowsing.deleteGeoJson(\"{}\", \"{}\")", + std::format( + "openspace.globebrowsing.deleteGeoJson([[{}]], [[{}]])", _globeNode.owner()->identifier(), _identifier ), scripting::ScriptEngine::ShouldBeSynchronized::Yes, diff --git a/modules/globebrowsing/src/geojson/geojsonmanager.cpp b/modules/globebrowsing/src/geojson/geojsonmanager.cpp index a66710a745..3a6dc63545 100644 --- a/modules/globebrowsing/src/geojson/geojsonmanager.cpp +++ b/modules/globebrowsing/src/geojson/geojsonmanager.cpp @@ -60,7 +60,7 @@ void GeoJsonManager::deinitializeGL() { } bool GeoJsonManager::isReady() const { - bool isReady = std::all_of( + const bool isReady = std::all_of( std::begin(_geoJsonObjects), std::end(_geoJsonObjects), [](const std::unique_ptr& g) { @@ -81,7 +81,7 @@ void GeoJsonManager::addGeoJsonLayer(const ghoul::Dictionary& layerDict) { "GeoJsonComponent" ); - std::string identifier = layerDict.value("Identifier"); + const std::string identifier = layerDict.value("Identifier"); if (hasPropertySubOwner(identifier)) { LERROR("GeoJson layer with identifier '" + identifier + "' already exists"); return; @@ -108,15 +108,12 @@ void GeoJsonManager::addGeoJsonLayer(const ghoul::Dictionary& layerDict) { void GeoJsonManager::deleteLayer(const std::string& layerIdentifier) { ZoneScoped; - for (auto it = _geoJsonObjects.begin(); it != _geoJsonObjects.end(); ++it) { + for (auto it = _geoJsonObjects.begin(); it != _geoJsonObjects.end(); it++) { if (it->get()->identifier() == layerIdentifier) { - // we need to make a copy as the layerIdentifier is only a reference - // which will no longer be valid once it is deleted - std::string id = layerIdentifier; + LINFO("Deleting GeoJson layer: " + layerIdentifier); removePropertySubOwner(it->get()); (*it)->deinitializeGL(); _geoJsonObjects.erase(it); - LINFO("Deleted GeoJson layer " + id); return; } } diff --git a/modules/globebrowsing/src/geojson/geojsonproperties.cpp b/modules/globebrowsing/src/geojson/geojsonproperties.cpp index 7c828f7a3c..1dab4ec7e8 100644 --- a/modules/globebrowsing/src/geojson/geojsonproperties.cpp +++ b/modules/globebrowsing/src/geojson/geojsonproperties.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #include #include @@ -71,7 +71,7 @@ namespace geojson::propertykeys { namespace { using PropertyInfo = openspace::properties::Property::PropertyInfo; - template + template bool keyMatches(const std::string_view key, const std::array& keyAlternativesArray, std::optional propInfo = std::nullopt) @@ -100,10 +100,10 @@ namespace { } std::optional hexToRgb(std::string_view hexColor) { - glm::ivec3 rgb; - auto ret = scn::scan(hexColor, "#{:2x}{:2x}{:2x}", rgb.r, rgb.g, rgb.b); + auto ret = scn::scan(hexColor, "#{:2x}{:2x}{:2x}"); if (ret) { - return (1.f / 255.f) * glm::vec3(rgb); + auto [x, y, z] = ret->values(); + return (1.f / 255.f) * glm::vec3(x, y, z); } else { return std::nullopt; @@ -120,7 +120,7 @@ namespace { // Should add some more information on which file the reading failed for LERRORC( "GeoJson", - fmt::format( + std::format( "Failed reading color property. Expected 3 values, got {}", val.size() ) @@ -135,12 +135,12 @@ namespace { ); } else if (value.isString()) { - const std::string hex = value.getString(); + const std::string& hex = value.getString(); std::optional c = hexToRgb(hex); if (!c) { LERRORC( "GeoJson", - fmt::format( + std::format( "Failed reading color property. Did not find a hex color, got {}", hex ) @@ -460,10 +460,10 @@ void GeoJsonProperties::createFromDictionary(const ghoul::Dictionary& dictionary // Distances are computed based on a certain lat/long angle size constexpr float DefaultAngle = glm::radians(1.f); constexpr float MaxAngle = glm::radians(45.f); - float defaultDistance = static_cast( + const float defaultDistance = static_cast( globe.ellipsoid().longitudalDistance(0.f, 0.f, DefaultAngle) ); - float maxDistance = static_cast( + const float maxDistance = static_cast( globe.ellipsoid().longitudalDistance(0.f, 0.f, MaxAngle) ); tessellation.distance = defaultDistance; @@ -532,7 +532,7 @@ GeoJsonOverrideProperties propsFromGeoJson(const geos::io::GeoJSONFeature& featu result.pointTextureAnchor = GeoJsonProperties::PointTextureAnchor::Center; } else { - LERRORC("GeoJson", fmt::format( + LERRORC("GeoJson", std::format( "Point texture anchor mode '{}' not supported", mode )); } @@ -554,7 +554,7 @@ GeoJsonOverrideProperties propsFromGeoJson(const geos::io::GeoJSONFeature& featu // result.altitudeMode = GeoJsonProperties::AltitudeMode::ClampToGround; //} else { - LERRORC("GeoJson", fmt::format( + LERRORC("GeoJson", std::format( "Altitude mode '{}' not supported", mode )); } @@ -587,7 +587,7 @@ GeoJsonOverrideProperties propsFromGeoJson(const geos::io::GeoJSONFeature& featu } catch (const geos::io::GeoJSONValue::GeoJSONTypeError&) { // @TODO: Should add some more information on which file the reading failed - LERRORC("GeoJson", fmt::format( + LERRORC("GeoJson", std::format( "Error reading GeoJson property '{}'. Value has wrong type", key )); } diff --git a/modules/globebrowsing/src/geojson/globegeometryfeature.cpp b/modules/globebrowsing/src/geojson/globegeometryfeature.cpp index eeeb3d9728..b925be7797 100644 --- a/modules/globebrowsing/src/geojson/globegeometryfeature.cpp +++ b/modules/globebrowsing/src/geojson/globegeometryfeature.cpp @@ -75,8 +75,8 @@ std::string GlobeGeometryFeature::key() const { return _key; } -void GlobeGeometryFeature::setOffsets(const glm::vec3& value) { - _offsets = value; +void GlobeGeometryFeature::setOffsets(glm::vec3 offsets) { + _offsets = std::move(offsets); } void GlobeGeometryFeature::initializeGL(ghoul::opengl::ProgramObject* pointsProgram, @@ -100,8 +100,8 @@ void GlobeGeometryFeature::deinitializeGL() { } bool GlobeGeometryFeature::isReady() const { - bool shadersAreReady = _linesAndPolygonsProgram && _pointsProgram; - bool textureIsReady = (!_hasTexture) || _pointTexture; + const bool shadersAreReady = _linesAndPolygonsProgram && _pointsProgram; + const bool textureIsReady = (!_hasTexture) || _pointTexture; return shadersAreReady && textureIsReady; } @@ -151,8 +151,8 @@ void GlobeGeometryFeature::updateTexture(bool isInitializeStep) { _pointTexture->uploadToGpu(); } else { - LERROR(fmt::format( - "Trying to use texture file that does not exist: {} ", texturePath + LERROR(std::format( + "Trying to use texture file that does not exist: {}", texturePath )); } } @@ -160,9 +160,11 @@ void GlobeGeometryFeature::updateTexture(bool isInitializeStep) { void GlobeGeometryFeature::createFromSingleGeosGeometry(const geos::geom::Geometry* geo, int index, bool ignoreHeights) { - ghoul_assert(geo, "No geometry provided"); + if (!geo) { + throw std::logic_error("No geometry provided"); + } ghoul_assert( - geo->isPuntal() || !geo->isCollection(), + (geo && geo->isPuntal()) || (geo && !geo->isCollection()), "Non-point geometry can not be a collection" ); @@ -180,7 +182,7 @@ void GlobeGeometryFeature::createFromSingleGeosGeometry(const geos::geom::Geomet } case geos::geom::GEOS_POLYGON: { try { - auto p = dynamic_cast(geo); + const auto p = dynamic_cast(geo); // Triangles // Note that Constrained Delaunay triangulation supports polygons with @@ -208,40 +210,41 @@ void GlobeGeometryFeature::createFromSingleGeosGeometry(const geos::geom::Geomet pNormalized->normalize(); const geos::geom::LinearRing* outerRing = pNormalized->getExteriorRing(); - std::vector outerBoundsGeoCoords = + const std::vector outerBoundsGeoCoords = geometryhelper::geometryCoordsAsGeoVector(outerRing); if (!outerBoundsGeoCoords.empty()) { - int nHoles = static_cast(pNormalized->getNumInteriorRing()); + const int nHoles = static_cast( + pNormalized->getNumInteriorRing() + ); _geoCoordinates.reserve(nHoles + 1); // Outer bounds _geoCoordinates.push_back(outerBoundsGeoCoords); // Inner bounds (holes) - for (int i = 0; i < nHoles; ++i) { + for (int i = 0; i < nHoles; i++) { const geos::geom::LinearRing* hole = pNormalized->getInteriorRingN(i); std::vector ringGeoCoords = geometryhelper::geometryCoordsAsGeoVector(hole); - - _geoCoordinates.push_back(ringGeoCoords); + _geoCoordinates.push_back(std::move(ringGeoCoords)); } } _type = GeometryType::Polygon; } catch (geos::util::IllegalStateException& e) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Non-simple (e.g. self-intersecting) polygons not supported yet. " - "GEOS error: '{}'", e.what() + "GEOS error: {}", e.what() )); // TODO: handle self-intersections points // https://www.sciencedirect.com/science/article/pii/S0304397520304199 } catch (geos::util::GEOSException& e) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Unknown geos error: {}", e.what() )); } @@ -279,7 +282,7 @@ void GlobeGeometryFeature::createFromSingleGeosGeometry(const geos::geom::Geomet _key = *_properties.overrideValues.name; } else { - _key = fmt::format("Feature {} - {}", index, geo->getGeometryType()); + _key = std::format("Feature {} - {}", index, geo->getGeometryType()); } } @@ -289,8 +292,8 @@ void GlobeGeometryFeature::render(const RenderData& renderData, int pass, { ghoul_assert(pass >= 0 && pass < 2, "Render pass variable out of accepted range"); - float opacity = mainOpacity * _properties.opacity(); - float fillOpacity = mainOpacity * _properties.fillOpacity(); + const float opacity = mainOpacity * _properties.opacity(); + const float fillOpacity = mainOpacity * _properties.fillOpacity(); const glm::dmat4 globeModelTransform = _globe.modelTransform(); const glm::dmat4 modelViewTransform = @@ -313,7 +316,7 @@ void GlobeGeometryFeature::render(const RenderData& renderData, int pass, continue; } - bool shouldRenderTwice = r.type == RenderType::Polygon && + const bool shouldRenderTwice = r.type == RenderType::Polygon && fillOpacity < 1.f && _properties.extrude(); if (pass > 0 && !shouldRenderTwice) { @@ -352,7 +355,7 @@ void GlobeGeometryFeature::render(const RenderData& renderData, int pass, break; case RenderType::Points: { shader->setUniform("opacity", opacity); - float scale = extraRenderData.pointSizeScale; + const float scale = extraRenderData.pointSizeScale; renderPoints(r, renderData, extraRenderData.pointRenderMode, scale); break; } @@ -382,8 +385,8 @@ void GlobeGeometryFeature::renderPoints(const RenderFeature& feature, ghoul_assert(feature.type == RenderType::Points, "Trying to render faulty geometry"); _pointsProgram->setUniform("color", _properties.color()); - float bs = static_cast(_globe.boundingSphere()); - float size = 0.001f * sizeScale * _properties.pointSize() * bs; + const float bs = static_cast(_globe.boundingSphere()); + const float size = 0.001f * sizeScale * _properties.pointSize() * bs; _pointsProgram->setUniform("pointSize", size); _pointsProgram->setUniform("renderMode", static_cast(renderMode)); @@ -395,29 +398,29 @@ void GlobeGeometryFeature::renderPoints(const RenderFeature& feature, ); // Points are rendered as billboards - glm::dvec3 cameraViewDirectionWorld = -renderData.camera.viewDirectionWorldSpace(); - glm::dvec3 cameraUpDirectionWorld = renderData.camera.lookUpVectorWorldSpace(); + const glm::dvec3 cameraViewDirWorld = -renderData.camera.viewDirectionWorldSpace(); + const glm::dvec3 cameraUpDirWorld = renderData.camera.lookUpVectorWorldSpace(); glm::dvec3 orthoRight = glm::normalize( - glm::cross(cameraUpDirectionWorld, cameraViewDirectionWorld) + glm::cross(cameraUpDirWorld, cameraViewDirWorld) ); if (orthoRight == glm::dvec3(0.0)) { - // For some reason, the up vector and camera view vecter were the same. Use a + // For some reason, the up vector and camera view vector were the same. Use a // slightly different vector - glm::dvec3 otherVector = glm::vec3( - cameraUpDirectionWorld.y, - cameraUpDirectionWorld.x, - cameraUpDirectionWorld.z + const glm::dvec3 otherVector = glm::vec3( + cameraUpDirWorld.y, + cameraUpDirWorld.x, + cameraUpDirWorld.z ); - orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirectionWorld)); + orthoRight = glm::normalize(glm::cross(otherVector, cameraViewDirWorld)); } - glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirectionWorld, orthoRight)); + const glm::dvec3 orthoUp = glm::normalize(glm::cross(cameraViewDirWorld, orthoRight)); _pointsProgram->setUniform("cameraUp", glm::vec3(orthoUp)); _pointsProgram->setUniform("cameraRight", glm::vec3(orthoRight)); - glm::dvec3 cameraPositionWorld = renderData.camera.positionVec3(); + const glm::dvec3 cameraPositionWorld = renderData.camera.positionVec3(); _pointsProgram->setUniform("cameraPosition", cameraPositionWorld); - _pointsProgram->setUniform("cameraLookUp", glm::vec3(cameraUpDirectionWorld)); + _pointsProgram->setUniform("cameraLookUp", glm::vec3(cameraUpDirWorld)); if (_pointTexture && _hasTexture) { ghoul::opengl::TextureUnit unit; @@ -426,7 +429,8 @@ void GlobeGeometryFeature::renderPoints(const RenderFeature& feature, _pointsProgram->setUniform("pointTexture", unit); _pointsProgram->setUniform("hasTexture", true); - float widthHeightRatio = static_cast(_pointTexture->texture()->width()) / + const float widthHeightRatio = + static_cast(_pointTexture->texture()->width()) / static_cast(_pointTexture->texture()->height()); _pointsProgram->setUniform("textureWidthFactor", widthHeightRatio); } @@ -480,7 +484,7 @@ void GlobeGeometryFeature::renderPolygons(const RenderFeature& feature, bool GlobeGeometryFeature::shouldUpdateDueToHeightMapChange() const { if (_properties.altitudeMode() == GeoJsonProperties::AltitudeMode::RelativeToGround) { // Cap the update to a given time interval - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); if (now - _lastHeightUpdateTime < HeightUpdateInterval) { return false; } @@ -491,7 +495,7 @@ bool GlobeGeometryFeature::shouldUpdateDueToHeightMapChange() const { // Check if last height values for the control positions have changed std::vector newHeights = getCurrentReferencePointsHeights(); - bool isSame = std::equal( + const bool isSame = std::equal( _lastControlHeights.begin(), _lastControlHeights.end(), newHeights.begin(), @@ -529,7 +533,7 @@ void GlobeGeometryFeature::updateGeometry() { createPointGeometry(); } else { - std::vector> edgeVertices = createLineGeometry(); + const std::vector> edgeVertices = createLineGeometry(); createExtrudedGeometry(edgeVertices); createPolygonGeometry(); } @@ -554,28 +558,27 @@ void GlobeGeometryFeature::updateHeightsFromHeightMap() { std::vector> GlobeGeometryFeature::createLineGeometry() { std::vector> resultPositions; resultPositions.reserve(_geoCoordinates.size()); - - for (size_t i = 0; i < _geoCoordinates.size(); ++i) { + for (const std::vector& coordinates : _geoCoordinates) { std::vector vertices; std::vector positions; // TODO: this is not correct anymore - vertices.reserve(_geoCoordinates[i].size() * 3); + vertices.reserve(coordinates.size() * 3); // TODO: this is not correct anymore - positions.reserve(_geoCoordinates[i].size() * 3); + positions.reserve(coordinates.size() * 3); glm::dvec3 lastPos = glm::dvec3(0.0); double lastHeightValue = 0.0; bool isFirst = true; - for (const Geodetic3& geodetic : _geoCoordinates[i]) { - glm::dvec3 v = geometryhelper::computeOffsetedModelCoordinate( + for (const Geodetic3& geodetic : coordinates) { + const glm::dvec3 v = geometryhelper::computeOffsetedModelCoordinate( geodetic, _globe, _offsets.x, _offsets.y ); - auto addLinePos = [&vertices, &positions](glm::vec3 pos) { + const auto addLinePos = [&vertices, &positions](const glm::vec3& pos) { vertices.push_back({ pos.x, pos.y, pos.z, 0.f, 0.f, 0.f }); positions.push_back(pos); }; @@ -592,7 +595,7 @@ std::vector> GlobeGeometryFeature::createLineGeometry() { // Tessellate. // But first, determine the step size for the tessellation (larger // features will not be tesselated) - float stepSize = tessellationStepSize(); + const float stepSize = tessellationStepSize(); std::vector subdividedPositions = geometryhelper::subdivideLine( @@ -639,24 +642,24 @@ void GlobeGeometryFeature::createPointGeometry() { return; } - for (size_t i = 0; i < _geoCoordinates.size(); ++i) { + for (const std::vector& coordinates : _geoCoordinates) { std::vector vertices; - vertices.reserve(_geoCoordinates[i].size()); + vertices.reserve(coordinates.size()); std::vector extrudedLineVertices; - extrudedLineVertices.reserve(2 * _geoCoordinates[i].size()); + extrudedLineVertices.reserve(2 * coordinates.size()); - for (const Geodetic3& geodetic : _geoCoordinates[i]) { - glm::dvec3 v = geometryhelper::computeOffsetedModelCoordinate( + for (const Geodetic3& geodetic : coordinates) { + const glm::dvec3 v = geometryhelper::computeOffsetedModelCoordinate( geodetic, _globe, _offsets.x, _offsets.y ); - glm::vec3 vf = static_cast(v); + const glm::vec3 vf = static_cast(v); // Normal is the out direction - glm::vec3 normal = glm::normalize(vf); + const glm::vec3 normal = glm::normalize(vf); vertices.push_back({ vf.x, vf.y, vf.z, normal.x, normal.y, normal.z }); @@ -691,8 +694,9 @@ void GlobeGeometryFeature::createExtrudedGeometry( return; } - std::vector vertices = - geometryhelper::createExtrudedGeometryVertices(edgeVertices); + const std::vector vertices = geometryhelper::createExtrudedGeometryVertices( + edgeVertices + ); RenderFeature feature; feature.type = RenderType::Polygon; @@ -732,14 +736,14 @@ void GlobeGeometryFeature::createPolygonGeometry() { const glm::vec3 v1 = triPositions[1]; const glm::vec3 v2 = triPositions[2]; - double h0 = triHeights[0]; - double h1 = triHeights[1]; - double h2 = triHeights[2]; + const double h0 = triHeights[0]; + const double h1 = triHeights[1]; + const double h2 = triHeights[2]; if (_properties.tessellationEnabled()) { // First determine the step size for the tessellation (larger features // will not be tesselated) - float stepSize = tessellationStepSize(); + const float stepSize = tessellationStepSize(); std::vector verts = geometryhelper::subdivideTriangle( v0, v1, v2, @@ -783,7 +787,7 @@ void GlobeGeometryFeature::initializeRenderFeature(RenderFeature& feature, float GlobeGeometryFeature::tessellationStepSize() const { float distance = _properties.tessellationDistance(); - bool shouldDivideDistance = _properties.useTessellationLevel() && + const bool shouldDivideDistance = _properties.useTessellationLevel() && _properties.tessellationLevel() > 0; if (shouldDivideDistance) { @@ -839,7 +843,7 @@ void GlobeGeometryFeature::bufferVertexData(const RenderFeature& feature, vertexData.data() ); - GLint positionAttrib = program->attributeLocation("in_position"); + const GLint positionAttrib = program->attributeLocation("in_position"); glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, @@ -850,7 +854,7 @@ void GlobeGeometryFeature::bufferVertexData(const RenderFeature& feature, nullptr ); - GLint normalAttrib = program->attributeLocation("in_normal"); + const GLint normalAttrib = program->attributeLocation("in_normal"); glEnableVertexAttribArray(normalAttrib); glVertexAttribPointer( normalAttrib, @@ -862,7 +866,7 @@ void GlobeGeometryFeature::bufferVertexData(const RenderFeature& feature, ); // Put height data after all vertex data in buffer - unsigned long long endOfVertexData = vertexData.size() * sizeof(Vertex); + const unsigned long long endOfVertexData = vertexData.size() * sizeof(Vertex); glBindVertexArray(feature.vaoId); glBindBuffer(GL_ARRAY_BUFFER, feature.vboId); glBufferSubData( @@ -872,7 +876,7 @@ void GlobeGeometryFeature::bufferVertexData(const RenderFeature& feature, feature.heights.data() ); - GLint heightAttrib = program->attributeLocation("in_height"); + const GLint heightAttrib = program->attributeLocation("in_height"); glEnableVertexAttribArray(heightAttrib); glVertexAttribPointer( heightAttrib, @@ -907,7 +911,7 @@ void GlobeGeometryFeature::bufferDynamicHeightData(const RenderFeature& feature) feature.heights.data() ); - GLint heightAttrib = program->attributeLocation("in_height"); + const GLint heightAttrib = program->attributeLocation("in_height"); glEnableVertexAttribArray(heightAttrib); glVertexAttribPointer( heightAttrib, diff --git a/modules/globebrowsing/src/geojson/globegeometryfeature.h b/modules/globebrowsing/src/geojson/globegeometryfeature.h index 02e3f63249..1f899e8004 100644 --- a/modules/globebrowsing/src/geojson/globegeometryfeature.h +++ b/modules/globebrowsing/src/geojson/globegeometryfeature.h @@ -119,7 +119,7 @@ public: std::string key() const; - void setOffsets(const glm::vec3& offsets); + void setOffsets(glm::vec3 offsets); void initializeGL(ghoul::opengl::ProgramObject* pointsProgram, ghoul::opengl::ProgramObject* linesAndPolygonsProgram); diff --git a/modules/globebrowsing/src/geojson/globegeometryhelper.cpp b/modules/globebrowsing/src/geojson/globegeometryhelper.cpp index 9473d3929d..bdaa473685 100644 --- a/modules/globebrowsing/src/geojson/globegeometryhelper.cpp +++ b/modules/globebrowsing/src/geojson/globegeometryhelper.cpp @@ -73,7 +73,7 @@ std::vector geodetic2FromVertexList(const RenderableGlobe& globe, std::vector res; res.reserve(verts.size()); for (const rendering::helper::VertexXYZNormal& v : verts) { - glm::dvec3 cartesian = glm::dvec3(v.xyz[0], v.xyz[1], v.xyz[2]); + const glm::dvec3 cartesian = glm::dvec3(v.xyz[0], v.xyz[1], v.xyz[2]); res.push_back(globe.ellipsoid().cartesianToGeodetic2(cartesian)); } return res; @@ -85,7 +85,7 @@ std::vector heightMapHeightsFromGeodetic2List(const RenderableGlobe& glob std::vector res; res.reserve(list.size()); for (const Geodetic2& geo : list) { - float h = static_cast(getHeightToReferenceSurface(geo, globe)); + const float h = static_cast(getHeightToReferenceSurface(geo, globe)); res.push_back(h); } return res; @@ -105,17 +105,17 @@ createExtrudedGeometryVertices(const std::vector>& edgeVe // Extrude polygon for (size_t nBound = 0; nBound < edgeVertices.size(); ++nBound) { const std::vector& boundary = edgeVertices[nBound]; - for (size_t i = 1; i < boundary.size(); ++i) { - glm::vec3 v0 = boundary[i - 1]; - glm::vec3 v1 = boundary[i ]; + for (size_t i = 1; i < boundary.size(); i++) { + const glm::vec3& v0 = boundary[i - 1]; + const glm::vec3& v1 = boundary[i]; // Vertices close to globe (Based on origin which is the zero point here) // For now, use center of globe (TODO: allow setting the height) - glm::vec3 vOrigin = glm::vec3(0.f); + const glm::vec3 vOrigin = glm::vec3(0.f); // Outer boundary is the first one if (nBound == 0) { - glm::vec3 n = glm::vec3( + const glm::vec3 n = glm::vec3( glm::normalize(glm::cross(v1 - vOrigin, v0 - vOrigin)) ); vertices.push_back({ vOrigin.x, vOrigin.y, vOrigin.z, n.x, n.y, n.z }); @@ -125,7 +125,9 @@ createExtrudedGeometryVertices(const std::vector>& edgeVe // Inner boundary else { // Flipped winding order and normal for inner rings - glm::vec3 n = glm::normalize(glm::cross(v0 - vOrigin, v1 - vOrigin)); + const glm::vec3 n = glm::normalize( + glm::cross(v0 - vOrigin, v1 - vOrigin) + ); vertices.push_back({ vOrigin.x, vOrigin.y, vOrigin.z, n.x, n.y, n.z }); vertices.push_back({ v0.x, v0.y, v0.z, n.x, n.y, n.z }); vertices.push_back({ v1.x, v1.y, v1.z, n.x, n.y, n.z }); @@ -144,7 +146,7 @@ createExtrudedGeometryVertices(const std::vector>& edgeVe double getHeightToReferenceSurface(const Geodetic2& geo, const RenderableGlobe& globe) { // Compute model space coordinate, and potentially account for height map - glm::dvec3 posModelSpaceZeroHeight = + const glm::dvec3 posModelSpaceZeroHeight = globe.ellipsoid().cartesianSurfacePosition(geo); const SurfacePositionHandle posHandle = @@ -158,8 +160,8 @@ glm::dvec3 computeOffsetedModelCoordinate(const Geodetic3& geo, float latOffset, float lonOffset) { // Account for lat long offset - double offsetLatRadians = glm::radians(latOffset); - double offsetLonRadians = glm::radians(lonOffset); + const double offsetLatRadians = glm::radians(latOffset); + const double offsetLonRadians = glm::radians(lonOffset); Geodetic3 adjusted = geo; adjusted.geodetic2.lat += offsetLatRadians; @@ -171,8 +173,8 @@ glm::dvec3 computeOffsetedModelCoordinate(const Geodetic3& geo, std::vector subdivideLine(const glm::dvec3& v0, const glm::dvec3& v1, double h0, double h1, double maxDistance) { - double edgeLength = glm::distance(v1, v0); - int nSegments = static_cast(std::ceil(edgeLength / maxDistance)); + const double edgeLength = glm::distance(v1, v0); + const int nSegments = static_cast(std::ceil(edgeLength / maxDistance)); std::vector positions; positions.reserve(nSegments + 1); @@ -183,15 +185,15 @@ std::vector subdivideLine(const glm::dvec3& v0, const glm::dvec3& } for (int seg = 0; seg < nSegments; ++seg) { - double t = static_cast(seg) / static_cast(nSegments); + const double t = static_cast(seg) / static_cast(nSegments); // Interpolate both position and height value - glm::dvec3 newV = glm::mix(v0, v1, t); - double newHeight = glm::mix(h0, h1, t); - double heightDiff = newHeight - h0; + const glm::dvec3 newV = glm::mix(v0, v1, t); + const double newHeight = glm::mix(h0, h1, t); + const double heightDiff = newHeight - h0; // Compute position along arc between v0 and v1, with adjusted height value - glm::vec3 newVf = static_cast( + const glm::vec3 newVf = static_cast( (glm::length(v0) + heightDiff) * glm::normalize(newV) ); positions.push_back({ newVf, newHeight }); @@ -230,66 +232,68 @@ subdivideTriangle(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, maxDistance ); - size_t nSteps01 = edge01.size(); - size_t nSteps02 = edge02.size(); - size_t nSteps12 = edge12.size(); - size_t maxSteps = std::max(std::max(nSteps01, nSteps02), nSteps12); + const size_t nSteps01 = edge01.size(); + const size_t nSteps02 = edge02.size(); + const size_t nSteps12 = edge12.size(); + const size_t maxSteps = std::max(std::max(nSteps01, nSteps02), nSteps12); vertices.reserve(maxSteps * maxSteps); // Add points inside the triangle std::vector pointCoords; pointCoords.reserve(3 * maxSteps + 1); + const globebrowsing::Ellipsoid& ellipsoid = globe.ellipsoid(); + const float lengthEdge01 = glm::length(v1 - v0); const float lengthEdge02 = glm::length(v2 - v0); - for (size_t i = 1; i < nSteps01; ++i) { - for (size_t j = 1; j < nSteps02; ++j) { - glm::vec3 comp01 = edge01[i].position - v0; - glm::vec3 comp02 = edge02[j].position - v0; + for (size_t i = 1; i < nSteps01; i++) { + for (size_t j = 1; j < nSteps02; j++) { + const glm::vec3 comp01 = edge01[i].position - v0; + const glm::vec3 comp02 = edge02[j].position - v0; - double hComp01 = edge01[i].height - h0; - double hComp02 = edge02[j].height - h0; + const double hComp01 = edge01[i].height - h0; + const double hComp02 = edge02[j].height - h0; - float w1 = glm::length(comp01) / lengthEdge01; - float w2 = glm::length(comp02) / lengthEdge02; + const float w1 = glm::length(comp01) / lengthEdge01; + const float w2 = glm::length(comp02) / lengthEdge02; if (w1 + w2 > 1.f - std::numeric_limits::epsilon()) { continue; // Sum larger than 1.0 => Outside of triangle } - glm::vec3 pos = v0 + comp01 + comp02; - double height = h0 + hComp01 + hComp02; + const glm::vec3 pos = v0 + comp01 + comp02; + const double height = h0 + hComp01 + hComp02; - Geodetic2 geo2 = globe.ellipsoid().cartesianToGeodetic2(pos); - Geodetic3 geo3 = { geo2, height }; + const Geodetic2 geo2 = ellipsoid.cartesianToGeodetic2(pos); + const Geodetic3 geo3 = { geo2, height }; pointCoords.push_back(geometryhelper::toGeosCoord(geo3)); } } // Add egde positions - for (size_t i = 0; i < maxSteps; ++i) { + for (size_t i = 0; i < maxSteps; i++) { if (i < edge01.size() - 1) { - Geodetic2 geo2 = globe.ellipsoid().cartesianToGeodetic2(edge01[i].position); - Geodetic3 geo3 = { geo2, edge01[i].height }; + const Geodetic2 geo2 = ellipsoid.cartesianToGeodetic2(edge01[i].position); + const Geodetic3 geo3 = { geo2, edge01[i].height }; pointCoords.push_back(geometryhelper::toGeosCoord(geo3)); } if (i < edge02.size() - 1) { - Geodetic2 geo2 = globe.ellipsoid().cartesianToGeodetic2(edge02[i].position); - Geodetic3 geo3 = { geo2, edge02[i].height }; + const Geodetic2 geo2 = ellipsoid.cartesianToGeodetic2(edge02[i].position); + const Geodetic3 geo3 = { geo2, edge02[i].height }; pointCoords.push_back(geometryhelper::toGeosCoord(geo3)); } if (i < edge12.size() - 1) { - Geodetic2 geo2 = globe.ellipsoid().cartesianToGeodetic2(edge12[i].position); - Geodetic3 geo3 = { geo2, edge12[i].height }; + const Geodetic2 geo2 = ellipsoid.cartesianToGeodetic2(edge12[i].position); + const Geodetic3 geo3 = { geo2, edge12[i].height }; pointCoords.push_back(geometryhelper::toGeosCoord(geo3)); } } // Also add the final position (not part of the subdivide step above) - Geodetic2 geo2 = globe.ellipsoid().cartesianToGeodetic2(v2); - glm::dvec3 centerToEllipsoidSurface = globe.ellipsoid().geodeticSurfaceProjection(v2); - double height = glm::length(glm::dvec3(v2) - centerToEllipsoidSurface); - Geodetic3 geo3 = { geo2, height }; + const Geodetic2 geo2 = ellipsoid.cartesianToGeodetic2(v2); + const glm::dvec3 centerToEllipsoidSurface = ellipsoid.geodeticSurfaceProjection(v2); + const double height = glm::length(glm::dvec3(v2) - centerToEllipsoidSurface); + const Geodetic3 geo3 = { geo2, height }; pointCoords.push_back(geometryhelper::toGeosCoord(geo3)); pointCoords.shrink_to_fit(); @@ -330,11 +334,11 @@ subdivideTriangle(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, count = 0; continue; } - Geodetic3 geodetic = geometryhelper::toGeodetic(coord); + const Geodetic3 geodetic = geometryhelper::toGeodetic(coord); // Note that offset should already have been applied to the coordinates. Use // zero offset => just get model coordinate - glm::vec3 v = + const glm::vec3 v = geometryhelper::computeOffsetedModelCoordinate(geodetic, globe, 0.f, 0.f); vertices.push_back({ v.x, v.y, v.z, 0.f, 0.f, 0.f }); @@ -343,7 +347,7 @@ subdivideTriangle(const glm::vec3& v0, const glm::vec3& v1, const glm::vec3& v2, // triangle vertices if (count == 3) { // Find previous vertices - size_t lastIndex = vertices.size() - 1; + const size_t lastIndex = vertices.size() - 1; rendering::helper::VertexXYZNormal& vert0 = vertices[lastIndex - 2]; rendering::helper::VertexXYZNormal& vert1 = vertices[lastIndex - 1]; rendering::helper::VertexXYZNormal& vert2 = vertices[lastIndex]; diff --git a/modules/globebrowsing/src/globelabelscomponent.cpp b/modules/globebrowsing/src/globelabelscomponent.cpp index 0755f28901..60f8409dc7 100644 --- a/modules/globebrowsing/src/globelabelscomponent.cpp +++ b/modules/globebrowsing/src/globelabelscomponent.cpp @@ -154,6 +154,62 @@ namespace { openspace::properties::Property::Visibility::User }; + bool isLabelInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position) { + // Frustum Planes + const glm::dvec3 col1(MVMatrix[0][0], MVMatrix[1][0], MVMatrix[2][0]); + const glm::dvec3 col2(MVMatrix[0][1], MVMatrix[1][1], MVMatrix[2][1]); + const glm::dvec3 col3(MVMatrix[0][2], MVMatrix[1][2], MVMatrix[2][2]); + const glm::dvec3 col4(MVMatrix[0][3], MVMatrix[1][3], MVMatrix[2][3]); + + glm::dvec3 leftNormal = col4 + col1; + glm::dvec3 rightNormal = col4 - col1; + glm::dvec3 bottomNormal = col4 + col2; + glm::dvec3 topNormal = col4 - col2; + glm::dvec3 nearNormal = col3 + col4; + glm::dvec3 farNormal = col4 - col3; + + // Plane Distances + double leftDistance = MVMatrix[3][3] + MVMatrix[3][0]; + double rightDistance = MVMatrix[3][3] - MVMatrix[3][0]; + double bottomDistance = MVMatrix[3][3] + MVMatrix[3][1]; + double topDistance = MVMatrix[3][3] - MVMatrix[3][1]; + double nearDistance = MVMatrix[3][3] + MVMatrix[3][2]; + // double farDistance = MVMatrix[3][3] - MVMatrix[3][2]; + + // Normalize Planes + const double invMagLeft = 1.0 / glm::length(leftNormal); + leftNormal *= invMagLeft; + leftDistance *= invMagLeft; + + const double invMagRight = 1.0 / glm::length(rightNormal); + rightNormal *= invMagRight; + rightDistance *= invMagRight; + + const double invMagBottom = 1.0 / glm::length(bottomNormal); + bottomNormal *= invMagBottom; + bottomDistance *= invMagBottom; + + const double invMagTop = 1.0 / glm::length(topNormal); + topNormal *= invMagTop; + topDistance *= invMagTop; + + const double invMagNear = 1.0 / glm::length(nearNormal); + nearNormal *= invMagNear; + nearDistance *= invMagNear; + + const double invMagFar = 1.0 / glm::length(farNormal); + farNormal *= invMagFar; + // farDistance *= invMagFar; + + constexpr float Radius = 1.0; + const bool res = ((glm::dot(leftNormal, position) + leftDistance) < -Radius) || + ((glm::dot(rightNormal, position) + rightDistance) < -Radius) || + ((glm::dot(bottomNormal, position) + bottomDistance) < -Radius) || + ((glm::dot(topNormal, position) + topDistance) < -Radius) || + ((glm::dot(nearNormal, position) + nearDistance) < -Radius); + return !res; + } + struct [[codegen::Dictionary(GlobeLabelsComponent)]] Parameters { // The path to the labels file std::optional fileName; @@ -318,9 +374,11 @@ bool GlobeLabelsComponent::loadLabelsData(const std::filesystem::path& file) { "GlobeLabelsComponent|" + identifier() ); - bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); + const bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); if (hasCachedFile) { - LINFO(fmt::format("Cached file {} used for labels file {}", cachedFile, file)); + LINFO(std::format( + "Cached file '{}' used for labels file '{}'", cachedFile, file + )); const bool hasCache = loadCachedFile(cachedFile); if (hasCache) { @@ -333,11 +391,11 @@ bool GlobeLabelsComponent::loadLabelsData(const std::filesystem::path& file) { } } else { - LINFO(fmt::format("Cache for labels file {} not found", file)); + LINFO(std::format("Cache for labels file '{}' not found", file)); } - LINFO(fmt::format("Loading labels file {}", file)); + LINFO(std::format("Loading labels file '{}'", file)); - bool success = readLabelsFile(file); + const bool success = readLabelsFile(file); if (success) { saveCachedFile(cachedFile); } @@ -348,7 +406,7 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { try { std::fstream csvLabelFile(file); if (!csvLabelFile.good()) { - LERROR(fmt::format("Failed to open labels file {}", file)); + LERROR(std::format("Failed to open labels file '{}'", file)); return false; } if (!csvLabelFile.is_open()) { @@ -383,7 +441,7 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { strncpy(lEntry.feature, token.c_str(), 255); int tokenChar = 0; while (tokenChar < 256) { - if (lEntry.feature[tokenChar] < 0 && lEntry.feature[tokenChar] != '\0') { + if (lEntry.feature[tokenChar] < 0 || lEntry.feature[tokenChar] == '\0') { lEntry.feature[tokenChar] = '*'; } else if (lEntry.feature[tokenChar] == '\"') { @@ -404,10 +462,10 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { lEntry.longitude = std::stof(token); std::getline(iss, token, ','); // Coord System - std::string coordinateSystem(token); - std::size_t found = coordinateSystem.find("West"); + const std::string_view coordinateSystem = token; + const size_t found = coordinateSystem.find("West"); if (found != std::string::npos) { - lEntry.longitude = 360.0f - lEntry.longitude; + lEntry.longitude = 360.f - lEntry.longitude; } // Clean white spaces @@ -416,7 +474,7 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { if (token.empty()) { std::getline(issFeature, token, '='); } - strncpy(lEntry.feature, token.c_str(), 255); + std::strncpy(lEntry.feature, token.c_str(), 255); GlobeBrowsingModule* _globeBrowsingModule = global::moduleEngine->module(); @@ -433,7 +491,7 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { return true; } catch (const std::fstream::failure& e) { - LERROR(fmt::format("Failed reading labels file {}", file)); + LERROR(std::format("Failed reading labels file '{}'", file)); LERROR(e.what()); return false; } @@ -442,7 +500,7 @@ bool GlobeLabelsComponent::readLabelsFile(const std::filesystem::path& file) { bool GlobeLabelsComponent::loadCachedFile(const std::filesystem::path& file) { std::ifstream fileStream(file, std::ifstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for loading cache file", file)); + LERROR(std::format("Error opening file '{}' for loading cache file", file)); return false; } @@ -470,21 +528,21 @@ bool GlobeLabelsComponent::loadCachedFile(const std::filesystem::path& file) { } bool GlobeLabelsComponent::saveCachedFile(const std::filesystem::path& file) const { - std::ofstream fileStream(file, std::ofstream::binary); + std::ofstream fileStream = std::ofstream(file, std::ofstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for save cache file", file)); + LERROR(std::format("Error opening file '{}' for save cache file", file)); return false; } fileStream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); - int32_t nValues = static_cast(_labels.labelsArray.size()); + const int32_t nValues = static_cast(_labels.labelsArray.size()); if (nValues == 0) { LERROR("Error writing cache: No values were loaded"); return false; } fileStream.write(reinterpret_cast(&nValues), sizeof(int32_t)); - size_t nBytes = nValues * sizeof(LabelEntry); + const size_t nBytes = nValues * sizeof(LabelEntry); fileStream.write(reinterpret_cast(_labels.labelsArray.data()), nBytes); return fileStream.good(); @@ -496,27 +554,27 @@ void GlobeLabelsComponent::draw(const RenderData& data) { } // Calculate the MVP matrix - glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); - glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * + const glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); + const glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * viewTransform; - glm::dmat4 mvp = vp * _globe->modelTransform(); + const glm::dmat4 mvp = vp * _globe->modelTransform(); - glm::dvec3 globePosWorld = + const glm::dvec3 globePosWorld = glm::dvec3(_globe->modelTransform() * glm::vec4(0.f, 0.f, 0.f, 1.f)); - glm::dvec3 cameraToGlobeWorld = globePosWorld - data.camera.positionVec3(); - double distanceCameraGlobeWorld = glm::length(cameraToGlobeWorld); + const glm::dvec3 cameraToGlobeWorld = globePosWorld - data.camera.positionVec3(); + const double distanceCameraGlobeWorld = glm::length(cameraToGlobeWorld); float varyingOpacity = 1.f; const glm::dvec3 globeRadii = _globe->ellipsoid().radii(); - double averageRadius = (globeRadii.x + globeRadii.y + globeRadii.z) / 3.0; + const double averageRadius = (globeRadii.x + globeRadii.y + globeRadii.z) / 3.0; if (_fadeInEnabled) { glm::dvec2 fadeRange = glm::dvec2(averageRadius + _heightOffset); fadeRange.x += _fadeDistances.value().y; - double a = 1.0 / (fadeRange.y - fadeRange.x); - double b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); - double funcValue = a * distanceCameraGlobeWorld + b; + const double a = 1.0 / (fadeRange.y - fadeRange.x); + const double b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); + const double funcValue = a * distanceCameraGlobeWorld + b; varyingOpacity *= static_cast(std::min(funcValue, 1.0)); if (varyingOpacity < MinOpacityValueConst) { @@ -529,9 +587,9 @@ void GlobeLabelsComponent::draw(const RenderData& data) { averageRadius + _heightOffset + LabelFadeOutLimitAltitudeMeters ); fadeRange.x += _fadeDistances.value().x; - double a = 1.0 / (fadeRange.x - fadeRange.y); - double b = -(fadeRange.y / (fadeRange.x - fadeRange.y)); - double funcValue = a * distanceCameraGlobeWorld + b; + const double a = 1.0 / (fadeRange.x - fadeRange.y); + const double b = -(fadeRange.y / (fadeRange.x - fadeRange.y)); + const double funcValue = a * distanceCameraGlobeWorld + b; varyingOpacity *= static_cast(std::min(funcValue, 1.0)); if (varyingOpacity < MinOpacityValueConst) { @@ -546,27 +604,24 @@ void GlobeLabelsComponent::renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, float distToCamera, float fadeInVariable ) { - glm::vec4 textColor = glm::vec4( - glm::vec3(_color), - opacity() * fadeInVariable - ); + const glm::vec4 textColor = glm::vec4(glm::vec3(_color), opacity() * fadeInVariable); - glm::dmat4 VP = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * + const glm::dmat4 VP = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * data.camera.combinedViewMatrix(); - glm::dmat4 invModelMatrix = glm::inverse(_globe->modelTransform()); + const glm::dmat4 invModelMatrix = glm::inverse(_globe->modelTransform()); - glm::dvec3 cameraViewDirectionObj = glm::dvec3( + const glm::dvec3 cameraViewDirectionObj = glm::dvec3( invModelMatrix * glm::dvec4(data.camera.viewDirectionWorldSpace(), 0.0) ); - glm::dvec3 cameraUpDirectionObj = glm::dvec3( + const glm::dvec3 cameraUpDirectionObj = glm::dvec3( invModelMatrix * glm::dvec4(data.camera.lookUpVectorWorldSpace(), 0.0) ); glm::dvec3 orthoRight = glm::normalize( glm::cross(cameraViewDirectionObj, cameraUpDirectionObj) ); if (orthoRight == glm::dvec3(0.0)) { - glm::dvec3 otherVector( + const glm::dvec3 otherVector = glm::dvec3( cameraUpDirectionObj.y, cameraUpDirectionObj.x, cameraUpDirectionObj.z @@ -577,9 +632,9 @@ void GlobeLabelsComponent::renderLabels(const RenderData& data, for (const LabelEntry& lEntry : _labels.labelsArray) { glm::vec3 position = lEntry.geoPosition; - glm::dvec3 locationPositionWorld = + const glm::dvec3 locationPositionWorld = glm::dvec3(_globe->modelTransform() * glm::dvec4(position, 1.0)); - double distanceCameraToLabelWorld = + const double distanceCameraToLabelWorld = glm::length(locationPositionWorld - data.camera.positionVec3()); if (_disableCulling || @@ -587,17 +642,17 @@ void GlobeLabelsComponent::renderLabels(const RenderData& data, isLabelInFrustum(VP, locationPositionWorld))) { if (_alignmentOption == Circularly) { - glm::dvec3 labelNormalObj = glm::dvec3( + const glm::dvec3 labelNormalObj = glm::dvec3( invModelMatrix * glm::dvec4(data.camera.positionVec3(), 1.0) ) - glm::dvec3(position); - glm::dvec3 labelUpDirectionObj = glm::dvec3(position); + const glm::dvec3 labelUpDirectionObj = glm::dvec3(position); orthoRight = glm::normalize( glm::cross(labelUpDirectionObj, labelNormalObj) ); if (orthoRight == glm::dvec3(0.0)) { - glm::dvec3 otherVector( + const glm::dvec3 otherVector = glm::dvec3( labelUpDirectionObj.y, labelUpDirectionObj.x, labelUpDirectionObj.z @@ -625,8 +680,8 @@ void GlobeLabelsComponent::renderLabels(const RenderData& data, labelInfo.disableTransmittance = true; // Testing - glm::dmat4 modelviewTransform = glm::dmat4(data.camera.combinedViewMatrix()) * - _globe->modelTransform(); + const glm::dmat4 modelviewTransform = glm::dmat4( + data.camera.combinedViewMatrix()) * _globe->modelTransform(); labelInfo.modelViewMatrix = modelviewTransform; labelInfo.projectionMatrix = glm::dmat4( data.camera.sgctInternal.projectionMatrix() @@ -643,73 +698,4 @@ void GlobeLabelsComponent::renderLabels(const RenderData& data, } } -bool GlobeLabelsComponent::isLabelInFrustum(const glm::dmat4& MVMatrix, - const glm::dvec3& position) const -{ - // Frustum Planes - glm::dvec3 col1(MVMatrix[0][0], MVMatrix[1][0], MVMatrix[2][0]); - glm::dvec3 col2(MVMatrix[0][1], MVMatrix[1][1], MVMatrix[2][1]); - glm::dvec3 col3(MVMatrix[0][2], MVMatrix[1][2], MVMatrix[2][2]); - glm::dvec3 col4(MVMatrix[0][3], MVMatrix[1][3], MVMatrix[2][3]); - - glm::dvec3 leftNormal = col4 + col1; - glm::dvec3 rightNormal = col4 - col1; - glm::dvec3 bottomNormal = col4 + col2; - glm::dvec3 topNormal = col4 - col2; - glm::dvec3 nearNormal = col3 + col4; - glm::dvec3 farNormal = col4 - col3; - - // Plane Distances - double leftDistance = MVMatrix[3][3] + MVMatrix[3][0]; - double rightDistance = MVMatrix[3][3] - MVMatrix[3][0]; - double bottomDistance = MVMatrix[3][3] + MVMatrix[3][1]; - double topDistance = MVMatrix[3][3] - MVMatrix[3][1]; - double nearDistance = MVMatrix[3][3] + MVMatrix[3][2]; - // double farDistance = MVMatrix[3][3] - MVMatrix[3][2]; - - // Normalize Planes - const double invMagLeft = 1.0 / glm::length(leftNormal); - leftNormal *= invMagLeft; - leftDistance *= invMagLeft; - - const double invMagRight = 1.0 / glm::length(rightNormal); - rightNormal *= invMagRight; - rightDistance *= invMagRight; - - const double invMagBottom = 1.0 / glm::length(bottomNormal); - bottomNormal *= invMagBottom; - bottomDistance *= invMagBottom; - - const double invMagTop = 1.0 / glm::length(topNormal); - topNormal *= invMagTop; - topDistance *= invMagTop; - - const double invMagNear = 1.0 / glm::length(nearNormal); - nearNormal *= invMagNear; - nearDistance *= invMagNear; - - const double invMagFar = 1.0 / glm::length(farNormal); - farNormal *= invMagFar; - // farDistance *= invMagFar; - - constexpr float Radius = 1.0; - if ((glm::dot(leftNormal, position) + leftDistance) < -Radius) { - return false; - } - else if ((glm::dot(rightNormal, position) + rightDistance) < -Radius) { - return false; - } - else if ((glm::dot(bottomNormal, position) + bottomDistance) < -Radius) { - return false; - } - else if ((glm::dot(topNormal, position) + topDistance) < -Radius) { - return false; - } - else if ((glm::dot(nearNormal, position) + nearDistance) < -Radius) { - return false; - } - - return true; -} - } // namespace openspace diff --git a/modules/globebrowsing/src/globelabelscomponent.h b/modules/globebrowsing/src/globelabelscomponent.h index a131e340a8..6c63a7bad8 100644 --- a/modules/globebrowsing/src/globelabelscomponent.h +++ b/modules/globebrowsing/src/globelabelscomponent.h @@ -69,7 +69,6 @@ private: bool saveCachedFile(const std::filesystem::path& file) const; void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, float distToCamera, float fadeInVariable); - bool isLabelInFrustum(const glm::dmat4& MVMatrix, const glm::dvec3& position) const; // Labels Structures struct LabelEntry { diff --git a/modules/globebrowsing/src/globerotation.cpp b/modules/globebrowsing/src/globerotation.cpp index b1e0fd68ff..62dd959b4f 100644 --- a/modules/globebrowsing/src/globerotation.cpp +++ b/modules/globebrowsing/src/globerotation.cpp @@ -186,15 +186,14 @@ glm::vec3 GlobeRotation::computeSurfacePosition(double latitude, double longitud ghoul_assert(_globeNode, "Globe cannot be nullptr"); GlobeBrowsingModule* mod = global::moduleEngine->module(); - glm::vec3 groundPos = mod->cartesianCoordinatesFromGeo( + const glm::vec3 groundPos = mod->cartesianCoordinatesFromGeo( *_globeNode, latitude, longitude, 0.0 ); - SurfacePositionHandle h = - _globeNode->calculateSurfacePositionHandle(groundPos); + const SurfacePositionHandle h = _globeNode->calculateSurfacePositionHandle(groundPos); // Compute position including heightmap return mod->cartesianCoordinatesFromGeo( @@ -228,12 +227,20 @@ glm::dmat3 GlobeRotation::matrix(const UpdateData&) const { return _matrix; } + if (!_globeNode) { + LERRORC( + "GlobeRotation", + std::format("Could not find globe '{}'", _globe.value()) + ); + return _matrix; + } + double lat = _latitude; double lon = _longitude; if (_useCamera) { GlobeBrowsingModule* mod = global::moduleEngine->module(); - glm::dvec3 position = mod->geoPosition(); + const glm::dvec3 position = mod->geoPosition(); lat = position.x; lon = position.y; } @@ -251,8 +258,8 @@ glm::dmat3 GlobeRotation::matrix(const UpdateData&) const { yAxis = glm::dvec3(glm::cross(v1, v2)); } else { - float latitudeRad = glm::radians(static_cast(lat)); - float longitudeRad = glm::radians(static_cast(lon)); + const float latitudeRad = glm::radians(static_cast(lat)); + const float longitudeRad = glm::radians(static_cast(lon)); yAxis = _globeNode->ellipsoid().geodeticSurfaceNormal( { latitudeRad, longitudeRad } ); diff --git a/modules/globebrowsing/src/globetranslation.cpp b/modules/globebrowsing/src/globetranslation.cpp index 1d423b0a37..2d997e1727 100644 --- a/modules/globebrowsing/src/globetranslation.cpp +++ b/modules/globebrowsing/src/globetranslation.cpp @@ -222,6 +222,14 @@ glm::dvec3 GlobeTranslation::position(const UpdateData&) const { return _position; } + if (!_attachedNode) { + LERRORC( + "GlobeRotation", + std::format("Could not find attached node '{}'", _globe.value()) + ); + return _position; + } + GlobeBrowsingModule* mod = global::moduleEngine->module(); double lat = _latitude; @@ -229,7 +237,7 @@ glm::dvec3 GlobeTranslation::position(const UpdateData&) const { double alt = _altitude; if (_useCamera) { - glm::dvec3 position = mod->geoPosition(); + const glm::dvec3 position = mod->geoPosition(); lat = position.x; lon = position.y; if (_useCameraAltitude) { @@ -238,16 +246,16 @@ glm::dvec3 GlobeTranslation::position(const UpdateData&) const { } if (_useHeightmap) { - - glm::vec3 groundPos = mod->cartesianCoordinatesFromGeo( + const glm::vec3 groundPos = mod->cartesianCoordinatesFromGeo( *_attachedNode, lat, lon, 0.0 ); - SurfacePositionHandle h = - _attachedNode->calculateSurfacePositionHandle(groundPos); + const SurfacePositionHandle h = _attachedNode->calculateSurfacePositionHandle( + groundPos + ); _position = mod->cartesianCoordinatesFromGeo( *_attachedNode, diff --git a/modules/globebrowsing/src/gpulayergroup.cpp b/modules/globebrowsing/src/gpulayergroup.cpp index c5f6355990..319ae6ea7c 100644 --- a/modules/globebrowsing/src/gpulayergroup.cpp +++ b/modules/globebrowsing/src/gpulayergroup.cpp @@ -43,9 +43,9 @@ void GPULayerGroup::setValue(ghoul::opengl::ProgramObject& program, ); const std::vector& activeLayers = layerGroup.activeLayers(); - for (unsigned int i = 0; i < activeLayers.size(); ++i) { + for (unsigned int i = 0; i < activeLayers.size(); i++) { const GPULayer& gal = _gpuActiveLayers[i]; - auto& galuc = gal.uniformCache; + const auto& galuc = gal.uniformCache; const Layer& al = *activeLayers[i]; program.setUniform(galuc.opacity, al.opacity()); @@ -80,7 +80,7 @@ void GPULayerGroup::setValue(ghoul::opengl::ProgramObject& program, tileIndex, layerGroup.pileSize() ); - for (size_t j = 0; j < _gpuActiveLayers[i].gpuChunkTiles.size(); ++j) { + for (size_t j = 0; j < _gpuActiveLayers[i].gpuChunkTiles.size(); j++) { GPULayer::GPUChunkTile& t = _gpuActiveLayers[i].gpuChunkTiles[j]; ghoul_assert(ctp[j].has_value(), "Wrong ChunkTiles number in pile"); const ChunkTile& ct = *ctp[j]; @@ -112,11 +112,11 @@ void GPULayerGroup::bind(ghoul::opengl::ProgramObject& p, const LayerGroup& laye const std::vector& activeLayers = layerGroup.activeLayers(); _gpuActiveLayers.resize(activeLayers.size()); const int pileSize = layerGroup.pileSize(); - for (size_t i = 0; i < _gpuActiveLayers.size(); ++i) { + for (size_t i = 0; i < _gpuActiveLayers.size(); i++) { GPULayer& gal = _gpuActiveLayers[i]; auto& galuc = gal.uniformCache; const Layer& al = *activeLayers[i]; - std::string name = fmt::format("{}[{}].", layerGroup.identifier(), i); + const std::string name = std::format("{}[{}].", layerGroup.identifier(), i); if (layerGroup.isHeightLayer()) { gal.isHeightLayer = true; @@ -149,10 +149,10 @@ void GPULayerGroup::bind(ghoul::opengl::ProgramObject& p, const LayerGroup& laye case layers::Layer::ID::TileProviderByIndex: case layers::Layer::ID::TileProviderByLevel: { gal.gpuChunkTiles.resize(pileSize); - for (size_t j = 0; j < gal.gpuChunkTiles.size(); ++j) { + for (size_t j = 0; j < gal.gpuChunkTiles.size(); j++) { GPULayer::GPUChunkTile& t = gal.gpuChunkTiles[j]; auto& tuc = t.uniformCache; - std::string n = name + "pile.chunkTile" + std::to_string(j) + "."; + const std::string n = std::format("{}pile.chunkTile{}.", name, j); tuc.texture = p.uniformLocation(n + "textureSampler"); tuc.uvOffset = p.uniformLocation(n + "uvTransform.uvOffset"); diff --git a/modules/globebrowsing/src/layer.cpp b/modules/globebrowsing/src/layer.cpp index 5512da068f..b1ef0eb2a7 100644 --- a/modules/globebrowsing/src/layer.cpp +++ b/modules/globebrowsing/src/layer.cpp @@ -209,7 +209,7 @@ Layer::Layer(layers::Group::ID id, const ghoul::Dictionary& layerDict, LayerGrou { const Parameters p = codegen::bake(layerDict); - layers::Layer::ID typeID = + const layers::Layer::ID typeID = p.type.has_value() ? ghoul::from_string(*p.type) : layers::Layer::ID::DefaultTileProvider; @@ -385,7 +385,7 @@ ChunkTilePile Layer::chunkTilePile(const TileIndex& tileIndex, int pileSize) con else { ChunkTilePile chunkTilePile; std::fill(chunkTilePile.begin(), chunkTilePile.end(), std::nullopt); - for (int i = 0; i < pileSize; ++i) { + for (int i = 0; i < pileSize; i++) { ChunkTile tile; tile.uvTransform = TileUvTransform{ { 0, 0 }, { 1, 1 } }; chunkTilePile[i] = tile; @@ -457,7 +457,7 @@ void Layer::update() { glm::vec2 Layer::tileUvToTextureSamplePosition(const TileUvTransform& uvTransform, const glm::vec2& tileUV) { - glm::vec2 uv = uvTransform.uvOffset + uvTransform.uvScale * tileUV; + const glm::vec2 uv = uvTransform.uvOffset + uvTransform.uvScale * tileUV; return uv; } @@ -481,10 +481,10 @@ void Layer::initializeBasedOnType(layers::Layer::ID id, ghoul::Dictionary initDi static_cast(_layerGroupId) ); if (initDict.hasKey(KeyName) && initDict.hasValue(KeyName)) { - std::string name = initDict.value(KeyName); + const std::string name = initDict.value(KeyName); LDEBUG("Initializing tile provider for layer: '" + name + "'"); } - _tileProvider = TileProvider::createFromDictionary(id, std::move(initDict)); + _tileProvider = TileProvider::createFromDictionary(id, initDict); break; case layers::Layer::ID::SolidColor: if (initDict.hasValue(ColorInfo.identifier)) { diff --git a/modules/globebrowsing/src/layeradjustment.cpp b/modules/globebrowsing/src/layeradjustment.cpp index f51fba812a..8ddf55e323 100644 --- a/modules/globebrowsing/src/layeradjustment.cpp +++ b/modules/globebrowsing/src/layeradjustment.cpp @@ -81,13 +81,13 @@ LayerAdjustment::LayerAdjustment() , _chromaKeyColor(ChromaKeyColorInfo, glm::vec3(0.f), glm::vec3(0.f), glm::vec3(1.f)) , _chromaKeyTolerance(ChromaKeyToleranceInfo, 0.f, 0.f, 1.f) , _typeOption(TypeInfo, properties::OptionProperty::DisplayType::Dropdown) + , _typeId(static_cast(_typeOption.value())) { // Add options to option properties for (const layers::Adjustment& ai : layers::Adjustments) { _typeOption.addOption(static_cast(ai.id), std::string(ai.identifier)); } _typeOption.setValue(static_cast(layers::Adjustment::ID::None)); - _typeId = static_cast(_typeOption.value()); _typeOption.onChange([this]() { switch (type()) { diff --git a/modules/globebrowsing/src/layergroup.cpp b/modules/globebrowsing/src/layergroup.cpp index 25778db067..c18b78bad2 100644 --- a/modules/globebrowsing/src/layergroup.cpp +++ b/modules/globebrowsing/src/layergroup.cpp @@ -58,10 +58,10 @@ LayerGroup::LayerGroup(layers::Group group) void LayerGroup::setLayersFromDict(const ghoul::Dictionary& dict) { for (size_t i = 1; i <= dict.size(); i++) { - ghoul::Dictionary layerDict = dict.value(std::to_string(i)); + const ghoul::Dictionary layer = dict.value(std::to_string(i)); try { - addLayer(layerDict); + addLayer(layer); } catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); @@ -101,7 +101,7 @@ void LayerGroup::update() { Layer* LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { ZoneScoped; - documentation::TestResult res = documentation::testSpecification( + const documentation::TestResult res = documentation::testSpecification( Layer::Documentation(), layerDict ); @@ -113,7 +113,7 @@ Layer* LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { LERROR("'Identifier' must be specified for layer"); return nullptr; } - std::string identifier = layerDict.value("Identifier"); + const std::string identifier = layerDict.value("Identifier"); if (hasPropertySubOwner(identifier)) { LINFO("Layer with identifier '" + identifier + "' already exists"); _levelBlendingEnabled.setVisibility(properties::Property::Visibility::User); @@ -162,12 +162,11 @@ Layer* LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { void LayerGroup::deleteLayer(const std::string& layerName) { for (std::vector>::iterator it = _layers.begin(); it != _layers.end(); - ++it) + it++) { if (it->get()->identifier() == layerName) { // we need to make a copy as the layername is only a reference // which will no longer be valid once it is deleted - std::string name = layerName; removePropertySubOwner(it->get()); (*it)->deinitialize(); properties::PropertyOwner* layerGroup = it->get()->owner(); @@ -184,7 +183,7 @@ void LayerGroup::deleteLayer(const std::string& layerName) { if (_onChangeCallback) { _onChangeCallback(nullptr); } - LINFO("Deleted layer " + name); + LINFO("Deleted layer " + layerName); if (_layers.empty()) { _levelBlendingEnabled.setVisibility( @@ -211,10 +210,10 @@ void LayerGroup::moveLayer(int oldPosition, int newPosition) { _layers.insert(newPosLayers, std::move(v)); auto oldPosOwner = _subOwners.begin() + oldPosition; - PropertyOwner* owner = std::move(*oldPosOwner); + PropertyOwner* owner = *oldPosOwner; _subOwners.erase(oldPosOwner); auto newPosOwner = _subOwners.begin() + newPosition; - _subOwners.insert(newPosOwner, std::move(owner)); + _subOwners.insert(newPosOwner, owner); } std::vector LayerGroup::layers() const { diff --git a/modules/globebrowsing/src/layergroupid.cpp b/modules/globebrowsing/src/layergroupid.cpp index 52ee68e097..4db0c8237b 100644 --- a/modules/globebrowsing/src/layergroupid.cpp +++ b/modules/globebrowsing/src/layergroupid.cpp @@ -55,19 +55,17 @@ static_assert( Groups.begin(), Groups.end(), [](const Group& gi) { - auto it = std::find_if( + const auto it = std::find_if( Groups.begin(), Groups.end(), [gi](const Group& g) { return g.id == gi.id; } ); - std::ptrdiff_t pos = std::distance(Groups.begin(), it); + const std::ptrdiff_t pos = std::distance(Groups.begin(), it); return static_cast(pos) == static_cast(gi.id); } ) ); - - static_assert( std::is_sorted( Layers.begin(), @@ -87,12 +85,12 @@ static_assert( Layers.begin(), Layers.end(), [](const Layer& li) { - auto it = std::find_if( + const auto it = std::find_if( Layers.begin(), Layers.end(), [li](const Layer& l) { return l.id == li.id; } ); - std::ptrdiff_t pos = std::distance(Layers.begin(), it); + const std::ptrdiff_t pos = std::distance(Layers.begin(), it); return static_cast(pos) == static_cast(li.id); } ) @@ -121,12 +119,12 @@ static_assert( Adjustments.begin(), Adjustments.end(), [](const Adjustment& ai) { - auto it = std::find_if( + const auto it = std::find_if( Adjustments.begin(), Adjustments.end(), [ai](const Adjustment& a) { return a.id == ai.id; } ); - std::ptrdiff_t pos = std::distance(Adjustments.begin(), it); + const std::ptrdiff_t pos = std::distance(Adjustments.begin(), it); return static_cast(pos) == static_cast(ai.id); } ) @@ -155,12 +153,12 @@ static_assert( Blends.begin(), Blends.end(), [](const Blend& bi) { - auto it = std::find_if( + const auto it = std::find_if( Blends.begin(), Blends.end(), [bi](const Blend& b) { return b.id == bi.id; } ); - std::ptrdiff_t pos = std::distance(Blends.begin(), it); + const std::ptrdiff_t pos = std::distance(Blends.begin(), it); return static_cast(pos) == static_cast(bi.id); } ) diff --git a/modules/globebrowsing/src/layergroupid.h b/modules/globebrowsing/src/layergroupid.h index b8e6d92c11..a1d5f159fd 100644 --- a/modules/globebrowsing/src/layergroupid.h +++ b/modules/globebrowsing/src/layergroupid.h @@ -210,7 +210,7 @@ constexpr openspace::globebrowsing::layers::Layer::ID from_string(std::string_vi return it->id; } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find Layer of type '{}'", string )); } @@ -231,7 +231,7 @@ constexpr openspace::globebrowsing::layers::Group::ID from_string(std::string_vi return it->id; } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find Group of type '{}'", string )); } diff --git a/modules/globebrowsing/src/layermanager.cpp b/modules/globebrowsing/src/layermanager.cpp index 7395554c18..3c088952fc 100644 --- a/modules/globebrowsing/src/layermanager.cpp +++ b/modules/globebrowsing/src/layermanager.cpp @@ -58,21 +58,21 @@ void LayerManager::initialize(const ghoul::Dictionary& layerGroupsDict) { ZoneScoped; // First create empty layer groups in case not all are specified - for (size_t i = 0; i < _layerGroups.size(); ++i) { + for (size_t i = 0; i < _layerGroups.size(); i++) { _layerGroups[i] = std::make_unique(layers::Groups[i]); } // Create all the layer groups - for (std::string_view groupName : layerGroupsDict.keys()) { + for (std::string_view group : layerGroupsDict.keys()) { using namespace layers; - Group::ID id = ghoul::from_string(groupName); + const Group::ID id = ghoul::from_string(group); if (id != Group::ID::Unknown) { - ghoul::Dictionary d = layerGroupsDict.value(groupName); + const ghoul::Dictionary d = layerGroupsDict.value(group); _layerGroups[static_cast(id)]->setLayersFromDict(d); } else { - LWARNINGC("LayerManager", fmt::format("Unknown layer group: {}", groupName)); + LWARNINGC("LayerManager", std::format("Unknown layer group '{}'", group)); } } @@ -140,7 +140,7 @@ std::array LayerManager::layerGroups( ZoneScoped; std::array res = {}; - for (size_t i = 0; i < NumLayerGroups; ++i) { + for (size_t i = 0; i < NumLayerGroups; i++) { res[i] = _layerGroups[i].get(); } return res; @@ -166,7 +166,7 @@ void LayerManager::reset(bool includeDisabled) { } } -void LayerManager::onChange(std::function callback) { +void LayerManager::onChange(const std::function& callback) { ZoneScoped; for (std::unique_ptr& layerGroup : _layerGroups) { diff --git a/modules/globebrowsing/src/layermanager.h b/modules/globebrowsing/src/layermanager.h index e8cc3e9722..f55341c610 100644 --- a/modules/globebrowsing/src/layermanager.h +++ b/modules/globebrowsing/src/layermanager.h @@ -55,8 +55,8 @@ public: void initialize(const ghoul::Dictionary& layerGroupsDict); void deinitialize(); - Layer* addLayer(layers::Group::ID groupId, const ghoul::Dictionary& layerDict); - void deleteLayer(layers::Group::ID groupId, const std::string& layerName); + Layer* addLayer(layers::Group::ID id, const ghoul::Dictionary& layerDict); + void deleteLayer(layers::Group::ID id, const std::string& layerName); LayerGroup& layerGroup(layers::Group::ID groupId); const LayerGroup& layerGroup(layers::Group::ID groupId) const; @@ -68,7 +68,7 @@ public: void update(); void reset(bool includeDisabled = false); - void onChange(std::function callback); + void onChange(const std::function& callback); static documentation::Documentation Documentation(); diff --git a/modules/globebrowsing/src/layerrendersettings.cpp b/modules/globebrowsing/src/layerrendersettings.cpp index 81e71a26ef..144289775a 100644 --- a/modules/globebrowsing/src/layerrendersettings.cpp +++ b/modules/globebrowsing/src/layerrendersettings.cpp @@ -81,27 +81,25 @@ LayerRenderSettings::LayerRenderSettings() }); } -void LayerRenderSettings::onChange(std::function callback) { +void LayerRenderSettings::onChange(const std::function& callback) { gamma.onChange(callback); multiplier.onChange(callback); multiplier.onChange(callback); offset.onChange(callback); } -float LayerRenderSettings::performLayerSettings(float v) const { +float LayerRenderSettings::performLayerSettings(float value) const { return - ((glm::sign(v) * glm::pow(glm::abs(v), gamma) * multiplier) + offset); + ((glm::sign(value) * glm::pow(glm::abs(value), gamma) * multiplier) + offset); } glm::vec4 LayerRenderSettings::performLayerSettings(const glm::vec4& currentValue) const { - glm::vec4 newValue = glm::vec4( + return glm::vec4( performLayerSettings(currentValue.r), performLayerSettings(currentValue.g), performLayerSettings(currentValue.b), performLayerSettings(currentValue.a) ); - - return newValue; } } // namespace openspace::globebrowsing diff --git a/modules/globebrowsing/src/layerrendersettings.h b/modules/globebrowsing/src/layerrendersettings.h index b0d36d97f7..58974cb143 100644 --- a/modules/globebrowsing/src/layerrendersettings.h +++ b/modules/globebrowsing/src/layerrendersettings.h @@ -40,7 +40,7 @@ struct LayerRenderSettings : public properties::PropertyOwner { properties::FloatProperty offset; properties::TriggerProperty setDefault; - void onChange(std::function callback); + void onChange(const std::function& callback); /** * This function matches the function with the same name in the shader code. diff --git a/modules/globebrowsing/src/lruthreadpool.inl b/modules/globebrowsing/src/lruthreadpool.inl index 6e6ed763c3..cfa17c6170 100644 --- a/modules/globebrowsing/src/lruthreadpool.inl +++ b/modules/globebrowsing/src/lruthreadpool.inl @@ -61,7 +61,7 @@ template LRUThreadPool::LRUThreadPool(size_t numThreads, size_t queueSize) : _queuedTasks(queueSize) { - for (size_t i = 0; i < numThreads; ++i) { + for (size_t i = 0; i < numThreads; i++) { _workers.push_back(std::thread(LRUThreadPoolWorker(*this))); } } @@ -81,7 +81,7 @@ LRUThreadPool::~LRUThreadPool() { _condition.notify_all(); // join them - for (size_t i = 0; i < _workers.size(); ++i) { + for (size_t i = 0; i < _workers.size(); i++) { _workers[i].join(); } } diff --git a/modules/globebrowsing/src/memoryawaretilecache.cpp b/modules/globebrowsing/src/memoryawaretilecache.cpp index e47709663d..ac35f07a88 100644 --- a/modules/globebrowsing/src/memoryawaretilecache.cpp +++ b/modules/globebrowsing/src/memoryawaretilecache.cpp @@ -215,12 +215,12 @@ void MemoryAwareTileCache::TextureContainer::reset() { using namespace ghoul::systemcapabilities; - ghoul::opengl::Texture::FilterMode mode = + const ghoul::opengl::Texture::FilterMode mode = OpenGLCap.gpuVendor() == OpenGLCapabilitiesComponent::Vendor::AmdATI ? ghoul::opengl::Texture::FilterMode::Linear : ghoul::opengl::Texture::FilterMode::AnisotropicMipMap; - for (size_t i = 0; i < _numTextures; ++i) { + for (size_t i = 0; i < _numTextures; i++) { using namespace ghoul::opengl; std::unique_ptr tex = std::make_unique( @@ -331,7 +331,7 @@ void MemoryAwareTileCache::createDefaultTextureContainers() { ZoneScoped; for (const layers::Group& gi : layers::Groups) { - TileTextureInitData initData = tileTextureInitData(gi.id); + const TileTextureInitData initData = tileTextureInitData(gi.id); assureTextureContainerExists(initData); } } @@ -341,13 +341,13 @@ void MemoryAwareTileCache::assureTextureContainerExists( { ZoneScoped; - TileTextureInitData::HashKey initDataKey = initData.hashKey; + const TileTextureInitData::HashKey initDataKey = initData.hashKey; if (_textureContainerMap.find(initDataKey) == _textureContainerMap.end()) { // For now create 500 textures of this type _textureContainerMap.emplace(initDataKey, TextureContainerTileCache( std::make_unique(initData, 500), - std::make_unique(std::numeric_limits::max()) + std::make_unique(std::numeric_limits::max()) ) ); } @@ -429,7 +429,7 @@ ghoul::opengl::Texture* MemoryAwareTileCache::texture(const TileTextureInitData& { // if this texture type does not exist among the texture containers // it needs to be created - TileTextureInitData::HashKey initDataKey = initData.hashKey; + const TileTextureInitData::HashKey initDataKey = initData.hashKey; assureTextureContainerExists(initData); // Now we know that the texture container exists, // check if there are any unused textures @@ -437,7 +437,7 @@ ghoul::opengl::Texture* MemoryAwareTileCache::texture(const TileTextureInitData& _textureContainerMap[initDataKey].first->getTextureIfFree(); // Second option. No more textures available. Pop from the LRU cache if (!texture) { - Tile oldTile = _textureContainerMap[initDataKey].second->popLRU().second; + const Tile oldTile = _textureContainerMap[initDataKey].second->popLRU().second; // Use the old tile's texture texture = oldTile.texture; } @@ -469,16 +469,16 @@ void MemoryAwareTileCache::createTileAndPut(ProviderTileKey key, RawTile rawTile } } else { - size_t previousExpectedDataSize = tex->expectedPixelDataSize(); + const size_t previousExpectedDataSize = tex->expectedPixelDataSize(); ghoul_assert( tex->dataOwnership(), "Texture must have ownership of old data to avoid leaks" ); tex->setPixelData(rawTile.imageData.release(), Texture::TakeOwnership::Yes); rawTile.imageData = nullptr; - [[ maybe_unused ]] size_t expectedDataSize = tex->expectedPixelDataSize(); + [[ maybe_unused ]] const size_t expectedSize = tex->expectedPixelDataSize(); const size_t numBytes = rawTile.textureInitData->totalNumBytes; - ghoul_assert(expectedDataSize == numBytes, "Pixel data size is incorrect"); + ghoul_assert(expectedSize == numBytes, "Pixel data size is incorrect"); _numTextureBytesAllocatedOnCPU += numBytes - previousExpectedDataSize; tex->reUploadTexture(); } @@ -486,14 +486,14 @@ void MemoryAwareTileCache::createTileAndPut(ProviderTileKey key, RawTile rawTile // mode at some point. This will introduce rendering artifacts when looking at the // globe at oblique angles (see #2752) using namespace ghoul::systemcapabilities; - ghoul::opengl::Texture::FilterMode mode = + const ghoul::opengl::Texture::FilterMode mode = OpenGLCap.gpuVendor() == OpenGLCapabilitiesComponent::Vendor::AmdATI ? ghoul::opengl::Texture::FilterMode::Linear : ghoul::opengl::Texture::FilterMode::AnisotropicMipMap; tex->setFilter(mode); Tile tile{ tex, std::move(rawTile.tileMetaData), Tile::Status::OK }; - TileTextureInitData::HashKey initDataKey = initData.hashKey; + const TileTextureInitData::HashKey initDataKey = initData.hashKey; _textureContainerMap[initDataKey].second->put(std::move(key), std::move(tile)); } } @@ -541,7 +541,7 @@ size_t MemoryAwareTileCache::cpuAllocatedDataSize() const { const TextureContainer& textureContainer = *p.second.first; const TileTextureInitData& initData = textureContainer.tileTextureInitData(); if (initData.shouldAllocateDataOnCPU) { - size_t bytesPerTexture = initData.totalNumBytes; + const size_t bytesPerTexture = initData.totalNumBytes; return s + bytesPerTexture * textureContainer.size(); } return s; diff --git a/modules/globebrowsing/src/rawtiledatareader.cpp b/modules/globebrowsing/src/rawtiledatareader.cpp index d6666ede97..feb2a6f75f 100644 --- a/modules/globebrowsing/src/rawtiledatareader.cpp +++ b/modules/globebrowsing/src/rawtiledatareader.cpp @@ -111,7 +111,7 @@ GDALDataType toGDALDataType(GLenum glType) { default: LERRORC( "GDALRawTileDataReader", - fmt::format( + std::format( "OpenGL data type unknown to GDAL: {}", static_cast(glType) ) ); @@ -126,8 +126,8 @@ GDALDataType toGDALDataType(GLenum glType) { */ int calculateTileLevelDifference(GDALDataset* dataset, int minimumPixelSize) { GDALRasterBand* firstBand = dataset->GetRasterBand(1); - GDALRasterBand* maxOverview; - int numOverviews = firstBand->GetOverviewCount(); + GDALRasterBand* maxOverview = nullptr; + const int numOverviews = firstBand->GetOverviewCount(); if (numOverviews <= 0) { // No overviews. Use first band. maxOverview = firstBand; } @@ -141,8 +141,8 @@ int calculateTileLevelDifference(GDALDataset* dataset, int minimumPixelSize) { } bool isInside(const PixelRegion& lhs, const PixelRegion& rhs) { - glm::ivec2 e = lhs.start + lhs.numPixels; - glm::ivec2 re = rhs.start + rhs.numPixels; + const glm::ivec2 e = lhs.start + lhs.numPixels; + const glm::ivec2 re = rhs.start + rhs.numPixels; return rhs.start.x <= lhs.start.x && e.x <= re.x && rhs.start.y <= lhs.start.y && e.y <= re.y; } @@ -152,7 +152,7 @@ bool isInside(const PixelRegion& lhs, const PixelRegion& rhs) { * by GDAL. */ std::array geoTransform(int rasterX, int rasterY) { - GeodeticPatch cov( + const GeodeticPatch cov( Geodetic2{ 0.0, 0.0 }, Geodetic2{ glm::half_pi(), glm::pi() } ); @@ -256,7 +256,7 @@ RawTileDataReader::RawTileDataReader(std::string filePath, } RawTileDataReader::~RawTileDataReader() { - std::lock_guard lockGuard(_datasetLock); + const std::lock_guard lockGuard(_datasetLock); if (_dataset) { GDALClose(_dataset); _dataset = nullptr; @@ -282,21 +282,21 @@ std::optional RawTileDataReader::mrfCache() { for (std::string_view fmt : Unsupported) { if (_datasetFilePath.ends_with(fmt)) { - LWARNING(fmt::format( - "Unsupported file format for MRF caching: {}, Dataset: {}", + LWARNING(std::format( + "Unsupported file format for MRF caching: '{}', Dataset: '{}'", fmt, _datasetFilePath )); return std::nullopt; } } - GlobeBrowsingModule& module = *global::moduleEngine->module(); + const GlobeBrowsingModule& mod = *global::moduleEngine->module(); - std::string datasetIdentifier = + const std::string datasetIdentifier = std::to_string(std::hash{}(_datasetFilePath)); - std::string path = fmt::format("{}/{}/{}/", - module.mrfCacheLocation(), _cacheProperties.path, datasetIdentifier); - std::string root = absPath(path).string(); + const std::string path = std::format("{}/{}/{}/", + mod.mrfCacheLocation(), _cacheProperties.path, datasetIdentifier); + const std::string root = absPath(path).string(); std::string mrf = root + datasetIdentifier + ".mrf"; if (!std::filesystem::exists(mrf)) { @@ -304,9 +304,9 @@ std::optional RawTileDataReader::mrfCache() { if (!std::filesystem::create_directories(root, ec)) { // Already existing directories causes a 'failure' but no error if (ec) { - LWARNING(fmt::format( - "Failed to create directories for cache at: {}. " - "Error Code: {}, message: {}", + LWARNING(std::format( + "Failed to create directories for cache at: '{}'. " + "Error Code: '{}', message: {}", root, std::to_string(ec.value()), ec.message() )); return std::nullopt; @@ -319,8 +319,8 @@ std::optional RawTileDataReader::mrfCache() { GDALOpen(_datasetFilePath.c_str(), GA_ReadOnly) ); if (!src) { - LWARNING(fmt::format( - "Failed to load dataset: {}. GDAL Error: {}", + LWARNING(std::format( + "Failed to load dataset '{}'. GDAL error: {}", _datasetFilePath, CPLGetLastErrorMsg() )); return std::nullopt; @@ -356,8 +356,8 @@ std::optional RawTileDataReader::mrfCache() { driver->CreateCopy(mrf.c_str(), src, false, createOpts, nullptr, nullptr) ); if (!dst) { - LWARNING(fmt::format( - "Failed to create MRF Caching dataset dataset: {}. GDAL Error: {}", + LWARNING(std::format( + "Failed to create MRF Caching dataset dataset '{}'. GDAL error: {}", mrf, CPLGetLastErrorMsg() )); return std::nullopt; @@ -397,8 +397,8 @@ void RawTileDataReader::initialize() { ZoneScopedN("GDALOpen"); _dataset = static_cast(GDALOpen(content.c_str(), GA_ReadOnly)); if (!_dataset) { - throw ghoul::RuntimeError(fmt::format( - "Failed to load dataset: {}. GDAL Error: {}", + throw ghoul::RuntimeError(std::format( + "Failed to load dataset '{}'. GDAL error: {}", _datasetFilePath, CPLGetLastErrorMsg() )); } @@ -408,15 +408,15 @@ void RawTileDataReader::initialize() { _rasterCount = _dataset->GetRasterCount(); // calculateTileDepthTransform - unsigned long long maximumValue = [](GLenum t) { + const unsigned long long maximumValue = [](GLenum t) { switch (t) { case GL_UNSIGNED_BYTE: return 1ULL << 8ULL; case GL_UNSIGNED_SHORT: return 1ULL << 16ULL; case GL_SHORT: return 1ULL << 15ULL; case GL_UNSIGNED_INT: return 1ULL << 32ULL; case GL_INT: return 1ULL << 31ULL; - case GL_HALF_FLOAT: return 1ULL; - case GL_FLOAT: return 1ULL; + case GL_HALF_FLOAT: + case GL_FLOAT: case GL_DOUBLE: return 1ULL; default: throw ghoul::MissingCaseException(); } @@ -434,12 +434,12 @@ void RawTileDataReader::initialize() { _noDataValue = static_cast(_dataset->GetRasterBand(1)->GetNoDataValue()); _dataType = toGDALDataType(_initData.glType); - CPLErr error = _dataset->GetGeoTransform(_padfTransform.data()); + const CPLErr error = _dataset->GetGeoTransform(_padfTransform.data()); if (error == CE_Failure) { _padfTransform = geoTransform(_rasterXSize, _rasterYSize); } - double tileLevelDifference = calculateTileLevelDifference( + const double tileLevelDifference = calculateTileLevelDifference( _dataset, _initData.dimensions.x ); @@ -453,7 +453,7 @@ void RawTileDataReader::initialize() { } void RawTileDataReader::reset() { - std::lock_guard lockGuard(_datasetLock); + const std::lock_guard lockGuard(_datasetLock); _maxChunkLevel = -1; if (_dataset) { GDALClose(_dataset); @@ -517,7 +517,7 @@ RawTile::ReadError RawTileDataReader::rasterRead(int rasterBand, } RawTile RawTileDataReader::readTileData(TileIndex tileIndex) const { - size_t numBytes = _initData.totalNumBytes; + const size_t numBytes = _initData.totalNumBytes; RawTile rawTile; rawTile.imageData = std::unique_ptr(new std::byte[numBytes]); @@ -546,7 +546,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor char* imageDataDest) const { // Only read the minimum number of rasters - int nRastersToRead = std::min(_rasterCount, static_cast(_initData.nRasters)); + const int nReadRasters = std::min(_rasterCount, static_cast(_initData.nRasters)); switch (_initData.ghoulTextureFormat) { case ghoul::opengl::Texture::Format::Red: { @@ -558,7 +558,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor case ghoul::opengl::Texture::Format::RG: case ghoul::opengl::Texture::Format::RGB: case ghoul::opengl::Texture::Format::RGBA: { - if (nRastersToRead == 1) { // Grayscale + if (nReadRasters == 1) { // Grayscale for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) @@ -567,7 +567,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor worstError = std::max(worstError, err); } } - else if (nRastersToRead == 2) { // Grayscale + alpha + else if (nReadRasters == 2) { // Grayscale + alpha for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) @@ -581,7 +581,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor worstError = std::max(worstError, err); } else { // Three or more rasters - for (int i = 0; i < nRastersToRead; i++) { + for (int i = 0; i < nReadRasters; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) char* dest = imageDataDest + (i * _initData.bytesPerDatum); @@ -593,7 +593,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor } case ghoul::opengl::Texture::Format::BGR: case ghoul::opengl::Texture::Format::BGRA: { - if (nRastersToRead == 1) { // Grayscale + if (nReadRasters == 1) { // Grayscale for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) @@ -602,7 +602,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor worstError = std::max(worstError, err); } } - else if (nRastersToRead == 2) { // Grayscale + alpha + else if (nReadRasters == 2) { // Grayscale + alpha for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) @@ -616,7 +616,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor worstError = std::max(worstError, err); } else { // Three or more rasters - for (int i = 0; i < 3 && i < nRastersToRead; i++) { + for (int i = 0; i < 3 && i < nReadRasters; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) char* dest = imageDataDest + (i * _initData.bytesPerDatum); @@ -624,7 +624,7 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor worstError = std::max(worstError, err); } } - if (nRastersToRead > 3) { // Alpha channel exists + if (nReadRasters > 3) { // Alpha channel exists // Last read is the alpha channel char* dest = imageDataDest + (3 * _initData.bytesPerDatum); const RawTile::ReadError err = rasterRead(4, io, dest); diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index 165a901d37..ff921efe5b 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -29,7 +29,6 @@ #include #include #include -#include #include #include #include @@ -332,11 +331,11 @@ const Chunk& findChunkNode(const Chunk& node, const Geodetic2& location) { const Geodetic2 center = n->surfacePatch.center(); int index = 0; if (center.lon < location.lon) { - ++index; + index++; } if (location.lat < center.lat) { - ++index; - ++index; + index++; + index++; } n = n->children[static_cast(index)]; } @@ -385,7 +384,7 @@ BoundingHeights boundingHeightsForChunk(const Chunk& chunk, const LayerManager& const size_t HeightChannel = 0; const LayerGroup& heightmaps = lm.layerGroup(layers::Group::ID::HeightLayers); - ChunkTileVector chunkTileSettingPairs = tilesAndSettingsUnsorted( + const ChunkTileVector chunkTileSettingPairs = tilesAndSettingsUnsorted( heightmaps, chunk.tileIndex ); @@ -443,7 +442,7 @@ bool colorAvailableForChunk(const Chunk& chunk, const LayerManager& lm) { const LayerGroup& colorLayers = lm.layerGroup(layers::Group::ID::ColorLayers); for (Layer* lyr : colorLayers.activeLayers()) { if (lyr->tileProvider()) { - ChunkTile t = lyr->tileProvider()->chunkTile(chunk.tileIndex); + const ChunkTile t = lyr->tileProvider()->chunkTile(chunk.tileIndex); if (t.tile.status == Tile::Status::Unavailable) { return false; } @@ -463,7 +462,7 @@ std::array boundingCornersForChunk(const Chunk& chunk, const double patchCenterRadius = ellipsoid.maximumRadius(); const double maxCenterRadius = patchCenterRadius + heights.max; - Geodetic2 halfSize = chunk.surfacePatch.halfSize(); + const Geodetic2 halfSize = chunk.surfacePatch.halfSize(); // As the patch is curved, the maximum height offsets at the corners must be long // enough to cover large enough to cover a heights.max at the center of the @@ -504,7 +503,7 @@ std::array boundingCornersForChunk(const Chunk& chunk, const Geodetic2 pGeodetic = ellipsoid.cartesianToGeodetic2(p); const double latDiff = latCloseToEquator - pGeodetic.lat; - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { const Quad q = static_cast(i % 4); const double cornerHeight = i < 4 ? minCornerHeight : maxCornerHeight; Geodetic3 cornerGeodetic = { chunk.surfacePatch.corner(q), cornerHeight }; @@ -608,8 +607,8 @@ RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) // @TODO (abock, 2021-03-25) The layermanager should be changed to take a // std::map instead and then we don't need to get it // as a bare dictionary anymore and can use the value from the struct directly - ghoul::Dictionary layersDictionary = dictionary.value("Layers"); - _layerManager.initialize(layersDictionary); + const ghoul::Dictionary layersDict = dictionary.value("Layers"); + _layerManager.initialize(layersDict); addProperty(Fadeable::_opacity); addProperty(_generalProperties.performShading); @@ -641,7 +640,7 @@ RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) addPropertySubOwner(_shadowMappingPropertyOwner); _generalProperties.targetLodScaleFactor.onChange([this]() { - float sf = _generalProperties.targetLodScaleFactor; + const float sf = _generalProperties.targetLodScaleFactor; _generalProperties.currentLodScaleFactor = sf; _lodScaleFactorDirty = true; }); @@ -785,7 +784,7 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask try { if (_shadowComponent && _shadowComponent->isEnabled()) { // Set matrices and other GL states - RenderData lightRenderData(_shadowComponent->begin(data)); + const RenderData lightRenderData(_shadowComponent->begin(data)); glDisable(GL_BLEND); @@ -829,7 +828,8 @@ void RenderableGlobe::render(const RenderData& data, RendererTasks& rendererTask } } catch (const ghoul::opengl::TextureUnit::TextureUnitError&) { - std::string layer = _lastChangedLayer ? _lastChangedLayer->guiName() : ""; + const std::string& layer = + _lastChangedLayer ? _lastChangedLayer->guiName() : ""; LWARNINGC( guiName(), @@ -866,7 +866,7 @@ void RenderableGlobe::renderSecondary(const RenderData& data, RendererTasks&) { _globeLabelsComponent.draw(data); } catch (const ghoul::opengl::TextureUnit::TextureUnitError& e) { - LERROR(fmt::format("Error on drawing globe labels: '{}'", e.message)); + LERROR(std::format("Error on drawing globe labels '{}'", e.message)); } if (_geoJsonManager.isReady()) { @@ -917,10 +917,10 @@ void RenderableGlobe::update(const UpdateData& data) { setBoundingSphere(bs); setInteractionSphere(bs); - glm::dmat4 translation = + const glm::dmat4 translation = glm::translate(glm::dmat4(1.0), data.modelTransform.translation); - glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); - glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), data.modelTransform.scale); + const glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); + const glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), data.modelTransform.scale); _cachedModelTransform = translation * rotation * scaling; _cachedInverseModelTransform = glm::inverse(_cachedModelTransform); @@ -1063,7 +1063,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, const std::array& layerGroups = _layerManager.layerGroups(); - for (size_t i = 0; i < layerGroups.size(); ++i) { + for (size_t i = 0; i < layerGroups.size(); i++) { _globalRenderer.gpuLayerGroups[i].bind( *_globalRenderer.program, *layerGroups[i] @@ -1085,7 +1085,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, const std::array& layerGroups = _layerManager.layerGroups(); - for (size_t i = 0; i < layerGroups.size(); ++i) { + for (size_t i = 0; i < layerGroups.size(); i++) { _localRenderer.gpuLayerGroups[i].bind( *_localRenderer.program, *layerGroups[i] @@ -1233,17 +1233,17 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, if (isLeaf(*n) && n->isVisible) { if (n->tileIndex.level < cutoff) { global[iGlobal] = n; - ++iGlobal; + iGlobal++; } else { local[iLocal] = n; - ++iLocal; + iLocal++; } } // Add children to queue, if any if (!isLeaf(*n)) { - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; i++) { traversalMemory.push_back(n->children[i]); } } @@ -1271,7 +1271,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, // Render all chunks that want to be rendered globally _globalRenderer.program->activate(); - for (int i = 0; i < globalCount; ++i) { + for (int i = 0; i < globalCount; i++) { renderChunkGlobally(*_globalChunkBuffer[i], data, shadowData, renderGeomOnly); } _globalRenderer.program->deactivate(); @@ -1279,7 +1279,7 @@ void RenderableGlobe::renderChunks(const RenderData& data, RendererTasks&, // Render all chunks that need to be rendered locally _localRenderer.program->activate(); - for (int i = 0; i < localCount; ++i) { + for (int i = 0; i < localCount; i++) { renderChunkLocally(*_localChunkBuffer[i], data, shadowData, renderGeomOnly); } _localRenderer.program->deactivate(); @@ -1327,7 +1327,7 @@ void RenderableGlobe::renderChunkGlobally(const Chunk& chunk, const RenderData& std::array layerGroups = _layerManager.layerGroups(); - for (size_t i = 0; i < layerGroups.size(); ++i) { + for (size_t i = 0; i < layerGroups.size(); i++) { _globalRenderer.gpuLayerGroups[i].setValue(program, *layerGroups[i], tileIndex); } @@ -1419,7 +1419,7 @@ void RenderableGlobe::renderChunkLocally(const Chunk& chunk, const RenderData& d const std::array& layerGroups = _layerManager.layerGroups(); - for (size_t i = 0; i < layerGroups.size(); ++i) { + for (size_t i = 0; i < layerGroups.size(); i++) { _localRenderer.gpuLayerGroups[i].setValue(program, *layerGroups[i], tileIndex); } @@ -1445,7 +1445,7 @@ void RenderableGlobe::renderChunkLocally(const Chunk& chunk, const RenderData& d std::array cornersCameraSpace; std::array cornersModelSpace; - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; i++) { const Quad q = static_cast(i); const Geodetic2 corner = chunk.surfacePatch.corner(q); const glm::dvec3 cornerModelSpace = _ellipsoid.cartesianSurfacePosition(corner); @@ -1554,7 +1554,7 @@ void RenderableGlobe::debugRenderChunk(const Chunk& chunk, const glm::dmat4& mvp std::vector clippingSpaceCorners(8); AABB3 screenSpaceBounds; - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { const glm::vec4& clippingSpaceCorner = mvp * modelSpaceCorners[i]; clippingSpaceCorners[i] = clippingSpaceCorner; @@ -1726,29 +1726,29 @@ void RenderableGlobe::recompileShaders() { // lastLayerIndex must be at least 0 for the shader to compile, // the layer type is inactivated by setting use to false shaderDictionary.setValue( - fmt::format("lastLayerIndex{}", layers::Groups[i].identifier), + std::format("lastLayerIndex{}", layers::Groups[i].identifier), glm::max(preprocessingData.layeredTextureInfo[i].lastLayerIdx, 0) ); shaderDictionary.setValue( - fmt::format("use{}", layers::Groups[i].identifier), + std::format("use{}", layers::Groups[i].identifier), preprocessingData.layeredTextureInfo[i].lastLayerIdx >= 0 ); shaderDictionary.setValue( - fmt::format("blend{}", layers::Groups[i].identifier), + std::format("blend{}", layers::Groups[i].identifier), preprocessingData.layeredTextureInfo[i].layerBlendingEnabled ); // This is to avoid errors from shader preprocessor shaderDictionary.setValue( - fmt::format("{}0LayerType", layers::Groups[i].identifier), + std::format("{}0LayerType", layers::Groups[i].identifier), 0 ); - std::string groupName = std::string(layers::Groups[i].identifier); + const std::string groupName = std::string(layers::Groups[i].identifier); for (int j = 0; j < preprocessingData.layeredTextureInfo[i].lastLayerIdx + 1; - ++j) + j++) { shaderDictionary.setValue( groupName + std::to_string(j) + "LayerType", @@ -1761,7 +1761,7 @@ void RenderableGlobe::recompileShaders() { for (int j = 0; j < preprocessingData.layeredTextureInfo[i].lastLayerIdx + 1; - ++j) + j++) { shaderDictionary.setValue( groupName + std::to_string(j) + "BlendMode", @@ -1770,12 +1770,12 @@ void RenderableGlobe::recompileShaders() { } // This is to avoid errors from shader preprocessor - std::string keyLayerAdjustmentType = groupName + "0" + "LayerAdjustmentType"; - shaderDictionary.setValue(keyLayerAdjustmentType, 0); + std::string layerAdjustmentType = groupName + "0" + "LayerAdjustmentType"; + shaderDictionary.setValue(std::move(layerAdjustmentType), 0); for (int j = 0; j < preprocessingData.layeredTextureInfo[i].lastLayerIdx + 1; - ++j) + j++) { shaderDictionary.setValue( groupName + std::to_string(j) + "LayerAdjustmentType", @@ -1787,7 +1787,7 @@ void RenderableGlobe::recompileShaders() { } ghoul::Dictionary layerGroupNames; - for (size_t i = 0; i < layers::Groups.size(); ++i) { + for (size_t i = 0; i < layers::Groups.size(); i++) { layerGroupNames.setValue( std::to_string(i), std::string(layers::Groups[i].identifier) @@ -1804,7 +1804,9 @@ void RenderableGlobe::recompileShaders() { shaderDictionary.setValue("nShadowSamples", _generalProperties.nShadowSamples - 1); // Exclise Shadow Samples - int nEclipseShadows = static_cast(_ellipsoid.shadowConfigurationArray().size()); + const int nEclipseShadows = static_cast( + _ellipsoid.shadowConfigurationArray().size() + ); shaderDictionary.setValue("nEclipseShadows", nEclipseShadows - 1); // // Create local shader @@ -1865,11 +1867,11 @@ SurfacePositionHandle RenderableGlobe::calculateSurfacePositionHandle( glm::dvec3 centerToEllipsoidSurface = _ellipsoid.geodeticSurfaceProjection(targetModelSpace); - glm::dvec3 ellipsoidSurfaceToTarget = targetModelSpace - centerToEllipsoidSurface; + const glm::dvec3 ellipsoidSrfToTarget = targetModelSpace - centerToEllipsoidSurface; // ellipsoidSurfaceOutDirection will point towards the target, we want the outward // direction. Therefore it must be flipped in case the target is under the reference // ellipsoid so that it always points outwards - glm::dvec3 ellipsoidSurfaceOutDirection = glm::normalize(ellipsoidSurfaceToTarget); + glm::dvec3 ellipsoidSurfaceOutDirection = glm::normalize(ellipsoidSrfToTarget); if (glm::dot(ellipsoidSurfaceOutDirection, centerToEllipsoidSurface) < 0) { ellipsoidSurfaceOutDirection *= -1.0; } @@ -1986,7 +1988,7 @@ float RenderableGlobe::getHeight(const glm::dvec3& position) const { return 0; } - glm::vec2 transformedUv = layer->tileUvToTextureSamplePosition( + const glm::vec2& transformedUv = layer->tileUvToTextureSamplePosition( uvTransform, patchUV ); @@ -2085,10 +2087,10 @@ void RenderableGlobe::calculateEclipseShadows(ghoul::opengl::ProgramObject& prog ); // Shadow calculations.. std::vector shadowDataArray; - std::vector shadowConfArray = + const std::vector& shadowConfArray = _ellipsoid.shadowConfigurationArray(); shadowDataArray.reserve(shadowConfArray.size()); - double lt; + double lt = 0.0; for (const auto& shadowConf : shadowConfArray) { // TO REMEMBER: all distances and lengths in world coordinates are in // meters!!! We need to move this to view space... @@ -2196,17 +2198,17 @@ void RenderableGlobe::calculateEclipseShadows(ghoul::opengl::ProgramObject& prog constexpr std::string_view NameSource = "shadowDataArray[{}].sourceCasterVec"; constexpr std::string_view NamePos = "shadowDataArray[{}].casterPositionVec"; - programObject.setUniform(fmt::format(NameIsShadowing, counter), sd.isShadowing); + programObject.setUniform(std::format(NameIsShadowing, counter), sd.isShadowing); if (sd.isShadowing) { - programObject.setUniform(fmt::format(NameXp, counter), sd.xp); - programObject.setUniform(fmt::format(NameXu, counter), sd.xu); - programObject.setUniform(fmt::format(NameRc, counter), sd.rc); + programObject.setUniform(std::format(NameXp, counter), sd.xp); + programObject.setUniform(std::format(NameXu, counter), sd.xu); + programObject.setUniform(std::format(NameRc, counter), sd.rc); programObject.setUniform( - fmt::format(NameSource, counter), sd.sourceCasterVec + std::format(NameSource, counter), sd.sourceCasterVec ); programObject.setUniform( - fmt::format(NamePos, counter), sd.casterPositionVec + std::format(NamePos, counter), sd.casterPositionVec ); } counter++; @@ -2363,7 +2365,7 @@ int RenderableGlobe::desiredLevelByAvailableTileData(const Chunk& chunk) const { for (const layers::Group& gi : layers::Groups) { const std::vector& lyrs = _layerManager.layerGroup(gi.id).activeLayers(); for (Layer* layer : lyrs) { - Tile::Status status = layer->tileStatus(chunk.tileIndex); + const Tile::Status status = layer->tileStatus(chunk.tileIndex); // Ensure that the current tile is OK and that the tileprovider for the // current layer has enough data to support an additional level. if (status == Tile::Status::OK && @@ -2391,7 +2393,7 @@ bool RenderableGlobe::isCullableByFrustum(const Chunk& chunk, // Create a bounding box that fits the patch corners AABB3 bounds; // in screen space - for (size_t i = 0; i < 8; ++i) { + for (size_t i = 0; i < 8; i++) { const glm::dvec4 cornerClippingSpace = mvp * corners[i]; const glm::dvec3 ndc = glm::dvec3( (1.f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace @@ -2419,7 +2421,7 @@ bool RenderableGlobe::isCullableByHorizon(const Chunk& chunk, _cachedInverseModelTransform * glm::dvec4(renderData.camera.positionVec3(), 1.0) ); - const glm::dvec3 globeToCamera = cameraPos; + const glm::dvec3& globeToCamera = cameraPos; const Geodetic2 camPosOnGlobe = _ellipsoid.cartesianToGeodetic2(globeToCamera); const Geodetic2 closestPatchPoint = patch.closestPoint(camPosOnGlobe); @@ -2435,7 +2437,7 @@ bool RenderableGlobe::isCullableByHorizon(const Chunk& chunk, _ellipsoid.cartesianSurfacePosition(chunk.surfacePatch.corner(SOUTH_EAST)) }; - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; i++) { const double distance = glm::length(cameraPos - corners[i]); if (distance < glm::length(cameraPos - objectPos)) { objectPos = corners[i]; @@ -2483,7 +2485,7 @@ void RenderableGlobe::splitChunkNode(Chunk& cn, int depth) { std::vector memory = _chunkPool.allocate( static_cast(cn.children.size()) ); - for (size_t i = 0; i < cn.children.size(); ++i) { + for (size_t i = 0; i < cn.children.size(); i++) { cn.children[i] = new (memory[i]) Chunk( cn.tileIndex.child(static_cast(i)) ); @@ -2557,7 +2559,7 @@ bool RenderableGlobe::updateChunkTree(Chunk& cn, const RenderData& data, else { ZoneScopedN("!leaf"); char requestedMergeMask = 0; - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; i++) { if (updateChunkTree(*cn.children[i], data, mvp)) { requestedMergeMask |= (1 << i); } diff --git a/modules/globebrowsing/src/renderableglobe.h b/modules/globebrowsing/src/renderableglobe.h index f4ce5e70e5..a3baeb1ff6 100644 --- a/modules/globebrowsing/src/renderableglobe.h +++ b/modules/globebrowsing/src/renderableglobe.h @@ -70,7 +70,7 @@ struct Chunk { WantSplit }; - Chunk(const TileIndex& tileIndex); + Chunk(const TileIndex& ti); const TileIndex tileIndex; const GeodeticPatch surfacePatch; diff --git a/modules/globebrowsing/src/ringscomponent.cpp b/modules/globebrowsing/src/ringscomponent.cpp index 74642535db..a7fe337ac0 100644 --- a/modules/globebrowsing/src/ringscomponent.cpp +++ b/modules/globebrowsing/src/ringscomponent.cpp @@ -452,7 +452,7 @@ void RingsComponent::draw(const RenderData& data, RenderPass renderPass, const glm::dmat4 inverseModelTransform = glm::inverse(modelTransform); - glm::vec3 sunPositionObjectSpace = glm::normalize( + const glm::vec3 sunPositionObjectSpace = glm::normalize( glm::vec3(inverseModelTransform * glm::vec4(_sunPosition, 0.f)) ); @@ -665,7 +665,7 @@ void RingsComponent::loadTexture() { if (texture) { LDEBUGC( "RingsComponent", - fmt::format("Loaded texture from {}", absPath(_texturePath)) + std::format("Loaded texture from '{}'", absPath(_texturePath)) ); _texture = std::move(texture); @@ -688,8 +688,8 @@ void RingsComponent::loadTexture() { if (textureForwards) { LDEBUGC( "RingsComponent", - fmt::format( - "Loaded forwards scattering texture from {}", + std::format( + "Loaded forwards scattering texture from '{}'", absPath(_textureFwrdPath) ) ); @@ -715,8 +715,8 @@ void RingsComponent::loadTexture() { if (textureBackwards) { LDEBUGC( "RingsComponent", - fmt::format( - "Loaded backwards scattering texture from {}", + std::format( + "Loaded backwards scattering texture from '{}'", absPath(_textureBckwrdPath) ) ); @@ -742,7 +742,7 @@ void RingsComponent::loadTexture() { if (textureUnlit) { LDEBUGC( "RingsComponent", - fmt::format("Loaded unlit texture from {}", absPath(_textureUnlitPath)) + std::format("Loaded unlit texture from '{}'", absPath(_textureUnlitPath)) ); _textureUnlit = std::move(textureUnlit); @@ -765,7 +765,7 @@ void RingsComponent::loadTexture() { if (textureColor) { LDEBUGC( "RingsComponent", - fmt::format("Loaded color texture from {}", absPath(_textureColorPath)) + std::format("Loaded color texture from '{}'", absPath(_textureColorPath)) ); _textureColor = std::move(textureColor); @@ -788,7 +788,7 @@ void RingsComponent::loadTexture() { if (textureTransparency) { LDEBUGC( "RingsComponent", - fmt::format("Loaded unlit texture from {}", absPath(_textureUnlitPath)) + std::format("Loaded unlit texture from '{}'", absPath(_textureUnlitPath)) ); _textureTransparency = std::move(textureTransparency); @@ -817,18 +817,18 @@ void RingsComponent::createPlane() { GLfloat t; }; - VertexData data[] = { - { -size, -size, 0.f, 0.f }, - { size, size, 1.f, 1.f }, - { -size, size, 0.f, 1.f }, - { -size, -size, 0.f, 0.f }, - { size, -size, 1.f, 0.f }, - { size, size, 1.f, 1.f }, + const std::array vertices = { + VertexData{ -size, -size, 0.f, 0.f }, + VertexData{ size, size, 1.f, 1.f }, + VertexData{ -size, size, 0.f, 1.f }, + VertexData{ -size, -size, 0.f, 0.f }, + VertexData{ size, -size, 1.f, 0.f }, + VertexData{ size, size, 1.f, 1.f }, }; glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, diff --git a/modules/globebrowsing/src/shadowcomponent.cpp b/modules/globebrowsing/src/shadowcomponent.cpp index 0797b817e5..7d0034e24e 100644 --- a/modules/globebrowsing/src/shadowcomponent.cpp +++ b/modules/globebrowsing/src/shadowcomponent.cpp @@ -94,67 +94,69 @@ namespace { openspace::properties::Property::Visibility::AdvancedUser }; - constexpr GLfloat ShadowBorder[] = { 1.f, 1.f, 1.f, 1.f }; + constexpr std::array ShadowBorder = { 1.f, 1.f, 1.f, 1.f }; void checkFrameBufferState(const std::string& codePosition) { if (glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LERROR("Framework not built. " + codePosition); - GLenum fbErr = glCheckFramebufferStatus(GL_FRAMEBUFFER); + const GLenum fbErr = glCheckFramebufferStatus(GL_FRAMEBUFFER); switch (fbErr) { - case GL_FRAMEBUFFER_UNDEFINED: - LERROR("Indefined framebuffer"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: - LERROR("Incomplete, missing attachement"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: - LERROR("Framebuffer doesn't have at least one image attached to it"); - break; - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: - LERROR( - "Returned if the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is " - "GL_NONE for any color attachment point(s) named by GL_DRAW_BUFFERi" - ); - break; - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: - LERROR( - "Returned if GL_READ_BUFFER is not GL_NONE and the value of " - "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color " - "attachment point named by GL_READ_BUFFER"); - break; - case GL_FRAMEBUFFER_UNSUPPORTED: - LERROR( - "Returned if the combination of internal formats of the attached " - "images violates an implementation - dependent set of restrictions" - ); - break; - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: - LERROR( - "Returned if the value of GL_RENDERBUFFE_r_samples is not the same " - "for all attached renderbuffers; if the value of GL_TEXTURE_SAMPLES " - "is the not same for all attached textures; or , if the attached " - "images are a mix of renderbuffers and textures, the value of " - "GL_RENDERBUFFE_r_samples does not match the value of " - "GL_TEXTURE_SAMPLES" - ); - LERROR( - "Returned if the value of GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not " - "the same for all attached textures; or , if the attached images are " - "a mix of renderbuffers and textures, the value of " - "GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not GL_TRUE for all attached " - "textures" - ); - break; - case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: - LERROR( - "Returned if any framebuffer attachment is layered, and any " - "populated attachment is not layered, or if all populated color " - "attachments are not from textures of the same target" - ); - break; - default: - LDEBUG("No error found checking framebuffer: " + codePosition); - break; + case GL_FRAMEBUFFER_UNDEFINED: + LERROR("Indefined framebuffer"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: + LERROR("Incomplete, missing attachement"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: + LERROR("Framebuffer doesn't have at least one image attached to it"); + break; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: + LERROR( + "Returned if the value of GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE " + "is GL_NONE for any color attachment point(s) named by " + "GL_DRAW_BUFFERi" + ); + break; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: + LERROR( + "Returned if GL_READ_BUFFER is not GL_NONE and the value of " + "GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is GL_NONE for the color " + "attachment point named by GL_READ_BUFFER"); + break; + case GL_FRAMEBUFFER_UNSUPPORTED: + LERROR( + "Returned if the combination of internal formats of the attached " + "images violates an implementation - dependent set of " + "restrictions" + ); + break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: + LERROR( + "Returned if the value of GL_RENDERBUFFE_r_samples is not the " + "same for all attached renderbuffers; if the value of " + "GL_TEXTURE_SAMPLES is the not same for all attached textures; " + "or , if the attached images are a mix of renderbuffers and " + "textures, the value of GL_RENDERBUFFE_r_samples does not match " + "the value of GL_TEXTURE_SAMPLES" + ); + LERROR( + "Returned if the value of GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is " + "not the same for all attached textures; or , if the attached " + "images are a mix of renderbuffers and textures, the value of " + "GL_TEXTURE_FIXED_SAMPLE_LOCATIONS is not GL_TRUE for all " + "attached textures" + ); + break; + case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: + LERROR( + "Returned if any framebuffer attachment is layered, and any " + "populated attachment is not layered, or if all populated color " + "attachments are not from textures of the same target" + ); + break; + default: + LDEBUG("No error found checking framebuffer: " + codePosition); + break; } } } @@ -190,7 +192,7 @@ ShadowComponent::ShadowComponent(const ghoul::Dictionary& dictionary) if (!dictionary.hasValue("Shadows")) { return; } - ghoul::Dictionary d = dictionary.value("Shadows"); + const ghoul::Dictionary d = dictionary.value("Shadows"); const Parameters p = codegen::bake(d); @@ -207,9 +209,9 @@ ShadowComponent::ShadowComponent(const ghoul::Dictionary& dictionary) _dynamicDepthTextureRes = false; } else { - glm::ivec2 renderingResolution = global::renderEngine->renderingResolution(); - _shadowDepthTextureWidth = renderingResolution.x * 2; - _shadowDepthTextureHeight = renderingResolution.y * 2; + const glm::ivec2 renderingRes= global::renderEngine->renderingResolution(); + _shadowDepthTextureWidth = renderingRes.x * 2; + _shadowDepthTextureHeight = renderingRes.y * 2; _dynamicDepthTextureRes = true; } @@ -239,7 +241,7 @@ void ShadowComponent::deinitializeGL() { } RenderData ShadowComponent::begin(const RenderData& data) { - glm::ivec2 renderingResolution = global::renderEngine->renderingResolution(); + const glm::ivec2 renderingResolution = global::renderEngine->renderingResolution(); if (_dynamicDepthTextureRes && ((_shadowDepthTextureWidth != renderingResolution.x) || (_shadowDepthTextureHeight != renderingResolution.y))) { @@ -252,21 +254,22 @@ RenderData ShadowComponent::begin(const RenderData& data) { // Builds light's ModelViewProjectionMatrix: // =========================================== - glm::dvec3 diffVector = glm::dvec3(_sunPosition) - data.modelTransform.translation; - double originalLightDistance = glm::length(diffVector); - glm::dvec3 lightDirection = glm::normalize(diffVector); + const glm::dvec3 diffVector = + glm::dvec3(_sunPosition) - data.modelTransform.translation; + const double originalLightDistance = glm::length(diffVector); + const glm::dvec3 lightDirection = glm::normalize(diffVector); // Percentage of the original light source distance (to avoid artifacts) //double multiplier = originalLightDistance * // (static_cast(_distanceFraction)/1.0E5); - double multiplier = originalLightDistance * + const double multiplier = originalLightDistance * (static_cast(_distanceFraction) / 1E17); // New light source position //glm::dvec3 lightPosition = data.modelTransform.translation + // (lightDirection * multiplier); - glm::dvec3 lightPosition = data.modelTransform.translation + + const glm::dvec3 lightPosition = data.modelTransform.translation + (diffVector * multiplier); //// Light Position @@ -275,27 +278,27 @@ RenderData ShadowComponent::begin(const RenderData& data) { //=============== Manually Created Camera Matrix =================== //================================================================== // camera Z - glm::dvec3 cameraZ = lightDirection; + const glm::dvec3 cameraZ = lightDirection; // camera X - glm::dvec3 upVector = glm::dvec3(0.0, 1.0, 0.0); - glm::dvec3 cameraX = glm::normalize(glm::cross(upVector, cameraZ)); + const glm::dvec3 upVector = glm::dvec3(0.0, 1.0, 0.0); + const glm::dvec3 cameraX = glm::normalize(glm::cross(upVector, cameraZ)); // camera Y - glm::dvec3 cameraY = glm::cross(cameraZ, cameraX); + const glm::dvec3 cameraY = glm::cross(cameraZ, cameraX); // init 4x4 matrix glm::dmat4 cameraRotationMatrix(1.0); double* matrix = glm::value_ptr(cameraRotationMatrix); - matrix[0] = cameraX.x; - matrix[4] = cameraX.y; - matrix[8] = cameraX.z; - matrix[1] = cameraY.x; - matrix[5] = cameraY.y; - matrix[9] = cameraY.z; - matrix[2] = cameraZ.x; - matrix[6] = cameraZ.y; + matrix[0] = cameraX.x; + matrix[4] = cameraX.y; + matrix[8] = cameraX.z; + matrix[1] = cameraY.x; + matrix[5] = cameraY.y; + matrix[9] = cameraY.z; + matrix[2] = cameraZ.x; + matrix[6] = cameraZ.y; matrix[10] = cameraZ.z; // set translation part @@ -315,7 +318,7 @@ RenderData ShadowComponent::begin(const RenderData& data) { //============= Light Matrix by Camera Matrices Composition ============= //======================================================================= - glm::dmat4 lightProjectionMatrix = glm::dmat4(_lightCamera->projectionMatrix()); + const glm::dmat4 lightProjectionMatrix = glm::dmat4(_lightCamera->projectionMatrix()); // The model transformation missing in the final shadow matrix is add when rendering // each object (using its transformations provided by the RenderData structure) @@ -326,16 +329,16 @@ RenderData ShadowComponent::begin(const RenderData& data) { // Saves current state glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_currentFBO); - global::renderEngine->openglStateCache().viewport(_mViewport); + global::renderEngine->openglStateCache().viewport(_viewport.data()); glBindFramebuffer(GL_FRAMEBUFFER, _shadowFBO); - GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_NONE, GL_NONE }; - glDrawBuffers(3, drawBuffers); + std::array drawBuffers = { GL_COLOR_ATTACHMENT0, GL_NONE, GL_NONE }; + glDrawBuffers(3, drawBuffers.data()); glViewport(0, 0, _shadowDepthTextureWidth, _shadowDepthTextureHeight); - glClearDepth(1.0f); + glClearDepth(1.f); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); - glClearColor(0.0, 0.0, 0.0, 0.0); + glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //glEnable(GL_CULL_FACE); @@ -344,7 +347,7 @@ RenderData ShadowComponent::begin(const RenderData& data) { //checkGLError("begin() -- set cullface to front"); //glEnable(GL_POLYGON_OFFSET_FILL); //checkGLError("begin() -- enabled polygon offset fill"); - //glPolygonOffset(2.5f, 10.0f); + //glPolygonOffset(2.5f, 10.f); //checkGLError("begin() -- set values for polygon offset"); RenderData lightRenderData{ @@ -365,11 +368,13 @@ void ShadowComponent::end() { // Restores system state glBindFramebuffer(GL_FRAMEBUFFER, _currentFBO); - GLenum drawBuffers[] = { - GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 + std::array drawBuffers = { + GL_COLOR_ATTACHMENT0, + GL_COLOR_ATTACHMENT1, + GL_COLOR_ATTACHMENT2 }; - glDrawBuffers(3, drawBuffers); - glViewport(_mViewport[0], _mViewport[1], _mViewport[2], _mViewport[3]); + glDrawBuffers(3, drawBuffers.data()); + glViewport(_viewport[0], _viewport[1], _viewport[2], _viewport[3]); // Restores OpenGL Rendering State global::renderEngine->openglStateCache().resetColorState(); @@ -415,16 +420,8 @@ void ShadowComponent::createShadowFBO() { 0 ); - //glFramebufferTexture( - // GL_FRAMEBUFFER, - // GL_COLOR_ATTACHMENT0, - // _positionInLightSpaceTexture, - // 0 - //); - - //GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_NONE, GL_NONE }; - GLenum drawBuffers[] = { GL_NONE, GL_NONE, GL_NONE }; - glDrawBuffers(3, drawBuffers); + std::array drawBuffers = { GL_NONE, GL_NONE, GL_NONE }; + glDrawBuffers(3, drawBuffers.data()); checkFrameBufferState("createShadowFBO()"); @@ -432,7 +429,7 @@ void ShadowComponent::createShadowFBO() { glBindFramebuffer(GL_FRAMEBUFFER, _currentFBO); } -void ShadowComponent::updateDepthTexture() { +void ShadowComponent::updateDepthTexture() const { glBindTexture(GL_TEXTURE_2D, _shadowDepthTexture); //glTexStorage2D( @@ -459,7 +456,7 @@ void ShadowComponent::updateDepthTexture() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, ShadowBorder); + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, ShadowBorder.data()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); @@ -509,8 +506,8 @@ void ShadowComponent::buildDDepthTexture() { glBindTexture(GL_TEXTURE_2D, 0); } -void ShadowComponent::saveDepthBuffer() { - int size = _shadowDepthTextureWidth * _shadowDepthTextureHeight; +void ShadowComponent::saveDepthBuffer() const { + const int size = _shadowDepthTextureWidth * _shadowDepthTextureHeight; std::vector buffer(size); glReadPixels( @@ -528,19 +525,18 @@ void ShadowComponent::saveDepthBuffer() { ppmFile.open("depthBufferShadowMapping.ppm", std::fstream::out); if (ppmFile.is_open()) { - ppmFile << "P3" << std::endl; - ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight - << std::endl; - ppmFile << "255" << std::endl; + ppmFile << "P3\n"; + ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight << '\n'; + ppmFile << "255\n"; LDEBUG("Saving depth texture to file depthBufferShadowMapping.ppm"); int k = 0; for (int i = 0; i < _shadowDepthTextureWidth; i++) { for (int j = 0; j < _shadowDepthTextureHeight; j++, k++) { - unsigned int val = static_cast(buffer[k]); - ppmFile << val << " " << val << " " << val << " "; + const unsigned int val = static_cast(buffer[k]); + ppmFile << std::format("{0} {0} {0} ", val); } - ppmFile << std::endl; + ppmFile << '\n'; } ppmFile.close(); @@ -567,10 +563,9 @@ void ShadowComponent::saveDepthBuffer() { ppmFile.open("positionBufferShadowMapping.ppm", std::fstream::out); if (ppmFile.is_open()) { - ppmFile << "P3" << std::endl; - ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight - << std::endl; - ppmFile << "255" << std::endl; + ppmFile << "P3\n"; + ppmFile << _shadowDepthTextureWidth << " " << _shadowDepthTextureHeight << '\n'; + ppmFile << "255\n"; LDEBUG("Saving texture position to positionBufferShadowMapping.ppm"); @@ -595,7 +590,7 @@ void ShadowComponent::saveDepthBuffer() { << static_cast(bBuffer[k + 2] / biggestValue) << " "; k += 4; } - ppmFile << std::endl; + ppmFile << '\n'; } ppmFile.close(); diff --git a/modules/globebrowsing/src/shadowcomponent.h b/modules/globebrowsing/src/shadowcomponent.h index 9791dd1e0d..561e961502 100644 --- a/modules/globebrowsing/src/shadowcomponent.h +++ b/modules/globebrowsing/src/shadowcomponent.h @@ -81,11 +81,11 @@ public: private: void createDepthTexture(); void createShadowFBO(); - void updateDepthTexture(); + void updateDepthTexture() const; void buildDDepthTexture(); // Debug - void saveDepthBuffer(); + void saveDepthBuffer() const; ShadowMapData _shadowData; @@ -105,7 +105,7 @@ private: GLuint _positionInLightSpaceTexture = 0; GLuint _shadowFBO = 0; GLint _currentFBO = 0; - GLint _mViewport[4]; + std::array _viewport; GLboolean _faceCulling; GLboolean _polygonOffSet; diff --git a/modules/globebrowsing/src/skirtedgrid.cpp b/modules/globebrowsing/src/skirtedgrid.cpp index 4bc5c1ef46..7437821cc5 100644 --- a/modules/globebrowsing/src/skirtedgrid.cpp +++ b/modules/globebrowsing/src/skirtedgrid.cpp @@ -117,13 +117,13 @@ void SkirtedGrid::initializeGL() { std::vector elementData = createElements(xSegments, ySegments); struct Vertex { - GLfloat texture[2]; + std::array texture; }; std::vector textures = createTextureCoordinates(xSegments, ySegments); std::vector vertexData(textures.size()); - for (size_t i = 0; i < textures.size(); ++i) { + for (size_t i = 0; i < textures.size(); i++) { vertexData[i].texture[0] = textures[i][0]; vertexData[i].texture[1] = textures[i][1]; } diff --git a/modules/globebrowsing/src/skirtedgrid.h b/modules/globebrowsing/src/skirtedgrid.h index 85360432ca..0dd21926cc 100644 --- a/modules/globebrowsing/src/skirtedgrid.h +++ b/modules/globebrowsing/src/skirtedgrid.h @@ -39,10 +39,10 @@ namespace openspace::globebrowsing { class SkirtedGrid { public: /** - * \param xSegments is the number of grid cells in the x direction - * \param ySegments is the number of grid cells in the y direction + * \param xSeg is the number of grid cells in the x direction + * \param ySeg is the number of grid cells in the y direction */ - SkirtedGrid(unsigned int xSegments, unsigned int ySegments); + SkirtedGrid(unsigned int xSeg, unsigned int ySeg); ~SkirtedGrid() = default; void initializeGL(); diff --git a/modules/globebrowsing/src/tileindex.h b/modules/globebrowsing/src/tileindex.h index 10f89628b7..3a0098a4ad 100644 --- a/modules/globebrowsing/src/tileindex.h +++ b/modules/globebrowsing/src/tileindex.h @@ -34,7 +34,7 @@ namespace openspace::globebrowsing { struct TileIndex { using TileHashKey = uint64_t; - TileIndex(uint32_t x, uint32_t y, uint8_t level); + TileIndex(uint32_t x_, uint32_t y_, uint8_t level_); uint32_t x = 0; uint32_t y = 0; diff --git a/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp b/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp index 637c181f9e..b791c499f0 100644 --- a/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp @@ -130,7 +130,7 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) const Parameters p = codegen::bake(dictionary); name = p.name.value_or("Name unspecified"); - std::string _loggerCat = "DefaultTileProvider (" + name + ")"; + const std::string _loggerCat = std::format("DefaultTileProvider ({})", name); // 1. Get required Keys _filePath = p.filePath; @@ -139,10 +139,10 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) // 2. Initialize default values for any optional Keys // getValue does not work for integers - int pixelSize = p.tilePixelSize.value_or(0); + const int pixelSize = p.tilePixelSize.value_or(0); // Only preprocess height layers by default - _performPreProcessing = _layerGroupID == layers::Group::ID::HeightLayers; + _performPreProcessing = (_layerGroupID == layers::Group::ID::HeightLayers); _performPreProcessing = p.performPreProcessing.value_or(_performPreProcessing); // Get the name of the layergroup to which this layer belongs @@ -162,10 +162,10 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) std::string identifier = p.identifier.value_or("unspecified"); std::string enclosing = p.globeName.value_or("unspecified"); - std::string path = fmt::format("{}/{}/{}/", enclosing, layerGroup, identifier); + std::string path = std::format("{}/{}/{}/", enclosing, layerGroup, identifier); - GlobeBrowsingModule& module = *global::moduleEngine->module(); - bool enabled = module.isMRFCachingEnabled(); + const GlobeBrowsingModule& mod = *global::moduleEngine->module(); + bool enabled = mod.isMRFCachingEnabled(); Compression compression = _layerGroupID == layers::Group::ID::HeightLayers ? Compression::LERC : @@ -182,16 +182,16 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) } _cacheProperties.enabled = enabled; - _cacheProperties.path = path; + _cacheProperties.path = std::move(path); _cacheProperties.quality = quality; _cacheProperties.blockSize = blockSize; _cacheProperties.compression = codegen::toString(compression); - TileTextureInitData initData( + TileTextureInitData initData = TileTextureInitData( tileTextureInitData(_layerGroupID, pixelSize) ); _tilePixelSize = initData.dimensions.x; - initAsyncTileDataReader(initData, _cacheProperties); + initAsyncTileDataReader(std::move(initData), _cacheProperties); addProperty(_filePath); addProperty(_tilePixelSize); @@ -206,8 +206,8 @@ void DefaultTileProvider::initAsyncTileDataReader(TileTextureInitData initData, name, std::make_unique( _filePath, - initData, - cacheProperties, + std::move(initData), + std::move(cacheProperties), RawTileDataReader::PerformPreprocessing(_performPreProcessing) ) ); diff --git a/modules/globebrowsing/src/tileprovider/imagesequencetileprovider.cpp b/modules/globebrowsing/src/tileprovider/imagesequencetileprovider.cpp index fade602401..fd2bbc2574 100644 --- a/modules/globebrowsing/src/tileprovider/imagesequencetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/imagesequencetileprovider.cpp @@ -135,7 +135,7 @@ void ImageSequenceTileProvider::update() { _currentTileProvider->deinitialize(); } - std::string p = _imagePaths[_index].string(); + const std::string p = _imagePaths[_index].string(); _currentImage = p; _initDict.setValue("FilePath", p); _currentTileProvider = std::make_unique(_initDict); @@ -150,7 +150,7 @@ void ImageSequenceTileProvider::update() { void ImageSequenceTileProvider::reset() { namespace fs = std::filesystem; - std::string path = _folderPath; + const std::string path = _folderPath; _imagePaths.clear(); for (const fs::directory_entry& p : fs::directory_iterator(path)) { if (p.is_regular_file()) { diff --git a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp index 38f06a658a..cd7f1af860 100644 --- a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp @@ -85,7 +85,7 @@ void SingleImageProvider::reset() { _tileTexture = ghoul::io::TextureReader::ref().loadTexture(_filePath, 2); if (!_tileTexture) { throw ghoul::RuntimeError( - fmt::format("Unable to load texture '{}'", _filePath.value()) + std::format("Unable to load texture '{}'", _filePath.value()) ); } diff --git a/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp b/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp index 13361a8025..136582a69e 100644 --- a/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/sizereferencetileprovider.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include @@ -84,7 +85,7 @@ Tile SizeReferenceTileProvider::tile(const TileIndex& tileIndex) { } double tileLongitudalLength = l; - const char* unit; + const char* unit = nullptr; if (tileLongitudalLength > 9999) { tileLongitudalLength *= 0.001; unit = "km"; @@ -93,8 +94,8 @@ Tile SizeReferenceTileProvider::tile(const TileIndex& tileIndex) { unit = "m"; } - std::string text = fmt::format(" {:.0f} {:s}", tileLongitudalLength, unit); - glm::vec2 textPosition = glm::vec2( + const std::string text = std::format("{:.0f} {:s}", tileLongitudalLength, unit); + const glm::vec2 textPosition = glm::vec2( 0.f, aboveEquator ? fontSize / 2.f : diff --git a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp index a92c98a846..1456f92ba4 100644 --- a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp @@ -197,7 +197,7 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) if (p.prototyped.has_value()) { _mode = Mode::Prototype; - Time start = Time(p.prototyped->time.start); + const Time start = Time(p.prototyped->time.start); Time end = Time::now(); _prototyped.startTimeJ2000 = start.j2000Seconds(); _prototyped.endTimeJ2000 = Time(p.prototyped->time.end).j2000Seconds(); @@ -217,13 +217,13 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) _prototyped.temporalResolution = p.prototyped->temporalResolution; } catch (const ghoul::RuntimeError& e) { - throw ghoul::RuntimeError(fmt::format( - "Could not create time quantizer for Temporal GDAL dataset. {}", e.message + throw ghoul::RuntimeError(std::format( + "Could not create time quantizer for Temporal GDAL dataset: {}", e.message )); } if (p.prototyped->timeFormat.size() >= 64) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Time format string '{}' too large. Maximum length of 64 is allowed", p.prototyped->timeFormat )); @@ -244,8 +244,8 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) continue; } - std::string file = path.path().filename().string(); - std::istringstream ss(file); + const std::string file = path.path().filename().string(); + std::istringstream ss = std::istringstream(file); std::tm tm = {}; ss >> std::get_time(&tm, p.folder->format.c_str()); @@ -257,7 +257,7 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) // unfortunately. Luckily, Spice understands DOY date formats, so // we can specify those directly and noone would use a DOY and a DOM // time string in the same format string, right? Right?! - date = fmt::format( + date = std::format( "{}-{}T{}:{}:{}", tm.tm_year + 1900, tm.tm_yday, @@ -267,7 +267,7 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) ); } else { - date = fmt::format( + date = std::format( "{}-{}-{} {}:{}:{}", tm.tm_year + 1900, tm.tm_mon + 1, @@ -278,8 +278,8 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) ); } - double et = SpiceManager::ref().ephemerisTimeFromDate(date); - _folder.files.push_back({ et, path.path().string() }); + const double et = SpiceManager::ref().ephemerisTimeFromDate(date); + _folder.files.emplace_back(et, path.path().string()); } } @@ -294,8 +294,8 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) ); if (_folder.files.empty()) { - throw ghoul::RuntimeError(fmt::format( - "Error loading layer '{}'. Folder {} does not contain any files that " + throw ghoul::RuntimeError(std::format( + "Error loading layer '{}'. Folder '{}' does not contain any files that " "matched the time format", _identifier, _folder.folder )); @@ -345,8 +345,8 @@ void TemporalTileProvider::update() { try { if (_useFixedTime && !_fixedTime.value().empty()) { if (_fixedTimeDirty) { - std::string fixedTime = _fixedTime.value(); - double et = SpiceManager::ref().ephemerisTimeFromDate(fixedTime); + const std::string fixedTime = _fixedTime.value(); + const double et = SpiceManager::ref().ephemerisTimeFromDate(fixedTime); newCurr = retrieveTileProvider(Time(et)); _fixedTimeDirty = false; } @@ -398,7 +398,7 @@ DefaultTileProvider TemporalTileProvider::createTileProvider( case Mode::Prototype: { static const std::vector IgnoredTokens = { // From: http://www.gdal.org/frmt_wms.html - "${x}", "${y}", "${z}", "${version}" "${format}", "${layer}" + "${x}", "${y}", "${z}", "${version}", "${format}", "${layer}" }; value = _prototyped.prototype; @@ -434,7 +434,7 @@ DefaultTileProvider* TemporalTileProvider::retrieveTileProvider(const Time& t) { return &it->second; } - std::string_view timeStr = [this, time]() { + const std::string_view timeStr = [this, time]() { switch (_mode) { case Mode::Prototype: return timeStringify(_prototyped.timeFormat, Time(time)); @@ -472,8 +472,7 @@ TemporalTileProvider::tileProvider( // Find the most current image that matches the current time. We can't pass the `time` // variable into the retrieveTileProvider function as it would generate a new // non-existing TileProvider for every new frame - using It = std::vector>::const_iterator; - It it = std::lower_bound( + auto it = std::lower_bound( _folder.files.begin(), _folder.files.end(), time.j2000Seconds(), @@ -486,7 +485,7 @@ TemporalTileProvider::tileProvider( it -= 1; } - double t = it->first; + const double t = it->first; return retrieveTileProvider(Time(t)); } @@ -495,8 +494,7 @@ TileProvider* TemporalTileProvider::tileProvider( const Time& time) { - using It = std::vector>::const_iterator; - It next = std::lower_bound( + auto next = std::lower_bound( _folder.files.begin(), _folder.files.end(), time.j2000Seconds(), @@ -505,8 +503,8 @@ TemporalTileProvider::tileProvider( } ); - It curr = next != _folder.files.begin() ? next - 1 : next; - It nextNext = next != _folder.files.end() ? next + 1 : curr; + auto curr = next != _folder.files.begin() ? next - 1 : next; + auto nextNext = next != _folder.files.end() ? next + 1 : curr; if (next == _folder.files.end()) { curr = _folder.files.end() - 1; @@ -514,14 +512,14 @@ TemporalTileProvider::tileProvider( nextNext = curr; } - It prev = curr != _folder.files.begin() ? curr - 1 : curr; + auto prev = curr != _folder.files.begin() ? curr - 1 : curr; _interpolateTileProvider->t1 = retrieveTileProvider(Time(curr->first)); _interpolateTileProvider->t2 = retrieveTileProvider(Time(next->first)); _interpolateTileProvider->future = retrieveTileProvider(Time(nextNext->first)); _interpolateTileProvider->before = retrieveTileProvider(Time(prev->first)); - float factor = static_cast( + const float factor = static_cast( (time.j2000Seconds() - curr->first) / (next->first - curr->first) ); @@ -678,7 +676,7 @@ TemporalTileProvider::InterpolateTileProvider::InterpolateTileProvider( glBindVertexArray(vaoQuad); glBindBuffer(GL_ARRAY_BUFFER, vboQuad); // Quad for fullscreen with vertex (xy) and texture coordinates (uv) - const GLfloat vertexData[] = { + constexpr std::array VertexData = { // x y u v -1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, @@ -687,7 +685,7 @@ TemporalTileProvider::InterpolateTileProvider::InterpolateTileProvider( 1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f }; - glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); // vertex coordinates at location 0 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); @@ -721,21 +719,21 @@ Tile TemporalTileProvider::InterpolateTileProvider::tile(const TileIndex& tileIn TracyGpuZone("tile"); // prev and next are the two tiles to interpolate between - Tile prev = t1->tile(tileIndex); - Tile next = t2->tile(tileIndex); + const Tile prev = t1->tile(tileIndex); + const Tile next = t2->tile(tileIndex); // the tile before and the tile after the interpolation interval are loaded so the // interpolation goes smoother. It is on purpose that we are not actually storing the // return tile here, we just want to trigger the load already before->tile(tileIndex); future->tile(tileIndex); - cache::ProviderTileKey key = { tileIndex, uniqueIdentifier }; + const cache::ProviderTileKey key = { tileIndex, uniqueIdentifier }; if (!prev.texture || !next.texture) { return Tile{ nullptr, std::nullopt, Tile::Status::Unavailable }; } // The data for initializing the texture - TileTextureInitData initData( + const TileTextureInitData initData( prev.texture->dimensions().x, prev.texture->dimensions().y, prev.texture->dataType(), @@ -747,7 +745,7 @@ Tile TemporalTileProvider::InterpolateTileProvider::tile(const TileIndex& tileIn // Initializing the tile that will contian the interpolated texture Tile ourTile; // The texture that will contain the interpolated image - ghoul::opengl::Texture* writeTexture; + ghoul::opengl::Texture* writeTexture = nullptr; cache::MemoryAwareTileCache* tileCache = global::moduleEngine->module()->tileCache(); if (tileCache->exist(key)) { @@ -762,24 +760,24 @@ Tile TemporalTileProvider::InterpolateTileProvider::tile(const TileIndex& tileIn } // Saves current state - GLint currentFBO; - GLint viewport[4]; + GLint currentFBO = 0; + std::array viewport; glGetIntegerv(GL_FRAMEBUFFER_BINDING, ¤tFBO); - global::renderEngine->openglStateCache().viewport(viewport); + global::renderEngine->openglStateCache().viewport(viewport.data()); // Bind render texture to FBO glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, *writeTexture, 0); glDisable(GL_BLEND); - GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, textureBuffers); + const GLenum textureBuffers = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &textureBuffers); // Setup our own viewport settings - GLsizei w = static_cast(writeTexture->width()); - GLsizei h = static_cast(writeTexture->height()); + const GLsizei w = static_cast(writeTexture->width()); + const GLsizei h = static_cast(writeTexture->height()); glViewport(0, 0, w, h); glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT); - GLint id; + GLint id = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &id); // Activate shader and bind uniforms shaderProgram->activate(); diff --git a/modules/globebrowsing/src/tileprovider/texttileprovider.cpp b/modules/globebrowsing/src/tileprovider/texttileprovider.cpp index f775ea1c73..bef9727ad1 100644 --- a/modules/globebrowsing/src/tileprovider/texttileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/texttileprovider.cpp @@ -38,11 +38,8 @@ namespace openspace::globebrowsing { TextTileProvider::TextTileProvider(TileTextureInitData initData_, size_t fontSize_) : initData(std::move(initData_)) , fontSize(fontSize_) -{ - ZoneScoped; - - tileCache = global::moduleEngine->module()->tileCache(); -} + , tileCache(global::moduleEngine->module()->tileCache()) +{} TextTileProvider::~TextTileProvider() {} @@ -66,12 +63,13 @@ Tile TextTileProvider::renderTile(const TileIndex& tileIndex, const std::string& ZoneScoped; TracyGpuZone("tile"); - cache::ProviderTileKey key = { tileIndex, uniqueIdentifier }; + const cache::ProviderTileKey key = { tileIndex, uniqueIdentifier }; Tile tile = tileCache->get(key); if (!tile.texture) { ghoul::opengl::Texture* texture = tileCache->texture(initData); - GLint prevProgram, prevFBO; + GLint prevProgram = 0; + GLint prevFBO = 0; glGetIntegerv(GL_CURRENT_PROGRAM, &prevProgram); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &prevFBO); @@ -85,8 +83,8 @@ Tile TextTileProvider::renderTile(const TileIndex& tileIndex, const std::string& 0 ); - GLsizei w = static_cast(texture->width()); - GLsizei h = static_cast(texture->height()); + const GLsizei w = static_cast(texture->width()); + const GLsizei h = static_cast(texture->height()); global::renderEngine->openglStateCache().loadCurrentGLState(); glViewport(0, 0, w, h); glClearColor( diff --git a/modules/globebrowsing/src/tileprovider/texttileprovider.h b/modules/globebrowsing/src/tileprovider/texttileprovider.h index a9bf92ec43..4d8ec98b86 100644 --- a/modules/globebrowsing/src/tileprovider/texttileprovider.h +++ b/modules/globebrowsing/src/tileprovider/texttileprovider.h @@ -31,7 +31,7 @@ namespace openspace::globebrowsing { class TextTileProvider : public TileProvider { public: - TextTileProvider(TileTextureInitData initData, size_t fontSize = 48); + TextTileProvider(TileTextureInitData initData_, size_t fontSize_ = 48); ~TextTileProvider() override; void reset() override; diff --git a/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp b/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp index 51028ccdb8..a0b186a5db 100644 --- a/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/tileindextileprovider.cpp @@ -59,17 +59,17 @@ TileIndexTileProvider::TileIndexTileProvider(const ghoul::Dictionary& dictionary Tile TileIndexTileProvider::tile(const TileIndex& tileIndex) { ZoneScoped; - std::string text = fmt::format( + const std::string text = std::format( "level: {}\nx: {}\ny: {}", tileIndex.level, tileIndex.x, tileIndex.y ); - glm::vec2 position = glm::vec2( + const glm::vec2 position = glm::vec2( initData.dimensions.x / 4 - (initData.dimensions.x / 32) * log10(1 << tileIndex.level), initData.dimensions.y / 2 + fontSize ); if (_uniqueBackgroundColors) { - TileIndex::TileHashKey key = tileIndex.hashKey(); + const TileIndex::TileHashKey key = tileIndex.hashKey(); size_t hash = std::hash{}(key); // This is pretty ugly, but it's just for debugging and it is reproducable... We @@ -78,11 +78,11 @@ Tile TileIndexTileProvider::tile(const TileIndex& tileIndex) { // each tile. If we divide the resulting number by 255 we get a value [0, 1] that // we can use for the color channel - uint8_t red = reinterpret_cast(&hash)[0]; - uint8_t green = reinterpret_cast(&hash)[1]; - uint8_t blue = reinterpret_cast(&hash)[2]; + const uint8_t red = reinterpret_cast(&hash)[0]; + const uint8_t green = reinterpret_cast(&hash)[1]; + const uint8_t blue = reinterpret_cast(&hash)[2]; - glm::vec4 backgroundColor = glm::vec4( + const glm::vec4 backgroundColor = glm::vec4( static_cast(red) / 255.f, static_cast(green) / 255.f, static_cast(blue) / 255.f, diff --git a/modules/globebrowsing/src/tileprovider/tileprovider.cpp b/modules/globebrowsing/src/tileprovider/tileprovider.cpp index e382233ecc..d6af722e30 100644 --- a/modules/globebrowsing/src/tileprovider/tileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/tileprovider.cpp @@ -75,7 +75,8 @@ std::unique_ptr TileProvider::createFromDictionary( { ZoneScoped; - std::string_view type = layers::Layers[static_cast(layerTypeID)].identifier; + const std::string_view type = + layers::Layers[static_cast(layerTypeID)].identifier; ghoul::TemplateFactory* factory = FactoryManager::ref().factory(); @@ -92,7 +93,7 @@ void TileProvider::initializeDefaultTile() { using namespace ghoul::opengl; // Create pixel data - TileTextureInitData initData( + const TileTextureInitData initData( 8, 8, GL_UNSIGNED_BYTE, @@ -152,7 +153,7 @@ void TileProvider::deinitialize() { } ChunkTile TileProvider::traverseTree(TileIndex tileIndex, int parents, int maxParents, - std::function& ascendToParent, + const std::function& ascendToParent, TileUvTransform& uvTransform) { // Step 1. Traverse 0 or more parents up the chunkTree as requested by the caller @@ -163,7 +164,7 @@ ChunkTile TileProvider::traverseTree(TileIndex tileIndex, int parents, int maxPa // Step 2. Traverse 0 or more parents up the chunkTree to make sure we're inside // the range of defined data. - int maximumLevel = maxLevel(); + const int maximumLevel = maxLevel(); while (tileIndex.level > maximumLevel) { ascendToParent(tileIndex, uvTransform); maxParents--; @@ -174,7 +175,7 @@ ChunkTile TileProvider::traverseTree(TileIndex tileIndex, int parents, int maxPa // Step 3. Traverse 0 or more parents up the chunkTree until we find a chunk that // has a loaded tile ready to use. - int minimumLevel = minLevel(); + const int minimumLevel = minLevel(); while (tileIndex.level > minimumLevel) { Tile t = tile(tileIndex); if (t.status != Tile::Status::OK) { @@ -199,17 +200,16 @@ ChunkTile TileProvider::chunkTile(TileIndex tileIndex, int parents, int maxParen ghoul_assert(isInitialized, "TileProvider was not initialized"); - std::function ascendToParent = [] - (TileIndex& ti, TileUvTransform& uv) { - uv.uvOffset *= 0.5; - uv.uvScale *= 0.5; + constexpr auto ascendToParent = [](TileIndex& ti, TileUvTransform& uv) { + uv.uvOffset *= 0.5; + uv.uvScale *= 0.5; - uv.uvOffset += ti.positionRelativeParent(); + uv.uvOffset += ti.positionRelativeParent(); - ti.x /= 2; - ti.y /= 2; - ti.level--; - }; + ti.x /= 2; + ti.y /= 2; + ti.level--; + }; TileUvTransform uvTransform = { .uvOffset = glm::vec2(0.f, 0.f), @@ -227,7 +227,7 @@ ChunkTilePile TileProvider::chunkTilePile(TileIndex tileIndex, int pileSize) { ChunkTilePile chunkTilePile; std::fill(chunkTilePile.begin(), chunkTilePile.end(), std::nullopt); - for (int i = 0; i < pileSize; ++i) { + for (int i = 0; i < pileSize; i++) { chunkTilePile[i] = chunkTile(tileIndex, i); if (chunkTilePile[i]->tile.status == Tile::Status::Unavailable) { if (i == 0) { diff --git a/modules/globebrowsing/src/tileprovider/tileprovider.h b/modules/globebrowsing/src/tileprovider/tileprovider.h index 7ea483a7b1..5712353df5 100644 --- a/modules/globebrowsing/src/tileprovider/tileprovider.h +++ b/modules/globebrowsing/src/tileprovider/tileprovider.h @@ -141,9 +141,10 @@ struct TileProvider : public properties::PropertyOwner { uint16_t uniqueIdentifier = 0; bool isInitialized = false; + protected: ChunkTile traverseTree(TileIndex tileIndex, int parents, int maxParents, - std::function& ascendToParent, + const std::function& ascendToParent, TileUvTransform& uvTransform); private: diff --git a/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp b/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp index a3c60c22b6..a64fb1f2e1 100644 --- a/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp +++ b/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp @@ -71,14 +71,14 @@ TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { layers::Layer::ID typeID = layers::Layer::ID::DefaultTileProvider; if (p.defaultProvider.hasValue("Type")) { - std::string type = p.defaultProvider.value("Type"); + const std::string type = p.defaultProvider.value("Type"); typeID = ghoul::from_string(type); } _defaultTileProvider = createFromDictionary(typeID, p.defaultProvider); for (const Parameters::IndexProvider& ip : p.indexTileProviders) { - const TileIndex tileIndex( + const TileIndex tileIndex = TileIndex( ip.tileIndex.x, ip.tileIndex.y, static_cast(ip.tileIndex.level) @@ -86,7 +86,7 @@ TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { layers::Layer::ID providerID = layers::Layer::ID::DefaultTileProvider; if (ip.tileProvider.hasValue("Type")) { - std::string type = ip.tileProvider.value("Type"); + const std::string type = ip.tileProvider.value("Type"); providerID = ghoul::from_string(type); } @@ -94,8 +94,8 @@ TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { providerID, ip.tileProvider ); - TileIndex::TileHashKey key = tileIndex.hashKey(); - _providers.insert(std::make_pair(key, std::move(stp))); + const TileIndex::TileHashKey key = tileIndex.hashKey(); + _providers.emplace(key, std::move(stp)); } } diff --git a/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp b/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp index 6e44128fbe..3413212e2d 100644 --- a/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp +++ b/modules/globebrowsing/src/tileprovider/tileproviderbylevel.cpp @@ -50,7 +50,7 @@ TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { const Parameters p = codegen::bake(dictionary); - layers::Group::ID group = static_cast(p.layerGroupID); + const layers::Group::ID group = static_cast(p.layerGroupID); for (Parameters::Provider provider : p.levelTileProviders) { ghoul::Dictionary& tileProviderDict = provider.tileProvider; @@ -65,15 +65,15 @@ TileProviderByLevel::TileProviderByLevel(const ghoul::Dictionary& dictionary) { } layers::Layer::ID typeID = layers::Layer::ID::DefaultTileProvider; if (tileProviderDict.hasValue("Type")) { - std::string type = tileProviderDict.value("Type"); + const std::string type = tileProviderDict.value("Type"); typeID = ghoul::from_string(type); } std::unique_ptr tp = createFromDictionary(typeID, tileProviderDict); - std::string provId = tileProviderDict.value("Identifier"); + const std::string provId = tileProviderDict.value("Identifier"); tp->setIdentifier(provId); - std::string providerName = tileProviderDict.value("Name"); + const std::string providerName = tileProviderDict.value("Name"); tp->setGuiName(providerName); addPropertySubOwner(tp.get()); @@ -130,12 +130,12 @@ TileProvider* TileProviderByLevel::levelProvider(int level) const { ZoneScoped; if (!_levelTileProviders.empty()) { - int clampedLevel = glm::clamp( + const int clampedLevel = glm::clamp( level, 0, static_cast(_providerIndices.size() - 1) ); - int idx = _providerIndices[clampedLevel]; + const int idx = _providerIndices[clampedLevel]; return _levelTileProviders[idx].get(); } else { diff --git a/modules/globebrowsing/src/tiletextureinitdata.cpp b/modules/globebrowsing/src/tiletextureinitdata.cpp index 7f9b918827..91687c9b79 100644 --- a/modules/globebrowsing/src/tiletextureinitdata.cpp +++ b/modules/globebrowsing/src/tiletextureinitdata.cpp @@ -82,7 +82,7 @@ openspace::globebrowsing::TileTextureInitData::HashKey calculateHashKey( ghoul_assert(dimensions.x <= 1024, "Incorrect dimension"); ghoul_assert(dimensions.y <= 1024, "Incorrect dimension"); ghoul_assert(dimensions.z == 1, "Incorrect dimension"); - unsigned int formatId = uniqueIdForTextureFormat(format); + const unsigned int formatId = uniqueIdForTextureFormat(format); ghoul_assert(formatId < 256, "Incorrect format"); openspace::globebrowsing::TileTextureInitData::HashKey res = 0ULL; @@ -169,20 +169,20 @@ TileTextureInitData::TileTextureInitData(size_t width, size_t height, GLenum typ , hashKey(calculateHashKey(dimensions, ghoulTextureFormat, glType)) {} -TileTextureInitData TileTextureInitData::operator=(const TileTextureInitData& rhs) { +TileTextureInitData& TileTextureInitData::operator=(const TileTextureInitData& rhs) { if (this == &rhs) { return *this; } - return rhs; + return *this; } -TileTextureInitData TileTextureInitData::operator=(TileTextureInitData&& rhs) noexcept { +TileTextureInitData& TileTextureInitData::operator=(TileTextureInitData&& rhs) noexcept { if (this == &rhs) { return *this; } - return std::move(rhs); + return *this; } } // namespace openspace::globebrowsing diff --git a/modules/globebrowsing/src/tiletextureinitdata.h b/modules/globebrowsing/src/tiletextureinitdata.h index ffc94a4a35..b1fcf0d80c 100644 --- a/modules/globebrowsing/src/tiletextureinitdata.h +++ b/modules/globebrowsing/src/tiletextureinitdata.h @@ -48,8 +48,8 @@ public: TileTextureInitData(const TileTextureInitData& original) = default; TileTextureInitData(TileTextureInitData&& original) = default; - TileTextureInitData operator=(const TileTextureInitData& rhs); - TileTextureInitData operator=(TileTextureInitData&& rhs) noexcept; + TileTextureInitData& operator=(const TileTextureInitData& rhs); + TileTextureInitData& operator=(TileTextureInitData&& rhs) noexcept; ~TileTextureInitData() = default; diff --git a/modules/globebrowsing/src/timequantizer.cpp b/modules/globebrowsing/src/timequantizer.cpp index 171b36806e..e54c51b352 100644 --- a/modules/globebrowsing/src/timequantizer.cpp +++ b/modules/globebrowsing/src/timequantizer.cpp @@ -47,8 +47,9 @@ namespace openspace::globebrowsing { namespace { // returns the number of days in a given month and year (takes leap year into account) - constexpr int monthSize(int month, int year) { - date::year_month_day_last d = date::year(year) / date::month(month) / date::last; + constexpr int monthSize(int month_, int year_) { + using namespace date; + const year_month_day_last d = year(year_) / month(month_) / last; return static_cast(static_cast(d.day())); } @@ -168,7 +169,7 @@ void DateTime::setTime(std::string_view input) { } std::string DateTime::ISO8601() const { - return fmt::format( + return std::format( "{:0>4}-{:0>2}-{:0>2}T{:0>2}:{:0>2}:{:0>2}", _year, _month, _day, _hour, _minute, _second ); @@ -177,7 +178,7 @@ std::string DateTime::ISO8601() const { double DateTime::J2000() const { char Buffer[20]; std::memset(Buffer, 0, 20); - fmt::format_to( + std::format_to( Buffer, "{:0>4}-{:0>2}-{:0>2}T{:0>2}:{:0>2}:{:0>2}", _year, _month, _day, _hour, _minute, _second @@ -190,7 +191,7 @@ int DateTime::increment(int value, char unit, double error, double resolution) { if (nIncrements == 0) { nIncrements = 1; } - for (unsigned int i = 0; i < nIncrements; ++i) { + for (unsigned int i = 0; i < nIncrements; i++) { incrementOnce(value, unit); } return nIncrements; @@ -225,7 +226,7 @@ void DateTime::incrementOnce(int value, char unit) { _year += value; break; default: - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid unit in incrementOnce '{}'. Expected 'y', 'M', 'd', 'h', or 'm'", unit )); @@ -237,7 +238,7 @@ int DateTime::decrement(int value, char unit, double error, double resolution) { if (nDecrements == 0) { nDecrements = 1; } - for (unsigned int i = 0; i < nDecrements; ++i) { + for (unsigned int i = 0; i < nDecrements; i++) { decrementOnce(value, unit); } return nDecrements; @@ -334,17 +335,17 @@ TimeQuantizer::TimeQuantizer(std::string start, std::string end, const std::string& resolution) : _start(start) , _timerange(std::move(start), std::move(end)) + , _resolution(parseTimeResolutionStr(resolution)) { - _resolution = parseTimeResolutionStr(resolution); verifyStartTimeRestrictions(); } double TimeQuantizer::parseTimeResolutionStr(const std::string& resolutionStr) { const char unit = resolutionStr.back(); - std::string numberString = resolutionStr.substr(0, resolutionStr.length() - 1); + const std::string numberString = resolutionStr.substr(0, resolutionStr.length() - 1); - char* p; - double value = strtol(numberString.c_str(), &p, 10); + char* p = nullptr; + const double value = strtol(numberString.c_str(), &p, 10); _resolutionValue = value; _resolutionUnit = unit; if (*p) { // not a number @@ -371,7 +372,7 @@ void TimeQuantizer::setResolution(const std::string& resolutionString) { void TimeQuantizer::verifyStartTimeRestrictions() { // If monthly time resolution then restrict to 28 days so every month is consistent - int dayUpperLimit; + int dayUpperLimit = 0; std::string helpfulDescription = "the selected month"; if (_resolutionUnit == 'M') { dayUpperLimit = 28; @@ -386,15 +387,13 @@ void TimeQuantizer::verifyStartTimeRestrictions() { dayUpperLimit = 31; } if (_start.day() < 1 || _start.day() > dayUpperLimit) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid start day value of {} for {}, valid days are 1 - {}", - _start.day(), - helpfulDescription, - dayUpperLimit + _start.day(), helpfulDescription, dayUpperLimit )); } if (_start.hour() != 0 || _start.minute() != 0 || _start.second() != 0) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid start time value of {}:{}:{}, time must be 00:00:00", _start.hour(), _start.minute(), _start.second() )); @@ -407,7 +406,7 @@ void TimeQuantizer::verifyResolutionRestrictions(const int value, const char uni break; case 'M': if (value < 1 || value > 6) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid resolution count of {} for (M)onth option. Valid counts are " "1, 2, 3, 4, or 6", value )); @@ -415,15 +414,15 @@ void TimeQuantizer::verifyResolutionRestrictions(const int value, const char uni break; case 'd': if (value < 1 || value > 28) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid resolution count of {} for (d)ay option. Valid counts are " "1 - 28", value )); } break; case 'h': - if (!((value >= 1 && value <= 4) || value == 6 || value == 12)) { - throw ghoul::RuntimeError(fmt::format( + if ((value < 1 || value > 4) && value != 6 && value != 12) { + throw ghoul::RuntimeError(std::format( "Invalid resolution count of {} for (h)our option. Valid counts are " "1, 2, 3, 4, 6, or 12", value )); @@ -431,14 +430,14 @@ void TimeQuantizer::verifyResolutionRestrictions(const int value, const char uni break; case 'm': if (value != 15 && value != 30) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid resolution count of {} for (m)inute option. Valid counts " "are 15 or 30", value )); } break; default: - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid unit format '{}'. Expected 'y', 'M', 'd', 'h', or 'm'", unit )); } @@ -470,7 +469,7 @@ double TimeQuantizer::computeSecondsFromResolution(const int valueIn, const char break; default: - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid resolution unit format '{}'. Expected 'y', 'M', 'd', 'h', 'm', " "or 's'", unit )); @@ -487,11 +486,14 @@ bool TimeQuantizer::quantize(Time& t, bool clamp) { std::memset(unquantizedString, 0, BufferSize); SpiceManager::ref().dateFromEphemerisTime( t.j2000Seconds(), - unquantizedString, BufferSize, + unquantizedString, + BufferSize, Format ); - DateTime unquantized(std::string_view(unquantizedString, BufferSize)); + const DateTime unquantized = DateTime( + std::string_view(unquantizedString, BufferSize) + ); // resolutionFraction helps to improve iteration performance constexpr double ResolutionFraction = 0.7; constexpr int IterationLimit = 50; @@ -521,7 +523,7 @@ bool TimeQuantizer::quantize(Time& t, bool clamp) { ); } error = unquantized.J2000() - quantized.J2000(); - bool hasSettled = (lastIncr == 1 && lastDecr == 1 && error >= 0.0); + const bool hasSettled = (lastIncr == 1 && lastDecr == 1 && error >= 0.0); iterations++; if (hasSettled || iterations > IterationLimit) { break; @@ -529,7 +531,7 @@ bool TimeQuantizer::quantize(Time& t, bool clamp) { } char Buffer[20]; std::memset(Buffer, 0, 20); - fmt::format_to( + std::format_to( Buffer, "{:0>4}-{:0>2}-{:0>2}T{:0>2}:{:0>2}:{:0>2}", quantized.year(), quantized.month(), quantized.day(), @@ -548,8 +550,8 @@ bool TimeQuantizer::quantize(Time& t, bool clamp) { } } -void TimeQuantizer::doFirstApproximation(DateTime& quantized, DateTime& unQ, double value, - char unit) +void TimeQuantizer::doFirstApproximation(DateTime& quantized, const DateTime& unQ, + double value, char unit) { ZoneScoped; @@ -567,10 +569,8 @@ void TimeQuantizer::doFirstApproximation(DateTime& quantized, DateTime& unQ, dou } case 'M': { - bool isSimMonthPastQuantizedMonth = unQ.month() > static_cast(value); - quantized.setYear( - (isSimMonthPastQuantizedMonth) ? unQ.year() : unQ.year() - 1 - ); + const bool isMonthPastQuantizedMonth = unQ.month() > static_cast(value); + quantized.setYear(isMonthPastQuantizedMonth ? unQ.year() : unQ.year() - 1); break; } case 'd': @@ -580,7 +580,7 @@ void TimeQuantizer::doFirstApproximation(DateTime& quantized, DateTime& unQ, dou const int originalMinute = quantized.minute(); const int originalSecond = quantized.second(); const double addToTime = std::round(error) * 86400; - Time testDay(quantized.J2000() + addToTime); + const Time testDay = Time(quantized.J2000() + addToTime); char Buffer[25]; testDay.ISO8601(Buffer); @@ -615,17 +615,17 @@ void TimeQuantizer::doFirstApproximation(DateTime& quantized, DateTime& unQ, dou } break; default: - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Invalid unit '{}'. Expected 'y', 'M', 'd', 'h', or 'm'", unit )); } } std::vector TimeQuantizer::quantized(Time& start, Time& end) { - DateTime s(start.ISO8601()); + const DateTime s = DateTime(start.ISO8601()); quantize(start, true); - DateTime e(end.ISO8601()); + const DateTime e = DateTime(end.ISO8601()); quantize(end, true); const double startSeconds = s.J2000(); @@ -637,7 +637,10 @@ std::vector TimeQuantizer::quantized(Time& start, Time& end) { std::vector result; DateTime itr = s; - RangedTime range(std::string(start.ISO8601()), std::string(end.ISO8601())); + const RangedTime range = RangedTime( + std::string(start.ISO8601()), + std::string(end.ISO8601()) + ); while (range.includes(Time(itr.ISO8601()))) { itr.incrementOnce(static_cast(_resolutionValue), _resolutionUnit); result.push_back(itr.ISO8601()); diff --git a/modules/globebrowsing/src/timequantizer.h b/modules/globebrowsing/src/timequantizer.h index d8d7143b92..df12aaa01b 100644 --- a/modules/globebrowsing/src/timequantizer.h +++ b/modules/globebrowsing/src/timequantizer.h @@ -94,9 +94,9 @@ public: /** * Set the end date/time of the time range. * - * \param start The ISO8601 date/time string that defines the end of the range + * \param end The ISO8601 date/time string that defines the end of the range */ - void setEnd(const std::string start); + void setEnd(const std::string end); private: std::string _start; @@ -362,7 +362,7 @@ public: private: void verifyStartTimeRestrictions(); void verifyResolutionRestrictions(const int value, const char unit); - void doFirstApproximation(DateTime& q, DateTime& unQ, double value, char unit); + void doFirstApproximation(DateTime& q, const DateTime& unQ, double value, char unit); double computeSecondsFromResolution(const int valueIn, const char unit); double _resolution = 0.0; double _resolutionValue = 0.0; diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index cfcb97199d..2521998b77 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -136,7 +136,7 @@ ImGUIModule::ImGUIModule() return; } - WindowDelegate& delegate = *global::windowDelegate; + const WindowDelegate& delegate = *global::windowDelegate; const bool showGui = delegate.hasGuiWindow() ? delegate.isGuiWindow() : true; if (delegate.isMaster() && showGui) { const glm::ivec2 windowSize = delegate.currentSubwindowSize(); @@ -281,7 +281,7 @@ void ImGUIModule::internalDeinitialize() { void ImGUIModule::internalInitializeGL() { std::filesystem::path file = FileSys.cacheManager()->cachedFilename("imgui.ini", ""); - LDEBUG(fmt::format("Using {} as ImGUI cache location", file)); + LDEBUG(std::format("Using '{}' as ImGUI cache location", file)); _iniFileBuffer.resize(file.string().size() + 1); @@ -291,10 +291,10 @@ void ImGUIModule::internalInitializeGL() { strcpy(_iniFileBuffer.data(), file.c_str()); #endif - int nWindows = global::windowDelegate->nWindows(); + const int nWindows = global::windowDelegate->nWindows(); _contexts.resize(nWindows); - for (int i = 0; i < nWindows; ++i) { + for (int i = 0; i < nWindows; i++) { _contexts[i] = ImGui::CreateContext(); ImGui::SetCurrentContext(_contexts[i]); @@ -393,9 +393,9 @@ void ImGUIModule::internalInitializeGL() { ghoul::opengl::updateUniformLocations(*_program, _uniformCache, UniformNames); { - unsigned char* texData; + unsigned char* texData = nullptr; glm::ivec2 texSize = glm::ivec2(0, 0); - for (int i = 0; i < nWindows; ++i) { + for (int i = 0; i < nWindows; i++) { ImGui::SetCurrentContext(_contexts[i]); ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&texData, &texSize.x, &texSize.y); @@ -409,8 +409,8 @@ void ImGUIModule::internalInitializeGL() { _fontTexture->setDataOwnership(ghoul::opengl::Texture::TakeOwnership::No); _fontTexture->uploadTexture(); } - for (int i = 0; i < nWindows; ++i) { - uintptr_t texture = static_cast(*_fontTexture); + for (int i = 0; i < nWindows; i++) { + const uintptr_t texture = static_cast(*_fontTexture); ImGui::SetCurrentContext(_contexts[i]); ImGui::GetIO().Fonts->TexID = reinterpret_cast(texture); } @@ -425,9 +425,9 @@ void ImGUIModule::internalInitializeGL() { glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); - GLuint positionAttrib = _program->attributeLocation("in_position"); - GLuint uvAttrib = _program->attributeLocation("in_uv"); - GLuint colorAttrib = _program->attributeLocation("in_color"); + const GLuint positionAttrib = _program->attributeLocation("in_position"); + const GLuint uvAttrib = _program->attributeLocation("in_uv"); + const GLuint colorAttrib = _program->attributeLocation("in_color"); glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( @@ -549,10 +549,10 @@ void ImGUIModule::renderFrame(float deltaTime, const glm::vec2& windowSize, // Avoid rendering when minimized, scale coordinates for retina displays // (screen coordinates != framebuffer coordinates) - GLsizei fbWidth = static_cast( + const GLsizei fbWidth = static_cast( io.DisplaySize.x * io.DisplayFramebufferScale.x ); - GLsizei fbHeight = static_cast( + const GLsizei fbHeight = static_cast( io.DisplaySize.y * io.DisplayFramebufferScale.y ); if (fbWidth == 0 || fbHeight == 0) { @@ -590,7 +590,7 @@ void ImGUIModule::renderFrame(float deltaTime, const glm::vec2& windowSize, glBindVertexArray(vao); - for (int i = 0; i < drawData->CmdListsCount; ++i) { + for (int i = 0; i < drawData->CmdListsCount; i++) { const ImDrawList* cmdList = drawData->CmdLists[i]; const ImDrawIdx* indexBufferOffset = nullptr; @@ -645,14 +645,14 @@ void ImGUIModule::renderFrame(float deltaTime, const glm::vec2& windowSize, } bool ImGUIModule::mouseButtonCallback(MouseButton, MouseAction) { - ImGuiIO& io = ImGui::GetIO(); - bool consumeEvent = io.WantCaptureMouse; + const ImGuiIO& io = ImGui::GetIO(); + const bool consumeEvent = io.WantCaptureMouse; return consumeEvent; } bool ImGUIModule::mouseWheelCallback(double position) { ImGuiIO& io = ImGui::GetIO(); - bool consumeEvent = io.WantCaptureMouse; + const bool consumeEvent = io.WantCaptureMouse; if (consumeEvent) { io.MouseWheel = static_cast(position); } @@ -701,7 +701,7 @@ bool ImGUIModule::keyCallback(Key key, KeyModifier modifier, KeyAction action) { bool ImGUIModule::charCallback(unsigned int character, KeyModifier) { ImGuiIO& io = ImGui::GetIO(); - bool consumeEvent = io.WantCaptureKeyboard; + const bool consumeEvent = io.WantCaptureKeyboard; if (consumeEvent) { io.AddInputCharacter(static_cast(character)); } @@ -740,7 +740,7 @@ bool ImGUIModule::touchUpdatedCallback(TouchInput input) { ); if (it == _validTouchStates.cbegin()) { - glm::vec2 windowPos = input.currentWindowCoordinates(); + const glm::vec2 windowPos = input.currentWindowCoordinates(); io.MousePos = ImVec2(windowPos.x, windowPos.y); io.MouseClicked[0] = true; return true; @@ -772,7 +772,7 @@ void ImGUIModule::touchExitCallback(TouchInput input) { ImGuiIO& io = ImGui::GetIO(); _validTouchStates.erase(found); if (_validTouchStates.empty()) { - glm::vec2 windowPos = input.currentWindowCoordinates(); + const glm::vec2 windowPos = input.currentWindowCoordinates(); io.MousePos = ImVec2(windowPos.x, windowPos.y); io.MouseClicked[0] = false; } diff --git a/modules/imgui/include/guiparallelcomponent.h b/modules/imgui/include/guiparallelcomponent.h index 04169c1b8b..46669f0ff2 100644 --- a/modules/imgui/include/guiparallelcomponent.h +++ b/modules/imgui/include/guiparallelcomponent.h @@ -40,7 +40,6 @@ private: void renderClientWithHost(); void renderClientWithoutHost(); void renderClientCommon(); - void renderHost(); }; } // namespace openspace::gui diff --git a/modules/imgui/src/guigibscomponent.cpp b/modules/imgui/src/guigibscomponent.cpp index 0ebde94979..22ff4ea0d0 100644 --- a/modules/imgui/src/guigibscomponent.cpp +++ b/modules/imgui/src/guigibscomponent.cpp @@ -114,7 +114,7 @@ void GuiGIBSComponent::render() { std::string imageFormat = std::string(ImageFormatBuffer.data()); // Construct the components of the Lua function - std::string xmlFunc = fmt::format( + std::string xmlFunc = std::format( "openspace.globebrowsing.createTemporalGibsGdalXml('{}', '{}', '{}')", layer, imageRes, imageFormat ); @@ -122,7 +122,7 @@ void GuiGIBSComponent::render() { if (startDate == "Present") { startDate.clear(); } - std::string layerScript = fmt::format( + std::string layerScript = std::format( "{{" " Identifier = '{}'," " Type = 'TemporalTileLayer'," @@ -141,12 +141,12 @@ void GuiGIBSComponent::render() { layer, startDate, endDate, temporalRes, temporalFormat, xmlFunc ); - std::string script = fmt::format( + std::string script = std::format( "openspace.globebrowsing.addLayer('Earth', 'ColorLayers', {})", layerScript ); global::scriptEngine->queueScript( - script, + std::move(script), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); diff --git a/modules/imgui/src/guiglobebrowsingcomponent.cpp b/modules/imgui/src/guiglobebrowsingcomponent.cpp index b8e712ef8f..be43f8f425 100644 --- a/modules/imgui/src/guiglobebrowsingcomponent.cpp +++ b/modules/imgui/src/guiglobebrowsingcomponent.cpp @@ -151,7 +151,7 @@ void GuiGlobeBrowsingComponent::render() { bool isNodeChanged = ImGui::Combo("Globe", &iNode, nodeNames.c_str()); ImGui::SameLine(); - bool selectFocusNode = ImGui::Button("From Focus"); + const bool selectFocusNode = ImGui::Button("From Focus"); if (selectFocusNode) { const SceneGraphNode* const focus = global::navigationHandler->orbitalNavigator().anchorNode(); @@ -186,7 +186,7 @@ void GuiGlobeBrowsingComponent::render() { // Render the list of servers for the planet std::vector urlInfo = module->urlInfo(_currentNode); - std::string serverList = std::accumulate( + const std::string serverList = std::accumulate( urlInfo.cbegin(), urlInfo.cend(), std::string(), @@ -226,21 +226,21 @@ void GuiGlobeBrowsingComponent::render() { if (ImGui::BeginPopup("globebrowsing_add_server")) { constexpr int InputBufferSize = 512; - static char NameInputBuffer[InputBufferSize]; - ImGui::InputText("Server Name", NameInputBuffer, InputBufferSize); + static std::array NameInputBuffer; + ImGui::InputText("Server Name", NameInputBuffer.data(), InputBufferSize); - static char UrlInputBuffer[InputBufferSize]; - ImGui::InputText("Server URL", UrlInputBuffer, InputBufferSize); + static std::array UrlInputBuffer; + ImGui::InputText("Server URL", UrlInputBuffer.data(), InputBufferSize); const bool addServer = ImGui::Button("Add Server"); if (addServer && (!_currentNode.empty())) { module->loadWMSCapabilities( - std::string(NameInputBuffer), + std::string(NameInputBuffer.data()), _currentNode, - std::string(UrlInputBuffer) + std::string(UrlInputBuffer.data()) ); - std::memset(NameInputBuffer, 0, InputBufferSize * sizeof(char)); - std::memset(UrlInputBuffer, 0, InputBufferSize * sizeof(char)); + std::memset(NameInputBuffer.data(), 0, InputBufferSize * sizeof(char)); + std::memset(UrlInputBuffer.data(), 0, InputBufferSize * sizeof(char)); urlInfo = module->urlInfo(_currentNode); _currentServer = urlInfo.back().name; @@ -267,10 +267,10 @@ void GuiGlobeBrowsingComponent::render() { ImGui::Separator(); - Capabilities cap = module->capabilities(_currentServer); + const Capabilities cap = module->capabilities(_currentServer); if (cap.empty()) { - LWARNINGC("GlobeBrowsing", fmt::format("Unknown server: '{}'", _currentServer)); + LWARNINGC("GlobeBrowsing", std::format("Unknown server '{}'", _currentServer)); } ImGui::Columns(6, nullptr, false); @@ -327,7 +327,7 @@ void GuiGlobeBrowsingComponent::render() { layerName.end() ); global::scriptEngine->queueScript( - fmt::format( + std::format( "openspace.globebrowsing.addLayer(\ '{}', \ '{}', \ diff --git a/modules/imgui/src/guijoystickcomponent.cpp b/modules/imgui/src/guijoystickcomponent.cpp index 8c2583b444..362e6b5fdc 100644 --- a/modules/imgui/src/guijoystickcomponent.cpp +++ b/modules/imgui/src/guijoystickcomponent.cpp @@ -50,7 +50,7 @@ void GuiJoystickComponent::render() { _isEnabled = v; _isCollapsed = ImGui::IsWindowCollapsed(); - for (size_t i = 0; i < global::joystickInputStates->size(); ++i) { + for (size_t i = 0; i < global::joystickInputStates->size(); i++) { const JoystickInputState& state = global::joystickInputStates->at(i); if (!state.isConnected) { continue; @@ -58,9 +58,9 @@ void GuiJoystickComponent::render() { ImGui::Text("%s [%i]", state.name.c_str(), static_cast(i)); ImGui::Text("%s", "Axes"); - for (int j = 0; j < state.nAxes; ++j) { + for (int j = 0; j < state.nAxes; j++) { float f = state.axes[j]; - std::string id = std::to_string(j) + "##" + state.name + "Axis"; + const std::string id = std::to_string(j) + "##" + state.name + "Axis"; ImGui::SliderFloat( id.c_str(), &f, @@ -69,8 +69,8 @@ void GuiJoystickComponent::render() { ); } ImGui::Text("%s", "Buttons"); - for (int j = 0; j < state.nButtons; ++j) { - std::string id = std::to_string(j) + "##" + state.name + "Button"; + for (int j = 0; j < state.nButtons; j++) { + const std::string id = std::to_string(j) + "##" + state.name + "Button"; ImGui::RadioButton( id.c_str(), state.buttons[j] == JoystickAction::Press || @@ -86,9 +86,9 @@ void GuiJoystickComponent::render() { ImGui::Text("%s", "Summed contributions"); ImGui::Text("%s", "Axes"); - for (int i = 0; i < global::joystickInputStates->numAxes(); ++i) { + for (int i = 0; i < global::joystickInputStates->numAxes(); i++) { float f = global::joystickInputStates->axis("", i); - std::string id = std::to_string(i) + "##" + "TotalAxis"; + const std::string id = std::to_string(i) + "##" + "TotalAxis"; ImGui::SliderFloat( id.c_str(), &f, @@ -97,8 +97,8 @@ void GuiJoystickComponent::render() { ); } ImGui::Text("%s", "Buttons"); - for (int i = 0; i < global::joystickInputStates->numButtons(); ++i) { - std::string id = std::to_string(i) + "##" + "TotalButton"; + for (int i = 0; i < global::joystickInputStates->numButtons(); i++) { + const std::string id = std::to_string(i) + "##" + "TotalButton"; ImGui::RadioButton( id.c_str(), global::joystickInputStates->button("", i, JoystickAction::Press) || diff --git a/modules/imgui/src/guimemorycomponent.cpp b/modules/imgui/src/guimemorycomponent.cpp index 4a29eeae78..c1ca19ccfb 100644 --- a/modules/imgui/src/guimemorycomponent.cpp +++ b/modules/imgui/src/guimemorycomponent.cpp @@ -36,7 +36,7 @@ namespace { //ImGui::Text("Bucket Size: %i", p.BucketSize); ImGui::Text("Number of Buckets: %i", p.nBuckets()); const std::vector& occupancies = p.occupancies(); - for (size_t i = 0; i < occupancies.size(); ++i) { + for (size_t i = 0; i < occupancies.size(); i++) { ImGui::Text( " %i: %i/%i (%.2f/%.2f kiB)", static_cast(i), diff --git a/modules/imgui/src/guimissioncomponent.cpp b/modules/imgui/src/guimissioncomponent.cpp index 5f82802a42..eae88610b6 100644 --- a/modules/imgui/src/guimissioncomponent.cpp +++ b/modules/imgui/src/guimissioncomponent.cpp @@ -37,13 +37,13 @@ namespace { void renderMission(const openspace::Mission& mission) { // The hashname is necessary since ImGui computes a hash based off the name of the // elements. This does not play well with using %s as the name - std::string missionHashname = "##" + mission.name(); + const std::string missionHashname = "##" + mission.name(); const double currentTime = openspace::global::timeManager->time().j2000Seconds(); - openspace::MissionPhase::Trace t = mission.phaseTrace(currentTime, 0); + const openspace::MissionPhase::Trace t = mission.phaseTrace(currentTime, 0); - int treeOption = t.empty() ? 0 : ImGuiTreeNodeFlags_DefaultOpen; + const int treeOption = t.empty() ? 0 : ImGuiTreeNodeFlags_DefaultOpen; if (ImGui::TreeNodeEx( ("%s" + missionHashname).c_str(), treeOption, @@ -55,9 +55,9 @@ namespace { ImGui::Text("%s", mission.description().c_str()); } - openspace::TimeRange range = mission.timeRange(); - openspace::Time startTime = openspace::Time(range.start); - openspace::Time endTime = openspace::Time(range.end); + const openspace::TimeRange range = mission.timeRange(); + const openspace::Time startTime = openspace::Time(range.start); + const openspace::Time endTime = openspace::Time(range.end); openspace::CaptionText("Mission Progress"); @@ -118,4 +118,4 @@ void GuiMissionComponent::render() { ImGui::End(); } -} // namespace openspace gui +} // namespace openspace::gui diff --git a/modules/imgui/src/guiparallelcomponent.cpp b/modules/imgui/src/guiparallelcomponent.cpp index ce06096833..b7f001865d 100644 --- a/modules/imgui/src/guiparallelcomponent.cpp +++ b/modules/imgui/src/guiparallelcomponent.cpp @@ -31,12 +31,32 @@ #include #include #include - #include - #include #include +namespace { + void renderHost() { + const size_t nConnections = openspace::global::parallelPeer->nConnections(); + + std::string connectionInfo; + const size_t nClients = nConnections - 1; + if (nClients == 1) { + connectionInfo = "Hosting session with 1 client"; + } + else { + connectionInfo = std::format("Hosting session with {} clients", nClients); + } + + ImGui::Text("%s", connectionInfo.c_str()); + + const bool resignHostship = ImGui::Button("Resign hostship"); + if (resignHostship) { + openspace::global::parallelPeer->resignHostship(); + } + } +} // namespace + namespace openspace::gui { GuiParallelComponent::GuiParallelComponent() @@ -70,12 +90,14 @@ void GuiParallelComponent::renderClientWithHost() { const size_t nClients = nConnections - 1; if (nClients > 2) { - std::string c = std::to_string(nClients - 1); - connectionInfo += "You and " + c + " more clients are connected"; + connectionInfo += std::format( + "You and {} more clients are connected", nClients - 1 + ); } else if (nClients == 2) { - std::string c = std::to_string(nClients - 1); - connectionInfo += "You and " + c + " more client are connected"; + connectionInfo += std::format( + "You and {} more client are connected", nClients - 1 + ); } else if (nClients == 1) { connectionInfo += "You are the only client"; @@ -88,11 +110,15 @@ void GuiParallelComponent::renderClientWithHost() { const size_t nCameraKeyframes = global::navigationHandler->keyframeNavigator().nKeyframes(); - std::string timeKeyframeInfo = "TimeKeyframes : " + std::to_string(nTimeKeyframes); - std::string cameraKeyframeInfo = "CameraKeyframes : " + - std::to_string(nCameraKeyframes); - std::string latencyStandardDeviation = "Latency standard deviation: " + - std::to_string(parallel.latencyStandardDeviation()) + " s"; + const std::string timeKeyframeInfo = std::format( + "TimeKeyframes: {}", nTimeKeyframes + ); + const std::string cameraKeyframeInfo = std::format( + "CameraKeyframes: {}", nCameraKeyframes + ); + const std::string latencyStandardDeviation = std::format( + "Latency standard deviation: {} s", parallel.latencyStandardDeviation() + ); const bool resetTimeOffset = ImGui::Button("Reset time offset"); @@ -110,12 +136,14 @@ void GuiParallelComponent::renderClientWithoutHost() { const size_t nConnections = global::parallelPeer->nConnections(); if (nConnections > 2) { - std::string c = std::to_string(nConnections - 1); - connectionInfo += "You and " + c + " more users are connected"; + connectionInfo += std::format( + "You and {} more users are connected", nConnections - 1 + ); } else if (nConnections == 2) { - std::string c = std::to_string(nConnections - 1); - connectionInfo += "You and " + c + " more users are connected"; + connectionInfo += std::format( + "You and {} more users are connected", nConnections - 1 + ); } else if (nConnections == 1) { connectionInfo += "You are the only one here"; @@ -138,26 +166,6 @@ void GuiParallelComponent::renderClientCommon() { } } -void GuiParallelComponent::renderHost() { - const size_t nConnections = global::parallelPeer->nConnections(); - - std::string connectionInfo; - const size_t nClients = nConnections - 1; - if (nClients == 1) { - connectionInfo = "Hosting session with 1 client"; - } - else { - connectionInfo = "Hosting session with " + std::to_string(nClients) + " clients"; - } - - ImGui::Text("%s", connectionInfo.c_str()); - - const bool resignHostship = ImGui::Button("Resign hostship"); - if (resignHostship) { - global::parallelPeer->resignHostship(); - } -} - void GuiParallelComponent::render() { ImGui::SetNextWindowCollapsed(_isCollapsed); bool v = _isEnabled; @@ -165,7 +173,7 @@ void GuiParallelComponent::render() { _isEnabled = v; _isCollapsed = ImGui::IsWindowCollapsed(); - ParallelConnection::Status status = global::parallelPeer->status(); + const ParallelConnection::Status status = global::parallelPeer->status(); switch (status) { case ParallelConnection::Status::Disconnected: diff --git a/modules/imgui/src/guipropertycomponent.cpp b/modules/imgui/src/guipropertycomponent.cpp index 016271781f..6725f15668 100644 --- a/modules/imgui/src/guipropertycomponent.cpp +++ b/modules/imgui/src/guipropertycomponent.cpp @@ -59,14 +59,15 @@ namespace { int nVisibleProperties(const std::vector& props) { - using Visibility = openspace::properties::Property::Visibility; - Visibility visibilityFilter = openspace::global::openSpaceEngine->visibility(); + using namespace openspace; + using Visibility = properties::Property::Visibility; + const Visibility visibilityFilter = global::openSpaceEngine->visibility(); return static_cast(std::count_if( props.begin(), props.end(), - [visibilityFilter](openspace::properties::Property* p) { - using V = openspace::properties::Property::Visibility; + [visibilityFilter](properties::Property* p) { + using V = properties::Property::Visibility; return static_cast>(visibilityFilter) >= static_cast>(p->visibility()); } @@ -124,7 +125,7 @@ namespace { } ); - TreeNode* n; + TreeNode* n = nullptr; if (it != node.children.end()) { // We have a child, so we use it n = it->get(); @@ -216,7 +217,7 @@ void GuiPropertyComponent::renderPropertyOwner(properties::PropertyOwner* owner) const std::vector& subOwners = owner->propertySubOwners(); for (PropertyOwner* subOwner : subOwners) { const std::vector& properties = subOwner->propertiesRecursive(); - int count = nVisibleProperties(properties); + const int count = nVisibleProperties(properties); if (count == 0) { continue; } @@ -280,7 +281,6 @@ void GuiPropertyComponent::render() { ImGui::SetNextWindowBgAlpha(0.75f); ImGui::Begin(guiName().c_str(), &v); _isEnabled = v; - bool showHiddenNode = openspace::global::openSpaceEngine->showHiddenSceneGraphNodes(); _isCollapsed = ImGui::IsWindowCollapsed(); using namespace properties; @@ -313,25 +313,25 @@ void GuiPropertyComponent::render() { owners.begin(), owners.end(), [&ordering](PropertyOwner* lhs, PropertyOwner* rhs) { - std::string lhsGroup = dynamic_cast(lhs)->guiPath(); - std::string rhsGroup = dynamic_cast(rhs)->guiPath(); + const std::string lhsGrp = dynamic_cast(lhs)->guiPath(); + const std::string rhsGrp = dynamic_cast(rhs)->guiPath(); - if (lhsGroup.empty()) { + if (lhsGrp.empty()) { return false; } - if (rhsGroup.empty()) { + if (rhsGrp.empty()) { return true; } if (ordering.empty()) { - return lhsGroup < rhsGroup; + return lhsGrp < rhsGrp; } - std::vector lhsToken = ghoul::tokenizeString(lhsGroup, '/'); + std::vector lhsToken = ghoul::tokenizeString(lhsGrp, '/'); // The first token is always empty auto lhsIt = std::find(ordering.begin(), ordering.end(), lhsToken[1]); - std::vector rhsToken = ghoul::tokenizeString(rhsGroup, '/'); + std::vector rhsToken = ghoul::tokenizeString(rhsGrp, '/'); // The first token is always empty auto rhsIt = std::find(ordering.begin(), ordering.end(), rhsToken[1]); @@ -342,7 +342,7 @@ void GuiPropertyComponent::render() { return lhsIt < rhsIt; } else { - return lhsGroup < rhsGroup; + return lhsGrp < rhsGrp; } } else if (lhsIt != ordering.end() && rhsIt == ordering.end()) { @@ -353,7 +353,7 @@ void GuiPropertyComponent::render() { return false; } else { - return lhsGroup < rhsGroup; + return lhsGrp < rhsGrp; } } ); @@ -397,20 +397,6 @@ void GuiPropertyComponent::render() { }; if (!_useTreeLayout || noGuiGroups) { - if (!showHiddenNode) { - // Remove all of the nodes that we want hidden first - owners.erase( - std::remove_if( - owners.begin(), - owners.end(), - [](properties::PropertyOwner* p) { - SceneGraphNode* s = dynamic_cast(p); - return s && s->hasGuiHintHidden(); - } - ), - owners.end() - ); - } std::for_each(owners.begin(), owners.end(), renderProp); } else { // _useTreeLayout && gui groups exist @@ -419,15 +405,13 @@ void GuiPropertyComponent::render() { for (properties::PropertyOwner* pOwner : owners) { // We checked above that pOwner is a SceneGraphNode SceneGraphNode* nOwner = static_cast(pOwner); - if (!showHiddenNode && nOwner->hasGuiHintHidden()) { - continue; - } const std::string gui = nOwner->guiPath(); if (gui.empty()) { // We know that we are done now since we stable_sort:ed them above break; } - std::vector paths = ghoul::tokenizeString(gui.substr(1), '/'); + const std::vector paths = + ghoul::tokenizeString(gui.substr(1), '/'); addPathToTree(root, paths, nOwner); } @@ -487,7 +471,7 @@ void GuiPropertyComponent::renderProperty(properties::Property* prop, // Check if the visibility of the property is high enough to be displayed using V = properties::Property::Visibility; using Visibility = openspace::properties::Property::Visibility; - Visibility visibilityFilter = openspace::global::openSpaceEngine->visibility(); + const Visibility visibilityFilter = openspace::global::openSpaceEngine->visibility(); const auto v = static_cast>(visibilityFilter); const auto propV = static_cast>(prop->visibility()); if (v >= propV) { diff --git a/modules/imgui/src/guiscenecomponent.cpp b/modules/imgui/src/guiscenecomponent.cpp index 6f5e089d89..57817bb47b 100644 --- a/modules/imgui/src/guiscenecomponent.cpp +++ b/modules/imgui/src/guiscenecomponent.cpp @@ -44,7 +44,7 @@ namespace { using namespace openspace; if (ImGui::TreeNode(node.identifier().c_str())) { - std::vector children = node.children(); + const std::vector children = node.children(); for (SceneGraphNode* c : children) { renderSceneGraphNode(*c, time); } @@ -67,8 +67,8 @@ namespace { bool isReady = renderable->isReady(); ImGui::Checkbox("Is Ready", &isReady); - Renderable::RenderBin bin = renderable->renderBin(); - std::string binStr = [](Renderable::RenderBin b) { + const Renderable::RenderBin bin = renderable->renderBin(); + const std::string binStr = [](Renderable::RenderBin b) { switch (b) { case Renderable::RenderBin::Background: return "Background"; diff --git a/modules/imgui/src/guispacetimecomponent.cpp b/modules/imgui/src/guispacetimecomponent.cpp index 37fd88a89d..a851c9a1e6 100644 --- a/modules/imgui/src/guispacetimecomponent.cpp +++ b/modules/imgui/src/guispacetimecomponent.cpp @@ -201,7 +201,7 @@ void GuiSpaceTimeComponent::render() { constexpr int BufferSize = 256; static char Buffer[BufferSize]; - bool dateChanged = ImGui::InputText( + const bool dateChanged = ImGui::InputText( "Change Date", Buffer, BufferSize, @@ -211,7 +211,7 @@ void GuiSpaceTimeComponent::render() { // No sync or send because time settings are always synced and sent to the // connected nodes and peers global::scriptEngine->queueScript( - "openspace.time.setTime(\"" + std::string(Buffer) + "\")", + std::format("openspace.time.setTime([[{}]])", std::string_view(Buffer)), scripting::ScriptEngine::ShouldBeSynchronized::No, scripting::ScriptEngine::ShouldSendToRemote::No ); @@ -345,7 +345,7 @@ void GuiSpaceTimeComponent::render() { openspace::TimeUnits.end(), std::string(""), [](const std::string& a, const openspace::TimeUnit& unit) { - return fmt::format( + return std::format( "{}{} / second", a, nameForTimeUnit(unit, true) ) + '\0'; } @@ -357,7 +357,7 @@ void GuiSpaceTimeComponent::render() { convertTime(dt, TimeUnit::Second, _deltaTimeUnit) ); - bool valueChanged = ImGui::InputFloat( + const bool valueChanged = ImGui::InputFloat( "##inputValueDeltaTime", &_deltaTime, 1.f, @@ -368,7 +368,7 @@ void GuiSpaceTimeComponent::render() { ImGui::SameLine(); int deltaTimeUnit = static_cast(_deltaTimeUnit); - bool unitChanged = ImGui::Combo( + const bool unitChanged = ImGui::Combo( "##inputUnit", &deltaTimeUnit, _timeUnits.c_str() @@ -377,8 +377,11 @@ void GuiSpaceTimeComponent::render() { if (valueChanged) { // If the value changed, we want to change the delta time to the new value - - double newDt = convertTime(_deltaTime, _deltaTimeUnit, TimeUnit::Second); + const double newDt = convertTime( + _deltaTime, + _deltaTimeUnit, + TimeUnit::Second + ); // No sync or send because time settings are always synced and sent // to the connected nodes and peers @@ -454,7 +457,7 @@ void GuiSpaceTimeComponent::render() { } } else { - bool accelerationDeltaChanged = ImGui::SliderFloat( + const bool accelerationDeltaChanged = ImGui::SliderFloat( "Delta Time Slider", &_accelerationDelta, -100.f, @@ -624,4 +627,4 @@ void GuiSpaceTimeComponent::render() { ImGui::End(); } -} // namespace openspace gui +} // namespace openspace::gui diff --git a/modules/imgui/src/renderproperties.cpp b/modules/imgui/src/renderproperties.cpp index 6c22585302..4e1b285951 100644 --- a/modules/imgui/src/renderproperties.cpp +++ b/modules/imgui/src/renderproperties.cpp @@ -73,7 +73,7 @@ void renderTooltip(Property* prop, double delay) { void executeSetPropertyScript(const std::string& id, const std::string& value) { global::scriptEngine->queueScript( - fmt::format("openspace.setPropertyValueSingle('{}', {});", id, value), + std::format("openspace.setPropertyValueSingle('{}', {});", id, value), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -175,11 +175,10 @@ void renderSelectionProperty(Property* prop, const std::string& ownerName, bool selectionChanged = false; std::set newSelected; - std::set selected = p->value(); + const std::set selected = p->value(); const std::vector& options = p->options(); - for (int i = 0; i < static_cast(options.size()); ++i) { - const std::string key = options[i]; + for (const std::string& key : options) { bool isSelected = p->isSelected(key); selectionChanged |= ImGui::Checkbox(key.c_str(), &isSelected); @@ -195,7 +194,7 @@ void renderSelectionProperty(Property* prop, const std::string& ownerName, if (selectionChanged) { std::string parameters = "{"; for (const std::string& s : newSelected) { - parameters += fmt::format("'{}',", s); + parameters += std::format("'{}',", s); } if (!newSelected.empty()) { parameters.pop_back(); @@ -218,14 +217,14 @@ void renderStringProperty(Property* prop, const std::string& ownerName, const std::string value = p->value(); - static constexpr int bufferSize = 256; - static char buffer[bufferSize]; + static constexpr int BufferSize = 256; + static std::array buffer; #ifdef _MSC_VER - strcpy_s(buffer, value.length() + 1, value.c_str()); + strcpy_s(buffer.data(), value.length() + 1, value.c_str()); #else - strcpy(buffer, value.c_str()); + strcpy(buffer.data(), value.c_str()); #endif - bool hasNewValue = ImGui::InputText(name.c_str(), buffer, bufferSize); + const bool hasNewValue = ImGui::InputText(name.c_str(), buffer.data(), BufferSize); if (showTooltip) { renderTooltip(prop, tooltipDelay); } @@ -233,7 +232,7 @@ void renderStringProperty(Property* prop, const std::string& ownerName, if (hasNewValue) { executeSetPropertyScript( p->fullyQualifiedIdentifier(), - "[[" + std::string(buffer) + "]]" + "[[" + std::string(buffer.data()) + "]]" ); } @@ -249,19 +248,19 @@ void renderListProperty(const std::string& name, const std::string& fullIdentifi ); // Remove brackets from the string value - std::string value = stringValue.substr(1, stringValue.size() - 2); + const std::string value = stringValue.substr(1, stringValue.size() - 2); - static const int bufferSize = 512; - static char buffer[bufferSize]; + static constexpr int BufferSize = 512; + static std::array buffer; #ifdef _MSC_VER - strcpy_s(buffer, value.length() + 1, value.c_str()); + strcpy_s(buffer.data(), value.length() + 1, value.c_str()); #else - strcpy(buffer, value.c_str()); + strcpy(buffer.data(), value.c_str()); #endif - bool hasNewValue = ImGui::InputText(name.c_str(), buffer, bufferSize); + const bool hasNewValue = ImGui::InputText(name.c_str(), buffer.data(), BufferSize); if (hasNewValue) { - std::vector tokens = ghoul::tokenizeString(std::string(buffer), ','); + std::vector tokens = ghoul::tokenizeString(buffer.data(), ','); std::string script = "{"; for (std::string& token : tokens) { if (!token.empty()) { @@ -271,7 +270,7 @@ void renderListProperty(const std::string& name, const std::string& fullIdentifi } script += '}'; - executeSetPropertyScript(fullIdentifier, std::move(script)); + executeSetPropertyScript(fullIdentifier, script); } } @@ -283,7 +282,7 @@ void renderDoubleListProperty(Property* prop, const std::string& ownerName, const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); - std::string value = p->stringValue(); + const std::string value = p->stringValue(); renderListProperty(name, p->fullyQualifiedIdentifier(), value); if (showTooltip) { @@ -301,7 +300,7 @@ void renderIntListProperty(Property* prop, const std::string& ownerName, const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); - std::string value = p->stringValue(); + const std::string value = p->stringValue(); renderListProperty(name, p->fullyQualifiedIdentifier(), value); if (showTooltip) { @@ -319,7 +318,7 @@ void renderStringListProperty(Property* prop, const std::string& ownerName, const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); - std::string value = p->stringValue(); + const std::string value = p->stringValue(); renderListProperty(name, p->fullyQualifiedIdentifier(), value); if (showTooltip) { @@ -334,7 +333,7 @@ void renderDoubleProperty(properties::Property* prop, const std::string& ownerNa { ghoul_assert(prop, "prop must not be nullptr"); DoubleProperty* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); float value = static_cast(*p); @@ -346,7 +345,7 @@ void renderDoubleProperty(properties::Property* prop, const std::string& ownerNa min = std::max(min, std::numeric_limits::min() / 2.f); max = std::min(max, std::numeric_limits::max() / 2.f); - bool changed = ImGui::SliderFloat( + const bool changed = ImGui::SliderFloat( name.c_str(), &value, min, @@ -370,14 +369,14 @@ void renderIntProperty(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); IntProperty* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); IntProperty::ValueType value = *p; - int min = p->minValue(); - int max = p->maxValue(); + const int min = p->minValue(); + const int max = p->maxValue(); - bool changed = ImGui::SliderInt(name.c_str(), &value, min, max); + const bool changed = ImGui::SliderInt(name.c_str(), &value, min, max); if (showTooltip) { renderTooltip(prop, tooltipDelay); } @@ -394,13 +393,13 @@ void renderIVec2Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); IVec2Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); IVec2Property::ValueType value = *p; - int min = glm::compMin(p->minValue()); - int max = glm::compMax(p->maxValue()); - bool changed = ImGui::SliderInt2(name.c_str(), &value.x, min, max); + const int min = glm::compMin(p->minValue()); + const int max = glm::compMax(p->maxValue()); + const bool changed = ImGui::SliderInt2(name.c_str(), &value.x, min, max); if (showTooltip) { renderTooltip(prop, tooltipDelay); } @@ -417,14 +416,13 @@ void renderIVec3Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); IVec3Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); IVec3Property::ValueType value = *p; - int min = glm::compMin(p->minValue()); - int max = glm::compMax(p->maxValue()); - - bool changed = ImGui::SliderInt3(name.c_str(), &value.x, min, max); + const int min = glm::compMin(p->minValue()); + const int max = glm::compMax(p->maxValue()); + const bool changed = ImGui::SliderInt3(name.c_str(), &value.x, min, max); if (showTooltip) { renderTooltip(prop, tooltipDelay); } @@ -440,14 +438,13 @@ void renderIVec4Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); IVec4Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); IVec4Property::ValueType value = *p; - int min = glm::compMin(p->minValue()); - int max = glm::compMax(p->maxValue()); - - bool changed = ImGui::SliderInt4(name.c_str(), &value.x, min, max); + const int min = glm::compMin(p->minValue()); + const int max = glm::compMax(p->maxValue()); + const bool changed = ImGui::SliderInt4(name.c_str(), &value.x, min, max); if (showTooltip) { renderTooltip(prop, tooltipDelay); } @@ -463,13 +460,13 @@ void renderFloatProperty(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); FloatProperty* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); FloatProperty::ValueType value = *p; - float min = p->minValue(); - float max = p->maxValue(); - bool changed = ImGui::SliderFloat( + const float min = p->minValue(); + const float max = p->maxValue(); + const bool changed = ImGui::SliderFloat( name.c_str(), &value, min, @@ -493,14 +490,13 @@ void renderVec2Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); Vec2Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); Vec2Property::ValueType value = *p; - float min = glm::compMin(p->minValue()); - float max = glm::compMax(p->maxValue()); - - bool changed = ImGui::SliderFloat2( + const float min = glm::compMin(p->minValue()); + const float max = glm::compMax(p->maxValue()); + const bool changed = ImGui::SliderFloat2( name.c_str(), &value.x, min, @@ -524,13 +520,12 @@ void renderVec3Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); Vec3Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); Vec3Property::ValueType value = *p; - float min = glm::compMin(p->minValue()); - float max = glm::compMax(p->maxValue()); - + const float min = glm::compMin(p->minValue()); + const float max = glm::compMax(p->maxValue()); bool changed = false; if (prop->viewOption(Property::ViewOptions::Color)) { changed = ImGui::ColorEdit3(name.c_str(), glm::value_ptr(value)); @@ -561,13 +556,12 @@ void renderVec4Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); Vec4Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); Vec4Property::ValueType value = *p; - float min = glm::compMin(p->minValue()); - float max = glm::compMax(p->maxValue()); - + const float min = glm::compMin(p->minValue()); + const float max = glm::compMax(p->maxValue()); bool changed = false; if (prop->viewOption(Property::ViewOptions::Color)) { changed = ImGui::ColorEdit4(name.c_str(), glm::value_ptr(value)); @@ -598,13 +592,13 @@ void renderDVec2Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); DVec2Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); glm::vec2 value = glm::dvec2(*p); - float min = static_cast(glm::compMin(p->minValue())); - float max = static_cast(glm::compMax(p->maxValue())); - bool changed = ImGui::SliderFloat2( + const float min = static_cast(glm::compMin(p->minValue())); + const float max = static_cast(glm::compMax(p->maxValue())); + const bool changed = ImGui::SliderFloat2( name.c_str(), &value.x, min, @@ -628,14 +622,13 @@ void renderDVec3Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); DVec3Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); glm::vec3 value = glm::dvec3(*p); - float min = static_cast(glm::compMin(p->minValue())); - float max = static_cast(glm::compMax(p->maxValue())); - - bool changed = ImGui::SliderFloat3( + const float min = static_cast(glm::compMin(p->minValue())); + const float max = static_cast(glm::compMax(p->maxValue())); + const bool changed = ImGui::SliderFloat3( name.c_str(), glm::value_ptr(value), min, @@ -659,14 +652,13 @@ void renderDVec4Property(Property* prop, const std::string& ownerName, { ghoul_assert(prop, "prop must not be nullptr"); DVec4Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); glm::vec4 value = glm::dvec4(*p); - float min = static_cast(glm::compMin(p->minValue())); - float max = static_cast(glm::compMax(p->maxValue())); - - bool changed = ImGui::SliderFloat4( + const float min = static_cast(glm::compMin(p->minValue())); + const float max = static_cast(glm::compMax(p->maxValue())); + const bool changed = ImGui::SliderFloat4( name.c_str(), &value.x, min, @@ -691,22 +683,22 @@ void renderDMat2Property(Property* prop, const std::string& ownerName, ghoul_assert(prop, "prop must not be nullptr"); DMat2Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); ImGui::Text("%s", name.c_str()); glm::mat2 value = glm::dmat2(*p); - glm::dvec2 minValues = glm::dvec2( + const glm::dvec2 minValues = glm::dvec2( glm::compMin(p->minValue()[0]), glm::compMin(p->minValue()[1]) ); - float min = static_cast(glm::compMin(minValues)); + const float min = static_cast(glm::compMin(minValues)); - glm::dvec2 maxValues = glm::dvec2( + const glm::dvec2 maxValues = glm::dvec2( glm::compMax(p->maxValue()[0]), glm::compMax(p->maxValue()[1]) ); - float max = static_cast(glm::compMax(maxValues)); + const float max = static_cast(glm::compMax(maxValues)); bool changed = false; changed |= ImGui::SliderFloat2( @@ -743,24 +735,24 @@ void renderDMat3Property(Property* prop, const std::string& ownerName, ghoul_assert(prop, "prop must not be nullptr"); DMat3Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); ImGui::Text("%s", name.c_str()); glm::mat3 value = glm::dmat3(*p); - glm::dvec3 minValues = glm::dvec3( + const glm::dvec3 minValues = glm::dvec3( glm::compMin(p->minValue()[0]), glm::compMin(p->minValue()[1]), glm::compMin(p->minValue()[2]) ); - float min = static_cast(glm::compMin(minValues)); + const float min = static_cast(glm::compMin(minValues)); - glm::dvec3 maxValues = glm::dvec3( + const glm::dvec3 maxValues = glm::dvec3( glm::compMax(p->maxValue()[0]), glm::compMax(p->maxValue()[1]), glm::compMax(p->maxValue()[2]) ); - float max = static_cast(glm::compMax(maxValues)); + const float max = static_cast(glm::compMax(maxValues)); bool changed = false; changed |= ImGui::SliderFloat3( @@ -805,26 +797,26 @@ void renderDMat4Property(Property* prop, const std::string& ownerName, ghoul_assert(prop, "prop must not be nullptr"); DMat4Property* p = static_cast(prop); - std::string name = p->guiName(); + const std::string& name = p->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); ImGui::Text("%s", name.c_str()); glm::mat4 value = glm::dmat4(*p); - glm::dvec4 minValues = glm::dvec4( + const glm::dvec4 minValues = glm::dvec4( glm::compMin(p->minValue()[0]), glm::compMin(p->minValue()[1]), glm::compMin(p->minValue()[2]), glm::compMin(p->minValue()[3]) ); - float min = static_cast(glm::compMin(minValues)); + const float min = static_cast(glm::compMin(minValues)); - glm::dvec4 maxValues = glm::dvec4( + const glm::dvec4 maxValues = glm::dvec4( glm::compMax(p->maxValue()[0]), glm::compMax(p->maxValue()[1]), glm::compMax(p->maxValue()[2]), glm::compMax(p->maxValue()[3]) ); - float max = static_cast(glm::compMax(maxValues)); + const float max = static_cast(glm::compMax(maxValues)); bool changed = false; changed |= ImGui::SliderFloat4( @@ -875,10 +867,10 @@ void renderTriggerProperty(Property* prop, const std::string& ownerName, ShowToolTip showTooltip, double tooltipDelay) { ghoul_assert(prop, "prop must not be nullptr"); - std::string name = prop->guiName(); + const std::string& name = prop->guiName(); ImGui::PushID((ownerName + '.' + name).c_str()); - bool pressed = ImGui::Button(name.c_str()); + const bool pressed = ImGui::Button(name.c_str()); if (pressed) { executeSetPropertyScript(prop->fullyQualifiedIdentifier(), "nil"); } diff --git a/modules/iswa/rendering/iswakameleongroup.cpp b/modules/iswa/rendering/iswakameleongroup.cpp index dab593a60d..f9af386224 100644 --- a/modules/iswa/rendering/iswakameleongroup.cpp +++ b/modules/iswa/rendering/iswakameleongroup.cpp @@ -99,12 +99,12 @@ void IswaKameleonGroup::registerProperties() { } void IswaKameleonGroup::readFieldlinePaths(const std::string& indexFile) { - LINFO(fmt::format("Reading seed points paths from file '{}'", indexFile)); + LINFO(std::format("Reading seed points paths from file '{}'", indexFile)); // Read the index file from disk std::ifstream seedFile(indexFile); if (!seedFile.good()) { - LERROR(fmt::format("Could not open seed points file '{}'", indexFile)); + LERROR(std::format("Could not open seed points file '{}'", indexFile)); } else { std::string line; @@ -118,7 +118,7 @@ void IswaKameleonGroup::readFieldlinePaths(const std::string& indexFile) { json fieldlines = json::parse(fileContent); int i = 0; - for (json::iterator it = fieldlines.begin(); it != fieldlines.end(); ++it) { + for (json::iterator it = fieldlines.begin(); it != fieldlines.end(); it++) { _fieldlines.addOption(it.key()); _fieldlineState[i] = std::make_tuple( identifier() + "/" + it.key(), diff --git a/modules/iswa/rendering/kameleonplane.cpp b/modules/iswa/rendering/kameleonplane.cpp index 2bdbf6ef6f..707aa8dd45 100644 --- a/modules/iswa/rendering/kameleonplane.cpp +++ b/modules/iswa/rendering/kameleonplane.cpp @@ -318,7 +318,7 @@ void KameleonPlane::updateFieldlineSeeds() { } void KameleonPlane::readFieldlinePaths(const std::string& indexFile) { - LINFO(fmt::format("Reading seed points paths from file '{}'", indexFile)); + LINFO(std::format("Reading seed points paths from file '{}'", indexFile)); if (_group) { dynamic_cast(_group)->setFieldlineInfo( indexFile, @@ -330,7 +330,7 @@ void KameleonPlane::readFieldlinePaths(const std::string& indexFile) { // Read the index file from disk std::ifstream seedFile(indexFile); if (!seedFile.good()) { - LERROR(fmt::format("Could not open seed points file '{}'", indexFile)); + LERROR(std::format("Could not open seed points file '{}'", indexFile)); } else { try { @@ -339,7 +339,7 @@ void KameleonPlane::readFieldlinePaths(const std::string& indexFile) { int i = 0; const std::string& fullName = identifier(); std::string partName = fullName.substr(0,fullName.find_last_of("-")); - for (json::iterator it = fieldlines.begin(); it != fieldlines.end(); ++it) { + for (json::iterator it = fieldlines.begin(); it != fieldlines.end(); it++) { _fieldlines.addOption(it.key()); _fieldlineState[i] = std::make_tuple( partName + "/" + it.key(), diff --git a/modules/iswa/rendering/texturecygnet.cpp b/modules/iswa/rendering/texturecygnet.cpp index f5a6dc28ec..280f07f9b7 100644 --- a/modules/iswa/rendering/texturecygnet.cpp +++ b/modules/iswa/rendering/texturecygnet.cpp @@ -52,8 +52,8 @@ bool TextureCygnet::updateTexture() { ); if (texture) { - LDEBUG(fmt::format( - "Loaded texture from image iswa cygnet with id: '{}'", _data.id + LDEBUG(std::format( + "Loaded texture from image iswa cygnet with id '{}'", _data.id )); texture->uploadTexture(); // Textures of planets looks much smoother with AnisotropicMipMap diff --git a/modules/iswa/util/dataprocessor.cpp b/modules/iswa/util/dataprocessor.cpp index 4a6aa92252..edda318d45 100644 --- a/modules/iswa/util/dataprocessor.cpp +++ b/modules/iswa/util/dataprocessor.cpp @@ -110,13 +110,13 @@ void DataProcessor::initializeVectors(int numOptions) { _max = std::vector(numOptions, std::numeric_limits::min()); } if (_sum.empty()) { - _sum = std::vector(numOptions, 0.0f); + _sum = std::vector(numOptions, 0.f); } if (_standardDeviation.empty()) { - _standardDeviation = std::vector(numOptions, 0.0f); + _standardDeviation = std::vector(numOptions, 0.f); } if (_numValues.empty()) { - _numValues = std::vector(numOptions, 0.0f); + _numValues = std::vector(numOptions, 0.f); } if (_histograms.empty()) { _histograms.clear(); @@ -173,7 +173,7 @@ void DataProcessor::add(const std::vector>& optionValues, { const int numOptions = static_cast(optionValues.size()); - for (int i = 0; i < numOptions; ++i) { + for (int i = 0; i < numOptions; i++) { const std::vector& values = optionValues[i]; const int numValues = static_cast(values.size()); @@ -248,7 +248,7 @@ void DataProcessor::add(const std::vector>& optionValues, numBins ); - for (int j = 0; j < numBins; ++j) { + for (int j = 0; j < numBins; j++) { float value = unnormalizeWithStandardScore( j * (histMax - histMin) + histMin, oldMean, @@ -269,7 +269,7 @@ void DataProcessor::add(const std::vector>& optionValues, _histograms[i] = std::move(newHist); } - for (int j = 0; j < numValues; ++j) { + for (int j = 0; j < numValues; j++) { _histograms[i]->add( normalizeWithStandardScore( values[j], diff --git a/modules/iswa/util/dataprocessorjson.cpp b/modules/iswa/util/dataprocessorjson.cpp index 5ca45fecb3..5e5c054c3b 100644 --- a/modules/iswa/util/dataprocessorjson.cpp +++ b/modules/iswa/util/dataprocessorjson.cpp @@ -44,7 +44,7 @@ std::vector DataProcessorJson::readMetadata(const std::string& data const json& j = json::parse(data); json variables = j["variables"]; - for (json::iterator it = variables.begin(); it != variables.end(); ++it) { + for (json::iterator it = variables.begin(); it != variables.end(); it++) { std::string option = it.key(); if (option == "ep") { const json& row = it.value(); @@ -75,7 +75,7 @@ void DataProcessorJson::addDataValues(const std::string& data, std::vector> optionValues(numOptions, std::vector()); const std::vector& options = dataOptions.options(); - for (int i = 0; i < numOptions; ++i) { + for (int i = 0; i < numOptions; i++) { const json& row = variables[options[i]]; // int rowsize = row.size(); diff --git a/modules/iswa/util/dataprocessorkameleon.cpp b/modules/iswa/util/dataprocessorkameleon.cpp index 1b17d5f354..56cab6a360 100644 --- a/modules/iswa/util/dataprocessorkameleon.cpp +++ b/modules/iswa/util/dataprocessorkameleon.cpp @@ -85,7 +85,7 @@ void DataProcessorKameleon::addDataValues(const std::string& path, const int numValues = static_cast(_dimensions.x * _dimensions.y * _dimensions.z); - for (int i = 0; i < numOptions; ++i) { + for (int i = 0; i < numOptions; i++) { //0.5 to gather interesting values for the normalization/histograms. float* values = _kw->uniformSliceValues( options[i], diff --git a/modules/iswa/util/dataprocessortext.cpp b/modules/iswa/util/dataprocessortext.cpp index 99c2ed623c..2eab2bbaa2 100644 --- a/modules/iswa/util/dataprocessortext.cpp +++ b/modules/iswa/util/dataprocessortext.cpp @@ -125,7 +125,7 @@ void DataProcessorText::addDataValues(const std::string& data, continue; } - for (int i = 0; i < numOptions; ++i) { + for (int i = 0; i < numOptions; i++) { const float value = values[i]; optionValues[i].push_back(value); diff --git a/modules/iswa/util/iswamanager.cpp b/modules/iswa/util/iswamanager.cpp index 6b3d86d121..40e60e7397 100644 --- a/modules/iswa/util/iswamanager.cpp +++ b/modules/iswa/util/iswamanager.cpp @@ -276,7 +276,7 @@ std::string IswaManager::iswaUrl(int id, double timestamp, const std::string& ty std::getline(ss, token, ' '); url += token + "-"; std::getline(ss, token, ' '); - url = fmt::format("{}{}-", url, monthNumber(token)); + url = std::format("{}{}-", url, monthNumber(token)); std::getline(ss, token, 'T'); url += token + "%20"; std::getline(ss, token, '.'); @@ -434,7 +434,7 @@ std::string IswaManager::parseKWToLuaTable(const CdfInfo& info, const std::strin } else { spatialScale = glm::vec4(1.f); - spatialScale.w = 1; //-log10(1.0f/max.x); + spatialScale.w = 1; //-log10(1.f/max.x); coordinateType = "Polar"; } @@ -622,7 +622,7 @@ void IswaManager::createKameleonPlane(CdfInfo info, std::string cut) { } else { LWARNING( - fmt::format("{} is not a cdf file or can't be found", absPath(info.path)) + std::format("'{}' is not a CDF file or cannot be found", absPath(info.path)) ); } } @@ -630,7 +630,7 @@ void IswaManager::createKameleonPlane(CdfInfo info, std::string cut) { void IswaManager::createFieldline(std::string name, std::string cdfPath, std::string seedPath) { - std::filesystem::path ext = std::filesystem::path(absPath(cdfPath)).extension(); + std::filesystem::path ext = absPath(cdfPath).extension(); if (std::filesystem::is_regular_file(absPath(cdfPath)) && ext == ".cdf") { std::string luaTable = "{" "Name = '" + name + "'," @@ -677,7 +677,7 @@ void IswaManager::fillCygnetInfo(std::string jsonString) { for (const std::string& list : lists) { nlohmann::json jsonList = j[list]; - for (size_t i = 0; i < jsonList.size(); ++i) { + for (size_t i = 0; i < jsonList.size(); i++) { nlohmann::json jCygnet = jsonList.at(i); std::string name = jCygnet["cygnetDisplayTitle"]; @@ -709,7 +709,7 @@ void IswaManager::addCdfFiles(std::string cdfpath) { if (jsonFile.is_open()) { nlohmann::json cdfGroups = nlohmann::json::parse(jsonFile); - for(size_t i = 0; i < cdfGroups.size(); ++i) { + for(size_t i = 0; i < cdfGroups.size(); i++) { nlohmann::json cdfGroup = cdfGroups.at(i); std::string groupName = cdfGroup["group"]; @@ -744,7 +744,7 @@ void IswaManager::addCdfFiles(std::string cdfpath) { } } else { - LWARNING(fmt::format("{} is not a cdf file or can't be found", cdfFile)); + LWARNING(std::format("'{}' is not a CDF file or cannot be found", cdfFile)); } } diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index ac98898112..fa98b9966d 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -50,8 +50,8 @@ namespace { info->selected = true; if (global::renderEngine->screenSpaceRenderable(name)) { - throw ghoul::lua::LuaError(fmt::format( - "A cygnet with the name \"{}\" already exist", name + throw ghoul::lua::LuaError(std::format( + "A cygnet with the name '{}' already exist", name )); } else { @@ -91,7 +91,7 @@ namespace { std::shared_ptr info = cygnetInformation[id]; info->selected = false; - std::string script = fmt::format( + std::string script = std::format( "openspace.unregisterScreenSpaceRenderable('{}');", cygnetInformation[id]->name ); diff --git a/modules/kameleon/CMakeLists.txt b/modules/kameleon/CMakeLists.txt index 08ea00b1be..be25d7dc12 100644 --- a/modules/kameleon/CMakeLists.txt +++ b/modules/kameleon/CMakeLists.txt @@ -82,5 +82,4 @@ target_precompile_headers(ccmc PRIVATE "$<$:map>" "$<$:unordered_map>" "$<$:vector>" - "$<$:boost/unordered_map.hpp>" ) diff --git a/modules/kameleon/ext/kameleon b/modules/kameleon/ext/kameleon index ae831dc372..18aa3fdd93 160000 --- a/modules/kameleon/ext/kameleon +++ b/modules/kameleon/ext/kameleon @@ -1 +1 @@ -Subproject commit ae831dc372c3713f97658cf1ff5f50ffeb23e54f +Subproject commit 18aa3fdd932e5a4a8e6cd9725b88acaa1fdafb49 diff --git a/modules/kameleon/src/kameleonhelper.cpp b/modules/kameleon/src/kameleonhelper.cpp index c5726aecb4..8ae94553f0 100644 --- a/modules/kameleon/src/kameleonhelper.cpp +++ b/modules/kameleon/src/kameleonhelper.cpp @@ -50,17 +50,17 @@ namespace openspace::kameleonHelper { std::unique_ptr createKameleonObject(const std::string& cdfFilePath) { auto kameleon = std::make_unique(); - LDEBUG(fmt::format("\tOpening the cdf file: {}", cdfFilePath)); + LDEBUG(std::format("Opening the CDF file '{}'", cdfFilePath)); long kamStatus = kameleon->open(cdfFilePath); if (kamStatus != ccmc::FileReader::OK) { - LERROR(fmt::format( - "Failed to create a Kameleon Object from file: {}", + LERROR(std::format( + "Failed to create a Kameleon Object from file '{}'", cdfFilePath )); return nullptr; } - LDEBUG(fmt::format("\tSuccessfully opened: {}", cdfFilePath)); + LDEBUG(std::format("Successfully opened '{}'", cdfFilePath)); return kameleon; } diff --git a/modules/kameleon/src/kameleonwrapper.cpp b/modules/kameleon/src/kameleonwrapper.cpp index 56862bb19c..e78fcbcfd9 100644 --- a/modules/kameleon/src/kameleonwrapper.cpp +++ b/modules/kameleon/src/kameleonwrapper.cpp @@ -117,9 +117,9 @@ bool KameleonWrapper::open(const std::string& filename) { _zCoordVar = v[2]; _type = modelType(); - LDEBUG(fmt::format("x: {}", _xCoordVar)); - LDEBUG(fmt::format("y: {}", _yCoordVar)); - LDEBUG(fmt::format("z: {}", _zCoordVar)); + LDEBUG(std::format("x: {}", _xCoordVar)); + LDEBUG(std::format("y: {}", _yCoordVar)); + LDEBUG(std::format("z: {}", _zCoordVar)); _min = glm::vec3( _model->getVariableAttribute(_xCoordVar, "actual_min").getAttributeFloat(), @@ -172,7 +172,9 @@ float* KameleonWrapper::uniformSampledValues(const std::string& var, { ghoul_assert(_model && _interpolator, "Model and interpolator must exist"); - LINFO(fmt::format("Loading variable {} from CDF data with a uniform sampling", var)); + LINFO(std::format( + "Loading variable '{}' from CDF data with a uniform sampling", var + )); const size_t size = outDimensions.x * outDimensions.y * outDimensions.z; float* data = new float[size]; @@ -181,10 +183,10 @@ float* KameleonWrapper::uniformSampledValues(const std::string& var, const double varMin = _model->getVariableAttribute(var, "actual_min").getAttributeFloat(); - LDEBUG(fmt::format("{} Min: {}", var, varMin)); + LDEBUG(std::format("{} Min: {}", var, varMin)); const double varMax = _model->getVariableAttribute(var, "actual_max").getAttributeFloat(); - LDEBUG(fmt::format("{} Max: {}", var, varMax)); + LDEBUG(std::format("{} Max: {}", var, varMax)); // HISTOGRAM constexpr int NBins = 200; @@ -290,7 +292,7 @@ float* KameleonWrapper::uniformSampledValues(const std::string& var, int stop = 0; constexpr float TruncationLimit = 0.9f; const int upperLimit = static_cast(size * TruncationLimit); - for (int i = 0; i < NBins; ++i) { + for (int i = 0; i < NBins; i++) { sum += histogram[i]; if (sum > upperLimit) { stop = i; @@ -301,15 +303,15 @@ float* KameleonWrapper::uniformSampledValues(const std::string& var, const double dist = ((varMax - varMin) / NBins) * stop; const double varMaxNew = varMin + dist; - for(size_t i = 0; i < size; ++i) { + for(size_t i = 0; i < size; i++) { const double normalizedVal = (doubleData[i] - varMin) / (varMaxNew - varMin); data[i] = static_cast(glm::clamp(normalizedVal, 0.0, 1.0)); if (data[i] < 0.f) { - LERROR(fmt::format("Datapoint {} less than 0", i)); + LERROR(std::format("Datapoint {} less than 0", i)); } if (data[i] > 1.f) { - LERROR(fmt::format("Datapoint {} more than 1", i)); + LERROR(std::format("Datapoint {} more than 1", i)); } } @@ -322,8 +324,8 @@ float* KameleonWrapper::uniformSliceValues(const std::string& var, float slice) const { ghoul_assert(_model && _interpolator, "Model and interpolator must exist"); - LINFO(fmt::format( - "Loading variable {} from CDF data with a uniform sampling", + LINFO(std::format( + "Loading variable '{}' from CDF data with a uniform sampling", var )); @@ -350,8 +352,8 @@ float* KameleonWrapper::uniformSliceValues(const std::string& var, const double yDim = hasYSlice ? 1.0 : outDimensions.y - 1; const double zDim = hasZSlice ? 1.0 : outDimensions.z - 1; - LDEBUG(fmt::format("{} min: {}", var, varMin)); - LDEBUG(fmt::format("{} max: {}", var, varMax)); + LDEBUG(std::format("{} min: {}", var, varMin)); + LDEBUG(std::format("{} max: {}", var, varMax)); //double maxValue = 0.0; //double minValue = std::numeric_limits::max(); @@ -453,8 +455,8 @@ float* KameleonWrapper::uniformSampledVectorValues(const std::string& xVar, { ghoul_assert(_model && _interpolator, "Model and interpolator must exist"); - LINFO(fmt::format( - "loading variables {} {} {} from CDF data with a uniform sampling", + LINFO(std::format( + "Loading variables {} {} {} from CDF data with a uniform sampling", xVar, yVar, zVar @@ -528,7 +530,7 @@ KameleonWrapper::Fieldlines KameleonWrapper::classifiedFieldLines(const std::str float stepSize) const { ghoul_assert(_model && _interpolator, "Model and interpolator must exist"); - LINFO(fmt::format( + LINFO(std::format( "Creating {} fieldlines from variables {} {} {}", seedPoints.size(), xVar, yVar, zVar )); @@ -590,7 +592,7 @@ KameleonWrapper::Fieldlines KameleonWrapper::fieldLines(const std::string& xVar, { ghoul_assert(_model && _interpolator, "Model and interpolator must exist"); - LINFO(fmt::format( + LINFO(std::format( "Creating {} fieldlines from variables {} {} {}", seedPoints.size(), xVar, yVar, zVar )); @@ -645,7 +647,7 @@ KameleonWrapper::Fieldlines KameleonWrapper::lorentzTrajectories( const glm::vec4& /*color*/, float step) const { - LINFO(fmt::format("Creating {} Lorentz force trajectories", seedPoints.size())); + LINFO(std::format("Creating {} Lorentz force trajectories", seedPoints.size())); Fieldlines trajectories; @@ -838,7 +840,7 @@ KameleonWrapper::TraceLine KameleonWrapper::traceCartesianFieldline( ++numSteps; if (numSteps > MaxSteps) { - LDEBUG(fmt::format("Max number of steps taken ({})", MaxSteps)); + LDEBUG(std::format("Max number of steps taken ({})", MaxSteps)); break; } } @@ -952,7 +954,7 @@ KameleonWrapper::TraceLine KameleonWrapper::traceLorentzTrajectory( ++numSteps; if (numSteps > MaxSteps) { - LDEBUG(fmt::format("Max number of steps taken ({})", MaxSteps)); + LDEBUG(std::format("Max number of steps taken ({})", MaxSteps)); break; } } @@ -1072,7 +1074,7 @@ std::vector KameleonWrapper::variables() const { int numVariables = _model->getNumberOfVariables(); - for (int i = 0; i < numVariables; ++i) { + for (int i = 0; i < numVariables; i++) { variableNames.push_back(_model->getVariableName(i));; } return variableNames; diff --git a/modules/kameleonvolume/kameleonvolumereader.cpp b/modules/kameleonvolume/kameleonvolumereader.cpp index 4e49fd372a..d3d7c61b89 100644 --- a/modules/kameleonvolume/kameleonvolumereader.cpp +++ b/modules/kameleonvolume/kameleonvolumereader.cpp @@ -83,8 +83,9 @@ KameleonVolumeReader::KameleonVolumeReader(std::string path) : _path(std::move(p const long status = _kameleon->open(_path); if (status != ccmc::FileReader::OK) { - LERROR(fmt::format("Failed to open file '{}' with Kameleon", _path)); - throw ghoul::RuntimeError("Failed to open file: " + _path + " with Kameleon"); + throw ghoul::RuntimeError(std::format( + "Failed to open file '{}' with Kameleon", _path + )); } // Possibly use a kameleon interpolator instead of a model interpolator? @@ -133,7 +134,7 @@ std::unique_ptr> KameleonVolumeReader::readFloatVolume( }; float* data = volume->data(); - for (size_t index = 0; index < volume->nCells(); ++index) { + for (size_t index = 0; index < volume->nCells(); index++) { const glm::vec3 coords = volume->indexToCoords(index); const glm::vec3 coordsZeroToOne = coords / dims; const glm::vec3 volumeCoords = lowerBound + diff * coordsZeroToOne; @@ -150,7 +151,7 @@ std::unique_ptr> KameleonVolumeReader::readFloatVolume( std::vector KameleonVolumeReader::variableNames() const { std::vector variableNames; const int nVariables = _kameleon->model->getNumberOfVariables(); - for (int i = 0; i < nVariables; ++i) { + for (int i = 0; i < nVariables; i++) { variableNames.push_back(_kameleon->model->getVariableName(i)); } return variableNames; @@ -163,7 +164,7 @@ std::vector KameleonVolumeReader::variableAttributeNames() const { std::vector KameleonVolumeReader::globalAttributeNames() const { std::vector attributeNames; const int nAttributes = _kameleon->model->getNumberOfGlobalAttributes(); - for (int i = 0; i < nAttributes; ++i) { + for (int i = 0; i < nAttributes; i++) { attributeNames.push_back(_kameleon->model->getGlobalAttributeName(i)); } return attributeNames; diff --git a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp index 925a88dd74..3413e7c901 100644 --- a/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp +++ b/modules/kameleonvolume/rendering/renderablekameleonvolume.cpp @@ -339,7 +339,7 @@ bool RenderableKameleonVolume::isCachingEnabled() const { void RenderableKameleonVolume::load() { if (!std::filesystem::is_regular_file(_sourcePath.value())) { - LERROR(fmt::format("File '{}' does not exist", _sourcePath.value())); + LERROR(std::format("File '{}' does not exist", _sourcePath.value())); return; } if (!isCachingEnabled()) { @@ -361,7 +361,7 @@ void RenderableKameleonVolume::load() { std::string RenderableKameleonVolume::cacheSuffix() const { glm::uvec3 dims = _dimensions; - return fmt::format(".{}.{}x{}x{}", _variable.value(), dims[0], dims[1], dims[2]); + return std::format(".{}.{}x{}x{}", _variable.value(), dims[0], dims[1], dims[2]); } void RenderableKameleonVolume::loadFromPath(const std::string& path) { @@ -430,7 +430,7 @@ void RenderableKameleonVolume::updateTextureFromVolume() { float min = _lowerValueBound; float diff = _upperValueBound - _lowerValueBound; - for (size_t i = 0; i < _normalizedVolume->nCells(); ++i) { + for (size_t i = 0; i < _normalizedVolume->nCells(); i++) { out[i] = glm::clamp((in[i] - min) / diff, 0.f, 1.f); } diff --git a/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp b/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp index 4fe1d2f4a0..f3d9ba8042 100644 --- a/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp +++ b/modules/kameleonvolume/tasks/kameleondocumentationtask.cpp @@ -64,8 +64,8 @@ KameleonDocumentationTask::KameleonDocumentationTask(const ghoul::Dictionary& di } std::string KameleonDocumentationTask::description() { - return fmt::format( - "Extract metadata from cdf file {} and output html documentation to {}", + return std::format( + "Extract metadata from CDF file '{}' and output HTML documentation to '{}'", _inputPath, _outputPath ); } @@ -151,7 +151,7 @@ void KameleonDocumentationTask::perform(const Task::ProgressCallback & progressC file << html.str(); - progressCallback(1.0f); + progressCallback(1.f); } } // namespace openspace::kameleonvolume diff --git a/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp b/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp index 38dae18c03..4493a589a3 100644 --- a/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp +++ b/modules/kameleonvolume/tasks/kameleonmetadatatojsontask.cpp @@ -58,8 +58,8 @@ KameleonMetadataToJsonTask::KameleonMetadataToJsonTask( } std::string KameleonMetadataToJsonTask::description() { - return fmt::format( - "Extract metadata from cdf file {} and write as json to {}", + return std::format( + "Extract metadata from CDF file '{}' and write as JSON to '{}'", _inputPath, _outputPath ); } @@ -72,7 +72,7 @@ void KameleonMetadataToJsonTask::perform(const Task::ProgressCallback& progressC std::string json = ghoul::formatJson(dictionary); std::ofstream output(_outputPath); output << std::move(json); - progressCallback(1.0f); + progressCallback(1.f); } } // namespace openspace::kameleonvolume diff --git a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp index 3ed9c394cc..c551aa8961 100644 --- a/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp +++ b/modules/kameleonvolume/tasks/kameleonvolumetorawtask.cpp @@ -97,9 +97,9 @@ KameleonVolumeToRawTask::KameleonVolumeToRawTask(const ghoul::Dictionary& dictio } std::string KameleonVolumeToRawTask::description() { - return fmt::format( - "Extract volumetric data from cdf file {}. Write raw volume data into {} " - "and dictionary with metadata to {}", + return std::format( + "Extract volumetric data from CDF file '{}'. Write raw volume data into '{}' " + "and dictionary with metadata to '{}'", _inputPath, _rawVolumeOutputPath, _dictionaryOutputPath ); } @@ -158,11 +158,10 @@ void KameleonVolumeToRawTask::perform(const Task::ProgressCallback& progressCall std::string metadataString = ghoul::formatLua(outputMetadata); - std::fstream f(_dictionaryOutputPath, std::ios::out); + std::fstream f = std::fstream(_dictionaryOutputPath, std::ios::out); f << "return " << metadataString; - f.close(); - progressCallback(1.0f); + progressCallback(1.f); } } // namespace openspace::kameleonvolume diff --git a/modules/multiresvolume/rendering/brickmanager.cpp b/modules/multiresvolume/rendering/brickmanager.cpp index ca2d46daaa..959b11522e 100644 --- a/modules/multiresvolume/rendering/brickmanager.cpp +++ b/modules/multiresvolume/rendering/brickmanager.cpp @@ -49,13 +49,13 @@ bool BrickManager::readHeader() { _header = _tsp->header(); - LDEBUG(fmt::format("Grid type: {}", _header.gridType)); - LDEBUG(fmt::format("Original num timesteps: {}", _header.numOrigTimesteps)); - LDEBUG(fmt::format("Num timesteps: {}", _header.numTimesteps)); - LDEBUG(fmt::format( + LDEBUG(std::format("Grid type: {}", _header.gridType)); + LDEBUG(std::format("Original num timesteps: {}", _header.numOrigTimesteps)); + LDEBUG(std::format("Num timesteps: {}", _header.numTimesteps)); + LDEBUG(std::format( "Brick dims: {} {} {}", _header.xBrickDim, _header.yBrickDim, _header.zBrickDim )); - LDEBUG(fmt::format( + LDEBUG(std::format( "Num bricks: {} {} {}", _header.xNumBricks, _header.yNumBricks, @@ -67,8 +67,8 @@ bool BrickManager::readHeader() { _paddedBrickDim = _brickDim + _paddingWidth * 2; _atlasDim = _paddedBrickDim*_numBricks; - LDEBUG(fmt::format("Padded brick dim: {}", _paddedBrickDim)); - LDEBUG(fmt::format("Atlas dim: {}", _atlasDim)); + LDEBUG(std::format("Padded brick dim: {}", _paddedBrickDim)); + LDEBUG(std::format("Atlas dim: {}", _atlasDim)); _numBrickVals = _paddedBrickDim*_paddedBrickDim*_paddedBrickDim; // Number of bricks per frame @@ -81,11 +81,11 @@ bool BrickManager::readHeader() { unsigned int numOTNodes = static_cast((pow(8, numOTLevels) - 1) / 7); unsigned int numBSTNodes = _header.numTimesteps * 2 - 1; _numBricksTree = numOTNodes * numBSTNodes; - LDEBUG(fmt::format("Num OT levels: {}", numOTLevels)); - LDEBUG(fmt::format("Num OT nodes: {}", numOTNodes)); - LDEBUG(fmt::format("Num BST nodes: {}", numBSTNodes)); - LDEBUG(fmt::format("Num bricks in tree: {}", _numBricksTree)); - LDEBUG(fmt::format("Num values per brick: {}", _numBrickVals)); + LDEBUG(std::format("Num OT levels: {}", numOTLevels)); + LDEBUG(std::format("Num OT nodes: {}", numOTNodes)); + LDEBUG(std::format("Num BST nodes: {}", numBSTNodes)); + LDEBUG(std::format("Num bricks in tree: {}", _numBricksTree)); + LDEBUG(std::format("Num values per brick: {}", _numBrickVals)); _brickSize = sizeof(float) * _numBrickVals; _volumeSize = _brickSize * _numBricksFrame; @@ -99,8 +99,8 @@ bool BrickManager::readHeader() { if (fileSize != calcFileSize) { LERROR("Sizes do not match"); - LERROR(fmt::format("Calculated file size: {}", calcFileSize)); - LERROR(fmt::format("File size: {}", fileSize)); + LERROR(std::format("Calculated file size: {}", calcFileSize)); + LERROR(std::format("File size: {}", fileSize)); return false; } @@ -168,7 +168,7 @@ bool BrickManager::buildBrickList(BUFFER_INDEX bufferIndex, // For every non-zero entry in the request list, assign a texture atlas // coordinate. For zero entries, signal "no brick" using -1. - for (unsigned int i = 0; i < brickRequest.size(); ++i) { + for (unsigned int i = 0; i < brickRequest.size(); i++) { if (brickRequest[i] > 0) { numBricks++; @@ -367,7 +367,7 @@ bool BrickManager::diskToPBO(BUFFER_INDEX pboIndex) { //INFO("Disk read "<(_numInnerNodes); LINFOC( "ErrorHistogramManager", - fmt::format("Build {} histograms with {} bins each", _numInnerNodes, numBins) + std::format("Build {} histograms with {} bins each", _numInnerNodes, numBins) ); // All TSP Leaves @@ -196,7 +196,7 @@ bool ErrorHistogramManager::loadFromFile(const std::filesystem::path& filename) _histograms = std::vector(_numInnerNodes); - for (int i = 0; i < static_cast(_numInnerNodes); ++i) { + for (int i = 0; i < static_cast(_numInnerNodes); i++) { int offset = i * _numBins; float* data = new float[_numBins]; memcpy(data, &histogramData[offset], sizeof(float) * _numBins); @@ -224,7 +224,7 @@ bool ErrorHistogramManager::saveToFile(const std::filesystem::path& filename) { int nFloats = _numInnerNodes * _numBins; float* histogramData = new float[nFloats]; - for (unsigned int i = 0; i < _numInnerNodes; ++i) { + for (unsigned int i = 0; i < _numInnerNodes; i++) { int offset = i * _numBins; memcpy(&histogramData[offset], _histograms[i].data(), sizeof(float) * _numBins); } diff --git a/modules/multiresvolume/rendering/histogrammanager.cpp b/modules/multiresvolume/rendering/histogrammanager.cpp index 91b7f6ab4a..a7929f18b5 100644 --- a/modules/multiresvolume/rendering/histogrammanager.cpp +++ b/modules/multiresvolume/rendering/histogrammanager.cpp @@ -139,7 +139,7 @@ bool HistogramManager::loadFromFile(const std::filesystem::path& filename) { _histograms = std::vector(numHistograms); - for (int i = 0; i < numHistograms; ++i) { + for (int i = 0; i < numHistograms; i++) { int offset = i * _numBins; // No need to deallocate histogram data, since histograms take ownership. float* data = new float[_numBins]; @@ -166,7 +166,7 @@ bool HistogramManager::saveToFile(const std::filesystem::path& filename) { size_t nFloats = numHistograms * _numBins; std::vector histogramData(nFloats); - for (size_t i = 0; i < numHistograms; ++i) { + for (size_t i = 0; i < numHistograms; i++) { size_t offset = i*_numBins; memcpy(&histogramData[offset], _histograms[i].data(), sizeof(float) * _numBins); } diff --git a/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp b/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp index 022aab6335..75d276767f 100644 --- a/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp +++ b/modules/multiresvolume/rendering/localerrorhistogrammanager.cpp @@ -38,7 +38,7 @@ namespace openspace { LocalErrorHistogramManager::LocalErrorHistogramManager(TSP* tsp) : _tsp(tsp) {} bool LocalErrorHistogramManager::buildHistograms(int numBins) { - LINFO(fmt::format("Build histograms with {} bins each", numBins)); + LINFO(std::format("Build histograms with {} bins each", numBins)); _numBins = numBins; _file = &(_tsp->file()); @@ -133,11 +133,9 @@ bool LocalErrorHistogramManager::buildFromOctreeChild(unsigned int bstOffset, childValues = it->second; } else { - LERROR(fmt::format( + LERROR(std::format( "Child {} visited without cache, {}, {}", - childIndex, - bstOffset, - octreeOffset + childIndex, bstOffset, octreeOffset )); return false; } @@ -154,7 +152,7 @@ bool LocalErrorHistogramManager::buildFromOctreeChild(unsigned int bstOffset, parentValues = it->second; } else { - LERROR(fmt::format("Parent {} visited without cache", parentIndex)); + LERROR(std::format("Parent {} visited without cache", parentIndex)); return false; } } @@ -239,7 +237,7 @@ bool LocalErrorHistogramManager::buildFromBstChild(unsigned int bstOffset, childValues = it->second; } else { - LERROR(fmt::format("Child {} visited without cache", childIndex)); + LERROR(std::format("Child {} visited without cache", childIndex)); return false; } } @@ -255,7 +253,7 @@ bool LocalErrorHistogramManager::buildFromBstChild(unsigned int bstOffset, parentValues = it->second; } else { - LERROR(fmt::format("Parent {} visited without cache", parentIndex)); + LERROR(std::format("Parent {} visited without cache", parentIndex)); return false; } } @@ -321,7 +319,7 @@ bool LocalErrorHistogramManager::loadFromFile(const std::filesystem::path& filen file.read(reinterpret_cast(histogramData.data()), sizeof(float) * nFloats); _spatialHistograms = std::vector(_numInnerNodes); - for (unsigned int i = 0; i < _numInnerNodes; ++i) { + for (unsigned int i = 0; i < _numInnerNodes; i++) { const int offset = i * _numBins; // No need to deallocate histogram data, since histograms take ownership. float* data = new float[_numBins]; @@ -331,7 +329,7 @@ bool LocalErrorHistogramManager::loadFromFile(const std::filesystem::path& filen file.read(reinterpret_cast(histogramData.data()), sizeof(float) * nFloats); _temporalHistograms = std::vector(_numInnerNodes); - for (unsigned int i = 0; i < _numInnerNodes; ++i) { + for (unsigned int i = 0; i < _numInnerNodes; i++) { const int offset = i * _numBins; // No need to deallocate histogram data, since histograms take ownership. float* data = new float[_numBins]; @@ -358,7 +356,7 @@ bool LocalErrorHistogramManager::saveToFile(const std::filesystem::path& filenam const int nFloats = _numInnerNodes * _numBins; std::vector histogramData(nFloats); - for (unsigned int i = 0; i < _numInnerNodes; ++i) { + for (unsigned int i = 0; i < _numInnerNodes; i++) { int offset = i * _numBins; memcpy( &histogramData[offset], @@ -368,7 +366,7 @@ bool LocalErrorHistogramManager::saveToFile(const std::filesystem::path& filenam } file.write(reinterpret_cast(histogramData.data()), sizeof(float) * nFloats); - for (unsigned int i = 0; i < _numInnerNodes; ++i) { + for (unsigned int i = 0; i < _numInnerNodes; i++) { int offset = i * _numBins; memcpy( &histogramData[offset], diff --git a/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp b/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp index b460b59513..64ad947e1c 100644 --- a/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp +++ b/modules/multiresvolume/rendering/multiresvolumeraycaster.cpp @@ -100,7 +100,7 @@ void MultiresVolumeRaycaster::preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) { std::string id = std::to_string(data.id); - //program.setUniform("opacity_" + std::to_string(id), visible ? 1.0f : 0.0f); + //program.setUniform("opacity_" + std::to_string(id), visible ? 1.f : 0.f); program.setUniform("stepSizeCoefficient_" + id, _stepSizeCoefficient); _tfUnit = std::make_unique(); diff --git a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp index 6189d4d20f..924a59ea24 100644 --- a/modules/multiresvolume/rendering/renderablemultiresvolume.cpp +++ b/modules/multiresvolume/rendering/renderablemultiresvolume.cpp @@ -192,7 +192,7 @@ RenderableMultiresVolume::RenderableMultiresVolume(const ghoul::Dictionary& dict _filename = absPath(dictionary.value(KeyDataSource)).string(); } else { - LERROR(fmt::format("Node did not contain a valid '{}'", KeyDataSource)); + LERROR(std::format("Node did not contain a valid '{}'", KeyDataSource)); return; } @@ -245,7 +245,7 @@ RenderableMultiresVolume::RenderableMultiresVolume(const ghoul::Dictionary& dict _transferFunction = std::make_shared(_transferFunctionPath); } else { - LERROR(fmt::format("Node did not contain a valid '{}'", KeyTransferFunction)); + LERROR(std::format("Node did not contain a valid '{}'", KeyTransferFunction)); return; } @@ -474,7 +474,7 @@ bool RenderableMultiresVolume::initializeSelector() { case Selector::TF: if (_errorHistogramManager) { std::filesystem::path cached = FileSys.cacheManager()->cachedFilename( - fmt::format( + std::format( "{}_{}_errorHistograms", std::filesystem::path(_filename).stem().string(), nHistograms ), @@ -482,28 +482,28 @@ bool RenderableMultiresVolume::initializeSelector() { ); std::ifstream cacheFile(cached, std::ios::in | std::ios::binary); if (cacheFile.is_open()) { - // Read histograms from cache. + // Read histograms from cache cacheFile.close(); LINFO( - fmt::format("Loading histograms from cache: {}", cached) + std::format("Loading histograms from cache '{}'", cached) ); success &= _errorHistogramManager->loadFromFile(cached); } else if (!_errorHistogramsPath.empty()) { - // Read histograms from scene data. - LINFO(fmt::format( - "Loading histograms from scene data: {}", _errorHistogramsPath + // Read histograms from scene data + LINFO(std::format( + "Loading histograms from scene data '{}'", _errorHistogramsPath )); success &= _errorHistogramManager->loadFromFile( _errorHistogramsPath.string() ); } else { - // Build histograms from tsp file. - LWARNING(fmt::format("Failed to open {}", cached)); + // Build histograms from tsp file + LWARNING(std::format("Failed to open '{}'", cached)); success &= _errorHistogramManager->buildHistograms(nHistograms); if (success) { - LINFO(fmt::format("Writing cache to {}", cached)); + LINFO(std::format("Writing cache to '{}'", cached)); _errorHistogramManager->saveToFile(cached); } } @@ -514,7 +514,7 @@ bool RenderableMultiresVolume::initializeSelector() { case Selector::SIMPLE: if (_histogramManager) { std::filesystem::path cached = FileSys.cacheManager()->cachedFilename( - fmt::format("{}_{}_histogram", + std::format("{}_{}_histogram", std::filesystem::path(_filename).stem().string(), nHistograms ), "" @@ -523,18 +523,18 @@ bool RenderableMultiresVolume::initializeSelector() { if (cacheFile.is_open()) { // Read histograms from cache. cacheFile.close(); - LINFO(fmt::format("Loading histograms from {}", cached)); + LINFO(std::format("Loading histograms from '{}'", cached)); success &= _histogramManager->loadFromFile(cached); } else { // Build histograms from tsp file. - LWARNING(fmt::format("Failed to open {}", cached)); + LWARNING(std::format("Failed to open '{}'", cached)); success &= _histogramManager->buildHistograms( _tsp.get(), nHistograms ); if (success) { - LINFO(fmt::format("Writing cache to {}", cached)); + LINFO(std::format("Writing cache to '{}'", cached)); _histogramManager->saveToFile(cached); } } @@ -545,7 +545,7 @@ bool RenderableMultiresVolume::initializeSelector() { case Selector::LOCAL: if (_localErrorHistogramManager) { std::filesystem::path cached = FileSys.cacheManager()->cachedFilename( - fmt::format( + std::format( "{}_{}_localErrorHistograms", std::filesystem::path(_filename).stem().string(), nHistograms ), @@ -555,15 +555,15 @@ bool RenderableMultiresVolume::initializeSelector() { if (cacheFile.is_open()) { // Read histograms from cache. cacheFile.close(); - LINFO(fmt::format("Loading histograms from {}", cached)); + LINFO(std::format("Loading histograms from '{}'", cached)); success &= _localErrorHistogramManager->loadFromFile(cached); } else { // Build histograms from tsp file. - LWARNING(fmt::format("Failed to open {}", cached)); + LWARNING(std::format("Failed to open '{}'", cached)); success &= _localErrorHistogramManager->buildHistograms(nHistograms); if (success) { - LINFO(fmt::format("Writing cache to {}", cached)); + LINFO(std::format("Writing cache to '{}'", cached)); _localErrorHistogramManager->saveToFile(cached); } } @@ -581,7 +581,7 @@ void RenderableMultiresVolume::preResolve(ghoul::opengl::ProgramObject* program) std::stringstream ss; ss << "opacity_" << getId(); - program->setUniform(ss.str(), visible ? 1.0f : 0.0f); + program->setUniform(ss.str(), visible ? 1.f : 0.f); ss.str(std::string()); ss << "stepSizeCoefficient_" << getId(); diff --git a/modules/multiresvolume/rendering/tsp.cpp b/modules/multiresvolume/rendering/tsp.cpp index b12b8ae868..a51c26d064 100644 --- a/modules/multiresvolume/rendering/tsp.cpp +++ b/modules/multiresvolume/rendering/tsp.cpp @@ -96,12 +96,12 @@ bool TSP::readHeader() { _file.read(reinterpret_cast(&_header), sizeof(Header)); - LDEBUG(fmt::format("Grid type: {}", _header.gridType)); - LDEBUG(fmt::format( + LDEBUG(std::format("Grid type: {}", _header.gridType)); + LDEBUG(std::format( "Brick dimensions: {} {} {}", _header.xBrickDim, _header.yBrickDim, _header.zBrickDim )); - LDEBUG(fmt::format( + LDEBUG(std::format( "Num bricks: {} {} {}", _header.xNumBricks, _header.yNumBricks, _header.zNumBricks )); @@ -118,15 +118,15 @@ bool TSP::readHeader() { _numBSTNodes = _header.numTimesteps * 2 - 1; _numTotalNodes = _numOTNodes * _numBSTNodes; - LDEBUG(fmt::format("Num OT levels: {}", _numOTLevels)); - LDEBUG(fmt::format("Num OT nodes: {}", _numOTNodes)); - LDEBUG(fmt::format("Num BST levels: {}", _numBSTLevels)); - LDEBUG(fmt::format("Num BST nodes: {}", _numBSTNodes)); - LDEBUG(fmt::format("Num total nodes: {}", _numTotalNodes)); + LDEBUG(std::format("Num OT levels: {}", _numOTLevels)); + LDEBUG(std::format("Num OT nodes: {}", _numOTNodes)); + LDEBUG(std::format("Num BST levels: {}", _numBSTLevels)); + LDEBUG(std::format("Num BST nodes: {}", _numBSTNodes)); + LDEBUG(std::format("Num total nodes: {}", _numTotalNodes)); // Allocate space for TSP structure _data.resize(_numTotalNodes*NUM_DATA); - LDEBUG(fmt::format("Data size: {}", _data.size())); + LDEBUG(std::format("Data size: {}", _data.size())); return true; } @@ -147,7 +147,7 @@ bool TSP::construct() { unsigned int OTLevel = 0; while (OTLevel < _numOTLevels) { unsigned int OTNodesInLevel = static_cast(pow(8, OTLevel)); - for (unsigned int i = 0; i(OTNode); @@ -363,7 +363,7 @@ bool TSP::calculateSpatialError() { // "Normalize" errors float minNorm = 1e20f; float maxNorm = 0.f; - for (unsigned int i = 0; i<_numTotalNodes; ++i) { + for (unsigned int i = 0; i<_numTotalNodes; i++) { //float normalized = (stdDevs[i]-minError)/(maxError-minError); if (stdDevs[i] > 0.f) { stdDevs[i] = pow(stdDevs[i], 0.5f); @@ -385,9 +385,9 @@ bool TSP::calculateSpatialError() { _maxSpatialError = maxNorm; _medianSpatialError = medNorm; - LDEBUG(fmt::format("Min normalized spatial std dev: {}", minNorm)); - LDEBUG(fmt::format("Max normalized spatial std dev: {}", maxNorm)); - LDEBUG(fmt::format("Median normalized spatial std dev: {}", medNorm)); + LDEBUG(std::format("Min normalized spatial std dev: {}", minNorm)); + LDEBUG(std::format("Max normalized spatial std dev: {}", maxNorm)); + LDEBUG(std::format("Median normalized spatial std dev: {}", medNorm)); return true; } @@ -476,7 +476,7 @@ bool TSP::calculateTemporalError() { // Adjust errors using user-provided exponents float minNorm = 1e20f; float maxNorm = 0.f; - for (unsigned int i = 0; i < _numTotalNodes; ++i) { + for (unsigned int i = 0; i < _numTotalNodes; i++) { if (errors[i] > 0.f) { errors[i] = pow(errors[i], 0.25f); } @@ -496,9 +496,9 @@ bool TSP::calculateTemporalError() { _maxTemporalError = maxNorm; _medianTemporalError = medNorm; - LDEBUG(fmt::format("Min normalized temporal std dev: {}", minNorm)); - LDEBUG(fmt::format("Max normalized temporal std dev: {}", maxNorm)); - LDEBUG(fmt::format("Median normalized temporal std dev: {}", medNorm)); + LDEBUG(std::format("Min normalized temporal std dev: {}", minNorm)); + LDEBUG(std::format("Max normalized temporal std dev: {}", maxNorm)); + LDEBUG(std::format("Median normalized temporal std dev: {}", medNorm)); return true; } @@ -514,7 +514,7 @@ bool TSP::readCache() { std::ifstream file(cacheFilename, std::ios::in | std::ios::binary); if (!file.is_open()) { - LWARNING(fmt::format("Failed to open {}", cacheFilename)); + LWARNING(std::format("Failed to open {}", cacheFilename)); return false; } @@ -530,12 +530,12 @@ bool TSP::readCache() { file.close(); LDEBUG("Cached errors:"); - LDEBUG(fmt::format("Min spatial error: {}", _minSpatialError)); - LDEBUG(fmt::format("Max spatial error: {}", _maxSpatialError)); - LDEBUG(fmt::format("Median spatial error: {}", _medianSpatialError)); - LDEBUG(fmt::format("Min temporal error: {}", _minTemporalError)); - LDEBUG(fmt::format("Max temporal error: {}", _maxTemporalError)); - LDEBUG(fmt::format("Median temporal error: {}", _medianTemporalError)); + LDEBUG(std::format("Min spatial error: {}", _minSpatialError)); + LDEBUG(std::format("Max spatial error: {}", _maxSpatialError)); + LDEBUG(std::format("Median spatial error: {}", _medianSpatialError)); + LDEBUG(std::format("Min temporal error: {}", _minTemporalError)); + LDEBUG(std::format("Max temporal error: {}", _maxTemporalError)); + LDEBUG(std::format("Median temporal error: {}", _medianTemporalError)); return true; } @@ -552,10 +552,10 @@ bool TSP::writeCache() { std::ofstream file(cacheFilename, std::ios::out | std::ios::binary); if (!file.is_open()) { - LWARNING(fmt::format("Failed to open {}", cacheFilename)); + LWARNING(std::format("Failed to open {}", cacheFilename)); return false; } - LINFO(fmt::format("Writing cache to {}", cacheFilename)); + LINFO(std::format("Writing cache to {}", cacheFilename)); file.write(reinterpret_cast(&_minSpatialError), sizeof(float)); file.write(reinterpret_cast(&_maxSpatialError), sizeof(float)); @@ -649,7 +649,7 @@ std::list TSP::coveredLeafBricks(unsigned int brickIndex) const { } else { // Queue the eight children - for (int i = 0; i<8; ++i) { + for (int i = 0; i<8; i++) { queue.push(child + i); } } diff --git a/modules/server/include/serverinterface.h b/modules/server/include/serverinterface.h index 66ffb0d4d9..090d18514b 100644 --- a/modules/server/include/serverinterface.h +++ b/modules/server/include/serverinterface.h @@ -42,7 +42,7 @@ public: const ghoul::Dictionary& dictionary); ServerInterface(const ghoul::Dictionary& dictionary); - virtual ~ServerInterface() override; + virtual ~ServerInterface() override = default; void initialize(); void deinitialize(); diff --git a/modules/server/include/topics/luascripttopic.h b/modules/server/include/topics/luascripttopic.h index c26814e584..d12f729687 100644 --- a/modules/server/include/topics/luascripttopic.h +++ b/modules/server/include/topics/luascripttopic.h @@ -35,7 +35,7 @@ public: bool isDone() const override; private: - void runScript(std::string script, bool returnValue, bool shouldBeSynchronized); + void runScript(std::string script, bool shouldReturn, bool shouldBeSynchronized); bool _waitingForReturnValue = true; }; diff --git a/modules/server/include/topics/timetopic.h b/modules/server/include/topics/timetopic.h index 16f8a6c34e..9c5534ccb3 100644 --- a/modules/server/include/topics/timetopic.h +++ b/modules/server/include/topics/timetopic.h @@ -41,7 +41,7 @@ public: private: static constexpr int UnsetOnChangeHandle = -1; - const nlohmann::json getNextPrevDeltaTimeStepJson(); + nlohmann::json getNextPrevDeltaTimeStepJson(); void sendCurrentTime(); void sendFullTimeData(); diff --git a/modules/server/servermodule.cpp b/modules/server/servermodule.cpp index dec3c0042c..aebcaf068f 100644 --- a/modules/server/servermodule.cpp +++ b/modules/server/servermodule.cpp @@ -96,9 +96,10 @@ void ServerModule::internalInitialize(const ghoul::Dictionary& configuration) { if (!configuration.hasValue(KeyInterfaces)) { return; } - ghoul::Dictionary interfaces = configuration.value(KeyInterfaces); + const ghoul::Dictionary interfaces = + configuration.value(KeyInterfaces); - for (std::string_view key : interfaces.keys()) { + for (const std::string_view key : interfaces.keys()) { ghoul::Dictionary interfaceDictionary = interfaces.value(key); // @TODO (abock, 2019-09-17); This is a hack to make the parsing of the @@ -143,7 +144,7 @@ void ServerModule::preSync() { std::unique_ptr socket; while ((socket = socketServer->nextPendingSocket())) { - std::string address = socket->address(); + const std::string address = socket->address(); if (serverInterface->clientIsBlocked(address)) { // Drop connection if the address is blocked. continue; @@ -200,7 +201,7 @@ void ServerModule::disconnectAll() { serverInterface->deinitialize(); } - for (ConnectionData& connectionData : _connections) { + for (const ConnectionData& connectionData : _connections) { Connection& connection = *connectionData.connection; if (connection.socket() && connection.socket()->isConnected()) { connection.socket()->disconnect( @@ -210,13 +211,13 @@ void ServerModule::disconnectAll() { } } -void ServerModule::handleConnection(std::shared_ptr connection) { +void ServerModule::handleConnection(const std::shared_ptr& connection) { ZoneScoped; std::string messageString; messageString.reserve(256); while (connection->socket()->getMessage(messageString)) { - std::lock_guard lock(_messageQueueMutex); + const std::lock_guard lock(_messageQueueMutex); _messageQueue.push_back({ connection, messageString }); } } @@ -224,19 +225,18 @@ void ServerModule::handleConnection(std::shared_ptr connection) { void ServerModule::consumeMessages() { ZoneScoped; - std::lock_guard lock(_messageQueueMutex); + const std::lock_guard lock(_messageQueueMutex); while (!_messageQueue.empty()) { const Message& m = _messageQueue.front(); - if (std::shared_ptr c = m.connection.lock()) { + if (const std::shared_ptr& c = m.connection.lock()) { c->handleMessage(m.messageString); } _messageQueue.pop_front(); } } -ServerModule::CallbackHandle ServerModule::addPreSyncCallback(CallbackFunction cb) -{ - CallbackHandle handle = _nextCallbackHandle++; +ServerModule::CallbackHandle ServerModule::addPreSyncCallback(CallbackFunction cb) { + const CallbackHandle handle = _nextCallbackHandle++; _preSyncCallbacks.emplace_back(handle, std::move(cb)); return handle; } diff --git a/modules/server/servermodule.h b/modules/server/servermodule.h index aa59142948..3bf7823a11 100644 --- a/modules/server/servermodule.h +++ b/modules/server/servermodule.h @@ -71,7 +71,7 @@ private: bool isMarkedForRemoval = false; }; - void handleConnection(std::shared_ptr connection); + void handleConnection(const std::shared_ptr& connection); void cleanUpFinishedThreads(); void consumeMessages(); void disconnectAll(); diff --git a/modules/server/src/connection.cpp b/modules/server/src/connection.cpp index 53026656fe..37e1f2709d 100644 --- a/modules/server/src/connection.cpp +++ b/modules/server/src/connection.cpp @@ -50,8 +50,8 @@ #include #include #include +#include #include -#include namespace { constexpr std::string_view _loggerCat = "ServerModule: Connection"; @@ -109,40 +109,40 @@ void Connection::handleMessage(const std::string& message) { ZoneScoped; try { - nlohmann::json j = nlohmann::json::parse(message.c_str()); + const nlohmann::json j = nlohmann::json::parse(message.c_str()); try { handleJson(j); } catch (const std::domain_error& e) { - LERROR(fmt::format("JSON handling error from: {}. {}", message, e.what())); + LERROR(std::format("JSON handling error from: {}. {}", message, e.what())); } } catch (const std::out_of_range& e) { - LERROR(fmt::format("JSON handling error from: {}. {}", message, e.what())); + LERROR(std::format("JSON handling error from: {}. {}", message, e.what())); } catch (const std::exception& e) { LERROR(e.what()); - } catch (...) { + } + catch (...) { if (!isAuthorized()) { _socket->disconnect(); - LERROR(fmt::format( - "Could not parse JSON: '{}'. Connection is unauthorized. Disconnecting", + LERROR(std::format( + "Could not parse JSON '{}'. Connection is unauthorized. Disconnecting", message )); return; } - else { - std::string sanitizedString = message; - std::transform( - message.begin(), - message.end(), - sanitizedString.begin(), - [](wchar_t c) { - return std::isprint(c, std::locale("")) ? char(c) : ' '; - } - ); - LERROR(fmt::format("Could not parse JSON: '{}'", sanitizedString)); - } + + std::string sanitizedString = message; + std::transform( + message.begin(), + message.end(), + sanitizedString.begin(), + [](wchar_t c) { + return std::isprint(c, std::locale("")) ? char(c) : ' '; + } + ); + LERROR(std::format("Could not parse JSON '{}'", sanitizedString)); } } @@ -163,7 +163,7 @@ void Connection::handleJson(const nlohmann::json& json) { } // The topic id may be an already discussed topic, or a new one. - TopicId topicId = *topicJson; + const TopicId topicId = *topicJson; auto topicIt = _topics.find(topicId); if (topicIt == _topics.end()) { @@ -173,9 +173,9 @@ void Connection::handleJson(const nlohmann::json& json) { LERROR("Type must be specified as a string when a new topic is initialized"); return; } - std::string type = *typeJson; + const std::string type = *typeJson; - if (!isAuthorized() && type != "authorize") { + if (!isAuthorized() && (type != "authorize")) { LERROR("Connection is not authorized"); return; } diff --git a/modules/server/src/connectionpool.cpp b/modules/server/src/connectionpool.cpp index ae4078ea3f..69136581d7 100644 --- a/modules/server/src/connectionpool.cpp +++ b/modules/server/src/connectionpool.cpp @@ -65,7 +65,7 @@ void ConnectionPool::updateConnections() { } void ConnectionPool::acceptNewSockets() { - for (std::shared_ptr& server : _socketServers) { + for (const std::shared_ptr& server : _socketServers) { std::unique_ptr socket; while ((socket = server->nextPendingSocket())) { _handleSocket(*socket); diff --git a/modules/server/src/jsonconverters.cpp b/modules/server/src/jsonconverters.cpp index ae62f728e8..18960ed5d4 100644 --- a/modules/server/src/jsonconverters.cpp +++ b/modules/server/src/jsonconverters.cpp @@ -34,10 +34,10 @@ using json = nlohmann::json; namespace openspace::properties { void to_json(json& j, const Property& p) { - std::string description = p.generateJsonDescription(); + const std::string description = p.generateJsonDescription(); json desc = json::parse(description); - std::string value = p.jsonValue(); + const std::string value = p.jsonValue(); json val = json::parse(value); j = { @@ -70,37 +70,37 @@ void to_json(json& j, const PropertyOwner* p) { namespace ghoul { -void to_json(json& j, const Dictionary& dictionary) { +void to_json(json& j, const Dictionary& d) { json object; - for (std::string_view k : dictionary.keys()) { - std::string key = std::string(k); - if (dictionary.hasValue(key)) { - const glm::dvec4 v = dictionary.value(key); + for (const std::string_view k : d.keys()) { + const std::string key = std::string(k); + if (d.hasValue(key)) { + const glm::dvec4 v = d.value(key); object[key] = json::array({ v[0], v[1], v[2], v[3] }); } - else if (dictionary.hasValue(key)) { - const glm::dvec3 v = dictionary.value(key); + else if (d.hasValue(key)) { + const glm::dvec3 v = d.value(key); object[key] = json::array({ v[0], v[1], v[2] }); } - else if (dictionary.hasValue(key)) { - const glm::dvec2 v = dictionary.value(key); + else if (d.hasValue(key)) { + const glm::dvec2 v = d.value(key); object[key] = json::array({ v[0], v[1] }); } - else if (dictionary.hasValue(key)) { - object[key] = dictionary.value(key); + else if (d.hasValue(key)) { + object[key] = d.value(key); } - else if (dictionary.hasValue(key)) { - object[key] = dictionary.value(key); + else if (d.hasValue(key)) { + object[key] = d.value(key); } - else if (dictionary.hasValue(key)) { - object[key] = dictionary.value(key); + else if (d.hasValue(key)) { + object[key] = d.value(key); } - else if (dictionary.hasValue(key)) { - object[key] = dictionary.value(key); + else if (d.hasValue(key)) { + object[key] = d.value(key); } - else if (dictionary.hasValue(key)) { + else if (d.hasValue(key)) { json child; - to_json(child, dictionary.value(key)); + to_json(child, d.value(key)); object[key] = child; } else { @@ -167,4 +167,4 @@ void to_json(json& j, const dvec3& v) { }; } -} // namepsace glm +} // namespace glm diff --git a/modules/server/src/serverinterface.cpp b/modules/server/src/serverinterface.cpp index 4c080721f2..c9bf5a08f5 100644 --- a/modules/server/src/serverinterface.cpp +++ b/modules/server/src/serverinterface.cpp @@ -99,14 +99,14 @@ namespace { namespace openspace { std::unique_ptr ServerInterface::createFromDictionary( - const ghoul::Dictionary& config) + const ghoul::Dictionary& dictionary) { // TODO: Use documentation to verify dictionary - auto si = std::make_unique(config); + auto si = std::make_unique(dictionary); return si; } -ServerInterface::ServerInterface(const ghoul::Dictionary& config) +ServerInterface::ServerInterface(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "", "", "" }) , _socketType(TypeInfo) , _port(PortInfo, 0) @@ -140,8 +140,10 @@ ServerInterface::ServerInterface(const ghoul::Dictionary& config) std::string(AllowAccess) ); - if (config.hasKey(DefaultAccessInfo.identifier)) { - std::string access = config.value(DefaultAccessInfo.identifier); + if (dictionary.hasKey(DefaultAccessInfo.identifier)) { + const std::string access = dictionary.value( + DefaultAccessInfo.identifier + ); if (access == DenyAccess) { _defaultAccess.setValue(static_cast(Access::Deny)); } @@ -153,14 +155,14 @@ ServerInterface::ServerInterface(const ghoul::Dictionary& config) } } - const std::string identifier = config.value(KeyIdentifier); + const std::string identifier = dictionary.value(KeyIdentifier); auto readList = - [config](const std::string& key, properties::StringListProperty& list) { - if (config.hasValue(key)) { - const ghoul::Dictionary& dict = config.value(key); + [dictionary](const std::string& key, properties::StringListProperty& list) { + if (dictionary.hasValue(key)) { + const ghoul::Dictionary& dict = dictionary.value(key); std::vector v; - for (std::string_view k : dict.keys()) { + for (const std::string_view k : dict.keys()) { v.push_back(dict.value(k)); } list = v; @@ -175,7 +177,7 @@ ServerInterface::ServerInterface(const ghoul::Dictionary& config) setGuiName(identifier); setDescription("Settings for server interface " + identifier); - const std::string type = config.value(TypeInfo.identifier); + const std::string type = dictionary.value(TypeInfo.identifier); if (type == TcpSocketType) { _socketType = static_cast(InterfaceType::TcpSocket); } @@ -183,12 +185,12 @@ ServerInterface::ServerInterface(const ghoul::Dictionary& config) _socketType = static_cast(InterfaceType::WebSocket); } - if (config.hasValue(PasswordInfo.identifier)) { - _password = config.value(PasswordInfo.identifier); + if (dictionary.hasValue(PasswordInfo.identifier)) { + _password = dictionary.value(PasswordInfo.identifier); } - _port = static_cast(config.value(PortInfo.identifier)); - _enabled = config.value(EnabledInfo.identifier); + _port = static_cast(dictionary.value(PortInfo.identifier)); + _enabled = dictionary.value(EnabledInfo.identifier); auto reinitialize = [this]() { deinitialize(); @@ -213,8 +215,6 @@ ServerInterface::ServerInterface(const ghoul::Dictionary& config) addProperty(_password); } -ServerInterface::~ServerInterface() {} - void ServerInterface::initialize() { if (!_enabled) { return; @@ -258,7 +258,7 @@ bool ServerInterface::clientHasAccessWithoutPassword( return true; } } - Access access = static_cast(_defaultAccess.value()); + const Access access = static_cast(_defaultAccess.value()); if (access == Access::Allow) { for (const std::string& address : _denyAddresses.value()) { if (clientAddress == address) { @@ -276,7 +276,7 @@ bool ServerInterface::clientIsBlocked(const std::string& clientAddress) const { return true; } } - Access access = static_cast(_defaultAccess.value()); + const Access access = static_cast(_defaultAccess.value()); if (access == Access::Deny) { for (const std::string& address : _allowAddresses.value()) { if (clientAddress == address) { @@ -297,5 +297,4 @@ ghoul::io::SocketServer* ServerInterface::server() { return _socketServer.get(); } - -} +} // namespace openspace diff --git a/modules/server/src/topics/authorizationtopic.cpp b/modules/server/src/topics/authorizationtopic.cpp index 3684412af3..946fc6c3ab 100644 --- a/modules/server/src/topics/authorizationtopic.cpp +++ b/modules/server/src/topics/authorizationtopic.cpp @@ -54,7 +54,7 @@ void AuthorizationTopic::handleJson(const nlohmann::json& json) { } else { try { - std::string providedKey = json.at("key").get(); + const std::string providedKey = json.at("key").get(); if (authorize(providedKey)) { _connection->setAuthorized(true); _connection->sendJson(wrappedPayload({ KeyStatus, Authorized })); diff --git a/modules/server/src/topics/camerapathtopic.cpp b/modules/server/src/topics/camerapathtopic.cpp index 54c6c579dd..7662530fc4 100644 --- a/modules/server/src/topics/camerapathtopic.cpp +++ b/modules/server/src/topics/camerapathtopic.cpp @@ -60,7 +60,7 @@ bool CameraPathTopic::isDone() const { } void CameraPathTopic::handleJson(const nlohmann::json& json) { - std::string event = json.at("event").get(); + const std::string event = json.at("event").get(); if (event != SubscribeEvent) { _isDone = true; @@ -70,10 +70,10 @@ void CameraPathTopic::handleJson(const nlohmann::json& json) { ServerModule* module = global::moduleEngine->module(); _dataCallbackHandle = module->addPreSyncCallback( [this]() { - bool isInPath = (global::openSpaceEngine->currentMode() + const bool isInPath =(global::openSpaceEngine->currentMode() == OpenSpaceEngine::Mode::CameraPath); - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); if (isInPath && (now - _lastUpdateTime) > _cameraPathUpdateTime) { sendCameraPathData(); _lastUpdateTime = std::chrono::system_clock::now(); @@ -100,7 +100,7 @@ void CameraPathTopic::sendCameraPathData() { ); seconds = std::max(seconds, 0); - nlohmann::json jsonData = { + const nlohmann::json jsonData = { { "target", path->endPoint().nodeIdentifier() }, { "remainingTime", seconds }, //{ "remainingDistance", path->remainingDistance() }, diff --git a/modules/server/src/topics/cameratopic.cpp b/modules/server/src/topics/cameratopic.cpp index c6690eb077..9e10c80518 100644 --- a/modules/server/src/topics/cameratopic.cpp +++ b/modules/server/src/topics/cameratopic.cpp @@ -59,7 +59,7 @@ bool CameraTopic::isDone() const { } void CameraTopic::handleJson(const nlohmann::json& json) { - std::string event = json.at("event").get(); + const std::string event = json.at("event").get(); if (event != SubscribeEvent) { _isDone = true; @@ -69,7 +69,7 @@ void CameraTopic::handleJson(const nlohmann::json& json) { ServerModule* module = global::moduleEngine->module(); _dataCallbackHandle = module->addPreSyncCallback( [this]() { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); if (now - _lastUpdateTime > _cameraPositionUpdateTime) { sendCameraData(); _lastUpdateTime = std::chrono::system_clock::now(); @@ -83,7 +83,7 @@ void CameraTopic::sendCameraData() { glm::dvec3 position = module->geoPosition(); std::pair altSimplified = simplifyDistance(position.z); - nlohmann::json jsonData = { + const nlohmann::json jsonData = { { "latitude", position.x }, { "longitude", position.y }, { "altitude", altSimplified.first }, diff --git a/modules/server/src/topics/documentationtopic.cpp b/modules/server/src/topics/documentationtopic.cpp index eb2467902e..b8910f6c12 100644 --- a/modules/server/src/topics/documentationtopic.cpp +++ b/modules/server/src/topics/documentationtopic.cpp @@ -38,7 +38,7 @@ using nlohmann::json; namespace openspace { void DocumentationTopic::handleJson(const nlohmann::json& json) { - std::string requestedType = json.at("type").get(); + const std::string requestedType = json.at("type").get(); nlohmann::json response; diff --git a/modules/server/src/topics/enginemodetopic.cpp b/modules/server/src/topics/enginemodetopic.cpp index 8f4cfdb2d2..ce4450b5a1 100644 --- a/modules/server/src/topics/enginemodetopic.cpp +++ b/modules/server/src/topics/enginemodetopic.cpp @@ -75,11 +75,10 @@ void EngineModeTopic::handleJson(const nlohmann::json& json) { if (event == SubscribeEvent) { _modeCallbackHandle = global::openSpaceEngine->addModeChangeCallback( [this]() { - OpenSpaceEngine::Mode currentMode = - global::openSpaceEngine->currentMode(); - if (currentMode != _lastMode) { + const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); + if (mode != _lastMode) { sendJsonData(); - _lastMode = currentMode; + _lastMode = mode; } } ); @@ -87,9 +86,7 @@ void EngineModeTopic::handleJson(const nlohmann::json& json) { } void EngineModeTopic::sendJsonData() { - json stateJson; - - OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); std::string modeString; switch (mode) { case OpenSpaceEngine::Mode::UserControl: @@ -102,6 +99,8 @@ void EngineModeTopic::sendJsonData() { modeString = "camera_path"; break; } + + json stateJson; stateJson["mode"] = modeString; if (!stateJson.empty()) { diff --git a/modules/server/src/topics/eventtopic.cpp b/modules/server/src/topics/eventtopic.cpp index cc46202166..bb04159b15 100644 --- a/modules/server/src/topics/eventtopic.cpp +++ b/modules/server/src/topics/eventtopic.cpp @@ -74,7 +74,7 @@ void EventTopic::handleJson(const nlohmann::json& json) { for (uint8_t i = 0; i < lastEvent; i++) { auto type = static_cast(i); - events.push_back(std::string(events::toString(type))); + events.emplace_back(events::toString(type)); } } else { @@ -99,7 +99,7 @@ void EventTopic::handleJson(const nlohmann::json& json) { global::eventEngine->registerEventTopic(_topicId, type, onCallback); } else if (status == StopSubscription) { - events::Event::Type type = events::fromString(event); + const events::Event::Type type = events::fromString(event); _subscribedEvents.erase(type); global::eventEngine->unregisterEventTopic(_topicId, type); } @@ -111,7 +111,7 @@ bool EventTopic::isSubscribed() const { return false; } - bool hasActiveSubscription = std::any_of( + const bool hasActiveSubscription = std::any_of( _subscribedEvents.begin(), _subscribedEvents.end(), [](const std::pair& subscription) { diff --git a/modules/server/src/topics/flightcontrollertopic.cpp b/modules/server/src/topics/flightcontrollertopic.cpp index 1ac4fd202f..7deecc1773 100644 --- a/modules/server/src/topics/flightcontrollertopic.cpp +++ b/modules/server/src/topics/flightcontrollertopic.cpp @@ -118,7 +118,7 @@ namespace { constexpr const char* Friction = "friction"; constexpr const char* Lua = "lua"; - const static std::unordered_map AxisIndexMap ({ + const std::unordered_map AxisIndexMap ({ { OrbitX, AxisType::OrbitX }, { OrbitY, AxisType::OrbitY }, { ZoomIn, AxisType::ZoomIn }, @@ -131,7 +131,7 @@ namespace { { PanY, AxisType::PanY } }); - const static std::unordered_map CommandMap ({ + const std::unordered_map CommandMap ({ { Connect, Command::Connect }, { Disconnect, Command::Disconnect }, { InputState, Command::InputState }, @@ -147,7 +147,7 @@ using nlohmann::json; namespace openspace { FlightControllerTopic::FlightControllerTopic() { - for (auto it = AxisIndexMap.begin(); it != AxisIndexMap.end(); ++it) { + for (auto it = AxisIndexMap.begin(); it != AxisIndexMap.end(); it++) { global::navigationHandler->setWebsocketAxisMapping( int(std::distance(AxisIndexMap.begin(), it)), it->second @@ -175,7 +175,7 @@ void FlightControllerTopic::handleJson(const nlohmann::json& json) { auto it = CommandMap.find(json[TypeKey]); if (it == CommandMap.end()) { LWARNING( - fmt::format("Poorly formatted JSON command: no '{}' in payload", TypeKey) + std::format("Malformed JSON command: no '{}' in payload", TypeKey) ); return; } @@ -203,7 +203,7 @@ void FlightControllerTopic::handleJson(const nlohmann::json& json) { processLua(json[Lua]); break; default: - LWARNING(fmt::format("Unrecognized action: {}", it->first)); + LWARNING(std::format("Unrecognized action: {}", it->first)); break; } } @@ -270,15 +270,15 @@ void FlightControllerTopic::changeFocus(const nlohmann::json& json) const { if (json.find(FocusKey) == json.end()) { const std::string j = json; LWARNING( - fmt::format("Could not find {} key in JSON. JSON was:\n{}", FocusKey, j) + std::format("Could not find '{}' key in JSON. JSON was:\n{}", FocusKey, j) ); if (json.find(AimKey) == json.end()) { LWARNING( - fmt::format("Could not find {} key in JSON. JSON was:\n{}", AimKey, j) + std::format("Could not find '{}' key in JSON. JSON was:\n{}", AimKey, j) ); if (json.find(AnchorKey) == json.end()) { - LWARNING(fmt::format( - "Could not find {} key in JSON. JSON was:\n{}", AnchorKey, j + LWARNING(std::format( + "Could not find '{}' key in JSON. JSON was:\n{}", AnchorKey, j )); return; } @@ -324,7 +324,7 @@ void FlightControllerTopic::setRenderableEnabled(const nlohmann::json& json) con if (json[RenderableKey].find(SceneNodeName) == json[RenderableKey].end()) { const std::string j = json; LWARNING( - fmt::format("Could not find {} key in JSON. JSON was:\n{}", FocusKey, j) + std::format("Could not find '{}' key in JSON. JSON was:\n{}", FocusKey, j) ); return; } @@ -389,12 +389,12 @@ void FlightControllerTopic::engageAutopilot(const nlohmann::json &json) { std::fill(_inputState.axes.begin(), _inputState.axes.end(), 0.f); _inputState.isConnected = true; - for (auto it = input.begin(); it != input.end(); ++it) { + for (auto it = input.begin(); it != input.end(); it++) { const auto mapIt = AxisIndexMap.find(it.key()); if (mapIt == AxisIndexMap.end()) { if (it.key() != TypeKey || CommandMap.find(it.value()) == CommandMap.end()) { - LWARNING(fmt::format( - "No axis, button, or command named {} (value: {})", + LWARNING(std::format( + "No axis, button, or command named '{}' (value: {})", it.key(), static_cast(it.value()) )); } @@ -429,12 +429,12 @@ void FlightControllerTopic::processInputState(const nlohmann::json& json) { // Get "inputState" object from "payload" auto input = json[InputState][ValuesKey]; - for (auto it = input.begin(); it != input.end(); ++it) { + for (auto it = input.begin(); it != input.end(); it++) { const auto mapIt = AxisIndexMap.find(it.key()); if (mapIt == AxisIndexMap.end()) { if (it.key() != TypeKey || CommandMap.find(it.value()) == CommandMap.end()) { - LWARNING(fmt::format( - "No axis, button, or command named {} (value: {})", + LWARNING(std::format( + "No axis, button, or command named '{}' (value: {})", it.key() , static_cast(it.value()) )); } diff --git a/modules/server/src/topics/getpropertytopic.cpp b/modules/server/src/topics/getpropertytopic.cpp index be96c0d54f..4c0f037ba6 100644 --- a/modules/server/src/topics/getpropertytopic.cpp +++ b/modules/server/src/topics/getpropertytopic.cpp @@ -52,7 +52,7 @@ namespace { namespace openspace { void GetPropertyTopic::handleJson(const nlohmann::json& json) { - std::string requestedKey = json.at("property").get(); + const std::string requestedKey = json.at("property").get(); LDEBUG("Getting property '" + requestedKey + "'..."); nlohmann::json response; if (requestedKey == AllPropertiesValue) { @@ -80,7 +80,7 @@ bool GetPropertyTopic::isDone() const { } json GetPropertyTopic::allProperties() { - json payload { + const json payload { { "value", { @@ -100,7 +100,7 @@ json GetPropertyTopic::propertyFromKey(const std::string& key) { return wrappedPayload(prop); } - return wrappedError(fmt::format("Property '{}' not found", key), 404); + return wrappedError(std::format("Property '{}' not found", key), 404); } } // namespace openspace diff --git a/modules/server/src/topics/luascripttopic.cpp b/modules/server/src/topics/luascripttopic.cpp index b7d492279b..bb0ac24bd4 100644 --- a/modules/server/src/topics/luascripttopic.cpp +++ b/modules/server/src/topics/luascripttopic.cpp @@ -73,7 +73,7 @@ namespace { std::string formatObjectAsLuaTable(const nlohmann::json& json) { std::string output = "{"; auto it = json.begin(); - for (size_t i = 0; i < json.size(); ++i, ++it) { + for (size_t i = 0; i < json.size(); i++, it++) { output += formatKeyValuePair(it); if (i < json.size() - 1) { output += ","; @@ -85,7 +85,7 @@ namespace { std::string formatArrayAsLuaTable(const nlohmann::json& json) { std::string output = "{"; auto it = json.begin(); - for (size_t i = 0; i < json.size(); ++i, ++it) { + for (size_t i = 0; i < json.size(); i++, it++) { output += formatLua(it); if (i < json.size() - 1) { output += ","; @@ -102,7 +102,7 @@ namespace { return formatArrayAsLuaTable(it->get()); } if (it->is_number()) { - return fmt::format("{}", it->get()); + return std::format("{}", it->get()); } if (it->is_string()) { return formatLuaString(it->get()); @@ -121,7 +121,7 @@ namespace { { std::string script = "return " + function + "("; auto it = args.begin(); - for (size_t i = 0; i < args.size(); ++i, ++it) { + for (size_t i = 0; i < args.size(); i++, it++) { script += *it; if (i < args.size() - 1) { script += ","; @@ -137,50 +137,48 @@ namespace openspace { void LuaScriptTopic::handleJson(const nlohmann::json& json) { try { - nlohmann::json::const_iterator script = json.find(KeyScript); - nlohmann::json::const_iterator function = json.find(KeyFunction); + const auto script = json.find(KeyScript); + const auto function = json.find(KeyFunction); if (script != json.end() && script->is_string()) { std::string luaScript = script->get(); - nlohmann::json::const_iterator ret = json.find(KeyReturn); - bool shouldReturn = (ret != json.end()) && - ret->is_boolean() && - ret->get(); + const auto ret = json.find(KeyReturn); + const bool shouldReturn = + (ret != json.end()) && ret->is_boolean() && ret->get(); - nlohmann::json::const_iterator sync = json.find(KeyShouldBeSynchronized); + const auto sync = json.find(KeyShouldBeSynchronized); bool shouldBeSynchronized = true; if (sync != json.end() && sync->is_boolean()) { shouldBeSynchronized = sync->get(); } - runScript(luaScript, shouldReturn, shouldBeSynchronized); + runScript(std::move(luaScript), shouldReturn, shouldBeSynchronized); } else if (function != json.end() && function->is_string()) { - std::string luaFunction = function->get(); - nlohmann::json::const_iterator ret = json.find(KeyReturn); - bool shouldReturn = (ret != json.end()) && - ret->is_boolean() && - ret->get(); + const std::string luaFunction = function->get(); + const auto ret = json.find(KeyReturn); + const bool shouldReturn = + (ret != json.end()) && ret->is_boolean() && ret->get(); - nlohmann::json::const_iterator sync = json.find(KeyShouldBeSynchronized); + const auto sync = json.find(KeyShouldBeSynchronized); bool shouldBeSynchronized = true; if (sync != json.end() && sync->is_boolean()) { shouldBeSynchronized = sync->get(); } - nlohmann::json::const_iterator args = json.find(KeyArguments); + const nlohmann::json::const_iterator args = json.find(KeyArguments); if (!args->is_array()) { return; } std::vector formattedArgs; formattedArgs.reserve(args->size()); - for (auto it = args->begin(); it != args->end(); ++it) { + for (auto it = args->begin(); it != args->end(); it++) { formattedArgs.push_back(formatLua(it)); } std::string luaScript = generateScript(luaFunction, formattedArgs); - runScript(luaScript, shouldReturn, shouldBeSynchronized); + runScript(std::move(luaScript), shouldReturn, shouldBeSynchronized); } } catch (const std::out_of_range& e) { @@ -194,10 +192,9 @@ void LuaScriptTopic::runScript(std::string script, bool shouldReturn, { scripting::ScriptEngine::ScriptCallback callback; if (shouldReturn) { - callback = [this](ghoul::Dictionary data) { + callback = [this](const ghoul::Dictionary& data) { if (_connection) { - nlohmann::json j = data; - nlohmann::json payload = wrappedPayload(j); + const nlohmann::json payload = wrappedPayload(data); _connection->sendJson(payload); _waitingForReturnValue = false; } diff --git a/modules/server/src/topics/missiontopic.cpp b/modules/server/src/topics/missiontopic.cpp index 09a9a82a53..51489775d3 100644 --- a/modules/server/src/topics/missiontopic.cpp +++ b/modules/server/src/topics/missiontopic.cpp @@ -45,7 +45,7 @@ nlohmann::json MissionTopic::missionJson() const { const std::map& missions = global::missionManager->missionMap(); - ImageSequencer& sequencer = ImageSequencer::ref(); + const ImageSequencer& sequencer = ImageSequencer::ref(); const std::vector& captureTimes = sequencer.captureProgression(); std::vector captureTimesString(captureTimes.size()); @@ -69,7 +69,7 @@ nlohmann::json MissionTopic::createPhaseJson(const MissionPhase& phase) const { json phases = json::array(); for (const MissionPhase& missionPhase : phase.phases()) { json subphaseJson = createPhaseJson(missionPhase); - phases.push_back(subphaseJson); + phases.push_back(std::move(subphaseJson)); } json milestones = json::array(); @@ -116,7 +116,7 @@ nlohmann::json MissionTopic::createPhaseJson(const MissionPhase& phase) const { } void MissionTopic::handleJson(const nlohmann::json&) { - nlohmann::json data = { {"missions", missionJson()} }; + const nlohmann::json data = { {"missions", missionJson()} }; _connection->sendJson(wrappedPayload(data)); } diff --git a/modules/server/src/topics/sessionrecordingtopic.cpp b/modules/server/src/topics/sessionrecordingtopic.cpp index cd9d660edb..5b785a3e48 100644 --- a/modules/server/src/topics/sessionrecordingtopic.cpp +++ b/modules/server/src/topics/sessionrecordingtopic.cpp @@ -78,7 +78,8 @@ void SessionRecordingTopic::handleJson(const nlohmann::json& json) { if (!json.at(PropertiesKey).is_array()) { LERROR("Properties must be an array of strings"); } - nlohmann::json requestedProperties = json.at(PropertiesKey).get(); + const nlohmann::json requestedProperties = + json.at(PropertiesKey).get(); for (const auto& p : requestedProperties) { if (!p.is_string()) { _isDone = true; @@ -100,7 +101,7 @@ void SessionRecordingTopic::handleJson(const nlohmann::json& json) { if (event == SubscribeEvent && _sendState) { _stateCallbackHandle = global::sessionRecording->addStateChangeCallback( [this]() { - interaction::SessionRecording::SessionState currentState = + const interaction::SessionRecording::SessionState currentState = global::sessionRecording->state(); if (currentState != _lastState) { sendJsonData(); @@ -113,9 +114,9 @@ void SessionRecordingTopic::handleJson(const nlohmann::json& json) { void SessionRecordingTopic::sendJsonData() { json stateJson; - using SessionRecording = openspace::interaction::SessionRecording; + using SessionRecording = interaction::SessionRecording; if (_sendState) { - SessionRecording::SessionState state = global::sessionRecording->state(); + const SessionRecording::SessionState state = global::sessionRecording->state(); std::string stateString; switch (state) { case SessionRecording::SessionState::Recording: diff --git a/modules/server/src/topics/setpropertytopic.cpp b/modules/server/src/topics/setpropertytopic.cpp index 182b6817c8..4c2d84612f 100644 --- a/modules/server/src/topics/setpropertytopic.cpp +++ b/modules/server/src/topics/setpropertytopic.cpp @@ -81,7 +81,7 @@ namespace { } std::string literal = "{"; - for (nlohmann::json::iterator it = value.begin(); it != value.end(); ++it) { + for (nlohmann::json::iterator it = value.begin(); it != value.end(); it++) { literal += luaLiteralFromJson(it.value()) += ","; } literal.pop_back(); // remove last comma @@ -94,7 +94,7 @@ namespace { } std::string literal = "{"; - for (nlohmann::json::iterator it = value.begin(); it != value.end(); ++it) { + for (nlohmann::json::iterator it = value.begin(); it != value.end(); it++) { literal += it.key() + "=" + luaLiteralFromJson(it.value()) += ","; } literal.pop_back(); // remove last comma @@ -119,11 +119,11 @@ void SetPropertyTopic::handleJson(const nlohmann::json& json) { global::timeManager->setTimeNextFrame(newTime); } else { - nlohmann::json value = json.at("value"); + const nlohmann::json value = json.at("value"); std::string literal = luaLiteralFromJson(value); global::scriptEngine->queueScript( - fmt::format( + std::format( "openspace.setPropertyValueSingle(\"{}\", {})", propertyKey, literal ), scripting::ScriptEngine::ShouldBeSynchronized::Yes, diff --git a/modules/server/src/topics/shortcuttopic.cpp b/modules/server/src/topics/shortcuttopic.cpp index a3ef7e12a2..7f99ec4d3f 100644 --- a/modules/server/src/topics/shortcuttopic.cpp +++ b/modules/server/src/topics/shortcuttopic.cpp @@ -55,7 +55,7 @@ std::vector ShortcutTopic::shortcutsJson() const { ); for (const interaction::Action& action : actions) { - nlohmann::json shortcutJson = { + const nlohmann::json shortcutJson = { { "identifier", action.identifier }, { "name", action.name }, { "script", action.command }, @@ -84,7 +84,7 @@ std::vector ShortcutTopic::shortcutsJson() const { keyBinding.second ); - nlohmann::json shortcutJson = { + const nlohmann::json shortcutJson = { { "key", ghoul::to_string(k.key) }, { "modifiers", { @@ -102,7 +102,7 @@ std::vector ShortcutTopic::shortcutsJson() const { } void ShortcutTopic::sendData() const { - nlohmann::json data = { {"shortcuts", shortcutsJson()} }; + const nlohmann::json data = { {"shortcuts", shortcutsJson()} }; _connection->sendJson(wrappedPayload(data)); } diff --git a/modules/server/src/topics/skybrowsertopic.cpp b/modules/server/src/topics/skybrowsertopic.cpp index 28d04402c1..b4432b7bb7 100644 --- a/modules/server/src/topics/skybrowsertopic.cpp +++ b/modules/server/src/topics/skybrowsertopic.cpp @@ -66,7 +66,7 @@ bool SkyBrowserTopic::isDone() const { } void SkyBrowserTopic::handleJson(const nlohmann::json& json) { - std::string event = json.at("event").get(); + const std::string event = json.at("event").get(); if (event == UnsubscribeEvent) { _isDone = true; return; @@ -80,7 +80,7 @@ void SkyBrowserTopic::handleJson(const nlohmann::json& json) { ServerModule* module = global::moduleEngine->module(); _targetDataCallbackHandle = module->addPreSyncCallback( [this]() { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); if (now - _lastUpdateTime > _skyBrowserUpdateTime) { sendBrowserData(); _lastUpdateTime = std::chrono::system_clock::now(); @@ -104,8 +104,8 @@ void SkyBrowserTopic::sendBrowserData() { const std::vector>& pairs = module->pairs(); ghoul::Dictionary targets; for (const std::unique_ptr& pair : pairs) { - std::string id = pair->browserId(); - ghoul::Dictionary target = pair->dataAsDictionary(); + const std::string id = pair->browserId(); + const ghoul::Dictionary target = pair->dataAsDictionary(); targets.setValue(id, target); } data.setValue("browsers", targets); @@ -115,7 +115,7 @@ void SkyBrowserTopic::sendBrowserData() { // Only send message if data actually changed if (jsonString != _lastUpdateJsonString) { - json jsonData = json::parse(jsonString.begin(), jsonString.end()); + const json jsonData = json::parse(jsonString.begin(), jsonString.end()); _connection->sendJson(wrappedPayload(jsonData)); } diff --git a/modules/server/src/topics/subscriptiontopic.cpp b/modules/server/src/topics/subscriptiontopic.cpp index 0eba60161c..383f695e9f 100644 --- a/modules/server/src/topics/subscriptiontopic.cpp +++ b/modules/server/src/topics/subscriptiontopic.cpp @@ -92,7 +92,7 @@ void SubscriptionTopic::handleJson(const nlohmann::json& json) { onChange(); } else { - LWARNING(fmt::format("Could not subscribe. Property '{}' not found", key)); + LWARNING(std::format("Could not subscribe. Property '{}' not found", key)); } } if (event == StopSubscription) { diff --git a/modules/server/src/topics/timetopic.cpp b/modules/server/src/topics/timetopic.cpp index 5496a0d29c..f34caff483 100644 --- a/modules/server/src/topics/timetopic.cpp +++ b/modules/server/src/topics/timetopic.cpp @@ -64,7 +64,7 @@ bool TimeTopic::isDone() const { } void TimeTopic::handleJson(const nlohmann::json& json) { - std::string event = json.at("event").get(); + const std::string event = json.at("event").get(); if (event == UnsubscribeEvent) { _isDone = true; return; @@ -79,7 +79,7 @@ void TimeTopic::handleJson(const nlohmann::json& json) { } _timeCallbackHandle = global::timeManager->addTimeChangeCallback([this]() { - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); if (now - _lastUpdateTime > TimeUpdateInterval) { sendCurrentTime(); } @@ -89,7 +89,7 @@ void TimeTopic::handleJson(const nlohmann::json& json) { // Throttle by last update, // but force update if pause state or target delta changes. - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); const double targetDeltaTime = global::timeManager->targetDeltaTime(); const bool isPaused = global::timeManager->isPaused(); const bool forceUpdate = @@ -110,7 +110,7 @@ void TimeTopic::handleJson(const nlohmann::json& json) { ); } -const json TimeTopic::getNextPrevDeltaTimeStepJson() { +json TimeTopic::getNextPrevDeltaTimeStepJson() { const std::optional nextStep = global::timeManager->nextDeltaTimeStep(); const std::optional prevStep = global::timeManager->previousDeltaTimeStep(); const bool hasNext = nextStep.has_value(); diff --git a/modules/server/src/topics/triggerpropertytopic.cpp b/modules/server/src/topics/triggerpropertytopic.cpp index a7d4e00445..c20f0afdfa 100644 --- a/modules/server/src/topics/triggerpropertytopic.cpp +++ b/modules/server/src/topics/triggerpropertytopic.cpp @@ -41,7 +41,7 @@ void TriggerPropertyTopic::handleJson(const nlohmann::json& json) { try { const std::string& propertyKey = json.at("property").get(); global::scriptEngine->queueScript( - fmt::format( + std::format( "openspace.setPropertyValueSingle(\"{}\", nil)", propertyKey ), scripting::ScriptEngine::ShouldBeSynchronized::Yes, diff --git a/modules/skybrowser/include/browser.h b/modules/skybrowser/include/browser.h index 32348a24ac..900afc2ae9 100644 --- a/modules/skybrowser/include/browser.h +++ b/modules/skybrowser/include/browser.h @@ -100,9 +100,9 @@ private: void setTexture(GLuint t); }; - std::unique_ptr _browserInstance; CefRefPtr _renderHandler; CefRefPtr _keyboardHandler; + std::unique_ptr _browserInstance; }; } // namespace openspace diff --git a/modules/skybrowser/include/targetbrowserpair.h b/modules/skybrowser/include/targetbrowserpair.h index 48b265eedb..04366b6d12 100644 --- a/modules/skybrowser/include/targetbrowserpair.h +++ b/modules/skybrowser/include/targetbrowserpair.h @@ -45,7 +45,7 @@ public: void initialize(); // Animation - void startAnimation(glm::dvec3 coordsEnd, double fovEnd); + void startAnimation(glm::dvec3 galacticCoords, double fovEnd); void incrementallyAnimateToCoordinate(); void startFading(float goal, float fadeTime); void stopAnimations(); diff --git a/modules/skybrowser/include/utility.h b/modules/skybrowser/include/utility.h index 170cefc93f..bb4ddbc3a2 100644 --- a/modules/skybrowser/include/utility.h +++ b/modules/skybrowser/include/utility.h @@ -200,7 +200,7 @@ glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& * \param worldPosition The galactic position of the plane * \return Field of view */ -double sizeFromFov(double fov, glm::dvec3 worldPosition); +double sizeFromFov(double fov, const glm::dvec3& worldPosition); template class Animation { diff --git a/modules/skybrowser/include/wwtcommunicator.h b/modules/skybrowser/include/wwtcommunicator.h index d62bb26c70..082486bf09 100644 --- a/modules/skybrowser/include/wwtcommunicator.h +++ b/modules/skybrowser/include/wwtcommunicator.h @@ -71,7 +71,7 @@ public: protected: void setIdInBrowser(const std::string& id) const; - SelectedImageDeque::iterator findSelectedImage(const std::string& id); + SelectedImageDeque::iterator findSelectedImage(const std::string& imageUrl); properties::DoubleProperty _verticalFov; diff --git a/modules/skybrowser/skybrowsermodule.cpp b/modules/skybrowser/skybrowsermodule.cpp index 3b3f852a53..693d9566ea 100644 --- a/modules/skybrowser/skybrowsermodule.cpp +++ b/modules/skybrowser/skybrowsermodule.cpp @@ -211,10 +211,10 @@ SkyBrowserModule::SkyBrowserModule() constexpr double SolarSystemRadius = 30.0 * distanceconstants::AstronomicalUnit; // Disable browser and targets when camera is outside of solar system - bool camWasInSolarSystem = _isCameraInSolarSystem; - glm::dvec3 cameraPos = global::navigationHandler->camera()->positionVec3(); + const bool camWasInSolarSystem = _isCameraInSolarSystem; + const glm::dvec3 cameraPos = global::navigationHandler->camera()->positionVec3(); _isCameraInSolarSystem = glm::length(cameraPos) < SolarSystemRadius; - bool vizModeChanged = _isCameraInSolarSystem != camWasInSolarSystem; + const bool vizModeChanged = _isCameraInSolarSystem != camWasInSolarSystem; // Visualization mode changed. Start fading in/out if (vizModeChanged) { @@ -350,7 +350,7 @@ void SkyBrowserModule::moveHoverCircle(const std::string& imageUrl, bool useScri // Show the circle if (useScript) { - const std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValueSingle('Scene.{}.Renderable.Fade', 1.0);", id ); @@ -374,7 +374,7 @@ void SkyBrowserModule::moveHoverCircle(const std::string& imageUrl, bool useScri pos *= skybrowser::CelestialSphereRadius * 1.1; // Note that the position can only be set through the script engine - const std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValueSingle('Scene.{}.Translation.Position', {});", id, ghoul::to_string(pos) ); @@ -388,7 +388,7 @@ void SkyBrowserModule::moveHoverCircle(const std::string& imageUrl, bool useScri void SkyBrowserModule::disableHoverCircle(bool useScript) { if (_hoverCircle && _hoverCircle->renderable()) { if (useScript) { - const std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValueSingle('Scene.{}.Renderable.Fade', 0.0);", _hoverCircle->identifier() ); @@ -439,23 +439,23 @@ TargetBrowserPair* SkyBrowserModule::pair(std::string_view id) const { ); TargetBrowserPair* found = it != _targetsBrowsers.end() ? it->get() : nullptr; if (found == nullptr) { - LINFO(fmt::format("Identifier '{}' not found", id)); + LINFO(std::format("Identifier '{}' not found", id)); } return found; } -void SkyBrowserModule::startRotatingCamera(glm::dvec3 endAnimation) { +void SkyBrowserModule::startRotatingCamera(const glm::dvec3& endAnimation) { // Save coordinates to rotate to in galactic world coordinates - glm::dvec3 start = skybrowser::cameraDirectionGalactic(); - double angle = skybrowser::angleBetweenVectors(start, endAnimation); - double time = angle / _cameraRotationSpeed; + const glm::dvec3 start = skybrowser::cameraDirectionGalactic(); + const double angle = skybrowser::angleBetweenVectors(start, endAnimation); + const double time = angle / _cameraRotationSpeed; _cameraRotation = skybrowser::Animation(start, endAnimation, time); _cameraRotation.start(); } void SkyBrowserModule::incrementallyRotateCamera() { if (_cameraRotation.isAnimating()) { - glm::dmat4 rotMat = _cameraRotation.rotationMatrix(); + const glm::dmat4 rotMat = _cameraRotation.rotationMatrix(); global::navigationHandler->camera()->rotate(glm::quat_cast(rotMat)); } } diff --git a/modules/skybrowser/skybrowsermodule.h b/modules/skybrowser/skybrowsermodule.h index 97b44fa65f..b194768f83 100644 --- a/modules/skybrowser/skybrowsermodule.h +++ b/modules/skybrowser/skybrowsermodule.h @@ -60,7 +60,9 @@ public: // Rotation, animation, placement void lookAtTarget(const std::string& id); - void startRotatingCamera(glm::dvec3 endAnimation); // Pass in galactic coordinate + + // Pass in galactic coordinate + void startRotatingCamera(const glm::dvec3& endAnimation); double targetAnimationSpeed() const; double browserAnimationSpeed() const; double spaceCraftAnimationTime() const; @@ -72,7 +74,7 @@ public: bool isSelectedPairUsingRae() const; // Managing the target browser pairs - void removeTargetBrowserPair(const std::string& browserId); + void removeTargetBrowserPair(const std::string& id); void addTargetBrowserPair(const std::string& targetId, const std::string& browserId); // Hover circle diff --git a/modules/skybrowser/skybrowsermodule_lua.inl b/modules/skybrowser/skybrowsermodule_lua.inl index b085b52df0..f5894e5fba 100644 --- a/modules/skybrowser/skybrowsermodule_lua.inl +++ b/modules/skybrowser/skybrowsermodule_lua.inl @@ -35,7 +35,7 @@ #include #include #include -#include +#include namespace { constexpr std::string_view _loggerCat = "SkyBrowserModule"; @@ -111,8 +111,8 @@ std::string prunedIdentifier(std::string identifier) { imageUrl ); if (!found.has_value()) { - LINFO(fmt::format( - "No image with identifier {} was found in the collection.", imageUrl + LINFO(std::format( + "No image with identifier '{}' was found in the collection.", imageUrl )); return; } @@ -160,8 +160,8 @@ std::string prunedIdentifier(std::string identifier) { SceneGraphNode* circle = global::renderEngine->scene()->sceneGraphNode(identifier); if (!circle) { - throw ghoul::lua::LuaError(fmt::format( - "Could not find node to set as hover circle: '{}'", identifier + throw ghoul::lua::LuaError(std::format( + "Could not find node to set as hover circle: {}", identifier )); } @@ -242,7 +242,7 @@ std::string prunedIdentifier(std::string identifier) { for (const std::unique_ptr& pair : pairs) { std::string id = pair->browserId(); glm::ivec3 color = pair->borderColor(); - std::string script = fmt::format( + std::string script = std::format( "openspace.skybrowser.setBorderColor('{}', {}, {}, {})", id, color.r, color.g, color.b ); diff --git a/modules/skybrowser/src/browser.cpp b/modules/skybrowser/src/browser.cpp index 7cf5b127c6..333f840c50 100644 --- a/modules/skybrowser/src/browser.cpp +++ b/modules/skybrowser/src/browser.cpp @@ -92,6 +92,11 @@ Browser::Browser(const ghoul::Dictionary& dictionary) ) , _url(UrlInfo) , _reload(ReloadInfo) + , _renderHandler(new RenderHandler) + , _keyboardHandler(new WebKeyboardHandler) + , _browserInstance( + std::make_unique(_renderHandler.get(), _keyboardHandler.get()) + ) { const Parameters p = codegen::bake(dictionary); @@ -104,8 +109,6 @@ Browser::Browser(const ghoul::Dictionary& dictionary) _reload.onChange([this]() { _shouldReload = true; }); // Create browser and render handler - _renderHandler = new RenderHandler(); - _keyboardHandler = new WebKeyboardHandler(); _browserInstance = std::make_unique( _renderHandler.get(), _keyboardHandler.get() @@ -139,7 +142,7 @@ void Browser::deinitializeGL() { _texture = nullptr; - LDEBUG(fmt::format("Deinitializing browser: {}", _url.value())); + LDEBUG(std::format("Deinitializing browser '{}'", _url.value())); _browserInstance->close(true); @@ -189,10 +192,12 @@ void Browser::reload() { } void Browser::setRatio(float ratio) { - float relativeRatio = ratio / browserRatio(); - float newX = static_cast(_browserDimensions.value().x) * relativeRatio; - glm::ivec2 newDims = { static_cast(floor(newX)), _browserDimensions.value().y }; - _browserDimensions = newDims; + const float relativeRatio = ratio / browserRatio(); + const float newX = static_cast(_browserDimensions.value().x) * relativeRatio; + _browserDimensions = { + static_cast(std::floor(newX)), + _browserDimensions.value().y + }; _isDimensionsDirty = true; } @@ -202,7 +207,7 @@ float Browser::browserRatio() const { } void Browser::updateBrowserDimensions() { - glm::ivec2 dim = _browserDimensions; + const glm::ivec2 dim = _browserDimensions; if (dim.x > 0 && dim.y > 0) { _texture->setDimensions(glm::uvec3(_browserDimensions.value(), 1)); _browserInstance->reshape(dim); @@ -212,11 +217,12 @@ void Browser::updateBrowserDimensions() { void Browser::executeJavascript(const std::string& script) const { // Make sure that the browser has a main frame - bool browserExists = _browserInstance && _browserInstance->getBrowser(); - bool frameIsLoaded = browserExists && _browserInstance->getBrowser()->GetMainFrame(); + const bool browserExists = _browserInstance && _browserInstance->getBrowser(); + const bool frameIsLoaded = + browserExists && _browserInstance->getBrowser()->GetMainFrame(); if (frameIsLoaded) { - CefRefPtr frame = _browserInstance->getBrowser()->GetMainFrame(); + const CefRefPtr frame = _browserInstance->getBrowser()->GetMainFrame(); frame->ExecuteJavaScript(script, frame->GetURL(), 0); } } diff --git a/modules/skybrowser/src/renderableskytarget.cpp b/modules/skybrowser/src/renderableskytarget.cpp index c28f1b1cc9..48d39e287e 100644 --- a/modules/skybrowser/src/renderableskytarget.cpp +++ b/modules/skybrowser/src/renderableskytarget.cpp @@ -173,20 +173,20 @@ glm::ivec3 RenderableSkyTarget::borderColor() const { } glm::dvec3 RenderableSkyTarget::rightVector() const { - double scaling = - (_verticalFov / 70) * static_cast(glm::compMax(_size.value())); + const double scaling = + (_verticalFov / 70.0) * static_cast(glm::compMax(_size.value())); return scaling * _rightVector; } glm::dvec3 RenderableSkyTarget::upVector() const { - double scaling = - (_verticalFov / 70) * static_cast(glm::compMax(_size.value())); + const double scaling = + (_verticalFov / 70.0) * static_cast(glm::compMax(_size.value())); return scaling * _upVector; } void RenderableSkyTarget::applyRoll() { Camera* camera = global::navigationHandler->camera(); - glm::dvec3 normal = glm::normalize(camera->positionVec3() - _worldPosition); + const glm::dvec3 normal = glm::normalize(camera->positionVec3() - _worldPosition); _rightVector = glm::normalize( glm::cross(camera->lookUpVectorWorldSpace(), normal) @@ -198,7 +198,7 @@ void RenderableSkyTarget::render(const RenderData& data, RendererTasks&) { ZoneScoped; const bool showRectangle = _verticalFov > _showRectangleThreshold; - glm::vec4 color = glm::vec4(glm::vec3(_borderColor) / 255.f, 1.0); + const glm::vec4 color = glm::vec4(glm::vec3(_borderColor) / 255.f, 1.0); _shader->activate(); _shader->setUniform("opacity", opacity()); @@ -216,7 +216,7 @@ void RenderableSkyTarget::render(const RenderData& data, RendererTasks&) { data.modelTransform.translation) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); - glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - _worldPosition); + const glm::dvec3 normal = glm::normalize(data.camera.positionVec3() - _worldPosition); // There are two modes - 1) target rolls to have its up vector parallel to the // cameras up vector or 2) it is decoupled from the camera, in which case it needs to // be initialized once @@ -253,7 +253,7 @@ void RenderableSkyTarget::render(const RenderData& data, RendererTasks&) { _shader->setUniform("multiplyColor", _multiplyColor); - bool additiveBlending = (_blendMode == static_cast(BlendMode::Additive)); + const bool additiveBlending = _blendMode == static_cast(BlendMode::Additive); if (additiveBlending) { glDepthMask(false); glBlendFunc(GL_SRC_ALPHA, GL_ONE); diff --git a/modules/skybrowser/src/screenspaceskybrowser.cpp b/modules/skybrowser/src/screenspaceskybrowser.cpp index 30125c257f..ebe5db7eb8 100644 --- a/modules/skybrowser/src/screenspaceskybrowser.cpp +++ b/modules/skybrowser/src/screenspaceskybrowser.cpp @@ -113,11 +113,10 @@ namespace { std::uniform_real_distribution hue(0.f, 360.f); // Value in saturation are in the unit percent [0,1] - float value = 0.9f; // Brightness - float saturation = 0.5f; - glm::vec3 hsvColor = glm::vec3(hue(rd), saturation, value); - glm::ivec3 rgbColor = glm::ivec3(glm::rgbColor(hsvColor) * 255.f); - + constexpr float Value = 0.9f; // Brightness + constexpr float Saturation = 0.5f; + const glm::vec3 hsvColor = glm::vec3(hue(rd), Saturation, Value); + const glm::ivec3 rgbColor = glm::ivec3(glm::rgbColor(hsvColor) * 255.f); return rgbColor; } } // namespace @@ -140,6 +139,7 @@ ScreenSpaceSkyBrowser::ScreenSpaceSkyBrowser(const ghoul::Dictionary& dictionary // Handle target dimension property const Parameters p = codegen::bake(dictionary); + _textureQuality = p.textureQuality.value_or(_textureQuality); _isHidden = p.isHidden.value_or(_isHidden); _isPointingSpacecraft = p.pointSpacecraft.value_or(_isPointingSpacecraft); @@ -194,16 +194,16 @@ bool ScreenSpaceSkyBrowser::initializeGL() { glm::dvec2 ScreenSpaceSkyBrowser::fineTuneVector(const glm::dvec2& drag) { // Fine tuning of target - glm::dvec2 wwtFov = fieldsOfView(); - glm::dvec2 openSpaceFOV = skybrowser::fovWindow(); + const glm::dvec2 wwtFov = fieldsOfView(); + const glm::dvec2 openSpaceFOV = skybrowser::fovWindow(); - glm::dvec2 browserDim = screenSpaceDimensions(); - glm::dvec2 angleResult = wwtFov * (drag / browserDim); - glm::dvec2 resultRelativeOs = angleResult / openSpaceFOV; + const glm::dvec2 browserDim = screenSpaceDimensions(); + const glm::dvec2 angleResult = wwtFov * (drag / browserDim); + const glm::dvec2 resultRelativeOs = angleResult / openSpaceFOV; // Convert to screen space coordinate system - glm::dvec2 convertToScreenSpace = glm::dvec2((2.f * skybrowser::windowRatio()), 2.f); - glm::dvec2 result = -convertToScreenSpace * resultRelativeOs; + const glm::dvec2 screenSpace = glm::dvec2((2.f * skybrowser::windowRatio()), 2.f); + const glm::dvec2 result = -screenSpace * resultRelativeOs; return result; } @@ -221,7 +221,7 @@ bool ScreenSpaceSkyBrowser::shouldUpdateWhileTargetAnimates() const { void ScreenSpaceSkyBrowser::setIdInBrowser() const { int currentNode = global::windowDelegate->currentNode(); - WwtCommunicator::setIdInBrowser(fmt::format("{}_{}", identifier(), currentNode)); + WwtCommunicator::setIdInBrowser(std::format("{}_{}", identifier(), currentNode)); } void ScreenSpaceSkyBrowser::setIsInitialized(bool isInitialized) { @@ -235,9 +235,9 @@ void ScreenSpaceSkyBrowser::setPointSpaceCraft(bool shouldPoint) { void ScreenSpaceSkyBrowser::updateTextureResolution() { // Check if texture quality has changed. If it has, adjust accordingly if (std::abs(_textureQuality.value() - _lastTextureQuality) > glm::epsilon()) { - float diffTextureQuality = _textureQuality / _lastTextureQuality; - glm::vec2 newRes = glm::vec2(_browserDimensions.value()) * diffTextureQuality; - _browserDimensions = glm::ivec2(newRes); + const float diffTextureQuality = _textureQuality / _lastTextureQuality; + const glm::vec2 res = glm::vec2(_browserDimensions.value()) * diffTextureQuality; + _browserDimensions = glm::ivec2(res); _lastTextureQuality = _textureQuality.value(); } _objectSize = glm::ivec3(_browserDimensions.value(), 1); @@ -248,12 +248,14 @@ void ScreenSpaceSkyBrowser::updateTextureResolution() { } void ScreenSpaceSkyBrowser::addDisplayCopy(const glm::vec3& raePosition, int nCopies) { - size_t start = _displayCopies.size(); + const size_t start = _displayCopies.size(); for (int i = 0; i < nCopies; i++) { openspace::properties::Property::PropertyInfo info = DisplayCopyInfo; - float azimuth = i * glm::two_pi() / nCopies; - glm::vec3 position = raePosition + glm::vec3(0.f, azimuth, 0.f); - std::string idDisplayCopy = "DisplayCopy" + std::to_string(start + i); + const float azimuth = i * glm::two_pi() / nCopies; + const glm::vec3 position = raePosition + glm::vec3(0.f, azimuth, 0.f); + // @TODO(abock) I think the lifetime for this string is a bit tricky. I don't + // think it will live long enough to be actually usable + const std::string idDisplayCopy = "DisplayCopy" + std::to_string(start + i); info.identifier = idDisplayCopy.c_str(); _displayCopies.push_back( std::make_unique( @@ -264,13 +266,12 @@ void ScreenSpaceSkyBrowser::addDisplayCopy(const glm::vec3& raePosition, int nCo ) ); openspace::properties::Property::PropertyInfo showInfo = DisplayCopyShowInfo; - std::string idDisplayCopyVisible = "ShowDisplayCopy" + std::to_string(start + i); - showInfo.identifier = idDisplayCopyVisible.c_str(); + // @TODO(abock) I think the lifetime for this string is a bit tricky. I don't + // think it will live long enough to be actually usable + const std::string idDispCpyVis = "ShowDisplayCopy" + std::to_string(start + i); + showInfo.identifier = idDispCpyVis.c_str(); _showDisplayCopies.push_back( - std::make_unique( - showInfo, - true - ) + std::make_unique(showInfo, true) ); addProperty(_displayCopies.back().get()); addProperty(_showDisplayCopies.back().get()); @@ -290,9 +291,9 @@ std::vector> ScreenSpaceSkyBrowser::displayCopies() const { std::vector> vec; - using vec3Property = std::unique_ptr; - for (const vec3Property& copy : _displayCopies) { - vec.push_back({ copy->identifier(), copy->value() }); + vec.reserve(_displayCopies.size()); + for (const std::unique_ptr& copy : _displayCopies) { + vec.emplace_back(copy->identifier(), copy->value()); } return vec; } @@ -301,9 +302,9 @@ std::vector> ScreenSpaceSkyBrowser::showDisplayCopies() const { std::vector> vec; - using boolProperty = std::unique_ptr; - for (const boolProperty& copy : _showDisplayCopies) { - vec.push_back({copy->identifier(), copy->value()}); + vec.reserve(_showDisplayCopies.size()); + for (const std::unique_ptr& copy : _showDisplayCopies) { + vec.emplace_back(copy->identifier(), copy->value()); } return vec; } @@ -318,7 +319,7 @@ void ScreenSpaceSkyBrowser::render(float blackoutFactor) { WwtCommunicator::render(); if (!_isHidden) { - glm::mat4 mat = + const glm::mat4 mat = globalRotationMatrix() * translationMatrix() * localRotationMatrix() * @@ -342,7 +343,7 @@ void ScreenSpaceSkyBrowser::render(float blackoutFactor) { )); } - glm::mat4 mat = + const glm::mat4 mat = globalRotationMatrix() * glm::translate(glm::mat4(1.f), coordinates) * localRotation * @@ -375,10 +376,12 @@ void ScreenSpaceSkyBrowser::update() { double ScreenSpaceSkyBrowser::setVerticalFovWithScroll(float scroll) { // Make scroll more sensitive the smaller the FOV - double x = _verticalFov; - double zoomFactor = atan(x / 50.0) + exp(x / 40.0) - 0.99999999999999999999999999999; - double zoom = scroll > 0.0 ? zoomFactor : -zoomFactor; + const double x = _verticalFov; + const double zoomFactor = + atan(x / 50.0) + exp(x / 40.0) - 0.99999999999999999999999999999; + const double zoom = scroll > 0.0 ? zoomFactor : -zoomFactor; _verticalFov = std::clamp(_verticalFov + zoom, 0.0, 70.0); + return _verticalFov; } diff --git a/modules/skybrowser/src/targetbrowserpair.cpp b/modules/skybrowser/src/targetbrowserpair.cpp index d375948d91..acd3430e92 100644 --- a/modules/skybrowser/src/targetbrowserpair.cpp +++ b/modules/skybrowser/src/targetbrowserpair.cpp @@ -41,11 +41,11 @@ #include namespace { - void aimTargetGalactic(std::string id, glm::dvec3 direction) { - glm::dvec3 positionCelestial = glm::normalize(direction) * + void aimTargetGalactic(std::string_view id, const glm::dvec3& direction) { + const glm::dvec3 positionCelestial = glm::normalize(direction) * openspace::skybrowser::CelestialSphereRadius; - std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValueSingle('Scene.{}.Translation.Position', {});", id, ghoul::to_string(positionCelestial) ); @@ -83,16 +83,16 @@ void TargetBrowserPair::startFinetuningTarget() { // drag on the sky browser window. This is to be able to drag the target around when it // has a very small field of view void TargetBrowserPair::fineTuneTarget(const glm::vec2& translation) { - glm::dvec2 percentage = glm::dvec2(translation); - glm::dvec3 right = _targetRenderable->rightVector() * percentage.x; - glm::dvec3 up = _targetRenderable->upVector() * percentage.y; + const glm::dvec2 percentage = glm::dvec2(translation); + const glm::dvec3 right = _targetRenderable->rightVector() * percentage.x; + const glm::dvec3 up = _targetRenderable->upVector() * percentage.y; - glm::dvec3 newPosition = _startTargetPosition - (right - up); + const glm::dvec3 newPosition = _startTargetPosition - (right - up); aimTargetGalactic(_targetNode->identifier(), newPosition); } void TargetBrowserPair::synchronizeAim() { - bool shouldUpdate = + const bool shouldUpdate = _browser->shouldUpdateWhileTargetAnimates() || !_targetAnimation.isAnimating(); if (shouldUpdate && _browser->isInitialized()) { @@ -113,7 +113,7 @@ bool TargetBrowserPair::isEnabled() const { void TargetBrowserPair::initialize() { _targetRenderable->setColor(_browser->borderColor()); - glm::vec2 dim = _browser->screenSpaceDimensions(); + const glm::vec2 dim = _browser->screenSpaceDimensions(); _targetRenderable->setRatio(dim.x / dim.y); _browser->updateBorderColor(); _browser->hideChromeInterface(); @@ -125,7 +125,7 @@ glm::ivec3 TargetBrowserPair::borderColor() const { } glm::dvec2 TargetBrowserPair::targetDirectionEquatorial() const { - glm::dvec3 cartesian = skybrowser::galacticToEquatorial( + const glm::dvec3 cartesian = skybrowser::galacticToEquatorial( glm::normalize(_targetNode->worldPosition()) ); return skybrowser::cartesianToSpherical(cartesian); @@ -164,13 +164,13 @@ std::vector TargetBrowserPair::selectedImages() const { } ghoul::Dictionary TargetBrowserPair::dataAsDictionary() const { - glm::dvec2 spherical = targetDirectionEquatorial(); - glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical); + const glm::dvec2 spherical = targetDirectionEquatorial(); + const glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical); SkyBrowserModule* module = global::moduleEngine->module(); std::vector selectedImagesIndices; for (const std::string& imageUrl : selectedImages()) { - bool imageExists = module->wwtDataHandler().image(imageUrl).has_value(); + const bool imageExists = module->wwtDataHandler().image(imageUrl).has_value(); ghoul_assert(imageExists, "Image doesn't exist in the wwt catalog!"); selectedImagesIndices.push_back( module->wwtDataHandler().image(imageUrl)->identifier @@ -218,7 +218,9 @@ void TargetBrowserPair::selectImage(const ImageData& image) { // If the image has coordinates, move the target if (image.hasCelestialCoords) { // Animate the target to the image coordinate position - glm::dvec3 galactic = skybrowser::equatorialToGalactic(image.equatorialCartesian); + const glm::dvec3 galactic = skybrowser::equatorialToGalactic( + image.equatorialCartesian + ); startAnimation(galactic * skybrowser::CelestialSphereRadius, image.fov); } } @@ -279,7 +281,7 @@ void TargetBrowserPair::setBrowserRatio(float ratio) { } void TargetBrowserPair::setVerticalFovWithScroll(float scroll) { - double fov = _browser->setVerticalFovWithScroll(scroll); + const double fov = _browser->setVerticalFovWithScroll(scroll); _targetRenderable->setVerticalFov(fov); } @@ -320,7 +322,7 @@ void TargetBrowserPair::incrementallyAnimateToCoordinate() { } void TargetBrowserPair::startFading(float goal, float fadeTime) { - const std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValueSingle('Scene.{0}.Renderable.Fade', {2}, {3});" "openspace.setPropertyValueSingle('ScreenSpace.{1}.Fade', {2}, {3});", _targetNode->identifier(), _browser->identifier(), goal, fadeTime @@ -339,40 +341,42 @@ void TargetBrowserPair::stopAnimations() { } void TargetBrowserPair::startAnimation(glm::dvec3 galacticCoords, double fovEnd) { + using namespace skybrowser; + SkyBrowserModule* module = global::moduleEngine->module(); - double fovSpeed = module->browserAnimationSpeed(); + const double fovSpeed = module->browserAnimationSpeed(); // The speed is given degrees /sec - double fovTime = std::abs(_browser->verticalFov() - fovEnd) / fovSpeed; + const double fovTime = std::abs(_browser->verticalFov() - fovEnd) / fovSpeed; // Fov animation _fovAnimation = skybrowser::Animation(_browser->verticalFov(), fovEnd, fovTime); // Target animation - glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) * + const glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) * skybrowser::CelestialSphereRadius; - double targetSpeed = module->targetAnimationSpeed(); - double angle = skybrowser::angleBetweenVectors(start, galacticCoords); - _targetAnimation = skybrowser::Animation(start, galacticCoords, angle / targetSpeed); + const double targetSpeed = module->targetAnimationSpeed(); + const double angle = angleBetweenVectors(start, galacticCoords); + _targetAnimation = Animation(start, std::move(galacticCoords), angle / targetSpeed); _targetAnimation.start(); _targetIsAnimating = true; } void TargetBrowserPair::centerTargetOnScreen() { // Get camera direction in celestial spherical coordinates - glm::dvec3 viewDirection = skybrowser::cameraDirectionGalactic(); + const glm::dvec3 viewDirection = skybrowser::cameraDirectionGalactic(); // Keep the current fov - double currentFov = verticalFov(); + const double currentFov = verticalFov(); startAnimation(viewDirection, currentFov); } double TargetBrowserPair::targetRoll() const { // To remove the lag effect when moving the camera while having a locked // target, send the locked coordinates to wwt - glm::dvec3 normal = glm::normalize( + const glm::dvec3 normal = glm::normalize( _targetNode->worldPosition() - global::navigationHandler->camera()->positionVec3() ); - glm::dvec3 right = _targetRenderable->rightVector(); - glm::dvec3 up = glm::normalize(glm::cross(right, normal)); + const glm::dvec3 right = _targetRenderable->rightVector(); + const glm::dvec3 up = glm::normalize(glm::cross(right, normal)); return skybrowser::targetRoll(up, normal); } diff --git a/modules/skybrowser/src/utility.cpp b/modules/skybrowser/src/utility.cpp index 51812de1fe..b9e3923fa6 100644 --- a/modules/skybrowser/src/utility.cpp +++ b/modules/skybrowser/src/utility.cpp @@ -40,9 +40,9 @@ namespace { // Conversion matrix - J2000 equatorial <-> galactic // https://arxiv.org/abs/1010.3773v1 constexpr glm::dmat3 ConversionMatrix = glm::dmat3( - -0.054875539390, 0.494109453633, -0.867666135681, // col 0 + -0.054875539390, 0.494109453633, -0.867666135681, // col 0 -0.873437104725, -0.444829594298, -0.198076389622, // col 1 - -0.483834991775, 0.746982248696, 0.455983794523 // col 2 + -0.483834991775, 0.746982248696, 0.455983794523 // col 2 ); } // namespace @@ -50,9 +50,8 @@ namespace openspace::skybrowser { // Converts from spherical coordinates in the unit of degrees to cartesian coordianates glm::dvec3 sphericalToCartesian(const glm::dvec2& coords) { - glm::dvec2 coordsRadians = glm::radians(coords); - - glm::dvec3 cartesian = glm::dvec3( + const glm::dvec2 coordsRadians = glm::radians(coords); + const glm::dvec3 cartesian = glm::dvec3( cos(coordsRadians.x) * cos(coordsRadians.y), sin(coordsRadians.x) * cos(coordsRadians.y), sin(coordsRadians.y) @@ -62,14 +61,17 @@ glm::dvec3 sphericalToCartesian(const glm::dvec2& coords) { } // Converts from cartesian coordianates to spherical in the unit of degrees -glm::dvec2 cartesianToSpherical(const glm::dvec3& coord) { +glm::dvec2 cartesianToSpherical(const glm::dvec3& coords) { // Equatorial coordinates RA = right ascension, Dec = declination - double ra = atan2(coord.y, coord.x); - double dec = atan2(coord.z, glm::sqrt((coord.x * coord.x) + (coord.y * coord.y))); + double ra = atan2(coords.y, coords.x); + const double dec = atan2( + coords.z, + glm::sqrt((coords.x * coords.x) + (coords.y * coords.y)) + ); ra = ra > 0.0 ? ra : ra + glm::two_pi(); - glm::dvec2 celestialCoords = glm::dvec2(ra, dec); + const glm::dvec2 celestialCoords = glm::dvec2(ra, dec); return glm::degrees(celestialCoords); } @@ -79,31 +81,31 @@ glm::dvec3 galacticToEquatorial(const glm::dvec3& coords) { glm::dvec3 equatorialToGalactic(const glm::dvec3& coords) { // On the unit sphere - glm::dvec3 rGalactic = ConversionMatrix * glm::normalize(coords); + const glm::dvec3 rGalactic = ConversionMatrix * glm::normalize(coords); return rGalactic; } glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords) { // Ensure that if the coord is behind the camera, // the converted coordinate will be there too - double zCoord = coords.z > 0.0 ? -ScreenSpaceZ : ScreenSpaceZ; + const double zCoord = coords.z > 0.0 ? -ScreenSpaceZ : ScreenSpaceZ; // Calculate screen space coords x and y - double tanX = coords.x / coords.z; - double tanY = coords.y / coords.z; + const double tanX = coords.x / coords.z; + const double tanY = coords.y / coords.z; - glm::dvec3 screenSpace = glm::dvec3(zCoord * tanX, zCoord * tanY, zCoord); + const glm::dvec3 screenSpace = glm::dvec3(zCoord * tanX, zCoord * tanY, zCoord); return screenSpace; } glm::dvec3 localCameraToGalactic(const glm::dvec3& coords) { - glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); - glm::dvec4 coordsVec4 = glm::dvec4(coords, 1.0) ; - glm::dmat4 camMat = glm::inverse( + const glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); + const glm::dvec4 coordsVec4 = glm::dvec4(coords, 1.0) ; + const glm::dmat4 camMat = glm::inverse( global::navigationHandler->camera()->combinedViewMatrix() ); // Subtract camera position to get the view direction - glm::dvec3 galactic = glm::dvec3(camMat * coordsVec4) - camPos; + const glm::dvec3 galactic = glm::dvec3(camMat * coordsVec4) - camPos; return glm::normalize(galactic) * CelestialSphereRadius; } @@ -111,65 +113,66 @@ glm::dvec3 localCameraToGalactic(const glm::dvec3& coords) { glm::dvec3 localCameraToEquatorial(const glm::dvec3& coords) { // Calculate the galactic coordinate of the target direction // projected onto the celestial sphere - glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); - glm::dvec3 galactic = camPos + localCameraToGalactic(coords); + const glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); + const glm::dvec3 galactic = camPos + localCameraToGalactic(coords); return galacticToEquatorial(galactic); } glm::dvec3 equatorialToLocalCamera(const glm::dvec3& coords) { // Transform equatorial J2000 to galactic coord with infinite radius - glm::dvec3 galactic = equatorialToGalactic(coords) * CelestialSphereRadius; - glm::dvec3 localCamera = galacticToLocalCamera(galactic); + const glm::dvec3 galactic = equatorialToGalactic(coords) * CelestialSphereRadius; + const glm::dvec3 localCamera = galacticToLocalCamera(galactic); return localCamera; } glm::dvec3 galacticToLocalCamera(const glm::dvec3& coords) { // Transform vector to camera's local coordinate system - glm::dmat4 camMat = global::navigationHandler->camera()->combinedViewMatrix(); - glm::dvec3 viewDirectionLocal = camMat * glm::dvec4(coords, 1.0); + const glm::dmat4 camMat = global::navigationHandler->camera()->combinedViewMatrix(); + const glm::dvec3 viewDirectionLocal = camMat * glm::dvec4(coords, 1.0); return glm::normalize(viewDirectionLocal); } double targetRoll(const glm::dvec3& up, const glm::dvec3& forward) { constexpr glm::dvec3 NorthPole = glm::dvec3(0.0, 0.0, 1.0); - glm::dvec3 upJ2000 = galacticToEquatorial(up); - glm::dvec3 forwardJ2000 = galacticToEquatorial(forward); + const glm::dvec3 upJ2000 = galacticToEquatorial(up); + const glm::dvec3 forwardJ2000 = galacticToEquatorial(forward); - glm::dvec3 crossUpNorth = glm::cross(upJ2000, NorthPole); - double dotNorthUp = glm::dot(NorthPole, upJ2000); - double dotCrossUpNorthForward = glm::dot(crossUpNorth, forwardJ2000); + const glm::dvec3 crossUpNorth = glm::cross(upJ2000, NorthPole); + const double dotNorthUp = glm::dot(NorthPole, upJ2000); + const double dotCrossUpNorthForward = glm::dot(crossUpNorth, forwardJ2000); return glm::degrees(atan2(dotCrossUpNorthForward, dotNorthUp)); } glm::dvec3 cameraDirectionEquatorial() { // Get the view direction of the screen in cartesian J2000 coordinates - glm::dvec3 camDirGalactic = cameraDirectionGalactic(); + const glm::dvec3 camDirGalactic = cameraDirectionGalactic(); return galacticToEquatorial(camDirGalactic); } glm::dvec3 cameraDirectionGalactic() { // Get the view direction of the screen in galactic coordinates - glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); - glm::dvec3 view = global::navigationHandler->camera()->viewDirectionWorldSpace(); - glm::dvec3 galCoord = camPos + CelestialSphereRadius * view; + Camera* camera = global::navigationHandler->camera(); + const glm::dvec3 camPos = camera->positionVec3(); + const glm::dvec3 view = camera->viewDirectionWorldSpace(); + const glm::dvec3 galCoord = camPos + CelestialSphereRadius * view; return galCoord; } float windowRatio() { - glm::vec2 windowRatio = global::windowDelegate->currentWindowSize(); + const glm::vec2 windowRatio = global::windowDelegate->currentWindowSize(); return windowRatio.x / windowRatio.y; } bool isCoordinateInView(const glm::dvec3& equatorial) { // Check if image coordinate is within current FOV - glm::dvec3 localCamera = equatorialToLocalCamera(equatorial); - glm::dvec3 coordsScreen = localCameraToScreenSpace3d(localCamera); - double r = windowRatio(); + const glm::dvec3 localCamera = equatorialToLocalCamera(equatorial); + const glm::dvec3 coordsScreen = localCameraToScreenSpace3d(localCamera); + const double r = windowRatio(); - bool isCoordInView = + const bool isCoordInView = std::abs(coordsScreen.x) < r && std::abs(coordsScreen.y) < 1.f && coordsScreen.z < 0.f; @@ -178,7 +181,7 @@ bool isCoordinateInView(const glm::dvec3& equatorial) { // Transforms a pixel coordinate to a screen space coordinate glm::vec2 pixelToScreenSpace2d(const glm::vec2& mouseCoordinate) { - glm::vec2 size = glm::vec2(global::windowDelegate->currentWindowSize()); + const glm::vec2 size = glm::vec2(global::windowDelegate->currentWindowSize()); // Change origin to middle of the window glm::vec2 screenSpacePos = mouseCoordinate - (size / 2.f); // Ensure the upper right corner is positive on the y axis @@ -191,16 +194,16 @@ glm::vec2 pixelToScreenSpace2d(const glm::vec2& mouseCoordinate) { // The horizontal and vertical fov of the OpenSpace window glm::dvec2 fovWindow() { // OpenSpace FOV - glm::dvec2 windowDim = glm::dvec2(global::windowDelegate->currentWindowSize()); - double ratio = windowDim.y / windowDim.x; - double hFov = global::windowDelegate->getHorizFieldOfView(); - glm::dvec2 OpenSpaceFOV = glm::dvec2(hFov, hFov * ratio); + const glm::dvec2 windowDim = glm::dvec2(global::windowDelegate->currentWindowSize()); + const double ratio = windowDim.y / windowDim.x; + const double hFov = global::windowDelegate->getHorizFieldOfView(); + const glm::dvec2 OpenSpaceFOV = glm::dvec2(hFov, hFov * ratio); return OpenSpaceFOV; } double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end) { // Find smallest angle between the two vectors - double cos = glm::dot(glm::normalize(start), glm::normalize(end)); + const double cos = glm::dot(glm::normalize(start), glm::normalize(end)); // Ensure cos is within defined interval [-1,1] return std::acos(std::clamp(cos, -1.0, 1.0)); } @@ -208,23 +211,23 @@ double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end) { glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, double percentage) { - double smallestAngle = angleBetweenVectors(start, end); + const double smallestAngle = angleBetweenVectors(start, end); // Calculate rotation this frame - double rotationAngle = smallestAngle * percentage; + const double rotationAngle = smallestAngle * percentage; // Create the rotation matrix - glm::dvec3 rotationAxis = glm::normalize(glm::cross(start, end)); + const glm::dvec3 rotationAxis = glm::normalize(glm::cross(start, end)); return glm::rotate(rotationAngle, rotationAxis); } -double sizeFromFov(double fov, glm::dvec3 worldPosition) { +double sizeFromFov(double fov, const glm::dvec3& worldPosition) { // Calculate the size with trigonometry // /| // /_| Adjacent is the horizontal line, opposite the vertical // \ | Calculate for half the triangle first, then multiply with 2 // \| - double adjacent = glm::length(worldPosition); - double opposite = 2.0 * adjacent * glm::tan(glm::radians(fov * 0.5)); + const double adjacent = glm::length(worldPosition); + const double opposite = 2.0 * adjacent * glm::tan(glm::radians(fov * 0.5)); return opposite; } @@ -234,8 +237,8 @@ double Animation::newValue() const { return _goal; } else { - double percentage = percentageSpent(); - double diff = (_goal - _start) * ghoul::exponentialEaseOut(percentage); + const double percentage = percentageSpent(); + const double diff = (_goal - _start) * ghoul::exponentialEaseOut(percentage); return _start + diff; } } @@ -246,8 +249,8 @@ glm::dmat4 Animation::rotationMatrix() { return glm::dmat4(1.0); } - double percentage = ghoul::sineEaseInOut(percentageSpent()); - double increment = percentage - _lastPercentage; + const double percentage = ghoul::sineEaseInOut(percentageSpent()); + const double increment = percentage - _lastPercentage; _lastPercentage = percentage; glm::dmat4 rotMat = skybrowser::incrementalAnimationMatrix( @@ -263,7 +266,7 @@ glm::dvec3 Animation::newValue() const { if (!isAnimating()) { return _goal; } - glm::dmat4 rotMat = skybrowser::incrementalAnimationMatrix( + const glm::dmat4 rotMat = skybrowser::incrementalAnimationMatrix( glm::normalize(_start), glm::normalize(_goal), ghoul::exponentialEaseOut(percentageSpent()) @@ -272,4 +275,4 @@ glm::dvec3 Animation::newValue() const { return glm::dvec3(rotMat * glm::dvec4(_start, 1.0));; } -} // namespace openspace +} // namespace openspace::skybrowser diff --git a/modules/skybrowser/src/wwtcommunicator.cpp b/modules/skybrowser/src/wwtcommunicator.cpp index c32efd492b..3507f2f513 100644 --- a/modules/skybrowser/src/wwtcommunicator.cpp +++ b/modules/skybrowser/src/wwtcommunicator.cpp @@ -135,8 +135,8 @@ WwtCommunicator::WwtCommunicator(const ghoul::Dictionary& dictionary) void WwtCommunicator::update() { // Cap how messages are passed - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - std::chrono::system_clock::duration timeSinceLastUpdate = now - _lastUpdateTime; + const std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const std::chrono::system_clock::duration timeSinceLastUpdate = now - _lastUpdateTime; if (timeSinceLastUpdate > TimeUpdateInterval) { if (_equatorialAimIsDirty) { @@ -161,7 +161,7 @@ void WwtCommunicator::selectImage(const std::string& url) { if (it == _selectedImages.end()) { // Push newly selected image to front - _selectedImages.push_front(std::pair(url, 1.0)); + _selectedImages.emplace_front(url, 1.0); // If wwt has not loaded the collection yet, wait with passing the message if (_isImageCollectionLoaded) { @@ -187,7 +187,7 @@ void WwtCommunicator::removeSelectedImage(const std::string& imageUrl) { void WwtCommunicator::sendMessageToWwt(const ghoul::Dictionary& msg) const { std::string m = ghoul::formatJson(msg); - executeJavascript(fmt::format("sendMessageToWWT({});", m)); + executeJavascript(std::format("sendMessageToWWT({});", m)); } std::vector WwtCommunicator::selectedImages() const { @@ -239,12 +239,12 @@ void WwtCommunicator::setBorderColor(glm::ivec3 color) { void WwtCommunicator::setBorderRadius(double radius) { _borderRadius = radius; - std::string scr = fmt::format("setBorderRadius({});", radius); + const std::string scr = std::format("setBorderRadius({});", radius); executeJavascript(scr); } void WwtCommunicator::updateBorderColor() const { - std::string script = fmt::format( + const std::string script = std::format( "setBackgroundColor('rgb({},{},{})');", _wwtBorderColor.x, _wwtBorderColor.y, _wwtBorderColor.z ); @@ -253,7 +253,11 @@ void WwtCommunicator::updateBorderColor() const { void WwtCommunicator::updateAim() const { // Message WorldWide Telescope current view - ghoul::Dictionary msg = moveCameraMessage(_equatorialAim, _verticalFov, _targetRoll); + const ghoul::Dictionary msg = moveCameraMessage( + _equatorialAim, + _verticalFov, + _targetRoll + ); sendMessageToWwt(msg); } @@ -287,7 +291,9 @@ glm::dvec2 WwtCommunicator::equatorialAim() const { void WwtCommunicator::setImageOrder(const std::string& imageUrl, int order) { // Find in selected images list auto current = findSelectedImage(imageUrl); - int currentIndex = static_cast(std::distance(_selectedImages.begin(), current)); + const int currentIndex = static_cast( + std::distance(_selectedImages.begin(), current) + ); std::deque> newDeque; @@ -311,8 +317,8 @@ void WwtCommunicator::setImageOrder(const std::string& imageUrl, int order) { } _selectedImages = newDeque; - int reverseOrder = static_cast(_selectedImages.size()) - order - 1; - ghoul::Dictionary message = setLayerOrderMessage(imageUrl, reverseOrder); + const int reverseOrder = static_cast(_selectedImages.size()) - order - 1; + const ghoul::Dictionary message = setLayerOrderMessage(imageUrl, reverseOrder); sendMessageToWwt(message); } @@ -326,12 +332,12 @@ void WwtCommunicator::setImageOpacity(const std::string& imageUrl, float opacity auto it = findSelectedImage(imageUrl); it->second = opacity; - ghoul::Dictionary msg = setImageOpacityMessage(imageUrl, opacity); + const ghoul::Dictionary msg = setImageOpacityMessage(imageUrl, opacity); sendMessageToWwt(msg); } void WwtCommunicator::hideChromeInterface() const { - std::string script = "sendMessageToWWT({event : \"modify_settings\", " + const std::string script = "sendMessageToWWT({event : \"modify_settings\", " "settings : [[\"hideAllChrome\", true]], target: \"app\"});"; executeJavascript(script); } @@ -342,7 +348,7 @@ void WwtCommunicator::setImageCollectionIsLoaded(bool isLoaded) { void WwtCommunicator::setIdInBrowser(const std::string& id) const { // Send ID to its browser - executeJavascript(fmt::format("setId('{}')", id)); + executeJavascript(std::format("setId('{}')", id)); } glm::ivec3 WwtCommunicator::borderColor() const { diff --git a/modules/skybrowser/src/wwtdatahandler.cpp b/modules/skybrowser/src/wwtdatahandler.cpp index f2e714641a..7da2fe075b 100644 --- a/modules/skybrowser/src/wwtdatahandler.cpp +++ b/modules/skybrowser/src/wwtdatahandler.cpp @@ -38,7 +38,7 @@ namespace { constexpr std::string_view ImageSet = "ImageSet"; constexpr std::string_view Dec = "Dec"; constexpr std::string_view RA = "RA"; - constexpr std::string_view Undefined = ""; + constexpr std::string_view Undefined; constexpr std::string_view Folder = "Folder"; constexpr std::string_view Place = "Place"; constexpr std::string_view ThumbnailUrl = "ThumbnailUrl"; @@ -50,13 +50,13 @@ namespace { constexpr std::string_view Sky = "Sky"; bool hasAttribute(const tinyxml2::XMLElement* element, std::string_view name) { - std::string n = std::string(name); + const std::string n = std::string(name); return element->FindAttribute(n.c_str()); } std::string attribute(const tinyxml2::XMLElement* element, std::string_view name) { if (hasAttribute(element, name)) { - std::string n = std::string(name); + const std::string n = std::string(name); return element->FindAttribute(n.c_str())->Value(); } return std::string(Undefined); @@ -105,7 +105,7 @@ namespace { { // Find the thumbnail image url // The thumbnail is the last node so traverse backwards for speed - std::string n = std::string(elementName); + const std::string n = std::string(elementName); const tinyxml2::XMLElement* child = imageSet->FirstChildElement(n.c_str()); return child && child->GetText() ? child->GetText() : std::string(Undefined); } @@ -132,11 +132,11 @@ namespace { { using namespace openspace; // Download file from url - std::filesystem::path file = directory.string() + fileName + ".aspx"; + const std::filesystem::path file = directory.string() + fileName + ".aspx"; const bool success = downloadFile(url, file); if (!success) { - LINFO(fmt::format( - "Could not download file '{}' to directory {}", url, directory + LINFO(std::format( + "Could not download file '{}' to directory '{}'", url, directory )); return false; } @@ -154,7 +154,7 @@ namespace { // If the file contains no folders, or there are folders but without urls, // stop recursion if (!folderExists || folderContainNoUrls) { - LINFO(fmt::format("Saving {}", url)); + LINFO(std::format("Saving '{}'", url)); return true; } @@ -162,8 +162,8 @@ namespace { while (element && std::string(element->Value()) == Folder) { // If folder contains urls, download and parse those urls if (hasAttribute(element, Url) && hasAttribute(element, Name)) { - std::string urlAttr = attribute(element, Url); - std::string fileNameAttr = attribute(element, Name); + const std::string urlAttr = attribute(element, Url); + const std::string fileNameAttr = attribute(element, Name); downloadWtmlFiles(directory, urlAttr, fileNameAttr); } element = element->NextSiblingElement(); @@ -180,7 +180,7 @@ namespace { // it is a Place or an ImageSet std::string thumbnailUrl = std::string(Undefined); const tinyxml2::XMLElement* imageSet = nullptr; - std::string type = node->Name(); + const std::string type = node->Name(); if (type == ImageSet) { thumbnailUrl = childNodeContentFromImageSet(node, ThumbnailUrl); @@ -208,20 +208,20 @@ namespace { name[0] = static_cast(std::toupper(name[0])); } - std::string imageUrl = attribute(imageSet, Url); - std::string credits = childNodeContentFromImageSet(imageSet, Credits); - std::string creditsUrl = childNodeContentFromImageSet(imageSet, CreditsUrl); + const std::string imageUrl = attribute(imageSet, Url); + const std::string credits = childNodeContentFromImageSet(imageSet, Credits); + const std::string creditsUrl = childNodeContentFromImageSet(imageSet, CreditsUrl); // Collect equatorial coordinates. All-sky surveys do not have these coordinates - bool hasCelestialCoords = hasAttribute(node, RA) && hasAttribute(node, Dec); + const bool hasCelestialCoords = hasAttribute(node, RA) && hasAttribute(node, Dec); glm::dvec2 equatorialSpherical = glm::dvec2(0.0); glm::dvec3 equatorialCartesian = glm::dvec3(0.0); if (hasCelestialCoords) { // The RA from WWT is in the unit hours: // to convert to degrees, multiply with 360 (deg) /24 (h) = 15 - double ra = 15.0 * std::stod(attribute(node, RA)); - double dec = std::stod(attribute(node, Dec)); + const double ra = 15.0 * std::stod(attribute(node, RA)); + const double dec = std::stod(attribute(node, Dec)); equatorialSpherical = glm::dvec2(ra, dec); equatorialCartesian = skybrowser::sphericalToCartesian(equatorialSpherical); } @@ -261,15 +261,18 @@ void WwtDataHandler::loadImages(const std::string& root, // 1. if (!directoryExists(directory)) { - LINFO(fmt::format("Creating directory {}", directory)); + LINFO(std::format("Creating directory '{}'", directory)); std::filesystem::create_directory(directory); } // Get the hash from the remote. If no such hash exists, the remoteHash will be empty std::string remoteHash; { - std::string remoteHashFile = root.substr(0, root.find_last_of('/')) + "/hash.md5"; - bool success = downloadFile(remoteHashFile, directory / "hash.tmp"); + const std::string remoteHashFile = root.substr( + 0, + root.find_last_of('/') + ) + "/hash.md5"; + const bool success = downloadFile(remoteHashFile, directory / "hash.tmp"); // The hash download might fail if the provided 'root' does not have a hash // in which case we assume that the underlying data has not changed if (success) { @@ -280,7 +283,7 @@ void WwtDataHandler::loadImages(const std::string& root, // Load the local hash. If no such hash exists, the localHash will be empty std::string localHash; - std::filesystem::path localHashFile = directory / "hash.md5"; + const std::filesystem::path localHashFile = directory / "hash.md5"; if (std::filesystem::exists(localHashFile)) { std::ifstream(localHashFile) >> localHash; } @@ -288,7 +291,7 @@ void WwtDataHandler::loadImages(const std::string& root, // Check if the hash has changed. This will be ignored if either the local of remote // hash does not exist if (!localHash.empty() && !remoteHash.empty() && localHash != remoteHash) { - LINFO(fmt::format( + LINFO(std::format( "Local hash '{}' differs from remote hash '{}'. Cleaning directory", localHash, remoteHash )); @@ -309,32 +312,33 @@ void WwtDataHandler::loadImages(const std::string& root, LINFO("Loading images from directory"); for (const auto& entry : std::filesystem::directory_iterator(directory)) { tinyxml2::XMLDocument document; - std::string path = entry.path().string(); - tinyxml2::XMLError successCode = document.LoadFile(path.c_str()); + const std::string path = entry.path().string(); + const tinyxml2::XMLError successCode = document.LoadFile(path.c_str()); if (successCode == tinyxml2::XMLError::XML_SUCCESS) { tinyxml2::XMLElement* rootNode = document.FirstChildElement(); - std::string collectionName = attribute(rootNode, Name); + const std::string collectionName = attribute(rootNode, Name); saveImagesFromXml(rootNode, collectionName); } } // Sort images. Copy images to vector - std::vector _imageVector; + std::vector imageVector; + imageVector.reserve(_images.size()); for (const auto& [id, img] : _images) { - _imageVector.push_back(img); + imageVector.push_back(img); } // Sort - std::sort(_imageVector.begin(), _imageVector.end(), + std::sort(imageVector.begin(), imageVector.end(), [](const ImageData& lhs, const ImageData& rhs) { return lhs.name < rhs.name; } ); // Set the identifiers to the correct order - for (size_t i = 0; i < _imageVector.size(); i++) { - _images[_imageVector[i].imageUrl].identifier = std::to_string(i); + for (size_t i = 0; i < imageVector.size(); i++) { + _images[imageVector[i].imageUrl].identifier = std::to_string(i); } - LINFO(fmt::format("Loaded {} WorldWide Telescope images", _images.size())); + LINFO(std::format("Loaded {} WorldWide Telescope images", _images.size())); } int WwtDataHandler::nLoadedImages() const { @@ -375,8 +379,10 @@ void WwtDataHandler::saveImagesFromXml(const tinyxml2::XMLElement* root, } // If node is another folder, open recursively else if (name == Folder) { - std::string nodeName = attribute(node, Name); - std::string newCollectionName = fmt::format("{}/{}", collection, nodeName); + const std::string nodeName = attribute(node, Name); + const std::string newCollectionName = std::format( + "{}/{}", collection, nodeName + ); saveImagesFromXml(node, newCollectionName); } node = node->NextSiblingElement(); diff --git a/modules/sound/ext/soloud b/modules/sound/ext/soloud new file mode 160000 index 0000000000..1157475881 --- /dev/null +++ b/modules/sound/ext/soloud @@ -0,0 +1 @@ +Subproject commit 1157475881da0d7f76102578255b937c7d4e8f57 diff --git a/modules/space/horizonsfile.cpp b/modules/space/horizonsfile.cpp index efb5036811..7fc790b4b0 100644 --- a/modules/space/horizonsfile.cpp +++ b/modules/space/horizonsfile.cpp @@ -66,7 +66,7 @@ HorizonsFile::HorizonsFile(std::filesystem::path filePath, std::string result) { // Write the response into a new file and save it std::ofstream file(_file); - file << ghoul::replaceAll(std::move(result), "\\n", "\n") << std::endl; + file << ghoul::replaceAll(std::move(result), "\\n", "\n") << '\n'; } void HorizonsFile::setFile(std::filesystem::path file) { @@ -96,7 +96,7 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, break; } - url += fmt::format( + url += std::format( "{}'{}'{}'{}'{}'{}'{}'{}'", Command, ghoul::encodeUrl(target), Center, ghoul::encodeUrl(observer), @@ -105,10 +105,10 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, ); if (unit.empty()) { - url += fmt::format("{}'{}'", StepSize, ghoul::encodeUrl(stepSize)); + url += std::format("{}'{}'", StepSize, ghoul::encodeUrl(stepSize)); } else { - url += fmt::format( + url += std::format( "{}'{}%20{}'", StepSize, ghoul::encodeUrl(stepSize), unit ); } @@ -116,9 +116,9 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, return url; } -json sendHorizonsRequest(const std::string& url, std::filesystem::path filePath) { +json sendHorizonsRequest(const std::string& url, const std::filesystem::path& filePath) { // Set up HTTP request and download result - std::unique_ptr download = std::make_unique( + const auto download = std::make_unique( url, filePath, HttpFileDownload::Overwrite::Yes @@ -130,7 +130,7 @@ json sendHorizonsRequest(const std::string& url, std::filesystem::path filePath) bool failed = false; dl->wait(); if (!dl->hasSucceeded()) { - LERROR(fmt::format("Error downloading horizons file with URL {}", dl->url())); + LERROR(std::format("Error downloading horizons file with URL '{}'", dl->url())); failed = true; } @@ -141,15 +141,15 @@ json sendHorizonsRequest(const std::string& url, std::filesystem::path filePath) return convertHorizonsDownloadToJson(filePath); } -nlohmann::json convertHorizonsDownloadToJson(std::filesystem::path filePath) { +nlohmann::json convertHorizonsDownloadToJson(const std::filesystem::path& filePath) { // Read the entire file into a string - constexpr size_t readSize = std::size_t(4096); + constexpr size_t ReadSize = 4096; std::ifstream stream = std::ifstream(filePath); stream.exceptions(std::ios_base::badbit); std::string answer; - std::string buf = std::string(readSize, '\0'); - while (stream.read(buf.data(), readSize)) { + std::string buf = std::string(ReadSize, '\0'); + while (stream.read(buf.data(), ReadSize)) { answer.append(buf, 0, stream.gcount()); } answer.append(buf, 0, stream.gcount()); @@ -163,7 +163,7 @@ HorizonsResultCode isValidHorizonsAnswer(const json& answer) { if (auto signature = answer.find("signature"); signature != answer.end()) { if (auto source = signature->find("source"); source != signature->end()) { if (*source != static_cast(ApiSource)) { - LWARNING(fmt::format( + LWARNING(std::format( "Horizons answer from unknown source '{}'", source->dump() )); } @@ -178,7 +178,7 @@ HorizonsResultCode isValidHorizonsAnswer(const json& answer) { v = v.substr(0, v.find('.')); if (v != CurrentMajorVersion) { - LWARNING(fmt::format( + LWARNING(std::format( "Unknown Horizons major version '{}' found. The currently supported " "major version is {}", version->dump(), CurrentMajorVersion )); @@ -197,7 +197,7 @@ HorizonsResultCode isValidHorizonsAnswer(const json& answer) { // Errors if (auto it = answer.find("error"); it != answer.end()) { // There was an error - std::string errorMsg = *it; + const std::string errorMsg = *it; // @CPP23 (malej, 2022-04-08) In all cases below, the string function contains // should be used instead of find @@ -247,7 +247,7 @@ HorizonsResultCode isValidHorizonsAnswer(const json& answer) { // Check whether the given Horizons file is valid or not // Return an error code with what is the problem if there was one -HorizonsResultCode isValidHorizonsFile(std::filesystem::path file) { +HorizonsResultCode isValidHorizonsFile(const std::filesystem::path& file) { std::ifstream fileStream(file); if (!fileStream.good()) { return HorizonsResultCode::Empty; @@ -388,7 +388,7 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { break; } - LINFO(fmt::format( + LINFO(std::format( "Valid time range is '{}' to '{}'", validTimeRange.first, validTimeRange.second )); @@ -412,7 +412,7 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { "selected observer" ); - std::vector matchingstations = + const std::vector matchingstations = parseMatches("Observatory Name", "Multiple matching stations found"); if (matchingstations.empty()) { LERROR("Could not parse the matching stations"); @@ -420,16 +420,16 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { } std::string matches; - for (std::string station : matchingstations) { + for (const std::string& station : matchingstations) { matches += '\n' + station; } - LINFO(fmt::format("Matching Observer Stations: {}", matches)); + LINFO(std::format("Matching Observer Stations: {}", matches)); break; } case HorizonsResultCode::MultipleObserver: { LWARNING("Multiple matches were found for the selected observer"); - std::vector matchingObservers = + const std::vector matchingObservers = parseMatches("Name", "matches", ">MATCH NAME<"); if (matchingObservers.empty()) { LERROR("Could not parse the matching observers"); @@ -437,10 +437,10 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { } std::string matches; - for (std::string observer : matchingObservers) { + for (const std::string& observer : matchingObservers) { matches += '\n' + observer; } - LINFO(fmt::format("Matching Observers: {}", matches)); + LINFO(std::format("Matching Observers: {}", matches)); break; } case HorizonsResultCode::ErrorNoTarget: @@ -460,7 +460,7 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { LWARNING("Multiple matches were found for the target"); - std::vector matchingTargets = + const std::vector matchingTargets = parseMatches("Name", "matches", ">MATCH NAME<"); if (matchingTargets.empty()) { LERROR("Could not parse the matching targets"); @@ -468,10 +468,10 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { } std::string matches; - for (std::string target : matchingTargets) { + for (const std::string& target : matchingTargets) { matches += '\n' + target; } - LINFO(fmt::format("Matching targets: {}", matches)); + LINFO(std::format("Matching targets: {}", matches)); break; } case HorizonsResultCode::UnknownError: @@ -485,7 +485,7 @@ void HorizonsFile::displayErrorMessage(HorizonsResultCode code) const { HorizonsResult readHorizonsFile(std::filesystem::path file) { // Check if valid - HorizonsResultCode code = isValidHorizonsFile(file); + const HorizonsResultCode code = isValidHorizonsFile(file); if (code != HorizonsResultCode::Valid) { HorizonsResult result; result.errorCode = code; @@ -495,7 +495,7 @@ HorizonsResult readHorizonsFile(std::filesystem::path file) { std::ifstream fileStream(file); if (!fileStream.good()) { - LERROR(fmt::format("Failed to open Horizons file '{}'", file)); + LERROR(std::format("Failed to open Horizons file '{}'", file)); return HorizonsResult(); } @@ -527,7 +527,7 @@ HorizonsResult readHorizonsVectorFile(std::filesystem::path file) { std::ifstream fileStream(file); if (!fileStream.good()) { - LERROR(fmt::format("Failed to open Horizons text file {}", file)); + LERROR(std::format("Failed to open Horizons text file {}", file)); return HorizonsResult(); } @@ -557,22 +557,22 @@ HorizonsResult readHorizonsVectorFile(std::filesystem::path file) { // Get next line of same data point std::getline(fileStream, line); if (!fileStream.good()) { - LERROR(fmt::format("Malformed Horizons file '{}'", file)); + LERROR(std::format("Malformed Horizons file '{}'", file)); return HorizonsResult(); } std::stringstream str2(line); // X Y Z - double xPos; - double yPos; - double zPos; + double xPos = 0.0; + double yPos = 0.0; + double zPos = 0.0; str2 >> xPos >> yPos >> zPos; // Convert date and time to seconds after 2000 - std::string timeString = fmt::format("{} {}", date, time); - double timeInJ2000 = Time::convertTime(timeString); + const std::string timeString = std::format("{} {}", date, time); + const double timeInJ2000 = Time::convertTime(timeString); glm::dvec3 pos = glm::dvec3(1000 * xPos, 1000 * yPos, 1000 * zPos); - glm::dmat3 transform = + const glm::dmat3 transform = SpiceManager::ref().positionTransformMatrix("ECLIPJ2000", "GALACTIC", 0.0); pos = transform * pos; @@ -596,7 +596,7 @@ HorizonsResult readHorizonsObserverFile(std::filesystem::path file) { std::ifstream fileStream(file); if (!fileStream.good()) { - LERROR(fmt::format("Failed to open Horizons text file '{}'", file)); + LERROR(std::format("Failed to open Horizons text file '{}'", file)); return HorizonsResult(); } @@ -631,17 +631,15 @@ HorizonsResult readHorizonsObserverFile(std::filesystem::path file) { // Convert date and time to seconds after 2000 // and pos to Galactic positions in meter from Observer. - std::string timeString = fmt::format("{} {}", date, time); - double timeInJ2000 = Time::convertTime(timeString); - glm::dvec3 gPos = glm::dvec3( + const std::string timeString = std::format("{} {}", date, time); + + // Add position to stored data + dataPoint.time = Time::convertTime(timeString); + dataPoint.position = glm::dvec3( 1000 * range * cos(glm::radians(gLat)) * cos(glm::radians(gLon)), 1000 * range * cos(glm::radians(gLat)) * sin(glm::radians(gLon)), 1000 * range * sin(glm::radians(gLat)) ); - - // Add position to stored data - dataPoint.time = timeInJ2000; - dataPoint.position = gPos; data.push_back(dataPoint); std::getline(fileStream, line); @@ -762,9 +760,8 @@ std::pair HorizonsFile::parseValidTimeRange( if (line.find(startPhrase) != std::string::npos) { break; } - else if (!altStartPhrase.empty() && - line.find(altStartPhrase) != std::string::npos) - { + + if (!altStartPhrase.empty() && line.find(altStartPhrase) != std::string::npos) { break; } @@ -780,7 +777,8 @@ std::pair HorizonsFile::parseValidTimeRange( // In the first file parse both start and end time // From the first line get the start time - std::string startTime, endTime; + std::string startTime; + std::string endTime; std::getline(fileStream, line); if (fileStream.good()) { std::stringstream str(line); @@ -795,10 +793,10 @@ std::pair HorizonsFile::parseValidTimeRange( // Parse time stamps backwards // Format: Trajectory file Name, Start, End (yyyy-mon-dd hh:mm) if (hasTime && words.size() > 4) { - startTime = fmt::format( + startTime = std::format( "{} T {}", words[words.size() - 4], words[words.size() - 3] ); - endTime = fmt::format( + endTime = std::format( "{} T {}", words[words.size() - 2], words[words.size() - 1] ); } @@ -833,7 +831,7 @@ std::pair HorizonsFile::parseValidTimeRange( // Parse time stamps backwards // Format: Trajectory file Name, Start, End (yyyy-mon-dd hh:mm) if (hasTime && words.size() > 4) { - endTime = fmt::format( + endTime = std::format( "{} T {}", words[words.size() - 2], words[words.size() - 1] ); } diff --git a/modules/space/horizonsfile.h b/modules/space/horizonsfile.h index f23f86fb00..92bc18fd01 100644 --- a/modules/space/horizonsfile.h +++ b/modules/space/horizonsfile.h @@ -128,10 +128,10 @@ std::string constructHorizonsUrl(HorizonsType type, const std::string& target, const std::string& stopTime, const std::string& stepSize, const std::string& unit); nlohmann::json sendHorizonsRequest(const std::string& url, - std::filesystem::path filePath); -nlohmann::json convertHorizonsDownloadToJson(std::filesystem::path filePath); + const std::filesystem::path& filePath); +nlohmann::json convertHorizonsDownloadToJson(const std::filesystem::path& filePath); HorizonsResultCode isValidHorizonsAnswer(const nlohmann::json& answer); -HorizonsResultCode isValidHorizonsFile(std::filesystem::path file); +HorizonsResultCode isValidHorizonsFile(const std::filesystem::path& file); HorizonsResult readHorizonsFile(std::filesystem::path file); HorizonsResult readHorizonsVectorFile(std::filesystem::path file); diff --git a/modules/space/kepler.cpp b/modules/space/kepler.cpp index 0e6ca11493..7c5059585b 100644 --- a/modules/space/kepler.cpp +++ b/modules/space/kepler.cpp @@ -28,8 +28,7 @@ #include #include #include -#include -#include +#include #include #include #include @@ -127,7 +126,7 @@ namespace { LeapSecond { .year = 2017, .dayOfYear = 1 } }; // Get the position of the last leap second before the desired date - LeapSecond date{ year, dayOfYear }; + const LeapSecond date = { year, dayOfYear }; const auto it = std::lower_bound(LeapSeconds.begin(), LeapSeconds.end(), date); // Get the position of the Epoch @@ -209,10 +208,13 @@ namespace { if (e.find('.') == std::string::npos) { e += ".0"; } - auto [res, year, daysInYear] = scn::scan_tuple(e, "{:2}{}"); + // @TODO(abock) The 'd' suffix can be removed when + // https://github.com/eliaskosunen/scnlib/issues/104 is fixed + auto res = scn::scan(e, "{:2d}{}"); if (!res) { - throw ghoul::RuntimeError(fmt::format("Error parsing epoch '{}'", epoch)); + throw ghoul::RuntimeError(std::format("Error parsing epoch '{}'", epoch)); } + auto [year, daysInYear] = res->values(); year += year > 57 ? 1900 : 2000; const int daysSince2000 = countDays(year); @@ -259,20 +261,20 @@ namespace { e += ".0"; } // 1, 2 - size_t nDashes = std::count_if( + const size_t nDashes = std::count_if( epoch.begin(), epoch.end(), [](char c) { return c == '-'; } ); - std::string formatString = (nDashes == 2) ? "{:4}-{:2}-{:2}{}" : "{:4}{:2}{:2}{}"; - auto [res, year, monthNum, dayOfMonthNum, fractionOfDay] = - scn::scan_tuple(e, formatString); + const std::string format = (nDashes == 2) ? "{:4}-{:2}-{:2}{}" : "{:4}{:2}{:2}{}"; + auto res = scn::scan(e, scn::runtime_format(format)); if (!res) { - throw ghoul::RuntimeError(fmt::format("Error parsing epoch '{}'", epoch)); + throw ghoul::RuntimeError(std::format("Error parsing epoch '{}'", epoch)); } + auto [year, monthNum, dayOfMonthNum, fractionOfDay] = res->values(); const int daysSince2000 = countDays(year); - int wholeDaysInto = daysIntoGivenYear(year, monthNum, dayOfMonthNum); - double daysInYear = static_cast(wholeDaysInto) + fractionOfDay; + const int wholeDaysInto = daysIntoGivenYear(year, monthNum, dayOfMonthNum); + const double daysInYear = static_cast(wholeDaysInto) + fractionOfDay; // 3 using namespace std::chrono; @@ -328,30 +330,37 @@ namespace { const size_t pos = epoch.find('T'); if (pos == 10) { // We have the first form - int month; - int days; - auto res = scn::scan( - epoch, "{:4}-{:2}-{:2}T{:2}:{:2}:{}", - date.year, month, days, date.hours, date.minutes, date.seconds + int month = 0; + int days = 0; + // @TODO(abock) The 'd' suffix can be removed when + // https://github.com/eliaskosunen/scnlib/issues/104 is fixed + auto res = scn::scan( + epoch, "{:4d}-{:2d}-{:2d}T{:2d}:{:2d}:{}" ); if (!res) { - throw ghoul::RuntimeError(fmt::format("Error parsing epoch '{}'", epoch)); + throw ghoul::RuntimeError(std::format("Error parsing epoch '{}'", epoch)); } + std::tie(date.year, month, days, date.hours, date.minutes, date.seconds) = + res->values(); date.nDays = daysIntoGivenYear(date.year, month, days); } else if (pos == 8) { // We have the second form - auto res = scn::scan( - epoch, "{:4}-{:3}T{:2}:{:2}:{}", - date.year, date.nDays, date.hours, date.minutes, date.seconds + // @TODO(abock) The 'd' suffix can be removed when + // https://github.com/eliaskosunen/scnlib/issues/104 is fixed + auto res = scn::scan( + epoch, "{:4d}-{:3d}T{:2d}:{:2d}:{}" + //date.year, date.nDays, date.hours, date.minutes, date.seconds ); if (!res) { - throw ghoul::RuntimeError(fmt::format("Error parsing epoch '{}'", epoch)); + throw ghoul::RuntimeError(std::format("Error parsing epoch '{}'", epoch)); } + std::tie(date.year, date.nDays, date.hours, date.minutes, date.seconds) = + res->values(); } else { - throw ghoul::RuntimeError(fmt::format("Malformed epoch string '{}'", epoch)); + throw ghoul::RuntimeError(std::format("Malformed epoch string '{}'", epoch)); } const int daysSince2000 = countDays(date.year); @@ -385,7 +394,7 @@ namespace { namespace openspace::kepler { -std::vector readTleFile(std::filesystem::path file) { +std::vector readTleFile(const std::filesystem::path& file) { ghoul_assert(std::filesystem::is_regular_file(file), "File must exist"); std::vector result; @@ -421,19 +430,19 @@ std::vector readTleFile(std::filesystem::path file) { std::string firstLine; std::getline(f, firstLine); if (f.bad() || firstLine[0] != '1') { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Malformed TLE file '{}' at line {}", file, lineNum + 1 )); } // The id only contains the last two digits of the launch year, so we have to // patch it to the full year { - std::string id = firstLine.substr(9, 6); - std::string prefix = [y = id.substr(0, 2)](){ - int year = std::atoi(y.c_str()); + const std::string id = firstLine.substr(9, 6); + const std::string prefix = [y = id.substr(0, 2)](){ + const int year = std::atoi(y.c_str()); return year >= 57 ? "19" : "20"; }(); - p.id = fmt::format("{}{}-{}", prefix, id.substr(0, 2), id.substr(3)); + p.id = std::format("{}{}-{}", prefix, id.substr(0, 2), id.substr(3)); } p.epoch = epochFromSubstring(firstLine.substr(18, 14)); // should be 13? @@ -453,7 +462,7 @@ std::vector readTleFile(std::filesystem::path file) { std::string secondLine; std::getline(f, secondLine); if (f.bad() || secondLine[0] != '2') { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Malformed TLE file '{}' at line {}", file, lineNum + 1 )); } @@ -488,7 +497,7 @@ std::vector readTleFile(std::filesystem::path file) { // Get mean motion stream.str(secondLine.substr(52, 11)); - float meanMotion; + float meanMotion = 0.f; stream >> meanMotion; p.semiMajorAxis = calculateSemiMajorAxis(meanMotion); @@ -502,7 +511,7 @@ std::vector readTleFile(std::filesystem::path file) { return result; } -std::vector readOmmFile(std::filesystem::path file) { +std::vector readOmmFile(const std::filesystem::path& file) { ghoul_assert(std::filesystem::is_regular_file(file), "File must exist"); std::vector result; @@ -525,7 +534,7 @@ std::vector readOmmFile(std::filesystem::path file) { } if (parts.size() != 2) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Malformed line '{}' at {}", line, lineNum )); } @@ -534,7 +543,7 @@ std::vector readOmmFile(std::filesystem::path file) { if (parts[1] != "2.0") { LWARNINGC( "OMM", - fmt::format( + std::format( "Only version 2.0 is currently supported but found {}. " "Parsing might fail", parts[1] @@ -563,7 +572,7 @@ std::vector readOmmFile(std::filesystem::path file) { current->epoch = epochFromOmmString(parts[1]); } else if (parts[0] == "MEAN_MOTION") { - float mm = std::stof(parts[1]); + const float mm = std::stof(parts[1]); current->semiMajorAxis = calculateSemiMajorAxis(mm); current->period = std::chrono::seconds(std::chrono::hours(24)).count() / mm; } @@ -594,7 +603,7 @@ std::vector readOmmFile(std::filesystem::path file) { return result; } -std::vector readSbdbFile(std::filesystem::path file) { +std::vector readSbdbFile(const std::filesystem::path& file) { constexpr int NDataFields = 9; constexpr std::string_view ExpectedHeader = "full_name,epoch_cal,e,a,i,om,w,ma,per"; @@ -608,7 +617,7 @@ std::vector readSbdbFile(std::filesystem::path file) { // Newer versions downloaded from the JPL SBDB website have " around variables line.erase(remove(line.begin(), line.end(), '\"'), line.end()); if (line != ExpectedHeader) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Expected JPL SBDB file to start with '{}' but found '{}' instead", ExpectedHeader, line.substr(0, 100) )); @@ -620,7 +629,7 @@ std::vector readSbdbFile(std::filesystem::path file) { std::vector parts = ghoul::tokenizeString(line, ','); if (parts.size() != NDataFields) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Malformed line {}, expected 8 data fields, got {}", line, parts.size() )); } @@ -658,7 +667,7 @@ std::vector readSbdbFile(std::filesystem::path file) { return result; } -void saveCache(const std::vector& params, std::filesystem::path file) { +void saveCache(const std::vector& params, const std::filesystem::path& file) { std::ofstream stream(file, std::ofstream::binary); stream.write(reinterpret_cast(&CurrentCacheVersion), sizeof(int8_t)); @@ -688,7 +697,7 @@ void saveCache(const std::vector& params, std::filesystem::path file } } -std::optional> loadCache(std::filesystem::path file) { +std::optional> loadCache(const std::filesystem::path& file) { std::ifstream stream(file, std::ifstream::binary); int8_t version = 0; @@ -733,8 +742,8 @@ std::optional> loadCache(std::filesystem::path file) { std::vector readFile(std::filesystem::path file, Format format) { std::filesystem::path cachedFile = FileSys.cacheManager()->cachedFilename(file); if (std::filesystem::is_regular_file(cachedFile)) { - LINFO(fmt::format( - "Cached file {} used for Kepler file {}", cachedFile, file + LINFO(std::format( + "Cached file '{}' used for Kepler file '{}'", cachedFile, file )); std::optional> res = loadCache(cachedFile); @@ -758,7 +767,7 @@ std::vector readFile(std::filesystem::path file, Format format) { break; } - LINFO(fmt::format("Saving cache {} for Kepler file {}", cachedFile, file)); + LINFO(std::format("Saving cache '{}' for Kepler file '{}'", cachedFile, file)); saveCache(res, cachedFile); return res; } diff --git a/modules/space/kepler.h b/modules/space/kepler.h index a86aa7e227..c17e487f69 100644 --- a/modules/space/kepler.h +++ b/modules/space/kepler.h @@ -58,7 +58,7 @@ struct Parameters { * \pre \p file must be a file and must exist * \throw ghoul::RuntimeError If the provided \p file is not a valid TLE file */ -std::vector readTleFile(std::filesystem::path file); +std::vector readTleFile(const std::filesystem::path& file); /** * Reads the object information from the provided \p file and returns them as individual @@ -70,7 +70,7 @@ std::vector readTleFile(std::filesystem::path file); * \pre \p file must be a file and must exist * \throw ghoul::RuntimeError If the provided \p file is not a valid OMM file */ -std::vector readOmmFile(std::filesystem::path file); +std::vector readOmmFile(const std::filesystem::path& file); /** * Reads the object information from a CSV file following JPL's Small Body Database @@ -83,7 +83,7 @@ std::vector readOmmFile(std::filesystem::path file); * \pre \p file must be a file and must exist * \throw ghoul::RuntimeError If the provided \p is not a valid JPL SBDB CSV format */ -std::vector readSbdbFile(std::filesystem::path file); +std::vector readSbdbFile(const std::filesystem::path& file); /** * The different formats that the readFile function is capable of loading. diff --git a/modules/space/rendering/renderableconstellationbounds.cpp b/modules/space/rendering/renderableconstellationbounds.cpp index a495d303e1..a0ad6493ec 100644 --- a/modules/space/rendering/renderableconstellationbounds.cpp +++ b/modules/space/rendering/renderableconstellationbounds.cpp @@ -114,7 +114,7 @@ void RenderableConstellationBounds::initialize() { if (it == options.end()) { // The user has specified a constellation name that doesn't exist - LWARNING(fmt::format( + LWARNING(std::format( "Option '{}' not found in list of constellations", s )); } @@ -145,11 +145,11 @@ void RenderableConstellationBounds::initializeGL() { glBufferData( GL_ARRAY_BUFFER, _vertexValues.size() * 3 * sizeof(float), - &_vertexValues[0], + _vertexValues.data(), GL_STATIC_DRAW ); - GLint positionAttrib = _program->attributeLocation("in_position"); + const GLint positionAttrib = _program->attributeLocation("in_position"); glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, 0, nullptr); @@ -208,7 +208,7 @@ void RenderableConstellationBounds::render(const RenderData& data, RendererTasks } bool RenderableConstellationBounds::loadData() { - bool success = loadVertexFile(); + const bool success = loadVertexFile(); if (!success) { throw ghoul::RuntimeError("Error loading data"); } @@ -245,10 +245,10 @@ bool RenderableConstellationBounds::loadVertexFile() { // @CHECK: Is this the best way of doing this? ---abock std::stringstream s(currentLine); - float ra; + float ra = 0.f; s >> ra; - float dec; + float dec = 0.f; s >> dec; std::string abbreviation; @@ -257,8 +257,8 @@ bool RenderableConstellationBounds::loadVertexFile() { if (!s.good()) { // If this evaluates to true, the stream was not completely filled, which // means that the line was incomplete, so there was an error - LERROR(fmt::format( - "Error reading file {} at line #{}", fileName, currentLineNumber + LERROR(std::format( + "Error reading file '{}' at line #{}", fileName, currentLineNumber )); break; } @@ -275,7 +275,8 @@ bool RenderableConstellationBounds::loadVertexFile() { currentBound.isEnabled = true; currentBound.constellationAbbreviation = abbreviation; std::string name = constellationFullName(abbreviation); - currentBound.constellationFullName = name.empty() ? abbreviation : name; + currentBound.constellationFullName = + name.empty() ? abbreviation : std::move(name); currentBound.startIndex = static_cast(_vertexValues.size()); } @@ -289,8 +290,8 @@ bool RenderableConstellationBounds::loadVertexFile() { // Convert the (right ascension, declination) to rectangular coordinates) // The 1.0 is the distance of the celestial sphere, we will scale that in the // render function - double rectangularValues[3]; - radrec_c(1.0, ra, dec, rectangularValues); + std::array rectangularValues; + radrec_c(1.0, ra, dec, rectangularValues.data()); // Add the new vertex to our list of vertices _vertexValues.push_back({ diff --git a/modules/space/rendering/renderableconstellationbounds.h b/modules/space/rendering/renderableconstellationbounds.h index 11e2bc0f08..cc1f354ad9 100644 --- a/modules/space/rendering/renderableconstellationbounds.h +++ b/modules/space/rendering/renderableconstellationbounds.h @@ -53,7 +53,7 @@ public: bool isReady() const override; - void render(const RenderData& data, RendererTasks& rendererTask) override; + void render(const RenderData& data, RendererTasks& tasks) override; static documentation::Documentation Documentation(); diff --git a/modules/space/rendering/renderableconstellationlines.cpp b/modules/space/rendering/renderableconstellationlines.cpp index f8b2b5f013..7e35fac3c9 100644 --- a/modules/space/rendering/renderableconstellationlines.cpp +++ b/modules/space/rendering/renderableconstellationlines.cpp @@ -34,7 +34,7 @@ #include #include #include -#include +#include #include #include #include @@ -128,7 +128,7 @@ RenderableConstellationLines::RenderableConstellationLines( if (p.colors.has_value()) { std::vector ops = *p.colors; - for (size_t i = 0; i < ops.size(); ++i) { + for (size_t i = 0; i < ops.size(); i++) { _constellationColorMap.insert({ static_cast(i) + 1, ops[i] }); } } @@ -152,7 +152,7 @@ void RenderableConstellationLines::selectionPropertyHasChanged() { else { // Enable all constellations that are selected for (ConstellationKeyValuePair& pair : _renderingConstellationsMap) { - bool isSelected = _selection.isSelected(pair.second.name); + const bool isSelected = _selection.isSelected(pair.second.name); pair.second.isEnabled = isSelected; if (_hasLabels) { @@ -168,7 +168,7 @@ void RenderableConstellationLines::selectionPropertyHasChanged() { } bool RenderableConstellationLines::isReady() const { - bool isReady = _program && !_renderingConstellationsMap.empty(); + const bool isReady = _program && !_renderingConstellationsMap.empty(); // If we have labels, they also need to be loaded if (_hasLabels) { @@ -198,7 +198,7 @@ void RenderableConstellationLines::initialize() { if (it == options.end()) { // The user has specified a constellation name that doesn't exist - LWARNING(fmt::format( + LWARNING(std::format( "Option '{}' not found in list of constellations", s )); } @@ -301,7 +301,7 @@ void RenderableConstellationLines::update(const UpdateData&) { } bool RenderableConstellationLines::loadData() { - bool success = readSpeckFile(); + const bool success = readSpeckFile(); if (!success) { throw ghoul::RuntimeError("Error loading data"); } @@ -314,10 +314,10 @@ bool RenderableConstellationLines::readSpeckFile() { } std::filesystem::path fileName = absPath(_speckFile); - LINFO(fmt::format("Loading Speck file {}", fileName)); + LINFO(std::format("Loading Speck file '{}'", fileName)); std::ifstream file(fileName); if (!file.good()) { - LERROR(fmt::format("Failed to open Speck file {}", fileName)); + LERROR(std::format("Failed to open Speck file '{}'", fileName)); return false; } @@ -347,91 +347,89 @@ bool RenderableConstellationLines::readSpeckFile() { continue; } - std::size_t found = line.find("mesh"); - if (found == std::string::npos) { + if (const size_t found = line.find("mesh"); found == std::string::npos) { continue; } - else { - // mesh lines are structured as follows: - // mesh -c colorindex { - // colorindex is the index of the color for the mesh - std::stringstream str(line); - ConstellationLine constellationLine; - constellationLine.lineIndex = lineIndex; + // mesh lines are structured as follows: + // mesh -c colorindex { + // colorindex is the index of the color for the mesh + std::stringstream str(line); - std::string dummy; - str >> dummy; // mesh command - dummy.clear(); - str >> dummy; // color index command - do { - if (dummy == "-c") { - str >> constellationLine.colorIndex; // color index - } - else { - std::string message = fmt::format("Unknown command '{}' found in " - "constellation file '{}'", dummy, fileName); - LWARNING(message); - } - dummy.clear(); - str >> dummy; - } while (dummy != "{"); + ConstellationLine constellationLine; + constellationLine.lineIndex = lineIndex; - std::getline(file, line); - - // Read the identifier - std::stringstream id(line); - std::string identifier; - - id >> dummy; // id command - dummy.clear(); - std::getline(id, identifier); // identifier - ghoul::trimWhitespace(identifier); - std::string name = constellationFullName(identifier); - if (!name.empty()) { - constellationLine.name = name; - } - - // Read the number of vertices - std::getline(file, line); - std::stringstream dim(line); - dim >> constellationLine.numV; - - // We can now read the vertices data: - for (int l = 0; l < constellationLine.numV; ++l) { - std::getline(file, line); - if (line.substr(0, 1) == "}") { - break; - } - - // Try to read three values for the position - glm::vec3 pos; - auto reading = scn::scan(line, "{} {} {}", pos.x, pos.y, pos.z); - if (reading) { - pos *= scale; - constellationLine.vertices.push_back(pos.x); - constellationLine.vertices.push_back(pos.y); - constellationLine.vertices.push_back(pos.z); - } - else { - LERROR(fmt::format( - "Failed reading position on line {} of mesh {} in file: '{}'. " - "Stopped reading constellation data", l, lineIndex, fileName - )); - } - - // Check if new max radius - const double r = glm::length(glm::dvec3(pos)); - maxRadius = std::max(maxRadius, r); - } - - std::getline(file, line); - if (line.substr(0, 1) == "}") { - _renderingConstellationsMap.insert({ lineIndex++, constellationLine }); + std::string dummy; + str >> dummy; // mesh command + dummy.clear(); + str >> dummy; // color index command + do { + if (dummy == "-c") { + str >> constellationLine.colorIndex; // color index } else { - return false; + LWARNING(std::format( + "Unknown command '{}' found in constellation file '{}'", + dummy, fileName + )); } + dummy.clear(); + str >> dummy; + } + while (dummy != "{"); + + std::getline(file, line); + + // Read the identifier + std::stringstream id(line); + std::string identifier; + + id >> dummy; // id command + dummy.clear(); + std::getline(id, identifier); // identifier + ghoul::trimWhitespace(identifier); + constellationLine.name = constellationFullName(identifier); + + // Read the number of vertices + std::getline(file, line); + std::stringstream dim(line); + dim >> constellationLine.numV; + + // We can now read the vertices data: + for (int l = 0; l < constellationLine.numV; ++l) { + std::getline(file, line); + if (line.substr(0, 1) == "}") { + break; + } + + // Try to read three values for the position + glm::vec3 pos; + auto reading = scn::scan(line, "{} {} {}"); + if (reading) { + std::tie(pos.x, pos.y, pos.z) = reading->values(); + pos *= scale; + constellationLine.vertices.push_back(pos.x); + constellationLine.vertices.push_back(pos.y); + constellationLine.vertices.push_back(pos.z); + } + else { + LERROR(std::format( + "Failed reading position on line {} of mesh {} in file '{}'. " + "Stopped reading constellation data", l, lineIndex, fileName + )); + } + + // Check if new max radius + const double r = glm::length(glm::dvec3(pos)); + maxRadius = std::max(maxRadius, r); + } + + std::getline(file, line); + if (line.substr(0, 1) == "}") { + _renderingConstellationsMap.insert({ lineIndex++, constellationLine }); + } + else { + return false; } } setBoundingSphere(maxRadius); @@ -443,11 +441,11 @@ void RenderableConstellationLines::createConstellations() { LDEBUG("Creating constellations"); for (std::pair& p : _renderingConstellationsMap) { - GLuint vao; + GLuint vao = 0; glGenVertexArrays(1, &vao); p.second.vaoArray = vao; - GLuint vbo; + GLuint vbo = 0; glGenBuffers(1, &vbo); p.second.vboArray = vbo; diff --git a/modules/space/rendering/renderableconstellationlines.h b/modules/space/rendering/renderableconstellationlines.h index 3c3dd430e9..8d316c7721 100644 --- a/modules/space/rendering/renderableconstellationlines.h +++ b/modules/space/rendering/renderableconstellationlines.h @@ -52,7 +52,7 @@ public: bool isReady() const override; - void render(const RenderData& data, RendererTasks& rendererTask) override; + void render(const RenderData& data, RendererTasks& tasks) override; void update(const UpdateData& data) override; static documentation::Documentation Documentation(); diff --git a/modules/space/rendering/renderableconstellationsbase.cpp b/modules/space/rendering/renderableconstellationsbase.cpp index 747db8bcd4..48bf87f33f 100644 --- a/modules/space/rendering/renderableconstellationsbase.cpp +++ b/modules/space/rendering/renderableconstellationsbase.cpp @@ -64,7 +64,7 @@ namespace { openspace::properties::Property::Visibility::NoviceUser }; - const static openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LabelsInfo = { "Labels", "Labels", "The labels for the constellations" @@ -140,7 +140,7 @@ std::string RenderableConstellationsBase::constellationFullName( return _namesTranslation.at(identifier); } - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Identifier '{}' could not be found in list of constellations", identifier )); } @@ -198,7 +198,7 @@ void RenderableConstellationsBase::initialize() { if (!entry.identifier.empty()) { std::string fullName = constellationFullName(entry.identifier); if (!fullName.empty()) { - entry.text = fullName; + entry.text = std::move(fullName); } } } @@ -228,7 +228,7 @@ void RenderableConstellationsBase::render(const RenderData& data, RendererTasks& ); if (orthoRight == glm::vec3(0.f)) { - glm::vec3 otherVector(lookup.y, lookup.x, lookup.z); + const glm::vec3 otherVector = glm::vec3(lookup.y, lookup.x, lookup.z); right = glm::cross(viewDirection, otherVector); orthoRight = glm::normalize( glm::vec3(worldToModelTransform * glm::vec4(right, 0.f)) diff --git a/modules/space/rendering/renderableeclipsecone.cpp b/modules/space/rendering/renderableeclipsecone.cpp index 928a1e9cbe..e32464c884 100644 --- a/modules/space/rendering/renderableeclipsecone.cpp +++ b/modules/space/rendering/renderableeclipsecone.cpp @@ -329,15 +329,15 @@ std::vector calculateShadowPoints(const std::vector& srcT // reference frame of the Moon const glm::dvec3 src = lightSourceToShadower * srcTerminator[i] + shadowerToLightSource; - const glm::dvec3 dst = dstTerminator[i]; + const glm::dvec3& dst = dstTerminator[i]; const glm::dvec3 dir = glm::normalize(dst - src); // The start point is the terminator point on the Moon - glm::vec3 p1 = dst; + const glm::vec3 p1 = dst; vertices.push_back({ p1.x, p1.y, p1.z }); // The end point is calculated by forward propagating the incoming direction - glm::vec3 p2 = dst + dir * lengthScale; + const glm::vec3 p2 = dst + dir * lengthScale; vertices.push_back({ p2.x, p2.y, p2.z }); } return vertices; @@ -428,7 +428,7 @@ void RenderableEclipseCone::createCone(double et) { // 3. Get the necessary conversion distances and matrices - glm::dvec3 diff = SpiceManager::ref().targetPosition( + const glm::dvec3 diff = SpiceManager::ref().targetPosition( _shadowee, _shadower, "GALACTIC", @@ -451,7 +451,7 @@ void RenderableEclipseCone::createCone(double et) { }, et ) * 1000.0; // to meter - glm::dmat3 lightSourceToShadower = SpiceManager::ref().frameTransformationMatrix( + const glm::dmat3 lightToShadower = SpiceManager::ref().frameTransformationMatrix( _lightSourceFrame, _shadowerFrame, et ); @@ -463,7 +463,7 @@ void RenderableEclipseCone::createCone(double et) { resSrc.terminatorPoints, resDst.terminatorPoints, shadowerToLightSource, - lightSourceToShadower, + lightToShadower, distance * static_cast(_shadowLength) ); @@ -488,7 +488,7 @@ void RenderableEclipseCone::createCone(double et) { resSrc.terminatorPoints, resDst.terminatorPoints, shadowerToLightSource, - lightSourceToShadower, + lightToShadower, distance * static_cast(_shadowLength) ); diff --git a/modules/space/rendering/renderablefluxnodes.cpp b/modules/space/rendering/renderablefluxnodes.cpp index 5b18355ae1..5260cf04f4 100644 --- a/modules/space/rendering/renderablefluxnodes.cpp +++ b/modules/space/rendering/renderablefluxnodes.cpp @@ -359,12 +359,12 @@ RenderableFluxNodes::RenderableFluxNodes(const ghoul::Dictionary& dictionary) // Ensure that there are available and valid source files left if (_binarySourceFiles.empty()) { - LERROR(fmt::format("{} contains no files", _binarySourceFolderPath)); + LERROR(std::format("'{}' contains no files", _binarySourceFolderPath)); } } else { - LERROR(fmt::format( - "Source folder {} is not a valid directory", _binarySourceFolderPath + LERROR(std::format( + "Source folder '{}' is not a valid directory", _binarySourceFolderPath )); } @@ -447,16 +447,16 @@ void RenderableFluxNodes::loadNodeData(int energybinOption) { break; } - std::string file = _binarySourceFolderPath.string() + "\\positions" + energybin; - std::string file2 = _binarySourceFolderPath.string() + "\\fluxes" + energybin; - std::string file3 = _binarySourceFolderPath.string() + "\\radiuses" + energybin; + const std::string file = _binarySourceFolderPath.string() + "\\positions" + energybin; + const std::string file2 = _binarySourceFolderPath.string() + "\\fluxes" + energybin; + const std::string file3 = _binarySourceFolderPath.string() + "\\radiuses" + energybin; std::ifstream fileStream(file, std::ifstream::binary); std::ifstream fileStream2(file2, std::ifstream::binary); std::ifstream fileStream3(file3, std::ifstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Could not read file '{}'", file)); + LERROR(std::format("Could not read file '{}'", file)); return; } @@ -479,7 +479,7 @@ void RenderableFluxNodes::loadNodeData(int energybinOption) { _statesPos.clear(); _statesRadius.clear(); - for (unsigned int i = 0; i < _nStates; ++i) { + for (unsigned int i = 0; i < _nStates; i++) { _vertexPositions.resize(nNodesPerTimestep); fileStream.read(reinterpret_cast( _vertexPositions.data()), nNodesPerTimestep * sizeof(glm::vec3) @@ -488,7 +488,7 @@ void RenderableFluxNodes::loadNodeData(int energybinOption) { _statesPos.push_back(_vertexPositions); _vertexPositions.clear(); } - for (unsigned int i = 0; i < _nStates; ++i) { + for (unsigned int i = 0; i < _nStates; i++) { _vertexColor.resize(nNodesPerTimestep); fileStream2.read(reinterpret_cast( _vertexColor.data()), nNodesPerTimestep * sizeof(float) @@ -497,7 +497,7 @@ void RenderableFluxNodes::loadNodeData(int energybinOption) { _statesColor.push_back(_vertexColor); _vertexColor.clear(); } - for (unsigned int i = 0; i < _nStates; ++i) { + for (unsigned int i = 0; i < _nStates; i++) { _vertexRadius.resize(nNodesPerTimestep); fileStream3.read(reinterpret_cast( _vertexRadius.data()), nNodesPerTimestep * sizeof(float) @@ -581,21 +581,21 @@ bool RenderableFluxNodes::isReady() const { void RenderableFluxNodes::populateStartTimes() { std::string timeFile; for (const std::string& filePath : _binarySourceFiles) { - if (filePath.substr(filePath.find_last_of(".") + 1) == "csv") { + if (filePath.substr(filePath.find_last_of('.') + 1) == "csv") { timeFile = filePath; break; } - else if (filePath.substr(filePath.find_last_of(".") + 1) == "dat") { + else if (filePath.substr(filePath.find_last_of('.') + 1) == "dat") { timeFile = filePath; break; } - else if (filePath.substr(filePath.find_last_of(".") + 1) == "txt") { + else if (filePath.substr(filePath.find_last_of('.') + 1) == "txt") { timeFile = filePath; break; } //if no file extention but word "time" in file name else if (filePath.find("time") != std::string::npos && - filePath.find(".") == std::string::npos) + filePath.find('.') == std::string::npos) { timeFile = filePath; break; @@ -629,7 +629,7 @@ void RenderableFluxNodes::populateStartTimes() { } while (std::getline(tfs, line)) { // for each line of data std::istringstream iss(line); - for (int i = 0; i < nColumns; ++i) { // for each column in line + for (int i = 0; i < nColumns; i++) { // for each column in line std::string columnValue; iss >> columnValue; if (i != nColumns - 1) { // last column @@ -646,8 +646,9 @@ void RenderableFluxNodes::populateStartTimes() { _startTimes.push_back(triggerTime); } else { - LERROR(fmt::format("Error in file formating. Last column in ", - "file '{}' is not on UTC ISO8601 format", timeFile + LERROR(std::format( + "Error in file formating. Last column in file '{}' is not on UTC " + "ISO8601 format", timeFile )); } } @@ -658,7 +659,7 @@ void RenderableFluxNodes::updateActiveTriggerTimeIndex(double currentTime) { auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime); if (iter != _startTimes.end()) { if (iter != _startTimes.begin()) { - std::ptrdiff_t idx = std::distance(_startTimes.begin(), iter); + const std::ptrdiff_t idx = std::distance(_startTimes.begin(), iter); _activeTriggerTimeIndex = static_cast(idx) - 1; } else { @@ -691,7 +692,7 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { if (!earthNode) { LWARNING("Could not find scene graph node 'Earth'"); } - glm::vec3 earthPos = glm::vec3( + const glm::vec3 earthPos = glm::vec3( earthNode->worldPosition() * data.modelTransform.rotation ); @@ -748,7 +749,7 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { _gaussianPulseEnabled ); - glm::vec3 cameraPos = data.camera.positionVec3() * data.modelTransform.rotation; + const glm::vec3 cameraPos = data.camera.positionVec3() * data.modelTransform.rotation; _shaderProgram->setUniform("cameraPos", cameraPos); @@ -823,7 +824,6 @@ void RenderableFluxNodes::update(const UpdateData& data) { _vertexPositions = _statesPos[_activeTriggerTimeIndex]; _vertexColor = _statesColor[_activeTriggerTimeIndex]; _vertexRadius = _statesRadius[_activeTriggerTimeIndex]; - needsUpdate = false; updatePositionBuffer(); updateVertexColorBuffer(); updateVertexFilteringBuffer(); diff --git a/modules/space/rendering/renderablehabitablezone.cpp b/modules/space/rendering/renderablehabitablezone.cpp index 622d69d777..276d8ea5a5 100644 --- a/modules/space/rendering/renderablehabitablezone.cpp +++ b/modules/space/rendering/renderablehabitablezone.cpp @@ -221,8 +221,8 @@ glm::dvec4 RenderableHabitableZone::computeKopparapuZoneBoundaries(float teff, // For the other stars, use a method by Tom E. Morris: // https://www.planetarybiology.com/calculating_habitable_zone.html const double L = static_cast(luminosity); - double inner = std::sqrt(L / 1.1); - double outer = std::sqrt(L / 0.53); + const double inner = std::sqrt(L / 1.1); + const double outer = std::sqrt(L / 0.53); return glm::dvec4(inner, inner, outer, outer); } @@ -236,15 +236,15 @@ glm::dvec4 RenderableHabitableZone::computeKopparapuZoneBoundaries(float teff, // Coefficients for planets of 1 Earth mass. Received from: // https://depts.washington.edu/naivpl/sites/default/files/HZ_coefficients.dat - constexpr Coefficients coefficients[] = { + constexpr std::array coefficients = { // Optimistic Inner boundary - Recent Venus - { 1.77600E+00, 2.13600E-04, 2.53300E-08, -1.33200E-11, -3.09700E-15 }, + Coefficients{ 1.77600E+00, 2.13600E-04, 2.53300E-08, -1.33200E-11, -3.09700E-15 }, // Conservative Inner boundary - Runaway greenhouse - { 1.10700E+00, 1.33200E-04, 1.58000E-08, -8.30800E-12, -1.93100E-15 }, + Coefficients{ 1.10700E+00, 1.33200E-04, 1.58000E-08, -8.30800E-12, -1.93100E-15 }, // Conservative Outer boundary - Maximum greenhouse - { 3.56000E-01, 6.17100E-05, 1.69800E-09, -3.19800E-12, -5.57500E-16 }, + Coefficients{ 3.56000E-01, 6.17100E-05, 1.69800E-09, -3.19800E-12, -5.57500E-16 }, // Optimistic Outer boundary - Early Mars - { 3.20000E-01, 5.54700E-05, 1.52600E-09, -2.87400E-12, -5.01100E-16 } + Coefficients{ 3.20000E-01, 5.54700E-05, 1.52600E-09, -2.87400E-12, -5.01100E-16 } }; const double tstar = static_cast(teff - 5780.f); @@ -252,9 +252,9 @@ glm::dvec4 RenderableHabitableZone::computeKopparapuZoneBoundaries(float teff, const double L = static_cast(luminosity); glm::dvec4 distances; - for (int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; i++) { const Coefficients& coeffs = coefficients[i]; - double seff = coeffs.seffSun + (coeffs.a * tstar) + (coeffs.b * tstar2) + + const double seff = coeffs.seffSun + (coeffs.a * tstar) + (coeffs.b * tstar2) + (coeffs.c * tstar * tstar2) + (coeffs.d * tstar2 * tstar2); distances[i] = std::pow(L / seff, 0.5); diff --git a/modules/space/rendering/renderableorbitalkepler.cpp b/modules/space/rendering/renderableorbitalkepler.cpp index 5acaf7e019..48c16d13d8 100644 --- a/modules/space/rendering/renderableorbitalkepler.cpp +++ b/modules/space/rendering/renderableorbitalkepler.cpp @@ -39,8 +39,8 @@ #include #include #include +#include #include -#include #include #include @@ -274,7 +274,10 @@ void RenderableOrbitalKepler::render(const RenderData& data, RendererTasks&) { _programObject->setUniform(_uniformCache.modelView, calcModelViewTransform(data)); // Because we want the property to work similar to the planet trails - const float fade = pow(_appearance.lineFade.maxValue() - _appearance.lineFade, 2.f); + const float fade = std::pow( + _appearance.lineFade.maxValue() - _appearance.lineFade, + 2.f + ); _programObject->setUniform(_uniformCache.projection, data.camera.projectionMatrix()); _programObject->setUniform(_uniformCache.color, _appearance.lineColor); @@ -304,7 +307,7 @@ void RenderableOrbitalKepler::updateBuffers() { _numObjects = parameters.size(); if (_startRenderIdx >= _numObjects) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Start index {} out of range [0, {}]", _startRenderIdx.value(), _numObjects )); } @@ -312,7 +315,7 @@ void RenderableOrbitalKepler::updateBuffers() { long long endElement = _startRenderIdx + _sizeRender - 1; endElement = (endElement >= _numObjects) ? _numObjects - 1 : endElement; if (endElement < 0 || endElement >= _numObjects) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "End index {} out of range [0, {}]", endElement, _numObjects )); } @@ -327,7 +330,7 @@ void RenderableOrbitalKepler::updateBuffers() { if (_startRenderIdx >= parameters.size() || (_startRenderIdx + _sizeRender) >= parameters.size()) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Tried to load {} objects but only {} are available", _startRenderIdx + _sizeRender, parameters.size() )); @@ -354,7 +357,7 @@ void RenderableOrbitalKepler::updateBuffers() { _segmentSize.clear(); _startIndex.clear(); _startIndex.push_back(0); - for (size_t i = 0; i < parameters.size(); ++i) { + for (size_t i = 0; i < parameters.size(); i++) { const double scale = static_cast(_segmentQuality) * 10.0; const kepler::Parameters& p = parameters[i]; _segmentSize.push_back( @@ -366,8 +369,8 @@ void RenderableOrbitalKepler::updateBuffers() { size_t nVerticesTotal = 0; - int numOrbits = static_cast(parameters.size()); - for (int i = 0; i < numOrbits; ++i) { + const int numOrbits = static_cast(parameters.size()); + for (int i = 0; i < numOrbits; i++) { nVerticesTotal += _segmentSize[i]; } _vertexBufferData.resize(nVerticesTotal); @@ -388,11 +391,11 @@ void RenderableOrbitalKepler::updateBuffers() { orbit.epoch ); - for (GLint j = 0 ; j < (_segmentSize[orbitIdx]); ++j) { - double timeOffset = orbit.period * + for (GLint j = 0 ; j < (_segmentSize[orbitIdx]); j++) { + const double timeOffset = orbit.period * static_cast(j) / static_cast(_segmentSize[orbitIdx] - 1); - glm::dvec3 position = keplerTranslator.position({ + const glm::dvec3 position = keplerTranslator.position({ {}, Time(timeOffset + orbit.epoch), Time(0.0) @@ -443,4 +446,4 @@ void RenderableOrbitalKepler::updateBuffers() { setBoundingSphere(maxSemiMajorAxis * 1000); } -} // namespace opensapce +} // namespace openspace diff --git a/modules/space/rendering/renderablerings.cpp b/modules/space/rendering/renderablerings.cpp index 3d62abbf7e..fbd66b88cd 100644 --- a/modules/space/rendering/renderablerings.cpp +++ b/modules/space/rendering/renderablerings.cpp @@ -246,7 +246,7 @@ void RenderableRings::loadTexture() { if (texture) { LDEBUGC( "RenderableRings", - fmt::format("Loaded texture from {}", absPath(_texturePath)) + std::format("Loaded texture from '{}'", absPath(_texturePath)) ); _texture = std::move(texture); @@ -271,18 +271,18 @@ void RenderableRings::createPlane() { GLfloat t; }; - VertexData data[] = { - { -size, -size, 0.f, 0.f }, - { size, size, 1.f, 1.f }, - { -size, size, 0.f, 1.f }, - { -size, -size, 0.f, 0.f }, - { size, -size, 1.f, 0.f }, - { size, size, 1.f, 1.f }, + const std::array Data = { + VertexData{ -size, -size, 0.f, 0.f }, + VertexData{ size, size, 1.f, 1.f }, + VertexData{ -size, size, 0.f, 1.f }, + VertexData{ -size, -size, 0.f, 0.f }, + VertexData{ size, -size, 1.f, 0.f }, + VertexData{ size, size, 1.f, 1.f }, }; glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, Data.size(), Data.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer( 0, diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index d0b5aa88c0..76f8dede5e 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -662,7 +662,7 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) _colorTextureIsDirty = true; } else { - LWARNING(fmt::format("File not found: {}", _colorTexturePath.value())); + LWARNING(std::format("File not found: {}", _colorTexturePath.value())); } }); _colorTextureFile->setCallback([this]() { _colorTextureIsDirty = true; }); @@ -682,7 +682,7 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) _otherDataColorMapIsDirty = true; } else { - LWARNING(fmt::format("File not found: {}", _otherDataColorMapPath.value())); + LWARNING(std::format("File not found: {}", _otherDataColorMapPath.value())); } }); @@ -770,8 +770,7 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) addPropertySubOwner(_moffatMethodOwner); if (p.fadeInDistances.has_value()) { - glm::vec2 v = *p.fadeInDistances; - _fadeInDistances = v; + _fadeInDistances = *p.fadeInDistances; _disableFadeInDistance = false; _fadeInDistances.setViewOption(properties::Property::ViewOptions::MinMaxRange); addProperty(_fadeInDistances); @@ -779,8 +778,6 @@ RenderableStars::RenderableStars(const ghoul::Dictionary& dictionary) } } -RenderableStars::~RenderableStars() {} - bool RenderableStars::isReady() const { return _program && _pointSpreadFunctionTexture; } @@ -801,9 +798,9 @@ void RenderableStars::initializeGL() { // data value actually exists or not. Once we determine the index, we no longer // need the value and can clear it if (!_queuedOtherData.empty()) { - int idx = _dataset.index(_queuedOtherData); + const int idx = _dataset.index(_queuedOtherData); if (idx == -1) { - LERROR(fmt::format("Could not find other data column {}", _queuedOtherData)); + LERROR(std::format("Could not find other data column {}", _queuedOtherData)); } else { _otherDataOption = idx; @@ -908,8 +905,8 @@ void RenderableStars::loadPSFTexture() { ); if (_pointSpreadFunctionTexture) { - LDEBUG(fmt::format( - "Loaded texture from {}", absPath(_pointSpreadFunctionTexturePath) + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_pointSpreadFunctionTexturePath) )); _pointSpreadFunctionTexture->uploadTexture(); } @@ -929,11 +926,11 @@ void RenderableStars::loadPSFTexture() { void RenderableStars::renderPSFToTexture() { // Creates the FBO for the calculations - GLuint psfFBO; + GLuint psfFBO = 0; glGenFramebuffers(1, &psfFBO); glBindFramebuffer(GL_FRAMEBUFFER, psfFBO); - GLenum drawBuffers[1] = { GL_COLOR_ATTACHMENT0 }; - glDrawBuffers(1, drawBuffers); + GLenum drawBuffers = GL_COLOR_ATTACHMENT0; + glDrawBuffers(1, &drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _psfTexture, 0); glViewport(0, 0, PsfTextureSize, PsfTextureSize); @@ -1039,20 +1036,20 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { _program->activate(); - glm::dvec3 eyePosition = glm::dvec3( + const glm::dvec3 eyePosition = glm::dvec3( glm::inverse(data.camera.combinedViewMatrix()) * glm::dvec4(0.0, 0.0, 0.0, 1.0) ); _program->setUniform(_uniformCache.eyePosition, eyePosition); - glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); + const glm::dvec3 cameraUp = data.camera.lookUpVectorWorldSpace(); _program->setUniform(_uniformCache.cameraUp, cameraUp); - glm::dmat4 modelMatrix = calcModelTransform(data); + const glm::dmat4 modelMatrix = calcModelTransform(data); - glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); + const glm::dmat4 projectionMatrix = glm::dmat4(data.camera.projectionMatrix()); - glm::dmat4 cameraViewProjectionMatrix = projectionMatrix * - data.camera.combinedViewMatrix(); + const glm::dmat4 cameraViewProjectionMatrix = + projectionMatrix * data.camera.combinedViewMatrix(); _program->setUniform(_uniformCache.modelMatrix, modelMatrix); _program->setUniform( @@ -1076,7 +1073,9 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { float fadeInVariable = 1.f; if (!_disableFadeInDistance) { - float distCamera = static_cast(glm::length(data.camera.positionVec3())); + const float distCamera = static_cast( + glm::length(data.camera.positionVec3()) + ); const glm::vec2 fadeRange = _fadeInDistances; const double a = 1.f / ((fadeRange.y - fadeRange.x) * PARSEC); const double b = -(fadeRange.x / (fadeRange.y - fadeRange.x)); @@ -1170,16 +1169,16 @@ void RenderableStars::update(const UpdateData&) { GL_STATIC_DRAW ); - GLint positionAttrib = _program->attributeLocation("in_position"); + const GLint positionAttrib = _program->attributeLocation("in_position"); // bvLumAbsMagAppMag = bv color, luminosity, abs magnitude and app magnitude - GLint bvLumAbsMagAppMagAttrib = _program->attributeLocation( + const GLint bvLumAbsMagAppMagAttrib = _program->attributeLocation( "in_bvLumAbsMagAppMag" ); const size_t nStars = _dataset.entries.size(); const size_t nValues = slice.size() / nStars; - GLsizei stride = static_cast(sizeof(GLfloat) * nValues); + const GLsizei stride = static_cast(sizeof(GLfloat) * nValues); glEnableVertexAttribArray(positionAttrib); glEnableVertexAttribArray(bvLumAbsMagAppMagAttrib); @@ -1224,7 +1223,7 @@ void RenderableStars::update(const UpdateData&) { reinterpret_cast(offsetof(VelocityVBOLayout, value)) ); - GLint velocityAttrib = _program->attributeLocation("in_velocity"); + const GLint velocityAttrib = _program->attributeLocation("in_velocity"); glEnableVertexAttribArray(velocityAttrib); glVertexAttribPointer( velocityAttrib, @@ -1256,7 +1255,7 @@ void RenderableStars::update(const UpdateData&) { reinterpret_cast(offsetof(SpeedVBOLayout, value)) ); - GLint speedAttrib = _program->attributeLocation("in_speed"); + const GLint speedAttrib = _program->attributeLocation("in_speed"); glEnableVertexAttribArray(speedAttrib); glVertexAttribPointer( speedAttrib, @@ -1303,13 +1302,15 @@ void RenderableStars::update(const UpdateData&) { if (_colorTextureIsDirty) { LDEBUG("Reloading Color Texture"); _colorTexture = nullptr; - if (_colorTexturePath.value() != "") { + if (!_colorTexturePath.value().empty()) { _colorTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_colorTexturePath).string(), 1 ); if (_colorTexture) { - LDEBUG(fmt::format("Loaded texture from {}", absPath(_colorTexturePath))); + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_colorTexturePath) + )); _colorTexture->uploadTexture(); } @@ -1332,9 +1333,8 @@ void RenderableStars::update(const UpdateData&) { 1 ); if (_otherDataColorMapTexture) { - LDEBUG(fmt::format( - "Loaded texture from {}", - absPath(_otherDataColorMapPath) + LDEBUG(std::format( + "Loaded texture from '{}'", absPath(_otherDataColorMapPath) )); _otherDataColorMapTexture->uploadTexture(); } @@ -1350,7 +1350,7 @@ void RenderableStars::update(const UpdateData&) { } void RenderableStars::loadData() { - std::filesystem::path file = absPath(_speckFile); + const std::filesystem::path file = absPath(_speckFile); if (!std::filesystem::is_regular_file(file)) { return; } @@ -1367,7 +1367,7 @@ void RenderableStars::loadData() { } _otherDataOption.addOptions(variableNames); - bool success = _dataset.normalizeVariable("lum"); + const bool success = _dataset.normalizeVariable("lum"); if (!success) { throw ghoul::RuntimeError("Could not find required variable 'luminosity'"); } @@ -1486,7 +1486,7 @@ std::vector RenderableStars::createDataSlice(ColorOption option) { static_cast(position[2]) }}; - int index = _otherDataOption.value(); + const int index = _otherDataOption.value(); // plus 3 because of the position layout.value.value = e.data[index]; diff --git a/modules/space/rendering/renderablestars.h b/modules/space/rendering/renderablestars.h index 3119e48614..cc42931b15 100644 --- a/modules/space/rendering/renderablestars.h +++ b/modules/space/rendering/renderablestars.h @@ -52,7 +52,7 @@ namespace documentation { struct Documentation; } class RenderableStars : public Renderable { public: explicit RenderableStars(const ghoul::Dictionary& dictionary); - ~RenderableStars() override; + ~RenderableStars() override = default; void initializeGL() override; void deinitializeGL() override; diff --git a/modules/space/rendering/renderabletravelspeed.cpp b/modules/space/rendering/renderabletravelspeed.cpp index b2bb48429e..5b3ab4d252 100644 --- a/modules/space/rendering/renderabletravelspeed.cpp +++ b/modules/space/rendering/renderabletravelspeed.cpp @@ -153,10 +153,8 @@ RenderableTravelSpeed::RenderableTravelSpeed(const ghoul::Dictionary& dictionary if (SceneGraphNode* n = sceneGraphNode(_targetName); n) { _targetNode = n; _targetPosition = _targetNode->worldPosition(); - _lightTravelTime = calculateLightTravelTime( - _sourcePosition, - _targetPosition - ); + _lightTravelTime = + glm::distance(_targetPosition, _sourcePosition) / _travelSpeed; calculateDirectionVector(); reinitiateTravel(); } @@ -164,9 +162,7 @@ RenderableTravelSpeed::RenderableTravelSpeed(const ghoul::Dictionary& dictionary _travelSpeed = p.travelSpeed.value_or(_travelSpeed); addProperty(_travelSpeed); - _travelSpeed.onChange([this]() { - reinitiateTravel(); - }); + _travelSpeed.onChange([this]() { reinitiateTravel(); }); } void RenderableTravelSpeed::initialize() { @@ -205,11 +201,6 @@ void RenderableTravelSpeed::deinitializeGL() { glDeleteBuffers(1, &_vBufferId); } -double RenderableTravelSpeed::calculateLightTravelTime(glm::dvec3 startPosition, - glm::dvec3 targetPosition) { - return glm::distance(targetPosition, startPosition) / _travelSpeed; -} - void RenderableTravelSpeed::calculateDirectionVector() { _directionVector = glm::normalize(_targetPosition - _sourcePosition); } @@ -273,10 +264,7 @@ void RenderableTravelSpeed::update(const UpdateData& data) { ghoul_assert(mySGNPointer, "Renderable have to be owned by scene graph node"); _sourcePosition = mySGNPointer->worldPosition(); - _lightTravelTime = calculateLightTravelTime( - _sourcePosition, - _targetPosition - ); + _lightTravelTime = glm::distance(_targetPosition, _sourcePosition) / _travelSpeed; const double currentTime = data.time.j2000Seconds(); // Unless we've reached the target diff --git a/modules/space/rendering/renderabletravelspeed.h b/modules/space/rendering/renderabletravelspeed.h index d1d9f2bf7f..d6bc9148a2 100644 --- a/modules/space/rendering/renderabletravelspeed.h +++ b/modules/space/rendering/renderabletravelspeed.h @@ -53,7 +53,6 @@ public: void update(const UpdateData& data) override; private: - double calculateLightTravelTime(glm::dvec3 startPosition, glm::dvec3 targetPosition); void calculateVerticesPositions(); void calculateDirectionVector(); void updateVertexData(); diff --git a/modules/space/rotation/spicerotation.cpp b/modules/space/rotation/spicerotation.cpp index 79d3744c67..53d4d42cde 100644 --- a/modules/space/rotation/spicerotation.cpp +++ b/modules/space/rotation/spicerotation.cpp @@ -73,9 +73,6 @@ namespace { // specified, a reference frame of 'GALACTIC' is used instead std::optional destinationFrame; - // [[codegen::verbatim(DestinationInfo.description)]] - std::optional, std::string>> kernels; - // [[codegen::verbatim(TimeFrameInfo.description)]] std::optional timeFrame [[codegen::reference("core_time_frame")]]; @@ -103,17 +100,6 @@ SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) _sourceFrame = p.sourceFrame; _destinationFrame = p.destinationFrame.value_or("GALACTIC"); - if (p.kernels.has_value()) { - if (std::holds_alternative(*p.kernels)) { - SpiceManager::ref().loadKernel(std::get(*p.kernels)); - } - else { - for (const std::string& s : std::get>(*p.kernels)) { - SpiceManager::ref().loadKernel(s); - } - } - } - _fixedDate.onChange([this]() { if (_fixedDate.value().empty()) { _fixedEphemerisTime = std::nullopt; @@ -126,7 +112,7 @@ SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) addProperty(_fixedDate); if (dictionary.hasKey(TimeFrameInfo.identifier)) { - ghoul::Dictionary timeFrameDictionary = + const ghoul::Dictionary timeFrameDictionary = dictionary.value(TimeFrameInfo.identifier); _timeFrame = TimeFrame::createFromDictionary(timeFrameDictionary); if (_timeFrame == nullptr) { @@ -140,7 +126,6 @@ SpiceRotation::SpiceRotation(const ghoul::Dictionary& dictionary) _sourceFrame.onChange([this]() { requireUpdate(); }); _destinationFrame.onChange([this]() { requireUpdate(); }); - } glm::dmat3 SpiceRotation::matrix(const UpdateData& data) const { diff --git a/modules/space/scripts/spice.lua b/modules/space/scripts/spice.lua new file mode 100644 index 0000000000..0c9dc9f851 --- /dev/null +++ b/modules/space/scripts/spice.lua @@ -0,0 +1,46 @@ +openspace.space.documentation = { + { + Name = "tleToSpiceTranslation", + Arguments = { tlePath = "String" }, + Return = "{ Translation, SpiceKernel }", + Documentation = [[ + Takes the provided TLE file, converts it into a SPICE kernel and returns a + SpiceTranslation instance that can be used to access the information in the TLE + file using SPICE's superior integral solver. + + The second return value is the spice kernel that should be loaded and unloaded by + whoever called this function. + ]] + } +} + +openspace.space.tleToSpiceTranslation = function(tlePath) + -- + -- First we have to create a name for the temporary file + -- + + -- We first pass the path through the absPath function to both get rid of path tokens, + -- but more importantly harmonize the path separators so we don't have to deal with + -- / and \ variants + tlePath = openspace.absPath(tlePath) + + -- We don't have a function to return the file component so we extract the directory + -- and remove as many characters as it is long instead + local dirComponent = openspace.directoryForPath(tlePath) + -- +2 because the sub function is inclusive and we have a trailing \ or / at the end + local filename = tlePath:sub(dirComponent:len() + 2, tlePath:len()) + local temporaryFile = openspace.absPath("${TEMPORARY}/" .. filename .. ".bsp") + -- Now the temporary file for, for example ISS.txt will be the solution for: + -- ${TEMPORARY}/ISS.txt.bsp + + local id = openspace.spice.convertTLEtoSPK(tlePath, temporaryFile) + + local translation = { + Type = "SpiceTranslation", + Target = tostring(id), + Observer = "Earth", + Frame = "J2000" + } + + return translation, temporaryFile +end diff --git a/modules/space/spacemodule.cpp b/modules/space/spacemodule.cpp index 2b025106c1..588fef8258 100644 --- a/modules/space/spacemodule.cpp +++ b/modules/space/spacemodule.cpp @@ -45,6 +45,7 @@ #include #include #include +#include #include #include @@ -138,11 +139,14 @@ std::vector SpaceModule::documentations() const { scripting::LuaLibrary SpaceModule::luaLibrary() const { return { - "space", - { + .name = "space", + .functions = { codegen::lua::ConvertFromRaDec, codegen::lua::ConvertToRaDec, codegen::lua::ReadKeplerFile + }, + .scripts = { + absPath("${MODULE_SPACE}/scripts/spice.lua") } }; } diff --git a/modules/space/spacemodule_lua.inl b/modules/space/spacemodule_lua.inl index 0b63785b0f..7f0da56a5d 100644 --- a/modules/space/spacemodule_lua.inl +++ b/modules/space/spacemodule_lua.inl @@ -93,7 +93,7 @@ std::vector readKeplerFile(std::filesystem::path p, std::stri f = openspace::kepler::Format::SBDB; } else { - throw ghoul::lua::LuaError(fmt::format("Unsupported format '{}'", type)); + throw ghoul::lua::LuaError(std::format("Unsupported format '{}'", type)); } std::vector params = openspace::kepler::readFile(p, f); diff --git a/modules/space/tasks/generatedebrisvolumetask.cpp b/modules/space/tasks/generatedebrisvolumetask.cpp index 5c535ce4fc..28027fdb10 100644 --- a/modules/space/tasks/generatedebrisvolumetask.cpp +++ b/modules/space/tasks/generatedebrisvolumetask.cpp @@ -291,7 +291,7 @@ std::vector readTLEFile(const std::string& filename){ keplerElements.epoch = epochFromSubstring(line.substr(18, 14)); } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "File {} @ line {} does not have '1' header", filename // linNum + 1 )); } @@ -344,7 +344,7 @@ std::vector readTLEFile(const std::string& filename){ stream >> keplerElements.meanMotion; } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "File {} @ line {} does not have '2' header", filename // , lineNum + 2 )); } @@ -402,7 +402,7 @@ std::vector getPositionBuffer(std::vector tleData, Time(0.0), false }); - // LINFO(fmt::format("cart: {} ", position)); + // LINFO(std::format("cart: {} ", position)); glm::dvec3 sphPos; if (gridType == "Spherical"){ sphPos = cartesianToSphericalCoord(position); @@ -419,7 +419,7 @@ std::vector getPositionBuffer(std::vector tleData, if (sphPos.z > maxPhi){ maxPhi = sphPos.z; } - // LINFO(fmt::format("pos: {} ", sphPos)); + // LINFO(std::format("pos: {} ", sphPos)); positionBuffer.push_back(sphPos); } @@ -430,10 +430,10 @@ std::vector getPositionBuffer(std::vector tleData, } - LINFO(fmt::format("max theta: {} ", maxTheta)); - LINFO(fmt::format("max phi: {} ", maxPhi)); - LINFO(fmt::format("min theta: {} ", minTheta)); - LINFO(fmt::format("min phi: {} ", minPhi)); + LINFO(std::format("max theta: {} ", maxTheta)); + LINFO(std::format("max phi: {} ", maxPhi)); + LINFO(std::format("min theta: {} ", minTheta)); + LINFO(std::format("min phi: {} ", minPhi)); return positionBuffer; } @@ -456,7 +456,7 @@ float getDensityAt(glm::uvec3 cell, double* densityArray, RawVolume& raw // return value at position cell from _densityPerVoxel size_t index = raw.coordsToIndex(cell); value = static_cast(densityArray[index]); - //LINFO(fmt::format("indensity: {} ", index)); + //LINFO(std::format("indensity: {} ", index)); return value; } @@ -537,9 +537,9 @@ double* mapDensityToVoxels(double* densityArray, std::vector positio { for (const glm::dvec3& position : positions) { - //LINFO(fmt::format("pos: {} ", position)); + //LINFO(std::format("pos: {} ", position)); int index = getIndexFromPosition(position, dim, maxApogee, gridType); - //LINFO(fmt::format("index: {} ", index)); + //LINFO(std::format("index: {} ", index)); if (gridType == "Cartesian"){ ++densityArray[index]; } @@ -645,7 +645,7 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal } // float maxApogee = getMaxApogee(_TLEDataVector); - LINFO(fmt::format("Max Apogee: {} ", _maxApogee)); + LINFO(std::format("Max Apogee: {} ", _maxApogee)); /** SEQUENCE * 1. handle timeStep @@ -663,7 +663,7 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal // 1.1 int numberOfIterations = static_cast(timeSpan/timeStep); - LINFO(fmt::format("timestep: {} ", numberOfIterations)); + LINFO(std::format("timestep: {} ", numberOfIterations)); std::queue> rawVolumeQueue = {}; const int size = _dimensions.x *_dimensions.y *_dimensions.z; @@ -676,7 +676,7 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal startTimeInSeconds + (i * timeStep), _gridType ); //+(i*timeStep) - //LINFO(fmt::format("pos: {} ", startPositionBuffer[4])); + //LINFO(std::format("pos: {} ", startPositionBuffer[4])); double *densityArrayp = new double[size](); //densityArrayp = mapDensityToVoxels( @@ -726,8 +726,8 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal minVal = std::min(minVal, value); maxVal = std::max(maxVal, value); - /*LINFO(fmt::format("min: {} ", minVal)); - LINFO(fmt::format("max: {} ", maxVal));*/ + /*LINFO(std::format("min: {} ", minVal)); + LINFO(std::format("max: {} ", maxVal));*/ }); rawVolumeQueue.push(rawVolume); delete[] densityArrayp; @@ -735,7 +735,7 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal // two loops is used to get a global min and max value for voxels. for(int i=0 ; i<=numberOfIterations ; ++i){ - // LINFO(fmt::format("raw file output name: {} ", _rawVolumeOutputPath)); + // LINFO(std::format("raw file output name: {} ", _rawVolumeOutputPath)); size_t lastIndex = _rawVolumeOutputPath.find_last_of("."); std::string rawOutputName = _rawVolumeOutputPath.substr(0, lastIndex); @@ -772,8 +772,8 @@ void GenerateDebrisVolumeTask::perform(const Task::ProgressCallback& progressCal metadata.minValue = minVal; metadata.maxValue = maxVal; - /*LINFO(fmt::format("min2: {} ", minVal)); - LINFO(fmt::format("max2: {} ", maxVal));*/ + /*LINFO(std::format("min2: {} ", minVal)); + LINFO(std::format("max2: {} ", maxVal));*/ ghoul::Dictionary outputDictionary = metadata.dictionary(); ghoul::DictionaryLuaFormatter formatter; diff --git a/modules/space/translation/gptranslation.cpp b/modules/space/translation/gptranslation.cpp index 0def33012c..ad27c563e3 100644 --- a/modules/space/translation/gptranslation.cpp +++ b/modules/space/translation/gptranslation.cpp @@ -72,12 +72,12 @@ GPTranslation::GPTranslation(const ghoul::Dictionary& dictionary) { ); if (element > static_cast(parameters.size())) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Requested element {} but only {} are available", element, parameters.size() )); } - kepler::Parameters param = parameters[element - 1]; + const kepler::Parameters& param = parameters[element - 1]; setKeplerElements( param.eccentricity, param.semiMajorAxis, diff --git a/modules/space/translation/horizonstranslation.cpp b/modules/space/translation/horizonstranslation.cpp index 7709f8fbd6..8e34504f8f 100644 --- a/modules/space/translation/horizonstranslation.cpp +++ b/modules/space/translation/horizonstranslation.cpp @@ -85,7 +85,7 @@ HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) if (std::holds_alternative(p.horizonsTextFile)) { std::string file = std::get(p.horizonsTextFile); if (!std::filesystem::is_regular_file(absPath(file))) { - LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); + LWARNING(std::format("The Horizons text file '{}' could not be found", file)); return; } @@ -94,12 +94,12 @@ HorizonsTranslation::HorizonsTranslation(const ghoul::Dictionary& dictionary) _horizonsTextFiles = files; } else if (std::holds_alternative>(p.horizonsTextFile)) { - std::vector files = + const std::vector files = std::get>(p.horizonsTextFile); for (const std::string& file : files) { if (!std::filesystem::is_regular_file(absPath(file))) { - LWARNING(fmt::format( + LWARNING(std::format( "The Horizons text file '{}' could not be found", file )); return; @@ -122,11 +122,11 @@ glm::dvec3 HorizonsTranslation::position(const UpdateData& data) const { if (lastBefore && firstAfter) { // We're inbetween first and last value. - double timelineDiff = firstAfter->timestamp - lastBefore->timestamp; - double timeDiff = data.time.j2000Seconds() - lastBefore->timestamp; - double diff = (timelineDiff > DBL_EPSILON) ? timeDiff / timelineDiff : 0.0; + const double timelineDiff = firstAfter->timestamp - lastBefore->timestamp; + const double timeDiff = data.time.j2000Seconds() - lastBefore->timestamp; + const double diff = (timelineDiff > DBL_EPSILON) ? timeDiff / timelineDiff : 0.0; - glm::dvec3 dir = firstAfter->data - lastBefore->data; + const glm::dvec3 dir = firstAfter->data - lastBefore->data; interpolatedPos = lastBefore->data + dir * diff; } else if (lastBefore) { @@ -145,14 +145,14 @@ void HorizonsTranslation::loadData() { for (const std::string& filePath : _horizonsTextFiles.value()) { std::filesystem::path file = absPath(filePath); if (!std::filesystem::is_regular_file(file)) { - LWARNING(fmt::format("The Horizons text file '{}' could not be found", file)); + LWARNING(std::format("The Horizons text file '{}' could not be found", file)); return; } std::filesystem::path cachedFile = FileSys.cacheManager()->cachedFilename(file); - bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); + const bool hasCachedFile = std::filesystem::is_regular_file(cachedFile); if (hasCachedFile) { - LINFO(fmt::format( + LINFO(std::format( "Cached file '{}' used for Horizon file '{}'", cachedFile, file )); @@ -166,13 +166,13 @@ void HorizonsTranslation::loadData() { } } else { - LINFO(fmt::format("Cache for Horizon file '{}' not found", file)); + LINFO(std::format("Cache for Horizon file '{}' not found", file)); } - LINFO(fmt::format("Loading Horizon file '{}'", file)); + LINFO(std::format("Loading Horizon file '{}'", file)); HorizonsFile horizonsFile(file); if (!readHorizonsTextFile(horizonsFile)) { - LERROR(fmt::format("Could not read data from Horizons file '{}'", file)); + LERROR(std::format("Could not read data from Horizons file '{}'", file)); return; } @@ -210,7 +210,7 @@ bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { std::ifstream fileStream(file, std::ifstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for loading cache file", file)); + LERROR(std::format("Error opening file '{}' for loading cache file", file)); return false; } @@ -241,10 +241,10 @@ bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { ); // Extract the data from the cache Keyframe vector - for (int i = 0; i < nKeyframes; ++i) { + for (int i = 0; i < nKeyframes; i++) { // Add keyframe in timeline _timeline.addKeyframe( - std::move(cacheKeyframes[i].timestamp), + cacheKeyframes[i].timestamp, { cacheKeyframes[i].position[0], cacheKeyframes[i].position[1], @@ -259,7 +259,7 @@ bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) const { std::ofstream fileStream(file, std::ofstream::binary); if (!fileStream.good()) { - LERROR(fmt::format("Error opening file {} for save cache file", file)); + LERROR(std::format("Error opening file '{}' for save cache file", file)); return; } diff --git a/modules/space/translation/keplertranslation.cpp b/modules/space/translation/keplertranslation.cpp index 3f13ceff46..547a5b1efa 100644 --- a/modules/space/translation/keplertranslation.cpp +++ b/modules/space/translation/keplertranslation.cpp @@ -35,7 +35,7 @@ namespace { T solveIteration(const Func& function, T x0, const T& err = 0.0, int maxIter = 100) { T x2 = x0; - for (int i = 0; i < maxIter; ++i) { + for (int i = 0; i < maxIter; i++) { T x = x2; x2 = function(x); if (std::abs(x2 - x) < err) { @@ -236,7 +236,7 @@ double KeplerTranslation::eccentricAnomaly(double meanAnomaly) const { auto sign = [](double val) -> double { return val > 0.0 ? 1.0 : ((val < 0.0) ? -1.0 : 0.0); }; - double e = meanAnomaly + 0.85 * _eccentricity * sign(sin(meanAnomaly)); + const double e = meanAnomaly + 0.85 * _eccentricity * sign(sin(meanAnomaly)); auto solver = [this, &meanAnomaly, &sign](double x) -> double { const double s = _eccentricity * sin(x); diff --git a/modules/space/translation/spicetranslation.cpp b/modules/space/translation/spicetranslation.cpp index 9291c594ec..5d1b7a4a84 100644 --- a/modules/space/translation/spicetranslation.cpp +++ b/modules/space/translation/spicetranslation.cpp @@ -88,10 +88,6 @@ namespace { std::optional fixedDate [[codegen::annotation("A date to lock the position to")]]; - - // A single kernel or list of kernels that this SpiceTranslation depends on. All - // provided kernels will be loaded before any other operation is performed - std::optional, std::string>> kernels; }; #include "spicetranslation_codegen.cpp" } // namespace @@ -111,32 +107,6 @@ SpiceTranslation::SpiceTranslation(const ghoul::Dictionary& dictionary) { const Parameters p = codegen::bake(dictionary); - auto loadKernel = [](const std::string& kernel) { - if (!std::filesystem::is_regular_file(kernel)) { - throw SpiceManager::SpiceException(fmt::format( - "Kernel '{}' does not exist", kernel - )); - } - - try { - SpiceManager::ref().loadKernel(kernel); - } - catch (const SpiceManager::SpiceException& exception) { - LERRORC("SpiceEphemeris", exception.message); - } - }; - - if (p.kernels.has_value()) { - if (std::holds_alternative(*p.kernels)) { - loadKernel(absPath(std::get(*p.kernels)).string()); - } - else { - for (const std::string& k : std::get>(*p.kernels)) { - loadKernel(absPath(k).string()); - } - } - } - _target.onChange([this]() { _cachedTarget = _target; requireUpdate(); diff --git a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp index 25ffc06545..66409cab5a 100644 --- a/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp +++ b/modules/spacecraftinstruments/dashboard/dashboarditeminstruments.cpp @@ -72,8 +72,8 @@ namespace { return progress; } - glm::vec2 addToBoundingbox(glm::vec2 lhs, glm::vec2 rhs) { - return { std::max(lhs.x, rhs.x), lhs.y + rhs.y }; + glm::vec2 addToBoundingbox(const glm::vec2& lhs, const glm::vec2& rhs) { + return glm::vec2(std::max(lhs.x, rhs.x), lhs.y + rhs.y); } struct [[codegen::Dictionary(DashboardItemInstruments)]] Parameters { @@ -122,7 +122,7 @@ DashboardItemInstruments::DashboardItemInstruments(const ghoul::Dictionary& dict void DashboardItemInstruments::render(glm::vec2& penPosition) { ZoneScoped; - double currentTime = global::timeManager->time().j2000Seconds(); + const double currentTime = global::timeManager->time().j2000Seconds(); if (!ImageSequencer::ref().isReady()) { return; @@ -133,9 +133,9 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { constexpr glm::vec4 targetColor(0.f, 0.75f, 1.f, 1.f); - double previous = sequencer.prevCaptureTime(currentTime); - double next = sequencer.nextCaptureTime(currentTime); - double remaining = next - currentTime; + const double previous = sequencer.prevCaptureTime(currentTime); + const double next = sequencer.nextCaptureTime(currentTime); + const double remaining = next - currentTime; float t = static_cast(1.0 - remaining / (next - previous)); t = std::clamp(t, 0.f, 1.f); @@ -156,11 +156,11 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { } const int Size = 25; - int p = std::max(static_cast((t * (Size - 1)) + 1), 0); + const int p = std::max(static_cast((t * (Size - 1)) + 1), 0); RenderFont( *_font, penPosition, - fmt::format( + std::format( "{:4.0f} {:s} |{:s}>{:s}| {:.1f} %", remainingConv.first, remainingConv.second, @@ -180,7 +180,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format("Data acquisition time: {}", str), + std::format("Data acquisition time: {}", str), glm::vec4(_activeColor.value(), 1.f), ghoul::fontrendering::CrDirection::Down ); @@ -203,7 +203,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format( + std::format( "Next image: [{:02d}:{:02d}:{:02d}]", tlh.count(), tlm.count(), tls.count() ), targetColor, @@ -215,7 +215,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { const std::vector>& activeMap = sequencer.activeInstruments(currentTime); - glm::vec4 firing = glm::vec4(0.58f - t, 1.f - t, 1.f - t, 1.f); + const glm::vec4 firing = glm::vec4(0.58f - t, 1.f - t, 1.f - t, 1.f); RenderFont( *_font, @@ -234,7 +234,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { RenderFont(*_font, penPosition, " |", glm::vec4(0.3f, 0.3f, 0.3f, 1.f)); RenderFont(*_font, penPosition, - fmt::format(" {:5s}", m.first), + std::format(" {:5s}", m.first), glm::vec4(_activeColor.value(), 1.f), ghoul::fontrendering::CrDirection::Down ); @@ -244,7 +244,7 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { RenderFont( *_font, penPosition, - fmt::format(" {:5s}", m.first), + std::format(" {:5s}", m.first), glm::vec4(0.3f, 0.3f, 0.3f, 1.f), ghoul::fontrendering::CrDirection::Down ); @@ -253,24 +253,24 @@ void DashboardItemInstruments::render(glm::vec2& penPosition) { } glm::vec2 DashboardItemInstruments::size() const { - glm::vec2 size = glm::vec2(0.f); - double currentTime = global::timeManager->time().j2000Seconds(); + const double time = global::timeManager->time().j2000Seconds(); if (!ImageSequencer::ref().isReady()) { return glm::vec2(0.f); } - ImageSequencer& sequencer = ImageSequencer::ref(); + const ImageSequencer& sequencer = ImageSequencer::ref(); - double previous = sequencer.prevCaptureTime(currentTime); - double next = sequencer.nextCaptureTime(currentTime); - double remaining = sequencer.nextCaptureTime(currentTime) - currentTime; + const double previous = sequencer.prevCaptureTime(time); + const double next = sequencer.nextCaptureTime(time); + const double remaining = sequencer.nextCaptureTime(time) - time; const float t = static_cast(1.0 - remaining / (next - previous)); const std::string& str = SpiceManager::ref().dateFromEphemerisTime( - sequencer.nextCaptureTime(currentTime), + sequencer.nextCaptureTime(time), "YYYY MON DD HR:MN:SC" ); + glm::vec2 size = glm::vec2(0.f); if (remaining > 0.0) { std::string progress = progressToStr(25, t); @@ -279,23 +279,23 @@ glm::vec2 DashboardItemInstruments::size() const { size = addToBoundingbox( size, _font->boundingBox( - fmt::format("{:.0f} s {:s} {:.1f} %", remaining, progress, t * 100.f) + std::format("{:.0f} s {:s} {:.1f} %", remaining, progress, t * 100.f) ) ); size = addToBoundingbox( size, - _font->boundingBox(fmt::format("Data acquisition time: {}", str)) + _font->boundingBox(std::format("Data acquisition time: {}", str)) ); } - std::pair nextTarget = sequencer.nextTarget(currentTime); - std::pair currentTarget = sequencer.currentTarget(currentTime); + const std::pair nextTarget = sequencer.nextTarget(time); + const std::pair currentTarget = sequencer.currentTarget(time); if (currentTarget.first <= 0.0) { return size; } - const int timeleft = static_cast(nextTarget.first - currentTime); + const int timeleft = static_cast(nextTarget.first - time); const int hour = timeleft / 3600; int second = timeleft % 3600; @@ -323,7 +323,7 @@ glm::vec2 DashboardItemInstruments::size() const { size = addToBoundingbox( size, _font->boundingBox( - fmt::format("Data acquisition adjacency: [{}:{}:{}]", hh, mm, ss) + std::format("Data acquisition adjacency: [{}:{}:{}]", hh, mm, ss) ) ); diff --git a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp index ab89151dbc..5654208eac 100644 --- a/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp +++ b/modules/spacecraftinstruments/rendering/renderablecrawlingline.cpp @@ -36,8 +36,8 @@ namespace { struct VBOData { - float position[3]; - float color[4]; + std::array position; + std::array color; }; struct [[codegen::Dictionary(RenderableCrawlingLine)]] Parameters { @@ -142,13 +142,12 @@ void RenderableCrawlingLine::render(const RenderData& data, RendererTasks&) { _program->activate(); _frameCounter++; - glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform(data); + const glm::dmat4 modelViewProjection = calcModelViewProjectionTransform(data); + _program->setUniform("modelViewProjection", modelViewProjection); - _program->setUniform("modelViewProjection", modelViewProjectionTransform); - - int frame = _frameCounter % 60; - float fadingFactor = static_cast(sin((frame * glm::pi()) / 60)); - float alpha = 0.6f + fadingFactor*0.4f; + const int frame = _frameCounter % 60; + const float fadingFactor = std::sin(frame * glm::pi() / 60.f); + const float alpha = 0.6f + fadingFactor * 0.4f; glLineWidth(2.f); @@ -176,12 +175,12 @@ void RenderableCrawlingLine::update(const UpdateData& data) { const glm::dvec3 boresight = res.boresightVector; const glm::vec4 target = glm::dmat4(tm) * glm::vec4(boresight, 12); - VBOData vboData[2] = { - { + std::array vboData = { + VBOData { { 0.f, 0.f, 0.f }, { _lineColorBegin.r, _lineColorBegin.g, _lineColorBegin.b, _lineColorBegin.a } }, - { + VBOData { { target.x * powf(10, target.w), target.y * powf(10, target.w), @@ -193,10 +192,10 @@ void RenderableCrawlingLine::update(const UpdateData& data) { glBindBuffer(GL_ARRAY_BUFFER, _vbo); - glBufferSubData(GL_ARRAY_BUFFER, 0, 2 * sizeof(VBOData), vboData); + glBufferSubData(GL_ARRAY_BUFFER, 0, 2 * sizeof(VBOData), vboData.data()); if (ImageSequencer::ref().isReady()) { - float imageSequenceTime = ImageSequencer::ref().instrumentActiveTime( + const float imageSequenceTime = ImageSequencer::ref().instrumentActiveTime( data.time.j2000Seconds(), _instrumentName ); diff --git a/modules/spacecraftinstruments/rendering/renderablefov.cpp b/modules/spacecraftinstruments/rendering/renderablefov.cpp index 6e9a1b402b..4af3d48cbb 100644 --- a/modules/spacecraftinstruments/rendering/renderablefov.cpp +++ b/modules/spacecraftinstruments/rendering/renderablefov.cpp @@ -301,14 +301,14 @@ void RenderableFov::initializeGL() { res.shape == SpiceManager::FieldOfViewResult::Shape::Rectangle; if (!supportedShape) { throw ghoul::RuntimeError( - fmt::format("'{}' has unsupported shape", _instrument.name), + std::format("'{}' has unsupported shape", _instrument.name), "RenderableFov" ); } if (_simplifyBounds) { const size_t sizeBefore = res.bounds.size(); - for (size_t i = 1; i < res.bounds.size() - 1; ++i) { + for (size_t i = 1; i < res.bounds.size() - 1; i++) { const glm::dvec3& prev = res.bounds[i - 1]; const glm::dvec3& curr = res.bounds[i]; const glm::dvec3& next = res.bounds[i + 1]; @@ -329,7 +329,7 @@ void RenderableFov::initializeGL() { LINFOC( _instrument.name, - fmt::format("Simplified from {} to {}", sizeBefore, sizeAfter) + std::format("Simplified from {} to {}", sizeBefore, sizeAfter) ); } @@ -448,8 +448,8 @@ glm::dvec3 RenderableFov::orthogonalProjection(const glm::dvec3& vecFov, double const std::string& target) const { if (target.empty()) { - glm::dvec3 vec = glm::dvec3(1.0, 0.0, 0.0); - return glm::normalize(glm::cross(vec, vecFov)); + constexpr glm::dvec3 Up = glm::dvec3(1.0, 0.0, 0.0); + return glm::normalize(glm::cross(Up, vecFov)); } else { const glm::dvec3 vecToTarget = SpiceManager::ref().targetPosition( @@ -473,7 +473,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, bool isInFov) { auto makeBodyFixedReferenceFrame = - [&target](std::string ref) -> std::pair + [&target](const std::string& ref) -> std::pair { const bool convert = (ref.find("IAU_") == std::string::npos); if (convert) { @@ -489,7 +489,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, // First we fill the field-of-view bounds array by testing each bounds vector against // the object. We need to test it against the object (rather than using a fixed // distance) as the field of view rendering should stop at the surface - for (size_t i = 0; i < _instrument.bounds.size(); ++i) { + for (size_t i = 0; i < _instrument.bounds.size(); i++) { const glm::dvec3& bound = _instrument.bounds[i]; RenderInformation::VBOData& first = _fieldOfViewBounds.data[2 * i]; @@ -515,7 +515,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, else { // The target is in the field of view, but not the entire field of view has to // be filled by the target - std::pair ref = makeBodyFixedReferenceFrame( + const std::pair ref = makeBodyFixedReferenceFrame( _instrument.referenceFrame ); @@ -582,7 +582,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, // An early out for when the target is not in field of view if (!isInFov) { - for (size_t i = 0; i < _instrument.bounds.size(); ++i) { + for (size_t i = 0; i < _instrument.bounds.size(); i++) { // If none of the points are able to intersect with the target, we can just // copy the values from the field-of-view boundary. So we take each second // item (the first one is (0,0,0)) and replicate it 'InterpolationSteps' times @@ -591,7 +591,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, } else { // At least one point will intersect - for (size_t i = 0; i < _instrument.bounds.size(); ++i) { + for (size_t i = 0; i < _instrument.bounds.size(); i++) { // Wrap around the array index to 0 const size_t j = (i == _instrument.bounds.size() - 1) ? 0 : i + 1; @@ -663,7 +663,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, #if 0 // DEBUG_THIS // At least one point will intersect - for (size_t i = 0; i < _instrument.bounds.size(); ++i) { + for (size_t i = 0; i < _instrument.bounds.size(); i++) { // Wrap around the array index to 0 const size_t j = (i == _instrument.bounds.size() - 1) ? 0 : i + 1; @@ -726,7 +726,7 @@ void RenderableFov::computeIntercepts(double time, const std::string& target, copyFieldOfViewValues(i, p2, indexForBounds(j)); // Are recompute the intersecting ones - for (size_t k = 0; k <= (p2 - p1); ++k) { + for (size_t k = 0; k <= (p2 - p1); k++) { const double t = t1 + k * (t2 - t1); const glm::dvec3 interpolated = glm::mix(iBound, jBound, t); const glm::vec3 icpt = interceptVector(interpolated); @@ -764,7 +764,7 @@ void RenderableFov::render(const RenderData& data, RendererTasks&) { _program->activate(); // Model transform and view transform needs to be in double precision - glm::mat4 modelViewProjectionTransform = + const glm::mat4 modelViewProjectionTransform = calcModelViewProjectionTransform(data); _program->setUniform(_uniformCache.modelViewProjection, modelViewProjectionTransform); @@ -835,7 +835,7 @@ std::pair RenderableFov::determineTarget(double time) { // First, for all potential targets, check whether they are in the field of view for (const std::string& pt : _instrument.potentialTargets) { - bool inFOV = SpiceManager::ref().isTargetInFieldOfView( + const bool inFOV = SpiceManager::ref().isTargetInFieldOfView( pt, _instrument.spacecraft, global::moduleEngine->module()->frameFromBody( @@ -865,7 +865,7 @@ std::pair RenderableFov::determineTarget(double time) { _instrument.potentialTargets.end(), distances.begin(), [&i = _instrument, &t = time] (const std::string& pt) { - double lt; + double lt = 0.0; const glm::dvec3 p = SpiceManager::ref().targetPosition( pt, i.spacecraft, diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 98884e3c70..97a5371bea 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -118,7 +118,7 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di { const Parameters p = codegen::bake(dictionary); - std::filesystem::path file = absPath(p.geometryFile.string()); + const std::filesystem::path file = absPath(p.geometryFile.string()); _geometry = ghoul::io::ModelReader::ref().loadModel( file.string(), ghoul::io::ModelReader::ForceRenderInvisible::No, @@ -129,9 +129,9 @@ RenderableModelProjection::RenderableModelProjection(const ghoul::Dictionary& di if (p.modelScale.has_value()) { if (std::holds_alternative(*p.modelScale)) { - Parameters::ScaleUnit scaleUnit = + const Parameters::ScaleUnit scaleUnit = std::get(*p.modelScale); - DistanceUnit distanceUnit = codegen::map(scaleUnit); + const DistanceUnit distanceUnit = codegen::map(scaleUnit); _modelScale = toMeter(distanceUnit); } else if (std::holds_alternative(*p.modelScale)) { @@ -231,15 +231,15 @@ void RenderableModelProjection::render(const RenderData& data, RendererTasks&) { _projectionComponent.clearAllProjections(); } - glm::vec3 up = data.camera.lookUpVectorCameraSpace(); + const glm::vec3 up = data.camera.lookUpVectorCameraSpace(); if (_shouldCapture && _projectionComponent.doesPerformProjection()) { for (const Image& i : _imageTimes) { try { - glm::mat4 projectorMatrix = attitudeParameters(i.timeRange.start, up); - std::shared_ptr t = + const glm::mat4 projectorMat = attitudeParameters(i.timeRange.start, up); + const std::shared_ptr t = _projectionComponent.loadProjectionTexture(i.path, i.isPlaceholder); - imageProjectGPU(*t, projectorMatrix); + imageProjectGPU(*t, projectorMat); } catch (const SpiceManager::SpiceException& e) { LERRORC(e.component, e.what()); @@ -436,7 +436,7 @@ glm::mat4 RenderableModelProjection::attitudeParameters(double time, const glm:: ); _boresight = std::move(res.boresightVector); - double lightTime; + double lightTime = 0.0; const glm::dvec3 p = SpiceManager::ref().targetPosition( _projectionComponent.projectorId(), _projectionComponent.projecteeId(), diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 19f653a933..1bbadb7caa 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -68,10 +68,10 @@ documentation::Documentation RenderablePlaneProjection::Documentation() { return codegen::doc("spacecraftinstruments_renderableplaneprojection"); } -RenderablePlaneProjection::RenderablePlaneProjection(const ghoul::Dictionary& dict) - : Renderable(dict) +RenderablePlaneProjection::RenderablePlaneProjection(const ghoul::Dictionary& dictionary) + : Renderable(dictionary) { - const Parameters p = codegen::bake(dict); + const Parameters p = codegen::bake(dictionary); _spacecraft = p.spacecraft; _instrument = p.instrument; _defaultTarget = p.defaultTarget.value_or(_defaultTarget); @@ -82,8 +82,6 @@ RenderablePlaneProjection::RenderablePlaneProjection(const ghoul::Dictionary& di } } -RenderablePlaneProjection::~RenderablePlaneProjection() {} - bool RenderablePlaneProjection::isReady() const { return _shader && _texture; } @@ -223,7 +221,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime LERROR(e.what()); } - double lt; + double lt = 0.0; const glm::dvec3 vecToTarget = SpiceManager::ref().targetPosition( _target.body, _spacecraft, @@ -239,7 +237,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime std::array projection; std::fill(projection.begin(), projection.end(), glm::vec3(0.f)); - for (size_t j = 0; j < bounds.size(); ++j) { + for (size_t j = 0; j < bounds.size(); j++) { bounds[j] = SpiceManager::ref().frameTransformationMatrix( frame, "GALACTIC", @@ -258,7 +256,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime projection[j] = glm::vec3(cornerPosition * 1000.0); } - const GLfloat vertex_data[] = { + const std::array VertexData = { // square of two triangles drawn within fov in target coordinates // x y z w s t // Lower left 1 @@ -277,7 +275,7 @@ void RenderablePlaneProjection::updatePlane(const Image& img, double currentTime glBindVertexArray(_quad); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, nullptr); glEnableVertexAttribArray(1); diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.h b/modules/spacecraftinstruments/rendering/renderableplaneprojection.h index 3a7acfb139..fcb974c765 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.h +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.h @@ -46,7 +46,7 @@ struct UpdateData; class RenderablePlaneProjection : public Renderable { public: RenderablePlaneProjection(const ghoul::Dictionary& dictionary); - ~RenderablePlaneProjection() override; + ~RenderablePlaneProjection() override = default; void initializeGL() override; void deinitializeGL() override; diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index 4ec427d2f9..4668b24a38 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -355,7 +355,7 @@ void RenderablePlanetProjection::initializeGL() { setBoundingSphere(std::max(std::max(radius[0], radius[1]), radius[2])); // SCREEN-QUAD - const GLfloat vertexData[] = { + constexpr std::array VertexData = { -1.f, -1.f, 1.f, 1.f, -1.f, 1.f, @@ -368,7 +368,7 @@ void RenderablePlanetProjection::initializeGL() { glBindVertexArray(_quad); glGenBuffers(1, &_vertexPositionBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); @@ -429,18 +429,18 @@ void RenderablePlanetProjection::imageProjectGPU( glm::mat4 RenderablePlanetProjection::attitudeParameters(double time, const glm::vec3& up) { // precomputations for shader - glm::dmat3 instrumentMatrix = SpiceManager::ref().positionTransformMatrix( + const glm::dmat3 instrumentMatrix = SpiceManager::ref().positionTransformMatrix( _projectionComponent.instrumentId(), "GALACTIC", time ); - SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( + const SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView( _projectionComponent.instrumentId() ); - double lightTime; - glm::dvec3 p = SpiceManager::ref().targetPosition( + double lightTime = 0.0; + const glm::dvec3 p = SpiceManager::ref().targetPosition( _projectionComponent.projectorId(), _projectionComponent.projecteeId(), "GALACTIC", @@ -479,7 +479,7 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _projectionComponent.generateMipMap(); } - glm::vec3 up = data.camera.lookUpVectorCameraSpace(); + const glm::vec3 up = data.camera.lookUpVectorCameraSpace(); if (_projectionComponent.doesPerformProjection()) { int nProjections = 0; for (const Image& img : _imageTimes) { @@ -487,10 +487,10 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) break; } try { - glm::mat4 projectorMatrix = attitudeParameters(img.timeRange.start, up); - std::shared_ptr t = + const glm::mat4 projMatrix = attitudeParameters(img.timeRange.start, up); + const std::shared_ptr t = _projectionComponent.loadProjectionTexture(img.path); - imageProjectGPU(*t, projectorMatrix); + imageProjectGPU(*t, projMatrix); ++nProjections; } catch (const SpiceManager::SpiceException& e) { @@ -507,8 +507,8 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) LERRORC(e.component, e.what()); } - double lt; - glm::dvec3 sunPos = SpiceManager::ref().targetPosition( + double lt = 0.0; + const glm::dvec3 sunPos = SpiceManager::ref().targetPosition( "SUN", _projectionComponent.projecteeId(), "GALACTIC", @@ -546,21 +546,23 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) _projectionComponent.projectionFading() ); - ghoul::opengl::TextureUnit unit[3]; + ghoul::opengl::TextureUnit baseUnit; if (_baseTexture) { - unit[0].activate(); + baseUnit.activate(); _baseTexture->bind(); - _programObject->setUniform(_mainUniformCache.baseTexture, unit[0]); + _programObject->setUniform(_mainUniformCache.baseTexture, baseUnit); } - unit[1].activate(); + ghoul::opengl::TextureUnit projectionUnit; + projectionUnit.activate(); _projectionComponent.projectionTexture().bind(); - _programObject->setUniform(_mainUniformCache.projectionTexture, unit[1]); + _programObject->setUniform(_mainUniformCache.projectionTexture, projectionUnit); + ghoul::opengl::TextureUnit heightUnit; if (_heightMapTexture) { - unit[2].activate(); + heightUnit.activate(); _heightMapTexture->bind(); - _programObject->setUniform(_mainUniformCache.heightTexture, unit[2]); + _programObject->setUniform(_mainUniformCache.heightTexture, heightUnit); } _sphere->render(); @@ -615,7 +617,7 @@ void RenderablePlanetProjection::update(const UpdateData& data) { ); if (!newImageTimes.empty()) { - double firstNewImage = newImageTimes[0].timeRange.end; + const double firstNewImage = newImageTimes[0].timeRange.end; // Make sure images are always projected in the correct order // (Remove buffered images with a later timestamp) const auto& it = std::find_if( @@ -644,7 +646,7 @@ void RenderablePlanetProjection::update(const UpdateData& data) { void RenderablePlanetProjection::loadColorTexture() { using ghoul::opengl::Texture; - std::string selectedPath = _colorTexturePaths.option().description; + const std::string selectedPath = _colorTexturePaths.option().description; // We delete the texture first in order to free up the memory, which could otherwise // run out in the case of two large textures @@ -667,7 +669,7 @@ void RenderablePlanetProjection::loadColorTexture() { void RenderablePlanetProjection::loadHeightTexture() { using ghoul::opengl::Texture; - std::string selectedPath = _heightMapTexturePaths.option().description; + const std::string selectedPath = _heightMapTexturePaths.option().description; // We delete the texture first in order to free up the memory, which could otherwise // run out in the case of two large textures diff --git a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp index e2ae7aa2e8..f2d9bda2d8 100644 --- a/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp +++ b/modules/spacecraftinstruments/rendering/renderableshadowcylinder.cpp @@ -206,10 +206,10 @@ RenderableShadowCylinder::RenderableShadowCylinder(const ghoul::Dictionary& dict { static_cast(T::LightTimeStellar), "Light Time Stellar" }, }); - SpiceManager::AberrationCorrection aberration = SpiceManager::AberrationCorrection( + const SpiceManager::AberrationCorrection abbcorr = SpiceManager::AberrationCorrection( p.aberration ); - _aberration = static_cast(aberration.type); + _aberration = static_cast(abbcorr.type); } void RenderableShadowCylinder::initializeGL() { @@ -315,7 +315,7 @@ void RenderableShadowCylinder::createCylinder(double time) { [](const glm::dvec3& p) { return p * 1000.0; } ); - double lt; + double lt = 0.0; glm::dvec3 vecLightSource = SpiceManager::ref().targetPosition( _body, _lightSource, diff --git a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp index 9efca1a851..34ed44b2b3 100644 --- a/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp +++ b/modules/spacecraftinstruments/spacecraftinstrumentsmodule.cpp @@ -113,7 +113,7 @@ std::string SpacecraftInstrumentsModule::frameFromBody(const std::string& body) constexpr std::string_view unionPrefix = "IAU_"; if (body.find(unionPrefix) == std::string::npos) { - return fmt::format("{}{}", unionPrefix, body); + return std::format("{}{}", unionPrefix, body); } else { return body; diff --git a/modules/spacecraftinstruments/util/hongkangparser.cpp b/modules/spacecraftinstruments/util/hongkangparser.cpp index 9024f434cc..87842787b7 100644 --- a/modules/spacecraftinstruments/util/hongkangparser.cpp +++ b/modules/spacecraftinstruments/util/hongkangparser.cpp @@ -82,11 +82,11 @@ HongKangParser::HongKangParser(std::string name, std::string fileName, continue; } - ghoul::Dictionary typeDictionary = + const ghoul::Dictionary typeDictionary = translationDictionary.value(decoderType); // for each playbook call -> create a Decoder object for (std::string_view key : typeDictionary.keys()) { - const std::string& currentKey = fmt::format("{}.{}", decoderType, key); + const std::string& currentKey = std::format("{}.{}", decoderType, key); ghoul::Dictionary decoderDictionary; if (translationDictionary.hasValue(currentKey)) { @@ -132,7 +132,7 @@ bool HongKangParser::create() { const bool hasObserver = SpiceManager::ref().hasNaifId(_spacecraft); if (!hasObserver) { throw ghoul::RuntimeError( - fmt::format("SPICE has no observer: '{}' in kernel pool", _spacecraft), + std::format("SPICE has no observer '{}' in kernel pool", _spacecraft), "HongKangParser" ); } @@ -142,7 +142,7 @@ bool HongKangParser::create() { "HongKangParser" ); } - size_t position = _fileName.find_last_of('.') + 1; + const size_t position = _fileName.find_last_of('.') + 1; if (position == 0 || position == std::string::npos) { return true; } @@ -168,7 +168,7 @@ bool HongKangParser::create() { while (!file.eof()) { std::getline(file, line); - std::string event = line.substr(0, line.find_first_of(' ')); + const std::string event = line.substr(0, line.find_first_of(' ')); const auto it = _fileTranslation.find(event); const bool foundEvent = (it != _fileTranslation.end()); @@ -208,13 +208,13 @@ bool HongKangParser::create() { _targetTimes.emplace_back(time, image.target); } - // store actual image in map. All targets get _only_ their corresp. subset - _subsetMap[image.target]._subset.push_back(image); // compute and store the range for each subset _subsetMap[image.target]._range.include(time); + // store actual image in map. All targets get _only_ their corresp. subset + _subsetMap[image.target]._subset.push_back(std::move(image)); } if (it->second->decoderType() == "SCANNER") { // SCANNER START - double scanStart = time; + const double scanStart = time; InstrumentDecoder* scanner = static_cast( it->second.get() @@ -222,18 +222,20 @@ bool HongKangParser::create() { const std::string& endNominal = scanner->stopCommand(); // store current position in file - std::streampos len = file.tellg(); + const std::streampos len = file.tellg(); std::string linePeek; while (!file.eof()) { // continue grabbing next line until we find what we need getline(file, linePeek); if (linePeek.find(endNominal) != std::string::npos) { met = linePeek.substr(25, 9); - double scanStop = ephemerisTimeFromMissionElapsedTime( + const double scanStop = ephemerisTimeFromMissionElapsedTime( met, _metRef ); - std::string scannerTarget = findPlaybookSpecifiedTarget(line); + const std::string scannerTarget = findPlaybookSpecifiedTarget( + line + ); TimeRange scanRange = TimeRange(scanStart, scanStop); ghoul_assert(scanRange.isDefined(), "Invalid time range"); @@ -241,7 +243,7 @@ bool HongKangParser::create() { // store individual image Image image = { - .timeRange = scanRange, + .timeRange = std::move(scanRange), .path = _defaultCaptureImage.string(), .activeInstruments = it->second->translations(), .target = cameraTarget, @@ -263,7 +265,7 @@ bool HongKangParser::create() { // end of capture sequence for camera, store end time of this sequence TimeRange cameraRange = TimeRange(captureStart, time); ghoul_assert(cameraRange.isDefined(), "Invalid time range"); - _instrumentTimes.emplace_back(previousCamera, cameraRange); + _instrumentTimes.emplace_back(previousCamera, std::move(cameraRange)); captureStart = -1; } } diff --git a/modules/spacecraftinstruments/util/imagesequencer.cpp b/modules/spacecraftinstruments/util/imagesequencer.cpp index ab77378408..0d50e38327 100644 --- a/modules/spacecraftinstruments/util/imagesequencer.cpp +++ b/modules/spacecraftinstruments/util/imagesequencer.cpp @@ -225,7 +225,8 @@ std::vector ImageSequencer::imagePaths(const std::string& projectee, // create temporary storage std::vector captures; // what to look for - Image findPrevious, findCurrent; + Image findPrevious; + Image findCurrent; findPrevious.timeRange.start = sinceTime; findCurrent.timeRange.start = time; @@ -254,7 +255,7 @@ std::vector ImageSequencer::imagePaths(const std::string& projectee, } std::vector toDelete; - for (std::vector::iterator it = captures.begin(); it != captures.end(); ++it) { + for (auto it = captures.begin(); it != captures.end(); it++) { if (!it->isPlaceholder) { continue; } @@ -274,10 +275,10 @@ std::vector ImageSequencer::imagePaths(const std::string& projectee, } } - for (size_t i = 0; i < toDelete.size(); ++i) { + for (size_t i = 0; i < toDelete.size(); i++) { // We have to subtract i here as we already have deleted i value before this and // we need to adjust the location - int v = toDelete[i] - static_cast(i); + const int v = toDelete[i] - static_cast(i); captures.erase(captures.begin() + v); } @@ -350,22 +351,23 @@ void ImageSequencer::runSequenceParser(SequenceParser& parser) { // simple search function double min = 10; auto findMin = [&min](const std::vector& vec) -> double { - for (size_t i = 1; i < vec.size(); ++i) { - double e = std::abs(vec[i].timeRange.start - vec[i - 1].timeRange.start); + for (size_t i = 1; i < vec.size(); i++) { + const double e = std::abs( + vec[i].timeRange.start - vec[i - 1].timeRange.start + ); min = std::min(e, min); } return min; }; // find the smallest separation of images in time - double epsilon; - epsilon = findMin(destination); + double epsilon = findMin(destination); // set epsilon as 1% smaller than min epsilon -= min * 0.01; // IFF images have same time as mission planned capture, erase that event // from 'predicted event file' (mission-playbook) - for (Image& i : source) { + for (const Image& i : source) { for (const Image& j : destination) { const double diff = std::abs(i.timeRange.start - j.timeRange.start); if (diff < epsilon) { diff --git a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp index 326f45a92d..130bde2a08 100644 --- a/modules/spacecraftinstruments/util/instrumenttimesparser.cpp +++ b/modules/spacecraftinstruments/util/instrumenttimesparser.cpp @@ -59,9 +59,13 @@ InstrumentTimesParser::InstrumentTimesParser(std::string name, std::string seque _target = p.target; for (const std::pair& ps : p.instruments) { - ghoul::Dictionary files = ps.second.value(KeyInstrumentFiles); - _fileTranslation[ps.first] = - Decoder::createFromDictionary(ps.second, KeyInstrument); + const ghoul::Dictionary files = ps.second.value( + KeyInstrumentFiles + ); + _fileTranslation[ps.first] = Decoder::createFromDictionary( + ps.second, + KeyInstrument + ); for (size_t i = 0; i < files.size(); i++) { std::string filename = files.value(std::to_string(i + 1)); _instrumentFiles[ps.first].push_back(std::move(filename)); @@ -72,7 +76,7 @@ InstrumentTimesParser::InstrumentTimesParser(std::string name, std::string seque bool InstrumentTimesParser::create() { std::filesystem::path sequenceDir = absPath(_fileName); if (!std::filesystem::is_directory(sequenceDir)) { - LERROR(fmt::format("Could not load Label Directory {}", sequenceDir)); + LERROR(std::format("Could not load label directory '{}'", sequenceDir)); return false; } @@ -80,11 +84,11 @@ bool InstrumentTimesParser::create() { using V = std::vector; for (const std::pair& p : _instrumentFiles) { const std::string& instrumentID = p.first; - for (std::string filename : p.second) { + for (const std::string& filename : p.second) { std::filesystem::path filepath = sequenceDir / filename; if (!std::filesystem::is_regular_file(filepath)) { - LERROR(fmt::format("Unable to read file {}. Skipping file", filepath)); + LERROR(std::format("Unable to read file '{}'. Skipping file", filepath)); continue; } @@ -110,8 +114,8 @@ bool InstrumentTimesParser::create() { TimeRange tr; try { // parse date strings - std::string start = matches[1].str(); - std::string stop = matches[2].str(); + const std::string start = matches[1].str(); + const std::string stop = matches[2].str(); tr.start = SpiceManager::ref().ephemerisTimeFromDate(start); tr.end = SpiceManager::ref().ephemerisTimeFromDate(stop); } diff --git a/modules/spacecraftinstruments/util/labelparser.cpp b/modules/spacecraftinstruments/util/labelparser.cpp index b374ecbee5..ee4b92db42 100644 --- a/modules/spacecraftinstruments/util/labelparser.cpp +++ b/modules/spacecraftinstruments/util/labelparser.cpp @@ -45,23 +45,25 @@ namespace openspace { LabelParser::LabelParser(std::string fileName, const ghoul::Dictionary& dictionary) : _fileName(std::move(fileName)) { + using ghoul::Dictionary; + // get the different instrument types // for each decoder (assuming might have more if hong makes changes) - for (std::string_view decoderStr : dictionary.keys()) { - if (!dictionary.hasValue(decoderStr)) { + for (const std::string_view decoderStr : dictionary.keys()) { + if (!dictionary.hasValue(decoderStr)) { continue; } - ghoul::Dictionary typeDict = dictionary.value(decoderStr); + const Dictionary typeDict = dictionary.value(decoderStr); // create dictionary containing all {playbookKeys , spice IDs} if (decoderStr == "Instrument") { // for each playbook call -> create a Decoder object - for (std::string_view key : typeDict.keys()) { - if (!typeDict.hasValue(key)) { + for (const std::string_view key : typeDict.keys()) { + if (!typeDict.hasValue(key)) { continue; } - ghoul::Dictionary decoderDict = typeDict.value(key); + const Dictionary decoderDict = typeDict.value(key); std::unique_ptr decoder = Decoder::createFromDictionary( decoderDict, @@ -73,33 +75,32 @@ LabelParser::LabelParser(std::string fileName, const ghoul::Dictionary& dictiona } } if (decoderStr == "Target") { - if (!typeDict.hasValue(keySpecs) || - !typeDict.hasValue(keySpecs)) + if (!typeDict.hasValue(keySpecs) || + !typeDict.hasValue(keySpecs)) { continue; } - ghoul::Dictionary specsOfInterestDict = - typeDict.value(keySpecs); + const Dictionary specsOfInterestDict = typeDict.value(keySpecs); _specsOfInterest.resize(specsOfInterestDict.size()); for (size_t n = 0; n < _specsOfInterest.size(); ++n) { - std::string key = std::to_string(n + 1); + const std::string key = std::to_string(n + 1); if (specsOfInterestDict.hasValue(key)) { std::string readMe = specsOfInterestDict.value(key); - _specsOfInterest[n] = readMe; + _specsOfInterest[n] = std::move(readMe); } } - ghoul::Dictionary convertDict = typeDict.value(keyConvert); + const Dictionary convertDict = typeDict.value(keyConvert); - for (std::string_view key : convertDict.keys()) { - if (!convertDict.hasValue(key)) { + for (const std::string_view key : convertDict.keys()) { + if (!convertDict.hasValue(key)) { continue; } - ghoul::Dictionary itemDict = convertDict.value(key); + const Dictionary item = convertDict.value(key); std::unique_ptr decoder = Decoder::createFromDictionary( - itemDict, + item, std::string(decoderStr) ); // insert decoder to map - this will be used in the parser to determine @@ -111,10 +112,12 @@ LabelParser::LabelParser(std::string fileName, const ghoul::Dictionary& dictiona } std::string LabelParser::decode(const std::string& line) { - for (std::pair>& key : _fileTranslation) { - std::size_t value = line.find(key.first); + using K = std::string; + using V = std::unique_ptr; + for (const std::pair& key : _fileTranslation) { + const size_t value = line.find(key.first); if (value != std::string::npos) { - std::string toTranslate = line.substr(value); + const std::string toTranslate = line.substr(value); return _fileTranslation[toTranslate]->translations()[0]; } } @@ -125,7 +128,7 @@ std::string LabelParser::encode(const std::string& line) const { using K = std::string; using V = std::unique_ptr; for (const std::pair& key : _fileTranslation) { - std::size_t value = line.find(key.first); + const size_t value = line.find(key.first); if (value != std::string::npos) { return line.substr(value); } @@ -136,7 +139,7 @@ std::string LabelParser::encode(const std::string& line) const { bool LabelParser::create() { std::filesystem::path sequenceDir = absPath(_fileName); if (!std::filesystem::is_directory(sequenceDir)) { - LERROR(fmt::format("Could not load Label Directory {}", sequenceDir)); + LERROR(std::format("Could not load label directory '{}'", sequenceDir)); return false; } @@ -149,12 +152,12 @@ bool LabelParser::create() { std::string path = e.path().string(); - size_t position = path.find_last_of('.') + 1; + const size_t position = path.find_last_of('.') + 1; if (position == 0 || position == std::string::npos) { continue; } - std::filesystem::path extension = std::filesystem::path(path).extension(); + const std::filesystem::path extension = std::filesystem::path(path).extension(); if (extension != ".lbl" && extension != ".LBL") { continue; } @@ -162,9 +165,7 @@ bool LabelParser::create() { std::ifstream file(path); if (!file.good()) { - LERROR(fmt::format( - "Failed to open label file {}", std::filesystem::path(path) - )); + LERROR(std::format("Failed to open label file '{}'", path)); return false; } @@ -194,21 +195,21 @@ bool LabelParser::create() { if (read == "TARGET_NAME") { _target = decode(line); if (_target.empty()) { - LWARNING(fmt::format(ErrorMsg, "TARGET_NAME", line, path)); + LWARNING(std::format(ErrorMsg, "TARGET_NAME", line, path)); } count++; } if (read == "INSTRUMENT_HOST_NAME") { _instrumentHostID = decode(line); if (_instrumentHostID.empty()) { - LWARNING(fmt::format(ErrorMsg, "INSTRUMENT_HOST_NAME", line, path)); + LWARNING(std::format(ErrorMsg, "INSTRUMENT_HOST_NAME", line, path)); } count++; } if (read == "INSTRUMENT_ID") { _instrumentID = decode(line); if (_instrumentID.empty()) { - LWARNING(fmt::format(ErrorMsg, "INSTRUMENT_ID", line, path)); + LWARNING(std::format(ErrorMsg, "INSTRUMENT_ID", line, path)); } lblName = encode(line); count++; @@ -216,7 +217,7 @@ bool LabelParser::create() { if (read == "DETECTOR_TYPE") { _detectorType = decode(line); if (_detectorType.empty()) { - LWARNING(fmt::format(ErrorMsg, "DETECTOR_TYPE", line, path)); + LWARNING(std::format(ErrorMsg, "DETECTOR_TYPE", line, path)); } count++; } @@ -247,8 +248,8 @@ bool LabelParser::create() { count++; } else{ - LERROR(fmt::format( - "Label file {} deviates from generic standard", path + LERROR(std::format( + "Label file '{}' deviates from generic standard", path )); LINFO( "Please make sure input data adheres to format from \ @@ -263,14 +264,14 @@ bool LabelParser::create() { count = 0; using namespace std::literals; - std::string p = path.substr(0, path.size() - ("lbl"s).size()); + const std::string p = path.substr(0, path.size() - ("lbl"s).size()); for (const std::string& ext : extensions) { - std::string imagePath = p + ext; + const std::string imagePath = p + ext; if (std::filesystem::is_regular_file(imagePath)) { std::vector spiceInstrument; spiceInstrument.push_back(_instrumentID); - Image image = { + const Image image = { .timeRange = TimeRange(startTime, stopTime), .path = imagePath, .activeInstruments = spiceInstrument, diff --git a/modules/spacecraftinstruments/util/projectioncomponent.cpp b/modules/spacecraftinstruments/util/projectioncomponent.cpp index 4945a52a48..8a735f1889 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.cpp +++ b/modules/spacecraftinstruments/util/projectioncomponent.cpp @@ -322,7 +322,7 @@ void ProjectionComponent::initialize(const std::string& identifier, } for (std::unique_ptr& parser : parsers) { - bool success = parser->create(); + const bool success = parser->create(); if (success) { ImageSequencer::ref().runSequenceParser(*parser); } @@ -334,7 +334,7 @@ void ProjectionComponent::initialize(const std::string& identifier, } bool ProjectionComponent::initializeGL() { - int maxSize = OpenGLCap.max2DTextureSize(); + const int maxSize = OpenGLCap.max2DTextureSize(); glm::ivec2 size; if (_projectionTextureAspectRatio > 1.f) { @@ -377,7 +377,7 @@ bool ProjectionComponent::initializeGL() { absPath("${MODULE_SPACECRAFTINSTRUMENTS}/shaders/dilation_fs.glsl") ); - const GLfloat plane[] = { + constexpr std::array Plane = { -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, @@ -391,7 +391,7 @@ bool ProjectionComponent::initializeGL() { glBindVertexArray(_dilation.vao); glBindBuffer(GL_ARRAY_BUFFER, _dilation.vbo); - glBufferData(GL_ARRAY_BUFFER, sizeof(plane), plane, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(Plane), Plane.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); @@ -425,7 +425,7 @@ void ProjectionComponent::imageProjectBegin() { if (_textureSizeDirty) { glm::ivec2 size = _textureSize; - LDEBUG(fmt::format("Changing texture size to {}, {}", size.x, size.y)); + LDEBUG(std::format("Changing texture size to ({}, {})", size.x, size.y)); // If the texture size has changed, we have to allocate new memory and copy // the image texture to the new target @@ -434,10 +434,12 @@ void ProjectionComponent::imageProjectBegin() { using ghoul::opengl::FramebufferObject; // Make a copy of the old textures - std::unique_ptr oldProjectionTexture = std::move(_projectionTexture); - std::unique_ptr oldDilationStencil = std::move(_dilation.stencilTexture); - std::unique_ptr oldDilationTexture = std::move(_dilation.texture); - std::unique_ptr oldDepthTexture = std::move(_shadowing.texture); + const std::unique_ptr oldProjectionTexture = + std::move(_projectionTexture); + const std::unique_ptr oldDilationStencil = + std::move(_dilation.stencilTexture); + const std::unique_ptr oldDilationTexture = std::move(_dilation.texture); + const std::unique_ptr oldDepthTexture = std::move(_shadowing.texture); // Generate the new textures generateProjectionLayerTexture(_textureSize); @@ -451,7 +453,7 @@ void ProjectionComponent::imageProjectBegin() { GLenum status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { - LERROR(fmt::format( + LERROR(std::format( "Read Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -460,7 +462,7 @@ void ProjectionComponent::imageProjectBegin() { status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { - LERROR(fmt::format( + LERROR(std::format( "Draw Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -480,7 +482,7 @@ void ProjectionComponent::imageProjectBegin() { GLenum status = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { - LERROR(fmt::format( + LERROR(std::format( "Read Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -489,7 +491,7 @@ void ProjectionComponent::imageProjectBegin() { status = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER); if (!FramebufferObject::errorChecking(status).empty()) { - LERROR(fmt::format( + LERROR(std::format( "Draw Buffer ({}): {}", msg, FramebufferObject::errorChecking(status) )); } @@ -504,8 +506,8 @@ void ProjectionComponent::imageProjectBegin() { ); }; - GLuint fbos[2]; - glGenFramebuffers(2, fbos); + std::array fbos; + glGenFramebuffers(2, fbos.data()); glBindFramebuffer(GL_READ_FRAMEBUFFER, fbos[0]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbos[1]); @@ -535,7 +537,7 @@ void ProjectionComponent::imageProjectBegin() { glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - glDeleteFramebuffers(2, fbos); + glDeleteFramebuffers(2, fbos.data()); glBindFramebuffer(GL_FRAMEBUFFER, _fboID); glFramebufferTexture2D( @@ -590,8 +592,8 @@ void ProjectionComponent::imageProjectBegin() { ); if (_dilation.isEnabled) { - GLenum buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; - glDrawBuffers(2, buffers); + std::array buffers = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; + glDrawBuffers(2, buffers.data()); } } @@ -599,7 +601,7 @@ bool ProjectionComponent::needsShadowMap() const { return _shadowing.isEnabled; } -ghoul::opengl::Texture& ProjectionComponent::depthTexture() { +ghoul::opengl::Texture& ProjectionComponent::depthTexture() const { return *_shadowing.texture; } @@ -633,16 +635,17 @@ void ProjectionComponent::imageProjectEnd() { glDisable(GL_BLEND); - ghoul::opengl::TextureUnit unit[2]; - unit[0].activate(); + ghoul::opengl::TextureUnit projUnit; + projUnit.activate(); _projectionTexture->bind(); - unit[1].activate(); + ghoul::opengl::TextureUnit stencilUnit; + stencilUnit.activate(); _dilation.stencilTexture->bind(); _dilation.program->activate(); - _dilation.program->setUniform("tex", unit[0]); - _dilation.program->setUniform("stencil", unit[1]); + _dilation.program->setUniform("tex", projUnit); + _dilation.program->setUniform("stencil", stencilUnit); glBindVertexArray(_dilation.vao); glDrawArrays(GL_TRIANGLES, 0, 6); @@ -658,14 +661,14 @@ void ProjectionComponent::imageProjectEnd() { _mipMapDirty = true; } -void ProjectionComponent::update() { +void ProjectionComponent::update() const { if (_dilation.isEnabled && _dilation.program->isDirty()) { _dilation.program->rebuildFromFile(); } } bool ProjectionComponent::depthRendertarget() { - GLint defaultFBO; + GLint defaultFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); // setup FBO glGenFramebuffers(1, &_depthFboID); @@ -680,7 +683,7 @@ bool ProjectionComponent::depthRendertarget() { glDrawBuffer(GL_NONE); - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + const GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { return false; } @@ -692,7 +695,7 @@ bool ProjectionComponent::depthRendertarget() { bool ProjectionComponent::auxiliaryRendertarget() { bool completeSuccess = true; - GLint defaultFBO; + GLint defaultFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); // setup FBO @@ -754,8 +757,9 @@ bool ProjectionComponent::auxiliaryRendertarget() { return completeSuccess; } -glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3 loc, glm::dvec3 aim, - const glm::vec3 up, +glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3& loc, + const glm::dvec3& aim, + const glm::vec3& up, const glm::dmat3& instrumentMatrix, float fieldOfViewY, float aspectRatio, @@ -765,21 +769,21 @@ glm::mat4 ProjectionComponent::computeProjectorMatrix(const glm::vec3 loc, glm:: // rotate boresight into correct alignment boreSight = instrumentMatrix * aim; - glm::vec3 uptmp = instrumentMatrix * glm::dvec3(up); + const glm::vec3 uptmp = instrumentMatrix * glm::dvec3(up); // create view matrix - glm::vec3 e3 = glm::normalize(-boreSight); - glm::vec3 e1 = glm::normalize(glm::cross(uptmp, e3)); - glm::vec3 e2 = glm::normalize(glm::cross(e3, e1)); + const glm::vec3 e3 = glm::normalize(-boreSight); + const glm::vec3 e1 = glm::normalize(glm::cross(uptmp, e3)); + const glm::vec3 e2 = glm::normalize(glm::cross(e3, e1)); - glm::mat4 projViewMatrix = glm::mat4( + const glm::mat4 projViewMatrix = glm::mat4( e1.x, e2.x, e3.x, 0.f, e1.y, e2.y, e3.y, 0.f, e1.z, e2.z, e3.z, 0.f, glm::dot(e1, -loc), glm::dot(e2, -loc), glm::dot(e3, -loc), 1.f ); // create perspective projection matrix - glm::mat4 projProjectionMatrix = glm::perspective( + const glm::mat4 projProjectionMatrix = glm::perspective( glm::radians(fieldOfViewY), aspectRatio, nearPlane, farPlane ); @@ -837,11 +841,11 @@ float ProjectionComponent::aspectRatio() const { void ProjectionComponent::clearAllProjections() { // keep handle to the current bound FBO - GLint defaultFBO; + GLint defaultFBO = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFBO); - GLint m_viewport[4]; - glGetIntegerv(GL_VIEWPORT, m_viewport); + std::array viewport; + glGetIntegerv(GL_VIEWPORT, viewport.data()); //counter = 0; glViewport( 0, @@ -861,7 +865,7 @@ void ProjectionComponent::clearAllProjections() { } glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); - glViewport(m_viewport[0], m_viewport[1], m_viewport[2], m_viewport[3]); + glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); _clearAllProjections = false; _mipMapDirty = true; @@ -900,7 +904,7 @@ std::shared_ptr ProjectionComponent::loadProjectionTextu } bool ProjectionComponent::generateProjectionLayerTexture(const glm::ivec2& size) { - LINFO(fmt::format("Creating projection texture of size '{}, {}'", size.x, size.y)); + LINFO(std::format("Creating projection texture of size ({}, {})", size.x, size.y)); using namespace ghoul::opengl; _projectionTexture = std::make_unique( @@ -939,7 +943,7 @@ bool ProjectionComponent::generateProjectionLayerTexture(const glm::ivec2& size) } bool ProjectionComponent::generateDepthTexture(const glm::ivec2& size) { - LINFO(fmt::format("Creating depth texture of size '{}, {}'", size.x, size.y)); + LINFO(std::format("Creating depth texture of size ({}, {})", size.x, size.y)); _shadowing.texture = std::make_unique( glm::uvec3(size, 1), diff --git a/modules/spacecraftinstruments/util/projectioncomponent.h b/modules/spacecraftinstruments/util/projectioncomponent.h index bde82ba1e4..c8ca7855ff 100644 --- a/modules/spacecraftinstruments/util/projectioncomponent.h +++ b/modules/spacecraftinstruments/util/projectioncomponent.h @@ -54,13 +54,13 @@ public: bool isReady() const; - ghoul::opengl::Texture& depthTexture(); + ghoul::opengl::Texture& depthTexture() const; void imageProjectBegin(); void imageProjectEnd(); void depthMapRenderBegin(); void depthMapRenderEnd(); - void update(); + void update() const; bool auxiliaryRendertarget(); bool depthRendertarget(); @@ -68,8 +68,8 @@ public: std::shared_ptr loadProjectionTexture( const std::string& texturePath, bool isPlaceholder = false); - glm::mat4 computeProjectorMatrix(const glm::vec3 loc, glm::dvec3 aim, - const glm::vec3 up, const glm::dmat3& instrumentMatrix, float fieldOfViewY, + glm::mat4 computeProjectorMatrix(const glm::vec3& loc, const glm::dvec3& aim, + const glm::vec3& up, const glm::dmat3& instrumentMatrix, float fieldOfViewY, float aspectRatio, float nearPlane, float farPlane, glm::vec3& boreSight); bool doesPerformProjection() const; diff --git a/modules/spacecraftinstruments/util/targetdecoder.cpp b/modules/spacecraftinstruments/util/targetdecoder.cpp index 4db4f343fa..8f2747bdd8 100644 --- a/modules/spacecraftinstruments/util/targetdecoder.cpp +++ b/modules/spacecraftinstruments/util/targetdecoder.cpp @@ -34,8 +34,8 @@ namespace openspace { TargetDecoder::TargetDecoder(const ghoul::Dictionary& dictionary) { _names.resize(dictionary.size()); - for (size_t i = 0; i < _names.size(); ++i) { - std::string key = std::to_string(i + 1); + for (size_t i = 0; i < _names.size(); i++) { + const std::string key = std::to_string(i + 1); if (dictionary.hasKey(key) && dictionary.hasValue(key)) { _names[i] = dictionary.value(key);; } diff --git a/modules/spout/renderableplanespout.cpp b/modules/spout/renderableplanespout.cpp index d43845af4c..4a71596eb2 100644 --- a/modules/spout/renderableplanespout.cpp +++ b/modules/spout/renderableplanespout.cpp @@ -89,7 +89,7 @@ RenderablePlaneSpout::RenderablePlaneSpout(const ghoul::Dictionary& dictionary) else { setIdentifier("RenderablePlaneSpout" + std::to_string(iIdentifier)); } - ++id; + id++; } if (_guiName.empty()) { diff --git a/modules/spout/renderablespherespout.cpp b/modules/spout/renderablespherespout.cpp index a45a0c8b64..384bacd254 100644 --- a/modules/spout/renderablespherespout.cpp +++ b/modules/spout/renderablespherespout.cpp @@ -77,7 +77,7 @@ RenderableSphereSpout::RenderableSphereSpout(const ghoul::Dictionary& dictionary else { setIdentifier("RenderableSphereSpout" + std::to_string(iIdentifier)); } - ++id; + id++; } if (_guiName.empty()) { diff --git a/modules/spout/spoutwrapper.cpp b/modules/spout/spoutwrapper.cpp index 7e50f31359..fe03d8a2c3 100644 --- a/modules/spout/spoutwrapper.cpp +++ b/modules/spout/spoutwrapper.cpp @@ -135,7 +135,7 @@ const std::vector &SpoutReceiver::spoutReceiverList() { const int nSenders = _spoutHandle->GetSenderCount(); _receiverList.clear(); - for (int i = 0; i < nSenders; ++i) { + for (int i = 0; i < nSenders; i++) { char Name[256]; _spoutHandle->GetSenderName(i, Name, 256); _receiverList.push_back(Name); @@ -213,7 +213,7 @@ bool SpoutReceiver::updateReceiverName(const std::string& name) { bool hasCreated = _spoutHandle->CreateReceiver(nameBuf, width, height); if (!hasCreated) { if (!_isErrorMessageDisplayed) { - LWARNING(fmt::format( + LWARNING(std::format( "Could not create receiver for {} -> {}x{}", name, width, height )); _isErrorMessageDisplayed = true; @@ -294,7 +294,7 @@ bool SpoutReceiver::updateTexture(unsigned int width, unsigned int height) { if (_spoutTexture) { _spoutTexture->uploadTexture(); if (_onUpdateTextureCallback && !_onUpdateTextureCallback(width, height)) { - LWARNING(fmt::format( + LWARNING(std::format( "Could not create callback texture for {} -> {}x{}", _currentSpoutName, width, height )); @@ -304,7 +304,7 @@ bool SpoutReceiver::updateTexture(unsigned int width, unsigned int height) { _spoutHeight = height; } else { - LWARNING(fmt::format( + LWARNING(std::format( "Could not create texture for {} -> {}x{}", _currentSpoutName, width, height )); @@ -373,10 +373,10 @@ SpoutReceiverPropertyProxy::SpoutReceiverPropertyProxy(properties::PropertyOwner _spoutSelection.addOption(0, ""); int idx = 0; - for (int i = 0; i < static_cast(receiverList.size()); ++i) { + for (int i = 0; i < static_cast(receiverList.size()); i++) { _spoutSelection.addOption(i + 1, receiverList[i]); - LWARNING(fmt::format("List {}", receiverList[i])); + LWARNING(std::format("List {}", receiverList[i])); if (!_isSelectAny && _spoutName.value() == receiverList[i]) { idx = i + 1; @@ -424,7 +424,7 @@ bool SpoutSender::updateSenderStatus() { if (!_isSending) { if (_spoutWidth == 0 || _spoutHeight == 0) { if (!_isErrorMessageDisplayed) { - LWARNING(fmt::format( + LWARNING(std::format( "Could not create sender for {}, dimensions invalid {}x{}", _currentSpoutName, _spoutWidth, _spoutHeight )); @@ -435,7 +435,7 @@ bool SpoutSender::updateSenderStatus() { if (_currentSpoutName.empty()) { if (!_isErrorMessageDisplayed) { - LWARNING(fmt::format("Could not create sender, invalid name")); + LWARNING(std::format("Could not create sender, invalid name")); _isErrorMessageDisplayed = true; } return false; @@ -448,7 +448,7 @@ bool SpoutSender::updateSenderStatus() { bool hasCreated = _spoutHandle->CreateSender(name, _spoutWidth, _spoutHeight); if (!hasCreated) { if (!_isErrorMessageDisplayed) { - LWARNING(fmt::format( + LWARNING(std::format( "Could not create sender for {} -> {}x{}", _currentSpoutName, _spoutWidth, _spoutHeight )); @@ -588,7 +588,7 @@ SpoutSenderPropertyProxy::SpoutSenderPropertyProxy(properties::PropertyOwner& ow _spoutName = dictionary.value(NameSenderInfo.identifier); } else { - LWARNING(fmt::format("Sender does not have a name")); + LWARNING(std::format("Sender does not have a name")); } _spoutName.onChange([this]() { _isSpoutDirty = true; }); diff --git a/modules/statemachine/include/statemachine.h b/modules/statemachine/include/statemachine.h index 520e526147..62761dbe7b 100644 --- a/modules/statemachine/include/statemachine.h +++ b/modules/statemachine/include/statemachine.h @@ -38,7 +38,7 @@ public: explicit StateMachine(const ghoul::Dictionary& dictionary); ~StateMachine() = default; - void setInitialState(const std::string initialState); + void setInitialState(const std::string& initialState); const State* currentState() const; void transitionTo(const std::string& newState); bool canTransitionTo(const std::string& state) const; diff --git a/modules/statemachine/src/statemachine.cpp b/modules/statemachine/src/statemachine.cpp index 4d472f943a..3acfd33ca4 100644 --- a/modules/statemachine/src/statemachine.cpp +++ b/modules/statemachine/src/statemachine.cpp @@ -59,7 +59,7 @@ StateMachine::StateMachine(const ghoul::Dictionary& dictionary) { _states.reserve(p.states.size()); for (const ghoul::Dictionary& s : p.states) { - _states.push_back(State(s)); + _states.emplace_back(s); } _transitions.reserve(p.transitions.size()); @@ -67,14 +67,14 @@ StateMachine::StateMachine(const ghoul::Dictionary& dictionary) { const Transition trans = Transition(t); // Check so transition has valid identifiers - bool foundFrom = findState(trans.from()) != -1; - bool foundTo = findState(trans.to()) != -1; + const bool foundFrom = findState(trans.from()) != -1; + const bool foundTo = findState(trans.to()) != -1; if (foundFrom && foundTo) { _transitions.push_back(trans); } else { - LERROR(fmt::format( + LERROR(std::format( "Invalid transition from '{}' to '{}'. One or both of the states do not " "exist in the state machine", trans.from(), trans.to() )); @@ -95,11 +95,11 @@ StateMachine::StateMachine(const ghoul::Dictionary& dictionary) { setInitialState(startState); } -void StateMachine::setInitialState(const std::string initialState) { - int stateIndex = findState(initialState); +void StateMachine::setInitialState(const std::string& initialState) { + const int stateIndex = findState(initialState); if (stateIndex == -1) { - LWARNING(fmt::format( + LWARNING(std::format( "Attempting to initialize with undefined state '{}'", initialState )); return; @@ -125,17 +125,17 @@ void StateMachine::transitionTo(const std::string& newState) { return; } - int stateIndex = findState(newState); + const int stateIndex = findState(newState); if (stateIndex == -1) { - LWARNING(fmt::format( + LWARNING(std::format( "Attempting to transition to undefined state '{}'", newState )); return; } - int transitionIndex = findTransitionTo(newState); + const int transitionIndex = findTransitionTo(newState); if (transitionIndex == -1) { - LWARNING(fmt::format( + LWARNING(std::format( "Transition from '{}' to '{}' is undefined", currentState()->name(), newState )); @@ -160,7 +160,7 @@ int StateMachine::findTransitionTo(const std::string& state) const { return -1; } - for (size_t i = 0; i < _transitions.size(); ++i) { + for (size_t i = 0; i < _transitions.size(); i++) { if (_transitions[i].from() == currentState()->name() && _transitions[i].to() == state) { @@ -173,7 +173,7 @@ int StateMachine::findTransitionTo(const std::string& state) const { // Search if the state exist. // If yes then return the index to the state, otherwise return -1 int StateMachine::findState(const std::string& state) const { - for (size_t i = 0; i < _states.size(); ++i) { + for (size_t i = 0; i < _states.size(); i++) { if (_states[i].name() == state) { return static_cast(i); } @@ -189,9 +189,9 @@ std::vector StateMachine::possibleTransitions() const { } res.reserve(_transitions.size()); - for (size_t i = 0; i < _transitions.size(); ++i) { - if (_transitions[i].from() == currentState()->name()) { - res.push_back(_transitions[i].to()); + for (const Transition& transition : _transitions) { + if (transition.from() == currentState()->name()) { + res.push_back(transition.to()); } } return res; @@ -202,22 +202,22 @@ void StateMachine::saveToDotFile(const std::string& filename) const { std::ofstream file(outputFile); if (!file.good()) { - LERROR(fmt::format( - "Error opening file {} for saving state machine dot file", outputFile + LERROR(std::format( + "Error opening file '{}' for saving state machine dot file", outputFile )); return; } - file << "digraph statemachine {" << std::endl; + file << "digraph statemachine {\n"; for (const State& s : _states) { - file << "\t" << s.name() << ";" << std::endl; + file << std::format("\t{};\n", s.name()); } for (const Transition& t : _transitions) { - file << "\t" << t.from() << " -> " << t.to() << ";" << std::endl; + file << std::format("\t{} -> {};\n", t.from(), t.to()); } - file << "}" << std::endl; + file << "}\n"; - LINFO(fmt::format("Saved state machine to file: {}", outputFile)); + LINFO(std::format("Saved state machine to file: {}", outputFile)); } } // namespace openspace diff --git a/modules/statemachine/statemachinemodule.cpp b/modules/statemachine/statemachinemodule.cpp index 9c3d90dd09..0654a8ecd4 100644 --- a/modules/statemachine/statemachinemodule.cpp +++ b/modules/statemachine/statemachinemodule.cpp @@ -52,24 +52,24 @@ StateMachineModule::StateMachineModule() void StateMachineModule::initializeStateMachine(const ghoul::Dictionary& states, const ghoul::Dictionary& transitions, - const std::optional startState) + std::optional startState) { ghoul::Dictionary dictionary; dictionary.setValue("States", states); dictionary.setValue("Transitions", transitions); if (startState.has_value()) { - dictionary.setValue("StartState", *startState); + dictionary.setValue("StartState", std::move(*startState)); } try { _machine = std::make_unique(dictionary); - LINFO(fmt::format( + LINFO(std::format( "State machine was created with start state: {}", currentState() )); } catch (const documentation::SpecificationError& e) { - LERROR(fmt::format("Error loading state machine: {}", e.what())); + LERROR(std::format("Error loading state machine: {}", e.what())); logError(e); } } @@ -83,7 +83,7 @@ bool StateMachineModule::hasStateMachine() const { return _machine != nullptr; } -void StateMachineModule::setInitialState(const std::string initialState) { +void StateMachineModule::setInitialState(const std::string& initialState) { if (!_machine) { LERROR("Attempting to use uninitialized state machine"); return; diff --git a/modules/statemachine/statemachinemodule.h b/modules/statemachine/statemachinemodule.h index 11fd4b2df2..dfb45d81df 100644 --- a/modules/statemachine/statemachinemodule.h +++ b/modules/statemachine/statemachinemodule.h @@ -42,13 +42,13 @@ public: void initializeStateMachine(const ghoul::Dictionary& states, const ghoul::Dictionary& transitions, - const std::optional startState = std::nullopt); + std::optional startState = std::nullopt); void deinitializeStateMachine(); bool hasStateMachine() const; // initializeStateMachine must have been called before - void setInitialState(const std::string initialState); + void setInitialState(const std::string& initialState); std::string currentState() const; std::vector possibleTransitions() const; void transitionTo(const std::string& newState); @@ -58,7 +58,7 @@ public: * Save the state machine to a file given by the name and optional directory. * If no directory is given, the TEMP folder is used. */ - void saveToFile(const std::string& fileName, + void saveToFile(const std::string& filename, std::string directory = "${TEMPORARY}/") const; scripting::LuaLibrary luaLibrary() const override; diff --git a/modules/statemachine/statemachinemodule_lua.inl b/modules/statemachine/statemachinemodule_lua.inl index bbe0778d0c..6672835113 100644 --- a/modules/statemachine/statemachinemodule_lua.inl +++ b/modules/statemachine/statemachinemodule_lua.inl @@ -111,11 +111,14 @@ namespace { if (module->hasStateMachine()) { std::string currentState = module->currentState(); std::vector transitions = module->possibleTransitions(); - LINFOC("StateMachine", fmt::format( - "Currently in state: '{}'. Can transition to states: [ {} ]", - currentState, - ghoul::join(transitions, ",") - )); + LINFOC( + "StateMachine", + std::format( + "Currently in state: '{}'. Can transition to states: [ {} ]", + currentState, + ghoul::join(transitions, ",") + ) + ); } else { LINFOC("StateMachine", "No state machine has been created"); diff --git a/modules/sync/syncs/httpsynchronization.cpp b/modules/sync/syncs/httpsynchronization.cpp index 6c4c493d91..22e917dca1 100644 --- a/modules/sync/syncs/httpsynchronization.cpp +++ b/modules/sync/syncs/httpsynchronization.cpp @@ -101,7 +101,7 @@ void HttpSynchronization::start() { } _state = State::Syncing; - bool isSynced = isEachFileDownloaded(); + const bool isSynced = isEachFileDownloaded(); if (isSynced) { _state = State::Resolved; return; @@ -111,7 +111,7 @@ void HttpSynchronization::start() { return; } - std::string query = fmt::format( + const std::string query = std::format( "?identifier={}&file_version={}&application_version={}", _identifier, _version, ApplicationVersion ); @@ -158,7 +158,7 @@ void HttpSynchronization::cancel() { } std::string HttpSynchronization::generateUid() { - return fmt::format("{}/{}", _identifier, _version); + return std::format("{}/{}", _identifier, _version); } void HttpSynchronization::createSyncFile(bool isFullySynchronized) const { @@ -168,7 +168,7 @@ void HttpSynchronization::createSyncFile(bool isFullySynchronized) const { dir.replace_extension("ossync"); std::ofstream syncFile(dir, std::ofstream::out); - syncFile << fmt::format( + syncFile << std::format( "{}\n{}\n", OssyncVersionNumber, (isFullySynchronized ? SynchronizationToken : "Partial Synchronized") @@ -227,7 +227,7 @@ bool HttpSynchronization::isEachFileDownloaded() { } } else { - LERROR(fmt::format( + LERROR(std::format( "{}: Unknown ossync version number read." "Got {} while {} and below are valid.", _identifier, @@ -240,8 +240,8 @@ bool HttpSynchronization::isEachFileDownloaded() { } HttpSynchronization::SynchronizationState -HttpSynchronization::trySyncFromUrl(std::string listUrl) { - HttpMemoryDownload fileListDownload(std::move(listUrl)); +HttpSynchronization::trySyncFromUrl(std::string url) { + HttpMemoryDownload fileListDownload = HttpMemoryDownload(std::move(url)); fileListDownload.onProgress([&c = _shouldCancel](int64_t, std::optional) { return !c; }); @@ -282,11 +282,11 @@ HttpSynchronization::trySyncFromUrl(std::string listUrl) { continue; } - std::string filename = std::filesystem::path(line).filename().string(); - std::filesystem::path destination = directory() / (filename + ".tmp"); + const std::string filename = std::filesystem::path(line).filename().string(); + const std::filesystem::path destination = directory() / (filename + ".tmp"); if (sizeData.find(line) != sizeData.end()) { - LWARNING(fmt::format("{}: Duplicate entry for {}", _identifier, line)); + LWARNING(std::format("{}: Duplicate entry for {}", _identifier, line)); continue; } @@ -320,7 +320,7 @@ HttpSynchronization::trySyncFromUrl(std::string listUrl) { return !_shouldCancel; } - std::lock_guard guard(mutex); + const std::lock_guard guard(mutex); sizeData[line] = { downloadedBytes, totalBytes }; @@ -372,7 +372,7 @@ HttpSynchronization::trySyncFromUrl(std::string listUrl) { for (const std::unique_ptr& d : downloads) { d->wait(); if (!d->hasSucceeded()) { - LERROR(fmt::format("Error downloading file from URL {}", d->url())); + LERROR(std::format("Error downloading file from URL '{}'", d->url())); failed = true; continue; } @@ -391,13 +391,13 @@ HttpSynchronization::trySyncFromUrl(std::string listUrl) { std::error_code ec; std::filesystem::rename(tempName, originalName, ec); if (ec) { - LERROR(fmt::format("Error renaming {} to {}", tempName, originalName)); + LERROR(std::format("Error renaming '{}' to '{}'", tempName, originalName)); failed = true; } if (_unzipFiles && originalName.extension() == ".zip") { std::string source = originalName.string(); - std::string dest = + const std::string dest = _unzipFilesDestination.has_value() ? (originalName.parent_path() / *_unzipFilesDestination).string() : originalName.replace_extension().string();; @@ -407,15 +407,15 @@ HttpSynchronization::trySyncFromUrl(std::string listUrl) { zip_close(z); if (is64) { - LERROR(fmt::format( - "Error while unzipping {}: Zip64 archives are not supported", source + LERROR(std::format( + "Error while unzipping '{}': Zip64 archives are not supported", source )); continue; } int ret = zip_extract(source.c_str(), dest.c_str(), nullptr, nullptr); if (ret != 0) { - LERROR(fmt::format("Error {} while unzipping {}", ret, source)); + LERROR(std::format("Error '{}' while unzipping '{}'", ret, source)); continue; } diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index c919736fa2..5ca58329b2 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -99,7 +99,7 @@ UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dictionary, } if (p.filename.has_value() && _urls.size() > 1) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "UrlSynchronization ({}) requested overwrite filename but specified {} URLs " "to download, which is not legal", p.identifier, _urls.size() @@ -128,11 +128,11 @@ UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dictionary, size_t hash = std::hash{}( std::accumulate(urls.begin(), urls.end(), std::string()) ); - _identifier += fmt::format("({})", hash); + _identifier += std::format("({})", hash); } if (p.forceOverride.has_value()) { - LWARNING(fmt::format( + LWARNING(std::format( "{}: The variable ForceOverride has been deprecated. " "Optionally, use SecondsUntilResync instead to specify file validity date.", p.identifier @@ -223,20 +223,18 @@ bool UrlSynchronization::isEachFileValid() { if (ossyncVersion == "1.0") { std::getline(file >> std::ws, line); std::string& fileIsValidToDate = line; - double fileValidAsJ2000 = Time::convertTime(fileIsValidToDate); + const double fileValidAsJ2000 = Time::convertTime(fileIsValidToDate); - std::string todaysDate = Time::currentWallTime(); - double todaysDateAsJ2000 = Time::convertTime(todaysDate); + const std::string todaysDate = Time::currentWallTime(); + const double todaysDateAsJ2000 = Time::convertTime(todaysDate); // Issue warning if file is kept but user changed setting to download on startup. if ((fileValidAsJ2000 > todaysDateAsJ2000) && _secondsUntilResync == 0) { - LWARNING(fmt::format( + LWARNING(std::format( "{}: File is valid to {} but asset specifies SecondsUntilResync = {} " "Did you mean to re-download the file? If so, remove file from sync " "folder to resync", - _identifier, - fileIsValidToDate, - _secondsUntilResync + _identifier, fileIsValidToDate, _secondsUntilResync )); } @@ -249,7 +247,7 @@ bool UrlSynchronization::isEachFileValid() { return false; } else { - LERROR(fmt::format( + LERROR(std::format( "{}: Unknown ossync version number read. Got {} while {} and below are valid", _identifier, ossyncVersion, OssyncVersionNumber )); @@ -266,12 +264,12 @@ void UrlSynchronization::createSyncFile(bool) const { dir.replace_extension("ossync"); std::ofstream syncFile(dir, std::ofstream::out); - std::string currentTimeAsISO8601 = Time::currentWallTime(); - double currentTimeAsJ2000 = Time::convertTime(currentTimeAsISO8601); + const std::string currentTimeAsISO8601 = Time::currentWallTime(); + const double currentTimeAsJ2000 = Time::convertTime(currentTimeAsISO8601); // With the format YYYY-MM... any year thats larger than 4 digits throws an error // Limit the future date to year 9999 - double futureTimeAsJ2000 = std::min( + const double futureTimeAsJ2000 = std::min( currentTimeAsJ2000 + _secondsUntilResync, MaxDateAsJ2000 ); @@ -281,7 +279,7 @@ void UrlSynchronization::createSyncFile(bool) const { "YYYY-MM-DDTHR:MN:SC.###" ); - const std::string msg = fmt::format("{}\n{}\n", OssyncVersionNumber, fileIsValidTo); + const std::string msg = std::format("{}\n{}\n", OssyncVersionNumber, fileIsValidTo); syncFile << msg; } @@ -313,13 +311,13 @@ bool UrlSynchronization::trySyncUrls() { std::filesystem::path destination = directory() / (_filename + ".tmp"); if (sizeData.find(url) != sizeData.end()) { - LWARNING(fmt::format("{}: Duplicate entry for {}", _identifier, url)); + LWARNING(std::format("{}: Duplicate entry for '{}'", _identifier, url)); continue; } auto download = std::make_unique( url, - destination, + std::move(destination), HttpFileDownload::Overwrite::Yes ); HttpFileDownload* dl = download.get(); @@ -336,7 +334,7 @@ bool UrlSynchronization::trySyncUrls() { return !_shouldCancel; } - std::lock_guard guard(fileSizeMutex); + const std::lock_guard guard(fileSizeMutex); sizeData[url] = { downloadedBytes, totalBytes }; _nTotalBytesKnown = true; @@ -362,7 +360,7 @@ bool UrlSynchronization::trySyncUrls() { d->wait(); if (!d->hasSucceeded()) { failed = true; - LERROR(fmt::format("Error downloading file from URL {}", d->url())); + LERROR(std::format("Error downloading file from URL: {}", d->url())); continue; } @@ -383,7 +381,7 @@ bool UrlSynchronization::trySyncUrls() { if (ec) { LERRORC( "URLSynchronization", - fmt::format("Error renaming file {} to {}", tempName, originalName) + std::format("Error renaming file '{}' to '{}'", tempName, originalName) ); failed = true; diff --git a/modules/touch/src/directinputsolver.cpp b/modules/touch/src/directinputsolver.cpp index 6f3a0dd6b2..0352438163 100644 --- a/modules/touch/src/directinputsolver.cpp +++ b/modules/touch/src/directinputsolver.cpp @@ -64,7 +64,7 @@ double distToMinimize(double* par, int x, void* fdata, LMstat* lmstat) { // { vec2 globalRot, zoom, roll, vec2 localRot } double q[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; - for (int i = 0; i < ptr->nDOF; ++i) { + for (int i = 0; i < ptr->nDOF; i++) { q[i] = par[i]; } @@ -150,7 +150,7 @@ void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { std::vector dPar(ptr->nDOF, 0.0); dPar.assign(par, par + ptr->nDOF); - for (int i = 0; i < ptr->nDOF; ++i) { + for (int i = 0; i < ptr->nDOF; i++) { // Initial values double h = 1e-8; double lastG = 1; @@ -158,7 +158,7 @@ void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { double f1 = distToMinimize(dPar.data(), x, fdata, lmstat); dPar.at(i) = par[i]; // Iterative process to find the minimum step h that gives a good gradient - for (int j = 0; j < 100; ++j) { + for (int j = 0; j < 100; j++) { if ((f1 - f0) != 0 && lastG == 0) { // found minimum step size h // scale up to get a good initial guess value h *= scale * scale * scale; @@ -196,12 +196,12 @@ void gradient(double* g, double* par, int x, void* fdata, LMstat* lmstat) { } if (ptr->nDOF == 2) { // normalize on 1 finger case to allow for horizontal/vertical movement - for (int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; i++) { g[i] = g[i] / std::abs(g[i]); } } else if (ptr->nDOF == 6) { - for (int i = 0; i < ptr->nDOF; ++i) { + for (int i = 0; i < ptr->nDOF; i++) { // lock to only pan and zoom on 3 finger case, no roll/orbit g[i] = (i == 2) ? g[i] : g[i] / std::abs(g[i]); } @@ -226,7 +226,7 @@ bool DirectInputSolver::solve(const std::vector& list, std::vector selectedPoints; std::vector screenPoints; - for (int i = 0; i < nFingers; ++i) { + for (int i = 0; i < nFingers; i++) { const SelectedBody& sb = selectedBodies.at(i); selectedPoints.push_back(sb.coordinates); screenPoints.emplace_back( diff --git a/modules/touch/src/touchinteraction.cpp b/modules/touch/src/touchinteraction.cpp index 59c788e193..1822ce108a 100644 --- a/modules/touch/src/touchinteraction.cpp +++ b/modules/touch/src/touchinteraction.cpp @@ -741,7 +741,7 @@ void TouchInteraction::computeVelocities(const std::vector& li if (pinchConsecCt > 0 && action != InteractionType::PINCH) { if (pinchConsecCt > 3) { - LDEBUG(fmt::format( + LDEBUG(std::format( "PINCH gesture ended with {} drag distance and {} counts", pinchConsecZoomFactor, pinchConsecCt )); @@ -1005,7 +1005,7 @@ void TouchInteraction::step(double dt, bool directTouch) { // Because of heightmaps we need to ensure we don't go through the surface if (_zoomInLimit.value() < nodeRadius) { #ifdef TOUCH_DEBUG_PROPERTIES - LINFO(fmt::format( + LINFO(std::format( "Zoom In limit should be larger than anchor " "center to surface, setting it to {}", zoomInBounds )); @@ -1021,7 +1021,7 @@ void TouchInteraction::step(double dt, bool directTouch) { // Make sure zoom in limit is not larger than zoom out limit if (zoomInBounds > zoomOutBounds) { - LWARNING(fmt::format( + LWARNING(std::format( "Zoom In Limit should be smaller than Zoom Out Limit", zoomOutBounds )); @@ -1069,7 +1069,7 @@ void TouchInteraction::step(double dt, bool directTouch) { } else if (currentPosViolatingZoomOutLimit) { #ifdef TOUCH_DEBUG_PROPERTIES - LINFO(fmt::format( + LINFO(std::format( "You are outside zoom out {} limit, only zoom in allowed", zoomOutBounds )); @@ -1112,7 +1112,7 @@ void TouchInteraction::step(double dt, bool directTouch) { //Show velocity status every N frames if (++stepVelUpdate >= 60) { stepVelUpdate = 0; - LINFO(fmt::format( + LINFO(std::format( "DistToFocusNode {} stepZoomVelUpdate {}", length(centerToCamera), _vel.zoom )); diff --git a/modules/touch/src/win32_touch.cpp b/modules/touch/src/win32_touch.cpp index ce08d85ff1..06dff64ab9 100644 --- a/modules/touch/src/win32_touch.cpp +++ b/modules/touch/src/win32_touch.cpp @@ -254,7 +254,7 @@ Win32TouchHook::Win32TouchHook(void* nativeWindow) { } if (!gTouchHook) { - LINFO(fmt::format("Failed to setup WindowsHook for touch input redirection")); + LINFO(std::format("Failed to setup WindowsHook for touch input redirection")); #ifdef ENABLE_TUIOMESSAGES delete gTuioServer; #endif diff --git a/modules/touch/touchmodule.cpp b/modules/touch/touchmodule.cpp index 91976bd1bb..6330111fd7 100644 --- a/modules/touch/touchmodule.cpp +++ b/modules/touch/touchmodule.cpp @@ -95,7 +95,7 @@ TouchModule::TouchModule() FactoryManager::ref().factory(); if (!fRenderable->hasClass(s)) { - LWARNING(fmt::format( + LWARNING(std::format( "In property 'DefaultDirectTouchRenderableTypes': '{}' is not a " "registered renderable type. Ignoring", s )); diff --git a/modules/toyvolume/rendering/renderabletoyvolume.cpp b/modules/toyvolume/rendering/renderabletoyvolume.cpp index 6fa4d3485c..f809341a63 100644 --- a/modules/toyvolume/rendering/renderabletoyvolume.cpp +++ b/modules/toyvolume/rendering/renderabletoyvolume.cpp @@ -150,18 +150,18 @@ RenderableToyVolume::RenderableToyVolume(const ghoul::Dictionary& dictionary) RenderableToyVolume::~RenderableToyVolume() {} void RenderableToyVolume::initializeGL() { - glm::vec4 color(glm::vec3(_color), opacity()); - _raycaster = std::make_unique(color); + glm::vec4 color = glm::vec4(glm::vec3(_color), opacity()); + _raycaster = std::make_unique(std::move(color)); _raycaster->initialize(); - global::raycasterManager->attachRaycaster(*_raycaster.get()); + global::raycasterManager->attachRaycaster(*_raycaster); - std::function onChange = [this](bool enabled) { + auto onChange = [this](bool enabled) { if (enabled) { - global::raycasterManager->attachRaycaster(*_raycaster.get()); + global::raycasterManager->attachRaycaster(*_raycaster); } else { - global::raycasterManager->detachRaycaster(*_raycaster.get()); + global::raycasterManager->detachRaycaster(*_raycaster); } }; @@ -179,7 +179,7 @@ void RenderableToyVolume::initializeGL() { void RenderableToyVolume::deinitializeGL() { if (_raycaster) { - global::raycasterManager->detachRaycaster(*_raycaster.get()); + global::raycasterManager->detachRaycaster(*_raycaster); _raycaster = nullptr; } } @@ -196,7 +196,7 @@ void RenderableToyVolume::update(const UpdateData& data) { static_cast(_translation) * std::pow(10.f, static_cast(_scalingExponent)) ); - glm::vec3 eulerRotation = static_cast(_rotation); + const glm::vec3 eulerRotation = _rotation; transform = glm::rotate(transform, eulerRotation.x, glm::vec3(1.f, 0.f, 0.f)); transform = glm::rotate(transform, eulerRotation.y, glm::vec3(0.f, 1.f, 0.f)); transform = glm::rotate(transform, eulerRotation.z, glm::vec3(0.f, 0.f, 1.f)); @@ -207,7 +207,7 @@ void RenderableToyVolume::update(const UpdateData& data) { std::pow(10.f, static_cast(_scalingExponent)) ); - glm::vec4 color(glm::vec3(_color), opacity()); + const glm::vec4 color = glm::vec4(glm::vec3(_color), opacity()); _raycaster->setColor(color); _raycaster->setStepSize(_stepSize); @@ -220,7 +220,7 @@ void RenderableToyVolume::update(const UpdateData& data) { void RenderableToyVolume::render(const RenderData& data, RendererTasks& tasks) { RaycasterTask task { _raycaster.get(), data }; - tasks.raycasterTasks.push_back(task); + tasks.raycasterTasks.push_back(std::move(task)); } } // namespace openspace diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.cpp b/modules/toyvolume/rendering/toyvolumeraycaster.cpp index d1caf09116..be3acef255 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.cpp +++ b/modules/toyvolume/rendering/toyvolumeraycaster.cpp @@ -91,7 +91,7 @@ void ToyVolumeRaycaster::renderExitPoints(const RenderData& data, } glm::dmat4 ToyVolumeRaycaster::modelViewTransform(const RenderData& data) { - glm::dmat4 modelTransform = + const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * @@ -115,14 +115,14 @@ void ToyVolumeRaycaster::postRaycast(const RaycastData&, ghoul::opengl::ProgramO bool ToyVolumeRaycaster::isCameraInside(const RenderData& data, glm::vec3& localPosition) { - glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * - glm::vec4(0.f, 0.f, 0.f, 1.f); + const glm::vec4 modelPos = + glm::inverse(modelViewTransform(data)) * glm::vec4(0.f, 0.f, 0.f, 1.f); localPosition = (glm::vec3(modelPos) + glm::vec3(0.5f)); - return (localPosition.x > 0 && localPosition.x < 1 && - localPosition.y > 0 && localPosition.y < 1 && - localPosition.z > 0 && localPosition.z < 1); + return (localPosition.x > 0.f && localPosition.x < 1.f && + localPosition.y > 0.f && localPosition.y < 1.f && + localPosition.z > 0.f && localPosition.z < 1.f); } std::string ToyVolumeRaycaster::boundsVertexShaderPath() const { diff --git a/modules/toyvolume/rendering/toyvolumeraycaster.h b/modules/toyvolume/rendering/toyvolumeraycaster.h index 7f7744b802..25e371707f 100644 --- a/modules/toyvolume/rendering/toyvolumeraycaster.h +++ b/modules/toyvolume/rendering/toyvolumeraycaster.h @@ -66,7 +66,7 @@ public: void setColor(glm::vec4 color); void setModelTransform(glm::mat4 transform); void setTime(double time); - void setStepSize(float time); + void setStepSize(float stepSize); private: glm::dmat4 modelViewTransform(const RenderData& data); diff --git a/modules/video/src/renderablevideoplane.cpp b/modules/video/src/renderablevideoplane.cpp index 4d0ed18dab..fd399eacb3 100644 --- a/modules/video/src/renderablevideoplane.cpp +++ b/modules/video/src/renderablevideoplane.cpp @@ -75,20 +75,18 @@ void RenderableVideoPlane::update(const UpdateData& data) { } // Shape the plane based on the aspect ratio of the video - glm::vec2 textureDim = glm::vec2(_videoPlayer.frameTexture()->dimensions()); + const glm::vec2 textureDim = glm::vec2(_videoPlayer.frameTexture()->dimensions()); if (_textureDimensions != textureDim) { - float aspectRatio = textureDim.x / textureDim.y; - float planeAspectRatio = _size.value().x / _size.value().y; + const float aspectRatio = textureDim.x / textureDim.y; + const float planeAspectRatio = _size.value().x / _size.value().y; if (std::abs(planeAspectRatio - aspectRatio) > std::numeric_limits::epsilon()) { - double scale = _size.value().y; - glm::vec2 newSize = - aspectRatio > 0.f ? + const double scale = _size.value().y; + _size = aspectRatio > 0.f ? glm::vec2(scale * aspectRatio, scale) : glm::vec2(scale, scale * aspectRatio); - _size = newSize; } _textureDimensions = textureDim; diff --git a/modules/video/src/renderablevideosphere.cpp b/modules/video/src/renderablevideosphere.cpp index a5659d0e48..4aa9244af2 100644 --- a/modules/video/src/renderablevideosphere.cpp +++ b/modules/video/src/renderablevideosphere.cpp @@ -77,7 +77,7 @@ void RenderableVideoSphere::update(const UpdateData&) { } void RenderableVideoSphere::bindTexture() { - _videoPlayer.frameTexture().get()->bind(); + _videoPlayer.frameTexture()->bind(); } } // namespace openspace diff --git a/modules/video/src/screenspacevideo.cpp b/modules/video/src/screenspacevideo.cpp index 0f24c0563e..9d5f62964c 100644 --- a/modules/video/src/screenspacevideo.cpp +++ b/modules/video/src/screenspacevideo.cpp @@ -73,7 +73,7 @@ void ScreenSpaceVideo::update() { if (!_videoPlayer.isInitialized()) { return; } - glm::uvec3 texDimensions = _videoPlayer.frameTexture()->dimensions(); + const glm::uvec3& texDimensions = _videoPlayer.frameTexture()->dimensions(); if (_objectSize != glm::ivec2(texDimensions.x, texDimensions.y)) { _objectSize = texDimensions; } diff --git a/modules/video/src/videoplayer.cpp b/modules/video/src/videoplayer.cpp index 199864d63c..856a0a9850 100644 --- a/modules/video/src/videoplayer.cpp +++ b/modules/video/src/videoplayer.cpp @@ -133,7 +133,7 @@ namespace { bool checkMpvError(int status) { if (status < 0) { - LERROR(fmt::format("Libmpv API error: {}", mpv_error_string(status))); + LERROR(std::format("Libmpv API error: {}", mpv_error_string(status))); return false; } return true; @@ -164,9 +164,9 @@ void VideoPlayer::observePropertyMpv(MpvKey key) { } void VideoPlayer::setPropertyStringMpv(const char* name, const char* value) { - int result = mpv_set_property_string(_mpvHandle, name, value); + const int result = mpv_set_property_string(_mpvHandle, name, value); if (!checkMpvError(result)) { - LWARNING(fmt::format("Error setting property {}", name)); + LWARNING(std::format("Error setting property '{}'", name)); } } @@ -174,7 +174,7 @@ void VideoPlayer::setPropertyAsyncMpv(int value, MpvKey key) { if (!_isInitialized) { return; } - int result = mpv_set_property_async( + const int result = mpv_set_property_async( _mpvHandle, static_cast(key), keys[key], @@ -190,7 +190,7 @@ void VideoPlayer::setPropertyAsyncMpv(const char* value, MpvKey key) { if (!_isInitialized) { return; } - int result = mpv_set_property_async( + const int result = mpv_set_property_async( _mpvHandle, static_cast(key), keys[key], @@ -206,7 +206,7 @@ void VideoPlayer::setPropertyAsyncMpv(double value, MpvKey key) { if (!_isInitialized) { return; } - int result = mpv_set_property_async( + const int result = mpv_set_property_async( _mpvHandle, static_cast(key), keys[key], @@ -219,26 +219,22 @@ void VideoPlayer::setPropertyAsyncMpv(double value, MpvKey key) { } void VideoPlayer::getPropertyAsyncMpv(MpvKey key) { - int result = mpv_get_property_async( + const int result = mpv_get_property_async( _mpvHandle, static_cast(key), keys[key], formats[key] ); if (!checkMpvError(result)) { - LWARNING(fmt::format("Could not find property {}", keys[key])); + LWARNING(std::format("Could not find property '{}'", keys[key])); return; } } void VideoPlayer::commandAsyncMpv(const char* cmd[], MpvKey key) { - int result = mpv_command_async( - _mpvHandle, - static_cast(key), - cmd - ); + const int result = mpv_command_async(_mpvHandle, static_cast(key), cmd); if (!checkMpvError(result)) { - LERROR(fmt::format("Could not execute command {}", keys[key])); + LERROR(std::format("Could not execute command '{}'", keys[key])); return; } } @@ -286,8 +282,7 @@ VideoPlayer::VideoPlayer(const ghoul::Dictionary& dictionary) _goToStart.onChange([this]() { goToStart(); }); addProperty(_goToStart); _loopVideo.onChange([this]() { - std::string newValue = _loopVideo ? "inf" : "no"; - setPropertyAsyncMpv(newValue.c_str(), MpvKey::Loop); + setPropertyAsyncMpv(_loopVideo ? "inf" : "no", MpvKey::Loop); }); addProperty(_loopVideo); // Audio only makes sense when the video is playing in real time @@ -343,13 +338,13 @@ VideoPlayer::~VideoPlayer() { } void VideoPlayer::pause() { - int isPaused = 1; - setPropertyAsyncMpv(isPaused, MpvKey::Pause); + constexpr int IsPaused = 1; + setPropertyAsyncMpv(IsPaused, MpvKey::Pause); } void VideoPlayer::play() { - int isPaused = 0; - setPropertyAsyncMpv(isPaused, MpvKey::Pause); + constexpr int IsPaused = 0; + setPropertyAsyncMpv(IsPaused, MpvKey::Pause); } void VideoPlayer::goToStart() { @@ -451,7 +446,7 @@ void VideoPlayer::initializeMpv() { ); // Load file - std::string file = _videoFile; + const std::string file = _videoFile; const char* cmd[] = { "loadfile", file.c_str(), nullptr }; result = mpv_command(_mpvHandle, cmd); if (!checkMpvError(result)) { @@ -501,7 +496,7 @@ void VideoPlayer::update() { } if (global::sessionRecording->isSavingFramesDuringPlayback()) { - double dt = global::sessionRecording->fixedDeltaTimeDuringFrameOutput(); + const double dt = global::sessionRecording->fixedDeltaTimeDuringFrameOutput(); if (_playbackMode == PlaybackMode::MapToSimulationTime) { _currentVideoTime = correctVideoPlaybackTime(); } @@ -509,7 +504,7 @@ void VideoPlayer::update() { _currentVideoTime = _currentVideoTime + dt; } - MpvKey key = MpvKey::Time; + const MpvKey key = MpvKey::Time; mpv_set_property(_mpvHandle, keys[key], formats[key], &_currentVideoTime); uint64_t result = mpv_render_context_update(_mpvRenderContext); @@ -534,7 +529,7 @@ void VideoPlayer::renderMpv() { // Renders a frame libmpv has been updated if (_wakeup) { - uint64_t result = mpv_render_context_update(_mpvRenderContext); + const uint64_t result = mpv_render_context_update(_mpvRenderContext); if ((result & MPV_RENDER_UPDATE_FRAME)) { renderFrame(); _wakeup = 0; @@ -544,12 +539,12 @@ void VideoPlayer::renderMpv() { void VideoPlayer::renderFrame() { // Save the currently bound fbo - GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); + const GLint defaultFBO = ghoul::opengl::FramebufferObject::getActiveObject(); // See render_gl.h on what OpenGL environment mpv expects, and other API // details. This function fills the fbo and texture with data, after it // we can get the data on the GPU, not the CPU - int fboInt = static_cast(_fbo); + const int fboInt = static_cast(_fbo); mpv_opengl_fbo mpfbo{ fboInt, _videoResolution.x, @@ -584,7 +579,7 @@ void VideoPlayer::handleMpvEvents() { break; } if (!checkMpvError(event->error)) { - LWARNING(fmt::format( + LWARNING(std::format( "Error at mpv event: {} {}", static_cast(event->event_id), event->reply_userdata )); @@ -606,9 +601,9 @@ void VideoPlayer::handleMpvEvents() { break; } // Validate reply with what we have stored - MpvKey key = static_cast(event->reply_userdata); + const MpvKey key = static_cast(event->reply_userdata); if (formats[key] != prop->format) { - LINFO(fmt::format("Wrong format for property {}", keys[key])); + LINFO(std::format("Wrong format for property '{}'", keys[key])); break; } getPropertyAsyncMpv(key); @@ -621,8 +616,7 @@ void VideoPlayer::handleMpvEvents() { case MPV_EVENT_LOG_MESSAGE: { mpv_event_log_message* msg = reinterpret_cast(event->data); - std::stringstream ss; - LINFO(fmt::format("[{}] {}: {}", msg->prefix, msg->level, msg->text)); + LINFO(std::format("[{}] {}: {}", msg->prefix, msg->level, msg->text)); break; } default: { @@ -634,20 +628,20 @@ void VideoPlayer::handleMpvEvents() { } void VideoPlayer::handleMpvProperties(mpv_event* event) { - MpvKey key = static_cast(event->reply_userdata); + const MpvKey key = static_cast(event->reply_userdata); if (!event->data) { - LERROR(fmt::format("Could not find data for property: {}", keys[key])); + LERROR(std::format("Could not find data for property: {}", keys[key])); return; } // Cast event to node or property depending on its format mpv_event_property* prop = nullptr; mpv_node node = {}; if (formats[key] == MPV_FORMAT_NODE) { - int result = mpv_event_to_node(&node, event); + const int result = mpv_event_to_node(&node, event); if (!checkMpvError(result)) { LWARNING( - fmt::format("Error getting data from libmpv property {}", keys[key]) + std::format("Error getting data from libmpv property: {}", keys[key]) ); } } @@ -658,6 +652,9 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { // Handle new values switch (key) { case MpvKey::Duration: { + if (!prop) { + break; + } double* duration = reinterpret_cast(prop->data); if (!duration) { @@ -670,10 +667,13 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { updateFrameDuration(); } - LINFO(fmt::format("Duration: {}", *duration)); + LINFO(std::format("Duration: {}", *duration)); break; } case MpvKey::Height: { + if (!prop) { + break; + } int* height = reinterpret_cast(prop->data); if (!height) { @@ -682,7 +682,7 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { } resizeTexture(glm::ivec2(_videoResolution.x, *height)); - LINFO(fmt::format("New height: {}", *height)); + LINFO(std::format("New height: {}", *height)); // Each time a size property is updated, it means libmpv is updating the video // so we have to re-render the first frame to show it @@ -691,6 +691,9 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { break; } case MpvKey::Width: { + if (!prop) { + break; + } int* width = reinterpret_cast(prop->data); if (!width) { @@ -699,7 +702,7 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { } resizeTexture(glm::ivec2(* width, _videoResolution.y)); - LINFO(fmt::format("New width: {}", *width)); + LINFO(std::format("New width: {}", *width)); // Each time a size property is updated, it means libmpv is updating the video // so we have to re-render the first frame to show it @@ -708,6 +711,9 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { break; } case MpvKey::Time: { + if (!prop) { + break; + } double* time = reinterpret_cast(prop->data); if (!time) { @@ -718,11 +724,17 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { break; } case MpvKey::IsSeeking: { + if (!prop) { + break; + } bool* isSeekingBool = reinterpret_cast(prop->data); _isSeeking = *isSeekingBool; break; } case MpvKey::Fps: { + if (!prop) { + break; + } double* fps = reinterpret_cast(prop->data); if (*fps < glm::epsilon()) { _fps = 24.0; @@ -738,11 +750,14 @@ void VideoPlayer::handleMpvProperties(mpv_event* event) { updateFrameDuration(); } - LINFO(fmt::format("Detected fps: {}", *fps)); + LINFO(std::format("Detected fps: {}", *fps)); _seekThreshold = 2.0 * (1.0 / _fps); break; } case MpvKey::Pause: { + if (!prop) { + break; + } int* videoIsPaused = reinterpret_cast(prop->data); _isPaused = (* videoIsPaused == 1); break; @@ -794,7 +809,7 @@ void VideoPlayer::postSync(bool isMaster) { return; } // Ensure the nodes have the same time as the master node - bool isMappingTime = _playbackMode == PlaybackMode::MapToSimulationTime; + const bool isMappingTime = _playbackMode == PlaybackMode::MapToSimulationTime; if (!isMaster) { if ((_correctPlaybackTime - _currentVideoTime) > glm::epsilon()) { seekToTime(_correctPlaybackTime, PauseAfterSeek(isMappingTime)); @@ -825,7 +840,7 @@ bool VideoPlayer::isWithingStartEndTime() const { } void VideoPlayer::updateFrameDuration() { - double openspaceVideoLength = (_endJ200Time - _startJ200Time) / _videoDuration; + const double openspaceVideoLength = (_endJ200Time - _startJ200Time) / _videoDuration; _frameDuration = (1.0 / _fps) * openspaceVideoLength; } @@ -845,7 +860,7 @@ double VideoPlayer::correctVideoPlaybackTime() const { } void VideoPlayer::createTexture(glm::ivec2 size) { - LINFO(fmt::format("Creating new FBO with width: {} and height: {}", size.x, size.y)); + LINFO(std::format("Creating new FBO with width: {} and height: {}", size.x, size.y)); if (size.x <= 0 || size.y <= 0) { LERROR("Cannot create empty fbo"); @@ -881,11 +896,11 @@ void VideoPlayer::createTexture(glm::ivec2 size) { } void VideoPlayer::resizeTexture(glm::ivec2 size) { - bool isValid = size.x > 0 && size.y > 0 && _fbo > 0; - bool isNew = size != _videoResolution; + const bool isValid = size.x > 0 && size.y > 0 && _fbo > 0; + const bool isNew = size != _videoResolution; if (isValid && isNew) { _videoResolution = size; - LINFO(fmt::format("Resizing texture: width: {} height: {}", size.x, size.y)); + LINFO(std::format("Resizing texture: width: {} height: {}", size.x, size.y)); // Delete texture _frameTexture = nullptr; @@ -894,4 +909,4 @@ void VideoPlayer::resizeTexture(glm::ivec2 size) { } } -} // namespace openspace::video +} // namespace openspace diff --git a/modules/video/src/videotileprovider.cpp b/modules/video/src/videotileprovider.cpp index 8a53522c1a..6c290f9456 100644 --- a/modules/video/src/videotileprovider.cpp +++ b/modules/video/src/videotileprovider.cpp @@ -70,9 +70,9 @@ globebrowsing::Tile VideoTileProvider::tile(const globebrowsing::TileIndex& tile } // For now, don't use the cache as we're trying to debug the problem w playback - uint64_t hash = tileIndex.hashKey(); + const uint64_t hash = tileIndex.hashKey(); auto foundTile = _tileCache.find(hash); - bool textureChanged = foundTile != _tileCache.end() && + const bool textureChanged = foundTile != _tileCache.end() && foundTile->second.texture != _videoPlayer.frameTexture().get(); if (foundTile == _tileCache.end() || textureChanged) { @@ -110,19 +110,18 @@ void VideoTileProvider::reset() { } ChunkTile VideoTileProvider::chunkTile(TileIndex tileIndex, int parents, int maxParents) { - std::function ascendToParent = - [](TileIndex& ti, TileUvTransform&) { - ti.level--; - }; + constexpr auto ascendToParent = [](TileIndex& ti, TileUvTransform&) { + ti.level--; + }; - glm::vec2 noOfTiles = { + const glm::vec2 nTiles = { std::pow(2, tileIndex.level), std::pow(2, tileIndex.level - 1) }; - glm::vec2 ratios = { 1.f / noOfTiles.x, 1.f / noOfTiles.y }; - float offsetX = ratios.x * static_cast(tileIndex.x); + const glm::vec2 ratios = { 1.f / nTiles.x, 1.f / nTiles.y }; + const float offsetX = ratios.x * static_cast(tileIndex.x); // The tiles on the y-axis should be traversed backwards - float offsetY = ratios.y * (noOfTiles.y - static_cast(tileIndex.y) - 1.f); + const float offsetY = ratios.y * (nTiles.y - static_cast(tileIndex.y) - 1.f); TileUvTransform uvTransform = { glm::vec2(offsetX, offsetY), ratios }; diff --git a/modules/vislab/rendering/renderabledistancelabel.cpp b/modules/vislab/rendering/renderabledistancelabel.cpp index bb056ed192..3e03e64851 100644 --- a/modules/vislab/rendering/renderabledistancelabel.cpp +++ b/modules/vislab/rendering/renderabledistancelabel.cpp @@ -130,32 +130,32 @@ void RenderableDistanceLabel::update(const UpdateData&) { std::string distanceText = std::to_string( std::round(nodeline->distance() / scale) ); - int pos = static_cast(distanceText.find(".")); - std::string subStr = distanceText.substr(pos); + const int pos = static_cast(distanceText.find('.')); + const std::string subStr = distanceText.substr(pos); distanceText.erase(pos, subStr.size()); // Create final label text and set it - const std::string finalText = fmt::format("{} {}", distanceText, unitDescriptor); + const std::string finalText = std::format("{} {}", distanceText, unitDescriptor); setLabelText(finalText); // Update placement of label with transformation matrix SceneGraphNode* startNode = RE.scene()->sceneGraphNode(nodeline->start()); SceneGraphNode* endNode = RE.scene()->sceneGraphNode(nodeline->end()); if (startNode && endNode) { - glm::dvec3 start = startNode->worldPosition(); - glm::dvec3 end = endNode->worldPosition(); - glm::dvec3 goalPos = start + (end - start) / 2.0; + const glm::dvec3 start = startNode->worldPosition(); + const glm::dvec3 end = endNode->worldPosition(); + const glm::dvec3 goalPos = start + (end - start) / 2.0; _transformationMatrix = glm::translate(glm::dmat4(1.0), goalPos); } else { - LERROR(fmt::format( - "Could not find scene graph node {} or {}", + LERROR(std::format( + "Could not find scene graph node '{}' or '{}'", nodeline->start(), nodeline->end() )); } } else { - LERROR(fmt::format( + LERROR(std::format( "There is no scenegraph node with id {}", _nodelineId.value() )); _errorThrown = true; diff --git a/modules/volume/envelope.cpp b/modules/volume/envelope.cpp index 9b900c0bc1..31cedf7995 100644 --- a/modules/volume/envelope.cpp +++ b/modules/volume/envelope.cpp @@ -33,8 +33,8 @@ using json = nlohmann::json; namespace openspace::volume { EnvelopePoint::EnvelopePoint(glm::vec3 c, float x, float y) - : color(c) - , colorHex(hexadecimalFromVec3(std::move(c))) + : color(std::move(c)) + , colorHex(hexadecimalFromVec3(color)) , position({ x, y }) {} @@ -44,9 +44,9 @@ EnvelopePoint::EnvelopePoint(std::string c, float x, float y) , position(std::make_pair(x, y)) {} -Envelope::Envelope(std::vector vec) { - _points = std::move(vec); -} +Envelope::Envelope(std::vector vec) + : _points(std::move(vec)) +{} bool Envelope::operator!=(const Envelope& env) const { constexpr double MinDist = 0.0001; @@ -57,7 +57,7 @@ bool Envelope::operator!=(const Envelope& env) const { for (auto iter = _points.begin(), envIter = env._points.begin(); iter != _points.end(); - ++iter, ++envIter) + iter++, envIter++) { if (std::fabs(iter->position.first - envIter->position.first) > MinDist || std::fabs(iter->position.second - envIter->position.second) > MinDist || @@ -87,13 +87,14 @@ bool Envelope::isEnvelopeValid() const { nextIter != _points.end(); ++currentIter, ++nextIter) { - if (currentIter->position.first > nextIter->position.first) + if (currentIter->position.first > nextIter->position.first) { return false; + } } return true; } -glm::vec3 Envelope::normalizeColor(glm::vec3 vec) const { +glm::vec3 Envelope::normalizeColor(const glm::vec3& vec) const { return { vec.r / 255.f, vec.g / 255.f , vec.b / 255.f }; } @@ -110,7 +111,7 @@ glm::vec4 Envelope::valueAtPosition(float pos) const { } auto beforeIter = afterIter - 1; - float dist = afterIter->position.first - beforeIter->position.first; + const float dist = afterIter->position.first - beforeIter->position.first; if (dist < 0.0001) { return { normalizeColor((beforeIter->color + afterIter->color) / 2.f), @@ -134,7 +135,7 @@ glm::vec4 Envelope::valueAtPosition(float pos) const { int EnvelopePoint::hexadecimalToDecimal(const std::string& hex) const { const size_t hexLength = hex.length(); double dec = 0; - for (size_t i = 0; i < hexLength; ++i) { + for (size_t i = 0; i < hexLength; i++) { char b = hex[i]; if (b >= 48 && b <= 57) { @@ -158,7 +159,7 @@ std::string EnvelopePoint::decimalToHexadecimal(int dec) const { std::string hexStr; while (dec > 0) { - int hex = dec % 16; + const int hex = dec % 16; if (hex < 10) { hexStr = hexStr.insert(0, std::string(1, static_cast(hex + 48))); @@ -180,9 +181,9 @@ glm::vec3 EnvelopePoint::hexadecimalToRGBConversion(const std::string& hex) cons } std::string EnvelopePoint::hexadecimalFromVec3(const glm::vec3& vec) const { - std::string r = decimalToHexadecimal(static_cast(vec.r)); - std::string g = decimalToHexadecimal(static_cast(vec.g)); - std::string b = decimalToHexadecimal(static_cast(vec.b)); + const std::string r = decimalToHexadecimal(static_cast(vec.r)); + const std::string g = decimalToHexadecimal(static_cast(vec.g)); + const std::string b = decimalToHexadecimal(static_cast(vec.b)); return ("#" + r + g + b); } @@ -214,7 +215,7 @@ json Envelope::jsonEnvelope() const { } void Envelope::setEnvelopeLuaTable(lua_State* state) const { - for (auto iter = _points.begin(); iter != _points.end(); ++iter) { + for (auto iter = _points.begin(); iter != _points.end(); iter++) { lua_newtable(state); ghoul::lua::push(state, iter->colorHex); lua_setfield(state, -2, "color"); diff --git a/modules/volume/envelope.h b/modules/volume/envelope.h index ee31491667..4723630cc4 100644 --- a/modules/volume/envelope.h +++ b/modules/volume/envelope.h @@ -56,7 +56,7 @@ public: const std::vector& points() const; glm::vec4 valueAtPosition(float pos) const; - glm::vec3 normalizeColor(glm::vec3 vec) const; + glm::vec3 normalizeColor(const glm::vec3& vec) const; nlohmann::json jsonPoints() const; nlohmann::json jsonEnvelope() const; void setEnvelopeLuaTable(lua_State* state) const; diff --git a/modules/volume/rawvolumemetadata.cpp b/modules/volume/rawvolumemetadata.cpp index e639b15f88..27e93726c0 100644 --- a/modules/volume/rawvolumemetadata.cpp +++ b/modules/volume/rawvolumemetadata.cpp @@ -100,7 +100,7 @@ RawVolumeMetadata RawVolumeMetadata::createFromDictionary( return metadata; } -ghoul::Dictionary RawVolumeMetadata::dictionary() { +ghoul::Dictionary RawVolumeMetadata::dictionary() const { ghoul::Dictionary dict; dict.setValue("Dimensions", glm::dvec3(dimensions)); dict.setValue("GridType", gridTypeToString(gridType)); diff --git a/modules/volume/rawvolumemetadata.h b/modules/volume/rawvolumemetadata.h index 9d6218bfbe..77edffd1e8 100644 --- a/modules/volume/rawvolumemetadata.h +++ b/modules/volume/rawvolumemetadata.h @@ -37,7 +37,7 @@ struct RawVolumeMetadata { static RawVolumeMetadata createFromDictionary(const ghoul::Dictionary& dictionary); static documentation::Documentation Documentation(); - ghoul::Dictionary dictionary(); + ghoul::Dictionary dictionary() const; glm::uvec3 dimensions = glm::uvec3(0); VolumeGridType gridType; diff --git a/modules/volume/rawvolumereader.inl b/modules/volume/rawvolumereader.inl index a392e43f80..f17fcc1215 100644 --- a/modules/volume/rawvolumereader.inl +++ b/modules/volume/rawvolumereader.inl @@ -104,7 +104,7 @@ std::unique_ptr> RawVolumeReader::read(bool inve std::unique_ptr> newVolume = std::make_unique>(dims); - for (size_t i = 0; i < volume->nCells(); ++i) { + for (size_t i = 0; i < volume->nCells(); i++) { const glm::uvec3& coords = volume->indexToCoords(i); glm::uvec3 newcoords = glm::uvec3(coords.x, coords.y, dims.z - coords.z - 1); diff --git a/modules/volume/rawvolumewriter.inl b/modules/volume/rawvolumewriter.inl index bb13a83897..01845da3aa 100644 --- a/modules/volume/rawvolumewriter.inl +++ b/modules/volume/rawvolumewriter.inl @@ -100,7 +100,7 @@ void RawVolumeWriter::write(const RawVolume& volume) { std::ofstream file(_path, std::ios::binary); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Could not create file {}", _path)); + throw ghoul::RuntimeError(std::format("Could not create file '{}'", _path)); } file.write(buffer, length); diff --git a/modules/volume/rendering/basicvolumeraycaster.cpp b/modules/volume/rendering/basicvolumeraycaster.cpp index 9458b1c03d..75f350b7c8 100644 --- a/modules/volume/rendering/basicvolumeraycaster.cpp +++ b/modules/volume/rendering/basicvolumeraycaster.cpp @@ -50,10 +50,10 @@ BasicVolumeRaycaster::BasicVolumeRaycaster( std::shared_ptr volumeTexture, std::shared_ptr transferFunction, std::shared_ptr clipPlanes) - : _clipPlanes(clipPlanes) - , _volumeTexture(volumeTexture) - , _transferFunction(transferFunction) - , _boundingBox(glm::vec3(1.0)) + : _clipPlanes(std::move(clipPlanes)) + , _volumeTexture(std::move(volumeTexture)) + , _transferFunction(std::move(transferFunction)) + , _boundingBox(glm::vec3(1.f)) {} BasicVolumeRaycaster::~BasicVolumeRaycaster() {} @@ -79,7 +79,7 @@ void BasicVolumeRaycaster::renderEntryPoints(const RenderData& data, } glm::dmat4 BasicVolumeRaycaster::modelViewTransform(const RenderData& data) { - glm::dmat4 modelTransform = + const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * glm::dmat4(data.modelTransform.rotation) * glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale)) * @@ -112,10 +112,10 @@ void BasicVolumeRaycaster::preRaycast(const RaycastData& data, return; } - std::string stepSizeUniformName = "maxStepSize" + std::to_string(data.id); + const std::string stepSizeUniformName = "maxStepSize" + std::to_string(data.id); program.setUniform(stepSizeUniformName, _stepSize); - std::string id = std::to_string(data.id); + const std::string id = std::to_string(data.id); _transferFunction->update(); _tfUnit = std::make_unique(); @@ -130,9 +130,9 @@ void BasicVolumeRaycaster::preRaycast(const RaycastData& data, program.setUniform("gridType_" + id, static_cast(_gridType)); - std::vector clipNormals = _clipPlanes->normals(); - std::vector clipOffsets = _clipPlanes->offsets(); - int nClips = static_cast(clipNormals.size()); + const std::vector clipNormals = _clipPlanes->normals(); + const std::vector clipOffsets = _clipPlanes->offsets(); + const int nClips = static_cast(clipNormals.size()); program.setUniform("nClips_" + id, nClips); program.setUniform("clipNormals_" + id, clipNormals); @@ -151,8 +151,8 @@ void BasicVolumeRaycaster::postRaycast(const RaycastData&, ghoul::opengl::Progra bool BasicVolumeRaycaster::isCameraInside(const RenderData& data, glm::vec3& localPosition) { - glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * - glm::vec4(0.f, 0.f, 0.f, 1.f); + const glm::vec4 modelPos = glm::inverse(modelViewTransform(data)) * + glm::vec4(0.f, 0.f, 0.f, 1.f); localPosition = (glm::vec3(modelPos) + glm::vec3(0.5f)); diff --git a/modules/volume/rendering/basicvolumeraycaster.h b/modules/volume/rendering/basicvolumeraycaster.h index 599e6757f7..43c3d24208 100644 --- a/modules/volume/rendering/basicvolumeraycaster.h +++ b/modules/volume/rendering/basicvolumeraycaster.h @@ -85,7 +85,7 @@ public: float rNormalization() const; void setRNormalization(float rNormalization); float rUpperBound() const; - void setRUpperBound(float rNormalization); + void setRUpperBound(float rUpperBound); VolumeGridType gridType() const; void setGridType(VolumeGridType gridType); void setModelTransform(glm::mat4 transform); diff --git a/modules/volume/rendering/renderabletimevaryingvolume.cpp b/modules/volume/rendering/renderabletimevaryingvolume.cpp index 968677ac30..f936f027aa 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.cpp +++ b/modules/volume/rendering/renderabletimevaryingvolume.cpp @@ -212,13 +212,13 @@ RenderableTimeVaryingVolume::RenderableTimeVaryingVolume( _secondsBefore = p.secondsBefore.value_or(_secondsBefore); _secondsAfter = p.secondsAfter; - ghoul::Dictionary clipPlanesDictionary = p.clipPlanes.value_or(ghoul::Dictionary()); - _clipPlanes = std::make_shared(clipPlanesDictionary); + const ghoul::Dictionary clipPlanesDict = p.clipPlanes.value_or(ghoul::Dictionary()); + _clipPlanes = std::make_shared(clipPlanesDict); _clipPlanes->setIdentifier("clipPlanes"); _clipPlanes->setGuiName("Clip Planes"); if (p.gridType.has_value()) { - VolumeGridType gridType = volume::parseGridType(*p.gridType); + const VolumeGridType gridType = volume::parseGridType(*p.gridType); _gridType = static_cast>(gridType); } @@ -232,7 +232,7 @@ void RenderableTimeVaryingVolume::initializeGL() { std::filesystem::path sequenceDir = absPath(_sourceDirectory); if (!std::filesystem::is_directory(sequenceDir)) { - LERROR(fmt::format("Could not load sequence directory {}", sequenceDir)); + LERROR(std::format("Could not load sequence directory '{}'", sequenceDir)); return; } @@ -246,21 +246,21 @@ void RenderableTimeVaryingVolume::initializeGL() { // TODO: defer loading of data to later (separate thread or at least not when loading) for (std::pair& p : _volumeTimesteps) { Timestep& t = p.second; - std::string path = fmt::format( + const std::string path = std::format( "{}/{}.rawvolume", _sourceDirectory.value(), t.baseName ); RawVolumeReader reader(path, t.metadata.dimensions); t.rawVolume = reader.read(_invertDataAtZ); - float min = t.metadata.minValue; - float diff = t.metadata.maxValue - t.metadata.minValue; + const float min = t.metadata.minValue; + const float diff = t.metadata.maxValue - t.metadata.minValue; float* data = t.rawVolume->data(); - for (size_t i = 0; i < t.rawVolume->nCells(); ++i) { + for (size_t i = 0; i < t.rawVolume->nCells(); i++) { data[i] = glm::clamp((data[i] - min) / diff, 0.f, 1.f); } t.histogram = std::make_shared(0.f, 1.f, 100); - for (size_t i = 0; i < t.rawVolume->nCells(); ++i) { + for (size_t i = 0; i < t.rawVolume->nCells(); i++) { t.histogram->add(data[i]); } // TODO: handle normalization properly for different timesteps + transfer function @@ -291,13 +291,13 @@ void RenderableTimeVaryingVolume::initializeGL() { ); _raycaster->initialize(); - global::raycasterManager->attachRaycaster(*_raycaster.get()); + global::raycasterManager->attachRaycaster(*_raycaster); onEnabledChange([this](bool enabled) { if (enabled) { - global::raycasterManager->attachRaycaster(*_raycaster.get()); + global::raycasterManager->attachRaycaster(*_raycaster); } else { - global::raycasterManager->detachRaycaster(*_raycaster.get()); + global::raycasterManager->detachRaycaster(*_raycaster); } }); @@ -338,7 +338,7 @@ void RenderableTimeVaryingVolume::loadTimestepMetadata(const std::string& path) RawVolumeMetadata metadata; try { - ghoul::Dictionary dictionary = ghoul::lua::loadDictionaryFromFile(path); + const ghoul::Dictionary dictionary = ghoul::lua::loadDictionaryFromFile(path); metadata = RawVolumeMetadata::createFromDictionary(dictionary); } catch (const ghoul::RuntimeError& e) { @@ -362,23 +362,23 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::currentTimes if (_volumeTimesteps.empty()) { return nullptr; } - double currentTime = global::timeManager->time().j2000Seconds(); + const double currentTime = global::timeManager->time().j2000Seconds(); // Get the first item with time > currentTime auto currentTimestepIt = _volumeTimesteps.upper_bound(currentTime); if (currentTimestepIt == _volumeTimesteps.end()) { // No such timestep was found: show last timestep if it is within the time margin. Timestep* lastTimestep = &(_volumeTimesteps.rbegin()->second); - double threshold = lastTimestep->metadata.time + - static_cast(_secondsAfter); + const double threshold = + lastTimestep->metadata.time + static_cast(_secondsAfter); return currentTime < threshold ? lastTimestep : nullptr; } if (currentTimestepIt == _volumeTimesteps.begin()) { // No such timestep was found: show first timestep if it is within the time margin Timestep* firstTimestep = &(_volumeTimesteps.begin()->second); - double threshold = firstTimestep->metadata.time - - static_cast(_secondsBefore); + const double threshold = + firstTimestep->metadata.time - static_cast(_secondsBefore); return currentTime >= threshold ? firstTimestep : nullptr; } @@ -398,7 +398,7 @@ int RenderableTimeVaryingVolume::timestepIndex( if (&(it.second) == t) { return index; } - ++index; + index++; } return -1; } @@ -415,7 +415,7 @@ RenderableTimeVaryingVolume::Timestep* RenderableTimeVaryingVolume::timestepFrom if (index == target) { return &(it.second); } - ++index; + index++; } return nullptr; } @@ -438,13 +438,13 @@ void RenderableTimeVaryingVolume::update(const UpdateData&) { // ie with lower bound from (-0.5, -0.5, -0.5) and upper bound (0.5, 0.5, 0.5) if (t && t->texture) { if (_raycaster->gridType() == volume::VolumeGridType::Cartesian) { - glm::dvec3 scale = t->metadata.upperDomainBound - - t->metadata.lowerDomainBound; - glm::dvec3 translation = + const glm::dvec3 scale = + t->metadata.upperDomainBound - t->metadata.lowerDomainBound; + const glm::dvec3 translation = (t->metadata.lowerDomainBound + t->metadata.upperDomainBound) * 0.5f; glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), translation); - glm::dmat4 scaleMatrix = glm::scale(glm::dmat4(1.0), scale); + const glm::dmat4 scaleMatrix = glm::scale(glm::dmat4(1.0), scale); modelTransform = modelTransform * scaleMatrix; _raycaster->setModelTransform(glm::mat4(modelTransform)); } @@ -482,7 +482,7 @@ bool RenderableTimeVaryingVolume::isReady() const { void RenderableTimeVaryingVolume::deinitializeGL() { if (_raycaster) { - global::raycasterManager->detachRaycaster(*_raycaster.get()); + global::raycasterManager->detachRaycaster(*_raycaster); _raycaster = nullptr; } } diff --git a/modules/volume/rendering/renderabletimevaryingvolume.h b/modules/volume/rendering/renderabletimevaryingvolume.h index 1bb1567821..a5d1f1a9cd 100644 --- a/modules/volume/rendering/renderabletimevaryingvolume.h +++ b/modules/volume/rendering/renderabletimevaryingvolume.h @@ -72,8 +72,8 @@ private: Timestep* currentTimestep(); int timestepIndex(const Timestep* t) const; - Timestep* timestepFromIndex(int index); - void jumpToTimestep(int i); + Timestep* timestepFromIndex(int target); + void jumpToTimestep(int target); void loadTimestepMetadata(const std::string& path); diff --git a/modules/volume/rendering/volumeclipplanes.cpp b/modules/volume/rendering/volumeclipplanes.cpp index 201a638ed8..689df97c6e 100644 --- a/modules/volume/rendering/volumeclipplanes.cpp +++ b/modules/volume/rendering/volumeclipplanes.cpp @@ -34,9 +34,9 @@ VolumeClipPlanes::VolumeClipPlanes(const ghoul::Dictionary& dictionary) // @TODO Missing documentation , _nClipPlanes({ "nClipPlanes", "Number of clip planes", "" }, 0, 0, 10) { - for (std::string_view key : dictionary.keys()) { - ghoul::Dictionary cutPlaneDictionary = dictionary.value(key); - VolumeClipPlane clipPlane = VolumeClipPlane(cutPlaneDictionary); + for (const std::string_view key : dictionary.keys()) { + const ghoul::Dictionary cutplane = dictionary.value(key); + VolumeClipPlane clipPlane = VolumeClipPlane(cutplane); clipPlane.setIdentifier(std::string(key)); _clipPlanes.push_back(std::move(clipPlane)); } @@ -54,6 +54,7 @@ void VolumeClipPlanes::deinitialize() {} std::vector VolumeClipPlanes::normals() { std::vector normals; + normals.reserve(_clipPlanes.size()); for (const VolumeClipPlane& clipPlane : _clipPlanes) { normals.push_back(clipPlane.normal()); } @@ -62,6 +63,7 @@ std::vector VolumeClipPlanes::normals() { std::vector VolumeClipPlanes::offsets() { std::vector offsets; + offsets.reserve(_clipPlanes.size()); for (const VolumeClipPlane& clipPlane : _clipPlanes) { offsets.push_back(clipPlane.offsets()); } diff --git a/modules/volume/tasks/generaterawvolumetask.cpp b/modules/volume/tasks/generaterawvolumetask.cpp index 5978b7de58..159d01aa85 100644 --- a/modules/volume/tasks/generaterawvolumetask.cpp +++ b/modules/volume/tasks/generaterawvolumetask.cpp @@ -88,11 +88,11 @@ GenerateRawVolumeTask::GenerateRawVolumeTask(const ghoul::Dictionary& dictionary } std::string GenerateRawVolumeTask::description() { - return fmt::format( + return std::format( "Generate a raw volume with dimenstions: ({}, {}, {}). For each cell, set the " "value by evaluating the lua function: `{}`, with three arguments (x, y, z) " - "ranging from ({}, {}, {}) to ({}, {}, {}). Write raw volume data into {} and " - "dictionary with metadata to {}", + "ranging from ({}, {}, {}) to ({}, {}, {}). Write raw volume data into '{}' and " + "dictionary with metadata to '{}'", _dimensions.x, _dimensions.y, _dimensions.z, _valueFunctionLua, _lowerDomainBound.x, _lowerDomainBound.y, _lowerDomainBound.z, _upperDomainBound.x, _upperDomainBound.y, _upperDomainBound.z, @@ -133,8 +133,8 @@ void GenerateRawVolumeTask::perform(const Task::ProgressCallback& progressCallba float minVal = std::numeric_limits::max(); float maxVal = std::numeric_limits::min(); - rawVolume.forEachVoxel([&](glm::uvec3 cell, float) { - glm::vec3 coord = _lowerDomainBound + + rawVolume.forEachVoxel([&](const glm::uvec3& cell, float) { + const glm::vec3 coord = _lowerDomainBound + glm::vec3(cell) / glm::vec3(_dimensions) * domainSize; #if (defined(NDEBUG) || defined(DEBUG)) @@ -154,7 +154,7 @@ void GenerateRawVolumeTask::perform(const Task::ProgressCallback& progressCallba return; } - float value = static_cast(luaL_checknumber(state, 1)); + const float value = static_cast(luaL_checknumber(state, 1)); lua_pop(state, 1); rawVolume.set(cell, value); @@ -189,14 +189,13 @@ void GenerateRawVolumeTask::perform(const Task::ProgressCallback& progressCallba metadata.minValue = minVal; metadata.maxValue = maxVal; - ghoul::Dictionary outputDictionary = metadata.dictionary(); - std::string metadataString = ghoul::formatLua(outputDictionary); + const ghoul::Dictionary outputDictionary = metadata.dictionary(); + const std::string metadataString = ghoul::formatLua(outputDictionary); - std::fstream f(_dictionaryOutputPath, std::ios::out); + std::fstream f = std::fstream(_dictionaryOutputPath, std::ios::out); f << "return " << metadataString; - f.close(); - progressCallback(1.0f); + progressCallback(1.f); } } // namespace openspace::volume diff --git a/modules/volume/transferfunction.cpp b/modules/volume/transferfunction.cpp index 8f5f0d9a5e..f07afd4ce8 100644 --- a/modules/volume/transferfunction.cpp +++ b/modules/volume/transferfunction.cpp @@ -33,20 +33,22 @@ using json = nlohmann::json; namespace openspace::volume { -TransferFunction::TransferFunction(const std::string& s) { - setEnvelopesFromString(s); +TransferFunction::TransferFunction(const std::string& string) { + setEnvelopesFromString(string); } bool TransferFunction::setEnvelopesFromString(const std::string& s) { - json j = json::parse(s); - for (json::iterator it = j.begin(); it != j.end(); ++it) { + const json j = json::parse(s); + for (const nlohmann::json& it : j) { Envelope env; std::vector tmpVec; + const nlohmann::json& points = it["points"]; for (size_t i = 0; i < 4; i++) { - std::string color = (*it)["points"][i]["color"].get(); - float x_value = (*it)["points"][i]["position"]["x"].get(); - float y_value = (*it)["points"][i]["position"]["y"].get(); - tmpVec.emplace_back(color, x_value, y_value); + const nlohmann::json& jt = points[i]; + const std::string color = jt["color"].get(); + const float xValue = jt["position"]["x"].get(); + const float yValue = jt["position"]["y"].get(); + tmpVec.emplace_back(color, xValue, yValue); } env.setPoints(tmpVec); _envelopes.emplace_back(env); @@ -57,32 +59,32 @@ bool TransferFunction::setEnvelopesFromString(const std::string& s) { bool TransferFunction::setEnvelopesFromLua(lua_State* state) { ghoul_assert(false, "Implement this"); - bool success = (lua_istable(state, -1) == 1); + const bool success = (lua_istable(state, -1) == 1); if (success) { lua_pushnil(state); while (lua_next(state, -2)) { - Envelope env; - std::vector tmpVec; + //Envelope env; + //std::vector tmpVec; - /*lua_pushnil(state); - while (lua_next(state, -2)) { - lua_pushnil(state); - while (lua_next(state, -2)) { - PrintTable(state); - std::string color = static_cast(lua_tostring(state, -1)); - lua_pop(state, 1); - lua_pushnil(state); - lua_next(state, -2); - float x_value = static_cast(lua_tonumber(state, -1)); + //lua_pushnil(state); + //while (lua_next(state, -2)) { + // lua_pushnil(state); + // while (lua_next(state, -2)) { + // PrintTable(state); + // std::string color = static_cast(lua_tostring(state, -1)); + // lua_pop(state, 1); + // lua_pushnil(state); + // lua_next(state, -2); + // float x_value = static_cast(lua_tonumber(state, -1)); - lua_pop(state, 1); - lua_next(state, -2); - float y_value = static_cast(lua_tonumber(state, -1)); - lua_pop(state, 1); - tmpVec.emplace_back(color, x_value, y_value); - lua_pop(state, 1); - } - }*/ + // lua_pop(state, 1); + // lua_next(state, -2); + // float y_value = static_cast(lua_tonumber(state, -1)); + // lua_pop(state, 1); + // tmpVec.emplace_back(color, x_value, y_value); + // lua_pop(state, 1); + // } + //} lua_pop(state, 2); } lua_pop(state, 1); @@ -92,7 +94,7 @@ bool TransferFunction::setEnvelopesFromLua(lua_State* state) { void TransferFunction::envelopesToLua(lua_State* state) const { lua_newtable(state); - for (auto iter = _envelopes.begin(); iter != _envelopes.end(); ++iter) { + for (auto iter = _envelopes.begin(); iter != _envelopes.end(); iter++) { lua_newtable(state); iter->setEnvelopeLuaTable(state); lua_setfield( @@ -108,24 +110,24 @@ void TransferFunction::loadEnvelopesFromFile(const std::string& path) { ghoul::Dictionary dictionary; ghoul::lua::loadDictionaryFromFile(path, dictionary, L); - for (std::string_view key : dictionary.keys()) { - ghoul::Dictionary tfDictionary = dictionary.value(key); + for (const std::string_view key : dictionary.keys()) { + const ghoul::Dictionary tfDictionary = dictionary.value(key); - for (std::string_view envelopeKey : tfDictionary.keys()) { - ghoul::Dictionary envelopeDictionary = + for (const std::string_view envelopeKey : tfDictionary.keys()) { + const ghoul::Dictionary envelopeDictionary = tfDictionary.value(envelopeKey); Envelope env; std::vector tmpVec; - for (std::string_view pointKey : envelopeDictionary.keys()) { - ghoul::Dictionary pointDictionary = + for (const std::string_view pointKey : envelopeDictionary.keys()) { + const ghoul::Dictionary pointDictionary = envelopeDictionary.value(pointKey); - ghoul::Dictionary positionDictionary = + const ghoul::Dictionary positionDictionary = pointDictionary.value("position"); - std::string color = pointDictionary.value("color"); - double posX = positionDictionary.value("x"); - double posY = positionDictionary.value("y"); + const std::string color = pointDictionary.value("color"); + const double posX = positionDictionary.value("x"); + const double posY = positionDictionary.value("y"); tmpVec.emplace_back( color, static_cast(posX), @@ -138,7 +140,7 @@ void TransferFunction::loadEnvelopesFromFile(const std::string& path) { } } -void TransferFunction::saveEnvelopesToFile(const std::string& path) { +void TransferFunction::saveEnvelopesToFile(const std::string& path) const { ghoul::Dictionary dictionary; lua_State* state = luaL_newstate(); envelopesToLua(state); @@ -163,9 +165,10 @@ bool TransferFunction::operator!=(const TransferFunction& tf) { auto iter = _envelopes.begin(); auto tfIter = tf._envelopes.begin(); - for (; iter != _envelopes.end(); ++iter, ++tfIter) { - if (*iter != *tfIter) + for (; iter != _envelopes.end(); iter++, tfIter++) { + if (*iter != *tfIter) { return true; + } } return false; } @@ -193,7 +196,7 @@ bool TransferFunction::createTexture(ghoul::opengl::Texture& ptr) { float* transferFunction = new float[_width * 4]; std::memset(transferFunction, 0, _width * 4 * sizeof(float)); - for (int i = 0; i < _width ; ++i) { + for (int i = 0; i < _width ; i++) { const float position = static_cast(i) / static_cast(_width); int count = 0; glm::vec4 rgbFromEnvelopes(0.f); diff --git a/modules/volume/transferfunction.h b/modules/volume/transferfunction.h index 396cab17f2..58a164e71d 100644 --- a/modules/volume/transferfunction.h +++ b/modules/volume/transferfunction.h @@ -41,10 +41,10 @@ public: void envelopesToLua(lua_State* state) const; bool setEnvelopesFromString(const std::string& s); - bool setEnvelopesFromLua(lua_State* lua); + bool setEnvelopesFromLua(lua_State* state); void loadEnvelopesFromFile(const std::string& path); - void saveEnvelopesToFile(const std::string& path); + void saveEnvelopesToFile(const std::string& path) const; bool operator!=(const TransferFunction& tf); bool hasEnvelopes() const; diff --git a/modules/volume/transferfunctionhandler.cpp b/modules/volume/transferfunctionhandler.cpp index 251211dc03..b840c5516d 100644 --- a/modules/volume/transferfunctionhandler.cpp +++ b/modules/volume/transferfunctionhandler.cpp @@ -68,9 +68,9 @@ namespace { namespace openspace::volume { -TransferFunctionHandler::TransferFunctionHandler(const properties::StringProperty& prop) +TransferFunctionHandler::TransferFunctionHandler(properties::StringProperty prop) : properties::PropertyOwner({ "TransferFunctionHandler", "Tranfer Function Handler" }) - , _transferFunctionPath(prop) + , _transferFunctionPath(std::move(prop)) , _dataUnit(DataUnitInfo) , _minValue(MinValueInfo) , _maxValue(MaxValueInfo) @@ -143,7 +143,7 @@ void TransferFunctionHandler::setFilepath(std::string path) { } ghoul::opengl::Texture& TransferFunctionHandler::texture() { - return *_texture.get(); + return *_texture; } void TransferFunctionHandler::uploadTexture() { diff --git a/modules/volume/transferfunctionhandler.h b/modules/volume/transferfunctionhandler.h index cc6fa9341a..2259f30cc1 100644 --- a/modules/volume/transferfunctionhandler.h +++ b/modules/volume/transferfunctionhandler.h @@ -44,7 +44,7 @@ class Envelope; class TransferFunctionHandler : public properties::PropertyOwner { public: - TransferFunctionHandler(const properties::StringProperty& prop); + TransferFunctionHandler(properties::StringProperty prop); void initialize(); diff --git a/modules/volume/transferfunctionproperty.cpp b/modules/volume/transferfunctionproperty.cpp index af280c22da..feb288b63b 100644 --- a/modules/volume/transferfunctionproperty.cpp +++ b/modules/volume/transferfunctionproperty.cpp @@ -29,7 +29,7 @@ namespace openspace::properties { TransferFunctionProperty::TransferFunctionProperty(Property::PropertyInfo info, volume::TransferFunction value) - : TemplateProperty(std::move(info), value) + : TemplateProperty(std::move(info), std::move(value)) {} std::string_view TransferFunctionProperty::className() const { diff --git a/modules/volume/volumegridtype.cpp b/modules/volume/volumegridtype.cpp index 917ae65a39..57ced6d10f 100644 --- a/modules/volume/volumegridtype.cpp +++ b/modules/volume/volumegridtype.cpp @@ -26,9 +26,9 @@ namespace openspace::volume { -InvalidGridTypeError::InvalidGridTypeError(std::string gt) - : RuntimeError("Invalid grid type: '" + gt + "'") - , gridType(std::move(gt)) +InvalidGridTypeError::InvalidGridTypeError(std::string gridType) + : RuntimeError("Invalid grid type: '" + gridType + "'") + , gridType(std::move(gridType)) {} VolumeGridType parseGridType(const std::string& gridType) { diff --git a/modules/volume/volumeutils.cpp b/modules/volume/volumeutils.cpp index 143397a700..624cd3f003 100644 --- a/modules/volume/volumeutils.cpp +++ b/modules/volume/volumeutils.cpp @@ -26,15 +26,15 @@ namespace openspace::volume { -size_t coordsToIndex(const glm::uvec3& coords, const glm::uvec3& dims) { - const size_t w = dims.x; - const size_t h = dims.y; +size_t coordsToIndex(const glm::uvec3& coords, const glm::uvec3& dimensions) { + const size_t w = dimensions.x; + const size_t h = dimensions.y; return coords.z * (h * w) + coords.y * w + coords.x; } -glm::uvec3 indexToCoords(size_t index, const glm::uvec3& dims) { - const size_t w = dims.x; - const size_t h = dims.y; +glm::uvec3 indexToCoords(size_t index, const glm::uvec3& dimensions) { + const size_t w = dimensions.x; + const size_t h = dimensions.y; const size_t x = index % w; const size_t y = (index / w) % h; diff --git a/modules/webbrowser/include/browserinstance.h b/modules/webbrowser/include/browserinstance.h index 0cb61eab11..0e29b93c49 100644 --- a/modules/webbrowser/include/browserinstance.h +++ b/modules/webbrowser/include/browserinstance.h @@ -61,7 +61,7 @@ public: BrowserInstance(WebRenderHandler* renderer, WebKeyboardHandler* keyboardHandler); ~BrowserInstance(); - void loadUrl(std::string url); + void loadUrl(const std::string& url); /** * Load a local file. diff --git a/modules/webbrowser/include/eventhandler.h b/modules/webbrowser/include/eventhandler.h index 959041dccf..7897e72492 100644 --- a/modules/webbrowser/include/eventhandler.h +++ b/modules/webbrowser/include/eventhandler.h @@ -82,7 +82,7 @@ private: /** * Create a mouse event on the current cursor position. */ - CefMouseEvent mouseEvent(KeyModifier mods = KeyModifier::None); + CefMouseEvent mouseEvent(KeyModifier mods = KeyModifier::None) const; #ifdef WIN32 /** diff --git a/modules/webbrowser/include/webbrowserapp.h b/modules/webbrowser/include/webbrowserapp.h index e3c0ccd865..32c3d2d3a6 100644 --- a/modules/webbrowser/include/webbrowserapp.h +++ b/modules/webbrowser/include/webbrowserapp.h @@ -51,7 +51,7 @@ public: void OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context) override; void OnBeforeCommandLineProcessing(const CefString &process_type, - CefRefPtr command_line) override; + CefRefPtr commandline) override; private: IMPLEMENT_REFCOUNTING(WebBrowserApp); diff --git a/modules/webbrowser/src/browserinstance.cpp b/modules/webbrowser/src/browserinstance.cpp index 33da63a9da..b2e523e7ea 100644 --- a/modules/webbrowser/src/browserinstance.cpp +++ b/modules/webbrowser/src/browserinstance.cpp @@ -47,9 +47,8 @@ BrowserInstance::BrowserInstance(WebRenderHandler* renderer, WebKeyboardHandler* keyboardHandler) : _renderHandler(renderer) , _keyboardHandler(keyboardHandler) + , _client(new BrowserClient(_renderHandler.get(), _keyboardHandler.get())) { - _client = new BrowserClient(_renderHandler.get(), _keyboardHandler.get()); - CefWindowInfo windowInfo; // On Windows and MacOS this function takes a pointer as a parameter, but Linux // requires this to be a long unsigned int, so we can't use nullptr here @@ -58,11 +57,10 @@ BrowserInstance::BrowserInstance(WebRenderHandler* renderer, CefBrowserSettings browserSettings; browserSettings.windowless_frame_rate = 60; - std::string url; _browser = CefBrowserHost::CreateBrowserSync( windowInfo, _client.get(), - url, + "", browserSettings, nullptr, nullptr @@ -86,13 +84,12 @@ void BrowserInstance::initialize() { _shouldReshape = true; } -void BrowserInstance::loadUrl(std::string url) { +void BrowserInstance::loadUrl(const std::string& url) { ghoul_assert(_isInitialized, "BrowserInstance should be initialized"); if (!url.empty()) { - LDEBUG(fmt::format("Loading URL: {}", url)); - CefString cefUrl = std::move(url); - _browser->GetMainFrame()->LoadURL(cefUrl); + LDEBUG(std::format("Loading URL '{}'", url)); + _browser->GetMainFrame()->LoadURL(url); } else { LWARNING("Provided browser URL is empty"); @@ -101,7 +98,7 @@ void BrowserInstance::loadUrl(std::string url) { bool BrowserInstance::loadLocalPath(std::string path) { if (!std::filesystem::is_regular_file(path)) { - LDEBUG(fmt::format("Could not find path '{}', verify that it is correct", path)); + LDEBUG(std::format("Could not find path '{}', verify that it is correct", path)); return false; } diff --git a/modules/webbrowser/src/cefhost.cpp b/modules/webbrowser/src/cefhost.cpp index 94388eb388..2c6e7870a4 100644 --- a/modules/webbrowser/src/cefhost.cpp +++ b/modules/webbrowser/src/cefhost.cpp @@ -28,7 +28,7 @@ #include #include #include -#include +#include #ifdef __APPLE__ #include @@ -67,9 +67,9 @@ CefHost::CefHost([[maybe_unused]] const std::string& helperLocation) { } #endif // __APPLE__ - CefRefPtr app(new WebBrowserApp); + const CefRefPtr app = CefRefPtr(new WebBrowserApp); - CefMainArgs args; + const CefMainArgs args; CefInitialize(args, settings, app.get(), nullptr); LDEBUG("Initializing CEF... done"); } @@ -81,7 +81,7 @@ CefHost::~CefHost() { void CefHost::attachDebugSettings(CefSettings &settings) { settings.remote_debugging_port = 8088; - LDEBUG(fmt::format( + LDEBUG(std::format( "Remote WebBrowser debugging available on http://localhost:{}", settings.remote_debugging_port )); diff --git a/modules/webbrowser/src/eventhandler.cpp b/modules/webbrowser/src/eventhandler.cpp index c4bf4b4e88..df745a55df 100644 --- a/modules/webbrowser/src/eventhandler.cpp +++ b/modules/webbrowser/src/eventhandler.cpp @@ -32,7 +32,7 @@ #include #include #include -#include +#include namespace { constexpr std::string_view _loggerCat = "WebBrowser:EventHandler"; @@ -263,7 +263,7 @@ void EventHandler::initialize() { ); _browserInstance->sendTouchEvent(event); #else // ^^^^ WIN32 // !WIN32 vvvv - glm::vec2 windowPos = input.currentWindowCoordinates(); + const glm::vec2 windowPos = input.currentWindowCoordinates(); _mousePosition.x = windowPos.x; _mousePosition.y = windowPos.y; _leftButton.down = true; @@ -311,7 +311,7 @@ void EventHandler::initialize() { _validTouchStates.erase(found); #ifndef WIN32 if (_validTouchStates.empty()) { - glm::vec2 windowPos = input.currentWindowCoordinates(); + const glm::vec2 windowPos = input.currentWindowCoordinates(); _mousePosition.x = windowPos.x; _mousePosition.y = windowPos.y; _leftButton.down = false; @@ -365,7 +365,7 @@ bool EventHandler::mouseButtonCallback(MouseButton button, MouseAction action, bool EventHandler::isDoubleClick(const MouseButtonState& button) const { auto now = std::chrono::high_resolution_clock::now(); - std::chrono::milliseconds maxTimeDifference(doubleClickTime()); + const std::chrono::milliseconds maxTimeDifference(doubleClickTime()); auto requiredTime = button.lastClickTime + maxTimeDifference; if (requiredTime < now) { return false; @@ -381,8 +381,8 @@ bool EventHandler::isDoubleClick(const MouseButtonState& button) const { bool EventHandler::mousePositionCallback(double x, double y) { const glm::vec2 dpiScaling = global::windowDelegate->dpiScaling(); - _mousePosition.x = floor(static_cast(x) * dpiScaling.x); - _mousePosition.y = floor(static_cast(y) * dpiScaling.y); + _mousePosition.x = std::floor(static_cast(x) * dpiScaling.x); + _mousePosition.y = std::floor(static_cast(y) * dpiScaling.y); _mousePosition = global::windowDelegate->mousePositionViewportRelative(_mousePosition); _browserInstance->sendMouseMoveEvent(mouseEvent()); @@ -468,7 +468,7 @@ cef_key_event_type_t EventHandler::keyEventType(KeyAction action) { return action == KeyAction::Release ? KEYEVENT_KEYUP : KEYEVENT_KEYDOWN; } -CefMouseEvent EventHandler::mouseEvent(KeyModifier mods) { +CefMouseEvent EventHandler::mouseEvent(KeyModifier mods) const { CefMouseEvent event; event.x = static_cast(_mousePosition.x); event.y = static_cast(_mousePosition.y); diff --git a/modules/webbrowser/src/processhelperlinux.cpp b/modules/webbrowser/src/processhelperlinux.cpp index fddd8356b6..16ac417937 100644 --- a/modules/webbrowser/src/processhelperlinux.cpp +++ b/modules/webbrowser/src/processhelperlinux.cpp @@ -32,12 +32,12 @@ // Entry point function for all processes. int main(int argc, char* argv[]) { // Provide CEF with command-line arguments. - CefMainArgs main_args(argc, argv); + const CefMainArgs mainArgs(argc, argv); - CefRefPtr app(new openspace::WebBrowserApp); + const CefRefPtr app(new openspace::WebBrowserApp); // CEF applications have multiple sub-processes (render, GPU, etc) that share // the same executable. This function checks the command-line and, if this is // a sub-process, executes the appropriate logic. - return CefExecuteProcess(main_args, app.get(), nullptr); + return CefExecuteProcess(mainArgs, app.get(), nullptr); } diff --git a/modules/webbrowser/src/screenspacebrowser.cpp b/modules/webbrowser/src/screenspacebrowser.cpp index a7aea56939..026c6f9f9a 100644 --- a/modules/webbrowser/src/screenspacebrowser.cpp +++ b/modules/webbrowser/src/screenspacebrowser.cpp @@ -82,6 +82,8 @@ void ScreenSpaceBrowser::ScreenSpaceRenderHandler::setTexture(GLuint t) { ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary& dictionary) : ScreenSpaceRenderable(dictionary) , _dimensions(DimensionsInfo, glm::vec2(0.f), glm::vec2(0.f), glm::vec2(3000.f)) + , _renderHandler(new ScreenSpaceRenderHandler) + , _keyboardHandler(new WebKeyboardHandler) , _url(UrlInfo) , _reload(ReloadInfo) { @@ -93,11 +95,9 @@ ScreenSpaceBrowser::ScreenSpaceBrowser(const ghoul::Dictionary& dictionary) _url = p.url.value_or(_url); - glm::vec2 windowDimensions = global::windowDelegate->currentSubwindowSize(); + const glm::vec2 windowDimensions = global::windowDelegate->currentSubwindowSize(); _dimensions = p.dimensions.value_or(windowDimensions); - _renderHandler = new ScreenSpaceRenderHandler; - _keyboardHandler = new WebKeyboardHandler(); _browserInstance = std::make_unique( _renderHandler.get(), _keyboardHandler.get() @@ -136,7 +136,7 @@ bool ScreenSpaceBrowser::deinitializeGL() { _renderHandler->setTexture(0); _texture = nullptr; - LDEBUG(fmt::format("Deinitializing ScreenSpaceBrowser: {}", _url.value())); + LDEBUG(std::format("Deinitializing ScreenSpaceBrowser: {}", _url.value())); _browserInstance->close(true); @@ -158,7 +158,7 @@ void ScreenSpaceBrowser::render(float blackoutFactor) { } _renderHandler->updateTexture(); - glm::mat4 mat = + const glm::mat4 mat = globalRotationMatrix() * translationMatrix() * localRotationMatrix() * diff --git a/modules/webbrowser/src/webbrowserapp.cpp b/modules/webbrowser/src/webbrowserapp.cpp index c4b09f8ed6..8867954074 100644 --- a/modules/webbrowser/src/webbrowserapp.cpp +++ b/modules/webbrowser/src/webbrowserapp.cpp @@ -40,18 +40,18 @@ void WebBrowserApp::OnContextCreated(CefRefPtr, CefRefPtr, } void WebBrowserApp::OnBeforeCommandLineProcessing(const CefString&, - CefRefPtr commandLine) + CefRefPtr commandline) { - commandLine->AppendSwitch("--enable-gpu-rasterization"); - commandLine->AppendSwitch("--use-gl=desktop"); - commandLine->AppendSwitch("--enable-webgl2-compute-context"); - commandLine->AppendSwitch("log-gpu-control-list-decisions"); - commandLine->AppendSwitch("use-mock-keychain"); - commandLine->AppendSwitch("enable-begin-frame-scheduling"); - commandLine->AppendSwitchWithValue("autoplay-policy", "no-user-gesture-required"); + commandline->AppendSwitch("--enable-gpu-rasterization"); + commandline->AppendSwitch("--use-gl=desktop"); + commandline->AppendSwitch("--enable-webgl2-compute-context"); + commandline->AppendSwitch("log-gpu-control-list-decisions"); + commandline->AppendSwitch("use-mock-keychain"); + commandline->AppendSwitch("enable-begin-frame-scheduling"); + commandline->AppendSwitchWithValue("autoplay-policy", "no-user-gesture-required"); #ifdef __APPLE__ - commandLine->AppendSwitch("--disable-gpu-sandbox"); - commandLine->AppendSwitch("--no-sandbox"); + commandline->AppendSwitch("--disable-gpu-sandbox"); + commandline->AppendSwitch("--no-sandbox"); #endif } diff --git a/modules/webbrowser/src/webrenderhandler.cpp b/modules/webbrowser/src/webrenderhandler.cpp index 3780722976..0bdccd183b 100644 --- a/modules/webbrowser/src/webrenderhandler.cpp +++ b/modules/webbrowser/src/webrenderhandler.cpp @@ -25,7 +25,6 @@ #include #include -#include #include namespace openspace { @@ -78,10 +77,10 @@ void WebRenderHandler::OnPaint(CefRefPtr, CefRenderHandler::PaintEle // Copy the updated rectangle line by line. for (int y = lowerUpdatingRectBound.y; y < upperUpdatingRectBound.y; ++y) { - int lineOffset = y * w + lowerUpdatingRectBound.x; + const int lineOffset = y * w + lowerUpdatingRectBound.x; // Chromium stores image upside down compared to OpenGL, so we flip it: - int invLineOffset = (h - y - 1) * w + lowerUpdatingRectBound.x; - int rectWidth = upperUpdatingRectBound.x - lowerUpdatingRectBound.x; + const int invLineOffset = (h - y - 1) * w + lowerUpdatingRectBound.x; + const int rectWidth = upperUpdatingRectBound.x - lowerUpdatingRectBound.x; std::copy( reinterpret_cast(buffer) + lineOffset, reinterpret_cast(buffer) + lineOffset + rectWidth, diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index 3a4675cbd3..61fd0e8360 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -69,6 +69,25 @@ namespace { "Only used if UpdateBrowserBetweenRenderables is true", openspace::properties::Property::Visibility::Developer }; + + /** + * Try to find the CEF Helper executable. It looks in the bin/openspace folder. + * Therefore, if you change that this might cause a crash here. + * + * \return the absolute path to the file + */ + std::filesystem::path findHelperExecutable() { + const std::filesystem::path execLocation = absPath(std::format( + "${{BIN}}/{}", SubprocessPath + )); + if (!std::filesystem::is_regular_file(execLocation)) { + LERROR(std::format( + "Could not find web helper executable at location: {}", execLocation + )); + } + return execLocation; + } + } // namespace namespace openspace { @@ -76,7 +95,7 @@ namespace openspace { WebBrowserModule::WebBrowserModule() : OpenSpaceModule(WebBrowserModule::Name) , _updateBrowserBetweenRenderables(UpdateBrowserBetweenRenderablesInfo, true) - , _browserUpdateInterval(BrowserUpdateIntervalInfo, 1.f, 1.0f, 1000.f) + , _browserUpdateInterval(BrowserUpdateIntervalInfo, 1.f, 1.f, 1000.f) , _eventHandler(new EventHandler) { global::callback::deinitialize->emplace_back([this]() { @@ -104,6 +123,8 @@ WebBrowserModule::WebBrowserModule() addProperty(_browserUpdateInterval); } +WebBrowserModule::~WebBrowserModule() {} + void WebBrowserModule::internalDeinitialize() { ZoneScoped; @@ -113,22 +134,12 @@ void WebBrowserModule::internalDeinitialize() { _eventHandler->resetBrowserInstance(); - bool forceBrowserShutdown = true; + const bool forceBrowserShutdown = true; for (BrowserInstance* browser : _browsers) { browser->close(forceBrowserShutdown); } } -std::filesystem::path WebBrowserModule::findHelperExecutable() { - std::filesystem::path execLocation = absPath("${BIN}/" + std::string(SubprocessPath)); - if (!std::filesystem::is_regular_file(execLocation)) { - LERROR(fmt::format( - "Could not find web helper executable at location: {}" , execLocation - )); - } - return execLocation; -} - void WebBrowserModule::internalInitialize(const ghoul::Dictionary& dictionary) { ZoneScoped; @@ -143,7 +154,7 @@ void WebBrowserModule::internalInitialize(const ghoul::Dictionary& dictionary) { _enabled = dictionary.value("Enabled"); } - LDEBUG(fmt::format("CEF using web helper executable: {}", _webHelperLocation)); + LDEBUG(std::format("CEF using web helper executable: {}", _webHelperLocation)); _cefHost = std::make_unique(_webHelperLocation.string()); LDEBUG("Starting CEF... done"); @@ -194,7 +205,7 @@ void WebBrowserModule::removeBrowser(BrowserInstance* browser) { global::callback::webBrowserPerformanceHotfix = nullptr; } - LDEBUG(fmt::format("Number of browsers stored: {}", _browsers.size())); + LDEBUG(std::format("Number of browsers stored: {}", _browsers.size())); } void WebBrowserModule::attachEventHandler(BrowserInstance* browserInstance) { @@ -229,7 +240,7 @@ void update() { const std::chrono::time_point timeBefore = std::chrono::high_resolution_clock::now(); - std::chrono::microseconds duration = + const std::chrono::microseconds duration = std::chrono::duration_cast(timeBefore - latestCall); if (duration > interval) { diff --git a/modules/webbrowser/webbrowsermodule.h b/modules/webbrowser/webbrowsermodule.h index d345ef74b5..3ec9a233f4 100644 --- a/modules/webbrowser/webbrowsermodule.h +++ b/modules/webbrowser/webbrowsermodule.h @@ -49,7 +49,7 @@ public: static constexpr const char* Name = "WebBrowser"; WebBrowserModule(); - ~WebBrowserModule() override = default; + ~WebBrowserModule() override; void addBrowser(BrowserInstance*); void removeBrowser(BrowserInstance*); @@ -63,14 +63,6 @@ protected: void internalDeinitialize() override; private: - /** - * Try to find the CEF Helper executable. It looks in the bin/openspace folder. - * Therefore, if you change that this might cause a crash here. - * - * \return the absolute path to the file - */ - std::filesystem::path findHelperExecutable(); - properties::BoolProperty _updateBrowserBetweenRenderables; properties::FloatProperty _browserUpdateInterval; diff --git a/modules/webgui/webguimodule.cpp b/modules/webgui/webguimodule.cpp index 26dc12233e..5e8ca13470 100644 --- a/modules/webgui/webguimodule.cpp +++ b/modules/webgui/webguimodule.cpp @@ -153,8 +153,8 @@ std::string WebGuiModule::address() const { WebGuiModule::CallbackHandle WebGuiModule::addEndpointChangeCallback(EndpointCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; - _endpointChangeCallbacks.push_back({ handle, std::move(cb) }); + const CallbackHandle handle = _nextCallbackHandle++; + _endpointChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } @@ -259,7 +259,7 @@ void WebGuiModule::startProcess() { std::string formattedDirectories = "["; std::vector directories = _directories; - for (size_t i = 0; i < directories.size(); ++i) { + for (size_t i = 0; i < directories.size(); i++) { std::string arg = directories[i]; if (i % 2 == 1) { arg = absPath(arg).string(); @@ -273,10 +273,10 @@ void WebGuiModule::startProcess() { std::string defaultEndpoint; if (!_defaultEndpoint.value().empty()) { - defaultEndpoint = fmt::format("--redirect \"{}\"", _defaultEndpoint.value()); + defaultEndpoint = std::format("--redirect \"{}\"", _defaultEndpoint.value()); } - const std::string command = fmt::format( + const std::string command = std::format( "\"{}\" \"{}\" --directories \"{}\" {} --http-port \"{}\" --ws-address \"{}\" " "--ws-port {} --auto-close --local", node.string(), absPath(_entryPoint.value()).string(), formattedDirectories, @@ -288,11 +288,11 @@ void WebGuiModule::startProcess() { absPath("${BIN}").string(), [](const char* data, size_t n) { const std::string str(data, n); - LDEBUG(fmt::format("Web GUI server output: {}", str)); + LDEBUG(std::format("Web GUI server output: {}", str)); }, [](const char* data, size_t n) { const std::string str(data, n); - LERROR(fmt::format("Web GUI server error: {}", str)); + LERROR(std::format("Web GUI server error: {}", str)); } ); } diff --git a/src/camera/camera.cpp b/src/camera/camera.cpp index 95a3b46744..075a851c59 100644 --- a/src/camera/camera.cpp +++ b/src/camera/camera.cpp @@ -46,14 +46,14 @@ void Camera::setPose(CameraPose pose) { void Camera::setPositionVec3(glm::dvec3 pos) { if (!glm::any(glm::isnan(pos))) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _position = std::move(pos); _cachedCombinedViewMatrix.isDirty = true; } } void Camera::setRotation(glm::dquat rotation) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _rotation = std::move(rotation); _cachedViewDirection.isDirty = true; _cachedLookupVector.isDirty = true; @@ -62,14 +62,14 @@ void Camera::setRotation(glm::dquat rotation) { } void Camera::setScaling(float scaling) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _scaling = scaling; _cachedViewScaleMatrix.isDirty = true; _cachedCombinedViewMatrix.isDirty = true; } void Camera::setMaxFov(float fov) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _maxFov = fov; _cachedSinMaxFov.isDirty = true; } @@ -78,9 +78,9 @@ void Camera::setParent(SceneGraphNode* parent) { _parent = parent; } -void Camera::rotate(glm::dquat rotation) { - std::lock_guard _lock(_mutex); - _rotation = std::move(rotation) * static_cast(_rotation); +void Camera::rotate(const glm::dquat& rotation) { + const std::lock_guard _lock(_mutex); + _rotation = rotation * static_cast(_rotation); _cachedViewDirection.isDirty = true; _cachedLookupVector.isDirty = true; @@ -93,19 +93,19 @@ const glm::dvec3& Camera::positionVec3() const { } glm::dvec3 Camera::eyePositionVec3() const { - glm::dvec4 eyeInEyeSpace(0.0, 0.0, 0.0, 1.0); + constexpr glm::dvec4 EyeInEyeSpace = glm::dvec4(0.0, 0.0, 0.0, 1.0); - glm::dmat4 invViewMatrix = glm::inverse(sgctInternal.viewMatrix()); - glm::dmat4 invRotationMatrix = glm::mat4_cast(static_cast(_rotation)); - glm::dmat4 invTranslationMatrix = glm::translate( + const glm::dmat4 invViewMat = glm::inverse(sgctInternal.viewMatrix()); + const glm::dmat4 invRotationMat = glm::mat4_cast(static_cast(_rotation)); + const glm::dmat4 invTranslationMat = glm::translate( glm::dmat4(1.0), static_cast(_position) ); - glm::dmat4 invViewScale = glm::inverse(viewScaleMatrix()); + const glm::dmat4 invViewScale = glm::inverse(viewScaleMatrix()); - glm::dvec4 eyeInWorldSpace = invTranslationMatrix * invRotationMatrix * - invViewScale * invViewMatrix * eyeInEyeSpace; + const glm::dvec4 eyeInWorldSpace = invTranslationMat * invRotationMat * + invViewScale * invViewMat * EyeInEyeSpace; return glm::dvec3(eyeInWorldSpace.x, eyeInWorldSpace.y, eyeInWorldSpace.z); } @@ -145,7 +145,7 @@ float Camera::maxFov() const { float Camera::sinMaxFov() const { if (_cachedSinMaxFov.isDirty) { - _cachedSinMaxFov.datum = sin(_maxFov); + _cachedSinMaxFov.datum = std::sin(_maxFov); _cachedSinMaxFov.isDirty = true; } return _cachedSinMaxFov.datum; @@ -216,8 +216,8 @@ void Camera::invalidateCache() { void Camera::serialize(std::ostream& os) const { const glm::dvec3 p = positionVec3(); const glm::dquat q = rotationQuaternion(); - os << p.x << " " << p.y << " " << p.z << std::endl; - os << q.x << " " << q.y << " " << q.z << " " << q.w << std::endl; + os << p.x << " " << p.y << " " << p.z << '\n'; + os << q.x << " " << q.y << " " << q.z << " " << q.w << '\n'; } void Camera::deserialize(std::istream& is) { @@ -236,20 +236,20 @@ Camera::SgctInternal::SgctInternal(const SgctInternal& o) {} void Camera::SgctInternal::setSceneMatrix(glm::mat4 sceneMatrix) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _sceneMatrix = std::move(sceneMatrix); } void Camera::SgctInternal::setViewMatrix(glm::mat4 viewMatrix) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _viewMatrix = std::move(viewMatrix); _cachedViewProjectionMatrix.isDirty = true; } void Camera::SgctInternal::setProjectionMatrix(glm::mat4 projectionMatrix) { - std::lock_guard _lock(_mutex); + const std::lock_guard _lock(_mutex); _projectionMatrix = std::move(projectionMatrix); _cachedViewProjectionMatrix.isDirty = true; @@ -268,11 +268,9 @@ const glm::mat4& Camera::SgctInternal::projectionMatrix() const { } const glm::mat4& Camera::SgctInternal::viewProjectionMatrix() const { - //if (_cachedViewProjectionMatrix.isDirty) { - std::lock_guard _lock(_mutex); - _cachedViewProjectionMatrix.datum = _projectionMatrix * _viewMatrix; - _cachedViewProjectionMatrix.isDirty = false; - //} + const std::lock_guard _lock(_mutex); + _cachedViewProjectionMatrix.datum = _projectionMatrix * _viewMatrix; + _cachedViewProjectionMatrix.isDirty = false; return _cachedViewProjectionMatrix.datum; } diff --git a/src/data/csvloader.cpp b/src/data/csvloader.cpp index 9bf8f3cfbc..4fa73168d2 100644 --- a/src/data/csvloader.cpp +++ b/src/data/csvloader.cpp @@ -33,11 +33,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include namespace { @@ -50,7 +52,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s ghoul_assert(std::filesystem::exists(filePath), "File must exist"); auto readFloatData = [](const std::string& str) -> float { - float result; + float result = 0.f; #ifdef WIN32 auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), result); if (ec == std::errc() && std::isfinite(result)) { @@ -60,7 +62,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s #else // ^^^^ WIN32 // !WIN32 vvvv // clang is missing float support for std::from_chars try { - result = std::stof(str.c_str(), nullptr); + result = std::stof(str, nullptr); if (std::isfinite(result)) { return result; } @@ -78,8 +80,8 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s ); if (rows.size() < 2) { - LWARNING(fmt::format( - "Error loading data file {}. No data items read", filePath + LWARNING(std::format( + "Error loading data file '{}'. No data items read", filePath )); return Dataset(); } @@ -94,15 +96,16 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s int yColumn = -1; int zColumn = -1; int nameColumn = -1; + int textureColumn = -1; int nDataColumns = 0; - bool hasExcludeColumns = specs.has_value() && (*specs).hasExcludeColumns(); + const bool hasExcludeColumns = specs.has_value() && specs->hasExcludeColumns(); std::vector skipColumns; if (hasExcludeColumns) { skipColumns.reserve((*specs).excludeColumns.size()); } - for (size_t i = 0; i < columns.size(); ++i) { + for (size_t i = 0; i < columns.size(); i++) { const std::string& col = columns[i]; if (isPositionColumn(col, specs)) { @@ -119,11 +122,17 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s else if (isNameColumn(col, specs)) { nameColumn = static_cast(i); } - else if (hasExcludeColumns && (*specs).isExcludeColumn(col)) { + else if (hasExcludeColumns && specs->isExcludeColumn(col)) { skipColumns.push_back(i); continue; } else { + // Note that the texture column is also a regular column. Just save the index + if (isTextureColumn(col, specs)) { + res.textureDataIndex = nDataColumns; + textureColumn = static_cast(i); + } + res.variables.push_back({ .index = nDataColumns, .name = col @@ -132,18 +141,45 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s } } - if (xColumn < 0 || yColumn < 0 || zColumn < 0) { - // One or more position columns weren't read - LERROR(fmt::format( - "Error loading data file {}. Missing X, Y or Z position column", filePath + // Some errors / warnings + if (specs.has_value()) { + bool hasAllProvided = specs->checkIfAllProvidedColumnsExist(columns); + if (!hasAllProvided) { + LERROR(std::format( + "Error loading data file {}. Not all columns provided in data mapping " + "exists in dataset", filePath + )); + } + } + + bool hasProvidedTextureFile = specs.has_value() && specs->textureMap.has_value(); + bool hasTextureIndex = (res.textureDataIndex >= 0); + + if (hasProvidedTextureFile && !hasTextureIndex && !specs->textureColumn.has_value()) { + throw ghoul::RuntimeError(std::format( + "Error loading data file {}. No texture column was specified in the data " + "mapping", filePath + )); + } + if (!hasProvidedTextureFile && hasTextureIndex) { + throw ghoul::RuntimeError(std::format( + "Error loading data file {}. Missing texture map file location in data " + "mapping", filePath )); } - LINFO(fmt::format( - "Loading {} rows with {} columns", rows.size(), columns.size() - )); + if (xColumn < 0 || yColumn < 0 || zColumn < 0) { + // One or more position columns weren't read + LERROR(std::format( + "Error loading data file '{}'. Missing X, Y or Z position column", filePath + )); + } + + LINFO(std::format("Loading {} rows with {} columns", rows.size(), columns.size())); ProgressBar progress = ProgressBar(static_cast(rows.size())); + std::set uniqueTextureIndicesInData; + // Skip first row (column names) for (size_t rowIdx = 1; rowIdx < rows.size(); ++rowIdx) { const std::vector& row = rows[rowIdx]; @@ -151,7 +187,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s Dataset::Entry entry; entry.data.reserve(nDataColumns); - for (size_t i = 0; i < row.size(); ++i) { + for (size_t i = 0; i < row.size(); i++) { // Check if column should be exluded. Note that list of indices is sorted // so we can do a binary search if (hasExcludeColumns && @@ -163,7 +199,7 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s const std::string& strValue = row[i]; // For now, all values are converted to float - float value = readFloatData(strValue); + const float value = readFloatData(strValue); if (i == xColumn) { entry.position.x = value; @@ -182,10 +218,14 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s else { entry.data.push_back(value); } + + if (i == textureColumn) { + uniqueTextureIndicesInData.emplace(static_cast(value)); + } } - glm::vec3 positive = glm::abs(entry.position); - float max = glm::compMax(positive); + const glm::vec3 positive = glm::abs(entry.position); + const float max = glm::compMax(positive); if (max > res.maxPositionComponent) { res.maxPositionComponent = max; } @@ -195,6 +235,82 @@ Dataset loadCsvFile(std::filesystem::path filePath, std::optional s progress.print(static_cast(rowIdx + 1)); } + // Load the textures. Skip textures that are not included in the dataset + if (hasProvidedTextureFile) { + const std::filesystem::path path = *specs->textureMap; + if (!std::filesystem::is_regular_file(path)) { + throw ghoul::RuntimeError(std::format( + "Failed to open texture map file {}", path + )); + } + res.textures = loadTextureMapFile(path, uniqueTextureIndicesInData); + } + + return res; +} + +std::vector loadTextureMapFile(std::filesystem::path path, + const std::set& texturesInData) +{ + ghoul_assert(std::filesystem::exists(path), "File must exist"); + + std::ifstream file(path); + if (!file.good()) { + throw ghoul::RuntimeError(std::format( + "Failed to open texture map file {}", path + )); + } + + int currentLineNumber = 0; + + std::vector res; + + std::string line; + while (std::getline(file, line)) { + ghoul::trimWhitespace(line); + currentLineNumber++; + + if (line.empty() || line.starts_with("#")) { + continue; + } + + std::vector tokens = ghoul::tokenizeString(line, ' '); + int nNonEmptyTokens = static_cast(std::count_if( + tokens.begin(), + tokens.end(), + [](const std::string& t) { return !t.empty(); } + )); + + if (nNonEmptyTokens > 2) { + throw ghoul::RuntimeError(std::format( + "Error loading texture map file {}: Line {} has too many parameters. " + "Expected 2: an integer index followed by a filename, where the file " + "name may not include whitespaces", + path, currentLineNumber + )); + } + + std::stringstream str(line); + + // Each line is following the template: + // + Dataset::Texture texture; + str >> texture.index >> texture.file; + + for (const Dataset::Texture& t : res) { + if (t.index == texture.index) { + throw ghoul::RuntimeError(std::format( + "Error loading texture map file {}: Texture index '{}' defined twice", + path, texture.index + )); + } + } + + if (texturesInData.contains(texture.index)) { + res.push_back(texture); + } + } + return res; } diff --git a/src/data/dataloader.cpp b/src/data/dataloader.cpp index 7234aaa613..c1815e60e8 100644 --- a/src/data/dataloader.cpp +++ b/src/data/dataloader.cpp @@ -47,7 +47,7 @@ namespace { template void checkSize(U value, std::string_view message) { if (value > std::numeric_limits::max()) { - throw ghoul::RuntimeError(fmt::format("Error saving file: {}", message)); + throw ghoul::RuntimeError(std::format("Error saving file '{}'", message)); } } @@ -87,7 +87,7 @@ namespace { if (std::filesystem::exists(cached)) { LINFOC( "DataLoader", - fmt::format("Cached file {} used for file {}", cached, filePath) + std::format("Cached file {} used for file {}", cached, filePath) ); std::optional dataset = loadCacheFunction(cached); @@ -99,7 +99,7 @@ namespace { FileSys.cacheManager()->removeCacheFile(cached); } } - LINFOC("DataLoader", fmt::format("Loading file {}", filePath)); + LINFOC("DataLoader", std::format("Loading file '{}'", filePath)); T dataset = loadFunction(filePath, specs); if (!dataset.entries.empty()) { @@ -118,23 +118,23 @@ namespace data { Dataset loadFile(std::filesystem::path path, std::optional specs) { ghoul_assert(std::filesystem::exists(path), "File must exist"); - std::ifstream file(path); + const std::ifstream file = std::ifstream(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open data file {}", path)); + throw ghoul::RuntimeError(std::format("Failed to open data file '{}'", path)); } - std::string extension = ghoul::toLowerCase(path.extension().string()); + const std::string extension = ghoul::toLowerCase(path.extension().string()); Dataset res; if (extension == ".csv") { - res = csv::loadCsvFile(path, specs); + res = csv::loadCsvFile(path, std::move(specs)); } else if (extension == ".speck") { - res = speck::loadSpeckFile(path, specs); + res = speck::loadSpeckFile(path, std::move(specs)); } else { - LERRORC("DataLoader", fmt::format( - "Could not read data file {}. File format {} is not supported", + LERRORC("DataLoader", std::format( + "Could not read data file '{}'. File format '{}' is not supported", path, path.extension() )); } @@ -142,15 +142,15 @@ Dataset loadFile(std::filesystem::path path, std::optional specs) { return res; } -std::optional loadCachedFile(std::filesystem::path path) { - std::ifstream file(path, std::ios::binary); +std::optional loadCachedFile(const std::filesystem::path& path) { + std::ifstream file = std::ifstream(path, std::ios::binary); if (!file.good()) { return std::nullopt; } Dataset result; - int8_t fileVersion; + int8_t fileVersion = 0; file.read(reinterpret_cast(&fileVersion), sizeof(int8_t)); if (fileVersion != DataCacheFileVersion) { // Incompatible version and we won't be able to read the file @@ -159,17 +159,17 @@ std::optional loadCachedFile(std::filesystem::path path) { // // Read variables - uint16_t nVariables; + uint16_t nVariables = 0; file.read(reinterpret_cast(&nVariables), sizeof(uint16_t)); result.variables.resize(nVariables); for (int i = 0; i < nVariables; i += 1) { Dataset::Variable var; - int16_t idx; + int16_t idx = 0; file.read(reinterpret_cast(&idx), sizeof(int16_t)); var.index = idx; - uint16_t len; + uint16_t len = 0; file.read(reinterpret_cast(&len), sizeof(uint16_t)); var.name.resize(len); file.read(var.name.data(), len); @@ -179,17 +179,17 @@ std::optional loadCachedFile(std::filesystem::path path) { // // Read textures - uint16_t nTextures; + uint16_t nTextures = 0; file.read(reinterpret_cast(&nTextures), sizeof(uint16_t)); result.textures.resize(nTextures); for (int i = 0; i < nTextures; i += 1) { Dataset::Texture tex; - int16_t idx; + int16_t idx = 0; file.read(reinterpret_cast(&idx), sizeof(int16_t)); tex.index = idx; - uint16_t len; + uint16_t len = 0; file.read(reinterpret_cast(&len), sizeof(uint16_t)); tex.file.resize(len); file.read(tex.file.data(), len); @@ -199,17 +199,17 @@ std::optional loadCachedFile(std::filesystem::path path) { // // Read indices - int16_t texDataIdx; + int16_t texDataIdx = 0; file.read(reinterpret_cast(&texDataIdx), sizeof(int16_t)); result.textureDataIndex = texDataIdx; - int16_t oriDataIdx; + int16_t oriDataIdx = 0; file.read(reinterpret_cast(&oriDataIdx), sizeof(int16_t)); result.orientationDataIndex = oriDataIdx; // // Read entries - uint64_t nEntries; + uint64_t nEntries = 0; file.read(reinterpret_cast(&nEntries), sizeof(uint64_t)); result.entries.reserve(nEntries); for (uint64_t i = 0; i < nEntries; i += 1) { @@ -218,12 +218,12 @@ std::optional loadCachedFile(std::filesystem::path path) { file.read(reinterpret_cast(&e.position.y), sizeof(float)); file.read(reinterpret_cast(&e.position.z), sizeof(float)); - uint16_t nValues; + uint16_t nValues = 0; file.read(reinterpret_cast(&nValues), sizeof(uint16_t)); e.data.resize(nValues); file.read(reinterpret_cast(e.data.data()), nValues * sizeof(float)); - uint16_t len; + uint16_t len = 0; file.read(reinterpret_cast(&len), sizeof(uint16_t)); if (len > 0) { std::string comment; @@ -237,15 +237,15 @@ std::optional loadCachedFile(std::filesystem::path path) { // // Read max data point variable - float max; + float max = 0.f; file.read(reinterpret_cast(&max), sizeof(float)); result.maxPositionComponent = max; return result; } -void saveCachedFile(const Dataset& dataset, std::filesystem::path path) { - std::ofstream file(path, std::ofstream::binary); +void saveCachedFile(const Dataset& dataset, const std::filesystem::path& path) { + std::ofstream file = std::ofstream(path, std::ofstream::binary); file.write(reinterpret_cast(&DataCacheFileVersion), sizeof(int8_t)); @@ -330,12 +330,10 @@ void saveCachedFile(const Dataset& dataset, std::filesystem::path path) { ); } -Dataset loadFileWithCache(std::filesystem::path filePath, - std::optional specs) -{ +Dataset loadFileWithCache(std::filesystem::path path, std::optional specs) { return internalLoadFileWithCache( - filePath, - specs, + std::move(path), + std::move(specs), &loadFile, &loadCachedFile, &saveCachedFile @@ -349,20 +347,20 @@ namespace label { Labelset loadFile(std::filesystem::path path, std::optional) { ghoul_assert(std::filesystem::exists(path), "File must exist"); - std::ifstream file(path); + const std::ifstream file = std::ifstream(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open dataset file {}", path)); + throw ghoul::RuntimeError(std::format("Failed to open dataset file '{}'", path)); } - std::string extension = ghoul::toLowerCase(path.extension().string()); + const std::string extension = ghoul::toLowerCase(path.extension().string()); Labelset res; if (extension == ".label") { res = speck::loadLabelFile(path); } else { - LERRORC("DataLoader", fmt::format( - "Could not read label data file {}. File format {} is not supported", + LERRORC("DataLoader", std::format( + "Could not read label data file '{}'. File format '{}' is not supported", path, path.extension() )); } @@ -370,13 +368,13 @@ Labelset loadFile(std::filesystem::path path, std::optional) { return res; } -std::optional loadCachedFile(std::filesystem::path path) { +std::optional loadCachedFile(const std::filesystem::path& path) { std::ifstream file(path, std::ios::binary); if (!file.good()) { return std::nullopt; } - int8_t fileVersion; + int8_t fileVersion = 0; file.read(reinterpret_cast(&fileVersion), sizeof(int8_t)); if (fileVersion != LabelCacheFileVersion) { // Incompatible version and we won't be able to read the file @@ -385,11 +383,11 @@ std::optional loadCachedFile(std::filesystem::path path) { Labelset result; - int16_t textColorIdx; + int16_t textColorIdx = 0; file.read(reinterpret_cast(&textColorIdx), sizeof(int16_t)); result.textColorIndex = textColorIdx; - uint32_t nEntries; + uint32_t nEntries = 0; file.read(reinterpret_cast(&nEntries), sizeof(uint32_t)); result.entries.reserve(nEntries); for (unsigned int i = 0; i < nEntries; i += 1) { @@ -399,13 +397,13 @@ std::optional loadCachedFile(std::filesystem::path path) { file.read(reinterpret_cast(&e.position.z), sizeof(float)); // Identifier - uint8_t idLen; + uint8_t idLen = 0; file.read(reinterpret_cast(&idLen), sizeof(uint8_t)); e.identifier.resize(idLen); file.read(e.identifier.data(), idLen); // Text - uint16_t len; + uint16_t len = 0; file.read(reinterpret_cast(&len), sizeof(uint16_t)); e.text.resize(len); file.read(e.text.data(), len); @@ -416,8 +414,8 @@ std::optional loadCachedFile(std::filesystem::path path) { return result; } -void saveCachedFile(const Labelset& labelset, std::filesystem::path path) { - std::ofstream file(path, std::ofstream::binary); +void saveCachedFile(const Labelset& labelset, const std::filesystem::path& path) { + std::ofstream file = std::ofstream(path, std::ofstream::binary); file.write(reinterpret_cast(&LabelCacheFileVersion), sizeof(int8_t)); @@ -451,9 +449,9 @@ void saveCachedFile(const Labelset& labelset, std::filesystem::path path) { } } -Labelset loadFileWithCache(std::filesystem::path filePath) { +Labelset loadFileWithCache(std::filesystem::path path) { return internalLoadFileWithCache( - filePath, + std::move(path), std::nullopt, &loadFile, &loadCachedFile, @@ -471,7 +469,7 @@ Labelset loadFromDataset(const Dataset& dataset) { label.position = entry.position; label.text = entry.comment.value_or("MISSING LABEL"); // @TODO: make is possible to configure this identifier? - label.identifier = fmt::format("Point-{}", count); + label.identifier = std::format("Point-{}", count); res.entries.push_back(std::move(label)); } @@ -485,20 +483,20 @@ namespace color { ColorMap loadFile(std::filesystem::path path, std::optional) { ghoul_assert(std::filesystem::exists(path), "File must exist"); - std::ifstream file(path); + const std::ifstream file = std::ifstream(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open colormap file {}", path)); + throw ghoul::RuntimeError(std::format("Failed to open colormap file '{}'", path)); } - std::string extension = ghoul::toLowerCase(path.extension().string()); + const std::string extension = ghoul::toLowerCase(path.extension().string()); ColorMap res; if (extension == ".cmap") { res = speck::loadCmapFile(path); } else { - LERRORC("DataLoader", fmt::format( - "Could not read color map file {}. File format {} is not supported", + LERRORC("DataLoader", std::format( + "Could not read color map file '{}'. File format '{}' is not supported", path, path.extension() )); } @@ -506,13 +504,13 @@ ColorMap loadFile(std::filesystem::path path, std::optional) { return res; } -std::optional loadCachedFile(std::filesystem::path path) { +std::optional loadCachedFile(const std::filesystem::path& path) { std::ifstream file(path, std::ios::binary); if (!file.good()) { return std::nullopt; } - int8_t fileVersion; + int8_t fileVersion = 0; file.read(reinterpret_cast(&fileVersion), sizeof(int8_t)); if (fileVersion != ColorCacheFileVersion) { // Incompatible version and we won't be able to read the file @@ -521,7 +519,7 @@ std::optional loadCachedFile(std::filesystem::path path) { ColorMap result; - uint32_t nColors; + uint32_t nColors = 0; file.read(reinterpret_cast(&nColors), sizeof(uint32_t)); result.entries.reserve(nColors); for (unsigned int i = 0; i < nColors; i += 1) { @@ -571,8 +569,8 @@ std::optional loadCachedFile(std::filesystem::path path) { return result; } -void saveCachedFile(const ColorMap& colorMap, std::filesystem::path path) { - std::ofstream file(path, std::ofstream::binary); +void saveCachedFile(const ColorMap& colorMap, const std::filesystem::path& path) { + std::ofstream file = std::ofstream(path, std::ofstream::binary); file.write(reinterpret_cast(&ColorCacheFileVersion), sizeof(int8_t)); @@ -610,10 +608,9 @@ void saveCachedFile(const ColorMap& colorMap, std::filesystem::path path) { file.write(reinterpret_cast(&nanColor.w), sizeof(float)); } -ColorMap loadFileWithCache(std::filesystem::path path) -{ +ColorMap loadFileWithCache(std::filesystem::path path) { return internalLoadFileWithCache( - path, + std::move(path), std::nullopt, &loadFile, &loadCachedFile, @@ -637,7 +634,7 @@ int Dataset::index(std::string_view variableName) const { } bool Dataset::normalizeVariable(std::string_view variableName) { - int idx = index(variableName); + const int idx = index(variableName); if (idx == -1) { // We didn't find the variable that was specified @@ -647,7 +644,7 @@ bool Dataset::normalizeVariable(std::string_view variableName) { float minValue = std::numeric_limits::max(); float maxValue = -std::numeric_limits::max(); for (Dataset::Entry& e : entries) { - float value = e.data[idx]; + const float value = e.data[idx]; if (std::isnan(value)) { continue; } @@ -656,7 +653,7 @@ bool Dataset::normalizeVariable(std::string_view variableName) { } for (Dataset::Entry& e : entries) { - float value = e.data[idx]; + const float value = e.data[idx]; if (std::isnan(value)) { continue; } @@ -681,7 +678,7 @@ glm::vec2 Dataset::findValueRange(int variableIndex) const { float maxValue = -std::numeric_limits::max(); for (const Dataset::Entry& e : entries) { if (!e.data.empty()) { - float value = e.data[variableIndex]; + const float value = e.data[variableIndex]; if (std::isnan(value)) { continue; } @@ -698,7 +695,7 @@ glm::vec2 Dataset::findValueRange(int variableIndex) const { } glm::vec2 Dataset::findValueRange(std::string_view variableName) const { - int idx = index(variableName); + const int idx = index(variableName); if (idx == -1) { // We didn't find the variable that was specified diff --git a/src/data/datamapping.cpp b/src/data/datamapping.cpp index 24c60a1877..9907d49ba5 100644 --- a/src/data/datamapping.cpp +++ b/src/data/datamapping.cpp @@ -31,6 +31,8 @@ #include namespace { + constexpr std::string_view _loggerCat = "RenderablePolygonCloud"; + constexpr std::string_view DefaultX = "x"; constexpr std::string_view DefaultY = "y"; constexpr std::string_view DefaultZ = "z"; @@ -48,19 +50,19 @@ namespace { if (mapping.has_value()) { switch (columnCase) { case PositionColumn::X: - column = (*mapping).xColumnName.value_or(column); + column = mapping->xColumnName.value_or(column); break; case PositionColumn::Y: - column = (*mapping).yColumnName.value_or(column); + column = mapping->yColumnName.value_or(column); break; case PositionColumn::Z: - column = (*mapping).zColumnName.value_or(column); + column = mapping->zColumnName.value_or(column); break; } } // Per default, allow both lower case and upper case versions of column names - if (!mapping.has_value() || !(*mapping).isCaseSensitive) { + if (!mapping.has_value() || !mapping->isCaseSensitive) { column = ghoul::toLowerCase(column); testColumn = ghoul::toLowerCase(testColumn); } @@ -68,6 +70,27 @@ namespace { return testColumn == column; } + bool isSameStringColumn(const std::string& left, const std::string& right, + bool isCaseSensitive) + { + std::string l = isCaseSensitive ? ghoul::toLowerCase(left) : left; + std::string r = isCaseSensitive ? ghoul::toLowerCase(right) : right; + return (l == r); + } + + bool containsColumn(const std::string& c, const std::vector& columns, + bool isCaseSensitive) + { + auto it = std::find_if( + columns.begin(), + columns.end(), + [&c, &isCaseSensitive](const std::string& col) { + return isSameStringColumn(c, col, isCaseSensitive); + } + ); + return it != columns.end(); + } + // This is a data mapping structure that can be used when creating point cloud // datasets, e.g. from a CSV or Speck file. // @@ -92,6 +115,18 @@ namespace { // files, where the name is given by the comment at the end of each line std::optional name; + // Specifies a column name for a column that has the data for which texture to + // use for each point (given as an integer index). If included, a texture map + // file need to be included as well + std::optional textureColumn; + + // A file where each line contains an integer index and an image file name. + // Not valid for SPECK files, which includes this information as part of its + // data format. This map will be used to map the data in the TextureColumn to + // an image file to use for rendering the points. Note that only the files with + // indices that are used in the dataset will actually be loaded + std::optional textureMapFile; + // Specifies whether to do case sensitive checks when reading column names. // Default is not to, so that 'X' and 'x' are both valid column names for the // x position column, for example @@ -107,7 +142,7 @@ namespace { std::optional> excludeColumns; }; #include "datamapping_codegen.cpp" -} +} // namespace namespace openspace::dataloader { @@ -124,6 +159,8 @@ DataMapping DataMapping::createFromDictionary(const ghoul::Dictionary& dictionar result.yColumnName = p.y; result.zColumnName = p.z; result.nameColumn = p.name; + result.textureColumn = p.textureColumn; + result.textureMap = p.textureMapFile; result.missingDataValue = p.missingDataValue; @@ -142,21 +179,44 @@ bool DataMapping::isExcludeColumn(std::string_view column) const { return (found != excludeColumns.end()); } +bool DataMapping::checkIfAllProvidedColumnsExist( + const std::vector& columns) const +{ + auto checkColumnIsOk = [this, &columns](std::optional col, + std::string_view key) + { + if (col.has_value() && !containsColumn(*col, columns, isCaseSensitive)) { + LWARNING(std::format("Could not find provided {} column: '{}'", key, *col)); + return false; + } + return true; + }; + + bool hasAll = true; + hasAll &= checkColumnIsOk(xColumnName, "X"); + hasAll &= checkColumnIsOk(yColumnName, "Y"); + hasAll &= checkColumnIsOk(zColumnName, "Z"); + hasAll &= checkColumnIsOk(nameColumn, "Name"); + hasAll &= checkColumnIsOk(textureColumn, "Texture"); + return hasAll; +} + std::string generateHashString(const DataMapping& dm) { std::string a; - for (std::string_view c : dm.excludeColumns) { + for (const std::string_view c : dm.excludeColumns) { a += c; } unsigned int excludeColumnsHash = ghoul::hashCRC32(a); - return fmt::format( - "DM|x{}|y{}|z{}|name{}|m{}|{}|{}", + return std::format( + "DM|{}|{}|{}|{}|{}|{}|{}|{}", dm.xColumnName.value_or(""), dm.yColumnName.value_or(""), dm.zColumnName.value_or(""), dm.nameColumn.value_or(""), + dm.textureColumn.value_or(""), dm.missingDataValue.has_value() ? ghoul::to_string(*dm.missingDataValue) : "", - dm.isCaseSensitive ? "1" : "0", + dm.isCaseSensitive ? 1 : 0, excludeColumnsHash ); } @@ -181,14 +241,14 @@ bool isNameColumn(const std::string& c, const std::optional& mappin if (!mapping.has_value() || !mapping->nameColumn.has_value()) { return false; } + return isSameStringColumn(c, *mapping->nameColumn, mapping->isCaseSensitive); +} - std::string testColumn = c; - std::string mappedColumn = *mapping->nameColumn; - if (!mapping->isCaseSensitive) { - testColumn = ghoul::toLowerCase(testColumn); - mappedColumn = ghoul::toLowerCase(mappedColumn); +bool isTextureColumn(const std::string& c, const std::optional& mapping) { + if (!mapping.has_value() || !mapping->textureColumn.has_value()) { + return false; } - return testColumn == mappedColumn; + return isSameStringColumn(c, *mapping->textureColumn, mapping->isCaseSensitive); } } // namespace openspace::dataloader diff --git a/src/data/speckloader.cpp b/src/data/speckloader.cpp index dbe254135c..e4a8c2e1cd 100644 --- a/src/data/speckloader.cpp +++ b/src/data/speckloader.cpp @@ -76,7 +76,7 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe std::ifstream file(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open speck file {}", path)); + throw ghoul::RuntimeError(std::format("Failed to open speck file '{}'", path)); } Dataset res; @@ -129,8 +129,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // texturevar // where is the data value index where the texture index is stored if (res.textureDataIndex != -1) { - throw ghoul::RuntimeError(fmt::format( - "Error loading speck file {}: Texturevar defined twice", path + throw ghoul::RuntimeError(std::format( + "Error loading speck file '{}': Texturevar defined twice", path )); } @@ -148,8 +148,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // starts. There are 6 values stored in total, xyz + uvw if (res.orientationDataIndex != -1) { - throw ghoul::RuntimeError(fmt::format( - "Error loading speck file {}: Orientation index defined twice", path + throw ghoul::RuntimeError(std::format( + "Error loading speck file '{}': Orientation index defined twice", path )); } @@ -176,12 +176,27 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // 2: texture 1 M1.sgi // The parameter in #1 is currently being ignored + std::vector tokens = ghoul::tokenizeString(line, ' '); + int nNonEmptyTokens = static_cast(std::count_if( + tokens.begin(), + tokens.end(), + [](const std::string& t) { return !t.empty(); } + )); + + if (nNonEmptyTokens > 4) { + throw ghoul::RuntimeError(std::format( + "Error loading speck file {}: Too many arguments for texture on line {}", + path, currentLineNumber + )); + } + + bool hasExtraParameter = nNonEmptyTokens > 3; + std::stringstream str(line); std::string dummy; str >> dummy; - - if (line.find('-') != std::string::npos) { + if (hasExtraParameter) { str >> dummy; } @@ -190,8 +205,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe for (const Dataset::Texture& t : res.textures) { if (t.index == texture.index) { - throw ghoul::RuntimeError(fmt::format( - "Error loading speck file {}: Texture index '{}' defined twice", + throw ghoul::RuntimeError(std::format( + "Error loading speck file '{}': Texture index '{}' defined twice", path, texture.index )); } @@ -209,8 +224,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // If we get this far, we had an illegal header as it wasn't an empty line and // didn't start with either '#' denoting a comment line, and didn't start with // either the 'datavar', 'texturevar', 'polyorivar', or 'texture' keywords - throw ghoul::RuntimeError(fmt::format( - "Error in line {} while reading the header information of file {}. Line is " + throw ghoul::RuntimeError(std::format( + "Error in line {} while reading the header information of file '{}'. Line is " "neither a comment line, nor starts with one of the supported keywords for " "SPECK files", currentLineNumber, path @@ -258,8 +273,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // If the first character is a digit, we have left the preamble and are in the // data section of the file if (!std::isdigit(line[0]) && line[0] != '-') { - throw ghoul::RuntimeError(fmt::format( - "Error loading speck file {}: Header information and datasegment " + throw ghoul::RuntimeError(std::format( + "Error loading speck file '{}': Header information and datasegment " "intermixed", path )); } @@ -273,8 +288,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe str >> entry.position.x >> entry.position.y >> entry.position.z; allZero &= (entry.position == glm::vec3(0.0)); - glm::vec3 positive = glm::abs(entry.position); - float max = glm::compMax(positive); + const glm::vec3 positive = glm::abs(entry.position); + const float max = glm::compMax(positive); if (max > res.maxPositionComponent) { res.maxPositionComponent = max; } @@ -282,8 +297,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe if (!str.good()) { // Need to subtract one of the line number here as we increase the current // line count in the beginning of the while loop we are currently in - throw ghoul::RuntimeError(fmt::format( - "Error loading position information out of data line {} in file {}. " + throw ghoul::RuntimeError(std::format( + "Error loading position information out of data line {} in file '{}'. " "Value was not a number", currentLineNumber - 1, path )); @@ -304,8 +319,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // Check if value corresponds to a missing value if (specs.has_value() && specs->missingDataValue.has_value()) { - float missingDataValue = specs->missingDataValue.value(); - float diff = std::abs(entry.data[i] - missingDataValue); + const float missingDataValue = specs->missingDataValue.value(); + const float diff = std::abs(entry.data[i] - missingDataValue); if (diff < std::numeric_limits::epsilon()) { entry.data[i] = std::numeric_limits::quiet_NaN(); } @@ -316,8 +331,8 @@ Dataset loadSpeckFile(std::filesystem::path path, std::optional spe // Need to subtract one of the line number here as we increase the // current line count in the beginning of the while loop we are // currently in - throw ghoul::RuntimeError(fmt::format( - "Error loading data value {} out of data line {} in file {}. " + throw ghoul::RuntimeError(std::format( + "Error loading data value {} out of data line {} in file '{}'. " "Value was not a number", i, currentLineNumber - 1, path )); @@ -361,7 +376,7 @@ Labelset loadLabelFile(std::filesystem::path path) { std::ifstream file(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open dataset file {}", path)); + throw ghoul::RuntimeError(std::format("Failed to open dataset file '{}'", path)); } Labelset res; @@ -395,8 +410,8 @@ Labelset loadLabelFile(std::filesystem::path path) { // really sure how these configuration files work, but they don't seem to be // included in the speck file) if (res.textColorIndex != -1) { - throw ghoul::RuntimeError(fmt::format( - "Error loading label file {}: Textcolor defined twice", path + throw ghoul::RuntimeError(std::format( + "Error loading label file '{}': Textcolor defined twice", path )); } @@ -433,8 +448,8 @@ Labelset loadLabelFile(std::filesystem::path path) { // If the first character is a digit, we have left the preamble and are in the // data section of the file if (!std::isdigit(line[0]) && line[0] != '-') { - throw ghoul::RuntimeError(fmt::format( - "Error loading label file {}: Header information and datasegment " + throw ghoul::RuntimeError(std::format( + "Error loading label file '{}': Header information and datasegment " "intermixed", path )); } @@ -455,15 +470,15 @@ Labelset loadLabelFile(std::filesystem::path path) { // optional arument with identifier // Remove the 'id' text rest = rest.substr(std::string_view("id ").size()); - size_t index = rest.find("text"); + const size_t index = rest.find("text"); entry.identifier = rest.substr(0, index - 1); // update the rest, remove the identifier rest = rest.substr(index); } if (!startsWith(rest, "text")) { - throw ghoul::RuntimeError(fmt::format( - "Error loading label file {}: File contains an unsupported value " + throw ghoul::RuntimeError(std::format( + "Error loading label file '{}': File contains an unsupported value " "between positions and text label", path )); } @@ -493,9 +508,11 @@ Labelset loadLabelFile(std::filesystem::path path) { ColorMap loadCmapFile(std::filesystem::path path) { ghoul_assert(std::filesystem::exists(path), "File must exist"); - std::ifstream file(path); + std::ifstream file = std::ifstream(path); if (!file.good()) { - throw ghoul::RuntimeError(fmt::format("Failed to open color map file {}", path)); + throw ghoul::RuntimeError(std::format( + "Failed to open color map file '{}'", path + )); } ColorMap res; @@ -558,7 +575,7 @@ ColorMap loadCmapFile(std::filesystem::path path) { res.entries.shrink_to_fit(); if (nColorLines != static_cast(res.entries.size())) { - LWARNINGC("SpeckLoader", fmt::format( + LWARNINGC("SpeckLoader", std::format( "While loading color map '{}', the expected number of color values '{}' was " "different from the actual number of color values '{}'", path, nColorLines, res.entries.size() diff --git a/src/documentation/documentation.cpp b/src/documentation/documentation.cpp index 0c43cc0128..a7820bc02f 100644 --- a/src/documentation/documentation.cpp +++ b/src/documentation/documentation.cpp @@ -74,15 +74,15 @@ std::string to_string(const openspace::documentation::TestResult& value) { stream << "Specification Failure. "; for (const TestResult::Offense& offense : value.offenses) { - stream << fmt::format(" {}", ghoul::to_string(offense)); + stream << std::format(" {}", ghoul::to_string(offense)); if (!offense.explanation.empty()) { - stream << fmt::format(" ({})", offense.explanation); + stream << std::format(" ({})", offense.explanation); } stream << '\n'; } for (const TestResult::Warning& warning : value.warnings) { - stream << fmt::format(" {}\n", ghoul::to_string(warning)); + stream << std::format(" {}\n", ghoul::to_string(warning)); } return stream.str(); @@ -95,7 +95,7 @@ std::string to_string(const openspace::documentation::TestResult::Offense& value stream << value.offender + ": " + ghoul::to_string(value.reason); if (!value.explanation.empty()) { - stream << fmt::format(" ({})", value.explanation); + stream << std::format(" ({})", value.explanation); } return stream.str(); @@ -159,16 +159,21 @@ void logError(const SpecificationError& error, std::string component) { LERRORC(error.component, error.message); } else { - LERRORC(fmt::format("{}: {}", component, error.component), error.message); + LERRORC(std::format("{}: {}", component, error.component), error.message); } for (const documentation::TestResult::Offense& o : error.result.offenses) { - LERRORC( - o.offender, - fmt::format("{}: {}", ghoul::to_string(o.reason), o.explanation) - ); + if (o.explanation.empty()) { + LERRORC(ghoul::to_string(o.reason), o.offender); + } + else { + LERRORC( + ghoul::to_string(o.reason), + std::format("{}: {}", o.offender, o.explanation) + ); + } } for (const documentation::TestResult::Warning& w : error.result.warnings) { - LWARNINGC(w.offender, ghoul::to_string(w.reason)); + LWARNINGC(ghoul::to_string(w.reason), w.offender); } } @@ -216,7 +221,7 @@ TestResult testSpecification(const Documentation& documentation, for (const auto& p : documentation.entries) { if (p.key == DocumentationEntry::Wildcard) { - for (std::string_view key : dictionary.keys()) { + for (const std::string_view key : dictionary.keys()) { applyVerifier(*(p.verifier), std::string(key)); } } @@ -232,14 +237,14 @@ TestResult testSpecification(const Documentation& documentation, // Remove duplicate offenders that might occur if multiple rules apply to a single // key and more than one of these rules are broken - std::set uniqueOffenders( + const std::set uniqueOffenders( result.offenses.begin(), result.offenses.end() ); result.offenses = std::vector( uniqueOffenders.begin(), uniqueOffenders.end() ); // Remove duplicate warnings. This should normally not happen, but we want to be sure - std::set uniqueWarnings( + const std::set uniqueWarnings( result.warnings.begin(), result.warnings.end() ); result.warnings = std::vector( @@ -253,9 +258,9 @@ void testSpecificationAndThrow(const Documentation& documentation, const ghoul::Dictionary& dictionary, std::string component) { // Perform testing against the documentation/specification - TestResult testResult = testSpecification(documentation, dictionary); + const TestResult testResult = testSpecification(documentation, dictionary); if (!testResult.success) { - throw SpecificationError(testResult, component); + throw SpecificationError(testResult, std::move(component)); } } diff --git a/src/documentation/documentationengine.cpp b/src/documentation/documentationengine.cpp index d3d769daa9..772f30c061 100644 --- a/src/documentation/documentationengine.cpp +++ b/src/documentation/documentationengine.cpp @@ -263,7 +263,7 @@ DocumentationEngine* DocumentationEngine::_instance = nullptr; DocumentationEngine::DuplicateDocumentationException::DuplicateDocumentationException( Documentation doc) - : ghoul::RuntimeError(fmt::format( + : ghoul::RuntimeError(std::format( "Duplicate Documentation with name '{}' and id '{}'", doc.name, doc.id )) , documentation(std::move(doc)) @@ -451,7 +451,7 @@ nlohmann::json DocumentationEngine::generateEventJson() const { actionJson[NameKey] = eventJson[NameKey]; actionJson[ActionKey] = action.action; // Create a unique ID - actionJson[IdKey] = fmt::format("{}{}", action.action, action.id); + actionJson[IdKey] = std::format("{}{}", action.action, action.id); // Output filters as a string if (action.filter.has_value()) { @@ -462,7 +462,7 @@ nlohmann::json DocumentationEngine::generateEventJson() const { std::string filtersString = ""; for (std::string_view key : keys) { std::string value = filters.value(key); - filtersString += fmt::format("{} = {}, ", key, value); + filtersString += std::format("{} = {}, ", key, value); } filtersString.pop_back(); // Remove last space from last entry filtersString.pop_back(); // Remove last comma from last entry diff --git a/src/documentation/verifier.cpp b/src/documentation/verifier.cpp index 671628954b..f221454833 100644 --- a/src/documentation/verifier.cpp +++ b/src/documentation/verifier.cpp @@ -138,9 +138,9 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict, if (dict.hasKey(key)) { if (dict.hasValue(key)) { // If we have a double value, we need to check if it is integer - double value = dict.value(key); - double intPart; - bool isInt = modf(value, &intPart) == 0.0; + const double value = dict.value(key); + double intPart = 0.0; + const bool isInt = modf(value, &intPart) == 0.0; if (isInt) { TestResult res; res.success = true; @@ -149,10 +149,11 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict, else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -160,20 +161,22 @@ TestResult IntVerifier::operator()(const ghoul::Dictionary& dict, // If we don't have a double value, we cannot have an int value TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::MissingKey; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::MissingKey + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -195,12 +198,15 @@ TestResult StringVerifier::operator()(const ghoul::Dictionary& dictionary, return res; } - std::string value = dictionary.value(key); + const std::string value = dictionary.value(key); if (value.empty() && _mustBeNotEmpty) { res.success = false; - res.offenses.push_back({ - key, TestResult::Offense::Reason::Verification, "value must not be empty" - }); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification, + .explanation = "value must not be empty" + }; + res.offenses.push_back(std::move(o)); } return res; } @@ -223,15 +229,16 @@ TestResult IdentifierVerifier::operator()(const ghoul::Dictionary& dict, return res; } - std::string identifier = dict.value(key); - size_t pos = identifier.find_first_of(" \t\n\r."); + const std::string identifier = dict.value(key); + const size_t pos = identifier.find_first_of(" \t\n\r."); if (pos != std::string::npos) { res.success = false; - TestResult::Offense off; - off.offender = key; - off.reason = TestResult::Offense::Reason::Verification; - off.explanation = "Identifier contained illegal character"; - res.offenses.push_back(off); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification, + .explanation = "Identifier contained illegal character" + }; + res.offenses.push_back(std::move(o)); } return res; } @@ -254,14 +261,15 @@ TestResult FileVerifier::operator()(const ghoul::Dictionary& dict, return res; } - std::string file = dict.value(key); + const std::string file = dict.value(key); if (!std::filesystem::exists(file) || !std::filesystem::is_regular_file(file)) { res.success = false; - TestResult::Offense off; - off.offender = key; - off.reason = TestResult::Offense::Reason::Verification; - off.explanation = "File did not exist"; - res.offenses.push_back(off); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification, + .explanation = "File did not exist" + }; + res.offenses.push_back(std::move(o)); } return res; } @@ -280,14 +288,15 @@ TestResult DirectoryVerifier::operator()(const ghoul::Dictionary& dict, return res; } - std::string dir = dict.value(key); + const std::string dir = dict.value(key); if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) { res.success = false; - TestResult::Offense off; - off.offender = key; - off.reason = TestResult::Offense::Reason::Verification; - off.explanation = "Directory did not exist"; - res.offenses.push_back(off); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification, + .explanation = "Directory did not exist" + }; + res.offenses.push_back(std::move(o)); } return res; } @@ -306,8 +315,8 @@ TestResult DateTimeVerifier::operator()(const ghoul::Dictionary& dict, return res; } - std::string dateTime = dict.value(key); - std::string format = "%Y %m %d %H:%M:%S"; // YYYY MM DD hh:mm:ss + const std::string dateTime = dict.value(key); + const std::string format = "%Y %m %d %H:%M:%S"; // YYYY MM DD hh:mm:ss std::tm t = {}; std::istringstream ss(dateTime); @@ -316,11 +325,12 @@ TestResult DateTimeVerifier::operator()(const ghoul::Dictionary& dict, // first check format (automatically checks if valid time) if (ss.fail()) { res.success = false; - TestResult::Offense off; - off.offender = key; - off.reason = TestResult::Offense::Reason::Verification; - off.explanation = "Not a valid format, should be: YYYY MM DD hh:mm:ss"; - res.offenses.push_back(off); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification, + .explanation = "Not a valid format, should be: YYYY MM DD hh:mm:ss" + }; + res.offenses.push_back(std::move(o)); } return res; } @@ -337,36 +347,39 @@ TestResult Color3Verifier::operator()(const ghoul::Dictionary& dictionary, return res; } - glm::dvec3 values = dictionary.value(key); + const glm::dvec3 values = dictionary.value(key); if (values.x < 0.0 || values.x > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".x"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".x", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } if (values.y < 0.0 || values.y > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".y"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".y", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } if (values.z < 0.0 || values.z > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".z"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".z", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } return res; } std::string Color3Verifier::type() const { - return std::string("Color3"); + return "Color3"; } TestResult Color4Verifier::operator()(const ghoul::Dictionary& dictionary, @@ -377,44 +390,48 @@ TestResult Color4Verifier::operator()(const ghoul::Dictionary& dictionary, return res; } - glm::dvec4 values = dictionary.value(key); + const glm::dvec4 values = dictionary.value(key); if (values.x < 0.0 || values.x > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".x"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".x", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } if (values.y < 0.0 || values.y > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".y"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".y", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } if (values.z < 0.0 || values.z > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".z"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".z", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } if (values.w < 0.0 || values.w > 1.0) { res.success = false; - TestResult::Offense o; - o.offender = key + ".a"; - o.reason = TestResult::Offense::Reason::Verification; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key + ".a", + .reason = TestResult::Offense::Reason::Verification + }; + res.offenses.push_back(std::move(o)); } return res; } std::string Color4Verifier::type() const { - return std::string("Color4"); + return "Color4"; } template <> @@ -429,9 +446,9 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dic else { if (dict.hasKey(key)) { if (dict.hasValue(key)) { - glm::dvec2 value = dict.value(key); + const glm::dvec2 value = dict.value(key); glm::dvec2 intPart; - glm::bvec2 isInt = glm::bvec2( + const glm::bvec2 isInt = glm::bvec2( modf(value.x, &intPart.x) == 0.0, modf(value.y, &intPart.y) == 0.0 ); @@ -443,30 +460,33 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dic else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::MissingKey; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::MissingKey + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -484,9 +504,9 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dic else { if (dict.hasKey(key)) { if (dict.hasValue(key)) { - glm::dvec3 value = dict.value(key); + const glm::dvec3 value = dict.value(key); glm::dvec3 intPart; - glm::bvec3 isInt = glm::bvec3( + const glm::bvec3 isInt = glm::bvec3( modf(value.x, &intPart.x) == 0.0, modf(value.y, &intPart.y) == 0.0, modf(value.z, &intPart.z) == 0.0 @@ -499,30 +519,33 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dic else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::MissingKey; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::MissingKey + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -540,46 +563,50 @@ TestResult TemplateVerifier::operator()(const ghoul::Dictionary& dic else { if (dict.hasKey(key)) { if (dict.hasValue(key)) { - glm::dvec4 value = dict.value(key); + const glm::dvec4 value = dict.value(key); glm::dvec4 intPart; - glm::bvec4 isInt = glm::bvec4( + const glm::bvec4 isInt = glm::bvec4( modf(value.x, &intPart.x) == 0.0, modf(value.y, &intPart.y) == 0.0, modf(value.z, &intPart.z) == 0.0, modf(value.w, &intPart.w) == 0.0 ); if (isInt.x && isInt.y && isInt.z && isInt.w) { - TestResult res; - res.success = true; + TestResult res = { + .success = true + }; return res; } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::MissingKey; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::MissingKey + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -593,18 +620,18 @@ TestResult TableVerifier::operator()(const ghoul::Dictionary& dictionary, const std::string& key) const { if (dictionary.hasValue(key)) { - ghoul::Dictionary d = dictionary.value(key); - Documentation doc = { .entries = documentations }; + const ghoul::Dictionary d = dictionary.value(key); + const Documentation doc = { .entries = documentations }; TestResult res = testSpecification(doc, d); // Add the 'key' as a prefix to make the new offender a fully qualified identifer for (TestResult::Offense& s : res.offenses) { - s.offender = fmt::format("{}.{}", key, s.offender); + s.offender = std::format("{}.{}", key, s.offender); } // Add the 'key' as a prefix to make the new warning a fully qualified identifer for (TestResult::Warning& w : res.warnings) { - w.offender = fmt::format("{}.{}", key, w.offender); + w.offender = std::format("{}.{}", key, w.offender); } return res; @@ -613,19 +640,21 @@ TestResult TableVerifier::operator()(const ghoul::Dictionary& dictionary, if (dictionary.hasKey(key)) { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::WrongType; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::WrongType + }; + res.offenses.push_back(std::move(o)); return res; } else { TestResult res; res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::MissingKey; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::MissingKey + }; + res.offenses.push_back(std::move(o)); return res; } } @@ -676,24 +705,25 @@ TestResult ReferencingVerifier::operator()(const ghoul::Dictionary& dictionary, if (it == docs.end()) { res.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::UnknownIdentifier; - res.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::UnknownIdentifier + }; + res.offenses.push_back(std::move(o)); return res; } - ghoul::Dictionary d = dictionary.value(key); + const ghoul::Dictionary d = dictionary.value(key); TestResult r = testSpecification(*it, d); // Add the 'key' as a prefix to make the offender a fully qualified identifer for (TestResult::Offense& s : r.offenses) { - s.offender = fmt::format("{}.{}", key, s.offender); + s.offender = std::format("{}.{}", key, s.offender); } // Add the 'key' as a prefix to make the warning a fully qualified identifer for (TestResult::Warning& w : r.warnings) { - w.offender = fmt::format("{}.{}", key, w.offender); + w.offender = std::format("{}.{}", key, w.offender); } return r; @@ -708,7 +738,7 @@ std::string ReferencingVerifier::documentation() const { } OrVerifier::OrVerifier( - const std::vector>> values_) + const std::vector>>& values_) { ghoul_assert(!values_.empty(), "values must not be empty"); for (const std::variant>& v : values_) { @@ -741,17 +771,19 @@ TestResult OrVerifier::operator()(const ghoul::Dictionary& dictionary, ); if (success) { - TestResult r; - r.success = true; + TestResult r = { + .success = true + }; return r; } else { TestResult r; r.success = false; - TestResult::Offense o; - o.offender = key; - o.reason = TestResult::Offense::Reason::Verification; - r.offenses.push_back(o); + TestResult::Offense o = { + .offender = key, + .reason = TestResult::Offense::Reason::Verification + }; + r.offenses.push_back(std::move(o)); return r; } } @@ -765,7 +797,7 @@ std::string OrVerifier::type() const { types.begin(), std::mem_fn(&Verifier::type) ); - types.push_back(fmt::format("or {}", values.back()->type())); + types.push_back(std::format("or {}", values.back()->type())); return ghoul::join(types, ", "); } @@ -779,7 +811,7 @@ std::string OrVerifier::documentation() const { documentations.begin(), std::mem_fn(&Verifier::documentation) ); - documentations.push_back(fmt::format("or {}", values.back()->documentation())); + documentations.push_back(std::format("or {}", values.back()->documentation())); return ghoul::join(documentations, ", "); } diff --git a/src/engine/configuration.cpp b/src/engine/configuration.cpp index b646709333..7f6f1dd0a9 100644 --- a/src/engine/configuration.cpp +++ b/src/engine/configuration.cpp @@ -331,7 +331,7 @@ ghoul::Dictionary Configuration::createDictionary() { res.setValue("PropertyVisibility", static_cast(propertyVisibility)); ghoul::Dictionary globalCustomizationScriptsDict; - for (size_t i = 0; i < globalCustomizationScripts.size(); ++i) { + for (size_t i = 0; i < globalCustomizationScripts.size(); i++) { globalCustomizationScriptsDict.setValue( std::to_string(i), globalCustomizationScripts[i] @@ -340,8 +340,8 @@ ghoul::Dictionary Configuration::createDictionary() { res.setValue("GlobalCustomizationScripts", globalCustomizationScriptsDict); ghoul::Dictionary fontsDict; - for (auto it = fonts.begin(); it != fonts.end(); ++it) { - fontsDict.setValue(it->first, it->second); + for (const auto& [name, path] : fonts) { + fontsDict.setValue(name, path); } res.setValue("Fonts", fontsDict); @@ -363,7 +363,7 @@ ghoul::Dictionary Configuration::createDictionary() { loggingDict.setValue("CapabilitiesVerbosity", logging.capabilitiesVerbosity); ghoul::Dictionary logsDict; - for (size_t i = 0; i < logging.logs.size(); ++i) { + for (size_t i = 0; i < logging.logs.size(); i++) { logsDict.setValue(std::to_string(i), logging.logs[i]); } loggingDict.setValue("Logs", logsDict); @@ -387,7 +387,10 @@ ghoul::Dictionary Configuration::createDictionary() { { ghoul::Dictionary loadingScreenDict; loadingScreenDict.setValue("IsShowingMessages", loadingScreen.isShowingMessages); - loadingScreenDict.setValue("IsShowingNodeNames", loadingScreen.isShowingNodeNames); + loadingScreenDict.setValue( + "IsShowingNodeNames", + loadingScreen.isShowingNodeNames + ); loadingScreenDict.setValue( "IsShowingLogMessages", loadingScreen.isShowingLogMessages @@ -413,8 +416,8 @@ ghoul::Dictionary Configuration::createDictionary() { res.setValue("LayerServer", layerServerToString(layerServer)); ghoul::Dictionary moduleConfigurationsDict; - for (auto it = moduleConfigurations.begin(); it != moduleConfigurations.end(); ++it) { - moduleConfigurationsDict.setValue(it->first, it->second); + for (const auto& [key, value] : moduleConfigurations) { + moduleConfigurationsDict.setValue(key, value); } res.setValue("ModuleConfigurations", moduleConfigurationsDict); @@ -431,7 +434,7 @@ ghoul::Dictionary Configuration::createDictionary() { ); ghoul::Dictionary identifierFiltersDict; - for (size_t i = 0; i < openGLDebugContext.severityFilters.size(); ++i) { + for (size_t i = 0; i < openGLDebugContext.severityFilters.size(); i++) { { ghoul::Dictionary identifierFilterDict; identifierFilterDict.setValue( @@ -447,13 +450,13 @@ ghoul::Dictionary Configuration::createDictionary() { static_cast(openGLDebugContext.identifierFilters[i].identifier) ); - openGLDebugContextDict.setValue(std::to_string(i), identifierFilterDict); + identifierFiltersDict.setValue(std::to_string(i), identifierFilterDict); } } openGLDebugContextDict.setValue("IdentifierFilters", identifierFiltersDict); ghoul::Dictionary severityFiltersDict; - for (size_t i = 0; i < openGLDebugContext.severityFilters.size(); ++i) { + for (size_t i = 0; i < openGLDebugContext.severityFilters.size(); i++) { severityFiltersDict.setValue( std::to_string(i), openGLDebugContext.severityFilters[i] @@ -486,7 +489,7 @@ void parseLuaState(Configuration& configuration) { // Shorten the rest of this function Configuration& c = configuration; - LuaState& s = c.state; + const LuaState& s = c.state; // The sgctConfigNameInitialized is a bit special lua_getglobal(s, "sgctconfiginitializeString"); @@ -503,7 +506,9 @@ void parseLuaState(Configuration& configuration) { // We go through all of the entries and lift them from global scope into the table on // the stack so that we can create a ghoul::Dictionary from this new table - documentation::Documentation doc = codegen::doc("core_configuration"); + const documentation::Documentation doc = codegen::doc( + "core_configuration" + ); for (const documentation::DocumentationEntry& e : doc.entries) { lua_pushstring(s, e.key.c_str()); lua_getglobal(s, e.key.c_str()); @@ -544,9 +549,9 @@ void parseLuaState(Configuration& configuration) { c.isPrintingEvents = p.printEvents.value_or(c.isPrintingEvents); if (p.consoleKey.has_value()) { - KeyWithModifier km = stringToKey(*p.consoleKey); + const KeyWithModifier km = stringToKey(*p.consoleKey); if (km.modifier != KeyModifier::None) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Console key '{}' must be a 'bare' key and cannot contain any modifiers", *p.consoleKey )); @@ -680,12 +685,12 @@ std::filesystem::path findConfiguration(const std::string& filename) { } // Otherwise, we traverse the directory tree up - std::filesystem::path nextDirectory = directory.parent_path(); + const std::filesystem::path nextDirectory = directory.parent_path(); if (directory == nextDirectory) { // We have reached the root of the file system and did not find the file throw ghoul::RuntimeError( - fmt::format("Could not find configuration file '{}'", filename), + std::format("Could not find configuration file '{}'", filename), "ConfigurationManager" ); } @@ -702,7 +707,7 @@ Configuration loadConfigurationFromFile(const std::filesystem::path& configurati Configuration result; // Injecting the resolution of the primary screen into the Lua state - std::string script = fmt::format( + const std::string script = std::format( "ScreenResolution = {{ x = {}, y = {} }}", primaryMonitorResolution.x, primaryMonitorResolution.y ); @@ -719,7 +724,7 @@ Configuration loadConfigurationFromFile(const std::filesystem::path& configurati parseLuaState(result); if (std::filesystem::is_regular_file(settingsFile)) { - Settings settings = loadSettings(settingsFile); + const Settings settings = loadSettings(settingsFile); patchConfiguration(result, settings); } diff --git a/src/engine/downloadmanager.cpp b/src/engine/downloadmanager.cpp index 199688c40f..c3768943ec 100644 --- a/src/engine/downloadmanager.cpp +++ b/src/engine/downloadmanager.cpp @@ -46,13 +46,13 @@ namespace { }; size_t writeData(void* ptr, size_t size, size_t nmemb, FILE* stream) { - size_t written = fwrite(ptr, size, nmemb, stream); + const 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 realsize = size * nmemb; - auto mem = static_cast(userp); + const size_t realsize = size * nmemb; + auto* mem = static_cast(userp); // @TODO(abock): Remove this and replace mem->buffer with std::vector mem->buffer = reinterpret_cast( @@ -128,7 +128,7 @@ std::shared_ptr DownloadManager::downloadFile( FailOnError failOnError, unsigned int timeout_secs, DownloadFinishedCallback finishedCallback, - DownloadProgressCallback progressCallback) + DownloadProgressCallback progressCallback) const { if (!overrideFile && std::filesystem::is_regular_file(file)) { return nullptr; @@ -140,7 +140,7 @@ std::shared_ptr DownloadManager::downloadFile( FILE* fp; errno_t error = fopen_s(&fp, file.string().c_str(), "wb"); if (error != 0) { - LERROR(fmt::format( + LERROR(std::format( "Could not open/create file: {}. Errno: {}", file, errno )); } @@ -148,7 +148,7 @@ std::shared_ptr DownloadManager::downloadFile( FILE* fp = fopen(file.string().c_str(), "wb"); // write binary #endif // WIN32 if (!fp) { - LERROR(fmt::format( + LERROR(std::format( "Could not open/create file: {}. Errno: {}", file, errno )); } @@ -184,7 +184,7 @@ std::shared_ptr DownloadManager::downloadFile( #endif curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); - CURLcode res = curl_easy_perform(curl); + const CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); fclose(fp); @@ -192,9 +192,9 @@ std::shared_ptr DownloadManager::downloadFile( future->isFinished = true; } else { - long rescode; + long rescode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &rescode); - future->errorMessage = fmt::format( + future->errorMessage = std::format( "{}. HTTP code: {}", curl_easy_strerror(res), rescode ); } @@ -227,7 +227,7 @@ std::future DownloadManager::fetchFile( SuccessCallback successCallback, ErrorCallback errorCallback) { - LDEBUG(fmt::format("Start downloading file: '{}' into memory", url)); + LDEBUG(std::format("Start downloading file '{}' into memory", url)); auto downloadFunction = [url, successCb = std::move(successCallback), errorCb = std::move(errorCallback)]() @@ -256,7 +256,7 @@ std::future DownloadManager::fetchFile( CURLcode res = curl_easy_perform(curl); if (res == CURLE_OK) { // ask for the content-type - char* ct; + char* ct = nullptr; res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); if (res == CURLE_OK) { std::string extension = std::string(ct); @@ -278,7 +278,7 @@ std::future DownloadManager::fetchFile( errorCb(err); } else { - LWARNING(fmt::format("Error downloading '{}': {}", url, err)); + LWARNING(std::format("Error downloading '{}': {}", url, err)); } curl_easy_cleanup(curl); // Set a boolean variable in MemoryFile to determine if it is @@ -293,8 +293,8 @@ std::future DownloadManager::fetchFile( return std::async(std::launch::async, downloadFunction); } -void DownloadManager::getFileExtension(const std::string& url, - RequestFinishedCallback finishedCallback) +void DownloadManager::fileExtension(const std::string& url, + RequestFinishedCallback finishedCallback) const { auto requestFunction = [url, finishedCb = std::move(finishedCallback)]() { CURL* curl = curl_easy_init(); @@ -304,7 +304,7 @@ void DownloadManager::getFileExtension(const std::string& url, curl_easy_setopt(curl, CURLOPT_NOBODY, 1); CURLcode res = curl_easy_perform(curl); if (CURLE_OK == res) { - char* ct; + char* ct = nullptr; // ask for the content-type res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct); if ((res == CURLE_OK) && ct && finishedCb) { diff --git a/src/engine/logfactory.cpp b/src/engine/logfactory.cpp index cb163c1456..c0f0020bbb 100644 --- a/src/engine/logfactory.cpp +++ b/src/engine/logfactory.cpp @@ -98,25 +98,25 @@ documentation::Documentation LogFactoryDocumentation() { std::unique_ptr createLog(const ghoul::Dictionary& dictionary) { const Parameters p = codegen::bake(dictionary); - std::filesystem::path filename = absPath(p.file); - bool append = p.append.value_or(true); - int nLogRotation = p.logRotation.value_or(0); - bool timeStamp = p.timeStamping.value_or(true); - bool dateStamp = p.dateStamping.value_or(true); - bool categoryStamp = p.categoryStamping.value_or(true); - bool logLevelStamp = p.logLevelStamping.value_or(true); - ghoul::logging::LogLevel level = codegen::map( + const std::filesystem::path filename = absPath(p.file); + const bool append = p.append.value_or(true); + const int nLogRotation = p.logRotation.value_or(0); + const bool timeStamp = p.timeStamping.value_or(true); + const bool dateStamp = p.dateStamping.value_or(true); + const bool categoryStamp = p.categoryStamping.value_or(true); + const bool logLevelStamp = p.logLevelStamping.value_or(true); + const ghoul::logging::LogLevel level = codegen::map( p.logLevel.value_or(Parameters::LogLevel::AllLogging) ); switch (p.type) { case Parameters::Type::Html: { - std::vector cssFiles{ + const std::vector cssFiles = { absPath(BootstrapPath).string(), absPath(CssPath).string() }; - std::vector jsFiles{ absPath(JsPath).string() }; + const std::vector jsFiles = { absPath(JsPath).string() }; return std::make_unique( filename.string(), @@ -142,7 +142,7 @@ std::unique_ptr createLog(const ghoul::Dictionary& dictiona level ); default: - throw new ghoul::MissingCaseException(); + throw ghoul::MissingCaseException(); } } diff --git a/src/engine/moduleengine.cpp b/src/engine/moduleengine.cpp index 4cf8da503c..e098301e56 100644 --- a/src/engine/moduleengine.cpp +++ b/src/engine/moduleengine.cpp @@ -63,7 +63,7 @@ void ModuleEngine::initialize( { ZoneScoped; - std::vector modules = AllModules(); + const std::vector modules = AllModules(); std::vector moduleNames; moduleNames.reserve(modules.size()); @@ -97,7 +97,7 @@ void ModuleEngine::initializeGL() { LDEBUG("Initializing OpenGL of modules"); for (std::unique_ptr& m : _modules) { - LDEBUG(fmt::format("Initializing OpenGL of module '{}'", m->identifier())); + LDEBUG(std::format("Initializing OpenGL of module '{}'", m->identifier())); m->initializeGL(); } LDEBUG("Finished initializing OpenGL of modules"); @@ -109,13 +109,13 @@ void ModuleEngine::deinitialize() { LDEBUG("Deinitializing modules"); for (auto mIt = _modules.rbegin(); mIt != _modules.rend(); ++mIt) { - LDEBUG(fmt::format("Deinitializing module '{}'", (*mIt)->identifier())); + LDEBUG(std::format("Deinitializing module '{}'", (*mIt)->identifier())); (*mIt)->deinitialize(); } LDEBUG("Finished deinitializing modules"); for (auto mIt = _modules.rbegin(); mIt != _modules.rend(); ++mIt) { - LDEBUG(fmt::format("Destroying module '{}'", (*mIt)->identifier())); + LDEBUG(std::format("Destroying module '{}'", (*mIt)->identifier())); (*mIt) = nullptr; } LDEBUG("Finished destroying modules"); @@ -128,34 +128,34 @@ void ModuleEngine::deinitializeGL() { LDEBUG("Deinitializing OpenGL of modules"); for (auto mIt = _modules.rbegin(); mIt != _modules.rend(); ++mIt) { - LDEBUG(fmt::format("Deinitializing OpenGL of module '{}'", (*mIt)->identifier())); + LDEBUG(std::format("Deinitializing OpenGL of module '{}'", (*mIt)->identifier())); (*mIt)->deinitializeGL(); } LDEBUG("Finished deinitializing OpenGL of modules"); } -void ModuleEngine::registerModule(std::unique_ptr mod) { +void ModuleEngine::registerModule(std::unique_ptr module) { ZoneScoped; - ghoul_assert(mod, "Module must not be nullptr"); + ghoul_assert(module, "Module must not be nullptr"); auto it = std::find_if( _modules.begin(), _modules.end(), - [&mod](std::unique_ptr& rhs) { - return rhs->identifier() == mod->identifier(); + [&module](std::unique_ptr& rhs) { + return rhs->identifier() == module->identifier(); } ); if (it != _modules.end()) { throw ghoul::RuntimeError( - fmt::format("Module name '{}' was registered before", mod->identifier()), + std::format("Module name '{}' was registered before", module->identifier()), "ModuleEngine" ); } - LDEBUG(fmt::format("Registered module '{}'", mod->identifier())); - _modules.push_back(std::move(mod)); + LDEBUG(std::format("Registered module '{}'", module->identifier())); + _modules.push_back(std::move(module)); } std::vector ModuleEngine::modules() const { diff --git a/src/engine/openspaceengine.cpp b/src/engine/openspaceengine.cpp index cd568f2e9f..3ecf2286f8 100644 --- a/src/engine/openspaceengine.cpp +++ b/src/engine/openspaceengine.cpp @@ -132,13 +132,6 @@ namespace { openspace::properties::Property::Visibility::Always }; - constexpr openspace::properties::Property::PropertyInfo ShowHiddenSceneInfo = { - "ShowHiddenSceneGraphNodes", - "Show Hidden Scene Graph Nodes", - "If checked, hidden scene graph nodes are visible in the UI", - openspace::properties::Property::Visibility::AdvancedUser - }; - constexpr openspace::properties::Property::PropertyInfo FadeDurationInfo = { "FadeDuration", "Fade Duration (seconds)", @@ -157,6 +150,47 @@ namespace { // @VISIBILITY(2.67) openspace::properties::Property::Visibility::User }; + + void viewportChanged() { + using namespace openspace; + + // Needs to be updated since each render call potentially targets a different + // window and/or viewport + using FR = ghoul::fontrendering::FontRenderer; + FR::defaultRenderer().setFramebufferSize(global::renderEngine->fontResolution()); + + FR::defaultProjectionRenderer().setFramebufferSize( + global::renderEngine->renderingResolution() + ); + } + + void resetPropertyChangeFlagsOfSubowners(openspace::properties::PropertyOwner* po) { + using namespace openspace; + + for (properties::PropertyOwner* subOwner : po->propertySubOwners()) { + resetPropertyChangeFlagsOfSubowners(subOwner); + } + for (properties::Property* p : po->properties()) { + p->resetToUnchanged(); + } + } + + void resetPropertyChangeFlags() { + using namespace openspace; + + ZoneScoped; + + Scene* scene = global::renderEngine->scene(); + if (!scene) { + return; + } + + const std::vector nodes = scene->allSceneGraphNodes(); + for (SceneGraphNode* n : nodes) { + resetPropertyChangeFlagsOfSubowners(n); + } + } + } // namespace namespace openspace { @@ -167,7 +201,6 @@ OpenSpaceEngine::OpenSpaceEngine() : properties::PropertyOwner({ "OpenSpaceEngine", "OpenSpace Engine" }) , _printEvents(PrintEventsInfo, false) , _visibility(VisibilityInfo) - , _showHiddenSceneGraphNodes(ShowHiddenSceneInfo, false) , _fadeOnEnableDuration(FadeDurationInfo, 1.f, 0.f, 5.f) , _disableAllMouseInputs(DisableMouseInputInfo, false) { @@ -187,7 +220,6 @@ OpenSpaceEngine::OpenSpaceEngine() }); addProperty(_visibility); - addProperty(_showHiddenSceneGraphNodes); addProperty(_fadeOnEnableDuration); addProperty(_disableAllMouseInputs); } @@ -202,11 +234,11 @@ void OpenSpaceEngine::registerPathTokens() { using T = std::string; for (const std::pair& path : global::configuration->pathTokens) { std::string fullKey = "${" + path.first + "}"; - LDEBUG(fmt::format("Registering path '{}': '{}'", fullKey, path.second)); + LDEBUG(std::format("Registering path '{}': {}", fullKey, path.second)); const bool overrideBase = (fullKey == "${BASE}"); if (overrideBase) { - LINFO(fmt::format("Overriding base path with '{}'", path.second)); + LINFO(std::format("Overriding base path with '{}'", path.second)); } const bool overrideTemporary = (fullKey == "${TEMPORARY}"); @@ -239,8 +271,8 @@ void OpenSpaceEngine::initialize() { if (global::configuration->usePerProfileCache) { cacheFolder = cacheFolder + "-" + global::configuration->profile; - LINFO(fmt::format("Old cache: {}", absPath("${CACHE}"))); - LINFO(fmt::format("New cache: {}", cacheFolder)); + LINFO(std::format("Old cache: {}", absPath("${CACHE}"))); + LINFO(std::format("New cache: {}", cacheFolder)); FileSys.registerPathToken( "${CACHE}", cacheFolder, @@ -272,10 +304,10 @@ void OpenSpaceEngine::initialize() { ghoul::logging::LogManager::deinitialize(); } - ghoul::logging::LogLevel level = ghoul::from_string( + const ghoul::logging::LogLevel level = ghoul::from_string( global::configuration->logging.level ); - bool immediateFlush = global::configuration->logging.forceImmediateFlush; + const bool immediateFlush = global::configuration->logging.forceImmediateFlush; using ImmediateFlush = ghoul::logging::LogManager::ImmediateFlush; ghoul::logging::LogManager::initialize(level, ImmediateFlush(immediateFlush)); @@ -313,18 +345,18 @@ void OpenSpaceEngine::initialize() { while (rot > 0) { // Move all of the existing logs one position up - std::filesystem::path file = absPath(global::configuration->scriptLog); - std::string fname = file.stem().string(); - std::string ext = file.extension().string(); + const std::filesystem::path file = absPath(global::configuration->scriptLog); + const std::string fname = file.stem().string(); + const std::string ext = file.extension().string(); std::filesystem::path newCandidate = file; - newCandidate.replace_filename(fmt::format("{}-{}{}", fname, rot, ext)); + newCandidate.replace_filename(std::format("{}-{}{}", fname, rot, ext)); std::filesystem::path oldCandidate = file; if (rot > 1) { // We don't actually have a -0 version, it is just the base name oldCandidate.replace_filename( - fmt::format("{}-{}{}", fname, rot - 1, ext) + std::format("{}-{}{}", fname, rot - 1, ext) ); } @@ -365,10 +397,10 @@ void OpenSpaceEngine::initialize() { // Process profile file std::filesystem::path profile; if (!std::filesystem::is_regular_file(global::configuration->profile)) { - std::filesystem::path userCandidate = absPath(fmt::format( + const std::filesystem::path userCandidate = absPath(std::format( "${{USER_PROFILES}}/{}.profile", global::configuration->profile )); - std::filesystem::path profileCandidate = absPath(fmt::format( + const std::filesystem::path profileCandidate = absPath(std::format( "${{PROFILES}}/{}.profile", global::configuration->profile )); @@ -380,7 +412,7 @@ void OpenSpaceEngine::initialize() { profile = profileCandidate; } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not load profile '{}': File does not exist", global::configuration->profile )); @@ -404,7 +436,7 @@ void OpenSpaceEngine::initialize() { for (OpenSpaceModule* module : global::moduleEngine->modules()) { global::scriptEngine->addLibrary(module->luaLibrary()); - for (scripting::LuaLibrary& l : module->luaLibraries()) { + for (const scripting::LuaLibrary& l : module->luaLibraries()) { global::scriptEngine->addLibrary(l); } } @@ -444,7 +476,7 @@ void OpenSpaceEngine::initializeGL() { SysCap.detectCapabilities(); using Verbosity = ghoul::systemcapabilities::SystemCapabilitiesComponent::Verbosity; - Verbosity verbosity = ghoul::from_string( + const Verbosity verbosity = ghoul::from_string( global::configuration->logging.capabilitiesVerbosity ); SysCap.logCapabilities(verbosity); @@ -455,9 +487,9 @@ void OpenSpaceEngine::initializeGL() { } // Check the required OpenGL versions of the registered modules - ghoul::systemcapabilities::Version version = + const ghoul::systemcapabilities::Version version = global::moduleEngine->requiredOpenGLVersion(); - LINFO(fmt::format("Required OpenGL version: {}", ghoul::to_string(version))); + LINFO(std::format("Required OpenGL version: {}", ghoul::to_string(version))); if (OpenGLCap.openGLVersion() < version) { throw ghoul::RuntimeError( @@ -473,10 +505,10 @@ void OpenSpaceEngine::initializeGL() { for (OpenSpaceModule* m : global::moduleEngine->modules()) { for (const std::string& ext : m->requiredOpenGLExtensions()) { if (!SysCap.component().isExtensionSupported(ext)) { - LFATAL(fmt::format( - "Module {} required OpenGL extension {} which is not available " - "on this system. Some functionality related to this module will " - "probably not work", + LFATAL(std::format( + "Module '{}' required OpenGL extension '{}' which is not " + "available on this system. Some functionality related to this " + "module will probably not work", m->guiName(), ext )); } @@ -507,7 +539,7 @@ void OpenSpaceEngine::initializeGL() { global::luaConsole->initialize(); global::luaConsole->setCommandInputButton(global::configuration->consoleKey); } - catch (ghoul::RuntimeError& e) { + catch (const ghoul::RuntimeError& e) { LERROR("Error initializing Console with error:"); LERRORC(e.component, e.message); } @@ -530,7 +562,7 @@ void OpenSpaceEngine::initializeGL() { if (debugActive) { using namespace ghoul::opengl::debug; - bool synchronous = global::configuration->openGLDebugContext.isSynchronous; + const bool synchronous = global::configuration->openGLDebugContext.isSynchronous; setDebugOutput(DebugOutput(debugActive), SynchronousOutput(synchronous)); for (const Configuration::OpenGLDebugContext::IdentifierFilter& f : @@ -556,40 +588,41 @@ void OpenSpaceEngine::initializeGL() { ); } - auto callback = [](Source source, Type type, Severity severity, - unsigned int id, std::string message) -> void - { - const std::string s = ghoul::to_string(source); - const std::string t = ghoul::to_string(type); + ghoul::opengl::debug::setDebugCallback( + [](Source source, Type type, Severity severity, unsigned int id, + const std::string& message) + { + const std::string s = ghoul::to_string(source); + const std::string t = ghoul::to_string(type); - const std::string category = fmt::format("OpenGL ({}) [{}] {{{}}}", s, t, id); - switch (severity) { - case Severity::High: - LERRORC(category, message); - break; - case Severity::Medium: - LWARNINGC(category, message); - break; - case Severity::Low: - LINFOC(category, message); - break; - case Severity::Notification: - LDEBUGC(category, message); - break; - default: - throw ghoul::MissingCaseException(); - } - - if (global::configuration->openGLDebugContext.printStacktrace) { - std::string stackString = "Stacktrace\n"; - std::vector stack = ghoul::stackTrace(); - for (size_t i = 0; i < stack.size(); i++) { - stackString += fmt::format("{}: {}\n", i, stack[i]); + const std::string cat = std::format("OpenGL ({}) [{}] {{{}}}", s, t, id); + switch (severity) { + case Severity::High: + LERRORC(cat, message); + break; + case Severity::Medium: + LWARNINGC(cat, message); + break; + case Severity::Low: + LINFOC(cat, message); + break; + case Severity::Notification: + LDEBUGC(cat, message); + break; + default: + throw ghoul::MissingCaseException(); + } + + if (global::configuration->openGLDebugContext.printStacktrace) { + std::string stackString = "Stacktrace\n"; + std::vector stack = ghoul::stackTrace(); + for (size_t i = 0; i < stack.size(); i++) { + stackString += std::format("{}: {}\n", i, stack[i]); + } + LDEBUGC(cat, stackString); } - LDEBUGC(category, stackString); } - }; - ghoul::opengl::debug::setDebugCallback(callback); + ); } LTRACE("OpenSpaceEngine::initializeGL::DebugContext(end)"); @@ -610,27 +643,27 @@ void OpenSpaceEngine::initializeGL() { case GL_INVALID_ENUM: LERRORC( "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_ENUM", f.function->name()) + std::format("Function '{}': GL_INVALID_ENUM", f.function->name()) ); break; case GL_INVALID_VALUE: LERRORC( "OpenGL Invalid State", - fmt::format("Function {}: GL_INVALID_VALUE", f.function->name()) + std::format("Function '{}': GL_INVALID_VALUE", f.function->name()) ); break; case GL_INVALID_OPERATION: LERRORC( "OpenGL Invalid State", - fmt::format( - "Function {}: GL_INVALID_OPERATION", f.function->name() + std::format( + "Function '{}': GL_INVALID_OPERATION", f.function->name() )); break; case GL_INVALID_FRAMEBUFFER_OPERATION: LERRORC( "OpenGL Invalid State", - fmt::format( - "Function {}: GL_INVALID_FRAMEBUFFER_OPERATION", + std::format( + "Function '{}': GL_INVALID_FRAMEBUFFER_OPERATION", f.function->name() ) ); @@ -638,13 +671,13 @@ void OpenSpaceEngine::initializeGL() { case GL_OUT_OF_MEMORY: LERRORC( "OpenGL Invalid State", - fmt::format("Function {}: GL_OUT_OF_MEMORY", f.function->name()) + std::format("Function '{}': GL_OUT_OF_MEMORY", f.function->name()) ); break; default: LERRORC( "OpenGL Invalid State", - fmt::format("Unknown error code: {0:x}", static_cast(error)) + std::format("Unknown error code: {0:x}", static_cast(error)) ); } }); @@ -652,7 +685,9 @@ void OpenSpaceEngine::initializeGL() { if (global::configuration->isLoggingOpenGLCalls) { using namespace ghoul::logging; - LogLevel lvl = ghoul::from_string(global::configuration->logging.level); + const LogLevel lvl = ghoul::from_string( + global::configuration->logging.level + ); if (lvl > LogLevel::Trace) { LWARNING( "Logging OpenGL calls is enabled, but the selected log level does " @@ -722,11 +757,11 @@ void OpenSpaceEngine::loadAssets() { std::unique_ptr sceneInitializer; if (global::configuration->useMultithreadedInitialization) { - unsigned int nAvailableThreads = std::min( + const unsigned int nAvailableThreads = std::min( std::thread::hardware_concurrency() - 1, 4u ); - unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads; + const unsigned int nThreads = nAvailableThreads == 0 ? 2 : nAvailableThreads; sceneInitializer = std::make_unique(nThreads); } else { @@ -870,14 +905,14 @@ void OpenSpaceEngine::runGlobalCustomizationScripts() { ZoneScoped; LINFO("Running Global initialization scripts"); - ghoul::lua::LuaState state; + const ghoul::lua::LuaState state; global::scriptEngine->initializeLuaState(state); for (const std::string& script : global::configuration->globalCustomizationScripts) { std::filesystem::path s = absPath(script); if (std::filesystem::is_regular_file(s)) { try { - LINFO(fmt::format("Running global customization script: {}", s)); + LINFO(std::format("Running global customization script: {}", s)); ghoul::lua::runScriptFile(state, s.string()); } catch (const ghoul::RuntimeError& e) { @@ -885,7 +920,7 @@ void OpenSpaceEngine::runGlobalCustomizationScripts() { } } else { - LDEBUG(fmt::format("Ignoring non-existing script file: {}", s)); + LDEBUG(std::format("Ignoring non-existing script file: {}", s)); } } } @@ -899,15 +934,17 @@ void OpenSpaceEngine::loadFonts() { std::filesystem::path fontName = absPath(font.second); if (!std::filesystem::is_regular_file(fontName)) { - LERROR(fmt::format("Could not find font {} for key '{}'", fontName, key)); + LERROR(std::format("Could not find font '{}' for key '{}'", fontName, key)); continue; } - LDEBUG(fmt::format("Registering font {} with key '{}'", fontName, key)); - bool success = global::fontManager->registerFontPath(key, fontName); + LDEBUG(std::format("Registering font '{}' with key '{}'", fontName, key)); + const bool success = global::fontManager->registerFontPath(key, fontName); if (!success) { - LERROR(fmt::format("Error registering font {} with key '{}'", fontName, key)); + LERROR(std::format( + "Error registering font '{}' with key '{}'", fontName, key + )); } } @@ -945,22 +982,21 @@ void OpenSpaceEngine::preSynchronization() { global::windowDelegate->setSynchronization(false); } - bool master = global::windowDelegate->isMaster(); + const bool master = global::windowDelegate->isMaster(); global::syncEngine->preSynchronization(SyncEngine::IsMaster(master)); if (master) { - double dt = global::windowDelegate->deltaTime(); - - if (global::sessionRecording->isSavingFramesDuringPlayback()) { - dt = global::sessionRecording->fixedDeltaTimeDuringFrameOutput(); - } + const double dt = + global::sessionRecording->isSavingFramesDuringPlayback() ? + global::sessionRecording->fixedDeltaTimeDuringFrameOutput() : + global::windowDelegate->deltaTime(); global::timeManager->preSynchronization(dt); - std::vector scheduledScripts = global::scriptScheduler->progressTo( + const std::vector schedScripts = global::scriptScheduler->progressTo( global::timeManager->time().j2000Seconds() ); - for (const std::string& script : scheduledScripts) { + for (const std::string& script : schedScripts) { global::scriptEngine->queueScript( script, scripting::ScriptEngine::ShouldBeSynchronized::Yes, @@ -1011,7 +1047,7 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { TracyGpuZone("postSynchronizationPreDraw"); LTRACE("OpenSpaceEngine::postSynchronizationPreDraw(begin)"); - bool master = global::windowDelegate->isMaster(); + const bool master = global::windowDelegate->isMaster(); global::syncEngine->postSynchronization(SyncEngine::IsMaster(master)); if (_shutdown.inShutdown) { @@ -1051,13 +1087,13 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { int fatalCounter = LogMgr.messageCounter(ghoul::logging::LogLevel::Fatal); if (warningCounter > 0) { - LWARNINGC("Logging", fmt::format("Number of Warnings: {}", warningCounter)); + LWARNINGC("Logging", std::format("Number of Warnings: {}", warningCounter)); } if (errorCounter > 0) { - LWARNINGC("Logging", fmt::format("Number of Errors: {}", errorCounter)); + LWARNINGC("Logging", std::format("Number of Errors: {}", errorCounter)); } if (fatalCounter > 0) { - LWARNINGC("Logging", fmt::format("Number of Fatals: {}", fatalCounter)); + LWARNINGC("Logging", std::format("Number of Fatals: {}", fatalCounter)); } LogMgr.resetMessageCounters(); @@ -1065,17 +1101,6 @@ void OpenSpaceEngine::postSynchronizationPreDraw() { LTRACE("OpenSpaceEngine::postSynchronizationPreDraw(end)"); } -void OpenSpaceEngine::viewportChanged() { - // Needs to be updated since each render call potentially targets a different - // window and/or viewport - using FR = ghoul::fontrendering::FontRenderer; - FR::defaultRenderer().setFramebufferSize(global::renderEngine->fontResolution()); - - FR::defaultProjectionRenderer().setFramebufferSize( - global::renderEngine->renderingResolution() - ); -} - void OpenSpaceEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix) { @@ -1158,25 +1183,6 @@ void OpenSpaceEngine::postDraw() { LTRACE("OpenSpaceEngine::postDraw(end)"); } -void OpenSpaceEngine::resetPropertyChangeFlags() { - ZoneScoped; - - std::vector nodes = - global::renderEngine->scene()->allSceneGraphNodes(); - for (SceneGraphNode* n : nodes) { - resetPropertyChangeFlagsOfSubowners(n); - } -} - -void OpenSpaceEngine::resetPropertyChangeFlagsOfSubowners(properties::PropertyOwner* po) { - for (properties::PropertyOwner* subOwner : po->propertySubOwners()) { - resetPropertyChangeFlagsOfSubowners(subOwner); - } - for (properties::Property* p : po->properties()) { - p->resetToUnchanged(); - } -} - void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction action, IsGuiWindow isGuiWindow) { @@ -1204,8 +1210,7 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio return; } - using F = global::callback::KeyboardCallback; - for (const F& func : *global::callback::keyboard) { + for (const global::callback::KeyboardCallback& func : *global::callback::keyboard) { const bool isConsumed = func(key, mod, action, isGuiWindow); if (isConsumed) { return; @@ -1213,8 +1218,8 @@ void OpenSpaceEngine::keyboardCallback(Key key, KeyModifier mod, KeyAction actio } if (!global::configuration->isConsoleDisabled) { - bool isConsoleConsumed = global::luaConsole->keyboardCallback(key, mod, action); - if (isConsoleConsumed) { + const bool isConsumed = global::luaConsole->keyboardCallback(key, mod, action); + if (isConsumed) { return; } } @@ -1233,9 +1238,8 @@ void OpenSpaceEngine::charCallback(unsigned int codepoint, KeyModifier modifier, { ZoneScoped; - using F = global::callback::CharacterCallback; - for (const F& func : *global::callback::character) { - bool isConsumed = func(codepoint, modifier, isGuiWindow); + for (const global::callback::CharacterCallback& func : *global::callback::character) { + const bool isConsumed = func(codepoint, modifier, isGuiWindow); if (isConsumed) { return; } @@ -1263,7 +1267,7 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action using F = global::callback::MouseButtonCallback; for (const F& func : *global::callback::mouseButton) { - bool isConsumed = func(button, action, mods, isGuiWindow); + const bool isConsumed = func(button, action, mods, isGuiWindow); if (isConsumed) { // If the mouse was released, we still want to forward it to the navigation // handler in order to reliably terminate a rotation or zoom, or to the other @@ -1282,7 +1286,8 @@ void OpenSpaceEngine::mouseButtonCallback(MouseButton button, MouseAction action // Check if the user clicked on one of the 'buttons' the RenderEngine is drawing. // Only handle the clicks if we are in a GUI window if (action == MouseAction::Press && isGuiWindow) { - bool isConsumed = global::renderEngine->mouseActivationCallback(_mousePosition); + const bool isConsumed = + global::renderEngine->mouseActivationCallback(_mousePosition); if (isConsumed) { return; } @@ -1328,7 +1333,7 @@ void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY, using F = global::callback::MouseScrollWheelCallback; for (const F& func : *global::callback::mouseScrollWheel) { - bool isConsumed = func(posX, posY, isGuiWindow); + const bool isConsumed = func(posX, posY, isGuiWindow); if (isConsumed) { return; } @@ -1341,9 +1346,8 @@ void OpenSpaceEngine::mouseScrollWheelCallback(double posX, double posY, void OpenSpaceEngine::touchDetectionCallback(TouchInput input) { ZoneScoped; - using F = std::function; - for (const F& func : *global::callback::touchDetected) { - bool isConsumed = func(input); + for (const std::function& func : *global::callback::touchDetected) { + const bool isConsumed = func(input); if (isConsumed) { return; } @@ -1353,9 +1357,8 @@ void OpenSpaceEngine::touchDetectionCallback(TouchInput input) { void OpenSpaceEngine::touchUpdateCallback(TouchInput input) { ZoneScoped; - using F = std::function; - for (const F& func : *global::callback::touchUpdated) { - bool isConsumed = func(input); + for (const std::function& func : *global::callback::touchUpdated) { + const bool isConsumed = func(input); if (isConsumed) { return; } @@ -1365,18 +1368,17 @@ void OpenSpaceEngine::touchUpdateCallback(TouchInput input) { void OpenSpaceEngine::touchExitCallback(TouchInput input) { ZoneScoped; - using F = std::function; - for (const F& func : *global::callback::touchExit) { + for (const std::function& func : *global::callback::touchExit) { func(input); } } void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) { - ghoul::lua::LuaState s(ghoul::lua::LuaState::IncludeStandardLibrary::Yes); - std::filesystem::path absolutePath = absPath("${SCRIPTS}/drag_drop_handler.lua"); - int status = luaL_loadfile(s, absolutePath.string().c_str()); + const ghoul::lua::LuaState s(ghoul::lua::LuaState::IncludeStandardLibrary::Yes); + const std::filesystem::path path = absPath("${SCRIPTS}/drag_drop_handler.lua"); + int status = luaL_loadfile(s, path.string().c_str()); if (status != LUA_OK) { - std::string error = lua_tostring(s, -1); + const std::string error = lua_tostring(s, -1); LERROR(error); return; } @@ -1385,7 +1387,7 @@ void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) { lua_setglobal(s, "filename"); std::string basename = file.filename().string(); - ghoul::lua::push(s, basename); + ghoul::lua::push(s, std::move(basename)); lua_setglobal(s, "basename"); std::string extension = file.extension().string(); @@ -1396,19 +1398,19 @@ void OpenSpaceEngine::handleDragDrop(std::filesystem::path file) { status = lua_pcall(s, 0, 1, 0); if (status != LUA_OK) { - std::string error = lua_tostring(s, -1); + const std::string error = lua_tostring(s, -1); LERROR(error); return; } if (lua_isnil(s, -1)) { - LWARNING(fmt::format("Unhandled file dropped: {}", file)); + LWARNING(std::format("Unhandled file dropped: {}", file)); return; } std::string script = ghoul::lua::value(s); global::scriptEngine->queueScript( - script, + std::move(script), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -1426,14 +1428,10 @@ void OpenSpaceEngine::decode(std::vector data) { global::syncEngine->decodeSyncables(std::move(data)); } -properties::Property::Visibility openspace::OpenSpaceEngine::visibility() const { +properties::Property::Visibility OpenSpaceEngine::visibility() const { return static_cast(_visibility.value()); } -bool openspace::OpenSpaceEngine::showHiddenSceneGraphNodes() const { - return _showHiddenSceneGraphNodes; -} - void OpenSpaceEngine::toggleShutdownMode() { if (_shutdown.inShutdown) { // If we are already in shutdown mode, we want to disable it @@ -1467,14 +1465,14 @@ bool OpenSpaceEngine::setMode(Mode newMode) { return false; } else if (_currentMode != Mode::UserControl && newMode != Mode::UserControl) { - LERROR(fmt::format( + LERROR(std::format( "Cannot switch to mode '{}' when in '{}' mode", stringify(newMode), stringify(_currentMode) )); return false; } - LDEBUG(fmt::format("Mode: {}", stringify(newMode))); + LDEBUG(std::format("Mode: {}", stringify(newMode))); _currentMode = newMode; return true; @@ -1482,13 +1480,13 @@ bool OpenSpaceEngine::setMode(Mode newMode) { void OpenSpaceEngine::resetMode() { _currentMode = Mode::UserControl; - LDEBUG(fmt::format("Reset engine mode to {}", stringify(_currentMode))); + LDEBUG(std::format("Reset engine mode to '{}'", stringify(_currentMode))); } OpenSpaceEngine::CallbackHandle OpenSpaceEngine::addModeChangeCallback( - ModeChangeCallback cb) + ModeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _modeChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } @@ -1556,7 +1554,7 @@ void setCameraFromProfile(const Profile& p) { auto checkNodeExists = [](const std::string& node) { if (global::renderEngine->scene()->sceneGraphNode(node) == nullptr) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Error when setting camera from profile. Could not find node '{}'", node )); } @@ -1597,10 +1595,10 @@ void setCameraFromProfile(const Profile& p) { // dependency in this core code. Eventually, goToGeo will be incorporated // in the OpenSpace core and this code will change. checkNodeExists(geo.anchor); - std::string geoScript = fmt::format("openspace.globebrowsing.goToGeo" + std::string geoScript = std::format("openspace.globebrowsing.goToGeo" "([[{}]], {}, {}", geo.anchor, geo.latitude, geo.longitude); if (geo.altitude.has_value()) { - geoScript += fmt::format(", {}", geo.altitude.value()); + geoScript += std::format(", {}", geo.altitude.value()); } geoScript += ")"; global::scriptEngine->queueScript( @@ -1614,12 +1612,12 @@ void setCameraFromProfile(const Profile& p) { checkNodeExists(node.anchor); - NodeCameraStateSpec spec = { + NodeCameraStateSpec spc = { .identifier = node.anchor, .height = node.height, .useTargetUpDirection = true }; - global::navigationHandler->setCameraFromNodeSpecNextFrame(spec); + global::navigationHandler->setCameraFromNodeSpecNextFrame(std::move(spc)); } }, p.camera.value() @@ -1660,13 +1658,13 @@ void setActionsFromProfile(const Profile& p) { LERROR("Identifier must to provided to register action"); } if (global::actionManager->hasAction(a.identifier)) { - LERROR(fmt::format( + LERROR(std::format( "Action for identifier '{}' already existed & registered", a.identifier )); } if (a.script.empty()) { - LERROR(fmt::format( - "Identifier '{}' doesn't provide a Lua command to execute", a.identifier + LERROR(std::format( + "Identifier '{}' does not provide a Lua command to execute", a.identifier )); } interaction::Action action; @@ -1686,10 +1684,10 @@ void setKeybindingsFromProfile(const Profile& p) { LERROR("Action must not be empty"); } if (!global::actionManager->hasAction(k.action)) { - LERROR(fmt::format("Action '{}' does not exist", k.action)); + LERROR(std::format("Action '{}' does not exist", k.action)); } if (k.key.key == openspace::Key::Unknown) { - LERROR(fmt::format( + LERROR(std::format( "Could not find key '{}'", std::to_string(static_cast(k.key.key)) )); diff --git a/src/engine/openspaceengine_lua.inl b/src/engine/openspaceengine_lua.inl index b8c4b8af9c..c615a72fa1 100644 --- a/src/engine/openspaceengine_lua.inl +++ b/src/engine/openspaceengine_lua.inl @@ -57,7 +57,7 @@ namespace { ghoul::filesystem::FileSystem::Override::Yes ); - global::windowDelegate->setScreenshotFolder(folder.string()); + global::windowDelegate->setScreenshotFolder(std::move(folder)); } // Adds a Tag to a SceneGraphNode identified by the provided uri @@ -66,7 +66,7 @@ namespace { SceneGraphNode* node = global::renderEngine->scene()->sceneGraphNode(uri); if (!node) { - throw ghoul::lua::LuaError(fmt::format("Unknown scene graph node '{}'", uri)); + throw ghoul::lua::LuaError(std::format("Unknown scene graph node '{}'", uri)); } node->addTag(std::move(tag)); @@ -78,7 +78,7 @@ namespace { SceneGraphNode* node = global::renderEngine->scene()->sceneGraphNode(uri); if (!node) { - throw ghoul::lua::LuaError(fmt::format("Unknown scene graph node '{}'", uri)); + throw ghoul::lua::LuaError(std::format("Unknown scene graph node '{}'", uri)); } node->removeTag(tag); @@ -90,7 +90,7 @@ namespace { { using namespace openspace; - LINFOC("OpenSpaceEngine", fmt::format("Downloading file from {}", url)); + LINFOC("OpenSpaceEngine", std::format("Downloading file from '{}'", url)); std::shared_ptr future = global::downloadManager->downloadFile( url, @@ -103,7 +103,7 @@ namespace { if (waitForCompletion) { while (!future->isFinished && future->errorMessage.empty()) { // just wait - LTRACEC("OpenSpaceEngine", fmt::format("waiting {}", future->errorMessage)); + LTRACEC("OpenSpaceEngine", std::format("waiting '{}'", future->errorMessage)); } } } @@ -142,7 +142,7 @@ namespace { ); const bool hasCachedFile = std::filesystem::is_regular_file(fileName); if (hasCachedFile) { - LDEBUGC("OpenSpaceEngine", fmt::format("Cached file '{}' used", fileName)); + LDEBUGC("OpenSpaceEngine", std::format("Cached file '{}' used", fileName)); return fileName; } else { @@ -220,7 +220,7 @@ namespace { bool includeFirstLine = false) { if (!std::filesystem::exists(file) || !std::filesystem::is_regular_file(file)) { - throw ghoul::lua::LuaError(fmt::format("Could not find file {}", file)); + throw ghoul::lua::LuaError(std::format("Could not find file '{}'", file)); } std::vector> res = @@ -258,7 +258,7 @@ namespace { */ [[codegen::luawrap]] ghoul::Dictionary loadJson(std::filesystem::path path) { if (!std::filesystem::exists(path)) { - throw ghoul::RuntimeError(fmt::format("File {} did not exist", path)); + throw ghoul::RuntimeError(std::format("File '{}' did not exist", path)); } std::ifstream f(path); diff --git a/src/engine/settings.cpp b/src/engine/settings.cpp index 90feb2bf1f..2b6a09b989 100644 --- a/src/engine/settings.cpp +++ b/src/engine/settings.cpp @@ -68,8 +68,8 @@ namespace version1 { settings.visibility = properties::Property::Visibility::Developer; } else { - throw ghoul::RuntimeError(fmt::format( - "Unknown visibility value {}", *visibility + throw ghoul::RuntimeError(std::format( + "Unknown visibility value '{}'", *visibility )); } } @@ -100,8 +100,8 @@ namespace version1 { std::filesystem::path findSettings(const std::string& filename) { // Right now the settings file lives next to the openspace.cfg file - std::filesystem::path path = findConfiguration(); - std::filesystem::path result = path.parent_path() / filename; + const std::filesystem::path path = findConfiguration(); + const std::filesystem::path result = path.parent_path() / filename; return result; } @@ -110,10 +110,12 @@ Settings loadSettings(const std::filesystem::path& filename) { return Settings(); } - std::ifstream f(filename); std::stringstream buffer; - buffer << f.rdbuf(); - std::string contents = buffer.str(); + { + const std::ifstream f = std::ifstream(filename); + buffer << f.rdbuf(); + } + const std::string contents = buffer.str(); nlohmann::json setting = nlohmann::json::parse(contents); if (setting.empty()) { @@ -125,7 +127,7 @@ Settings loadSettings(const std::filesystem::path& filename) { return version1::parseSettings(setting); } - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Unrecognized version for setting: {}", version )); } @@ -186,8 +188,8 @@ void saveSettings(const Settings& settings, const std::filesystem::path& filenam json["mrf"] = mrf; } - std::string content = json.dump(2); - std::ofstream f(filename); + std::ofstream f = std::ofstream(filename); + const std::string content = json.dump(2); f << content; } diff --git a/src/events/event.cpp b/src/events/event.cpp index b6cdf174b6..f1aa87de91 100644 --- a/src/events/event.cpp +++ b/src/events/event.cpp @@ -45,12 +45,12 @@ namespace openspace::events { void log(int i, const EventSceneGraphNodeAdded& e) { ghoul_assert(e.type == EventSceneGraphNodeAdded::Type, "Wrong type"); - LINFO(fmt::format("[{}] SceneGraphNodeAdded: {}", i, e.node)); + LINFO(std::format("[{}] SceneGraphNodeAdded: {}", i, e.node)); } void log(int i, const EventSceneGraphNodeRemoved& e) { ghoul_assert(e.type == EventSceneGraphNodeRemoved::Type, "Wrong type"); - LINFO(fmt::format("[{}] SceneGraphNodeRemoved: {}", i, e.node)); + LINFO(std::format("[{}] SceneGraphNodeRemoved: {}", i, e.node)); } void log(int i, const EventParallelConnection& e) { @@ -64,17 +64,17 @@ void log(int i, const EventParallelConnection& e) { default: throw ghoul::MissingCaseException(); } }(e.state); - LINFO(fmt::format("[{}] ParallelConnection ({})", i, state)); + LINFO(std::format("[{}] ParallelConnection ({})", i, state)); } void log(int i, [[ maybe_unused ]] const EventProfileLoadingFinished& e) { ghoul_assert(e.type == EventProfileLoadingFinished::Type, "Wrong type"); - LINFO(fmt::format("[{}] ProfileLoadingFinished", i)); + LINFO(std::format("[{}] ProfileLoadingFinished", i)); } void log(int i, const EventApplicationShutdown& e) { ghoul_assert(e.type == EventApplicationShutdown::Type, "Wrong type"); - std::string t = [](EventApplicationShutdown::State state) { + const std::string t = [](EventApplicationShutdown::State state) { switch (state) { case EventApplicationShutdown::State::Started: return "started"; case EventApplicationShutdown::State::Aborted: return "aborted"; @@ -82,17 +82,17 @@ void log(int i, const EventApplicationShutdown& e) { default: throw ghoul::MissingCaseException(); } }(e.state); - LINFO(fmt::format("[{}] ApplicationShutdown", i)); + LINFO(std::format("[{}] ApplicationShutdown", i)); } void log(int i, const EventScreenSpaceRenderableAdded& e) { ghoul_assert(e.type == EventScreenSpaceRenderableAdded::Type, "Wrong type"); - LINFO(fmt::format("[{}] ScreenSpaceRenderableAdded: {}", i, e.renderable)); + LINFO(std::format("[{}] ScreenSpaceRenderableAdded: {}", i, e.renderable)); } void log(int i, const EventScreenSpaceRenderableRemoved& e) { ghoul_assert(e.type == EventScreenSpaceRenderableRemoved::Type, "Wrong type"); - LINFO(fmt::format("[{}] ScreenSpaceRenderableRemoved: {}", i, e.renderable)); + LINFO(std::format("[{}] ScreenSpaceRenderableRemoved: {}", i, e.renderable)); } void log(int i, const EventCameraFocusTransition& e) { @@ -112,7 +112,7 @@ void log(int i, const EventCameraFocusTransition& e) { } }(e.transition); - LINFO(fmt::format( + LINFO(std::format( "[{}] CameraTransition: {}, {} ({})", i, reinterpret_cast(e.camera), e.node, t )); @@ -120,7 +120,7 @@ void log(int i, const EventCameraFocusTransition& e) { void log(int i, const EventTimeOfInterestReached& e) { ghoul_assert(e.type == EventTimeOfInterestReached::Type, "Wrong type"); - LINFO(fmt::format( + LINFO(std::format( "[{}] TimeOfInterestReached: {}, {}", i, e.time->UTC(), reinterpret_cast(e.camera) )); @@ -128,32 +128,32 @@ void log(int i, const EventTimeOfInterestReached& e) { void log(int i, [[ maybe_unused ]] const EventMissionEventReached& e) { ghoul_assert(e.type == EventMissionEventReached::Type, "Wrong type"); - LINFO(fmt::format("[{}] MissionEventReached", i)); + LINFO(std::format("[{}] MissionEventReached", i)); } void log(int i, const EventPlanetEclipsed& e) { ghoul_assert(e.type == EventPlanetEclipsed::Type, "Wrong type"); - LINFO(fmt::format("[{}] PlanetEclipsed: {} -> {}", i, e.eclipsee, e.eclipser)); + LINFO(std::format("[{}] PlanetEclipsed: {} -> {}", i, e.eclipsee, e.eclipser)); } void log(int i, [[ maybe_unused ]] const EventInterpolationFinished& e) { ghoul_assert(e.type == EventInterpolationFinished::Type, "Wrong type"); - LINFO(fmt::format("[{}] InterpolationFinished", i)); + LINFO(std::format("[{}] InterpolationFinished", i)); } void log(int i, const EventFocusNodeChanged& e) { ghoul_assert(e.type == EventFocusNodeChanged::Type, "Wrong type"); - LINFO(fmt::format("[{}] FocusNodeChanged: {} -> {}", i, e.oldNode, e.newNode)); + LINFO(std::format("[{}] FocusNodeChanged: {} -> {}", i, e.oldNode, e.newNode)); } void log(int i, const EventLayerAdded& e) { ghoul_assert(e.type == EventLayerAdded::Type, "Wrong type"); - LINFO(fmt::format("[{}] LayerAdded: {}", i, e.layer)); + LINFO(std::format("[{}] LayerAdded: {}", i, e.layer)); } void log(int i, const EventLayerRemoved& e) { ghoul_assert(e.type == EventLayerRemoved::Type, "Wrong type"); - LINFO(fmt::format("[{}] LayerRemoved: {}", i, e.layer)); + LINFO(std::format("[{}] LayerRemoved: {}", i, e.layer)); } void log(int i, const EventSessionRecordingPlayback& e) { @@ -169,12 +169,12 @@ void log(int i, const EventSessionRecordingPlayback& e) { } }(e.state); - LINFO(fmt::format("[{}] SessionRecordingPlayback: {}", i, state)); + LINFO(std::format("[{}] SessionRecordingPlayback: {}", i, state)); } void log(int i, const EventPointSpacecraft& e) { ghoul_assert(e.type == EventPointSpacecraft::Type, "Wrong type"); - LINFO(fmt::format( + LINFO(std::format( "[{}] PointSpacecraft: Ra: {}, Dec: {}, Duration: {}", i, e.ra, e.dec, e.duration )); @@ -182,17 +182,17 @@ void log(int i, const EventPointSpacecraft& e) { void log(int i, const EventRenderableEnabled& e) { ghoul_assert(e.type == EventRenderableEnabled::Type, "Wrong type"); - LINFO(fmt::format("[{}] EventRenderableEnabled: {}", i, e.node)); + LINFO(std::format("[{}] EventRenderableEnabled: {}", i, e.node)); } void log(int i, const EventRenderableDisabled& e) { ghoul_assert(e.type == EventRenderableDisabled::Type, "Wrong type"); - LINFO(fmt::format("[{}] EventRenderableDisabled: {}", i, e.node)); + LINFO(std::format("[{}] EventRenderableDisabled: {}", i, e.node)); } void log(int i, const EventCameraPathStarted& e) { ghoul_assert(e.type == EventCameraPathStarted::Type, "Wrong type"); - LINFO(fmt::format( + LINFO(std::format( "[{}] EventCameraPathStarted: Origin: '{}' Destination: '{}'", i, e.origin, e.destination )); @@ -200,7 +200,7 @@ void log(int i, const EventCameraPathStarted& e) { void log(int i, const EventCameraPathFinished& e) { ghoul_assert(e.type == EventCameraPathFinished::Type, "Wrong type"); - LINFO(fmt::format( + LINFO(std::format( "[{}] EventCameraPathFinished: Origin: '{}' Destination: '{}'", i, e.origin, e.destination )); @@ -208,12 +208,12 @@ void log(int i, const EventCameraPathFinished& e) { void log(int i, const EventCameraMovedPosition& e) { ghoul_assert(e.type == EventCameraMovedPosition::Type, "Wrong type"); - LINFO(fmt::format("[{}] EventCameraMovedPosition", i)); + LINFO(std::format("[{}] EventCameraMovedPosition", i)); } void log(int i, const CustomEvent& e) { ghoul_assert(e.type == CustomEvent::Type, "Wrong type"); - LINFO(fmt::format("[{}] CustomEvent: {} ({})", i, e.subtype, e.payload)); + LINFO(std::format("[{}] CustomEvent: {} ({})", i, e.subtype, e.payload)); } std::string_view toString(Event::Type type) { @@ -318,7 +318,7 @@ Event::Type fromString(std::string_view str) { return Event::Type::Custom; } - throw ghoul::RuntimeError(fmt::format("Unknown event type '{}'", str)); + throw ghoul::RuntimeError(std::format("Unknown event type '{}'", str)); } ghoul::Dictionary toParameter(const Event& e) { diff --git a/src/events/eventengine.cpp b/src/events/eventengine.cpp index 087b55ff89..7ac200a65b 100644 --- a/src/events/eventengine.cpp +++ b/src/events/eventengine.cpp @@ -79,14 +79,14 @@ void EventEngine::registerEventTopic(size_t topicId, events::Event::Type type, { TopicInfo ti; ti.id = topicId; - ti.callback = callback; + ti.callback = std::move(callback); _eventTopics[type].push_back(ti); } void EventEngine::unregisterEventAction(events::Event::Type type, const std::string& identifier, - std::optional filter) + const std::optional& filter) { const auto it = _eventActions.find(type); if (it != _eventActions.end()) { @@ -123,8 +123,8 @@ void EventEngine::unregisterEventAction(uint32_t identifier) { } // If we get this far, we haven't found the identifier - throw ghoul::RuntimeError(fmt::format( - "Could not find event with identifier {}", identifier + throw ghoul::RuntimeError(std::format( + "Could not find event with identifier '{}'", identifier )); } @@ -147,13 +147,13 @@ void EventEngine::unregisterEventTopic(size_t topicId, events::Event::Type type) } } else { - LWARNING(fmt::format("Could not find registered event '{}' with topicId: {}", + LWARNING(std::format("Could not find registered event '{}' with topicId: {}", events::toString(type), topicId) ); } } else { - LWARNING(fmt::format("Could not find registered event '{}'", + LWARNING(std::format("Could not find registered event '{}'", events::toString(type)) ); } @@ -209,7 +209,7 @@ void EventEngine::triggerActions() const { while (e) { const auto it = _eventActions.find(e->type); if (it != _eventActions.end()) { - ghoul::Dictionary params = toParameter(*e); + const ghoul::Dictionary params = toParameter(*e); for (const ActionInfo& ai : it->second) { if (ai.isEnabled && (!ai.filter.has_value() || params.isSubset(*ai.filter))) @@ -240,7 +240,7 @@ void EventEngine::triggerTopics() const { const auto it = _eventTopics.find(e->type); if (it != _eventTopics.end()) { - ghoul::Dictionary params = toParameter(*e); + const ghoul::Dictionary params = toParameter(*e); for (const TopicInfo& ti : it->second) { ti.callback(params); } diff --git a/src/interaction/actionmanager.cpp b/src/interaction/actionmanager.cpp index 608ce69005..5f72d9cbc1 100644 --- a/src/interaction/actionmanager.cpp +++ b/src/interaction/actionmanager.cpp @@ -88,7 +88,7 @@ void ActionManager::triggerAction(const std::string& identifier, if (!hasAction(identifier)) { LWARNINGC( "ActionManager", - fmt::format("Action '{}' not found in the list", identifier) + std::format("Action '{}' not found in the list", identifier) ); return; } @@ -97,18 +97,18 @@ void ActionManager::triggerAction(const std::string& identifier, std::string script = arguments.isEmpty() ? a.command : - fmt::format("args = {}\n{}", ghoul::formatLua(arguments), a.command); + std::format("args = {}\n{}", ghoul::formatLua(arguments), a.command); if (!shouldBeSynchronized || a.isLocal) { global::scriptEngine->queueScript( - script, + std::move(script), scripting::ScriptEngine::ShouldBeSynchronized::No, scripting::ScriptEngine::ShouldSendToRemote::No ); } else { global::scriptEngine->queueScript( - script, + std::move(script), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); diff --git a/src/interaction/actionmanager_lua.inl b/src/interaction/actionmanager_lua.inl index f07d82b63a..be68d6672f 100644 --- a/src/interaction/actionmanager_lua.inl +++ b/src/interaction/actionmanager_lua.inl @@ -64,7 +64,7 @@ namespace { } if (!global::actionManager->hasAction(identifier)) { throw ghoul::lua::LuaError( - fmt::format("Identifier '{}' for action not found", identifier) + std::format("Identifier '{}' for action not found", identifier) ); } @@ -105,7 +105,7 @@ struct [[codegen::Dictionary(Action)]] Action { using namespace openspace; if (global::actionManager->hasAction(action.identifier)) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Identifier '{}' for action already registered", action.identifier )); } @@ -118,7 +118,7 @@ struct [[codegen::Dictionary(Action)]] Action { a.guiPath = action.guiPath.value_or(a.guiPath); if (!a.guiPath.starts_with('/')) { throw ghoul::RuntimeError( - fmt::format( + std::format( "Tried to register action: '{}'. The field 'GuiPath' is set to '{}' but " "should be '/{}' ", a.name, a.guiPath, a.guiPath) ); @@ -141,7 +141,7 @@ struct [[codegen::Dictionary(Action)]] Action { } if (!global::actionManager->hasAction(identifier)) { throw ghoul::lua::LuaError( - fmt::format("Identifier '{}' for action not found", identifier) + std::format("Identifier '{}' for action not found", identifier) ); } @@ -189,7 +189,7 @@ struct [[codegen::Dictionary(Action)]] Action { throw ghoul::lua::LuaError("Identifier must not be empty"); } if (!global::actionManager->hasAction(id)) { - throw ghoul::lua::LuaError(fmt::format("Action '{}' not found", id)); + throw ghoul::lua::LuaError(std::format("Action '{}' not found", id)); } // No sync because this is already inside a Lua script, therefor it has diff --git a/src/interaction/camerainteractionstates.cpp b/src/interaction/camerainteractionstates.cpp index 428d07a6d8..c0118d664a 100644 --- a/src/interaction/camerainteractionstates.cpp +++ b/src/interaction/camerainteractionstates.cpp @@ -84,7 +84,7 @@ void CameraInteractionStates::resetVelocities() { _globalRollState.velocity.setHard({ 0.0, 0.0 }); } -bool CameraInteractionStates::hasNonZeroVelocities(bool checkOnlyMovement) { +bool CameraInteractionStates::hasNonZeroVelocities(bool checkOnlyMovement) const { glm::dvec2 sum = glm::dvec2(0.0); sum += globalRotationVelocity(); sum += truckMovementVelocity(); diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 002e8f45ad..676130bbe4 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -47,7 +47,7 @@ void JoystickCameraStates::updateStateFromInput( const JoystickInputStates& joystickInputStates, double deltaTime) { - OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); if (mode == OpenSpaceEngine::Mode::CameraPath || mode == OpenSpaceEngine::Mode::SessionRecordingPlayback) { @@ -71,17 +71,17 @@ void JoystickCameraStates::updateStateFromInput( continue; } - int nAxes = joystickInputStates.numAxes(joystickInputState.name); + const int nAxes = joystickInputStates.numAxes(joystickInputState.name); for (int i = 0; i < std::min(nAxes, static_cast(joystick->axisMapping.size())); - ++i) + i++) { AxisInformation t = joystick->axisMapping[i]; if (t.type == AxisType::None) { continue; } - float rawValue = joystickInputStates.axis(joystickInputState.name, i); + const float rawValue = joystickInputStates.axis(joystickInputState.name, i); float value = rawValue; if (t.isSticky) { @@ -162,7 +162,7 @@ void JoystickCameraStates::updateStateFromInput( localRotation.second.y += value; break; case AxisType::Property: - std::string script = fmt::format( + const std::string script = std::format( "openspace.setPropertyValue('{}', {});", t.propertyUri, value ); @@ -176,11 +176,11 @@ void JoystickCameraStates::updateStateFromInput( } } - int nButtons = joystickInputStates.numButtons(joystickInputState.name); - for (int i = 0; i < nButtons; ++i) { + const int nButtons = joystickInputStates.numButtons(joystickInputState.name); + for (int i = 0; i < nButtons; i++) { auto itRange = joystick->buttonMapping.equal_range(i); - for (auto it = itRange.first; it != itRange.second; ++it) { - bool active = global::joystickInputStates->button( + for (auto it = itRange.first; it != itRange.second; it++) { + const bool active = global::joystickInputStates->button( joystickInputState.name, i, it->second.action @@ -237,7 +237,7 @@ void JoystickCameraStates::updateStateFromInput( } } -void JoystickCameraStates::setAxisMapping(std::string joystickName, +void JoystickCameraStates::setAxisMapping(const std::string& joystickName, int axis, AxisType mapping, AxisInvert shouldInvert, JoystickType joystickType, @@ -267,7 +267,7 @@ void JoystickCameraStates::setAxisMapping(std::string joystickName, global::joystickInputStates->axis(joystickName, axis); } -void JoystickCameraStates::setAxisMappingProperty(std::string joystickName, +void JoystickCameraStates::setAxisMappingProperty(const std::string& joystickName, int axis, std::string propertyUri, float min, float max, @@ -287,7 +287,7 @@ void JoystickCameraStates::setAxisMappingProperty(std::string joystickName, joystickCameraState->axisMapping[axis].type = AxisType::Property; joystickCameraState->axisMapping[axis].invert = shouldInvert; - joystickCameraState->axisMapping[axis].propertyUri = propertyUri; + joystickCameraState->axisMapping[axis].propertyUri = std::move(propertyUri); joystickCameraState->axisMapping[axis].minValue = min; joystickCameraState->axisMapping[axis].maxValue = max; joystickCameraState->axisMapping[axis].isRemote = isRemote; @@ -378,7 +378,7 @@ void JoystickCameraStates::clearButtonCommand(const std::string& joystickName, it = joystick->buttonMapping.erase(it); } else { - ++it; + it++; } } } @@ -394,7 +394,7 @@ std::vector JoystickCameraStates::buttonCommand( } auto itRange = joystick->buttonMapping.equal_range(button); - for (auto it = itRange.first; it != itRange.second; ++it) { + for (auto it = itRange.first; it != itRange.second; it++) { result.push_back(it->second.command); } return result; @@ -421,7 +421,7 @@ JoystickCameraStates::joystickCameraState(const std::string& joystickName) const } } - LWARNING(fmt::format("Cannot find JoystickCameraState with name '{}'", joystickName)); + LWARNING(std::format("Cannot find JoystickCameraState with name '{}'", joystickName)); return nullptr; } @@ -431,13 +431,15 @@ JoystickCameraStates::findOrAddJoystickCameraState(const std::string& joystickNa JoystickCameraState* joystick = joystickCameraState(joystickName); if (!joystick) { if (_joystickCameraStates.size() < JoystickInputStates::MaxNumJoysticks) { - _joystickCameraStates.push_back(JoystickCameraState()); + _joystickCameraStates.emplace_back(); joystick = &_joystickCameraStates.back(); joystick->joystickName = joystickName; } else { - LWARNING(fmt::format("Cannot add more joysticks, only {} joysticks are " - "supported", JoystickInputStates::MaxNumJoysticks)); + LWARNING(std::format( + "Cannot add more joysticks, only {} joysticks are supported", + JoystickInputStates::MaxNumJoysticks + )); return nullptr; } } diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp index d904f0201d..321b0b5f0d 100644 --- a/src/interaction/joystickinputstate.cpp +++ b/src/interaction/joystickinputstate.cpp @@ -36,7 +36,7 @@ namespace openspace::interaction { int JoystickInputStates::numAxes(const std::string& joystickName) const { if (joystickName.empty()) { int maxNumAxes = -1; - for (auto it = begin(); it < end(); ++it) { + for (auto it = begin(); it < end(); it++) { if (it->nAxes > maxNumAxes) { maxNumAxes = it->nAxes; } @@ -44,9 +44,9 @@ int JoystickInputStates::numAxes(const std::string& joystickName) const { return maxNumAxes; } - for (auto it = begin(); it < end(); ++it) { - if (it->name == joystickName) { - return it->nAxes; + for (const JoystickInputState& state : *this) { + if (state.name == joystickName) { + return state.nAxes; } } return -1; @@ -55,19 +55,20 @@ int JoystickInputStates::numAxes(const std::string& joystickName) const { int JoystickInputStates::numButtons(const std::string& joystickName) const { if (joystickName.empty()) { int maxNumButtons = -1; - for (auto it = begin(); it < end(); ++it) { - if (it->nButtons > maxNumButtons) { - maxNumButtons = it->nButtons; + for (const JoystickInputState& state : *this) { + if (state.nButtons > maxNumButtons) { + maxNumButtons = state.nButtons; } } return maxNumButtons; } - for (auto it = begin(); it < end(); ++it) { - if (it->name == joystickName) { - return it->nButtons; + for (const JoystickInputState& state : *this) { + if (state.name == joystickName) { + return state.nButtons; } } + return -1; } @@ -75,7 +76,7 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const ghoul_precondition(axis >= 0, "axis must be 0 or positive"); if (joystickName.empty()) { - float res = std::accumulate( + const float res = std::accumulate( begin(), end(), 0.f, @@ -93,18 +94,13 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const return res; } - const JoystickInputState* state = nullptr; - for (auto it = begin(); it < end(); ++it) { - if (it->name == joystickName) { - state = &(*it); + for (const JoystickInputState& state : *this) { + if (state.name == joystickName) { + return state.axes[axis]; } } - if (!state) { - return 0.f; - } - - return state->axes[axis]; + return 0.f; } bool JoystickInputStates::button(const std::string& joystickName, int button, @@ -113,7 +109,7 @@ bool JoystickInputStates::button(const std::string& joystickName, int button, ghoul_precondition(button >= 0, "button must be 0 or positive"); if (joystickName.empty()) { - bool res = std::any_of( + const bool res = std::any_of( begin(), end(), [button, action](const JoystickInputState& state) { @@ -123,18 +119,13 @@ bool JoystickInputStates::button(const std::string& joystickName, int button, return res; } - const JoystickInputState* state = nullptr; - for (auto it = begin(); it < end(); ++it) { - if (it->name == joystickName) { - state = &(*it); + for (const JoystickInputState& state : *this) { + if (state.name == joystickName) { + return state.isConnected ? (state.buttons[button] == action) : false; } } - if (!state) { - return false; - } - - return state->isConnected ? (state->buttons[button] == action) : false; + return false; } } // namespace openspace::interaction diff --git a/src/interaction/keybindingmanager.cpp b/src/interaction/keybindingmanager.cpp index 61c3e5ddfb..1e43f92526 100644 --- a/src/interaction/keybindingmanager.cpp +++ b/src/interaction/keybindingmanager.cpp @@ -37,14 +37,12 @@ namespace openspace::interaction { -KeybindingManager::KeybindingManager() {} - void KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action) { if (action == KeyAction::Press || action == KeyAction::Repeat) { // iterate over key bindings auto ret = _keyLua.equal_range({ key, modifier }); - for (auto it = ret.first; it != ret.second; ++it) { + for (auto it = ret.first; it != ret.second; it++) { ghoul_assert(!it->second.empty(), "Action must not be empty"); if (!global::actionManager->hasAction(it->second)) { // Silently ignoring the unknown action as the user might have intended to @@ -77,7 +75,7 @@ void KeybindingManager::bindKey(Key key, KeyModifier modifier, std::string actio #endif // WIN32 ghoul_assert(!action.empty(), "Action must not be empty"); - KeyWithModifier km = { key, modifier }; + const KeyWithModifier km = { key, modifier }; _keyLua.insert({ km, std::move(action) }); } @@ -92,7 +90,7 @@ void KeybindingManager::removeKeyBinding(const KeyWithModifier& key) { } else { // If it is not, we continue iteration - ++it; + it++; } } } @@ -103,7 +101,7 @@ std::vector> KeybindingManager::keyBindi std::vector> result; auto itRange = _keyLua.equal_range(key); - for (auto it = itRange.first; it != itRange.second; ++it) { + for (auto it = itRange.first; it != itRange.second; it++) { result.emplace_back(it->first, it->second); } return result; diff --git a/src/interaction/keybindingmanager_lua.inl b/src/interaction/keybindingmanager_lua.inl index 6343059530..a6d369110c 100644 --- a/src/interaction/keybindingmanager_lua.inl +++ b/src/interaction/keybindingmanager_lua.inl @@ -35,12 +35,12 @@ namespace { throw ghoul::lua::LuaError("Action must not be empty"); } if (!global::actionManager->hasAction(action)) { - throw ghoul::lua::LuaError(fmt::format("Action '{}' does not exist", action)); + throw ghoul::lua::LuaError(std::format("Action '{}' does not exist", action)); } openspace::KeyWithModifier iKey = openspace::stringToKey(key); if (iKey.key == openspace::Key::Unknown) { - throw ghoul::lua::LuaError(fmt::format("Could not find key '{}'", key)); + throw ghoul::lua::LuaError(std::format("Could not find key '{}'", key)); } global::keybindingManager->bindKey(iKey.key, iKey.modifier, std::move(action)); diff --git a/src/interaction/mousecamerastates.cpp b/src/interaction/mousecamerastates.cpp index 8b2121efcc..219183c061 100644 --- a/src/interaction/mousecamerastates.cpp +++ b/src/interaction/mousecamerastates.cpp @@ -28,9 +28,9 @@ #include namespace { - const double SENSITIVITY_ADJUSTMENT_INCREASE = 8.0; - const double SENSITIVITY_ADJUSTMENT_DECREASE = 0.5; -} + constexpr double SensitivityAdjustmentIncrease = 8.0; + constexpr double SensitivityAdjustmentDecrease = 0.5; +} // namespace namespace openspace::interaction { @@ -38,32 +38,35 @@ MouseCameraStates::MouseCameraStates(double sensitivity, double velocityScaleFac : CameraInteractionStates(sensitivity, velocityScaleFactor) {} -void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputState, - const KeyboardInputState& keyboardinputState, +void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseState, + const KeyboardInputState& keyboardState, double deltaTime) { - MouseButton primary = + const MouseButton primary = _isMouseButtonInverted ? MouseButton::Button2 : MouseButton::Button1; - MouseButton secondary = + const MouseButton secondary = _isMouseButtonInverted ? MouseButton::Button1 : MouseButton::Button2; - glm::dvec2 mousePosition = mouseinputState.mousePosition(); + const glm::dvec2 mousePosition = mouseState.mousePosition(); - bool primaryPressed = mouseinputState.isMouseButtonPressed(primary); - bool secondaryPressed = mouseinputState.isMouseButtonPressed(secondary); - bool button3Pressed = mouseinputState.isMouseButtonPressed(MouseButton::Button3); - bool keyCtrlPressed = keyboardinputState.isKeyPressed(Key::LeftControl) || - keyboardinputState.isKeyPressed(Key::RightControl); - bool keyShiftPressed = keyboardinputState.isKeyPressed(Key::LeftShift) || - keyboardinputState.isKeyPressed(Key::RightShift); - bool keyAltPressed = keyboardinputState.isKeyPressed(Key::LeftAlt) || - keyboardinputState.isKeyPressed(Key::RightAlt); + const bool primaryPressed = mouseState.isMouseButtonPressed(primary); + const bool secondaryPressed = mouseState.isMouseButtonPressed(secondary); + const bool button3Pressed = mouseState.isMouseButtonPressed(MouseButton::Button3); + const bool keyCtrlPressed = + keyboardState.isKeyPressed(Key::LeftControl) || + keyboardState.isKeyPressed(Key::RightControl); + const bool keyShiftPressed = + keyboardState.isKeyPressed(Key::LeftShift) || + keyboardState.isKeyPressed(Key::RightShift); + const bool keyAltPressed = + keyboardState.isKeyPressed(Key::LeftAlt) || + keyboardState.isKeyPressed(Key::RightAlt); // Update the mouse states if (primaryPressed && !keyShiftPressed && !keyAltPressed) { if (keyCtrlPressed) { - glm::dvec2 mousePositionDelta = _localRotationState.previousPosition - - mousePosition; + const glm::dvec2 mousePositionDelta = + _localRotationState.previousPosition - mousePosition; _localRotationState.velocity.set( mousePositionDelta * _sensitivity, deltaTime @@ -73,8 +76,8 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt _globalRotationState.velocity.decelerate(deltaTime); } else { - glm::dvec2 mousePositionDelta = _globalRotationState.previousPosition - - mousePosition; + const glm::dvec2 mousePositionDelta = + _globalRotationState.previousPosition - mousePosition; _globalRotationState.velocity.set( mousePositionDelta * _sensitivity, deltaTime @@ -92,15 +95,15 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt _globalRotationState.velocity.decelerate(deltaTime); } if (secondaryPressed || (keyAltPressed && primaryPressed)) { - glm::dvec2 mousePositionDelta = _truckMovementState.previousPosition - - mousePosition; + const glm::dvec2 mousePositionDelta = + _truckMovementState.previousPosition - mousePosition; double sensitivity = _sensitivity; - if (keyboardinputState.isKeyPressed(Key::Z)) { - sensitivity *= SENSITIVITY_ADJUSTMENT_INCREASE; + if (keyboardState.isKeyPressed(Key::Z)) { + sensitivity *= SensitivityAdjustmentIncrease; } - else if (keyboardinputState.isKeyPressed(Key::X)) { - sensitivity *= SENSITIVITY_ADJUSTMENT_DECREASE; + else if (keyboardState.isKeyPressed(Key::X)) { + sensitivity *= SensitivityAdjustmentDecrease; } _truckMovementState.velocity.set( @@ -114,7 +117,7 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt } if (button3Pressed || (keyShiftPressed && primaryPressed)) { if (keyCtrlPressed) { - glm::dvec2 mousePositionDelta = _localRollState.previousPosition - + const glm::dvec2 mousePositionDelta = _localRollState.previousPosition - mousePosition; _localRollState.velocity.set( mousePositionDelta * _sensitivity, @@ -125,7 +128,7 @@ void MouseCameraStates::updateStateFromInput(const MouseInputState& mouseinputSt _globalRollState.velocity.decelerate(deltaTime); } else { - glm::dvec2 mousePositionDelta = _globalRollState.previousPosition - + const glm::dvec2 mousePositionDelta = _globalRollState.previousPosition - mousePosition; _globalRollState.velocity.set( mousePositionDelta * _sensitivity, diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 9cb631505c..83d6c9fd33 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -120,9 +120,6 @@ SessionRecording::SessionRecording(bool isGlobal) } } -SessionRecording::~SessionRecording() { -} - void SessionRecording::deinitialize() { stopRecording(); stopPlayback(); @@ -132,7 +129,9 @@ void SessionRecording::setRecordDataFormat(DataMode dataMode) { _recordingDataMode = dataMode; } -bool SessionRecording::hasFileExtension(std::string filename, std::string extension) { +bool SessionRecording::hasFileExtension(const std::string& filename, + const std::string& extension) +{ if (filename.length() <= extension.length()) { return false; } @@ -142,12 +141,12 @@ bool SessionRecording::hasFileExtension(std::string filename, std::string extens } bool SessionRecording::isPath(std::string& filename) { - size_t unixDelimiter = filename.find("/"); - size_t windowsDelimiter = filename.find("\\"); + const size_t unixDelimiter = filename.find('/'); + const size_t windowsDelimiter = filename.find('\\'); return (unixDelimiter != std::string::npos || windowsDelimiter != std::string::npos); } -void SessionRecording::removeTrailingPathSlashes(std::string& filename) { +void SessionRecording::removeTrailingPathSlashes(std::string& filename) const { while (filename.substr(filename.length() - 1, 1) == "/") { filename.pop_back(); } @@ -184,8 +183,8 @@ bool SessionRecording::handleRecordingFile(std::string filenameIn) { std::filesystem::path absFilename = absPath("${RECORDINGS}/" + filenameIn); if (std::filesystem::is_regular_file(absFilename)) { - LERROR(fmt::format( - "Unable to start recording; file {} already exists", absFilename + LERROR(std::format( + "Unable to start recording; file '{}' already exists", absFilename )); return false; } @@ -197,7 +196,9 @@ bool SessionRecording::handleRecordingFile(std::string filenameIn) { } if (!_recordFile.is_open() || !_recordFile.good()) { - LERROR(fmt::format("Unable to open file {} for keyframe recording", absFilename)); + LERROR(std::format( + "Unable to open file '{}' for keyframe recording", absFilename + )); return false; } return true; @@ -217,7 +218,7 @@ bool SessionRecording::startRecording(const std::string& filename) { std::filesystem::create_directories(absPath("${RECORDINGS}")); } - bool recordingFileOK = handleRecordingFile(filename); + const bool recordingFileOK = handleRecordingFile(filename); if (recordingFileOK) { _state = SessionState::Recording; @@ -258,17 +259,17 @@ bool SessionRecording::startRecording(const std::string& filename) { } void SessionRecording::recordCurrentTimePauseState() { - bool isPaused = global::timeManager->isPaused(); + const bool isPaused = global::timeManager->isPaused(); std::string initialTimePausedCommand = "openspace.time.setPause(" + std::string(isPaused ? "true" : "false") + ")"; - saveScriptKeyframeToPropertiesBaseline(initialTimePausedCommand); + saveScriptKeyframeToPropertiesBaseline(std::move(initialTimePausedCommand)); } void SessionRecording::recordCurrentTimeRate() { - std::string initialTimeRateCommand = fmt::format( + std::string initialTimeRateCommand = std::format( "openspace.time.setDeltaTime({})", global::timeManager->targetDeltaTime() ); - saveScriptKeyframeToPropertiesBaseline(initialTimeRateCommand); + saveScriptKeyframeToPropertiesBaseline(std::move(initialTimeRateCommand)); } void SessionRecording::stopRecording() { @@ -298,8 +299,8 @@ void SessionRecording::stopRecording() { std::move(kf.position), std::move(kf.rotation), std::move(kf.focusNode), - std::move(kf.followFocusNodeRotation), - std::move(kf.scale) + kf.followFocusNodeRotation, + kf.scale ); saveSingleKeyframeCamera( kfMsg, @@ -388,7 +389,7 @@ bool SessionRecording::startPlayback(std::string& filename, // Open in ASCII first _playbackFile.open(_playbackFilename, std::ifstream::in); // Read header - std::string readBackHeaderString = readHeaderElement( + const std::string readBackHeaderString = readHeaderElement( _playbackFile, FileHeaderTitle.length() ); @@ -417,7 +418,7 @@ bool SessionRecording::startPlayback(std::string& filename, // past the header, version, and data type _playbackFile.close(); _playbackFile.open(_playbackFilename, std::ifstream::in | std::ios::binary); - size_t headerSize = FileHeaderTitle.length() + FileHeaderVersionLength + const size_t headerSize = FileHeaderTitle.length() + FileHeaderVersionLength + sizeof(DataFormatBinaryTag) + sizeof('\n'); std::vector hBuffer; hBuffer.resize(headerSize); @@ -425,8 +426,8 @@ bool SessionRecording::startPlayback(std::string& filename, } if (!_playbackFile.is_open() || !_playbackFile.good()) { - LERROR(fmt::format( - "Unable to open file {} for keyframe playback", absFilename.c_str() + LERROR(std::format( + "Unable to open file '{}' for keyframe playback", absFilename.c_str() )); stopPlayback(); cleanUpPlayback(); @@ -454,7 +455,7 @@ bool SessionRecording::startPlayback(std::string& filename, return false; } - bool canTriggerPlayback = global::openSpaceEngine->setMode( + const bool canTriggerPlayback = global::openSpaceEngine->setMode( OpenSpaceEngine::Mode::SessionRecordingPlayback ); @@ -463,7 +464,7 @@ bool SessionRecording::startPlayback(std::string& filename, return false; } - LINFO(fmt::format( + LINFO(std::format( "Playback session started: ({:8.3f},0.0,{:13.3f}) with {}/{}/{} entries, " "forceTime={}", now, _timestampPlaybackStarted_simulation, _keyframesCamera.size(), @@ -510,7 +511,7 @@ bool SessionRecording::initializePlayback_timeline() { return false; } if (_playbackForceSimTimeAtStart) { - Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps; + const Timestamps times = _timeline[_idxTimeline_cameraFirstInTimeline].t3stamps; global::timeManager->setTimeNextFrame(Time(times.timeSim)); _saveRenderingCurrentRecordedTime = times.timeRec; } @@ -638,9 +639,9 @@ void SessionRecording::cleanUpPlayback() { ghoul_assert(camera != nullptr, "Camera must not be nullptr"); Scene* scene = camera->parent()->scene(); if (!_timeline.empty()) { - unsigned int p = + const unsigned int p = _timeline[_idxTimeline_cameraPtrPrev].idxIntoKeyframeTypeArray; - if (_keyframesCamera.size() > 0) { + if (!_keyframesCamera.empty()) { const SceneGraphNode* n = scene->sceneGraphNode( _keyframesCamera[p].focusNode ); @@ -726,7 +727,7 @@ void SessionRecording::saveStringToFile(const std::string& s, std::ofstream& file) { size_t strLen = s.size(); - size_t writeSize_bytes = sizeof(size_t); + const size_t writeSize_bytes = sizeof(size_t); idx = 0; unsigned char const *p = reinterpret_cast(&strLen); @@ -738,18 +739,18 @@ void SessionRecording::saveStringToFile(const std::string& s, } bool SessionRecording::hasCameraChangedFromPrev( - datamessagestructures::CameraKeyframe kfNew) + const datamessagestructures::CameraKeyframe& kfNew) { constexpr double threshold = 1e-2; bool hasChanged = false; - glm::dvec3 positionDiff = kfNew._position - _prevRecordedCameraKeyframe._position; - if (glm::length(positionDiff) > threshold) { + const glm::dvec3 position = kfNew._position - _prevRecordedCameraKeyframe._position; + if (glm::length(position) > threshold) { hasChanged = true; } - double rotationDiff = dot(kfNew._rotation, _prevRecordedCameraKeyframe._rotation); - if (std::abs(rotationDiff - 1.0) > threshold) { + const double rotation = dot(kfNew._rotation, _prevRecordedCameraKeyframe._rotation); + if (std::abs(rotation - 1.0) > threshold) { hasChanged = true; } @@ -757,10 +758,12 @@ bool SessionRecording::hasCameraChangedFromPrev( return hasChanged; } -SessionRecording::Timestamps SessionRecording::generateCurrentTimestamp3(double kfTime) { +SessionRecording::Timestamps SessionRecording::generateCurrentTimestamp3( + double keyframeTime) const +{ return { - kfTime, - kfTime - _timestampRecordStarted, + keyframeTime, + keyframeTime - _timestampRecordStarted, global::timeManager->time().j2000Seconds() }; } @@ -778,7 +781,7 @@ void SessionRecording::saveCameraKeyframeToTimeline() { Timestamps times = generateCurrentTimestamp3(kf._timestamp); interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); - addKeyframe(times, pbFrame, _recordingEntryNum++); + addKeyframe(std::move(times), std::move(pbFrame), _recordingEntryNum++); } void SessionRecording::saveHeaderBinary(Timestamps& times, @@ -823,7 +826,7 @@ void SessionRecording::saveCameraKeyframeAscii(Timestamps& times, { if (_addModelMatrixinAscii) { SceneGraphNode* node = sceneGraphNode(kf._focusNode); - glm::dmat4 modelTransform = node->modelTransform(); + const glm::dmat4 modelTransform = node->modelTransform(); file << HeaderCommentAscii << ' ' << ghoul::to_string(modelTransform) << '\n'; } @@ -836,11 +839,11 @@ void SessionRecording::saveCameraKeyframeAscii(Timestamps& times, void SessionRecording::saveTimeKeyframeToTimeline() { // Create a time keyframe, then call to populate it with current time props - datamessagestructures::TimeKeyframe kf = + const datamessagestructures::TimeKeyframe kf = datamessagestructures::generateTimeKeyframe(); Timestamps times = generateCurrentTimestamp3(kf._timestamp); - addKeyframe(times, kf, _recordingEntryNum++); + addKeyframe(std::move(times), kf, _recordingEntryNum++); } void SessionRecording::saveTimeKeyframeBinary(Timestamps& times, @@ -867,33 +870,28 @@ void SessionRecording::saveTimeKeyframeAscii(Timestamps& times, } void SessionRecording::saveScriptKeyframeToTimeline(std::string script) { - if (doesStartWithSubstring(script, scriptReturnPrefix)) { + if (script.starts_with(scriptReturnPrefix)) { script = script.substr(scriptReturnPrefix.length()); } - for (std::string reject : _scriptRejects) { - if (doesStartWithSubstring(script, reject)) { + for (const std::string& reject : _scriptRejects) { + if (script.starts_with(reject)) { return; } } trimCommandsFromScriptIfFound(script); replaceCommandsFromScriptIfFound(script); - datamessagestructures::ScriptMessage sm + const datamessagestructures::ScriptMessage sm = datamessagestructures::generateScriptMessage(script); Timestamps times = generateCurrentTimestamp3(sm._timestamp); - addKeyframe(times, sm._script, _playbackLineNum); -} - -bool SessionRecording::doesStartWithSubstring(const std::string& s, - const std::string& matchSubstr) -{ - return s.substr(0, matchSubstr.length()) == matchSubstr; + addKeyframe(std::move(times), sm._script, _playbackLineNum); } void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script) { - Timestamps times = - generateCurrentTimestamp3(global::windowDelegate->applicationTime()); - size_t indexIntoScriptKeyframesFromMainTimeline = + const Timestamps times = generateCurrentTimestamp3( + global::windowDelegate->applicationTime() + ); + const size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesSavePropertiesBaseline_scripts.size(); _keyframesSavePropertiesBaseline_scripts.push_back(std::move(script)); addKeyframeToTimeline( @@ -906,7 +904,7 @@ void SessionRecording::saveScriptKeyframeToPropertiesBaseline(std::string script } void SessionRecording::trimCommandsFromScriptIfFound(std::string& script) { - for (std::string trimSnippet : _scriptsToBeTrimmed) { + for (const std::string& trimSnippet : _scriptsToBeTrimmed) { auto findIdx = script.find(trimSnippet); if (findIdx != std::string::npos) { auto findClosingParens = script.find_first_of(')', findIdx); @@ -916,7 +914,7 @@ void SessionRecording::trimCommandsFromScriptIfFound(std::string& script) { } void SessionRecording::replaceCommandsFromScriptIfFound(std::string& script) { - for (ScriptSubstringReplace replacementSnippet : _scriptsToBeReplaced) { + for (const ScriptSubstringReplace& replacementSnippet : _scriptsToBeReplaced) { auto findIdx = script.find(replacementSnippet.substringFound); if (findIdx != std::string::npos) { script.erase(findIdx, replacementSnippet.substringFound.length()); @@ -948,24 +946,24 @@ void SessionRecording::saveScriptKeyframeAscii(Timestamps& times, // Erase all \r (from windows newline), and all \n from line endings and replace with // ';' so that lua will treat them as separate lines. This is done in order to treat // a multi-line script as a single line in the file. - size_t startPos = sm._script.find("\r", 0); + size_t startPos = sm._script.find('\r', 0); while (startPos != std::string::npos) { sm._script.erase(startPos, 1); - startPos = sm._script.find("\r", startPos); + startPos = sm._script.find('\r', startPos); } - startPos = sm._script.find("\n", 0); + startPos = sm._script.find('\n', 0); while (startPos != std::string::npos) { sm._script.replace(startPos, 1, ";"); - startPos = sm._script.find("\n", startPos); + startPos = sm._script.find('\n', startPos); } sm.write(keyframeLine); saveKeyframeToFile(keyframeLine.str(), file); } void SessionRecording::savePropertyBaseline(properties::Property& prop) { - std::string propIdentifier = prop.fullyQualifiedIdentifier(); + const std::string propIdentifier = prop.fullyQualifiedIdentifier(); if (isPropertyAllowedForBaseline(propIdentifier)) { - bool isPropAlreadySaved = ( + const bool isPropAlreadySaved = ( std::find( _propertyBaselinesSaved.begin(), _propertyBaselinesSaved.end(), @@ -974,7 +972,7 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) { != _propertyBaselinesSaved.end() ); if (!isPropAlreadySaved) { - std::string initialScriptCommand = fmt::format( + const std::string initialScriptCommand = std::format( "openspace.setPropertyValueSingle(\"{}\", {})", propIdentifier, prop.stringValue() ); @@ -985,8 +983,8 @@ void SessionRecording::savePropertyBaseline(properties::Property& prop) { } bool SessionRecording::isPropertyAllowedForBaseline(const std::string& propString) { - for (std::string reject : _propertyBaselineRejects) { - if (doesStartWithSubstring(propString, reject)) { + for (const std::string& reject : _propertyBaselineRejects) { + if (propString.starts_with(reject)) { return false; } } @@ -1033,15 +1031,15 @@ void SessionRecording::render() { constexpr std::string_view FontName = "Mono"; constexpr float FontSizeFrameinfo = 32.f; - std::shared_ptr font = + const std::shared_ptr font = global::fontManager->font(FontName, FontSizeFrameinfo); - glm::vec2 res = global::renderEngine->fontResolution(); + const glm::vec2 res = global::renderEngine->fontResolution(); glm::vec2 penPosition = glm::vec2( res.x / 2 - 150.f, res.y / 4 ); - std::string text1 = std::to_string(currentTime()); + const std::string text1 = std::to_string(currentTime()); ghoul::fontrendering::RenderFont( *font, penPosition, @@ -1049,7 +1047,7 @@ void SessionRecording::render() { glm::vec4(1.f), ghoul::fontrendering::CrDirection::Down ); - std::string text2 = fmt::format( + const std::string text2 = std::format( "Scale: {}", global::navigationHandler->camera()->scaling() ); ghoul::fontrendering::RenderFont(*font, penPosition, text2, glm::vec4(1.f)); @@ -1083,8 +1081,8 @@ bool SessionRecording::playbackAddEntriesToTimeline() { unsigned char frameType = readFromPlayback(_playbackFile); // Check if have reached EOF if (!_playbackFile) { - LINFO(fmt::format( - "Finished parsing {} entries from playback file {}", + LINFO(std::format( + "Finished parsing {} entries from playback file '{}'", _playbackLineNum - 1, _playbackFilename )); break; @@ -1099,8 +1097,8 @@ bool SessionRecording::playbackAddEntriesToTimeline() { parsingStatusOk = playbackScript(); } else { - LERROR(fmt::format( - "Unknown frame type {} @ index {} of playback file {}", + LERROR(std::format( + "Unknown frame type {} @ index {} of playback file '{}'", frameType, _playbackLineNum - 1, _playbackFilename )); parsingStatusOk = false; @@ -1117,8 +1115,8 @@ bool SessionRecording::playbackAddEntriesToTimeline() { std::istringstream iss(_playbackLineParsing); std::string entryType; if (!(iss >> entryType)) { - LERROR(fmt::format( - "Error reading entry type @ line {} of playback file {}", + LERROR(std::format( + "Error reading entry type @ line {} of playback file '{}'", _playbackLineNum, _playbackFilename )); break; @@ -1137,16 +1135,16 @@ bool SessionRecording::playbackAddEntriesToTimeline() { continue; } else { - LERROR(fmt::format( - "Unknown frame type {} @ line {} of playback file {}", + LERROR(std::format( + "Unknown frame type {} @ line {} of playback file '{}'", entryType, _playbackLineNum, _playbackFilename )); parsingStatusOk = false; break; } } - LINFO(fmt::format( - "Finished parsing {} entries from playback file {}", + LINFO(std::format( + "Finished parsing {} entries from playback file '{}'", _playbackLineNum, _playbackFilename )); } @@ -1249,7 +1247,7 @@ bool SessionRecording::playbackCamera() { _playbackLineNum ); - interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); + const interaction::KeyframeNavigator::CameraPose pbFrame(std::move(kf)); if (success) { success = addKeyframe( {times.timeOs, times.timeRec, times.timeSim}, @@ -1267,7 +1265,7 @@ bool SessionRecording::convertCamera(std::stringstream& inStream, DataMode mode, Timestamps times; datamessagestructures::CameraKeyframe kf; - bool success = readSingleKeyframeCamera( + const bool success = readSingleKeyframeCamera( kf, times, mode, @@ -1325,14 +1323,14 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times, kf.read(&file); } catch (std::bad_alloc&) { - LERROR(fmt::format( + LERROR(std::format( "Allocation error with camera playback from keyframe entry {}", lineN - 1 )); return false; } catch (std::length_error&) { - LERROR(fmt::format( + LERROR(std::format( "length_error with camera playback from keyframe entry {}", lineN - 1 )); @@ -1340,7 +1338,7 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times, } if (!file) { - LINFO(fmt::format( + LINFO(std::format( "Error reading camera playback from keyframe entry {}", lineN - 1 )); @@ -1351,13 +1349,11 @@ bool SessionRecording::readCameraKeyframeBinary(Timestamps& times, bool SessionRecording::readCameraKeyframeAscii(Timestamps& times, datamessagestructures::CameraKeyframe& kf, - std::string currentParsingLine, + const std::string& currentParsingLine, int lineN) { - std::string rotationFollowing; + std::istringstream iss = std::istringstream(currentParsingLine); std::string entryType; - - std::istringstream iss(currentParsingLine); iss >> entryType; iss >> times.timeOs >> times.timeRec >> times.timeSim; kf.read(iss); @@ -1365,7 +1361,7 @@ bool SessionRecording::readCameraKeyframeAscii(Timestamps& times, kf._timestamp = times.timeOs; if (iss.fail() || !iss.eof()) { - LERROR(fmt::format("Error parsing camera line {} of playback file", lineN)); + LERROR(std::format("Error parsing camera line {} of playback file", lineN)); return false; } return true; @@ -1402,7 +1398,7 @@ bool SessionRecording::convertTimeChange(std::stringstream& inStream, DataMode m Timestamps times; datamessagestructures::TimeKeyframe kf; - bool success = readSingleKeyframeTime( + const bool success = readSingleKeyframeTime( kf, times, mode, @@ -1457,14 +1453,14 @@ bool SessionRecording::readTimeKeyframeBinary(Timestamps& times, kf.read(&file); } catch (std::bad_alloc&) { - LERROR(fmt::format( + LERROR(std::format( "Allocation error with time playback from keyframe entry {}", lineN - 1 )); return false; } catch (std::length_error&) { - LERROR(fmt::format( + LERROR(std::format( "length_error with time playback from keyframe entry {}", lineN - 1 )); @@ -1472,7 +1468,7 @@ bool SessionRecording::readTimeKeyframeBinary(Timestamps& times, } if (!file) { - LERROR(fmt::format( + LERROR(std::format( "Error reading time playback from keyframe entry {}", lineN - 1 )); return false; @@ -1482,7 +1478,7 @@ bool SessionRecording::readTimeKeyframeBinary(Timestamps& times, bool SessionRecording::readTimeKeyframeAscii(Timestamps& times, datamessagestructures::TimeKeyframe& kf, - std::string currentParsingLine, + const std::string& currentParsingLine, int lineN) { std::string entryType; @@ -1493,7 +1489,7 @@ bool SessionRecording::readTimeKeyframeAscii(Timestamps& times, kf.read(iss); if (iss.fail() || !iss.eof()) { - LERROR(fmt::format( + LERROR(std::format( "Error parsing time line {} of playback file", lineN )); return false; @@ -1502,18 +1498,18 @@ bool SessionRecording::readTimeKeyframeAscii(Timestamps& times, } std::string SessionRecording::readHeaderElement(std::ifstream& stream, - size_t readLen_chars) + size_t readLenChars) { - std::vector readTemp(readLen_chars); - stream.read(&readTemp[0], readLen_chars); + std::vector readTemp(readLenChars); + stream.read(readTemp.data(), readLenChars); return std::string(readTemp.begin(), readTemp.end()); } std::string SessionRecording::readHeaderElement(std::stringstream& stream, - size_t readLen_chars) + size_t readLenChars) { - std::vector readTemp(readLen_chars); - stream.read(&readTemp[0], readLen_chars); + std::vector readTemp = std::vector(readLenChars); + stream.read(readTemp.data(), readLenChars); return std::string(readTemp.begin(), readTemp.end()); } @@ -1543,7 +1539,7 @@ bool SessionRecording::playbackScript() { } void SessionRecording::populateListofLoadedSceneGraphNodes() { - std::vector nodes = + const std::vector nodes = global::renderEngine->scene()->allSceneGraphNodes(); for (SceneGraphNode* n : nodes) { _loadedNodes.push_back(n->identifier()); @@ -1555,20 +1551,19 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { s.erase(0, scriptReturnPrefix.length()); } // This works for both setPropertyValue and setPropertyValueSingle - bool containsSetPropertyVal = (s.rfind("openspace.setPropertyValue", 0) == 0); - bool containsParensStart = (s.find("(") != std::string::npos); + const bool containsSetPropertyVal = (s.rfind("openspace.setPropertyValue", 0) == 0); + const bool containsParensStart = (s.find('(') != std::string::npos); if (containsSetPropertyVal && containsParensStart) { - std::string subjectOfSetProp = isolateTermFromQuotes(s.substr(s.find("(") + 1)); + std::string subjectOfSetProp = isolateTermFromQuotes(s.substr(s.find('(') + 1)); if (checkForScenegraphNodeAccessNav(subjectOfSetProp)) { - size_t commaPos = s.find(","); + const size_t commaPos = s.find(','); std::string navNode = isolateTermFromQuotes(s.substr(commaPos + 1)); if (navNode != "nil") { - std::vector::iterator it = - std::find(_loadedNodes.begin(), _loadedNodes.end(), navNode); + auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), navNode); if (it == _loadedNodes.end()) { - LWARNING(fmt::format( - "Playback file contains a property setting of navigation using" - " scenegraph node '{}', which is not currently loaded", navNode + LWARNING(std::format( + "Playback file contains a property setting of navigation using " + "scenegraph node '{}', which is not currently loaded", navNode )); } } @@ -1576,14 +1571,14 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { else if (checkForScenegraphNodeAccessScene(subjectOfSetProp)) { std::string found = extractScenegraphNodeFromScene(subjectOfSetProp); if (!found.empty()) { - std::vector matchHits = + const std::vector matchHits = global::renderEngine->scene()->propertiesMatchingRegex( subjectOfSetProp ); if (matchHits.empty()) { - LWARNING(fmt::format( - "Playback file contains a property setting of scenegraph" - " node '{}', which is not currently loaded", found + LWARNING(std::format( + "Playback file contains a property setting of scenegraph " + "node '{}', which is not currently loaded", found )); } } @@ -1591,17 +1586,17 @@ void SessionRecording::checkIfScriptUsesScenegraphNode(std::string s) { } } -bool SessionRecording::checkForScenegraphNodeAccessScene(std::string& s) { +bool SessionRecording::checkForScenegraphNodeAccessScene(const std::string& s) { const std::string scene = "Scene."; return (s.find(scene) != std::string::npos); } -std::string SessionRecording::extractScenegraphNodeFromScene(std::string& s) { +std::string SessionRecording::extractScenegraphNodeFromScene(const std::string& s) { const std::string scene = "Scene."; std::string extracted; - size_t posScene = s.find(scene); + const size_t posScene = s.find(scene); if (posScene != std::string::npos) { - size_t posDot = s.find(".", posScene + scene.length() + 1); + const size_t posDot = s.find('.', posScene + scene.length() + 1); if (posDot > posScene && posDot != std::string::npos) { extracted = s.substr(posScene + scene.length(), posDot - (posScene + scene.length())); @@ -1612,9 +1607,9 @@ std::string SessionRecording::extractScenegraphNodeFromScene(std::string& s) { bool SessionRecording::checkForScenegraphNodeAccessNav(std::string& navTerm) { const std::string nextTerm = "NavigationHandler.OrbitalNavigator."; - size_t posNav = navTerm.find(nextTerm); + const size_t posNav = navTerm.find(nextTerm); if (posNav != std::string::npos) { - for (std::string accessName : _navScriptsUsingNodes) { + for (const std::string& accessName : _navScriptsUsingNodes) { if (navTerm.find(accessName) != std::string::npos) { return true; } @@ -1632,14 +1627,14 @@ std::string SessionRecording::isolateTermFromQuotes(std::string s) { while (possibleQuotes.find(s.front()) != std::string::npos) { s.erase(0, 1); } - for (char q : possibleQuotes) { + for (const char q : possibleQuotes) { if (s.find(q) != std::string::npos) { s = s.substr(0, s.find(q)); return s; } } //If no quotes found, remove other possible characters from end - std::string unwantedChars = " );"; + const std::string unwantedChars = " );"; while (!s.empty() && (unwantedChars.find(s.back()) != std::string::npos)) { s.pop_back(); } @@ -1652,10 +1647,10 @@ void SessionRecording::eraseSpacesFromString(std::string& s) { std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) { std::string result; - char quote = s.at(0); + const char quote = s.at(0); // Handle either ' or " marks if (quote == '\'' || quote == '\"') { - size_t quoteCount = std::count(s.begin(), s.end(), quote); + const size_t quoteCount = std::count(s.begin(), s.end(), quote); // Must be an opening and closing quote char if (quoteCount == 2) { result = s.substr(1, s.rfind(quote) - 1); @@ -1664,18 +1659,20 @@ std::string SessionRecording::getNameFromSurroundingQuotes(std::string& s) { return result; } -bool SessionRecording::checkIfInitialFocusNodeIsLoaded(unsigned int camIdx1) { - if (_keyframesCamera.size() > 0) { - std::string startFocusNode - = _keyframesCamera[_timeline[camIdx1].idxIntoKeyframeTypeArray].focusNode; - auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), startFocusNode); - if (it == _loadedNodes.end()) { - LERROR(fmt::format( - "Playback file requires scenegraph node '{}', which is " - "not currently loaded", startFocusNode - )); - return false; - } +bool SessionRecording::checkIfInitialFocusNodeIsLoaded(unsigned int firstCamIndex) { + if (_keyframesCamera.empty()) { + return true; + } + + std::string startFocusNode = + _keyframesCamera[_timeline[firstCamIndex].idxIntoKeyframeTypeArray].focusNode; + auto it = std::find(_loadedNodes.begin(), _loadedNodes.end(), startFocusNode); + if (it == _loadedNodes.end()) { + LERROR(std::format( + "Playback file requires scenegraph node '{}', which is " + "not currently loaded", startFocusNode + )); + return false; } return true; } @@ -1688,7 +1685,7 @@ bool SessionRecording::convertScript(std::stringstream& inStream, DataMode mode, Timestamps times; datamessagestructures::ScriptMessage kf; - bool success = readSingleKeyframeScript( + const bool success = readSingleKeyframeScript( kf, times, mode, @@ -1746,14 +1743,14 @@ bool SessionRecording::readScriptKeyframeBinary(Timestamps& times, kf.read(&file); } catch (std::bad_alloc&) { - LERROR(fmt::format( + LERROR(std::format( "Allocation error with script playback from keyframe entry {}", lineN - 1 )); return false; } catch (std::length_error&) { - LERROR(fmt::format( + LERROR(std::format( "length_error with script playback from keyframe entry {}", lineN - 1 )); @@ -1761,7 +1758,7 @@ bool SessionRecording::readScriptKeyframeBinary(Timestamps& times, } if (!file) { - LERROR(fmt::format( + LERROR(std::format( "Error reading script playback from keyframe entry {}", lineN - 1 )); @@ -1772,7 +1769,8 @@ bool SessionRecording::readScriptKeyframeBinary(Timestamps& times, bool SessionRecording::readScriptKeyframeAscii(Timestamps& times, datamessagestructures::ScriptMessage& kf, - std::string currentParsingLine, int lineN) + const std::string& currentParsingLine, + int lineN) { std::string entryType; std::istringstream iss(currentParsingLine); @@ -1780,14 +1778,11 @@ bool SessionRecording::readScriptKeyframeAscii(Timestamps& times, iss >> times.timeOs >> times.timeRec >> times.timeSim; kf.read(iss); if (iss.fail()) { - LERROR(fmt::format( - "Error parsing script line {} of playback file", lineN - )); + LERROR(std::format("Error parsing script line {} of playback file", lineN)); return false; - } else if (!iss.eof()) { - LERROR(fmt::format( - "Did not find an EOL at line {} of playback file", lineN - )); + } + else if (!iss.eof()) { + LERROR(std::format("Did not find an EOL at line {} of playback file", lineN)); return false; } return true; @@ -1806,7 +1801,7 @@ bool SessionRecording::addKeyframeToTimeline(std::vector& timelin }); } catch(...) { - LERROR(fmt::format( + LERROR(std::format( "Timeline memory allocation error trying to add keyframe {}. The playback " "file may be too large for system memory", lineNum - 1 @@ -1820,7 +1815,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps, interaction::KeyframeNavigator::CameraPose keyframe, int lineNum) { - size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size(); + const size_t indexIntoCameraKeyframesFromMainTimeline = _keyframesCamera.size(); _keyframesCamera.push_back(std::move(keyframe)); return addKeyframeToTimeline( _timeline, @@ -1835,7 +1830,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps, datamessagestructures::TimeKeyframe keyframe, int lineNum) { - size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size(); + const size_t indexIntoTimeKeyframesFromMainTimeline = _keyframesTime.size(); _keyframesTime.push_back(std::move(keyframe)); return addKeyframeToTimeline( _timeline, @@ -1850,7 +1845,7 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps, std::string scriptToQueue, int lineNum) { - size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size(); + const size_t indexIntoScriptKeyframesFromMainTimeline = _keyframesScript.size(); _keyframesScript.push_back(std::move(scriptToQueue)); return addKeyframeToTimeline( _timeline, @@ -1864,14 +1859,14 @@ bool SessionRecording::addKeyframe(Timestamps t3stamps, void SessionRecording::moveAheadInTime() { using namespace std::chrono; - bool playbackPaused = (_state == SessionState::PlaybackPaused); + const bool playbackPaused = (_state == SessionState::PlaybackPaused); if (playbackPaused) { _playbackPauseOffset += global::windowDelegate->applicationTime() - _previousTime; } _previousTime = global::windowDelegate->applicationTime(); - double currTime = currentTime(); + const double currTime = currentTime(); lookForNonCameraKeyframesThatHaveComeDue(currTime); updateCameraWithOrWithoutNewKeyframes(currTime); // Unfortunately the first frame is sometimes rendered because globebrowsing reports @@ -1923,12 +1918,11 @@ void SessionRecording::updateCameraWithOrWithoutNewKeyframes(double currTime) { return; } - bool didFindFutureCameraKeyframes = findNextFutureCameraIndex(currTime); - - bool isPrevAtFirstKeyframe = (_idxTimeline_cameraPtrPrev == - _idxTimeline_cameraFirstInTimeline); - bool isFirstTimelineCameraKeyframeInFuture = (currTime < - _cameraFirstInTimeline_timestamp); + const bool didFindFutureCameraKeyframes = findNextFutureCameraIndex(currTime); + const bool isPrevAtFirstKeyframe = + (_idxTimeline_cameraPtrPrev == _idxTimeline_cameraFirstInTimeline); + const bool isFirstTimelineCameraKeyframeInFuture = + (currTime < _cameraFirstInTimeline_timestamp); if (! (isPrevAtFirstKeyframe && isFirstTimelineCameraKeyframeInFuture)) { processCameraKeyframe(currTime); @@ -1939,8 +1933,8 @@ void SessionRecording::updateCameraWithOrWithoutNewKeyframes(double currTime) { } bool SessionRecording::isTimeToHandleNextNonCameraKeyframe(double currTime) { - bool isNonCameraPlaybackActive = (_playbackActive_time || _playbackActive_script); - return (currTime > getNextTimestamp()) && isNonCameraPlaybackActive; + const bool nonCameraPlaybackActive = (_playbackActive_time || _playbackActive_script); + return (currTime > getNextTimestamp()) && nonCameraPlaybackActive; } bool SessionRecording::findNextFutureCameraIndex(double currTime) { @@ -1952,9 +1946,9 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) { } if (doesTimelineEntryContainCamera(seekAheadIndex)) { - unsigned int indexIntoCameraKeyframes = + const unsigned int indexIntoCameraKeyframes = _timeline[seekAheadIndex].idxIntoKeyframeTypeArray; - double seekAheadKeyframeTimestamp + const double seekAheadKeyframeTimestamp = appropriateTimestamp(_timeline[seekAheadIndex].t3stamps); if (indexIntoCameraKeyframes >= (_keyframesCamera.size() - 1)) { @@ -1974,7 +1968,7 @@ bool SessionRecording::findNextFutureCameraIndex(double currTime) { } } - double interpolationUpperBoundTimestamp = + const double interpolationUpperBoundTimestamp = appropriateTimestamp(_timeline[_idxTimeline_cameraPtrNext].t3stamps); if ((currTime > interpolationUpperBoundTimestamp) && _hasHitEndOfCameraKeyframes) { @@ -2010,7 +2004,7 @@ bool SessionRecording::processNextNonCameraKeyframeAheadInTime() { _idxScript = _timeline[_idxTimeline_nonCamera].idxIntoKeyframeTypeArray; return processScriptKeyframe(); default: - LERROR(fmt::format( + LERROR(std::format( "Bad keyframe type encountered during playback at index {}", _idxTimeline_nonCamera )); @@ -2034,8 +2028,8 @@ bool SessionRecording::processCameraKeyframe(double now) { interaction::KeyframeNavigator::CameraPose nextPose; interaction::KeyframeNavigator::CameraPose prevPose; - unsigned int prevIdx; - unsigned int nextIdx; + unsigned int prevIdx = 0; + unsigned int nextIdx = 0; if (!_playbackActive_camera) { return false; } @@ -2050,19 +2044,16 @@ bool SessionRecording::processCameraKeyframe(double now) { } // getPrevTimestamp(); - double prevTime = appropriateTimestamp( + const double prevTime = appropriateTimestamp( _timeline[_idxTimeline_cameraPtrPrev].t3stamps ); // getNextTimestamp(); - double nextTime = appropriateTimestamp( + const double nextTime = appropriateTimestamp( _timeline[_idxTimeline_cameraPtrNext].t3stamps ); - double t; - if ((nextTime - prevTime) < 1e-7) { - t = 0; - } - else { + double t = 0.0; + if ((nextTime - prevTime) >= 1e-7) { t = (now - prevTime) / (nextTime - prevTime); } @@ -2092,24 +2083,20 @@ bool SessionRecording::processCameraKeyframe(double now) { } bool SessionRecording::processScriptKeyframe() { - if (!_playbackActive_script) { + if (!_playbackActive_script || _keyframesScript.empty()) { return false; } - else if (_keyframesScript.empty()) { - return false; - } - else { - std::string nextScript = nextKeyframeObj( - _idxScript, - _keyframesScript, - ([this]() { signalPlaybackFinishedForComponent(RecordedType::Script); }) - ); - global::scriptEngine->queueScript( - nextScript, - scripting::ScriptEngine::ShouldBeSynchronized::Yes, - scripting::ScriptEngine::ShouldSendToRemote::Yes - ); - } + + const std::string nextScript = nextKeyframeObj( + _idxScript, + _keyframesScript, + ([this]() { signalPlaybackFinishedForComponent(RecordedType::Script); }) + ); + global::scriptEngine->queueScript( + nextScript, + scripting::ScriptEngine::ShouldBeSynchronized::Yes, + scripting::ScriptEngine::ShouldSendToRemote::Yes + ); return true; } @@ -2177,14 +2164,14 @@ void SessionRecording::saveKeyframeToFileBinary(unsigned char* buffer, file.write(reinterpret_cast(buffer), size); } -void SessionRecording::saveKeyframeToFile(std::string entry, std::ofstream& file) { - file << std::move(entry) << std::endl; +void SessionRecording::saveKeyframeToFile(const std::string& entry, std::ofstream& file) { + file << entry << '\n'; } SessionRecording::CallbackHandle SessionRecording::addStateChangeCallback( StateChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _stateChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } @@ -2223,7 +2210,7 @@ std::vector SessionRecording::playbackList() const { DWORD attributes = GetFileAttributes(e.path().string().c_str()); bool isHidden = attributes & FILE_ATTRIBUTE_HIDDEN; #else - bool isHidden = filename.find(".") == 0; + const bool isHidden = filename.find('.') == 0; #endif // WIN32 if (!isHidden) { // Don't add hidden files @@ -2239,7 +2226,7 @@ void SessionRecording::readPlaybackHeader_stream(std::stringstream& conversionIn std::string& version, DataMode& mode) { // Read header - std::string readBackHeaderString = readHeaderElement( + const std::string readBackHeaderString = readHeaderElement( conversionInStream, FileHeaderTitle.length() ); @@ -2262,13 +2249,15 @@ void SessionRecording::readPlaybackHeader_stream(std::stringstream& conversionIn readHeaderElement(conversionInStream, 1); } -SessionRecording::DataMode SessionRecording::readModeFromHeader(std::string filename) { - DataMode mode; +SessionRecording::DataMode SessionRecording::readModeFromHeader( + const std::string& filename) +{ + DataMode mode = DataMode::Unknown; std::ifstream inputFile; // Open in ASCII first inputFile.open(filename, std::ifstream::in); // Read header - std::string readBackHeaderString = readHeaderElement( + const std::string readBackHeaderString = readHeaderElement( inputFile, FileHeaderTitle.length() ); @@ -2295,12 +2284,13 @@ void SessionRecording::readFileIntoStringStream(std::string filename, { std::filesystem::path conversionInFilename = absPath(filename); if (!std::filesystem::is_regular_file(conversionInFilename)) { - throw ConversionError(fmt::format( - "Cannot find the specified playback file {} to convert", conversionInFilename + throw ConversionError(std::format( + "Cannot find the specified playback file '{}' to convert", + conversionInFilename )); } - DataMode mode = readModeFromHeader(conversionInFilename.string()); + const DataMode mode = readModeFromHeader(conversionInFilename.string()); stream.str(""); stream.clear(); @@ -2313,15 +2303,16 @@ void SessionRecording::readFileIntoStringStream(std::string filename, } stream << inputFstream.rdbuf(); if (!inputFstream.is_open() || !inputFstream.good()) { - throw ConversionError(fmt::format( - "Unable to open file {} for conversion", filename.c_str() + throw ConversionError(std::format( + "Unable to open file '{}' for conversion", filename )); } inputFstream.close(); } void SessionRecording::convertFileRelativePath(std::string filenameRelative) { - convertFile(absPath(filenameRelative).string()); + const std::filesystem::path path = absPath(std::move(filenameRelative)); + convertFile(path.string()); } std::string SessionRecording::convertFile(std::string filename, int depth) { @@ -2335,14 +2326,14 @@ std::string SessionRecording::convertFile(std::string filename, int depth) { std::string newFilename = filename; try { readFileIntoStringStream(filename, conversionInFile, conversionInStream); - DataMode mode; + DataMode mode = DataMode::Unknown; std::string fileVersion; readPlaybackHeader_stream( conversionInStream, fileVersion, mode ); - int conversionLineNum = 1; + const int conversionLineNum = 1; // If this instance of the SessionRecording class isn't the instance with the // correct version of the file to be converted, then call getLegacy() to recurse @@ -2364,9 +2355,9 @@ std::string SessionRecording::convertFile(std::string filename, int depth) { } if (depth != 0) { conversionOutFilename = determineConversionOutFilename(filename, mode); - LINFO(fmt::format( - "Starting conversion on rec file {}, version {} in {} mode. " - "Writing result to {}", + LINFO(std::format( + "Starting conversion on rec file '{}', version {} in {} mode. " + "Writing result to '{}'", newFilename, fileVersion, (mode == DataMode::Ascii) ? "ascii" : "binary", conversionOutFilename )); @@ -2378,9 +2369,9 @@ std::string SessionRecording::convertFile(std::string filename, int depth) { conversionOutFile.open(conversionOutFilename); } if (!conversionOutFile.is_open() || !conversionOutFile.good()) { - LERROR(fmt::format( - "Unable to open file {} for conversion result", - conversionOutFilename.c_str() + LERROR(std::format( + "Unable to open file '{}' for conversion result", + conversionOutFilename )); return ""; } @@ -2431,8 +2422,8 @@ bool SessionRecording::convertEntries(std::string& inFilename, unsigned char frameType = readFromPlayback(inStream); // Check if have reached EOF if (!inStream) { - LINFO(fmt::format( - "Finished converting {} entries from playback file {}", + LINFO(std::format( + "Finished converting {} entries from playback file '{}'", lineNum - 1, inFilename )); break; @@ -2474,8 +2465,8 @@ bool SessionRecording::convertEntries(std::string& inFilename, } } else { - LERROR(fmt::format( - "Unknown frame type {} @ index {} of conversion file {}", + LERROR(std::format( + "Unknown frame type {} @ index {} of conversion file '{}'", frameType, lineNum - 1, inFilename )); conversionStatusOk = false; @@ -2490,8 +2481,8 @@ bool SessionRecording::convertEntries(std::string& inFilename, std::istringstream iss(lineParsing); std::string entryType; if (!(iss >> entryType)) { - LERROR(fmt::format( - "Error reading entry type @ line {} of conversion file {}", + LERROR(std::format( + "Error reading entry type @ line {} of conversion file '{}'", lineNum, inFilename )); break; @@ -2537,15 +2528,15 @@ bool SessionRecording::convertEntries(std::string& inFilename, continue; } else { - LERROR(fmt::format( - "Unknown frame type {} @ line {} of conversion file {}", + LERROR(std::format( + "Unknown frame type {} @ line {} of conversion file '{}'", entryType, lineNum, inFilename )); conversionStatusOk = false; } } - LINFO(fmt::format( - "Finished parsing {} entries from conversion file {}", + LINFO(std::format( + "Finished parsing {} entries from conversion file '{}'", lineNum, inFilename )); } @@ -2554,7 +2545,7 @@ bool SessionRecording::convertEntries(std::string& inFilename, std::string SessionRecording::getLegacyConversionResult(std::string filename, int depth) { SessionRecording_legacy_0085 legacy; - return legacy.convertFile(filename, depth); + return legacy.convertFile(std::move(filename), depth); } std::string SessionRecording_legacy_0085::getLegacyConversionResult(std::string filename, @@ -2562,9 +2553,9 @@ std::string SessionRecording_legacy_0085::getLegacyConversionResult(std::string { // This method is overriden in each legacy subclass, but does nothing in this instance // as the oldest supported legacy version. - LERROR(fmt::format( + LERROR(std::format( "Version 00.85 is the oldest supported legacy file format; no conversion " - "can be made. It is possible that file {} has a corrupted header or an invalid " + "can be made. It is possible that file '{}' has a corrupted header or an invalid " "file format version number", filename )); @@ -2579,15 +2570,15 @@ std::string SessionRecording::targetFileFormatVersion() { return std::string(FileHeaderVersion); } -std::string SessionRecording::determineConversionOutFilename(const std::string filename, +std::string SessionRecording::determineConversionOutFilename(const std::string& filename, DataMode mode) { std::string filenameSansExtension = filename; - std::string fileExtension = (mode == DataMode::Binary) ? + const std::string fileExtension = (mode == DataMode::Binary) ? FileExtensionBinary : FileExtensionAscii; - if (filename.find_last_of(".") != std::string::npos) { - filenameSansExtension = filename.substr(0, filename.find_last_of(".")); + if (filename.find_last_of('.') != std::string::npos) { + filenameSansExtension = filename.substr(0, filename.find_last_of('.')); } filenameSansExtension += "_" + fileFormatVersion() + "-" + targetFileFormatVersion(); return filenameSansExtension + fileExtension; @@ -2602,7 +2593,7 @@ bool SessionRecording_legacy_0085::convertScript(std::stringstream& inStream, Timestamps times; ScriptMessage_legacy_0085 kf; - bool success = readSingleKeyframeScript( + const bool success = readSingleKeyframeScript( kf, times, mode, @@ -2633,7 +2624,8 @@ scripting::LuaLibrary SessionRecording::luaLibrary() { codegen::lua::FileFormatConversion, codegen::lua::SetPlaybackPause, codegen::lua::TogglePlaybackPause, - codegen::lua::IsPlayingBack + codegen::lua::IsPlayingBack, + codegen::lua::IsRecording } }; } diff --git a/src/interaction/sessionrecording_lua.inl b/src/interaction/sessionrecording_lua.inl index 6b76b6cf49..1fb6164865 100644 --- a/src/interaction/sessionrecording_lua.inl +++ b/src/interaction/sessionrecording_lua.inl @@ -202,6 +202,11 @@ namespace { return openspace::global::sessionRecording->isPlayingBack(); } +// Returns true if session recording is currently recording a recording. +[[codegen::luawrap]] bool isRecording() { + return openspace::global::sessionRecording->isRecording(); +} + #include "sessionrecording_lua_codegen.cpp" } // namespace diff --git a/src/interaction/tasks/convertrecfileversiontask.cpp b/src/interaction/tasks/convertrecfileversiontask.cpp index 0ecf27d203..930f7a0112 100644 --- a/src/interaction/tasks/convertrecfileversiontask.cpp +++ b/src/interaction/tasks/convertrecfileversiontask.cpp @@ -54,7 +54,7 @@ ConvertRecFileVersionTask::ConvertRecFileVersionTask(const ghoul::Dictionary& di ghoul_assert(std::filesystem::is_regular_file(_inFilePath), "The file must exist"); if (!std::filesystem::is_regular_file(_inFilePath)) { - LERROR(fmt::format("Failed to load session recording file: {}", _inFilePath)); + LERROR(std::format("Failed to load session recording file: {}", _inFilePath)); } else { sessRec = new SessionRecording(false); @@ -62,14 +62,12 @@ ConvertRecFileVersionTask::ConvertRecFileVersionTask(const ghoul::Dictionary& di } ConvertRecFileVersionTask::~ConvertRecFileVersionTask() { - if (sessRec != nullptr) { - delete sessRec; - } + delete sessRec; } std::string ConvertRecFileVersionTask::description() { - std::string description = fmt::format( - "Convert file format of session recording file {} to current version", + std::string description = std::format( + "Convert file format of session recording file '{}' to current version", _inFilePath ); return description; @@ -80,17 +78,17 @@ void ConvertRecFileVersionTask::perform(const Task::ProgressCallback&) { } void ConvertRecFileVersionTask::convert() { - bool hasBinaryFileExtension = sessRec->hasFileExtension( + const bool hasBinaryFileExtension = SessionRecording::hasFileExtension( _inFilename, SessionRecording::FileExtensionBinary ); - bool hasAsciiFileExtension = sessRec->hasFileExtension( + const bool hasAsciiFileExtension = SessionRecording::hasFileExtension( _inFilename, SessionRecording::FileExtensionAscii ); if (!hasBinaryFileExtension && !hasAsciiFileExtension) { - LERROR(fmt::format( - "Input filename does not have expected {} or {} extension", + LERROR(std::format( + "Input filename does not have expected '{}' or '{}' extension", SessionRecording::FileExtensionBinary, SessionRecording::FileExtensionAscii )); return; @@ -115,4 +113,4 @@ documentation::Documentation ConvertRecFileVersionTask::documentation() { }; } -} +} // namespace openspace::interaction diff --git a/src/interaction/tasks/convertrecformattask.cpp b/src/interaction/tasks/convertrecformattask.cpp index b5a95c70a9..b8010199fb 100644 --- a/src/interaction/tasks/convertrecformattask.cpp +++ b/src/interaction/tasks/convertrecformattask.cpp @@ -38,6 +38,17 @@ namespace { constexpr std::string_view KeyInFilePath = "InputFilePath"; constexpr std::string_view KeyOutFilePath = "OutputFilePath"; + + std::string addFileSuffix(const std::string& filePath, const std::string& suffix) { + const size_t lastdot = filePath.find_last_of('.'); + const std::string extension = filePath.substr(0, lastdot); + if (lastdot == std::string::npos) { + return filePath + suffix; + } + else { + return filePath.substr(0, lastdot) + suffix + extension; + } + } } // namespace namespace openspace::interaction { @@ -54,7 +65,7 @@ ConvertRecFormatTask::ConvertRecFormatTask(const ghoul::Dictionary& dictionary) ghoul_assert(std::filesystem::is_regular_file(_inFilePath), "The file must exist"); if (!std::filesystem::is_regular_file(_inFilePath)) { - LERROR(fmt::format("Failed to load session recording file: {}", _inFilePath)); + LERROR(std::format("Failed to load session recording file: {}", _inFilePath)); } else { _iFile.open(_inFilePath, std::ifstream::in | std::ifstream::binary); @@ -66,14 +77,12 @@ ConvertRecFormatTask::ConvertRecFormatTask(const ghoul::Dictionary& dictionary) ConvertRecFormatTask::~ConvertRecFormatTask() { _iFile.close(); _oFile.close(); - if (sessRec != nullptr) { - delete sessRec; - } + delete sessRec; } std::string ConvertRecFormatTask::description() { std::string description = - fmt::format("Convert session recording file {}", _inFilePath); + std::format("Convert session recording file '{}'", _inFilePath); if (_fileFormatType == SessionRecording::DataMode::Ascii) { description += "(ascii format) "; } @@ -83,7 +92,7 @@ std::string ConvertRecFormatTask::description() { else { description += "(UNKNOWN format) "; } - description += fmt::format("conversion to file {}", _outFilePath); + description += std::format("conversion to file '{}'", _outFilePath); return description; } @@ -92,7 +101,8 @@ void ConvertRecFormatTask::perform(const Task::ProgressCallback&) { } void ConvertRecFormatTask::convert() { - std::string expectedFileExtension_in, expectedFileExtension_out; + std::string expectedFileExtension_in; + std::string expectedFileExtension_out; std::string currentFormat; if (_fileFormatType == SessionRecording::DataMode::Binary) { currentFormat = "binary"; @@ -106,13 +116,14 @@ void ConvertRecFormatTask::convert() { } if (_inFilePath.extension() != expectedFileExtension_in) { - LWARNING(fmt::format( - "Input filename doesn't have expected {} format file extension", currentFormat + LWARNING(std::format( + "Input filename doesn't have expected '{}' format file extension", + currentFormat )); } if (_outFilePath.extension() == expectedFileExtension_in) { - LERROR(fmt::format( - "Output filename has {} file extension, but is conversion from {}", + LERROR(std::format( + "Output filename has '{}' file extension, but is conversion from '{}'", currentFormat, currentFormat )); return; @@ -161,8 +172,8 @@ void ConvertRecFormatTask::determineFormatType() { if (line.substr(0, SessionRecording::FileHeaderTitle.length()) != SessionRecording::FileHeaderTitle) { - LERROR(fmt::format( - "Session recording file {} does not have expected header", _inFilePath + LERROR(std::format( + "Session recording file '{}' does not have expected header", _inFilePath )); } else { @@ -184,23 +195,21 @@ void ConvertRecFormatTask::determineFormatType() { void ConvertRecFormatTask::convertToAscii() { SessionRecording::Timestamps times; datamessagestructures::CameraKeyframe ckf; - datamessagestructures::TimeKeyframe tkf; - datamessagestructures::ScriptMessage skf; + datamessagestructures::TimeKeyframe tkf; + datamessagestructures::ScriptMessage skf; int lineNum = 1; _oFile.open(_outFilePath, std::ifstream::app); - char tmpType = SessionRecording::DataFormatAsciiTag; + const char tmpType = SessionRecording::DataFormatAsciiTag; _oFile.write(&tmpType, 1); _oFile.write("\n", 1); - bool fileReadOk = true; - while (fileReadOk) { - unsigned char frameType = readFromPlayback(_iFile); + while (true) { + const unsigned char frameType = readFromPlayback(_iFile); // Check if have reached EOF if (!_iFile) { - LINFO(fmt::format( - "Finished converting {} entries from file {}", lineNum - 1, _inFilePath + LINFO(std::format( + "Finished converting {} entries from file '{}'", lineNum - 1, _inFilePath )); - fileReadOk = false; break; } @@ -209,25 +218,34 @@ void ConvertRecFormatTask::convertToAscii() { if (frameType == SessionRecording::HeaderCameraBinary) { sessRec->readCameraKeyframeBinary(times, ckf, _iFile, lineNum); - sessRec->saveHeaderAscii(times, SessionRecording::HeaderCameraAscii, - keyframeLine); + SessionRecording::saveHeaderAscii( + times, + SessionRecording::HeaderCameraAscii, + keyframeLine + ); ckf.write(keyframeLine); } else if (frameType == SessionRecording::HeaderTimeBinary) { sessRec->readTimeKeyframeBinary(times, tkf, _iFile, lineNum); - sessRec->saveHeaderAscii(times, SessionRecording::HeaderTimeAscii, - keyframeLine); + SessionRecording::saveHeaderAscii( + times, + SessionRecording::HeaderTimeAscii, + keyframeLine + ); tkf.write(keyframeLine); } else if (frameType == SessionRecording::HeaderScriptBinary) { sessRec->readScriptKeyframeBinary(times, skf, _iFile, lineNum); - sessRec->saveHeaderAscii(times, SessionRecording::HeaderScriptAscii, - keyframeLine); + SessionRecording::saveHeaderAscii( + times, + SessionRecording::HeaderScriptAscii, + keyframeLine + ); skf.write(keyframeLine); } else { - LERROR(fmt::format( - "Unknown frame type @ index {} of playback file {}", + LERROR(std::format( + "Unknown frame type @ index {} of playback file '{}'", lineNum - 1, _inFilePath )); break; @@ -236,19 +254,18 @@ void ConvertRecFormatTask::convertToAscii() { SessionRecording::saveKeyframeToFile(keyframeLine.str(), _oFile); lineNum++; } - _oFile.close(); } void ConvertRecFormatTask::convertToBinary() { SessionRecording::Timestamps times; datamessagestructures::CameraKeyframe ckf; - datamessagestructures::TimeKeyframe tkf; - datamessagestructures::ScriptMessage skf; + datamessagestructures::TimeKeyframe tkf; + datamessagestructures::ScriptMessage skf; int lineNum = 1; std::string lineContents; - unsigned char keyframeBuffer[SessionRecording::_saveBufferMaxSize_bytes]; + std::array keyframeBuffer; _oFile.open(_outFilePath, std::ifstream::app | std::ios::binary); - char tmpType = SessionRecording::DataFormatBinaryTag; + const char tmpType = SessionRecording::DataFormatBinaryTag; _oFile.write(&tmpType, 1); _oFile.write("\n", 1); @@ -258,57 +275,44 @@ void ConvertRecFormatTask::convertToBinary() { std::istringstream iss(lineContents); std::string entryType; if (!(iss >> entryType)) { - LERROR(fmt::format( - "Error reading entry type @ line {} of file {}", lineNum, _inFilePath + LERROR(std::format( + "Error reading entry type @ line {} of file '{}'", lineNum, _inFilePath )); break; } if (entryType == SessionRecording::HeaderCameraAscii) { sessRec->readCameraKeyframeAscii(times, ckf, lineContents, lineNum); - sessRec->saveCameraKeyframeBinary(times, ckf, keyframeBuffer, + sessRec->saveCameraKeyframeBinary(times, ckf, keyframeBuffer.data(), _oFile); } else if (entryType == SessionRecording::HeaderTimeAscii) { sessRec->readTimeKeyframeAscii(times, tkf, lineContents, lineNum); - sessRec->saveTimeKeyframeBinary(times, tkf, keyframeBuffer, + sessRec->saveTimeKeyframeBinary(times, tkf, keyframeBuffer.data(), _oFile); } else if (entryType == SessionRecording::HeaderScriptAscii) { sessRec->readScriptKeyframeAscii(times, skf, lineContents, lineNum); - sessRec->saveScriptKeyframeBinary(times, skf, keyframeBuffer, + sessRec->saveScriptKeyframeBinary(times, skf, keyframeBuffer.data(), _oFile); } else if (entryType.substr(0, 1) == SessionRecording::HeaderCommentAscii) { continue; } else { - LERROR(fmt::format( - "Unknown frame type {} @ line {} of file {}", + LERROR(std::format( + "Unknown frame type {} @ line {} of file '{}'", entryType, lineContents, _inFilePath )); break; } } _oFile.close(); - LINFO(fmt::format( - "Finished converting {} entries from file {}", lineNum, _inFilePath + LINFO(std::format( + "Finished converting {} entries from file '{}'", lineNum, _inFilePath )); } -std::string ConvertRecFormatTask::addFileSuffix(const std::string& filePath, - const std::string& suffix) -{ - size_t lastdot = filePath.find_last_of("."); - std::string extension = filePath.substr(0, lastdot); - if (lastdot == std::string::npos) { - return filePath + suffix; - } - else { - return filePath.substr(0, lastdot) + suffix + extension; - } -} - documentation::Documentation ConvertRecFormatTask::documentation() { using namespace documentation; return { @@ -332,4 +336,4 @@ documentation::Documentation ConvertRecFormatTask::documentation() { }; } -} +} // namespace openspace::interaction diff --git a/src/interaction/touchbar.mm b/src/interaction/touchbar.mm index d96f89837f..8cc7149f73 100644 --- a/src/interaction/touchbar.mm +++ b/src/interaction/touchbar.mm @@ -190,7 +190,7 @@ NSArray* focusIdentifiers; NSString* title = [button title]; - std::string str = fmt::format( + std::string str = std::format( "openspace.setPropertyValueSingle('{}', '{}');\ openspace.setPropertyValueSingle('{}', '');\ openspace.setPropertyValueSingle('{}', '');", diff --git a/src/interaction/websocketcamerastates.cpp b/src/interaction/websocketcamerastates.cpp index bfa13e316d..0262cfd3ea 100644 --- a/src/interaction/websocketcamerastates.cpp +++ b/src/interaction/websocketcamerastates.cpp @@ -49,14 +49,14 @@ void WebsocketCameraStates::updateStateFromInput( std::pair localRotation = std::pair(false, glm::dvec2(0.0)); if (!websocketInputStates.empty()) { - for (int i = 0; i < WebsocketInputState::MaxAxes; ++i) { - AxisInformation t = _axisMapping[i]; + for (int i = 0; i < WebsocketInputState::MaxAxes; i++) { + const AxisInformation t = _axisMapping[i]; if (t.type == AxisType::None) { continue; } float value = websocketInputStates.axis(i); - bool hasValue = std::fabs(value) > t.deadzone; + const bool hasValue = std::fabs(value) > t.deadzone; if (!hasValue) { value = 0.f; @@ -198,7 +198,7 @@ void WebsocketCameraStates::clearButtonCommand(int button) { it = _buttonMapping.erase(it); } else { - ++it; + it++; } } } @@ -206,7 +206,7 @@ void WebsocketCameraStates::clearButtonCommand(int button) { std::vector WebsocketCameraStates::buttonCommand(int button) const { std::vector result; auto itRange = _buttonMapping.equal_range(button); - for (auto it = itRange.first; it != itRange.second; ++it) { + for (auto it = itRange.first; it != itRange.second; it++) { result.push_back(it->second.command); } return result; diff --git a/src/interaction/websocketinputstate.cpp b/src/interaction/websocketinputstate.cpp index ea07a518ee..4ea18f55b2 100644 --- a/src/interaction/websocketinputstate.cpp +++ b/src/interaction/websocketinputstate.cpp @@ -36,7 +36,7 @@ namespace openspace::interaction { float WebsocketInputStates::axis(int axis) const { ghoul_precondition(axis >= 0, "axis must be 0 or positive"); - float res = std::accumulate( + const float res = std::accumulate( begin(), end(), 0.f, @@ -58,7 +58,7 @@ float WebsocketInputStates::axis(int axis) const { bool WebsocketInputStates::button(int button, WebsocketAction action) const { ghoul_precondition(button >= 0, "button must be 0 or positive"); - bool res = std::any_of( + const bool res = std::any_of( begin(), end(), [button, action](const std::pair state) diff --git a/src/mission/mission.cpp b/src/mission/mission.cpp index ab98243f04..c22dd8441e 100644 --- a/src/mission/mission.cpp +++ b/src/mission/mission.cpp @@ -114,16 +114,16 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) { // user may specify an overall time range. In that case expand this timerange if (p.timeRange.has_value()) { - std::string start = p.timeRange->start; - std::string end = p.timeRange->end.value_or(start); + const std::string start = p.timeRange->start; + const std::string end = p.timeRange->end.value_or(start); - TimeRange overallTimeRange = TimeRange( + const TimeRange overallTimeRange = TimeRange( SpiceManager::ref().ephemerisTimeFromDate(start), SpiceManager::ref().ephemerisTimeFromDate(end) ); if (!overallTimeRange.includes(timeRangeSubPhases)) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "User specified time range must at least include its subphases'", "Mission ({})", _name )); @@ -139,8 +139,8 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) { } else { if (p.timeRange.has_value()) { - std::string start = p.timeRange->start; - std::string end = p.timeRange->end.value_or(start); + const std::string start = p.timeRange->start; + const std::string end = p.timeRange->end.value_or(start); _timeRange = TimeRange( SpiceManager::ref().ephemerisTimeFromDate(start), @@ -148,7 +148,7 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) { ); } else { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "If there are no subphases specified, the time range has to be specified", "Mission ({})", _name )); @@ -163,10 +163,9 @@ MissionPhase::MissionPhase(const ghoul::Dictionary& dictionary) { _milestones.reserve(p.milestones->size()); for (const Parameters::Milestone& milestone : *p.milestones) { std::string name = milestone.name; - Time newTime = Time(milestone.date); Milestone newDate = { - .name = name, - .date = newTime + .name = std::move(name), + .date = Time(milestone.date) }; if (milestone.description.has_value()) { newDate.description = milestone.description.value(); @@ -235,7 +234,7 @@ void MissionPhase::phaseTrace(double time, Trace& trace, int maxDepth) const { for (const MissionPhase& phase : _subphases) { if (phase.timeRange().includes(time)) { - trace.push_back(phase); + trace.emplace_back(phase); phase.phaseTrace(time, trace, maxDepth - 1); return; } diff --git a/src/mission/missionmanager.cpp b/src/mission/missionmanager.cpp index 7ff5e0d3e7..39814f6032 100644 --- a/src/mission/missionmanager.cpp +++ b/src/mission/missionmanager.cpp @@ -60,8 +60,8 @@ bool MissionManager::hasCurrentMission() const { std::string MissionManager::loadMission(Mission mission) { // Changing the values might invalidate the _currentMission iterator - std::string currentMission = hasCurrentMission() ? _currentMission->first : ""; - std::string missionName = mission.name(); + const std::string currentMission = hasCurrentMission() ? _currentMission->first : ""; + const std::string missionName = mission.name(); _missionMap.insert({ missionName, std::move(mission) }); if (_missionMap.size() == 1) { setCurrentMission(missionName); diff --git a/src/navigation/keyframenavigator.cpp b/src/navigation/keyframenavigator.cpp index 5f71578f6b..0c133d46c2 100644 --- a/src/navigation/keyframenavigator.cpp +++ b/src/navigation/keyframenavigator.cpp @@ -35,24 +35,18 @@ #include -#ifdef INTERPOLATION_DEBUG_PRINT -namespace { - constexpr std::string_view _loggerCat = "KeyframeNavigator"; -} // namespace -#endif - namespace openspace::interaction { KeyframeNavigator::CameraPose::CameraPose(datamessagestructures::CameraKeyframe&& kf) : position(std::move(kf._position)) , rotation(std::move(kf._rotation)) , focusNode(std::move(kf._focusNode)) - , scale(std::move(kf._scale)) - , followFocusNodeRotation(std::move(kf._followNodeRotation)) + , scale(kf._scale) + , followFocusNodeRotation(kf._followNodeRotation) {} bool KeyframeNavigator::updateCamera(Camera& camera, bool ignoreFutureKeyframes) { - double now = currentTime(); + const double now = currentTime(); bool foundPrevKeyframe = false; if (_cameraPoseTimeline.nKeyframes() == 0) { @@ -100,8 +94,8 @@ bool KeyframeNavigator::updateCamera(Camera& camera, bool ignoreFutureKeyframes) return updateCamera(&camera, prevPose, nextPose, t, ignoreFutureKeyframes); } -bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose, - const CameraPose nextPose, double t, +bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose& prevPose, + const CameraPose& nextPose, double t, bool ignoreFutureKeyframes) { Scene* scene = camera->parent()->scene(); @@ -142,16 +136,16 @@ bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose, // Linear interpolation t = std::max(0.0, std::min(1.0, t)); - glm::dvec3 nowCameraPosition = prevKeyframeCameraPosition * (1.0 - t) + - nextKeyframeCameraPosition * t; + const glm::dvec3 nowCameraPosition = + prevKeyframeCameraPosition * (1.0 - t) + nextKeyframeCameraPosition * t; glm::dquat nowCameraRotation = glm::slerp( prevKeyframeCameraRotation, nextKeyframeCameraRotation, t ); - camera->setPositionVec3(nowCameraPosition); - camera->setRotation(nowCameraRotation); + camera->setPositionVec3(std::move(nowCameraPosition)); + camera->setRotation(std::move(nowCameraRotation)); // We want to affect view scaling, such that we achieve // logarithmic interpolation of distance to an imagined focus node. @@ -165,19 +159,6 @@ bool KeyframeNavigator::updateCamera(Camera* camera, const CameraPose prevPose, camera->setScaling(1.f / glm::exp(interpolatedInvScaleExp)); } -#ifdef INTERPOLATION_DEBUG_PRINT - LINFO(fmt::format( - "Cam pos = {} {} {} rot = {} {} {} {}", - nowCameraPosition.x, - nowCameraPosition.y, - nowCameraPosition.z, - nowCameraRotation.x, - nowCameraRotation.y, - nowCameraRotation.z, - nowCameraRotation.w - )); -#endif - return true; } diff --git a/src/navigation/navigationhandler.cpp b/src/navigation/navigationhandler.cpp index de63360dfb..0b6f8f589c 100644 --- a/src/navigation/navigationhandler.cpp +++ b/src/navigation/navigationhandler.cpp @@ -35,12 +35,13 @@ #include #include #include +#include #include #include #include #include #include -#include +#include #include #include #include @@ -187,8 +188,8 @@ void NavigationHandler::updateCamera(double deltaTime) { return; } - OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); - bool playbackMode = (mode == OpenSpaceEngine::Mode::SessionRecordingPlayback); + const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); + const bool playbackMode = (mode == OpenSpaceEngine::Mode::SessionRecordingPlayback); // If we're in session recording payback mode, the session recording is responsible // for navigation. So don't do anything more here @@ -225,14 +226,14 @@ void NavigationHandler::applyPendingState() { std::variant pending = *_pendingState; if (std::holds_alternative(pending)) { - NavigationState ns = std::get(pending); + const NavigationState ns = std::get(pending); _orbitalNavigator.setAnchorNode(ns.anchor); _orbitalNavigator.setAimNode(ns.aim); _camera->setPose(ns.cameraPose()); } else if (std::holds_alternative(pending)) { - NodeCameraStateSpec spec = std::get(pending); - Waypoint wp = computeWaypointFromNodeInfo(spec); + const NodeCameraStateSpec spec = std::get(pending); + const Waypoint wp = computeWaypointFromNodeInfo(spec); _orbitalNavigator.setAnchorNode(wp.nodeIdentifier()); _orbitalNavigator.setAimNode(""); @@ -271,13 +272,13 @@ void NavigationHandler::updateCameraTransitions() { // Updated checks compared to last time, so we can check if we are still in the // approach or anchor sphere - bool isInApproachSphere = currDistance < d * af; - bool isInReachSphere = currDistance < d * rf; + const bool isInApproachSphere = currDistance < d * af; + const bool isInReachSphere = currDistance < d * rf; // Compare these to the values from last frame, to trigger the correct transition // events - bool wasInApproachSphere = _inAnchorApproachSphere; - bool wasInReachSphere = _inAnchorReachSphere; + const bool wasInApproachSphere = _inAnchorApproachSphere; + const bool wasInReachSphere = _inAnchorReachSphere; _inAnchorApproachSphere = isInApproachSphere; _inAnchorReachSphere = isInReachSphere; @@ -377,7 +378,7 @@ void NavigationHandler::updateCameraTransitions() { ); }; - bool anchorWasChanged = anchorNode() != _lastAnchor; + const bool anchorWasChanged = anchorNode() != _lastAnchor; if (anchorWasChanged) { // The anchor was changed between frames, so the transitions we have to check // are a bit different. Just directly trigger the relevant events for the @@ -509,8 +510,8 @@ NavigationState NavigationHandler::navigationState( glm::normalize(_camera->lookUpVectorWorldSpace()) )); - glm::dquat localRotation = invNeutralRotation * _camera->rotationQuaternion(); - glm::dvec3 eulerAngles = glm::eulerAngles(localRotation); + const glm::dquat localRotation = invNeutralRotation * _camera->rotationQuaternion(); + const glm::dvec3 eulerAngles = glm::eulerAngles(localRotation); const double pitch = eulerAngles.x; const double yaw = -eulerAngles.y; @@ -531,12 +532,15 @@ NavigationState NavigationHandler::navigationState( _orbitalNavigator.aimNode() ? _orbitalNavigator.aimNode()->identifier() : "", referenceFrame.identifier(), position, - invReferenceFrameTransform * neutralUp, yaw, pitch + invReferenceFrameTransform * neutralUp, + yaw, + pitch, + global::timeManager->time().j2000Seconds() ); } void NavigationHandler::saveNavigationState(const std::filesystem::path& filepath, - const std::string& referenceFrameIdentifier) + const std::string& referenceFrameIdentifier) const { ghoul_precondition(!filepath.empty(), "File path must not be empty"); @@ -544,7 +548,7 @@ void NavigationHandler::saveNavigationState(const std::filesystem::path& filepat if (!referenceFrameIdentifier.empty()) { const SceneGraphNode* referenceFrame = sceneGraphNode(referenceFrameIdentifier); if (!referenceFrame) { - LERROR(fmt::format( + LERROR(std::format( "Could not find node '{}' to use as reference frame", referenceFrameIdentifier )); @@ -561,36 +565,54 @@ void NavigationHandler::saveNavigationState(const std::filesystem::path& filepat // Adding the .navstate extension to the filepath if it came without one absolutePath.replace_extension(".navstate"); } - LINFO(fmt::format("Saving camera position: {}", absolutePath)); + LINFO(std::format("Saving camera position: {}", absolutePath)); std::ofstream ofs(absolutePath); if (!ofs.good()) { - throw ghoul::RuntimeError(fmt::format( - "Error saving navigation state to {}", filepath + throw ghoul::RuntimeError(std::format( + "Error saving navigation state to '{}'", filepath )); } ofs << state.toJson().dump(2); } -void NavigationHandler::loadNavigationState(const std::string& filepath) { - const std::filesystem::path absolutePath = absPath(filepath); - LINFO(fmt::format("Reading camera state from file: {}", absolutePath)); +void NavigationHandler::loadNavigationState(const std::string& filepath, + bool useTimeStamp) +{ + std::filesystem::path absolutePath = absPath(filepath); + LINFO(std::format("Reading camera state from file: {}", absolutePath)); + + if (!absolutePath.has_extension()) { + // Adding the .navstate extension to the filepath if it came without one + absolutePath.replace_extension(".navstate"); + } if (!std::filesystem::is_regular_file(absolutePath)) { throw ghoul::FileNotFoundError(absolutePath.string(), "NavigationState"); } - std::ifstream f(filepath); - std::string contents = std::string( + std::ifstream f = std::ifstream(absolutePath); + const std::string contents = std::string( std::istreambuf_iterator(f), std::istreambuf_iterator() ); - nlohmann::json json = nlohmann::json::parse(contents); - NavigationState state = NavigationState(json); + if (contents.empty()) { + throw::ghoul::RuntimeError(std::format( + "Failed reading camera state from file: {}. File is empty", absolutePath + )); + } + + const nlohmann::json json = nlohmann::json::parse(contents); + + const NavigationState state = NavigationState(json); setNavigationStateNextFrame(state); + + if (useTimeStamp && state.timestamp.has_value()) { + global::timeManager->setTimeNextFrame(Time(*state.timestamp)); + } } std::vector NavigationHandler::listAllJoysticks() const { diff --git a/src/navigation/navigationhandler_lua.inl b/src/navigation/navigationhandler_lua.inl index 7045a1dc81..7a805751e6 100644 --- a/src/navigation/navigationhandler_lua.inl +++ b/src/navigation/navigationhandler_lua.inl @@ -27,14 +27,20 @@ namespace { /** * Load a navigation state from file. The file should be a lua file returning the * navigation state as a table formatted as a Navigation State, such as the output files - * of saveNavigationState. + * of saveNavigationState. If usetimeStamp is set to true and the provided navigation + * state has a timestamp, time will be set as well. */ -[[codegen::luawrap]] void loadNavigationState(std::string cameraStateFilePath) { +[[codegen::luawrap]] void loadNavigationState(std::string cameraStateFilePath, + bool useTimeStamp = false) +{ if (cameraStateFilePath.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } - openspace::global::navigationHandler->loadNavigationState(cameraStateFilePath); + openspace::global::navigationHandler->loadNavigationState( + cameraStateFilePath, + useTimeStamp + ); } /** @@ -54,7 +60,7 @@ namespace { const SceneGraphNode* referenceFrame = sceneGraphNode(*frame); if (!referenceFrame) { throw ghoul::lua::LuaError( - fmt::format("Could not find node '{}' as reference frame", *frame) + std::format("Could not find node '{}' as reference frame", *frame) ); } state = global::navigationHandler->navigationState(*referenceFrame); @@ -66,13 +72,21 @@ namespace { return state.dictionary(); } -// Set the navigation state. The argument must be a valid Navigation State. -[[codegen::luawrap]] void setNavigationState(ghoul::Dictionary navigationState) { +// Set the navigation state. The first argument must be a valid Navigation State. If +// useTimeStamp is set to true and the provided navigation state has a timestamp, time +// will be set as well. +[[codegen::luawrap]] void setNavigationState(ghoul::Dictionary navigationState, + bool useTimeStamp = false) +{ using namespace openspace; - global::navigationHandler->setNavigationStateNextFrame( - interaction::NavigationState(navigationState) - ); + interaction::NavigationState ns = interaction::NavigationState(navigationState); + + global::navigationHandler->setNavigationStateNextFrame(ns); + + if (useTimeStamp && ns.timestamp.has_value()) { + global::timeManager->setTimeNextFrame(Time(*ns.timestamp)); + } } /** diff --git a/src/navigation/navigationstate.cpp b/src/navigation/navigationstate.cpp index 03f8460a4e..a8c2d035c2 100644 --- a/src/navigation/navigationstate.cpp +++ b/src/navigation/navigationstate.cpp @@ -25,8 +25,9 @@ #include #include #include -#include #include +#include +#include namespace { constexpr std::string_view _loggerCat = "NavigationState"; @@ -45,12 +46,10 @@ namespace { // To get the current navigation state of the camera, use the // `openspace.navigation.getNavigationState()` function in the Scripting API. // - // Note that a NavigationState does not include information about what timestamp - // within OpenSpace that the NavigationState was generated. When laoding a - // NavigationState, the visuals may be different depending on what the simulation - // timestamp is, as the relative positions of objects in the scene may have changed. - // The get the exact same visuals as when the NavigationState was saved, make sure - // to also set the time to be the same as on save. + // Note that when loading a NavigationState, the visuals may be different depending + // on what the simulation timestamp is, as the relative positions of objects in the + // scene may have changed. The get the exact same visuals as when the NavigationState + // was saved you need to also set the simulation time to correpsond to the timestamp. struct [[codegen::Dictionary(NavigationState)]] Parameters { // The identifier of the anchor node std::string anchor; @@ -74,6 +73,11 @@ namespace { // The pitch angle in radians. Positive angle means pitching camera upwards std::optional pitch; + + // The timestamp for when the navigation state was captured or is valid. Specified + // either as seconds past the J2000 epoch, or as a date string in ISO 8601 format: + // 'YYYY MM DD HH:mm:ss.xxx' + std::optional> timestamp; }; #include "navigationstate_codegen.cpp" } // namespace @@ -92,6 +96,17 @@ NavigationState::NavigationState(const ghoul::Dictionary& dictionary) { up = p.up; yaw = p.yaw.value_or(yaw); pitch = p.pitch.value_or(pitch); + + if (p.timestamp.has_value()) { + if (std::holds_alternative(*p.timestamp)) { + timestamp = std::get(*p.timestamp); + } + else { + timestamp = SpiceManager::ref().ephemerisTimeFromDate( + std::get(*p.timestamp) + ); + } + } } NavigationState::NavigationState(const nlohmann::json& json) { @@ -126,12 +141,24 @@ NavigationState::NavigationState(const nlohmann::json& json) { if (auto it = json.find("pitch"); it != json.end()) { pitch = it->get(); } + + if (auto it = json.find("timestamp"); it != json.end()) { + if (it->is_string()) { + timestamp = SpiceManager::ref().ephemerisTimeFromDate( + it->get() + ); + } + else { + timestamp = it->get(); + } + } } NavigationState::NavigationState(std::string anchor_, std::string aim_, std::string referenceFrame_, glm::dvec3 position_, std::optional up_, - double yaw_, double pitch_) + double yaw_, double pitch_, + std::optional timestamp_) : anchor(std::move(anchor_)) , aim(std::move(aim_)) , referenceFrame(std::move(referenceFrame_)) @@ -139,6 +166,7 @@ NavigationState::NavigationState(std::string anchor_, std::string aim_, , up(std::move(up_)) , yaw(yaw_) , pitch(pitch_) + , timestamp(timestamp_) {} CameraPose NavigationState::cameraPose() const { @@ -146,14 +174,14 @@ CameraPose NavigationState::cameraPose() const { const SceneGraphNode* anchorNode = sceneGraphNode(anchor); if (!anchorNode) { - LERROR(fmt::format( + LERROR(std::format( "Could not find scene graph node '{}' used as anchor", anchor )); return CameraPose(); } if (!referenceFrameNode) { - LERROR(fmt::format( + LERROR(std::format( "Could not find scene graph node '{}' used as reference frame", referenceFrame )); @@ -170,22 +198,20 @@ CameraPose NavigationState::cameraPose() const { resultingPose.position = anchorNode->worldPosition() + referenceFrameTransform * glm::dvec3(position); - glm::dvec3 upVector = up.has_value() ? + const glm::dvec3 upVector = up.has_value() ? glm::normalize(referenceFrameTransform * *up) : glm::dvec3(0.0, 1.0, 0.0); // Construct vectors of a "neutral" view, i.e. when the anchor is centered in view - glm::dvec3 neutralView = + const glm::dvec3 neutralView = glm::normalize(anchorNode->worldPosition() - resultingPose.position); - glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast(glm::lookAt( - glm::dvec3(0.0), - neutralView, - upVector - ))); + const glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast( + glm::lookAt(glm::dvec3(0.0), neutralView, upVector) + )); - glm::dquat pitchRotation = glm::angleAxis(pitch, glm::dvec3(1.0, 0.0, 0.0)); - glm::dquat yawRotation = glm::angleAxis(yaw, glm::dvec3(0.0, -1.0, 0.0)); + const glm::dquat pitchRotation = glm::angleAxis(pitch, glm::dvec3(1.0, 0.0, 0.0)); + const glm::dquat yawRotation = glm::angleAxis(yaw, glm::dvec3(0.0, -1.0, 0.0)); resultingPose.rotation = neutralCameraRotation * yawRotation * pitchRotation; @@ -212,6 +238,15 @@ ghoul::Dictionary NavigationState::dictionary() const { if (std::abs(pitch) > Epsilon) { cameraDict.setValue("Pitch", pitch); } + if (timestamp.has_value()) { + cameraDict.setValue( + "Timestamp", + SpiceManager::ref().dateFromEphemerisTime( + *timestamp, + "YYYY MON DD HR:MN:SC" + ) + ); + } return cameraDict; } @@ -254,6 +289,13 @@ nlohmann::json NavigationState::toJson() const { result["pitch"] = pitch; } + if (timestamp.has_value()) { + result["timestamp"] = SpiceManager::ref().dateFromEphemerisTime( + *timestamp, + "YYYY MON DD HR:MN:SC" + ); + } + return result; } diff --git a/src/navigation/orbitalnavigator.cpp b/src/navigation/orbitalnavigator.cpp index 268acbebd2..f9b801b683 100644 --- a/src/navigation/orbitalnavigator.cpp +++ b/src/navigation/orbitalnavigator.cpp @@ -331,7 +331,7 @@ namespace { openspace::properties::Property::Visibility::AdvancedUser }; - static const openspace::properties::PropertyOwner::PropertyOwnerInfo LimitZoomInfo = { + const openspace::properties::PropertyOwner::PropertyOwnerInfo LimitZoomInfo = { "LimitZoom", "Limit Zoom", "Settings to limit the camera from going to close to or too far away from the " @@ -411,6 +411,28 @@ namespace { "choice for globes, and the Y-axis is a good choice for models", openspace::properties::Property::Visibility::AdvancedUser }; + + /** + * Calculates a SurfacePositionHandle given a camera position in world space. + */ + openspace::SurfacePositionHandle calculateSurfacePositionHandle( + const openspace::SceneGraphNode& node, + const glm::dvec3& cameraPositionWorldSpace) + { + ghoul_assert( + glm::length(cameraPositionWorldSpace) > 0.0, + "Cannot have degenerate vector" + ); + + const glm::dmat4 inverseModelTransform = glm::inverse(node.modelTransform()); + const glm::dvec3 cameraPositionModelSpace = + glm::dvec3(inverseModelTransform * glm::dvec4(cameraPositionWorldSpace, 1.0)); + const openspace::SurfacePositionHandle posHandle = + node.calculateSurfacePositionHandle(cameraPositionModelSpace); + + return posHandle; + } + } // namespace namespace openspace::interaction { @@ -468,7 +490,7 @@ OrbitalNavigator::IdleBehavior::IdleBehavior() OrbitalNavigator::LimitZoom::LimitZoom() : properties::PropertyOwner(LimitZoomInfo) , enableZoomInLimit(EnabledMinimumAllowedDistanceInfo, true) - , minimumAllowedDistance(MinimumDistanceInfo, 10.0f, 0.0f, 10000.f) + , minimumAllowedDistance(MinimumDistanceInfo, 10.f, 0.f, 10000.f) , enableZoomOutLimit(EnabledMaximumDistanceInfo, false) , maximumAllowedDistance( MaximumDistanceInfo, @@ -498,8 +520,8 @@ OrbitalNavigator::OrbitalNavigator() , _disableZoom(DisableZoomInfo, false) , _disableRoll(DisableRollInfo, false) , _mouseSensitivity(MouseSensitivityInfo, 15.f, 1.f, 50.f) - , _joystickSensitivity(JoystickSensitivityInfo, 10.f, 1.0f, 50.f) - , _websocketSensitivity(WebsocketSensitivityInfo, 5.f, 1.0f, 50.f) + , _joystickSensitivity(JoystickSensitivityInfo, 10.f, 1.f, 50.f) + , _websocketSensitivity(WebsocketSensitivityInfo, 5.f, 1.f, 50.f) , _useAdaptiveStereoscopicDepth(UseAdaptiveStereoscopicDepthInfo, true) , _stereoscopicDepthOfFocusSurface( StereoscopicDepthOfFocusSurfaceInfo, @@ -533,8 +555,8 @@ OrbitalNavigator::OrbitalNavigator() ); } else { - LERROR(fmt::format( - "No scenegraph node with identifier {} exists", _anchor.value() + LERROR(std::format( + "No scenegraph node with identifier '{}' exists", _anchor.value() )); } }); @@ -549,8 +571,8 @@ OrbitalNavigator::OrbitalNavigator() setAimNode(node); } else { - LERROR(fmt::format( - "No scenegraph node with identifier {} exists", _aim.value() + LERROR(std::format( + "No scenegraph node with identifier '{}' exists", _aim.value() )); } }); @@ -734,7 +756,7 @@ glm::dvec3 OrbitalNavigator::anchorNodeToCameraVector() const { } glm::quat OrbitalNavigator::anchorNodeToCameraRotation() const { - glm::dmat4 invWorldRotation = glm::dmat4( + const glm::dmat4 invWorldRotation = glm::dmat4( glm::inverse(anchorNode()->worldRotationMatrix()) ); return glm::quat(invWorldRotation) * glm::quat(_camera->rotationQuaternion()); @@ -777,7 +799,8 @@ void OrbitalNavigator::updateStatesFromInput(const MouseInputState& mouseInputSt _websocketStates.updateStateFromInput(*global::websocketInputStates, deltaTime); _scriptStates.updateStateFromInput(deltaTime); - bool interactionHappened = _mouseStates.hasNonZeroVelocities() || + const bool interactionHappened = + _mouseStates.hasNonZeroVelocities() || _joystickStates.hasNonZeroVelocities() || _websocketStates.hasNonZeroVelocities() || _scriptStates.hasNonZeroVelocities(); @@ -789,7 +812,8 @@ void OrbitalNavigator::updateStatesFromInput(const MouseInputState& mouseInputSt tickIdleBehaviorTimer(deltaTime); } - bool cameraLocationChanged = _mouseStates.hasNonZeroVelocities(true) || + const bool cameraLocationChanged = + _mouseStates.hasNonZeroVelocities(true) || _joystickStates.hasNonZeroVelocities(true) || _websocketStates.hasNonZeroVelocities(true) || _scriptStates.hasNonZeroVelocities(true); @@ -869,7 +893,7 @@ void OrbitalNavigator::updateCameraStateFromStates(double deltaTime) { // Rotate with the object by finding a differential rotation from the previous // to the current rotation - glm::dquat anchorRotation = glm::quat_cast(_anchorNode->worldRotationMatrix()); + const glm::dquat anchorRotation = glm::quat_cast(_anchorNode->worldRotationMatrix()); glm::dquat anchorNodeRotationDiff = _previousAnchorNodeRotation.has_value() ? *_previousAnchorNodeRotation * glm::inverse(anchorRotation) : @@ -893,7 +917,7 @@ void OrbitalNavigator::updateCameraStateFromStates(double deltaTime) { camRot.localRotation = interpolateLocalRotation(deltaTime, camRot.localRotation); camRot.localRotation = rotateLocally(deltaTime, camRot.localRotation); - double horizontalTranslationSpeedScale = + const double horizontalTranslationSpeedScale = rotationSpeedScaleFromCameraHeight(pose.position, posHandle); // Rotation around target object's up vector based on user input @@ -986,8 +1010,10 @@ void OrbitalNavigator::updateCameraScalingFromAnchor(double deltaTime) { return; } - SurfacePositionHandle posHandle = - calculateSurfacePositionHandle(*_anchorNode, cameraPos); + const SurfacePositionHandle posHandle = calculateSurfacePositionHandle( + *_anchorNode, + cameraPos + ); double targetCameraToSurfaceDistance = glm::length( cameraToSurfaceVector(cameraPos, anchorPos, posHandle) @@ -1046,7 +1072,7 @@ void OrbitalNavigator::tickIdleBehaviorTimer(double deltaTime) { } glm::dquat OrbitalNavigator::composeCameraRotation( - const CameraRotationDecomposition& decomposition) + const CameraRotationDecomposition& decomposition) const { return decomposition.globalRotation * decomposition.localRotation; } @@ -1063,13 +1089,13 @@ glm::dvec3 OrbitalNavigator::cameraToSurfaceVector(const glm::dvec3& cameraPos, const glm::dvec3& centerPos, const SurfacePositionHandle& posHandle) { - glm::dmat4 modelTransform = _anchorNode->modelTransform(); - glm::dvec3 posDiff = cameraPos - centerPos; - glm::dvec3 centerToActualSurfaceModelSpace = + const glm::dmat4 modelTransform = _anchorNode->modelTransform(); + const glm::dvec3 posDiff = cameraPos - centerPos; + const glm::dvec3 centerToActualSurfaceModelSpace = posHandle.centerToReferenceSurface + posHandle.referenceSurfaceOutDirection * posHandle.heightToSurface; - glm::dvec3 centerToActualSurface = + const glm::dvec3 centerToActualSurface = glm::dmat3(modelTransform) * centerToActualSurfaceModelSpace; return centerToActualSurface - posDiff; @@ -1256,7 +1282,7 @@ bool OrbitalNavigator::shouldFollowAnchorRotation(const glm::dvec3& cameraPositi const double distanceToCamera = glm::distance(cameraPosition, _anchorNode->worldPosition()); - bool shouldFollow = distanceToCamera < maximumDistanceForRotation; + const bool shouldFollow = distanceToCamera < maximumDistanceForRotation; return shouldFollow; } @@ -1296,7 +1322,7 @@ double OrbitalNavigator::maxAllowedDistance() const { } OrbitalNavigator::CameraRotationDecomposition - OrbitalNavigator::decomposeCameraRotationSurface(CameraPose cameraPose, + OrbitalNavigator::decomposeCameraRotationSurface(const CameraPose& cameraPose, const SceneGraphNode& reference) { const glm::dvec3 cameraUp = cameraPose.rotation * Camera::UpDirectionCameraSpace; @@ -1330,8 +1356,8 @@ OrbitalNavigator::CameraRotationDecomposition } OrbitalNavigator::CameraRotationDecomposition - OrbitalNavigator::decomposeCameraRotation(CameraPose cameraPose, - glm::dvec3 reference) +OrbitalNavigator::decomposeCameraRotation(const CameraPose& cameraPose, + const glm::dvec3& reference) { const glm::dvec3 cameraUp = cameraPose.rotation * glm::dvec3(0.0, 1.0, 0.0); const glm::dvec3 cameraViewDirection = ghoul::viewDirection(cameraPose.rotation); @@ -1349,8 +1375,8 @@ OrbitalNavigator::CameraRotationDecomposition return { localCameraRotation, globalCameraRotation }; } -CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAnchor, - Displacement anchorToAim) +CameraPose OrbitalNavigator::followAim(CameraPose pose, const glm::dvec3& cameraToAnchor, + const Displacement& anchorToAim) { CameraRotationDecomposition anchorDecomp = decomposeCameraRotation(pose, pose.position + cameraToAnchor); @@ -1368,7 +1394,7 @@ CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAncho // 2. Adjustment of the camera to account for radial displacement of the aim // Step 1 (Rotation around anchor based on aim's projection) - glm::dvec3 newAnchorToProjectedAim = + const glm::dvec3 newAnchorToProjectedAim = glm::length(anchorToAim.first) * glm::normalize(anchorToAim.second); const double spinRotationAngle = glm::angle( glm::normalize(anchorToAim.first), glm::normalize(newAnchorToProjectedAim) @@ -1432,11 +1458,11 @@ CameraPose OrbitalNavigator::followAim(CameraPose pose, glm::dvec3 cameraToAncho const double newCameraAimAngle = glm::pi() - anchorAimAngle - newCameraAnchorAngle; - double distanceRotationAngle = correctionFactor * + const double distanceRotationAngle = correctionFactor * (newCameraAimAngle - prevCameraAimAngle); if (glm::abs(distanceRotationAngle) > AngleEpsilon) { - glm::dvec3 distanceRotationAxis = glm::normalize( + const glm::dvec3 distanceRotationAxis = glm::normalize( glm::cross(intermediateCameraToAnchor, newAnchorToProjectedAim) ); const glm::dquat orbitRotation = @@ -1539,63 +1565,68 @@ glm::dquat OrbitalNavigator::interpolateLocalRotation(double deltaTime, } OrbitalNavigator::Displacement -OrbitalNavigator::interpolateRetargetAim(double deltaTime, CameraPose pose, - glm::dvec3 prevCameraToAnchor, +OrbitalNavigator::interpolateRetargetAim(double deltaTime, const CameraPose& pose, + const glm::dvec3& prevCameraToAnchor, Displacement anchorToAim) { - if (_retargetAimInterpolator.isInterpolating()) { - double t = _retargetAimInterpolator.value(); - _retargetAimInterpolator.setDeltaTime(static_cast(deltaTime)); - _retargetAimInterpolator.step(); + if (!_retargetAimInterpolator.isInterpolating()) { + return anchorToAim; + } - const glm::dvec3 prevCameraToAim = prevCameraToAnchor + anchorToAim.first; - const double aimDistance = glm::length(prevCameraToAim); - const glm::dquat prevRotation = pose.rotation; + const double t = _retargetAimInterpolator.value(); + _retargetAimInterpolator.setDeltaTime(static_cast(deltaTime)); + _retargetAimInterpolator.step(); - // Introduce a virtual aim - a position straight ahead of the camera, - // that should be rotated around the camera, until it reaches the aim node. + const glm::dvec3 prevCameraToAim = prevCameraToAnchor + anchorToAim.first; + const double aimDistance = glm::length(prevCameraToAim); + const glm::dquat prevRotation = pose.rotation; - const glm::dvec3 prevCameraToVirtualAim = - aimDistance * (prevRotation * Camera::ViewDirectionCameraSpace); + // Introduce a virtual aim - a position straight ahead of the camera, + // that should be rotated around the camera, until it reaches the aim node. - // Max angle: the maximum possible angle between anchor and aim, given that - // the camera orbits the anchor on a fixed distance. - const double maxAngle = - glm::atan(glm::length(anchorToAim.first), glm::length(prevCameraToAnchor)); + const glm::dvec3 prevCameraToVirtualAim = + aimDistance * (prevRotation * Camera::ViewDirectionCameraSpace); - // Requested angle: The angle between the vector straight ahead from the - // camera and the vector from camera to anchor should remain constant, in - // order for the anchor not to move in screen space. - const double requestedAngle = glm::angle( - glm::normalize(prevCameraToVirtualAim), - glm::normalize(prevCameraToAnchor) + // Max angle: the maximum possible angle between anchor and aim, given that + // the camera orbits the anchor on a fixed distance. + const double maxAngle = + glm::atan(glm::length(anchorToAim.first), glm::length(prevCameraToAnchor)); + + // Requested angle: The angle between the vector straight ahead from the + // camera and the vector from camera to anchor should remain constant, in + // order for the anchor not to move in screen space. + const double requestedAngle = glm::angle( + glm::normalize(prevCameraToVirtualAim), + glm::normalize(prevCameraToAnchor) + ); + + if (requestedAngle <= maxAngle) { + const glm::dvec3 aimPos = pose.position + prevCameraToAnchor + anchorToAim.second; + const CameraRotationDecomposition aimDecomp = decomposeCameraRotation( + pose, + aimPos ); - if (requestedAngle <= maxAngle) { - glm::dvec3 aimPos = pose.position + prevCameraToAnchor + anchorToAim.second; - CameraRotationDecomposition aimDecomp = decomposeCameraRotation(pose, aimPos); + const glm::dquat interpolatedRotation = glm::slerp( + prevRotation, + aimDecomp.globalRotation, + glm::min(t * _retargetAimInterpolator.deltaTimeScaled(), 1.0) + ); - const glm::dquat interpolatedRotation = glm::slerp( - prevRotation, - aimDecomp.globalRotation, - glm::min(t * _retargetAimInterpolator.deltaTimeScaled(), 1.0) - ); + const glm::dvec3 recomputedCameraToVirtualAim = + aimDistance * (interpolatedRotation * Camera::ViewDirectionCameraSpace); - const glm::dvec3 recomputedCameraToVirtualAim = - aimDistance * (interpolatedRotation * Camera::ViewDirectionCameraSpace); - - return { - prevCameraToVirtualAim - prevCameraToAnchor, - recomputedCameraToVirtualAim - prevCameraToAnchor - }; - } - else { - // Bail out. - // Cannot put aim node in center without moving anchor in screen space. - // Future work: Rotate as much as possible, - // or possibly use some other DOF to find solution, like moving the camera. - _retargetAimInterpolator.end(); - } + return { + prevCameraToVirtualAim - prevCameraToAnchor, + recomputedCameraToVirtualAim - prevCameraToAnchor + }; + } + else { + // Bail out. + // Cannot put aim node in center without moving anchor in screen space. + // Future work: Rotate as much as possible, + // or possibly use some other DOF to find solution, like moving the camera. + _retargetAimInterpolator.end(); } return anchorToAim; } @@ -1609,18 +1640,18 @@ double OrbitalNavigator::interpolateCameraToSurfaceDistance(double deltaTime, return targetDistance; } - double t = _cameraToSurfaceDistanceInterpolator.value(); + const double t = _cameraToSurfaceDistanceInterpolator.value(); _cameraToSurfaceDistanceInterpolator.setDeltaTime(static_cast(deltaTime)); _cameraToSurfaceDistanceInterpolator.step(); // Interpolate distance logarithmically - double result = glm::exp(glm::mix( + const double result = glm::exp(glm::mix( glm::log(currentDistance), glm::log(targetDistance), glm::min(t * _cameraToSurfaceDistanceInterpolator.deltaTimeScaled(), 1.0)) ); - double ratio = currentDistance / targetDistance; + const double ratio = currentDistance / targetDistance; if (glm::abs(ratio - 1.0) < 0.000001) { _cameraToSurfaceDistanceInterpolator.end(); } @@ -1641,12 +1672,12 @@ void OrbitalNavigator::rotateAroundAnchorUp(double deltaTime, double speedScale, } }(UpDirectionChoice(_upToUseForRotation.value())); - double combinedXInput = _mouseStates.globalRotationVelocity().x + + const double combinedXInput = _mouseStates.globalRotationVelocity().x + _joystickStates.globalRotationVelocity().x + _websocketStates.globalRotationVelocity().x + _scriptStates.globalRotationVelocity().x; - double angle = combinedXInput * deltaTime * speedScale; + const double angle = combinedXInput * deltaTime * speedScale; orbitAroundAxis(axis, angle, cameraPosition, globalCameraRotation); } @@ -1658,9 +1689,9 @@ glm::dvec3 OrbitalNavigator::translateHorizontally(double deltaTime, double spee { // If we are orbiting around an up vector, we only want to allow verical // movement and not use the x velocity - bool useX = !_shouldRotateAroundUp; + const bool useX = !_shouldRotateAroundUp; - double angleScale = deltaTime * speedScale; + const double angleScale = deltaTime * speedScale; // Get rotation in camera space const glm::dquat mouseRotationDiffCamSpace = glm::dquat(glm::dvec3( @@ -1792,10 +1823,10 @@ glm::dvec3 OrbitalNavigator::pushToSurface(const glm::dvec3& cameraPosition, const glm::dvec3& objectPosition, const SurfacePositionHandle& positionHandle) const { - double minHeight = _limitZoom.enableZoomInLimit ? + const double minHeight = _limitZoom.enableZoomInLimit ? static_cast(_limitZoom.minimumAllowedDistance) : 0.0; - double maxHeight = _limitZoom.enableZoomOutLimit ? + const double maxHeight = _limitZoom.enableZoomOutLimit ? static_cast(_limitZoom.maximumAllowedDistance) : -1.0; if (maxHeight > 0.0 && minHeight > maxHeight) { @@ -1854,24 +1885,6 @@ glm::dquat OrbitalNavigator::interpolateRotationDifferential(double deltaTime, ); } -SurfacePositionHandle OrbitalNavigator::calculateSurfacePositionHandle( - const SceneGraphNode& node, - const glm::dvec3& cameraPositionWorldSpace) const -{ - ghoul_assert( - glm::length(cameraPositionWorldSpace) > 0.0, - "Cannot have degenerate vector" - ); - - const glm::dmat4 inverseModelTransform = glm::inverse(node.modelTransform()); - const glm::dvec3 cameraPositionModelSpace = - glm::dvec3(inverseModelTransform * glm::dvec4(cameraPositionWorldSpace, 1.0)); - const SurfacePositionHandle posHandle = - node.calculateSurfacePositionHandle(cameraPositionModelSpace); - - return posHandle; -} - JoystickCameraStates& OrbitalNavigator::joystickStates() { return _joystickStates; } @@ -1897,7 +1910,7 @@ const ScriptCameraStates& OrbitalNavigator::scriptStates() const { } void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) { - OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode mode = global::openSpaceEngine->currentMode(); if (mode != OpenSpaceEngine::Mode::UserControl) { LERROR( "Could not start idle behavior. The camera is being controlled " @@ -1910,7 +1923,7 @@ void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) { _idleBehavior.chosenBehavior = std::nullopt; } else { - IdleBehavior::Behavior behavior; + IdleBehavior::Behavior behavior = IdleBehavior::Behavior::Orbit; if (choice == IdleKeyOrbit) { behavior = IdleBehavior::Behavior::Orbit; } @@ -1921,9 +1934,9 @@ void OrbitalNavigator::triggerIdleBehavior(std::string_view choice) { behavior = IdleBehavior::Behavior::OrbitAroundUp; } else { - throw ghoul::RuntimeError( - fmt::format("No existing IdleBehavior with identifier '{}'", choice) - ); + throw ghoul::RuntimeError(std::format( + "No existing IdleBehavior with identifier '{}'", choice + )); } _idleBehavior.chosenBehavior = behavior; } @@ -1950,8 +1963,10 @@ void OrbitalNavigator::applyIdleBehavior(double deltaTime, glm::dvec3& position, return; } - SurfacePositionHandle posHandle = - calculateSurfacePositionHandle(*_anchorNode, position); + const SurfacePositionHandle posHandle = calculateSurfacePositionHandle( + *_anchorNode, + position + ); // Same speed scale as horizontal translation double speedScale = rotationSpeedScaleFromCameraHeight(position, posHandle); @@ -1964,10 +1979,10 @@ void OrbitalNavigator::applyIdleBehavior(double deltaTime, glm::dvec3& position, } // Interpolate so that the start and end are smooth - double s = _idleBehaviorDampenInterpolator.value(); + const double s = _idleBehaviorDampenInterpolator.value(); speedScale *= _invertIdleBehaviorInterpolation ? (1.0 - s) : s; - double angle = deltaTime * speedScale; + const double angle = deltaTime * speedScale; // Apply the chosen behavior const IdleBehavior::Behavior choice = _idleBehavior.chosenBehavior.value_or( @@ -2021,7 +2036,7 @@ void OrbitalNavigator::orbitAnchor(double angle, glm::dvec3& position, position += rotationDiffVec3; } -void OrbitalNavigator::orbitAroundAxis(const glm::dvec3 axis, double angle, +void OrbitalNavigator::orbitAroundAxis(const glm::dvec3& axis, double angle, glm::dvec3& position, glm::dquat& globalRotation) { ghoul_assert(_anchorNode != nullptr, "Node to orbit must be set"); diff --git a/src/navigation/path.cpp b/src/navigation/path.cpp index a2bb04cce1..4a89772f36 100644 --- a/src/navigation/path.cpp +++ b/src/navigation/path.cpp @@ -118,8 +118,8 @@ documentation::Documentation Path::Documentation() { } Path::Path(Waypoint start, Waypoint end, Type type, std::optional duration) - : _start(start) - , _end(end) + : _start(std::move(start)) + , _end(std::move(end)) , _type(type) { switch (_type) { @@ -196,7 +196,7 @@ CameraPose Path::traversePath(double dt, float speedScale) { double speed = speedAlongPath(_traveledDistance); speed *= static_cast(speedScale); - double displacement = dt * speed; + const double displacement = dt * speed; const double prevDistance = _traveledDistance; @@ -231,7 +231,7 @@ void Path::quitPath() { } std::string Path::currentAnchor() const { - bool pastHalfway = (_traveledDistance / pathLength()) > 0.5; + const bool pastHalfway = (_traveledDistance / pathLength()) > 0.5; return (pastHalfway) ? _end.nodeIdentifier() : _start.nodeIdentifier(); } @@ -243,10 +243,10 @@ bool Path::hasReachedEnd() const { // @TODO (emmbr, 2022-11-07) Handle linear paths separately, as they might // abort prematurely due to the "isPositionFinished" condition - bool isPositionFinished = (_traveledDistance / pathLength()) >= 1.0; + const bool isPositionFinished = (_traveledDistance / pathLength()) >= 1.0; constexpr double RotationEpsilon = 0.0001; - bool isRotationFinished = ghoul::isSameOrientation( + const bool isRotationFinished = ghoul::isSameOrientation( _prevPose.rotation, _end.rotation(), RotationEpsilon @@ -280,8 +280,8 @@ CameraPose Path::linearInterpolatedPose(double distance, double displacement) { const glm::dvec3 lineDir = glm::normalize(prevPosToEnd); pose.position = _prevPose.position - displacement * lineDir; - double newRemainingDistance = glm::length(pose.position - _end.position()); - double diff = remainingDistance - newRemainingDistance; + const double newRemainingDistance = glm::length(pose.position - _end.position()); + const double diff = remainingDistance - newRemainingDistance; // Avoid remaining distances close to zero, or even negative if (relativeDistance > 0.5 && diff < LengthEpsilon) { // The positions are too large, so we are not making progress because of @@ -342,7 +342,7 @@ glm::dquat Path::linearPathRotation(double) const { double factor = 5.0 / glm::half_pi(); factor *= global::navigationHandler->pathNavigator().linearRotationSpeedFactor(); - double turnDuration = std::max(angle * factor, 1.0); // Always at least 1 second + const double turnDuration = std::max(angle * factor, 1.0); // Always at least 1 second const double time = glm::clamp(_progressedTime / turnDuration, 0.0, 1.0); return easedSlerpRotation(time); @@ -433,10 +433,10 @@ glm::dquat Path::lookAtTargetsRotation(double t) const { // camera, but just the "hint" up vector for the lookAt. This leads to fast rolling // when the up vector gets close to the camera's forward vector. Should be improved // so any rolling is spread out over the entire motion instead - double tUp = ghoul::sineEaseInOut(t); - glm::dvec3 startUp = _start.rotation() * glm::dvec3(0.0, 1.0, 0.0); - glm::dvec3 endUp = _end.rotation() * glm::dvec3(0.0, 1.0, 0.0); - glm::dvec3 up = ghoul::interpolateLinear(tUp, startUp, endUp); + const double tUp = ghoul::sineEaseInOut(t); + const glm::dvec3 startUp = _start.rotation() * glm::dvec3(0.0, 1.0, 0.0); + const glm::dvec3 endUp = _end.rotation() * glm::dvec3(0.0, 1.0, 0.0); + const glm::dvec3 up = ghoul::interpolateLinear(tUp, startUp, endUp); return ghoul::lookAtQuaternion(_curve->positionAt(t), lookAtPos, up); } @@ -448,7 +448,7 @@ double Path::speedAlongPath(double traveledDistance) const { // Set speed based on distance to closest node const double distanceToEndNode = glm::distance(_prevPose.position, endNodePos); const double distanceToStartNode = glm::distance(_prevPose.position, startNodePos); - bool isCloserToEnd = distanceToEndNode < distanceToStartNode; + const bool isCloserToEnd = (distanceToEndNode < distanceToStartNode); const glm::dvec3 closestPos = isCloserToEnd ? endNodePos : startNodePos; const double distanceToClosestNode = glm::distance(closestPos, _prevPose.position); @@ -541,7 +541,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, const std::optional duration = p.duration; - Path::Type type; + Path::Type type = Path::Type::Linear; if (forceType.has_value()) { type = *forceType; } @@ -552,7 +552,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, type = global::navigationHandler->pathNavigator().defaultPathType(); } - bool hasStart = p.startState.has_value(); + const bool hasStart = p.startState.has_value(); const Waypoint startPoint = hasStart ? Waypoint(NavigationState(p.startState.value())) : interaction::waypointFromCamera(); @@ -569,7 +569,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, const SceneGraphNode* targetNode = sceneGraphNode(navigationState.anchor); if (!targetNode) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find anchor node '{}' in provided navigation state", navigationState.anchor )); @@ -587,19 +587,19 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, const SceneGraphNode* targetNode = sceneGraphNode(nodeIdentifier); if (!targetNode) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Could not find target node '{}'", nodeIdentifier )); } - interaction::NodeCameraStateSpec info { + const interaction::NodeCameraStateSpec info { nodeIdentifier, p.position, p.height, p.useTargetUpDirection.value_or(false) }; - double startToTargetCenterDistance = glm::distance( + const double startToTargetCenterDistance = glm::distance( startPoint.position(), targetNode->worldPosition() ); @@ -607,7 +607,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, // Use a linear path if camera start is within the bounding sphere const PathNavigator& navigator = global::navigationHandler->pathNavigator(); const double bs = navigator.findValidBoundingSphere(targetNode); - bool withinTargetBoundingSphere = startToTargetCenterDistance < bs; + const bool withinTargetBoundingSphere = (startToTargetCenterDistance < bs); if (withinTargetBoundingSphere) { LINFO( "Camera is within the bounding sphere of the target node. " @@ -616,7 +616,7 @@ Path createPathFromDictionary(const ghoul::Dictionary& dictionary, type = Path::Type::Linear; } - bool isLinear = type == Path::Type::Linear; + const bool isLinear = type == Path::Type::Linear; waypoints = { computeWaypointFromNodeInfo(info, startPoint, isLinear) }; break; } diff --git a/src/navigation/pathcurve.cpp b/src/navigation/pathcurve.cpp index de9af43d31..8553e6c8dc 100644 --- a/src/navigation/pathcurve.cpp +++ b/src/navigation/pathcurve.cpp @@ -83,9 +83,9 @@ void PathCurve::initializeParameterData() { _lengthSums.reserve(_nSegments + 1); _lengthSums.push_back(0.0); for (unsigned int i = 1; i <= _nSegments; i++) { - double u = _curveParameterSteps[i]; - double uPrev = _curveParameterSteps[i - 1]; - double length = arcLength(uPrev, u); + const double u = _curveParameterSteps[i]; + const double uPrev = _curveParameterSteps[i - 1]; + const double length = arcLength(uPrev, u); _lengthSums.push_back(_lengthSums[i - 1] + length); } _totalLength = _lengthSums.back(); @@ -100,13 +100,13 @@ void PathCurve::initializeParameterData() { _parameterSamples.reserve(Steps * _nSegments + 1); for (unsigned int i = 0; i < _nSegments; i++) { - double uStart = _curveParameterSteps[i]; - double sStart = _lengthSums[i]; + const double uStart = _curveParameterSteps[i]; + const double sStart = _lengthSums[i]; _parameterSamples.push_back({ uStart, sStart }); // Intermediate sampels - for (int j = 1; j < Steps; ++j) { - double u = uStart + j * uStep; - double s = sStart + arcLength(uStart, u); + for (int j = 1; j < Steps; j++) { + const double u = uStart + j * uStep; + const double s = sStart + arcLength(uStart, u); // Identify samples that are indistinguishable due to precision limitations if (std::abs(s - _parameterSamples.back().s) < LengthEpsilon) { throw InsufficientPrecisionError( @@ -133,8 +133,12 @@ void PathCurve::initializeParameterData() { // Input s is a length value, in the range [0, _totalLength] // Returns curve parameter in range [0, _nSegments] double PathCurve::curveParameter(double s) const { - if (s <= 0.0) return 0.0; - if (s >= (_totalLength - LengthEpsilon)) return _curveParameterSteps.back(); + if (s <= 0.0) { + return 0.0; + } + if (s >= (_totalLength - LengthEpsilon)) { + return _curveParameterSteps.back(); + } unsigned int segmentIndex = 1; while (s > _lengthSums[segmentIndex]) { @@ -158,8 +162,8 @@ double PathCurve::curveParameter(double s) const { return std::distance(samples.begin(), it); }; - size_t startIndex = findIndexOfFirstEqualOrLarger_u(uMin); - size_t endIndex = findIndexOfFirstEqualOrLarger_u(uMax); + const size_t startIndex = findIndexOfFirstEqualOrLarger_u(uMin); + const size_t endIndex = findIndexOfFirstEqualOrLarger_u(uMax); // Use samples to find an initial guess for Newton's method // Find first sample with s larger than input s @@ -185,8 +189,8 @@ double PathCurve::curveParameter(double s) const { double lower = uMin; double upper = uMax; - for (int i = 0; i < maxIterations; ++i) { - double F = arcLength(uMin, u) - segmentS; + for (int i = 0; i < maxIterations; i++) { + const double F = arcLength(uMin, u) - segmentS; // The error we tolerate, in meters. Note that distances are very large constexpr double tolerance = 0.5; @@ -195,8 +199,8 @@ double PathCurve::curveParameter(double s) const { } // Generate a candidate for Newton's method - double dfdu = approximatedDerivative(u); // > 0 - double uCandidate = u - F / dfdu; + const double dfdu = approximatedDerivative(u); // > 0 + const double uCandidate = u - F / dfdu; // Update root-bounding interval and test candidate if (F > 0) { // => candidate < u <= upper @@ -248,15 +252,15 @@ glm::dvec3 PathCurve::interpolate(double u) const { return *(_points.end() - 2); } - std::vector::const_iterator segmentEndIt = + const std::vector::const_iterator segmentEndIt = std::lower_bound(_curveParameterSteps.begin(), _curveParameterSteps.end(), u); const int index = static_cast((segmentEndIt - 1) - _curveParameterSteps.begin()); - double segmentStart = _curveParameterSteps[index]; - double segmentDuration = (_curveParameterSteps[index + 1] - segmentStart); - double uSegment = (u - segmentStart) / segmentDuration; + const double segmentStart = _curveParameterSteps[index]; + const double segmentDuration = (_curveParameterSteps[index + 1] - segmentStart); + const double uSegment = (u - segmentStart) / segmentDuration; return ghoul::interpolateCatmullRom( uSegment, diff --git a/src/navigation/pathcurves/avoidcollisioncurve.cpp b/src/navigation/pathcurves/avoidcollisioncurve.cpp index 9070cc94e5..ebb3286e48 100644 --- a/src/navigation/pathcurves/avoidcollisioncurve.cpp +++ b/src/navigation/pathcurves/avoidcollisioncurve.cpp @@ -51,9 +51,9 @@ namespace { namespace openspace::interaction { -AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) { - _relevantNodes = global::navigationHandler->pathNavigator().relevantNodes(); - +AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) + : _relevantNodes(global::navigationHandler->pathNavigator().relevantNodes()) +{ if (!start.node() || !end.node()) { // guard, but should never happen LERROR("Something went wrong. The start or end node does not exist"); return; @@ -70,7 +70,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& _points.push_back(start.position()); // Add an extra point to first go backwards if starting close to planet - glm::dvec3 nodeToStart = start.position() - startNodeCenter; + const glm::dvec3 nodeToStart = start.position() - startNodeCenter; const double distanceToStartNode = glm::length(nodeToStart); // Note that the factor 2.0 is arbitrarily chosen to look ok. @@ -83,8 +83,8 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& if (distanceToStartNode < closeToNodeThresholdFactor * startNodeRadius) { const double distance = startNodeRadius; - glm::dvec3 newPos = start.position() + distance * glm::normalize(nodeToStart); - _points.push_back(newPos); + glm::dvec3 newP = start.position() + distance * glm::normalize(nodeToStart); + _points.push_back(std::move(newP)); } const glm::dvec3 startToEnd = end.position() - start.position(); @@ -92,12 +92,12 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& // Add point for moving out if the end state is far away and in opposite direction. // This helps with avoiding fast rotation in the center of the path const double maxRadius = std::max(startNodeRadius, endNodeRadius); - bool nodesAreDifferent = start.nodeIdentifier() != end.nodeIdentifier(); + const bool nodesAreDifferent = (start.nodeIdentifier() != end.nodeIdentifier()); if (glm::length(startToEnd) > 0.5 * maxRadius && nodesAreDifferent) { - double cosAngleToTarget = glm::dot( + const double cosAngleToTarget = glm::dot( normalize(-startViewDir), normalize(startToEnd) ); - bool targetInOppositeDirection = cosAngleToTarget > 0.7; + const bool targetInOppositeDirection = (cosAngleToTarget > 0.7); if (targetInOppositeDirection) { const glm::dquat midleRot = glm::slerp(start.rotation(), end.rotation(), 0.5); @@ -106,8 +106,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& glm::dvec3 newPos = start.position() + 0.2 * startToEnd - stepOutDistance * glm::normalize(middleViewDir); - - _points.push_back(newPos); + _points.push_back(std::move(newPos)); } } @@ -118,7 +117,7 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& if (distanceToEndNode < closeToNodeThresholdFactor * endNodeRadius) { const double distance = endNodeRadius; glm::dvec3 newPos = end.position() + distance * glm::normalize(nodeToEnd); - _points.push_back(newPos); + _points.push_back(std::move(newPos)); } _points.push_back(end.position()); @@ -139,7 +138,7 @@ void AvoidCollisionCurve::removeCollisions(int step) { } const int nSegments = static_cast(_points.size() - 3); - for (int i = 0; i < nSegments; ++i) { + for (int i = 0; i < nSegments; i++) { const glm::dvec3 lineStart = _points[i + 1]; const glm::dvec3 lineEnd = _points[i + 2]; @@ -148,32 +147,36 @@ void AvoidCollisionCurve::removeCollisions(int step) { } for (SceneGraphNode* node : _relevantNodes) { + using namespace collision; + // Do collision check in relative coordinates, to avoid huge numbers const glm::dmat4 modelTransform = node->modelTransform(); - glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0); - glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0); + const glm::dvec3 p1 = + glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0); + const glm::dvec3 p2 = + glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0); // Sphere to check for collision. Make sure it does not have radius zero. const double minValidBoundingSphere = global::navigationHandler->pathNavigator().minValidBoundingSphere(); double radius = std::max(node->boundingSphere(), minValidBoundingSphere); - glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0); + constexpr glm::dvec3 Center = glm::dvec3(0.0, 0.0, 0.0); // Add a buffer to avoid passing too close to the node. // Dont't add it if any point is inside the buffer - double buffer = CollisionBufferSizeRadiusMultiplier * radius; - bool p1IsInside = collision::isPointInsideSphere(p1, center, radius + buffer); - bool p2IsInside = collision::isPointInsideSphere(p2, center, radius + buffer); + const double buffer = CollisionBufferSizeRadiusMultiplier * radius; + const bool p1IsInside = isPointInsideSphere(p1, Center, radius + buffer); + const bool p2IsInside = isPointInsideSphere(p2, Center, radius + buffer); if (!p1IsInside && !p2IsInside) { radius += buffer; } glm::dvec3 intersectionPointModelCoords; - bool collision = collision::lineSphereIntersection( + const bool collision = lineSphereIntersection( p1, p2, - center, + Center, radius, intersectionPointModelCoords ); @@ -182,14 +185,14 @@ void AvoidCollisionCurve::removeCollisions(int step) { continue; } - glm::dvec3 collisionPoint = modelTransform * + const glm::dvec3 collisionPoint = modelTransform * glm::dvec4(intersectionPointModelCoords, 1.0); // before collision response, make sure none of the points are inside the node - bool isStartInsideNode = collision::isPointInsideSphere(p1, center, radius); - bool isEndInsideNode = collision::isPointInsideSphere(p2, center, radius); + const bool isStartInsideNode = isPointInsideSphere(p1, Center, radius); + const bool isEndInsideNode = isPointInsideSphere(p2, Center, radius); if (isStartInsideNode || isEndInsideNode) { - LWARNING(fmt::format( + LWARNING(std::format( "Something went wrong! " "At least one point in the path is inside node: {}", node->identifier() @@ -209,7 +212,7 @@ void AvoidCollisionCurve::removeCollisions(int step) { const double avoidCollisionDistance = AvoidCollisionDistanceRadiusMultiplier * radius; - glm::dvec3 extraKnot = collisionPoint - + const glm::dvec3 extraKnot = collisionPoint - avoidCollisionDistance * glm::normalize(orthogonal); // Don't add invalid positions (indicating precision issues) diff --git a/src/navigation/pathcurves/zoomoutoverviewcurve.cpp b/src/navigation/pathcurves/zoomoutoverviewcurve.cpp index 36367c7224..e34b051a4f 100644 --- a/src/navigation/pathcurves/zoomoutoverviewcurve.cpp +++ b/src/navigation/pathcurves/zoomoutoverviewcurve.cpp @@ -71,8 +71,8 @@ ZoomOutOverviewCurve::ZoomOutOverviewCurve(const Waypoint& start, const Waypoint if (start.nodeIdentifier() != end.nodeIdentifier() && glm::length(startPosToEndPos) > Epsilon) { - const glm::dvec3 n1 = startTangentDir; - const glm::dvec3 n2 = endTangentDir; + const glm::dvec3& n1 = startTangentDir; + const glm::dvec3& n2 = endTangentDir; const glm::dvec3 halfWayPos = start.position() + 0.5 * startPosToEndPos; // Decide the step direction for the "overview point" based on the directions diff --git a/src/navigation/pathnavigator.cpp b/src/navigation/pathnavigator.cpp index 3b1daed7ce..c623b79946 100644 --- a/src/navigation/pathnavigator.cpp +++ b/src/navigation/pathnavigator.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include #include @@ -267,7 +266,7 @@ void PathNavigator::updateCamera(double deltaTime) { // Set anchor node in orbitalNavigator, to render visible nodes and add activate // navigation when we reach the end. - std::string currentAnchor = anchor()->identifier(); + const std::string currentAnchor = anchor()->identifier(); if (currentAnchor != newAnchor) { global::navigationHandler->orbitalNavigator().setFocusNode(newAnchor, false); } @@ -294,7 +293,7 @@ void PathNavigator::updateCamera(double deltaTime) { } void PathNavigator::createPath(const ghoul::Dictionary& dictionary) { - OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); if (m == OpenSpaceEngine::Mode::SessionRecordingPlayback) { // Silently ignore any paths that are being created during a session recording // playback. The camera path should already have been recorded @@ -314,7 +313,7 @@ void PathNavigator::createPath(const ghoul::Dictionary& dictionary) { // Do nothing } catch (const ghoul::RuntimeError& e) { - LERROR(fmt::format("Could not create path. Reason: {}", e.message)); + LERROR(std::format("Could not create path. Reason: {}", e.message)); return; } @@ -334,7 +333,9 @@ void PathNavigator::startPath() { return; } - bool success = global::openSpaceEngine->setMode(OpenSpaceEngine::Mode::CameraPath); + const bool success = global::openSpaceEngine->setMode( + OpenSpaceEngine::Mode::CameraPath + ); if (!success) { LERROR("Could not start camera path"); return; // couldn't switch to camera path mode @@ -427,15 +428,15 @@ double PathNavigator::findValidBoundingSphere(const SceneGraphNode* node) const // Use the biggest of the bounding sphere and interaction sphere, // so we don't accidentally choose a bounding sphere that is much smaller // than the interaction sphere of the node - double bs = n->boundingSphere(); - double is = n->interactionSphere(); + const double bs = n->boundingSphere(); + const double is = n->interactionSphere(); return std::max(is, bs); }; double result = sphere(node); if (result < _minValidBoundingSphere) { - LDEBUG(fmt::format( + LDEBUG(std::format( "The scene graph node '{}' has no, or a very small, bounding sphere. Using " "minimal value of {}. This might lead to unexpected results", node->identifier(), _minValidBoundingSphere.value() @@ -497,7 +498,7 @@ void PathNavigator::findRelevantNodes() { } auto isRelevant = [&relevantTags](const SceneGraphNode* node) { - const std::vector tags = node->tags(); + const std::vector& tags = node->tags(); auto result = std::find_first_of( relevantTags.begin(), relevantTags.end(), @@ -547,7 +548,7 @@ SceneGraphNode* PathNavigator::findNodeNearTarget(const SceneGraphNode* node) { const glm::dvec3 posInModelCoords = glm::inverse(n->modelTransform()) * glm::dvec4(node->worldPosition(), 1.0); - bool isClose = collision::isPointInsideSphere( + const bool isClose = collision::isPointInsideSphere( posInModelCoords, glm::dvec3(0.0, 0.0, 0.0), proximityRadius @@ -561,7 +562,7 @@ SceneGraphNode* PathNavigator::findNodeNearTarget(const SceneGraphNode* node) { return nullptr; } -void PathNavigator::removeRollRotation(CameraPose& pose) { +void PathNavigator::removeRollRotation(CameraPose& pose) const { // The actual position for the camera does not really matter. Use the origin, // to avoid precision problems when we have large values for the position const glm::dvec3 cameraPos = glm::dvec3(0.0); @@ -573,9 +574,9 @@ void PathNavigator::removeRollRotation(CameraPose& pose) { // enough away from the camera constexpr double NotTooCloseDistance = 10000.0; - glm::dvec3 lookAtPos = cameraPos + NotTooCloseDistance * cameraDir; + const glm::dvec3 lookAtPos = cameraPos + NotTooCloseDistance * cameraDir; - glm::dquat rollFreeRotation = ghoul::lookAtQuaternion( + const glm::dquat rollFreeRotation = ghoul::lookAtQuaternion( cameraPos, lookAtPos, camera()->lookUpVectorWorldSpace() diff --git a/src/navigation/pathnavigator_lua.inl b/src/navigation/pathnavigator_lua.inl index 97d8999681..060fe7f0d5 100644 --- a/src/navigation/pathnavigator_lua.inl +++ b/src/navigation/pathnavigator_lua.inl @@ -173,7 +173,7 @@ namespace { } catch (const documentation::SpecificationError& e) { logError(e, "flyToNavigationState"); - throw ghoul::lua::LuaError(fmt::format("Unable to create a path: {}", e.what())); + throw ghoul::lua::LuaError(std::format("Unable to create a path: {}", e.what())); } ghoul::Dictionary instruction; diff --git a/src/navigation/waypoint.cpp b/src/navigation/waypoint.cpp index 155a0852f8..bb8be8f1c5 100644 --- a/src/navigation/waypoint.cpp +++ b/src/navigation/waypoint.cpp @@ -43,14 +43,14 @@ namespace { namespace openspace::interaction { -Waypoint::Waypoint(const glm::dvec3& pos, const glm::dquat& rot, const std::string& ref) - : _nodeIdentifier(ref) +Waypoint::Waypoint(const glm::dvec3& pos, const glm::dquat& rot, std::string ref) + : _nodeIdentifier(std::move(ref)) { _pose = { .position = pos, .rotation = rot }; const SceneGraphNode* node = sceneGraphNode(_nodeIdentifier); if (!node) { - LERROR(fmt::format("Could not find node '{}'", _nodeIdentifier)); + LERROR(std::format("Could not find node '{}'", _nodeIdentifier)); return; } @@ -62,7 +62,7 @@ Waypoint::Waypoint(const NavigationState& ns) { const SceneGraphNode* anchorNode = sceneGraphNode(ns.anchor); if (!anchorNode) { - LERROR(fmt::format("Could not find node '{}' to target", ns.anchor)); + LERROR(std::format("Could not find node '{}' to target", ns.anchor)); return; } @@ -71,7 +71,7 @@ Waypoint::Waypoint(const NavigationState& ns) { if (!ns.aim.empty()) { const SceneGraphNode* aimNode = sceneGraphNode(ns.aim); if (!aimNode) { - LERROR(fmt::format("Could not find node '{}' to use as aim", ns.aim)); + LERROR(std::format("Could not find node '{}' to use as aim", ns.aim)); return; } _aimNodeIdentifier = ns.aim; @@ -172,24 +172,24 @@ glm::dvec3 computeGoodStepDirection(const SceneGraphNode* targetNode, } Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec, - std::optional startPoint, + const std::optional& startPoint, bool useLinear) { const SceneGraphNode* targetNode = sceneGraphNode(spec.identifier); if (!targetNode) { - LERROR(fmt::format("Could not find target node '{}'", spec.identifier)); + LERROR(std::format("Could not find target node '{}'", spec.identifier)); return Waypoint(); } // Use current camera position if no previous point was specified - Waypoint prevPoint = startPoint.value_or(waypointFromCamera()); + const Waypoint prevPoint = startPoint.value_or(waypointFromCamera()); glm::dvec3 stepDir; - glm::dvec3 targetPos; + glm::dvec3 cameraPos; if (spec.position.has_value()) { // The position in instruction is given in the targetNode's local coordinates. // Convert to world coordinates - targetPos = glm::dvec3( + cameraPos = glm::dvec3( targetNode->modelTransform() * glm::dvec4(*spec.position, 1.0) ); } @@ -203,14 +203,14 @@ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec, if (useLinear) { // If linear path, compute position along line form start to end point - glm::dvec3 endNodePos = targetNode->worldPosition(); + const glm::dvec3 endNodePos = targetNode->worldPosition(); stepDir = glm::normalize(prevPoint.position() - endNodePos); } else { stepDir = computeGoodStepDirection(targetNode, prevPoint); } - targetPos = targetNode->worldPosition() + stepDir * distanceFromNodeCenter; + cameraPos = targetNode->worldPosition() + stepDir * distanceFromNodeCenter; } glm::dvec3 up = global::navigationHandler->camera()->lookUpVectorWorldSpace(); @@ -224,20 +224,20 @@ Waypoint computeWaypointFromNodeInfo(const NodeCameraStateSpec& spec, // Compute rotation so the camera is looking at the targetted node glm::dvec3 lookAtPos = targetNode->worldPosition(); - // Check if we can distinguish between targetpos and lookAt pos. Otherwise, move it + // Check if we can distinguish between cameraPos and lookAt pos. Otherwise, move it // further away - const glm::dvec3 diff = targetPos - lookAtPos; - double distSquared = glm::dot(diff, diff); + const glm::dvec3 diff = cameraPos - lookAtPos; + const double distSquared = glm::dot(diff, diff); if (std::isnan(distSquared) || distSquared < LengthEpsilon) { - double startToEndDist = glm::length( + const double startToEndDist = glm::length( prevPoint.position() - targetNode->worldPosition() ); - lookAtPos = targetPos - stepDir * 0.1 * startToEndDist; + lookAtPos = cameraPos - stepDir * 0.1 * startToEndDist; } - const glm::dquat targetRot = ghoul::lookAtQuaternion(targetPos, lookAtPos, up); + const glm::dquat targetRot = ghoul::lookAtQuaternion(cameraPos, lookAtPos, up); - return Waypoint(targetPos, targetRot, spec.identifier); + return Waypoint(cameraPos, targetRot, spec.identifier); } } // namespace openspace::interaction diff --git a/src/network/parallelconnection.cpp b/src/network/parallelconnection.cpp index a2729d1f08..4c51f97286 100644 --- a/src/network/parallelconnection.cpp +++ b/src/network/parallelconnection.cpp @@ -112,13 +112,12 @@ bool ParallelConnection::sendMessage(const Message& message) { reinterpret_cast(&messageSizeOut) + sizeof(uint32_t) ); - if (!_socket->put(header.data(), header.size())) { + const bool res = _socket->put(header.data(), header.size()); + if (!res) { return false; } - if (!_socket->put(message.content.data(), message.content.size())) { - return false; - } - return true; + const bool res2 = _socket->put(message.content.data(), message.content.size()); + return res2; } void ParallelConnection::disconnect() { @@ -158,7 +157,7 @@ ParallelConnection::Message ParallelConnection::receiveMessage() { } // Make sure that header matches this version of OpenSpace - if (!(headerBuffer[0] == 'O' && headerBuffer[1] == 'S')) { + if (headerBuffer[0] != 'O' || headerBuffer[1] != 'S') { LERROR("Expected to read message header 'OS' from socket"); throw ConnectionLostError(); } @@ -169,7 +168,7 @@ ParallelConnection::Message ParallelConnection::receiveMessage() { offset += sizeof(uint8_t); if (protocolVersionIn != ProtocolVersion) { - LERROR(fmt::format( + LERROR(std::format( "Protocol versions do not match. Remote version: {}, Local version: {}", protocolVersionIn, ProtocolVersion diff --git a/src/network/parallelpeer.cpp b/src/network/parallelpeer.cpp index d0c4bafa63..53d7b99f80 100644 --- a/src/network/parallelpeer.cpp +++ b/src/network/parallelpeer.cpp @@ -247,7 +247,7 @@ void ParallelPeer::sendAuthentication() { } void ParallelPeer::queueInMessage(const ParallelConnection::Message& message) { - std::lock_guard unqlock(_receiveBufferMutex); + const std::lock_guard unqlock(_receiveBufferMutex); _receiveBuffer.push_back(message); } @@ -269,7 +269,7 @@ void ParallelPeer::handleMessage(const ParallelConnection::Message& message) { } void ParallelPeer::analyzeTimeDifference(double messageTimestamp) { - std::lock_guard latencyLock(_latencyMutex); + const std::lock_guard latencyLock(_latencyMutex); const double timeDiff = global::windowDelegate->applicationTime() - messageTimestamp; if (_latencyDiffs.empty()) { @@ -283,7 +283,7 @@ void ParallelPeer::analyzeTimeDifference(double messageTimestamp) { } double ParallelPeer::convertTimestamp(double messageTimestamp) { - std::lock_guard latencyLock(_latencyMutex); + const std::lock_guard latencyLock(_latencyMutex); return messageTimestamp + _initialTimeDiff + _bufferTime; } @@ -291,7 +291,7 @@ double ParallelPeer::convertTimestamp(double messageTimestamp) { double ParallelPeer::latencyStandardDeviation() const { double accumulatedLatencyDiffSquared = 0; double accumulatedLatencyDiff = 0; - for (double diff : _latencyDiffs) { + for (const double diff : _latencyDiffs) { accumulatedLatencyDiff += diff; accumulatedLatencyDiffSquared += diff*diff; } @@ -319,11 +319,10 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) { analyzeTimeDifference(timestamp); - std::vector buffer(message.begin() + offset, message.end()); - + const std::vector buffer(message.begin() + offset, message.end()); switch (static_cast(type)) { case datamessagestructures::Type::CameraData: { - datamessagestructures::CameraKeyframe kf(buffer); + const datamessagestructures::CameraKeyframe kf(buffer); const double convertedTimestamp = convertTimestamp(kf._timestamp); global::navigationHandler->keyframeNavigator().removeKeyframesAfter( @@ -345,7 +344,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) { } case datamessagestructures::Type::TimelineData: { const double now = global::windowDelegate->applicationTime(); - datamessagestructures::TimeTimeline timelineMessage(buffer); + const datamessagestructures::TimeTimeline timelineMessage(buffer); if (timelineMessage._clear) { global::timeManager->removeKeyframesAfter( @@ -402,8 +401,9 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) { break; } default: - LERROR(fmt::format( - "Unidentified message with identifier {} received in parallel connection", + LERROR(std::format( + "Unidentified message with identifier '{}' received in parallel " + "connection", type )); break; @@ -434,7 +434,6 @@ void ParallelPeer::connectionStatusMessageReceived(const std::vector& mess if (hostNameSize > 0) { hostName = std::string(&message[pointer], hostNameSize); } - pointer += hostNameSize; if (status > ParallelConnection::Status::Host) { LERROR("Invalid status"); @@ -462,16 +461,17 @@ void ParallelPeer::nConnectionsMessageReceived(const std::vector& message) LERROR("Malformed host info message"); return; } - const uint32_t nConnections = *(reinterpret_cast(&message[0])); + const uint32_t nConnections = *(reinterpret_cast(message.data())); setNConnections(nConnections); } void ParallelPeer::handleCommunication() { while (!_shouldDisconnect && _connection.isConnectedOrConnecting()) { try { - ParallelConnection::Message m = _connection.receiveMessage(); + const ParallelConnection::Message m = _connection.receiveMessage(); queueInMessage(m); - } catch (const ParallelConnection::ConnectionLostError& e) { + } + catch (const ParallelConnection::ConnectionLostError& e) { if (e.shouldLogError) { LERROR("Parallel connection lost"); } @@ -503,18 +503,21 @@ void ParallelPeer::requestHostship() { ); buffer.insert(buffer.end(), hostPw.begin(), hostPw.end()); - _connection.sendMessage(ParallelConnection::Message( - ParallelConnection::MessageType::HostshipRequest, - buffer - )); + _connection.sendMessage( + ParallelConnection::Message( + ParallelConnection::MessageType::HostshipRequest, + buffer + ) + ); } void ParallelPeer::resignHostship() { - std::vector buffer; - _connection.sendMessage(ParallelConnection::Message( - ParallelConnection::MessageType::HostshipResignation, - buffer - )); + _connection.sendMessage( + ParallelConnection::Message( + ParallelConnection::MessageType::HostshipResignation, + std::vector() + ) + ); } void ParallelPeer::setPassword(std::string password) { @@ -536,8 +539,8 @@ void ParallelPeer::sendScript(std::string script) { std::vector buffer; sm.serialize(buffer); - double timestamp = global::windowDelegate->applicationTime(); - ParallelConnection::DataMessage message( + const double timestamp = global::windowDelegate->applicationTime(); + const ParallelConnection::DataMessage message = ParallelConnection::DataMessage( datamessagestructures::Type::ScriptData, timestamp, buffer @@ -548,22 +551,22 @@ void ParallelPeer::sendScript(std::string script) { void ParallelPeer::resetTimeOffset() { global::navigationHandler->keyframeNavigator().clearKeyframes(); global::timeManager->clearKeyframes(); - std::lock_guard latencyLock(_latencyMutex); + const std::lock_guard latencyLock(_latencyMutex); _latencyDiffs.clear(); } void ParallelPeer::preSynchronization() { ZoneScoped; - std::unique_lock unlock(_receiveBufferMutex); + const std::unique_lock unlock(_receiveBufferMutex); while (!_receiveBuffer.empty()) { - ParallelConnection::Message& message = _receiveBuffer.front(); + const ParallelConnection::Message& message = _receiveBuffer.front(); handleMessage(message); _receiveBuffer.pop_front(); } if (isHost()) { - double now = global::windowDelegate->applicationTime(); + const double now = global::windowDelegate->applicationTime(); if (_lastCameraKeyframeTimestamp + _cameraKeyframeInterval < now) { sendCameraKeyframe(); @@ -585,7 +588,7 @@ void ParallelPeer::preSynchronization() { void ParallelPeer::setStatus(ParallelConnection::Status status) { if (_status != status) { - ParallelConnection::Status prevStatus = _status; + const ParallelConnection::Status prevStatus = _status; _status = status; _timeJumped = true; _connectionEvent->publish("statusChanged"); @@ -737,7 +740,7 @@ void ParallelPeer::sendTimeTimeline() { timelineMessage._keyframes.reserve(timeline.nKeyframes()); // Case 1: Copy all keyframes from the native timeline - for (size_t i = 0; i < timeline.nKeyframes(); ++i) { + for (size_t i = 0; i < timeline.nKeyframes(); i++) { const Keyframe& kf = keyframes.at(i); datamessagestructures::TimeKeyframe kfMessage; @@ -767,7 +770,7 @@ void ParallelPeer::sendTimeTimeline() { // Fill the timeline buffer timelineMessage.serialize(buffer); - double timestamp = global::windowDelegate->applicationTime(); + const double timestamp = global::windowDelegate->applicationTime(); // Send message _connection.sendDataMessage(ParallelConnection::DataMessage( datamessagestructures::Type::TimelineData, diff --git a/src/properties/list/doublelistproperty.cpp b/src/properties/list/doublelistproperty.cpp index f7918f0afc..eb3ae55a6b 100644 --- a/src/properties/list/doublelistproperty.cpp +++ b/src/properties/list/doublelistproperty.cpp @@ -46,7 +46,7 @@ int DoubleListProperty::typeLua() const { } std::string DoubleListProperty::toStringConversion() const { - nlohmann::json json(_value); + const nlohmann::json json(_value); return json.dump(); } diff --git a/src/properties/list/intlistproperty.cpp b/src/properties/list/intlistproperty.cpp index 04b30da344..82669b0ad5 100644 --- a/src/properties/list/intlistproperty.cpp +++ b/src/properties/list/intlistproperty.cpp @@ -45,7 +45,7 @@ int IntListProperty::typeLua() const { } std::string IntListProperty::toStringConversion() const { - nlohmann::json json(_value); + const nlohmann::json json = _value; return json.dump(); } diff --git a/src/properties/list/stringlistproperty.cpp b/src/properties/list/stringlistproperty.cpp index 8f1458f063..64f198f4d7 100644 --- a/src/properties/list/stringlistproperty.cpp +++ b/src/properties/list/stringlistproperty.cpp @@ -46,7 +46,7 @@ int StringListProperty::typeLua() const { } std::string StringListProperty::toStringConversion() const { - nlohmann::json json(_value); + const nlohmann::json json = nlohmann::json(_value); return json.dump(); } diff --git a/src/properties/optionproperty.cpp b/src/properties/optionproperty.cpp index 66c771a8c3..98b1be9a3c 100644 --- a/src/properties/optionproperty.cpp +++ b/src/properties/optionproperty.cpp @@ -59,11 +59,11 @@ const std::vector& OptionProperty::options() const { } void OptionProperty::addOption(int value, std::string desc) { - Option option = { .value = std::move(value), .description = std::move(desc) }; + Option option = { .value = value, .description = std::move(desc) }; for (const Option& o : _options) { if (o.value == option.value) { - LWARNING(fmt::format( + LWARNING(std::format( "The value of option {{ {} -> {} }} was already registered when trying " "to add option {{ {} -> {} }}", o.value, o.description, option.value, option.description @@ -79,12 +79,12 @@ void OptionProperty::addOption(int value, std::string desc) { void OptionProperty::addOptions(std::vector> options) { for (std::pair& p : options) { - addOption(std::move(p.first), std::move(p.second)); + addOption(p.first, std::move(p.second)); } } void OptionProperty::addOptions(std::vector options) { - for (int i = 0; i < static_cast(options.size()); ++i) { + for (int i = 0; i < static_cast(options.size()); i++) { addOption(i, std::move(options[i])); } } @@ -96,9 +96,8 @@ void OptionProperty::clearOptions() { void OptionProperty::setValue(int value) { // Check if the passed value belongs to any option - for (size_t i = 0; i < _options.size(); ++i) { - const Option& o = _options[i]; - if (o.value == value) { + for (const Option& option : _options) { + if (option.value == value) { // If it does, set it by calling the superclasses setValue method // @TODO(abock): This should be setValue(value) instead or otherwise the // stored indices and option values start to drift if the @@ -109,7 +108,7 @@ void OptionProperty::setValue(int value) { } // Otherwise, log an error - LERROR(fmt::format("Could not find an option for value '{}'", value)); + LERROR(std::format("Could not find an option for value '{}'", value)); } bool OptionProperty::hasOption() const { @@ -154,17 +153,16 @@ std::string OptionProperty::getDescriptionByValue(int value) { std::string OptionProperty::generateAdditionalJsonDescription() const { // @REFACTOR from selectionproperty.cpp, possible refactoring? ---abock - std::string result = - "{ \"" + OptionsKey + "\": ["; - for (size_t i = 0; i < _options.size(); ++i) { + std::string result = "{ \"" + OptionsKey + "\": ["; + for (size_t i = 0; i < _options.size(); i++) { const Option& o = _options[i]; - std::string v = std::to_string(o.value); - std::string vSan = escapedJson(v); - std::string d = o.description; - std::string dSan = escapedJson(d); + const std::string v = std::to_string(o.value); + const std::string vSan = escapedJson(v); + const std::string d = o.description; + const std::string dSan = escapedJson(d); result += '{'; - result += fmt::format(R"("{}": "{}")", vSan, dSan); + result += std::format(R"("{}": "{}")", vSan, dSan); result += '}'; if (i != _options.size() - 1) { diff --git a/src/properties/property.cpp b/src/properties/property.cpp index 344f7721dd..ef54ba8367 100644 --- a/src/properties/property.cpp +++ b/src/properties/property.cpp @@ -80,9 +80,9 @@ std::string Property::fullyQualifiedIdentifier() const { std::string identifier = _identifier; PropertyOwner* currentOwner = owner(); while (currentOwner) { - std::string ownerId = currentOwner->identifier(); + const std::string& ownerId = currentOwner->identifier(); if (!ownerId.empty()) { - identifier = ownerId + "." + identifier; + identifier = std::format("{}.{}", ownerId, identifier); } currentOwner = currentOwner->owner(); } @@ -157,7 +157,7 @@ void Property::setNeedsConfirmation(bool state) { void Property::setViewOption(std::string option, bool value) { ghoul::Dictionary d; - d.setValue(option, value); + d.setValue(std::move(option), value); _metaData.setValue(std::string(MetaDataKeyViewOptions), d); } @@ -165,7 +165,8 @@ bool Property::viewOption(const std::string& option, bool defaultValue) const { if (!_metaData.hasValue(MetaDataKeyViewOptions)) { return defaultValue; } - ghoul::Dictionary d = _metaData.value(MetaDataKeyViewOptions); + const ghoul::Dictionary d = + _metaData.value(MetaDataKeyViewOptions); if (d.hasKey(option)) { return d.value(option); } @@ -185,7 +186,7 @@ std::string Property::jsonValue() const { Property::OnChangeHandle Property::onChange(std::function callback) { ghoul_assert(callback, "The callback must not be empty"); - OnChangeHandle handle = _currentHandleValue++; + const OnChangeHandle handle = _currentHandleValue++; _onChangeCallbacks.emplace_back(handle, std::move(callback)); return handle; } @@ -193,7 +194,7 @@ Property::OnChangeHandle Property::onChange(std::function callback) { Property::OnChangeHandle Property::onDelete(std::function callback) { ghoul_assert(callback, "The callback must not be empty"); - OnDeleteHandle handle = _currentHandleValue++; + const OnDeleteHandle handle = _currentHandleValue++; _onDeleteCallbacks.emplace_back(handle, std::move(callback)); return handle; } @@ -266,15 +267,15 @@ void Property::resetToUnchanged() { } std::string Property::generateJsonDescription() const { - std::string cName = escapedJson(std::string(className())); - std::string identifier = fullyQualifiedIdentifier(); - std::string identifierSan = escapedJson(identifier); - std::string gName = guiName(); - std::string gNameSan = escapedJson(gName); - std::string metaData = generateMetaDataJsonDescription(); - std::string description = generateAdditionalJsonDescription(); + const std::string cName = escapedJson(std::string(className())); + const std::string identifier = fullyQualifiedIdentifier(); + const std::string identifierSan = escapedJson(identifier); + const std::string gName = guiName(); + const std::string gNameSan = escapedJson(gName); + const std::string metaData = generateMetaDataJsonDescription(); + const std::string description = generateAdditionalJsonDescription(); - return fmt::format( + return std::format( R"({{"{}":"{}","{}":"{}","{}":"{}","{}":{},"{}":{}}})", TypeKey, cName, IdentifierKey, identifierSan, NameKey, gNameSan, MetaDataKey, metaData, AdditionalDataKey, description @@ -290,8 +291,9 @@ std::string Property::generateMetaDataJsonDescription() const { { Visibility::Developer, "Developer" }, { Visibility::Hidden, "Hidden" } }; - Visibility visibility = static_cast( - _metaData.value>(MetaDataKeyVisibility)); + const Visibility visibility = static_cast( + _metaData.value>(MetaDataKeyVisibility) + ); const std::string& vis = VisibilityConverter.at(visibility); bool isReadOnly = false; @@ -306,8 +308,8 @@ std::string Property::generateMetaDataJsonDescription() const { } std::string needsConfirmationString = (needsConfirmation ? "true" : "false"); - std::string groupId = groupIdentifier(); - std::string sanitizedGroupId = escapedJson(groupId); + const std::string groupId = groupIdentifier(); + const std::string sanitizedGroupId = escapedJson(groupId); std::string viewOptions = "{}"; if (_metaData.hasValue(MetaDataKeyViewOptions)) { @@ -316,7 +318,7 @@ std::string Property::generateMetaDataJsonDescription() const { ); } - std::string result = fmt::format( + std::string result = std::format( R"({{"{}":"{}","{}":"{}","{}":{},"{}":{},"{}":{}}})", MetaDataKeyGroup, sanitizedGroupId, MetaDataKeyVisibility, vis, diff --git a/src/properties/propertyowner.cpp b/src/properties/propertyowner.cpp index 0f4ddc8eb0..29e87914b6 100644 --- a/src/properties/propertyowner.cpp +++ b/src/properties/propertyowner.cpp @@ -178,7 +178,7 @@ void PropertyOwner::addProperty(Property* prop) { // If we found the property identifier, we need to bail out if (it != _properties.end() && (*it)->identifier() == prop->identifier()) { - LERROR(fmt::format( + LERROR(std::format( "Property identifier '{}' already present in PropertyOwner '{}'", prop->identifier(), identifier() @@ -189,7 +189,7 @@ void PropertyOwner::addProperty(Property* prop) { // Otherwise we still have to look if there is a PropertyOwner with the same name const bool hasOwner = hasPropertySubOwner(prop->identifier()); if (hasOwner) { - LERROR(fmt::format( + LERROR(std::format( "Property identifier '{}' already names a registered PropertyOwner", prop->identifier() )); @@ -224,7 +224,7 @@ void PropertyOwner::addPropertySubOwner(openspace::properties::PropertyOwner* ow // If we found the propertyowner's name, we need to bail out if (it != _subOwners.end() && (*it)->identifier() == owner->identifier()) { - LERROR(fmt::format( + LERROR(std::format( "PropertyOwner '{}' already present in PropertyOwner '{}'", owner->identifier(), identifier() @@ -235,7 +235,7 @@ void PropertyOwner::addPropertySubOwner(openspace::properties::PropertyOwner* ow // We still need to check if the PropertyOwners name is used in a Property const bool hasProp = hasProperty(owner->identifier()); if (hasProp) { - LERROR(fmt::format( + LERROR(std::format( "PropertyOwner '{}'s name already names a Property", owner->identifier() )); return; @@ -267,7 +267,7 @@ void PropertyOwner::removeProperty(Property* prop) { _properties.erase(it); } else { - LERROR(fmt::format( + LERROR(std::format( "Property with identifier '{}' not found for removal", prop->identifier() )); } @@ -294,7 +294,7 @@ void PropertyOwner::removePropertySubOwner(openspace::properties::PropertyOwner* _subOwners.erase(it); } else { - LERROR(fmt::format( + LERROR(std::format( "PropertyOwner with name '{}' not found for removal", owner->identifier() )); } diff --git a/src/properties/scalar/intproperty.cpp b/src/properties/scalar/intproperty.cpp index 9f40b17364..af10f72e5d 100644 --- a/src/properties/scalar/intproperty.cpp +++ b/src/properties/scalar/intproperty.cpp @@ -49,7 +49,7 @@ int IntProperty::fromLuaConversion(lua_State* state) const { return ghoul::lua::value(state); } else { - throw ghoul::RuntimeError(fmt::format("Error extracting value in IntProperty")); + throw ghoul::RuntimeError("Error extracting value in IntProperty"); } } diff --git a/src/properties/scalar/uintproperty.cpp b/src/properties/scalar/uintproperty.cpp index e46c829520..03b454604c 100644 --- a/src/properties/scalar/uintproperty.cpp +++ b/src/properties/scalar/uintproperty.cpp @@ -56,7 +56,7 @@ unsigned int UIntProperty::fromLuaConversion(lua_State* state) const { return ghoul::lua::value(state); } else { - throw ghoul::RuntimeError(fmt::format("Error extracting value in UIntProperty")); + throw ghoul::RuntimeError("Error extracting value in UIntProperty"); } } diff --git a/src/properties/selectionproperty.cpp b/src/properties/selectionproperty.cpp index 982d8b107f..c652b05c85 100644 --- a/src/properties/selectionproperty.cpp +++ b/src/properties/selectionproperty.cpp @@ -92,14 +92,14 @@ void SelectionProperty::setOptions(const std::vector& keys) { _options.push_back(key); } else { - LWARNING(fmt::format("Ignoring duplicated key '{}'", key)); + LWARNING(std::format("Ignoring duplicated key '{}'", key)); } } _options.shrink_to_fit(); sortOptions(); // In case we have a selection, remove non-existing options - bool changed = removeInvalidKeys(_value); + const bool changed = removeInvalidKeys(_value); if (changed) { _isValueDirty = true; } @@ -109,7 +109,7 @@ void SelectionProperty::setOptions(const std::vector& keys) { void SelectionProperty::addOption(const std::string& key) { if (hasOption(key)) { - LWARNING(fmt::format("Cannot add option. Key '{}' already exists", key)); + LWARNING(std::format("Cannot add option. Key '{}' already exists", key)); return; } @@ -135,12 +135,12 @@ std::set SelectionProperty::fromLuaConversion(lua_State* state) con } void SelectionProperty::toLuaConversion(lua_State* state) const { - std::vector value(_value.begin(), _value.end()); + const std::vector value(_value.begin(), _value.end()); ghoul::lua::push(state, value); } std::string SelectionProperty::toStringConversion() const { - nlohmann::json json(_value); + const nlohmann::json json(_value); return json.dump(); } @@ -148,29 +148,29 @@ void SelectionProperty::sortOptions() { std::sort(_options.begin(), _options.end()); } -bool SelectionProperty::removeInvalidKeys(std::set& keys) { +bool SelectionProperty::removeInvalidKeys(std::set& keys) const { bool changed = false; - std::set::iterator it = keys.begin(); + auto it = keys.begin(); while (it != keys.end()) { if (!hasOption(*it)) { - LWARNING(fmt::format( + LWARNING(std::format( "Key '{}' is not a valid option and is removed from selection", *it )); it = keys.erase(it); changed = true; } else { - ++it; + it++; } } return changed; } std::string SelectionProperty::generateAdditionalJsonDescription() const { - nlohmann::json optionsJson(_options); - std::string result = "{ "; - result += fmt::format("\"{}\": {}", OptionsKey, optionsJson.dump()); - result += " }"; + const nlohmann::json optionsJson(_options); + std::string result = std::format( + R"({{ "{}": {} }})", OptionsKey, optionsJson.dump() + ); return result; } diff --git a/src/properties/stringproperty.cpp b/src/properties/stringproperty.cpp index 5f114bbce7..492420dd2d 100644 --- a/src/properties/stringproperty.cpp +++ b/src/properties/stringproperty.cpp @@ -31,7 +31,7 @@ namespace openspace::properties { StringProperty::StringProperty(Property::PropertyInfo info, std::string value) - : TemplateProperty(info, value) + : TemplateProperty(std::move(info), std::move(value)) {} std::string_view StringProperty::className() const { diff --git a/src/query/query.cpp b/src/query/query.cpp index c932accdb5..4bb2d64e87 100644 --- a/src/query/query.cpp +++ b/src/query/query.cpp @@ -59,4 +59,4 @@ std::vector allProperties() { return global::rootPropertyOwner->propertiesRecursive(); } -} // namespace +} // namespace openspace diff --git a/src/rendering/colormappingcomponent.cpp b/src/rendering/colormappingcomponent.cpp index ddac7f80dd..6070f3c4af 100644 --- a/src/rendering/colormappingcomponent.cpp +++ b/src/rendering/colormappingcomponent.cpp @@ -240,9 +240,9 @@ ColorMappingComponent::ColorMappingComponent() addProperty(setRangeFromData); colorMapFile.onChange([this]() { - bool fileExists = std::filesystem::exists(colorMapFile.value()); + const bool fileExists = std::filesystem::exists(colorMapFile.value()); if (!fileExists) { - LERROR(fmt::format("Could not find cmap file: '{}'", colorMapFile.value())); + LERROR(std::format("Could not find cmap file: {}", colorMapFile.value())); } _colorMapFileIsDirty = true; }); @@ -280,7 +280,7 @@ ColorMappingComponent::ColorMappingComponent(const ghoul::Dictionary& dictionary std::vector opts = *p.parameterOptions; _colorRangeData.reserve(opts.size()); - for (size_t i = 0; i < opts.size(); ++i) { + for (size_t i = 0; i < opts.size(); i++) { dataColumn.addOption(static_cast(i), opts[i].key); // Add the provided range or an empty range. We will fill it later on, // when the dataset is loaded, if it is empty @@ -321,6 +321,8 @@ ColorMappingComponent::ColorMappingComponent(const ghoul::Dictionary& dictionary if (p.file.has_value()) { colorMapFile = absPath(*p.file).string(); } + + invert = p.invert.value_or(invert); } ghoul::opengl::Texture* ColorMappingComponent::texture() const { @@ -354,9 +356,9 @@ void ColorMappingComponent::initializeTexture() { return; } - unsigned int width = static_cast(_colorMap.entries.size()); - unsigned int height = 1; - unsigned int size = width * height; + const unsigned int width = static_cast(_colorMap.entries.size()); + const unsigned int height = 1; + const unsigned int size = width * height; std::vector img; img.reserve(size * 4); @@ -399,14 +401,14 @@ void ColorMappingComponent::update(const dataloader::Dataset& dataset) { } glm::vec4 ColorMappingComponent::colorFromColorMap(float valueToColorFrom) const { - glm::vec2 currentColorRange = valueRange; - float cmax = currentColorRange.y; - float cmin = currentColorRange.x; + const glm::vec2 currentColorRange = valueRange; + const float cmax = currentColorRange.y; + const float cmin = currentColorRange.x; - float nColors = static_cast(_colorMap.entries.size()); + const float nColors = static_cast(_colorMap.entries.size()); - bool isOutsideMin = valueToColorFrom < cmin; - bool isOutsideMax = valueToColorFrom > cmax; + const bool isOutsideMin = valueToColorFrom < cmin; + const bool isOutsideMax = valueToColorFrom > cmax; if (hideOutsideRange && (isOutsideMin || isOutsideMax)) { return glm::vec4(0.f); @@ -417,7 +419,7 @@ glm::vec4 ColorMappingComponent::colorFromColorMap(float valueToColorFrom) const } // Find color value using Nearest neighbor (same as texture) - float normalization = (cmax != cmin) ? (nColors) / (cmax - cmin) : 0; + const float normalization = (cmax != cmin) ? (nColors) / (cmax - cmin) : 0; int colorIndex = static_cast((valueToColorFrom - cmin) * normalization); // Clamp color index to valid range @@ -434,8 +436,8 @@ void ColorMappingComponent::initializeParameterData(const dataloader::Dataset& d // Initialize empty ranges based on values in the dataset for (const properties::OptionProperty::Option& option : dataColumn.options()) { - int optionIndex = option.value; - int colorParameterIndex = dataset.index(option.description); + const int optionIndex = option.value; + const int colorParameterIndex = dataset.index(option.description); glm::vec2& range = _colorRangeData[optionIndex]; if (glm::length(range) < glm::epsilon()) { @@ -464,7 +466,7 @@ void ColorMappingComponent::initializeParameterData(const dataloader::Dataset& d } else { // Otherwise, check if the selected columns exist - for (size_t i = 0; i < dataColumn.options().size(); ++i) { + for (size_t i = 0; i < dataColumn.options().size(); i++) { std::string o = dataColumn.options()[i].description; bool found = false; @@ -476,7 +478,7 @@ void ColorMappingComponent::initializeParameterData(const dataloader::Dataset& d } if (!found) { - LWARNING(fmt::format( + LWARNING(std::format( "Dataset does not contain specified parameter '{}'", o )); } @@ -489,7 +491,7 @@ void ColorMappingComponent::initializeParameterData(const dataloader::Dataset& d if (_providedParameter.has_value()) { if (indexOfProvidedOption == -1) { - LERROR(fmt::format( + LERROR(std::format( "Error when reading Parameter. Could not find provided parameter '{}' in " "list of parameter options", *_providedParameter )); diff --git a/src/rendering/dashboard_lua.inl b/src/rendering/dashboard_lua.inl index 0cc98277cb..a7533b834a 100644 --- a/src/rendering/dashboard_lua.inl +++ b/src/rendering/dashboard_lua.inl @@ -33,7 +33,7 @@ namespace { ); } catch (const ghoul::RuntimeError& e) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Error adding dashboard item: {}", e.what() )); } diff --git a/src/rendering/dashboarditem.cpp b/src/rendering/dashboarditem.cpp index 2fce1a640f..2d73518b8b 100644 --- a/src/rendering/dashboarditem.cpp +++ b/src/rendering/dashboarditem.cpp @@ -61,7 +61,7 @@ documentation::Documentation DashboardItem::Documentation() { } std::unique_ptr DashboardItem::createFromDictionary( - ghoul::Dictionary dictionary) + const ghoul::Dictionary& dictionary) { ghoul::TemplateFactory* factory = FactoryManager::ref().factory(); @@ -69,7 +69,7 @@ std::unique_ptr DashboardItem::createFromDictionary( const std::string& dashboardType = dictionary.value(KeyType); - DashboardItem* item = factory->create(dashboardType, std::move(dictionary)); + DashboardItem* item = factory->create(dashboardType, dictionary); item->_type = dashboardType; return std::unique_ptr(item); diff --git a/src/rendering/framebufferrenderer.cpp b/src/rendering/framebufferrenderer.cpp index 0d650e91f4..d63722b271 100644 --- a/src/rendering/framebufferrenderer.cpp +++ b/src/rendering/framebufferrenderer.cpp @@ -77,7 +77,7 @@ namespace { constexpr std::string_view RenderFragmentShaderPath = "${SHADERS}/framebuffer/renderframebuffer.frag"; - const GLenum ColorAttachmentArray[4] = { + constexpr std::array ColorAttachmentArray = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, @@ -92,7 +92,7 @@ namespace openspace { //============================// GLuint FramebufferRenderer::additionalColorTexture1() const { // Gives access to the currently NOT used pingPongTexture - int unusedPingPongIndex = _pingPongIndex == 0 ? 1 : 0; + const int unusedPingPongIndex = _pingPongIndex == 0 ? 1 : 0; return _pingPongBuffers.colorTexture[unusedPingPongIndex]; } @@ -140,7 +140,7 @@ void FramebufferRenderer::initialize() { LDEBUG("Initializing FramebufferRenderer"); - const GLfloat vertexData[] = { + constexpr std::array VertexData = { // x y -1.f, -1.f, 1.f, 1.f, @@ -156,8 +156,8 @@ void FramebufferRenderer::initialize() { glGenBuffers(1, &_vertexPositionBuffer); glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 2, nullptr); + glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData.data(), GL_STATIC_DRAW); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(0); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); @@ -492,8 +492,8 @@ void FramebufferRenderer::applyFXAA(const glm::ivec4& viewport) { renderedTextureUnit ); - glm::vec2 inverseScreenSize = glm::vec2(1.f / _resolution.x, 1.f / _resolution.y); - _fxaaProgram->setUniform(_fxaaUniformCache.inverseScreenSize, inverseScreenSize); + const glm::vec2 invScreenSize = glm::vec2(1.f / _resolution.x, 1.f / _resolution.y); + _fxaaProgram->setUniform(_fxaaUniformCache.inverseScreenSize, invScreenSize); _fxaaProgram->setUniform(_fxaaUniformCache.Viewport, glm::vec4(viewport)); _fxaaProgram->setUniform(_fxaaUniformCache.Resolution, glm::vec2(_resolution)); @@ -510,8 +510,8 @@ void FramebufferRenderer::applyFXAA(const glm::ivec4& viewport) { _fxaaProgram->deactivate(); } -void FramebufferRenderer::updateDownscaleTextures() { - float cdf = _downscaleVolumeRendering.currentDownscaleFactor; +void FramebufferRenderer::updateDownscaleTextures() const { + const float cdf = _downscaleVolumeRendering.currentDownscaleFactor; glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture); glTexImage2D( @@ -833,7 +833,7 @@ void FramebufferRenderer::updateResolution() { glObjectLabel(GL_TEXTURE, _fxaaBuffers.fxaaTexture, -1, "FXAA"); } - float cdf = _downscaleVolumeRendering.currentDownscaleFactor; + const float cdf = _downscaleVolumeRendering.currentDownscaleFactor; // Downscale Volume Rendering glBindTexture(GL_TEXTURE_2D, _downscaleVolumeRendering.colorTexture); @@ -853,8 +853,8 @@ void FramebufferRenderer::updateResolution() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - float volumeBorderColor[] = { 0.f, 0.f, 0.f, 1.f }; - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, volumeBorderColor); + constexpr std::array VolumeBorderColor = { 0.f, 0.f, 0.f, 1.f }; + glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, VolumeBorderColor.data()); if (glbinding::Binding::ObjectLabel.isResolved()) { glObjectLabel( GL_TEXTURE, @@ -970,7 +970,7 @@ void FramebufferRenderer::updateRaycastData() { try { _exitPrograms[raycaster] = ghoul::opengl::ProgramObject::Build( - "Volume " + std::to_string(data.id) + " exit", + std::format("Volume {} exit", data.id), absPath(vsPath), absPath(ExitFragmentShaderPath), dict @@ -983,7 +983,7 @@ void FramebufferRenderer::updateRaycastData() { ghoul::Dictionary outsideDict = dict; outsideDict.setValue("getEntryPath", std::string(GetEntryOutsidePath)); _raycastPrograms[raycaster] = ghoul::opengl::ProgramObject::Build( - "Volume " + std::to_string(data.id) + " raycast", + std::format("Volume {} raycast", data.id), absPath(vsPath), absPath(RaycastFragmentShaderPath), outsideDict @@ -996,7 +996,7 @@ void FramebufferRenderer::updateRaycastData() { ghoul::Dictionary insideDict = dict; insideDict.setValue("getEntryPath", std::string(GetEntryInsidePath)); _insideRaycastPrograms[raycaster] = ghoul::opengl::ProgramObject::Build( - "Volume " + std::to_string(data.id) + " inside raycast", + std::format("Volume {} inside raycast", data.id), absPath("${SHADERS}/framebuffer/resolveframebuffer.vert"), absPath(RaycastFragmentShaderPath), insideDict @@ -1019,14 +1019,14 @@ void FramebufferRenderer::updateDeferredcastData() { for (Deferredcaster* caster : deferredcasters) { DeferredcastData data = { .id = nextId++, .namespaceName = "HELPER" }; - std::filesystem::path vsPath = caster->deferredcastVSPath(); - std::filesystem::path fsPath = caster->deferredcastFSPath(); + const std::filesystem::path vsPath = caster->deferredcastVSPath(); + const std::filesystem::path fsPath = caster->deferredcastFSPath(); ghoul::Dictionary dict; dict.setValue("rendererData", _rendererData); //dict.setValue("fragmentPath", fsPath); dict.setValue("id", data.id); - std::filesystem::path helperPath = caster->helperPath(); + const std::filesystem::path helperPath = caster->helperPath(); ghoul::Dictionary helpersDict; if (!helperPath.empty()) { helpersDict.setValue("0", helperPath.string()); @@ -1037,7 +1037,7 @@ void FramebufferRenderer::updateDeferredcastData() { try { _deferredcastPrograms[caster] = ghoul::opengl::ProgramObject::Build( - "Deferred " + std::to_string(data.id) + " raycast", + std::format("Deferred {} raycast", data.id), vsPath, fsPath, dict @@ -1045,7 +1045,7 @@ void FramebufferRenderer::updateDeferredcastData() { caster->initializeCachedVariables(*_deferredcastPrograms[caster]); } - catch (ghoul::RuntimeError& e) { + catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } } @@ -1090,10 +1090,10 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_defaultFBO); global::renderEngine->openglStateCache().setDefaultFramebuffer(_defaultFBO); - GLint vp[4] = { 0 }; - glGetIntegerv(GL_VIEWPORT, vp); - global::renderEngine->openglStateCache().setViewportState(vp); - glm::ivec4 viewport = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); + std::array vp = {}; + glGetIntegerv(GL_VIEWPORT, vp.data()); + global::renderEngine->openglStateCache().setViewportState(vp.data()); + const glm::ivec4 viewport = glm::ivec4(vp[0], vp[1], vp[2], vp[3]); // Reset Render Pipeline State global::renderEngine->openglStateCache().resetCachedStates(); @@ -1110,36 +1110,35 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac TracyGpuZone("Deferred G-Buffer"); glBindFramebuffer(GL_FRAMEBUFFER, _gBuffers.framebuffer); - glDrawBuffers(3, ColorAttachmentArray); + glDrawBuffers(3, ColorAttachmentArray.data()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearBufferfv(GL_COLOR, 1, glm::value_ptr(PosBufferClearVal)); } - Time time = global::timeManager->time(); RenderData data = { .camera = *camera, - .time = std::move(time), + .time = global::timeManager->time(), .renderBinMask = 0 }; RendererTasks tasks; { TracyGpuZone("Background") - ghoul::GLDebugGroup group("Background"); + const ghoul::GLDebugGroup group("Background"); data.renderBinMask = static_cast(Renderable::RenderBin::Background); scene->render(data, tasks); } { TracyGpuZone("Opaque") - ghoul::GLDebugGroup group("Opaque"); + const ghoul::GLDebugGroup group("Opaque"); data.renderBinMask = static_cast(Renderable::RenderBin::Opaque); scene->render(data, tasks); } { TracyGpuZone("PreDeferredTransparent") - ghoul::GLDebugGroup group("PreDeferredTransparent"); + const ghoul::GLDebugGroup group("PreDeferredTransparent"); data.renderBinMask = static_cast( Renderable::RenderBin::PreDeferredTransparent ); @@ -1149,13 +1148,13 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac // Run Volume Tasks { TracyGpuZone("Raycaster Tasks") - ghoul::GLDebugGroup group("Raycaster Tasks"); + const ghoul::GLDebugGroup group("Raycaster Tasks"); performRaycasterTasks(tasks.raycasterTasks, viewport); } if (!tasks.deferredcasterTasks.empty()) { TracyGpuZone("Deferred Caster Tasks") - ghoul::GLDebugGroup group("Deferred Caster Tasks"); + const ghoul::GLDebugGroup group("Deferred Caster Tasks"); // We use ping pong rendering in order to be able to render multiple deferred // tasks at same time (e.g. more than 1 ATM being seen at once) to the same final @@ -1171,14 +1170,14 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac { TracyGpuZone("Overlay") - ghoul::GLDebugGroup group("Overlay"); + const ghoul::GLDebugGroup group("Overlay"); data.renderBinMask = static_cast(Renderable::RenderBin::Overlay); scene->render(data, tasks); } { TracyGpuZone("PostDeferredTransparent") - ghoul::GLDebugGroup group("PostDeferredTransparent"); + const ghoul::GLDebugGroup group("PostDeferredTransparent"); data.renderBinMask = static_cast( Renderable::RenderBin::PostDeferredTransparent ); @@ -1187,7 +1186,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac { TracyGpuZone("Sticker") - ghoul::GLDebugGroup group("Sticker"); + const ghoul::GLDebugGroup group("Sticker"); data.renderBinMask = static_cast( Renderable::RenderBin::Sticker ); @@ -1201,7 +1200,7 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac if (_enableFXAA) { glBindFramebuffer(GL_FRAMEBUFFER, _fxaaBuffers.fxaaFramebuffer); - glDrawBuffers(1, ColorAttachmentArray); + glDrawBuffers(1, ColorAttachmentArray.data()); glDisable(GL_BLEND); } @@ -1214,14 +1213,14 @@ void FramebufferRenderer::render(Scene* scene, Camera* camera, float blackoutFac { // Apply the selected TMO on the results and resolve the result to the default FBO TracyGpuZone("Apply TMO"); - ghoul::GLDebugGroup group("Apply TMO"); + const ghoul::GLDebugGroup group("Apply TMO"); applyTMO(blackoutFactor, viewport); } if (_enableFXAA) { TracyGpuZone("Apply FXAA") - ghoul::GLDebugGroup group("Apply FXAA"); + const ghoul::GLDebugGroup group("Apply FXAA"); glBindFramebuffer(GL_FRAMEBUFFER, _defaultFBO); applyFXAA(viewport); } @@ -1251,13 +1250,13 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector if (raycaster->downscaleRender() < 1.f) { glBindFramebuffer(GL_FRAMEBUFFER, _downscaleVolumeRendering.framebuffer); const float s = raycaster->downscaleRender(); - GLint newVP[4] = { + const std::array newVP = { static_cast(viewport[0] * s), static_cast(viewport[1] * s), static_cast(viewport[2] * s), static_cast(viewport[3] * s) }; - global::renderEngine->openglStateCache().setViewportState(newVP); + global::renderEngine->openglStateCache().setViewportState(newVP.data()); if (_downscaleVolumeRendering.currentDownscaleFactor != s) { _downscaleVolumeRendering.currentDownscaleFactor = s; @@ -1270,7 +1269,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector } glm::vec3 cameraPosition = glm::vec3(0.f); - bool isCameraInside = raycaster->isCameraInside( + const bool isCameraInside = raycaster->isCameraInside( raycasterTask.renderData, cameraPosition ); @@ -1320,7 +1319,7 @@ void FramebufferRenderer::performRaycasterTasks(const std::vector raycastProgram->setUniform("mainDepthTexture", mainDepthTextureUnit); if (raycaster->downscaleRender() < 1.f) { - float scaleDown = raycaster->downscaleRender(); + const float scaleDown = raycaster->downscaleRender(); raycastProgram->setUniform( "windowSize", glm::vec2(_resolution.x * scaleDown, _resolution.y * scaleDown) @@ -1379,7 +1378,7 @@ void FramebufferRenderer::performDeferredTasks( if (deferredcastProgram) { _pingPongIndex = _pingPongIndex == 0 ? 1 : 0; - int fromIndex = _pingPongIndex == 0 ? 1 : 0; + const int fromIndex = _pingPongIndex == 0 ? 1 : 0; glDrawBuffers(1, &ColorAttachmentArray[_pingPongIndex]); glDisablei(GL_BLEND, 0); glDisablei(GL_BLEND, 1); @@ -1462,34 +1461,29 @@ void FramebufferRenderer::setResolution(glm::ivec2 res) { } void FramebufferRenderer::setDisableHDR(bool disable) { - _disableHDR = std::move(disable); + _disableHDR = disable; } void FramebufferRenderer::setHDRExposure(float hdrExposure) { ghoul_assert(hdrExposure > 0.f, "HDR exposure must be greater than zero"); - _hdrExposure = std::move(hdrExposure); + _hdrExposure = hdrExposure; updateRendererData(); } void FramebufferRenderer::setGamma(float gamma) { ghoul_assert(gamma > 0.f, "Gamma value must be greater than zero"); - _gamma = std::move(gamma); + _gamma = gamma; } -void FramebufferRenderer::setHue(float hue) { - _hue = std::move(hue); -} - -void FramebufferRenderer::setValue(float value) { - _value = std::move(value); -} - -void FramebufferRenderer::setSaturation(float sat) { - _saturation = std::move(sat); +void FramebufferRenderer::setHueValueSaturation(float hue, float value, float saturation) +{ + _hue = hue; + _value = value; + _saturation = saturation; } void FramebufferRenderer::enableFXAA(bool enable) { - _enableFXAA = std::move(enable); + _enableFXAA = enable; } void FramebufferRenderer::updateRendererData() { diff --git a/src/rendering/helper.cpp b/src/rendering/helper.cpp index 3409c9ffb2..817fab517f 100644 --- a/src/rendering/helper.cpp +++ b/src/rendering/helper.cpp @@ -221,11 +221,11 @@ void initialize() { glBindBuffer(GL_ARRAY_BUFFER, vertexObjects.square.vbo); struct VertexXYUVRGBA { - GLfloat xy[2]; - GLfloat uv[2]; - GLfloat rgba[4]; + std::array xy; + std::array uv; + std::array rgba; }; - VertexXYUVRGBA data[] = { + constexpr std::array Vtx = { // X Y U V R G B A -1.f, -1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f, 1.f, @@ -235,16 +235,28 @@ void initialize() { 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, -1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 1.f }; - glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(VertexXYUVRGBA), data, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(VertexXYUVRGBA), Vtx.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA), nullptr); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA), - reinterpret_cast(offsetof(VertexXYUVRGBA, uv))); + glVertexAttribPointer( + 1, + 2, + GL_FLOAT, + GL_FALSE, + sizeof(VertexXYUVRGBA), + reinterpret_cast(offsetof(VertexXYUVRGBA, uv)) + ); glEnableVertexAttribArray(2); - glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(VertexXYUVRGBA), - reinterpret_cast(offsetof(VertexXYUVRGBA, rgba))); + glVertexAttribPointer( + 2, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(VertexXYUVRGBA), + reinterpret_cast(offsetof(VertexXYUVRGBA, rgba)) + ); glBindVertexArray(0); @@ -502,7 +514,7 @@ std::vector convert(std::vector v) { } Vertex computeCircleVertex(int i, int nSegments, float radius, - glm::vec4 color = glm::vec4(1.f)) + const glm::vec4& color = glm::vec4(1.f)) { const float fsegments = static_cast(nSegments); @@ -520,11 +532,11 @@ Vertex computeCircleVertex(int i, int nSegments, float radius, return { x, y, z, u, v, color.r, color.g, color.b, color.a }; } -std::vector createRing(int nSegments, float radius, glm::vec4 colors) { +std::vector createRing(int nSegments, float radius, const glm::vec4& colors) { const int nVertices = nSegments + 1; std::vector vertices(nVertices); - for (int i = 0; i <= nSegments; ++i) { + for (int i = 0; i <= nSegments; i++) { vertices[i] = computeCircleVertex(i, nSegments, radius, colors); } return vertices; @@ -534,15 +546,15 @@ std::vector createRingXYZ(int nSegments, float radius) { const int nVertices = nSegments + 1; std::vector vertices(nVertices); - for (int i = 0; i <= nSegments; ++i) { - Vertex fullVertex = computeCircleVertex(i, nSegments, radius); + for (int i = 0; i <= nSegments; i++) { + const Vertex fullVertex = computeCircleVertex(i, nSegments, radius); vertices[i] = { fullVertex.xyz[0], fullVertex.xyz[1], fullVertex.xyz[2] }; } return vertices; } VertexIndexListCombo createSphere(int nSegments, glm::vec3 radii, - glm::vec4 colors) + const glm::vec4& colors) { std::vector vertices; vertices.reserve(nSegments * nSegments); @@ -558,9 +570,10 @@ VertexIndexListCombo createSphere(int nSegments, glm::vec3 radii, // 0 -> 2*PI const float phi = fj * glm::pi() * 2.f / nSegments; - const float x = radii[0] * sin(theta) * cos(phi); - const float y = radii[1] * sin(theta) * sin(phi); - const float z = radii[2] * cos(theta); // Z points towards pole (theta = 0) + const float x = radii[0] * std::sin(theta) * std::cos(phi); + const float y = radii[1] * std::sin(theta) * std::sin(phi); + // Z points towards pole (theta = 0) + const float z = radii[2] * std::cos(theta); Vertex v; v.xyz[0] = x; @@ -640,7 +653,7 @@ VertexIndexListCombo createConicalCylinder(unsigned int nSegmen ); } else { - glm::vec3 p = glm::closestPointOnLine( + const glm::vec3 p = glm::closestPointOnLine( glm::vec3(0.f), glm::vec3(vBot.xyz[0], vBot.xyz[1], vBot.xyz[2]), glm::vec3(vTop.xyz[0], vTop.xyz[1], vTop.xyz[2]) @@ -693,12 +706,15 @@ VertexIndexListCombo createConicalCylinder(unsigned int nSegmen return static_cast(1 + ringIndex * (nSegments + 1) + i); }; - GLushort botCenterIndex = 0; - GLushort topCenterIndex = static_cast(vertices.size()) - 1; + const GLushort botCenterIndex = 0; + const GLushort topCenterIndex = static_cast(vertices.size()) - 1; - for (unsigned int i = 0; i < nSegments; ++i) { - bool isLast = (i == nSegments - 1); - GLushort v0, v1, v2, v3; + for (unsigned int i = 0; i < nSegments; i++) { + const bool isLast = (i == nSegments - 1); + GLushort v0 = 0; + GLushort v1 = 0; + GLushort v2 = 0; + GLushort v3 = 0; // Bottom triangle v0 = ringVerticeIndex(0, i); diff --git a/src/rendering/labelscomponent.cpp b/src/rendering/labelscomponent.cpp index 8e6fe2b92c..4d5e47643f 100644 --- a/src/rendering/labelscomponent.cpp +++ b/src/rendering/labelscomponent.cpp @@ -258,7 +258,7 @@ void LabelsComponent::initialize() { } void LabelsComponent::loadLabels() { - LINFO(fmt::format("Loading label file {}", _labelFile)); + LINFO(std::format("Loading label file '{}'", _labelFile)); if (_createdFromDataset) { // The labelset should already have been loaded @@ -289,9 +289,10 @@ void LabelsComponent::render(const RenderData& data, if (!_enabled) { return; } - float scale = static_cast(toMeter(_unit)); + const float scale = static_cast(toMeter(_unit)); - int renderOption = _faceCamera ? RenderOptionFaceCamera : RenderOptionPositionNormal; + const int renderOption = + _faceCamera ? RenderOptionFaceCamera : RenderOptionPositionNormal; ghoul::fontrendering::FontRenderer::ProjectedLabelsInformation labelInfo; labelInfo.orthoRight = orthoRight; @@ -306,7 +307,7 @@ void LabelsComponent::render(const RenderData& data, labelInfo.enableDepth = true; labelInfo.enableFalseDepth = false; - glm::vec4 textColor = glm::vec4(glm::vec3(_color), opacity() * fadeInVariable); + const glm::vec4 textColor = glm::vec4(glm::vec3(_color), opacity() * fadeInVariable); for (const dataloader::Labelset::Entry& e : _labelset.entries) { if (!e.isEnabled) { @@ -314,9 +315,10 @@ void LabelsComponent::render(const RenderData& data, } // Transform and scale the labels - glm::vec3 transformedPos(_transformationMatrix * glm::dvec4(e.position, 1.0)); - glm::vec3 scaledPos(transformedPos); - scaledPos *= scale; + const glm::vec3 transformedPos = glm::vec3( + _transformationMatrix * glm::dvec4(e.position, 1.0) + ); + const glm::vec3 scaledPos = glm::vec3(transformedPos * scale); ghoul::fontrendering::FontRenderer::defaultProjectionRenderer().render( *_font, diff --git a/src/rendering/loadingscreen.cpp b/src/rendering/loadingscreen.cpp index 739e106e92..7a23ccd012 100644 --- a/src/rendering/loadingscreen.cpp +++ b/src/rendering/loadingscreen.cpp @@ -84,15 +84,11 @@ namespace { rhsLl -= glm::vec2(ItemStandoffDistance / 2.f); rhsUr += glm::vec2(ItemStandoffDistance / 2.f); - return !( - lhsUr.x < rhsLl.x || - lhsLl.x > rhsUr.x || - lhsUr.y < rhsLl.y || - lhsLl.y > rhsUr.y - ); + return lhsUr.x >= rhsLl.x && lhsLl.x <= rhsUr.x && + lhsUr.y >= rhsLl.y && lhsLl.y <= rhsUr.y; } - glm::vec2 ndcToScreen(glm::vec2 ndc, glm::ivec2 res) { + glm::vec2 ndcToScreen(glm::vec2 ndc, const glm::ivec2& res) { ndc.x = (ndc.x + 1.f) / 2.f * res.x; ndc.y = (ndc.y + 1.f) / 2.f * res.y; return ndc; @@ -230,7 +226,7 @@ void LoadingScreen::exec(AssetManager& manager, Scene& scene) { LoadingScreen::ItemStatus::Started, progressInfo ); - ++it; + it++; } else if ((*it)->isRejected()) { updateItem( @@ -239,7 +235,7 @@ void LoadingScreen::exec(AssetManager& manager, Scene& scene) { LoadingScreen::ItemStatus::Failed, LoadingScreen::ProgressInfo() ); - ++it; + it++; } else { LoadingScreen::ProgressInfo progressInfo; @@ -261,7 +257,7 @@ void LoadingScreen::exec(AssetManager& manager, Scene& scene) { return; } - bool finishedLoading = std::all_of( + const bool finishedLoading = std::all_of( allAssets.begin(), allAssets.end(), [](const Asset* asset) { return asset->isInitialized() || asset->isFailed(); } @@ -298,9 +294,9 @@ void LoadingScreen::render() { const glm::ivec2 res = glm::vec2(global::windowDelegate->firstWindowResolution()) * dpiScaling; - float screenAspectRatio = static_cast(res.x) / static_cast(res.y); + const float screenAspectRatio = static_cast(res.x) / static_cast(res.y); - float textureAspectRatio = static_cast(_logoTexture->dimensions().x) / + const float textureAspectRatio = static_cast(_logoTexture->dimensions().x) / static_cast(_logoTexture->dimensions().y); ghoul::fontrendering::FontRenderer::defaultRenderer().setFramebufferSize(res); @@ -359,7 +355,7 @@ void LoadingScreen::render() { glm::vec2 messageLl = glm::vec2(0.f); glm::vec2 messageUr = glm::vec2(0.f); if (_showMessage) { - std::lock_guard guard(_messageMutex); + const std::lock_guard guard(_messageMutex); const glm::vec2 bboxMessage = _messageFont->boundingBox(_message); @@ -373,8 +369,8 @@ void LoadingScreen::render() { renderer.render(*_messageFont, messageLl, _message); } - glm::vec2 logLl = glm::vec2(0.f, 0.f); - glm::vec2 logUr = glm::vec2(res.x, res.y * (LogBackgroundPosition + 0.015)); + const glm::vec2 logLl = glm::vec2(0.f, 0.f); + const glm::vec2 logUr = glm::vec2(res.x, res.y * (LogBackgroundPosition + 0.015)); // Font rendering enables depth testing so we disable again to render the log box glDisable(GL_DEPTH_TEST); @@ -389,9 +385,9 @@ void LoadingScreen::render() { } if (_showNodeNames) { - std::lock_guard guard(_itemsMutex); + const std::lock_guard guard(_itemsMutex); - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + const auto now = std::chrono::system_clock::now(); const glm::vec2 logoLl = glm::vec2(LogoCenter.x - size.x, LogoCenter.y - size.y); const glm::vec2 logoUr = glm::vec2(LogoCenter.x + size.x, LogoCenter.y + size.y); @@ -407,7 +403,7 @@ void LoadingScreen::render() { glm::vec2 ll = glm::vec2(0.f); glm::vec2 ur = glm::vec2(0.f); int i = 0; - for (; i < MaxNumberLocationSamples; ++i) { + for (; i < MaxNumberLocationSamples; i++) { std::uniform_int_distribution distX( 15, static_cast(res.x - b.x - 15) @@ -512,7 +508,7 @@ void LoadingScreen::render() { int p = static_cast(std::round(info.progress * 100)); if (isTotalSizeKnown) { if (info.totalSize < 1024 * 1024) { // 1MB - text = fmt::format( + text = std::format( "{} ({}%)\n{}/{} {}", text, p, info.currentSize, info.totalSize, "bytes" ); @@ -521,7 +517,7 @@ void LoadingScreen::render() { float curr = info.currentSize / (1024.f * 1024.f); float total = info.totalSize / (1024.f * 1024.f); - text = fmt::format( + text = std::format( "{} ({}%)\n{:.3f}/{:.3f} {}", text, p, curr, total, "MB" ); @@ -530,11 +526,11 @@ void LoadingScreen::render() { else { // We don't know the total size but we have started downloading data if (info.currentSize < 1024 * 1024) { - text = fmt::format("{}\n{} {}", text, info.currentSize, "bytes"); + text = std::format("{}\n{} {}", text, info.currentSize, "bytes"); } else { float curr = info.currentSize / (1024.f * 1024.f); - text = fmt::format("{}\n{:.3f} {}", text, curr, "MB"); + text = std::format("{}\n{:.3f} {}", text, curr, "MB"); } } } @@ -585,7 +581,7 @@ void LoadingScreen::renderLogMessages() const { const std::vector& entries = _log->entries(); size_t nRows = 0; - size_t j = std::min(MaxNumberMessages, entries.size()); + const size_t j = std::min(MaxNumberMessages, entries.size()); for (size_t i = 1; i <= j; i++) { ZoneScopedN("Entry"); @@ -630,13 +626,13 @@ void LoadingScreen::renderLogMessages() const { // Render # of warnings and error messages std::map numberOfErrorsPerLevel; - for (auto& entry : _log->entries()) { + for (const auto& entry : _log->entries()) { numberOfErrorsPerLevel[entry.level]++; } size_t row = 0; for (auto& [level, amount] : numberOfErrorsPerLevel) { - const std::string text = fmt::format("{}: {}", ghoul::to_string(level), amount); - glm::vec2 bbox = _logFont->boundingBox(text); + const std::string text = std::format("{}: {}", ghoul::to_string(level), amount); + const glm::vec2 bbox = _logFont->boundingBox(text); renderer.render( *_logFont, glm::vec2( @@ -651,7 +647,7 @@ void LoadingScreen::renderLogMessages() const { } void LoadingScreen::postMessage(std::string message) { - std::lock_guard guard(_messageMutex); + const std::lock_guard guard(_messageMutex); _message = std::move(message); } @@ -688,7 +684,7 @@ void LoadingScreen::updateItem(const std::string& itemIdentifier, // also would create any of the text information return; } - std::lock_guard guard(_itemsMutex); + const std::lock_guard guard(_itemsMutex); auto it = std::find_if( _items.begin(), diff --git a/src/rendering/luaconsole.cpp b/src/rendering/luaconsole.cpp index cb7e8624e2..fd1ea36d20 100644 --- a/src/rendering/luaconsole.cpp +++ b/src/rendering/luaconsole.cpp @@ -56,8 +56,8 @@ namespace { constexpr uint64_t CurrentVersion = 0xFEEE'FEEE'0000'0001; constexpr std::string_view FontName = "Console"; - constexpr float EntryFontSize = 14.0f; - constexpr float HistoryFontSize = 11.0f; + constexpr float EntryFontSize = 14.f; + constexpr float HistoryFontSize = 11.f; // Additional space between the entry text and the history (in pixels) constexpr float SeparatorSpace = 30.f; @@ -183,8 +183,6 @@ LuaConsole::LuaConsole() addProperty(_historyTextColor); } -LuaConsole::~LuaConsole() {} - void LuaConsole::initialize() { ZoneScoped; @@ -197,26 +195,26 @@ void LuaConsole::initialize() { if (file.good()) { // Read the number of commands from the history - uint64_t version; + uint64_t version = 0; file.read(reinterpret_cast(&version), sizeof(uint64_t)); if (version != CurrentVersion) { LWARNINGC( "LuaConsole", - fmt::format("Outdated console history version: {}", version) + std::format("Outdated console history version: {}", version) ); } else { - int64_t nCommands; + int64_t nCommands = 0; file.read(reinterpret_cast(&nCommands), sizeof(int64_t)); - for (int64_t i = 0; i < nCommands; ++i) { - int64_t length; + for (int64_t i = 0; i < nCommands; i++) { + int64_t length = 0; file.read(reinterpret_cast(&length), sizeof(int64_t)); std::vector tmp(length); file.read(tmp.data(), length); - _commandsHistory.emplace_back(std::string(tmp.begin(), tmp.end())); + _commandsHistory.emplace_back(tmp.begin(), tmp.end()); } } } @@ -244,7 +242,7 @@ void LuaConsole::initialize() { "luaConsole", "statusChanged", [this]() { - ParallelConnection::Status status = global::parallelPeer->status(); + const ParallelConnection::Status status = global::parallelPeer->status(); parallelConnectionChanged(status); } ); @@ -451,7 +449,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio } if (key == Key::Enter || key == Key::KeypadEnter) { - std::string cmd = _commands.at(_activeCommand); + const std::string cmd = _commands.at(_activeCommand); if (!cmd.empty()) { global::scriptEngine->queueScript( cmd, @@ -489,7 +487,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio std::vector allCommands = global::scriptEngine->allLuaFunctions(); std::sort(allCommands.begin(), allCommands.end()); - std::string currentCommand = _commands.at(_activeCommand); + const std::string currentCommand = _commands.at(_activeCommand); // Check if it is the first time the tab has been pressed. If so, we need to // store the already entered command so that we can later start the search @@ -500,7 +498,7 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio _autoCompleteInfo.hasInitialValue = true; } - for (int i = 0; i < static_cast(allCommands.size()); ++i) { + for (int i = 0; i < static_cast(allCommands.size()); i++) { const std::string& command = allCommands[i]; // Check if the command has enough length (we don't want crashes here) @@ -510,10 +508,11 @@ bool LuaConsole::keyboardCallback(Key key, KeyModifier modifier, KeyAction actio const size_t fullLength = _autoCompleteInfo.initialValue.length(); const bool correctLength = command.length() >= fullLength; - std::string commandLowerCase = ghoul::toLowerCase(command); + const std::string commandLowerCase = ghoul::toLowerCase(command); - std::string initialValueLowerCase = - ghoul::toLowerCase(_autoCompleteInfo.initialValue); + const std::string initialValueLowerCase = ghoul::toLowerCase( + _autoCompleteInfo.initialValue + ); const bool correctCommand = commandLowerCase.substr(0, fullLength) == initialValueLowerCase; @@ -661,7 +660,7 @@ void LuaConsole::render() { using namespace ghoul::fontrendering; - ghoul::GLDebugGroup group("LuaConsole"); + const ghoul::GLDebugGroup group("LuaConsole"); // Don't render the console if it's collapsed. if (_currentHeight < 1.f) { @@ -831,7 +830,7 @@ void LuaConsole::render() { else if (_shouldSendToRemote) { const glm::vec4 Red(1.f, 0.f, 0.f, 1.f); - ParallelConnection::Status status = global::parallelPeer->status(); + const ParallelConnection::Status status = global::parallelPeer->status(); const int nClients = status != ParallelConnection::Status::Disconnected ? global::parallelPeer->nConnections() - 1 : @@ -863,9 +862,9 @@ void LuaConsole::setCommandInputButton(Key key) { _commandInputButton = key; } -void LuaConsole::addToCommand(std::string c) { +void LuaConsole::addToCommand(const std::string& c) { const size_t length = c.length(); - _commands.at(_activeCommand).insert(_inputPosition, std::move(c)); + _commands.at(_activeCommand).insert(_inputPosition, c); _inputPosition += length; } diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index d40ffeb414..732adc40e8 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -116,7 +116,7 @@ documentation::Documentation Renderable::Documentation() { } ghoul::mm_unique_ptr Renderable::createFromDictionary( - ghoul::Dictionary dictionary) + const ghoul::Dictionary& dictionary) { if (!dictionary.hasKey(KeyType)) { throw ghoul::RuntimeError("Tried to create Renderable but no 'Type' was found"); @@ -125,7 +125,7 @@ ghoul::mm_unique_ptr Renderable::createFromDictionary( // This should be done in the constructor instead with noexhaustive documentation::testSpecificationAndThrow(Documentation(), dictionary, "Renderable"); - std::string renderableType = dictionary.value(KeyType); + const std::string renderableType = dictionary.value(KeyType); ghoul::TemplateFactory* factory = FactoryManager::ref().factory(); ghoul_assert(factory, "Renderable factory did not exist"); @@ -142,7 +142,6 @@ ghoul::mm_unique_ptr Renderable::createFromDictionary( Renderable::Renderable(const ghoul::Dictionary& dictionary, RenderableSettings settings) : properties::PropertyOwner({ "Renderable" }) - , Fadeable() , _enabled(EnabledInfo, true) , _renderableType(RenderableTypeInfo, "Renderable") , _dimInAtmosphere(DimInAtmosphereInfo, false) @@ -340,29 +339,29 @@ bool Renderable::hasOverrideRenderBin() const noexcept { glm::dmat4 Renderable::calcModelTransform(const RenderData& data, const AlternativeTransform& altTransform) const { - glm::dvec3 translation = + const glm::dvec3 translation = altTransform.translation.value_or(data.modelTransform.translation); - glm::dmat3 rotation = altTransform.rotation.value_or(data.modelTransform.rotation); - glm::dvec3 scale = altTransform.scale.value_or(data.modelTransform.scale); + const glm::dmat3 rot = altTransform.rotation.value_or(data.modelTransform.rotation); + const glm::dvec3 scale = altTransform.scale.value_or(data.modelTransform.scale); return glm::translate(glm::dmat4(1.0), translation) * - glm::dmat4(rotation) * + glm::dmat4(rot) * glm::scale(glm::dmat4(1.0), scale); } glm::dmat4 Renderable::calcModelViewTransform(const RenderData& data, - std::optional modelTransform) const + const std::optional& modelTransform) const { - glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data)); + const glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data)); return data.camera.combinedViewMatrix() * modelMatrix; } glm::dmat4 Renderable::calcModelViewProjectionTransform(const RenderData& data, - std::optional modelTransform) const + const std::optional& modelTransform) const { - glm::dmat4 modelMatrix = modelTransform.value_or(calcModelTransform(data)); - glm::dmat4 viewMatrix = data.camera.combinedViewMatrix(); - glm::dmat4 projectionMatrix = data.camera.projectionMatrix(); + const glm::dmat4& modelMatrix = modelTransform.value_or(calcModelTransform(data)); + const glm::dmat4 viewMatrix = data.camera.combinedViewMatrix(); + const glm::dmat4 projectionMatrix = data.camera.projectionMatrix(); return glm::dmat4(projectionMatrix * viewMatrix * modelMatrix); } @@ -370,9 +369,9 @@ std::tuple Renderable::calcAllTransforms( const RenderData& data, const AlternativeTransform& altModelTransform) const { - glm::dmat4 modelTransform = calcModelTransform(data, altModelTransform); - glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform); - glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform( + const glm::dmat4 modelTransform = calcModelTransform(data, altModelTransform); + const glm::dmat4 modelViewTransform = calcModelViewTransform(data, modelTransform); + const glm::dmat4 modelViewProjectionTransform = calcModelViewProjectionTransform( data, modelTransform ); diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 644292f962..4f21e42357 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -1,4 +1,3 @@ - /***************************************************************************************** * * * OpenSpace * @@ -331,7 +330,7 @@ RenderEngine::RenderEngine() , _hdrExposure(HDRExposureInfo, 3.7f, 0.01f, 10.f) , _gamma(GammaInfo, 0.95f, 0.01f, 5.f) , _hue(HueInfo, 0.f, 0.f, 360.f) - , _saturation(SaturationInfo, 1.f, 0.0f, 2.f) + , _saturation(SaturationInfo, 1.f, 0.f, 2.f) , _value(ValueInfo, 1.f, 0.f, 2.f) , _framerateLimit(FramerateLimitInfo, 0, 0, 500) , _horizFieldOfView(HorizFieldOfViewInfo, 80.f, 1.f, 179.f) @@ -376,13 +375,16 @@ RenderEngine::RenderEngine() _gamma.onChange([this]() { _renderer.setGamma(_gamma); }); addProperty(_gamma); - _hue.onChange([this]() { _renderer.setHue(_hue / 360.f); }); + auto setHueValueSaturation = [this]() { + _renderer.setHueValueSaturation(_hue / 360.f, _value, _saturation); + }; + _hue.onChange(setHueValueSaturation); addProperty(_hue); - _saturation.onChange([this]() { _renderer.setSaturation(_saturation); }); + _saturation.onChange(setHueValueSaturation); addProperty(_saturation); - _value.onChange([this]() { _renderer.setValue(_value); }); + _value.onChange(setHueValueSaturation); addProperty(_value); addProperty(_globalBlackOutFactor); @@ -405,13 +407,13 @@ RenderEngine::RenderEngine() // Going from 'false' -> 'true' // We might need to create the folder first - std::time_t now = std::time(nullptr); + const std::time_t now = std::time(nullptr); std::tm* nowTime = std::localtime(&now); - char date[128]; - strftime(date, sizeof(date), "%Y-%m-%d-%H-%M", nowTime); + std::array date; + strftime(date.data(), sizeof(date), "%Y-%m-%d-%H-%M", nowTime); - std::filesystem::path newFolder = absPath( - "${STARTUP_SCREENSHOT}/" + std::string(date) + const std::filesystem::path newFolder = absPath( + "${STARTUP_SCREENSHOT}/" + std::string(date.data()) ); FileSys.registerPathToken( @@ -429,7 +431,7 @@ RenderEngine::RenderEngine() ghoul::filesystem::FileSystem::Override::Yes ); } - global::windowDelegate->setScreenshotFolder(absPath("${SCREENSHOTS}").string()); + global::windowDelegate->setScreenshotFolder(absPath("${SCREENSHOTS}")); }); addProperty(_screenshotUseDate); @@ -448,10 +450,10 @@ RenderEngine::RenderEngine() addProperty(_masterRotation); addProperty(_disableMasterRendering); - _enabledFontColor.setViewOption(openspace::properties::Property::ViewOptions::Color); + _enabledFontColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_enabledFontColor); - _disabledFontColor.setViewOption(openspace::properties::Property::ViewOptions::Color); + _disabledFontColor.setViewOption(properties::Property::ViewOptions::Color); addProperty(_disabledFontColor); } @@ -492,13 +494,13 @@ void RenderEngine::initialize() { if (global::versionChecker->hasLatestVersionInfo()) { VersionChecker::SemanticVersion latest = global::versionChecker->latestVersion(); - VersionChecker::SemanticVersion current{ + const VersionChecker::SemanticVersion current { OPENSPACE_VERSION_MAJOR, OPENSPACE_VERSION_MINOR, OPENSPACE_VERSION_PATCH }; if (current < latest) { - _versionString += fmt::format( + _versionString += std::format( " [Available: {}.{}.{}]", latest.major, latest.minor, latest.patch ); } @@ -523,7 +525,7 @@ void RenderEngine::initializeGL() { // initialized window _horizFieldOfView = static_cast(global::windowDelegate->getHorizFieldOfView()); - Configuration::FontSizes fontSize = global::configuration->fontSize; + const Configuration::FontSizes fontSize = global::configuration->fontSize; { ZoneScopedN("Fonts"); TracyGpuZone("Fonts"); @@ -599,7 +601,7 @@ void RenderEngine::updateRenderer() { using FR = ghoul::fontrendering::FontRenderer; FR::defaultRenderer().setFramebufferSize(fontResolution()); FR::defaultProjectionRenderer().setFramebufferSize(renderingResolution()); - //Override the aspect ratio property value to match that of resized window + // Override the aspect ratio property value to match that of resized window _horizFieldOfView = static_cast(global::windowDelegate->getHorizFieldOfView()); } @@ -630,21 +632,21 @@ glm::ivec2 RenderEngine::fontResolution() const { } glm::mat4 RenderEngine::globalRotation() const { - glm::vec3 rot = _globalRotation; + const glm::vec3 rot = _globalRotation; - glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); - glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); - glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); + const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); + const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); + const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); return glm::mat4_cast(glm::normalize(pitch * yaw * roll)); } glm::mat4 RenderEngine::screenSpaceRotation() const { - glm::vec3 rot = _screenSpaceRotation; + const glm::vec3 rot = _screenSpaceRotation; - glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); - glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); - glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); + const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); + const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); + const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); return glm::mat4_cast(glm::normalize(pitch * yaw * roll)); } @@ -653,11 +655,11 @@ glm::mat4 RenderEngine::nodeRotation() const { if (!global::windowDelegate->isMaster()) { return glm::mat4(1.f); } - glm::vec3 rot = _masterRotation; + const glm::vec3 rot = _masterRotation; - glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); - glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); - glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); + const glm::quat pitch = glm::angleAxis(rot.x, glm::vec3(1.f, 0.f, 0.f)); + const glm::quat yaw = glm::angleAxis(rot.y, glm::vec3(0.f, 1.f, 0.f)); + const glm::quat roll = glm::angleAxis(rot.z, glm::vec3(0.f, 0.f, 1.f)); return glm::mat4_cast(glm::normalize(pitch * yaw * roll)); } @@ -677,7 +679,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat const glm::mat4 globalRot = globalRotation(); const glm::mat4 nodeRot = nodeRotation(); - glm::mat4 combinedGlobalRot = nodeRot * globalRot; + const glm::mat4 combinedGlobalRot = nodeRot * globalRot; if (_camera) { _camera->sgctInternal.setViewMatrix(viewMatrix * combinedGlobalRot * sceneMatrix); @@ -717,7 +719,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat ); std::string fn = std::to_string(_frameNumber); - WindowDelegate::Frustum frustum = global::windowDelegate->frustumMode(); + const WindowDelegate::Frustum frustum = global::windowDelegate->frustumMode(); std::string fr = [](WindowDelegate::Frustum f) -> std::string { switch (f) { case WindowDelegate::Frustum::Mono: return ""; @@ -731,7 +733,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat std::string dt = std::to_string(global::windowDelegate->deltaTime()); std::string avgDt = std::to_string(global::windowDelegate->averageDeltaTime()); - std::string res = fmt::format( + const std::string res = std::format( "Frame: {} {}\nSwap group frame: {}\nDt: {}\nAvg Dt: {}", fn, fr, sgFn, dt, avgDt ); @@ -755,7 +757,7 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat ssrs.begin(), ssrs.end(), [](ScreenSpaceRenderable* lhs, ScreenSpaceRenderable* rhs) { - // Render back to front. + // Render back to front return lhs->depth() > rhs->depth(); } ); @@ -780,12 +782,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons if (intersects(mousePosition, _cameraButtonLocations.rotation)) { - constexpr const char ToggleRotationFrictionScript[] = R"( + constexpr std::string_view ToggleRotationFrictionScript = R"( local f = 'NavigationHandler.OrbitalNavigator.Friction.RotationalFriction'; openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)"; global::scriptEngine->queueScript( - ToggleRotationFrictionScript, + std::string(ToggleRotationFrictionScript), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -793,12 +795,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons } if (intersects(mousePosition, _cameraButtonLocations.zoom)) { - constexpr const char ToggleZoomFrictionScript[] = R"( + constexpr std::string_view ToggleZoomFrictionScript = R"( local f = 'NavigationHandler.OrbitalNavigator.Friction.ZoomFriction'; openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)"; global::scriptEngine->queueScript( - ToggleZoomFrictionScript, + std::string(ToggleZoomFrictionScript), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -806,12 +808,12 @@ bool RenderEngine::mouseActivationCallback(const glm::dvec2& mousePosition) cons } if (intersects(mousePosition, _cameraButtonLocations.roll)) { - constexpr const char ToggleRollFrictionScript[] = R"( + constexpr std::string_view ToggleRollFrictionScript = R"( local f = 'NavigationHandler.OrbitalNavigator.Friction.RollFriction'; openspace.setPropertyValueSingle(f, not openspace.propertyValue(f));)"; global::scriptEngine->queueScript( - ToggleRollFrictionScript, + std::string(ToggleRollFrictionScript), scripting::ScriptEngine::ShouldBeSynchronized::Yes, scripting::ScriptEngine::ShouldSendToRemote::Yes ); @@ -869,7 +871,7 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) { glEnable(GL_BLEND); // t = 1.f -> start of shutdown counter t = 0.f -> timer has reached shutdown - float t = 1.f - (timer / fullTime); + const float t = 1.f - (timer / fullTime); rendering::helper::renderBox( glm::vec2(0.f), @@ -885,7 +887,7 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) { constexpr std::string_view FirstLine = "Shutdown in: {:.2f}s/{:.2f}s"; const glm::vec2 size1 = _fontShutdown->boundingBox( - fmt::format(FirstLine, timer, fullTime) + std::format(FirstLine, timer, fullTime) ); glm::vec2 penPosition = glm::vec2( @@ -896,17 +898,17 @@ void RenderEngine::renderShutdownInformation(float timer, float fullTime) { RenderFont( *_fontShutdown, penPosition, - fmt::format(FirstLine, timer, fullTime), + std::format(FirstLine, timer, fullTime), ghoul::fontrendering::CrDirection::Down ); // Important: Length of this string is the same as the first line to make them align RenderFont(*_fontShutdown, penPosition, "Press ESC again to abort"); } -void RenderEngine::renderDashboard() { +void RenderEngine::renderDashboard() const { ZoneScoped; - glm::vec2 dashboardStart = global::dashboard->getStartPositionOffset(); + const glm::vec2 dashboardStart = global::dashboard->getStartPositionOffset(); glm::vec2 penPosition = glm::vec2( dashboardStart.x, dashboardStart.y + fontResolution().y - global::luaConsole->currentHeight() @@ -963,7 +965,7 @@ bool RenderEngine::isHdrDisabled() const { std::unique_ptr RenderEngine::buildRenderProgram( const std::string& name, const std::filesystem::path& vsPath, - std::filesystem::path fsPath, + const std::filesystem::path& fsPath, ghoul::Dictionary data) { ghoul::Dictionary dict = std::move(data); @@ -980,7 +982,7 @@ std::unique_ptr RenderEngine::buildRenderProgram( name, vsPath, absPath(RenderFsPath), - std::move(dict) + dict ); if (program) { @@ -995,7 +997,7 @@ std::unique_ptr RenderEngine::buildRenderProgram( std::unique_ptr RenderEngine::buildRenderProgram( const std::string& name, const std::filesystem::path& vsPath, - std::filesystem::path fsPath, + const std::filesystem::path& fsPath, const std::filesystem::path& csPath, ghoul::Dictionary data) { @@ -1013,7 +1015,7 @@ std::unique_ptr RenderEngine::buildRenderProgram( vsPath, absPath(RenderFsPath), csPath, - std::move(dict) + dict ); if (program) { @@ -1033,11 +1035,6 @@ void RenderEngine::removeRenderProgram(ghoul::opengl::ProgramObject* program) { } } -/** -* Set renderer data -* Called from the renderer, whenever it needs to update -* the dictionary of all rendering programs. -*/ void RenderEngine::setRendererData(ghoul::Dictionary rendererData) { _rendererData = std::move(rendererData); for (ghoul::opengl::ProgramObject* program : _programs) { @@ -1047,11 +1044,6 @@ void RenderEngine::setRendererData(ghoul::Dictionary rendererData) { } } -/** -* Set resolve data -* Called from the renderer, whenever it needs to update -* the dictionary of all post rendering programs. -*/ void RenderEngine::setResolveData(ghoul::Dictionary resolveData) { _resolveData = std::move(resolveData); for (ghoul::opengl::ProgramObject* program : _programs) { @@ -1061,9 +1053,6 @@ void RenderEngine::setResolveData(ghoul::Dictionary resolveData) { } } -/** - * Take a screenshot and store it in the ${SCREENSHOTS} directory - */ void RenderEngine::takeScreenshot() { // We only create the directory here, as we don't want to spam the users // screenshot folder everytime we start OpenSpace even when we are not taking any @@ -1115,7 +1104,7 @@ void RenderEngine::addScreenSpaceRenderable(std::unique_ptrend()) { - LERROR(fmt::format( + LERROR(std::format( "Cannot add scene space renderable. Identifier '{}' already exists", identifier )); @@ -1193,8 +1182,8 @@ void RenderEngine::renderCameraInformation() { return; } - const glm::vec4 EnabledColor = _enabledFontColor.value(); - const glm::vec4 DisabledColor = _disabledFontColor.value(); + const glm::vec4 EnabledColor = _enabledFontColor; + const glm::vec4 DisabledColor = _disabledFontColor; const glm::vec2 rotationBox = _fontCameraInfo->boundingBox("Rotation"); @@ -1274,7 +1263,7 @@ void RenderEngine::renderVersionInformation() { // If a developer hasn't placed the Git command in the path, this variable will be // empty - if (!std::string_view(OPENSPACE_GIT_COMMIT).empty()) { + if (!OPENSPACE_GIT_COMMIT.empty()) { // We check OPENSPACE_GIT_COMMIT but use OPENSPACE_GIT_FULL on purpose since // OPENSPACE_GIT_FULL will never be empty (always will contain at least @, but // checking for that is a bit brittle) @@ -1286,8 +1275,8 @@ void RenderEngine::renderVersionInformation() { ); } - [[maybe_unused]] float debugOffset = 0.f; #ifdef _DEBUG + [[maybe_unused]] float debugOffset = 0.f; { const glm::vec2 debugBox = _fontVersionInfo->boundingBox("Debug build"); debugOffset = debugBox.y; @@ -1302,6 +1291,8 @@ void RenderEngine::renderVersionInformation() { glm::vec4(0.2f, 0.75f, 0.15f, 1.f) ); } +#else // !_DEBUG + [[maybe_unused]] const float debugOffset = 0.f; #endif // _DEBUG #ifdef TRACY_ENABLE @@ -1359,29 +1350,29 @@ void RenderEngine::renderScreenLog() { const double d = (diff - ttf).count(); const float t = static_cast(d) / static_cast(FadeTime.count()); const float p = 0.8f - t; - alpha = (p <= 0.f) ? 0.f : pow(p, 0.4f); + alpha = (p <= 0.f) ? 0.f : std::pow(p, 0.4f); } // Since all log entries are ordered, once one exceeds alpha, all have if (alpha <= 0.f) { break; } - std::string_view message = std::string_view(it.message).substr(0, MessageLength); + const std::string_view message = + std::string_view(it.message).substr(0, MessageLength); nRows += std::count(message.begin(), message.end(), '\n'); - const glm::vec4 white(0.9f, 0.9f, 0.9f, alpha); + const glm::vec4 white = glm::vec4(0.9f, 0.9f, 0.9f, alpha); std::array buf; { std::fill(buf.begin(), buf.end(), char(0)); - char* end = fmt::format_to( + char* end = std::format_to( buf.data(), "{:<15} {}{}", it.timeString, std::string_view(it.category).substr(0, CategoryLength), it.category.length() > CategoryLength ? "..." : "" ); - std::string_view text = std::string_view(buf.data(), end - buf.data()); RenderFont( *_fontLog, @@ -1389,7 +1380,7 @@ void RenderEngine::renderScreenLog() { 10.f, _fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset ), - text, + std::string_view(buf.data(), end - buf.data()), white ); } @@ -1400,15 +1391,14 @@ void RenderEngine::renderScreenLog() { const std::string_view lvl = ghoul::to_string(it.level); std::fill(buf.begin(), buf.end(), char(0)); - char* end = fmt::format_to(buf.data(), "({})", lvl); - std::string_view levelText = std::string_view(buf.data(), end - buf.data()); + char* end = std::format_to(buf.data(), "({})", lvl); RenderFont( *_fontLog, glm::vec2( 10 + (30 + 3) * _fontLog->pointSize(), _fontLog->pointSize() * nRows * 2 + fontRes.y * _verticalLogOffset ), - levelText, + std::string_view(buf.data(), end - buf.data()), color ); } diff --git a/src/rendering/screenspacerenderable.cpp b/src/rendering/screenspacerenderable.cpp index 11c55fb8d1..af8f29ea08 100644 --- a/src/rendering/screenspacerenderable.cpp +++ b/src/rendering/screenspacerenderable.cpp @@ -283,7 +283,7 @@ std::string ScreenSpaceRenderable::makeUniqueIdentifier(std::string name) { return taken; }; - std::string baseName = name; + const std::string baseName = name; int i = 1; while (nameTaken(name)) { name = baseName + std::to_string(i); @@ -424,7 +424,7 @@ ScreenSpaceRenderable::ScreenSpaceRenderable(const ghoul::Dictionary& dictionary // when this triggerProperty was pressed in the gui, therefor it has already been // synced and sent to the connected nodes and peers global::scriptEngine->queueScript( - script, + std::move(script), scripting::ScriptEngine::ShouldBeSynchronized::No, scripting::ScriptEngine::ShouldSendToRemote::No ); @@ -459,7 +459,7 @@ bool ScreenSpaceRenderable::deinitializeGL() { void ScreenSpaceRenderable::render(float blackoutFactor) { ZoneScoped; - glm::mat4 mat = + const glm::mat4 mat = globalRotationMatrix() * translationMatrix() * localRotationMatrix() * @@ -533,7 +533,7 @@ void ScreenSpaceRenderable::createShaders() { glm::mat4 ScreenSpaceRenderable::scaleMatrix() { // to scale the plane - float textureRatio = + const float textureRatio = static_cast(_objectSize.y) / static_cast(_objectSize.x); glm::mat4 scale = glm::scale( @@ -549,7 +549,8 @@ glm::vec2 ScreenSpaceRenderable::screenSpacePosition() { } glm::vec2 ScreenSpaceRenderable::screenSpaceDimensions() { - float ratio = static_cast(_objectSize.x) / static_cast(_objectSize.y); + const float ratio = + static_cast(_objectSize.x) / static_cast(_objectSize.y); return glm::vec2(2.f * _scale * ratio, 2.f * _scale); } @@ -561,22 +562,22 @@ glm::vec2 ScreenSpaceRenderable::lowerLeftCornerScreenSpace() { return screenSpacePosition() - (screenSpaceDimensions() / 2.0f); } -bool ScreenSpaceRenderable::isIntersecting(glm::vec2 coord) { - bool isUnderTopBorder = coord.x < upperRightCornerScreenSpace().x; - bool isLeftToRightBorder = coord.y < upperRightCornerScreenSpace().y; - bool isRightToLeftBorder = coord.x > lowerLeftCornerScreenSpace().x; - bool isOverBottomBorder = coord.y > lowerLeftCornerScreenSpace().y; +bool ScreenSpaceRenderable::isIntersecting(const glm::vec2& coord) { + const bool isUnderTopBorder = coord.x < upperRightCornerScreenSpace().x; + const bool isLeftToRightBorder = coord.y < upperRightCornerScreenSpace().y; + const bool isRightToLeftBorder = coord.x > lowerLeftCornerScreenSpace().x; + const bool isOverBottomBorder = coord.y > lowerLeftCornerScreenSpace().y; return isUnderTopBorder && isLeftToRightBorder && isRightToLeftBorder && isOverBottomBorder; } void ScreenSpaceRenderable::translate(glm::vec2 translation, glm::vec2 position) { - glm::mat4 translationMatrix = glm::translate( + const glm::mat4 translationMatrix = glm::translate( glm::mat4(1.f), - glm::vec3(translation, 0.0f) + glm::vec3(translation, 0.f) ); - glm::vec4 origin = glm::vec4(position, _cartesianPosition.value().z, 1.0f); + const glm::vec4 origin = glm::vec4(position, _cartesianPosition.value().z, 1.f); _cartesianPosition = translationMatrix * origin; } @@ -597,7 +598,7 @@ glm::mat4 ScreenSpaceRenderable::globalRotationMatrix() { // 1) The global rotation of the view applied in the render engine // 2) sgct's scene matrix (also called model matrix by sgct) - glm::mat4 inverseRotation = glm::inverse( + const glm::mat4 inverseRotation = glm::inverse( global::renderEngine->globalRotation() * global::windowDelegate->modelMatrix() ); @@ -609,7 +610,7 @@ glm::mat4 ScreenSpaceRenderable::globalRotationMatrix() { glm::mat4 ScreenSpaceRenderable::localRotationMatrix() { glm::mat4 rotation = glm::mat4(1.f); if (_faceCamera) { - glm::vec3 translation = _useRadiusAzimuthElevation ? + const glm::vec3 translation = _useRadiusAzimuthElevation ? sphericalToCartesian(raeToSpherical(_raePosition)) : _cartesianPosition; @@ -620,9 +621,9 @@ glm::mat4 ScreenSpaceRenderable::localRotationMatrix() { )); } - float roll = _localRotation.value().x; - float pitch = _localRotation.value().y; - float yaw = _localRotation.value().z; + const float roll = _localRotation.value().x; + const float pitch = _localRotation.value().y; + const float yaw = _localRotation.value().z; return rotation * glm::mat4(glm::quat(glm::vec3(pitch, yaw, roll))); } @@ -635,19 +636,19 @@ glm::vec3 ScreenSpaceRenderable::cartesianToRae(const glm::vec3& cartesian) cons } glm::mat4 ScreenSpaceRenderable::translationMatrix() { - glm::vec3 translation = _useRadiusAzimuthElevation ? + const glm::vec3 translation = _useRadiusAzimuthElevation ? sphericalToCartesian(raeToSpherical(_raePosition)) : _cartesianPosition; return glm::translate(glm::mat4(1.f), translation); } -void ScreenSpaceRenderable::draw(glm::mat4 modelTransform, float blackoutFactor) { +void ScreenSpaceRenderable::draw(const glm::mat4& modelTransform, float blackoutFactor) { glDisable(GL_CULL_FACE); _shader->activate(); // Calculate the border from pixels to UV coordinates - glm::vec2 borderUV = glm::vec2( + const glm::vec2 borderUV = glm::vec2( _borderWidth / static_cast(_objectSize.x), _borderWidth / static_cast(_objectSize.y) ); @@ -715,18 +716,18 @@ glm::vec3 ScreenSpaceRenderable::sphericalToCartesian(glm::vec3 spherical) const glm::vec3 ScreenSpaceRenderable::cartesianToSpherical(const glm::vec3& cartesian) const { // Rotate cartesian coordinates. - glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y); + const glm::vec3 rotated = glm::vec3(cartesian.x, cartesian.z, -cartesian.y); - const float r = sqrt( - pow(rotated.x, 2.f) + pow(rotated.y, 2.f) + pow(rotated.z, 2.f) + const float r = std::sqrt( + std::pow(rotated.x, 2.f) + std::pow(rotated.y, 2.f) + std::pow(rotated.z, 2.f) ); - const float theta = acos(rotated.z / r); - const float phi = atan2(rotated.y, rotated.x); + const float theta = std::acos(rotated.z / r); + const float phi = std::atan2(rotated.y, rotated.x); return sanitizeSphericalCoordinates(glm::vec3(r, theta, phi)); } // Radius, azimiuth, elevation to spherical coordinates. -glm::vec3 ScreenSpaceRenderable::raeToSpherical(glm::vec3 rae) const { +glm::vec3 ScreenSpaceRenderable::raeToSpherical(const glm::vec3& rae) const { //return rae; const float r = rae.x; @@ -741,15 +742,15 @@ glm::vec3 ScreenSpaceRenderable::raeToSpherical(glm::vec3 rae) const { } // Spherical coordinates to radius, azimuth and elevation. -glm::vec3 ScreenSpaceRenderable::sphericalToRae(glm::vec3 spherical) const { +glm::vec3 ScreenSpaceRenderable::sphericalToRae(const glm::vec3& spherical) const { //return spherical; const float r = spherical.x; // Azimuth on screen is angle from negative y, as opposed to from x. - float azimuth = spherical.z + glm::half_pi(); + const float azimuth = spherical.z + glm::half_pi(); // Elevation is polar angle - pi/2 - float elevation = wrap( + const float elevation = wrap( spherical.y - glm::half_pi(), -glm::pi(), glm::pi() diff --git a/src/rendering/texturecomponent.cpp b/src/rendering/texturecomponent.cpp index f66337a530..dcda824d91 100644 --- a/src/rendering/texturecomponent.cpp +++ b/src/rendering/texturecomponent.cpp @@ -99,7 +99,7 @@ void TextureComponent::loadFromFile(const std::filesystem::path& path) { ); if (texture) { - LDEBUG(fmt::format("Loaded texture from {}", absolutePath)); + LDEBUG(std::format("Loaded texture from '{}'", absolutePath)); _texture = std::move(texture); _textureFile = std::make_unique(absolutePath); diff --git a/src/rendering/transferfunction.cpp b/src/rendering/transferfunction.cpp index 5d663e9c80..893119cfd3 100644 --- a/src/rendering/transferfunction.cpp +++ b/src/rendering/transferfunction.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include #include @@ -56,7 +55,7 @@ void TransferFunction::setPath(const std::string& filepath) { if (_file) { _file = nullptr; } - std::filesystem::path f = absPath(filepath); + const std::filesystem::path f = absPath(filepath); if (!std::filesystem::is_regular_file(f)) { LERROR("Could not find transfer function file"); _file = nullptr; @@ -71,7 +70,7 @@ void TransferFunction::setPath(const std::string& filepath) { ghoul::opengl::Texture& TransferFunction::texture() { ghoul_assert(_texture != nullptr, "Transfer function is null"); update(); - return *_texture.get(); + return *_texture; } void TransferFunction::update() { @@ -127,10 +126,10 @@ void TransferFunction::setTextureFromTxt() { upper = glm::clamp(upper, lower, 1.f); } else if (key == "mappingkey") { - float intensity; - glm::vec4 rgba = glm::vec4(0.f); + float intensity = 0.f; + glm::vec4 rgba; iss >> intensity; - for(int i = 0; i < 4; ++i) { + for(int i = 0; i < 4; i++) { iss >> rgba[i]; } mappingKeys.emplace_back(intensity, rgba); @@ -152,18 +151,22 @@ void TransferFunction::setTextureFromTxt() { // allocate new float array with zeros float* transferFunction = new float[width * 4]; - for (int i = 0; i < 4 * width; ++i) { + for (int i = 0; i < 4 * width; i++) { transferFunction[i] = 0.f; } - size_t lowerIndex = static_cast(floorf(lower * static_cast(width-1))); - size_t upperIndex = static_cast(floorf(upper * static_cast(width-1))); + const size_t lowerIndex = static_cast( + std::floor(lower * static_cast(width - 1)) + ); + const size_t upperIndex = static_cast( + std::floor(upper * static_cast(width - 1)) + ); auto prevKey = mappingKeys.begin(); auto currentKey = prevKey + 1; auto lastKey = mappingKeys.end() -1; - for (size_t i = lowerIndex; i <= upperIndex; ++i) { + for (size_t i = lowerIndex; i <= upperIndex; i++) { const float fpos = static_cast(i) / static_cast(width-1); if (fpos > currentKey->position) { prevKey = currentKey; diff --git a/src/scene/asset.cpp b/src/scene/asset.cpp index 15c34bdfff..309ce7de86 100644 --- a/src/scene/asset.cpp +++ b/src/scene/asset.cpp @@ -24,6 +24,7 @@ #include +#include #include #include #include @@ -278,10 +279,10 @@ void Asset::initialize() { return; } if (!isSynchronized()) { - LERROR(fmt::format("Cannot initialize unsynchronized asset {}", _assetPath)); + LERROR(std::format("Cannot initialize unsynchronized asset '{}'", _assetPath)); return; } - LDEBUG(fmt::format("Initializing asset {}", _assetPath)); + LDEBUG(std::format("Initializing asset '{}'", _assetPath)); // 1. Initialize requirements for (Asset* child : _requiredAssets) { @@ -292,9 +293,15 @@ void Asset::initialize() { try { _manager.callOnInitialize(this); } + catch (const documentation::SpecificationError& e) { + LERROR(std::format("Failed to initialize asset '{}'", path())); + documentation::logError(e); + setState(State::InitializationFailed); + return; + } catch (const ghoul::RuntimeError& e) { - LERROR(fmt::format("Failed to initialize asset {}", path())); - LERROR(fmt::format("{}: {}", e.component, e.message)); + LERROR(std::format("Failed to initialize asset '{}'", path())); + LERROR(std::format("{}: {}", e.component, e.message)); setState(State::InitializationFailed); return; } @@ -307,7 +314,7 @@ void Asset::deinitialize() { if (!isInitialized()) { return; } - LDEBUG(fmt::format("Deinitializing asset {}", _assetPath)); + LDEBUG(std::format("Deinitializing asset '{}'", _assetPath)); // Perform inverse actions as in initialize, in reverse order (3 - 1) @@ -319,8 +326,8 @@ void Asset::deinitialize() { _manager.callOnDeinitialize(this); } catch (const ghoul::lua::LuaRuntimeException& e) { - LERROR(fmt::format("Failed to deinitialize asset {}", _assetPath)); - LERROR(fmt::format("{}: {}", e.component, e.message)); + LERROR(std::format("Failed to deinitialize asset '{}'", _assetPath)); + LERROR(std::format("{}: {}", e.component, e.message)); return; } diff --git a/src/scene/assetmanager.cpp b/src/scene/assetmanager.cpp index a085346bd8..7a9dc5e14f 100644 --- a/src/scene/assetmanager.cpp +++ b/src/scene/assetmanager.cpp @@ -106,21 +106,6 @@ namespace { #include "assetmanager_codegen.cpp" } // namespace -namespace fmt { - template - struct formatter> :fmt::formatter { - - template - auto format(const std::optional& opt, FormatContext& ctx) { - if (opt) { - fmt::formatter::format(*opt, ctx); - return ctx.out(); - } - return fmt::format_to(ctx.out(), ""); - } - }; -} // namespace fmt - namespace openspace { AssetManager::AssetManager(ghoul::lua::LuaState* state, @@ -169,7 +154,7 @@ void AssetManager::update() { // Initialize all assets that have been loaded and synchronized but that not yet // initialized - for (auto it = _toBeInitialized.cbegin(); it != _toBeInitialized.cend(); ++it) { + for (auto it = _toBeInitialized.cbegin(); it != _toBeInitialized.cend(); it++) { ZoneScopedN("Initializing queued assets"); Asset* a = *it; @@ -194,7 +179,7 @@ void AssetManager::update() { for (const std::string& asset : _assetAddQueue) { ZoneScopedN("Adding queued assets"); - std::filesystem::path path = generateAssetPath(_assetRootDirectory, asset); + const std::filesystem::path path = generateAssetPath(_assetRootDirectory, asset); Asset* a = nullptr; try { a = retrieveAsset(path, ""); @@ -238,7 +223,7 @@ void AssetManager::update() { [&path](const std::unique_ptr& a) { return a->path() == path; } ); if (it == _assets.cend()) { - LWARNING(fmt::format("Tried to remove unknown asset {}. Skipping", asset)); + LWARNING(std::format("Tried to remove unknown asset '{}'. Skipping", asset)); continue; } @@ -288,7 +273,7 @@ void AssetManager::update() { it = _unfinishedSynchronizations.erase(it); } else if (si->synchronization->isRejected()) { - LERROR(fmt::format( + LERROR(std::format( "Failed to synchronize resource '{}'", si->synchronization->name() )); for (Asset* a : si->assets) { @@ -297,7 +282,7 @@ void AssetManager::update() { it = _unfinishedSynchronizations.erase(it); } else { - ++it; + it++; } } } @@ -362,8 +347,8 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) { }; if (!std::filesystem::is_regular_file(asset->path())) { - LERROR(fmt::format( - "Could not load asset {}: File does not exist", asset->path()) + LERROR(std::format( + "Could not load asset '{}': File does not exist", asset->path()) ); return false; } @@ -372,7 +357,7 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) { ghoul::lua::runScriptFile(*_luaState, asset->path()); } catch (const ghoul::lua::LuaRuntimeException& e) { - LERROR(fmt::format("Could not load asset {}: {}", asset->path(), e.message)); + LERROR(std::format("Could not load asset '{}': {}", asset->path(), e.message)); return false; } catch (const ghoul::RuntimeError& e) { @@ -384,18 +369,18 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) { lua_getglobal(*_luaState, AssetGlobalVariableName); ghoul_assert(lua_istable(*_luaState, -1), "Expected 'asset' table"); lua_getfield(*_luaState, -1, "meta"); - ghoul::Dictionary metaDict = ghoul::lua::luaDictionaryFromState(*_luaState); + const ghoul::Dictionary metaDict = ghoul::lua::luaDictionaryFromState(*_luaState); if (!metaDict.isEmpty()) { - Parameters p = codegen::bake(metaDict); + const Parameters p = codegen::bake(metaDict); Asset::MetaInformation meta; - meta.name = p.name.value_or(""); - meta.version = p.version.value_or(""); - meta.description = p.description.value_or(""); - meta.author = p.author.value_or(""); - meta.url = p.url.value_or(""); - meta.license = p.license.value_or(""); - meta.identifiers = p.identifiers.value_or(std::vector()); + meta.name = p.name.value_or(meta.name); + meta.version = p.version.value_or(meta.version); + meta.description = p.description.value_or(meta.description); + meta.author = p.author.value_or(meta.author); + meta.url = p.url.value_or(meta.url); + meta.license = p.license.value_or(meta.license); + meta.identifiers = p.identifiers.value_or(meta.identifiers); // We need to do this as the asset might have 'export'ed identifiers before // defining the meta table. Therefore the meta information already contains some @@ -415,12 +400,12 @@ bool AssetManager::loadAsset(Asset* asset, Asset* parent) { void AssetManager::unloadAsset(Asset* asset) { ghoul_precondition(asset, "Asset must not be nullptr"); - for (int ref : _onInitializeFunctionRefs[asset]) { + for (const int ref : _onInitializeFunctionRefs[asset]) { luaL_unref(*_luaState, LUA_REGISTRYINDEX, ref); } _onInitializeFunctionRefs[asset].clear(); - for (int ref : _onDeinitializeFunctionRefs[asset]) { + for (const int ref : _onDeinitializeFunctionRefs[asset]) { luaL_unref(*_luaState, LUA_REGISTRYINDEX, ref); } _onDeinitializeFunctionRefs[asset].clear(); @@ -435,7 +420,7 @@ void AssetManager::unloadAsset(Asset* asset) { ghoul::lua::push(*_luaState, ghoul::lua::nil_t()); // Clear entry from global asset table (pushed to the Lua stack earlier) - std::string path = asset->path().string(); + const std::string path = asset->path().string(); lua_setfield(*_luaState, globalTableIndex, path.c_str()); lua_settop(*_luaState, top); @@ -509,11 +494,12 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource"); if (ghoul::lua::hasValue(L)) { - ghoul::Dictionary d = ghoul::lua::value(L); + const ghoul::Dictionary d = ghoul::lua::value(L); std::unique_ptr s = ResourceSynchronization::createFromDictionary(d); - std::string uid = d.value("Type") + "/" + s->generateUid(); + const std::string uid = + d.value("Type") + "/" + s->generateUid(); SyncItem* syncItem = nullptr; auto it = manager->_synchronizations.find(uid); if (it == manager->_synchronizations.end()) { @@ -539,7 +525,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { } else if (ghoul::lua::hasValue>(L)) { auto [name] = ghoul::lua::values>(L); - std::filesystem::path path = + const std::filesystem::path path = name.has_value() ? thisAsset->path().parent_path() / *name : thisAsset->path().parent_path(); @@ -569,7 +555,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource"); auto [name] = ghoul::lua::values>(L); - std::filesystem::path path = + const std::filesystem::path path = name.has_value() ? thisAsset->path().parent_path() / *name : thisAsset->path().parent_path(); @@ -595,11 +581,11 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { Asset* thisAsset = ghoul::lua::userData(L, 2); ghoul::lua::checkArgumentsAndThrow(L, { 0, 1 }, "lua::resource"); - ghoul::Dictionary d = ghoul::lua::value(L); + const ghoul::Dictionary d = ghoul::lua::value(L); std::unique_ptr s = ResourceSynchronization::createFromDictionary(d); - std::string uid = d.value("Type") + "/" + s->generateUid(); + const std::string uid = d.value("Type") + "/" + s->generateUid(); SyncItem* syncItem = nullptr; auto it = manager->_synchronizations.find(uid); if (it == manager->_synchronizations.end()) { @@ -645,7 +631,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { auto [assetName, explicitEnable] = ghoul::lua::values>(L); - std::filesystem::path path = manager->generateAssetPath( + const std::filesystem::path path = manager->generateAssetPath( parent->path().parent_path(), assetName ); @@ -657,7 +643,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { if (!dependency) { return ghoul::lua::luaError( L, - fmt::format("Asset '{}' not found", assetName) + std::format("Asset '{}' not found", assetName) ); } // this = parent ; child = dependency @@ -683,7 +669,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { // Get the exports table lua_rawgeti(L, LUA_REGISTRYINDEX, manager->_assetsTableRef); - std::string p = dependency->path().string(); + const std::string p = dependency->path().string(); lua_getfield(L, -1, p.c_str()); lua_getfield(L, -1, ExportsTableName); return 1; @@ -705,7 +691,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { ghoul::lua::checkArgumentsAndThrow(L, 1, "lua::exists"); const std::string name = ghoul::lua::value(L); - std::filesystem::path path = manager->generateAssetPath( + const std::filesystem::path path = manager->generateAssetPath( thisAsset->path().parent_path(), name ); @@ -728,12 +714,16 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { AssetManager* manager = ghoul::lua::userData(L, 1); Asset* thisAsset = ghoul::lua::userData(L, 2); - int n = ghoul::lua::checkArgumentsAndThrow(L, { 1 , 2 }, "lua::exportAsset"); + const int n = ghoul::lua::checkArgumentsAndThrow( + L, + { 1 , 2 }, + "lua::exportAsset" + ); std::string exportName; std::string identifier; - int targetLocation; + int targetLocation = 0; if (n == 1) { - ghoul::Dictionary d = ghoul::lua::value( + const ghoul::Dictionary d = ghoul::lua::value( L, 1, ghoul::lua::PopValue::No @@ -762,7 +752,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { // the identifier if it actually is a table *and* if that table // contains the 'Identifier' key - ghoul::Dictionary d = ghoul::lua::value( + const ghoul::Dictionary d = ghoul::lua::value( L, 2, ghoul::lua::PopValue::No @@ -779,7 +769,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { lua_rawgeti(L, LUA_REGISTRYINDEX, manager->_assetsTableRef); - std::string path = thisAsset->path().string(); + const std::string path = thisAsset->path().string(); lua_getfield(L, -1, path.c_str()); lua_getfield(L, -1, ExportsTableName); const int exportsTableIndex = lua_gettop(L); @@ -864,7 +854,7 @@ void AssetManager::setUpAssetLuaTable(Asset* asset) { // Extend global asset info table (pushed to the Lua stack earlier) // with this AssetInfo table - std::string path = asset->path().string(); + const std::string path = asset->path().string(); lua_setfield(*_luaState, globalTableIndex, path.c_str()); lua_settop(*_luaState, top); } @@ -887,7 +877,7 @@ Asset* AssetManager::retrieveAsset(const std::filesystem::path& path, if (a->firstParent()) { // The first request came from another asset, so we can mention it in the // error message - LWARNING(fmt::format( + LWARNING(std::format( "Loading asset {0} from {1} with enable state {3} different from " "initial loading from {2} with state {4}. Only {4} will have an " "effect", @@ -914,8 +904,8 @@ Asset* AssetManager::retrieveAsset(const std::filesystem::path& path, } if (!std::filesystem::is_regular_file(path)) { - throw ghoul::RuntimeError(fmt::format( - "Could not find asset file {} requested by {}", + throw ghoul::RuntimeError(std::format( + "Could not find asset file '{}' requested by '{}'", path, retriever )); } @@ -935,11 +925,11 @@ void AssetManager::callOnInitialize(Asset* asset) const { return; } - for (int init : it->second) { + for (const int init : it->second) { lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, init); if (lua_pcall(*_luaState, 0, 0, 0) != LUA_OK) { - throw ghoul::lua::LuaRuntimeException(fmt::format( - "When initializing {}: {}", + throw ghoul::lua::LuaRuntimeException(std::format( + "When initializing '{}': {}", asset->path(), ghoul::lua::value(*_luaState, -1) )); @@ -958,11 +948,11 @@ void AssetManager::callOnDeinitialize(Asset* asset) const { return; } - for (int deinit : it->second) { + for (const int deinit : it->second) { lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, deinit); if (lua_pcall(*_luaState, 0, 0, 0) != LUA_OK) { - throw ghoul::lua::LuaRuntimeException(fmt::format( - "When deinitializing {}: {}", + throw ghoul::lua::LuaRuntimeException(std::format( + "When deinitializing '{}': {}", asset->path(), ghoul::lua::value(*_luaState, -1) )); @@ -983,7 +973,7 @@ void AssetManager::setCurrentAsset(Asset* asset) { else { // Set `asset` lua global to point to the current asset table lua_rawgeti(*_luaState, LUA_REGISTRYINDEX, _assetsTableRef); - std::string path = asset->path().string(); + const std::string path = asset->path().string(); lua_getfield(*_luaState, -1, path.c_str()); lua_getfield(*_luaState, -1, AssetTableName); lua_setglobal(*_luaState, AssetGlobalVariableName); @@ -1000,7 +990,7 @@ std::filesystem::path AssetManager::generateAssetPath( // 3) Absolute paths (*:/* or /*) // 2) Relative to the global asset root (*) - PathType pathType = classifyPath(assetPath); + const PathType pathType = classifyPath(assetPath); std::string prefix; if (pathType == PathType::RelativeToAsset) { prefix = baseDirectory.string() + '/'; diff --git a/src/scene/profile.cpp b/src/scene/profile.cpp index 7b80defb18..571a232506 100644 --- a/src/scene/profile.cpp +++ b/src/scene/profile.cpp @@ -78,12 +78,12 @@ namespace { if (!isOptional) { throw Profile::ParsingError( Profile::ParsingError::Severity::Error, - fmt::format("'{}.{}' field is missing", keyPrefix, key) + std::format("'{}.{}' field is missing", keyPrefix, key) ); } } else { - const nlohmann::json value = j[key]; + const nlohmann::json& value = j[key]; if (!(value.*checkFunc)()) { std::string type = [](auto c) { if (c == &nlohmann::json::is_string) { return "a string"; } @@ -98,7 +98,7 @@ namespace { throw Profile::ParsingError( Profile::ParsingError::Severity::Error, - fmt::format("'{}.{}' must be {}", keyPrefix, key, type) + std::format("'{}.{}' must be {}", keyPrefix, key, type) ); } } @@ -111,7 +111,7 @@ namespace { if (allowedKeys.find(key) == allowedKeys.end()) { LINFOC( "Profile", - fmt::format("Key '{}' not supported in '{}'", key, prefix) + std::format("Key '{}' not supported in '{}'", key, prefix) ); } } @@ -229,7 +229,7 @@ void to_json(nlohmann::json& j, const Profile::Property::SetType& v) { } void from_json(const nlohmann::json& j, Profile::Property::SetType& v) { - std::string value = j.get(); + const std::string value = j.get(); if (value == "setPropertyValue") { v = Profile::Property::SetType::SetPropertyValue; } @@ -315,7 +315,7 @@ void to_json(nlohmann::json& j, const Profile::Time::Type& v) { } void from_json(const nlohmann::json& j, Profile::Time::Type& v) { - std::string value = j.get(); + const std::string value = j.get(); if (value == "absolute") { v = Profile::Time::Type::Absolute; } @@ -381,14 +381,14 @@ void to_json(nlohmann::json& j, const Profile::CameraNavState& v) { j["aim"] = *v.aim; } j["frame"] = v.referenceFrame; - nlohmann::json p { + const nlohmann::json p { { "x", v.position.x }, { "y", v.position.y }, { "z", v.position.z } }; j["position"] = p; if (v.up.has_value()) { - nlohmann::json u { + const nlohmann::json u { { "x", v.up->x }, { "y", v.up->y }, { "z", v.up->z } @@ -575,16 +575,16 @@ void convertVersion10to11(nlohmann::json& profile) { std::vector kbs = profile.at("keybindings").get>(); - for (size_t i = 0; i < kbs.size(); ++i) { + for (size_t i = 0; i < kbs.size(); i++) { version10::Keybinding& kb = kbs[i]; - std::string identifier = fmt::format("profile.keybind.{}", i); + const std::string identifier = std::format("profile.keybind.{}", i); Profile::Action action; action.identifier = identifier; action.documentation = std::move(kb.documentation); action.name = std::move(kb.name); action.guiPath = std::move(kb.guiPath); - action.isLocal = std::move(kb.isLocal); + action.isLocal = kb.isLocal; action.script = std::move(kb.script); actions.push_back(std::move(action)); @@ -635,7 +635,7 @@ void Profile::saveCurrentSettingsToProfile(const properties::PropertyOwner& root version = Profile::CurrentVersion; // Update properties - std::vector ps = changedProperties(rootOwner); + const std::vector ps = changedProperties(rootOwner); for (properties::Property* prop : ps) { Property p; @@ -749,13 +749,13 @@ Profile::Profile(const std::filesystem::path& path) { inFile.open(path, std::ifstream::in); } catch (const std::ifstream::failure& e) { - throw ghoul::RuntimeError(fmt::format( - "Exception opening profile file for read: {} ({})", path, e.what() + throw ghoul::RuntimeError(std::format( + "Exception opening profile file for read '{}': {}", path, e.what() )); } - std::string content( - (std::istreambuf_iterator(inFile)), + const std::string content = std::string( + std::istreambuf_iterator(inFile), std::istreambuf_iterator() ); @@ -830,7 +830,7 @@ Profile::Profile(const std::filesystem::path& path) { } catch (const nlohmann::json::exception& e) { std::string err = e.what(); - throw ParsingError(ParsingError::Severity::Error, err); + throw ParsingError(ParsingError::Severity::Error, std::move(err)); } } diff --git a/src/scene/profile_lua.inl b/src/scene/profile_lua.inl index f006c6de3c..9fd8f3de0f 100644 --- a/src/scene/profile_lua.inl +++ b/src/scene/profile_lua.inl @@ -43,7 +43,7 @@ namespace { std::tm* utcTime = std::gmtime(&t); ghoul_assert(utcTime, "Conversion to UTC failed"); - std::string time = fmt::format( + std::string time = std::format( "{:04d}-{:02d}-{:02d}T{:02d}_{:02d}_{:02d}", utcTime->tm_year + 1900, utcTime->tm_mon + 1, @@ -54,22 +54,25 @@ namespace { ); std::filesystem::path path = global::configuration->profile; path.replace_extension(); - std::string newFile = fmt::format("{}_{}", path.string(), time); - std::string sourcePath = fmt::format( + std::string newFile = std::format("{}_{}", path.string(), time); + std::string sourcePath = std::format( "{}/{}.profile", absPath("${USER_PROFILES}").string(), global::configuration->profile ); - std::string destPath = fmt::format( + std::string destPath = std::format( "{}/{}.profile", absPath("${PROFILES}").string(), global::configuration->profile ); if (!std::filesystem::is_regular_file(sourcePath)) { - sourcePath = fmt::format( + sourcePath = std::format( "{}/{}.profile", absPath("${USER_PROFILES}").string(), global::configuration->profile ); } - LINFOC("Profile", fmt::format("Saving a copy of the old profile as {}", newFile)); + LINFOC( + "Profile", + std::format("Saving a copy of the old profile as '{}'", newFile) + ); std::filesystem::copy(sourcePath, destPath); saveFilePath = global::configuration->profile; } @@ -95,7 +98,7 @@ namespace { ); } - std::string absFilename = fmt::format( + std::string absFilename = std::format( "{}/{}.profile", absPath("${PROFILES}").string(), *saveFilePath ); if (!std::filesystem::is_regular_file(absFilename)) { @@ -104,7 +107,7 @@ namespace { if (std::filesystem::is_regular_file(absFilename) && !overwrite) { throw ghoul::lua::LuaError( - fmt::format( + std::format( "Unable to save profile '{}'. File of same name already exists", absFilename ) @@ -118,8 +121,8 @@ namespace { } catch (const std::ofstream::failure& e) { throw ghoul::lua::LuaError( - fmt::format( - "Exception opening profile file for write: {} ({})", absFilename, e.what() + std::format( + "Exception opening profile file for write '{}': {}", absFilename, e.what() ) ); } @@ -129,7 +132,7 @@ namespace { } catch (const std::ofstream::failure& e) { throw ghoul::lua::LuaError( - fmt::format("Data write error to file: {} ({})", absFilename, e.what()) + std::format("Data write error to file '{}': {}", absFilename, e.what()) ); } } diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index 12953dd95d..0f9af62620 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -60,6 +60,7 @@ namespace { constexpr std::string_view _loggerCat = "Scene"; constexpr std::string_view KeyIdentifier = "Identifier"; constexpr std::string_view KeyParent = "Parent"; + constexpr const char* RootNodeIdentifier = "Root"; #ifdef TRACY_ENABLE constexpr const char* renderBinToString(int renderBin) { @@ -88,6 +89,16 @@ namespace { } #endif // TRACY_ENABLE + std::chrono::steady_clock::time_point currentTimeForInterpolation() { + using namespace openspace::global; + if (sessionRecording->isSavingFramesDuringPlayback()) { + return sessionRecording->currentPlaybackInterpolationTime(); + } + else { + return std::chrono::steady_clock::now(); + } + } + template struct overloaded : Ts... { using Ts::operator()...; }; template overloaded(Ts...) -> overloaded; } // namespace @@ -103,10 +114,10 @@ Scene::Scene(std::unique_ptr initializer) , _camera(std::make_unique()) , _initializer(std::move(initializer)) { - _rootDummy.setIdentifier(SceneGraphNode::RootNodeIdentifier); - _rootDummy.setScene(this); + _rootNode.setIdentifier(RootNodeIdentifier); + _rootNode.setScene(this); - _camera->setParent(&_rootDummy); + _camera->setParent(&_rootNode); } Scene::~Scene() { @@ -116,7 +127,7 @@ Scene::~Scene() { continue; } - LWARNING(fmt::format( + LWARNING(std::format( "SceneGraphNode '{}' was not removed before shutdown", node->identifier() )); @@ -127,16 +138,16 @@ Scene::~Scene() { node->deinitializeGL(); node->deinitialize(); } - _rootDummy.clearChildren(); - _rootDummy.setScene(nullptr); + _rootNode.clearChildren(); + _rootNode.setScene(nullptr); } void Scene::attachNode(ghoul::mm_unique_ptr node) { - _rootDummy.attachChild(std::move(node)); + _rootNode.attachChild(std::move(node)); } ghoul::mm_unique_ptr Scene::detachNode(SceneGraphNode& node) { - return _rootDummy.detachChild(node); + return _rootNode.detachChild(node); } Camera* Scene::camera() const { @@ -144,10 +155,10 @@ Camera* Scene::camera() const { } void Scene::registerNode(SceneGraphNode* node) { - if (_nodesByIdentifier.count(node->identifier())) { - throw Scene::InvalidSceneError( - "Node with identifier " + node->identifier() + " already exists" - ); + if (_nodesByIdentifier.contains(node->identifier())) { + throw Scene::InvalidSceneError(std::format( + "Node with identifier '{}' already exists", node->identifier() + )); } _topologicallySortedNodes.push_back(node); @@ -206,7 +217,7 @@ void Scene::sortTopologically() { } // Only the Root node can have an in-degree of 0 - SceneGraphNode* root = _nodesByIdentifier[SceneGraphNode::RootNodeIdentifier]; + SceneGraphNode* root = _nodesByIdentifier[RootNodeIdentifier]; if (!root) { throw Scene::InvalidSceneError("No root node found"); } @@ -248,7 +259,7 @@ void Scene::sortTopologically() { } } if (!inDegrees.empty()) { - LERROR(fmt::format( + LERROR(std::format( "The scene contains circular dependencies. {} nodes will be disabled", inDegrees.size() )); @@ -262,6 +273,8 @@ void Scene::sortTopologically() { } void Scene::initializeNode(SceneGraphNode* node) { + ghoul_assert(node, "Node must not be nullptr"); + _initializer->initializeNode(node); } @@ -272,8 +285,8 @@ bool Scene::isInitializing() const { void Scene::update(const UpdateData& data) { ZoneScoped; - std::vector initializedNodes = _initializer->takeInitializedNodes(); - for (SceneGraphNode* node : initializedNodes) { + const std::vector initialized = _initializer->takeInitializedNodes(); + for (SceneGraphNode* node : initialized) { try { node->initializeGL(); } @@ -333,11 +346,11 @@ const std::unordered_map& Scene::nodesByIdentifier } SceneGraphNode* Scene::root() { - return &_rootDummy; + return &_rootNode; } const SceneGraphNode* Scene::root() const { - return &_rootDummy; + return &_rootNode; } SceneGraphNode* Scene::sceneGraphNode(const std::string& name) const { @@ -360,7 +373,7 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { const bool hasParent = nodeDictionary.hasKey(KeyParent); if (_nodesByIdentifier.find(nodeIdentifier) != _nodesByIdentifier.end()) { - LERROR(fmt::format( + LERROR(std::format( "Cannot add scene graph node '{}'. A node with that name already exists", nodeIdentifier )); @@ -373,7 +386,7 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { parent = sceneGraphNode(parentIdentifier); if (!parent) { // TODO: Throw exception - LERROR(fmt::format( + LERROR(std::format( "Could not find parent '{}' for '{}'", parentIdentifier, nodeIdentifier )); return nullptr; @@ -383,10 +396,6 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { ghoul::mm_unique_ptr node = SceneGraphNode::createFromDictionary( nodeDictionary ); - if (!node) { - // TODO: Throw exception - LERROR("Could not create node from dictionary: " + nodeIdentifier); - } if (nodeDictionary.hasKey(SceneGraphNode::KeyDependencies)) { if (!nodeDictionary.hasValue(SceneGraphNode::KeyDependencies)) @@ -394,12 +403,12 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { // TODO: Throw exception LERROR("Dependencies did not have the corrent type"); } - ghoul::Dictionary nodeDependencies = + const ghoul::Dictionary nodeDependencies = nodeDictionary.value(SceneGraphNode::KeyDependencies); - for (std::string_view key : nodeDependencies.keys()) { + for (const std::string_view key : nodeDependencies.keys()) { std::string value = nodeDependencies.value(key); - dependencyNames.push_back(value); + dependencyNames.push_back(std::move(value)); } } @@ -410,7 +419,7 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { SceneGraphNode* dep = sceneGraphNode(depName); if (!dep) { // TODO: Throw exception - LERROR(fmt::format( + LERROR(std::format( "Could not find dependency '{}' for '{}'", depName, nodeIdentifier )); foundAllDeps = false; @@ -437,15 +446,6 @@ SceneGraphNode* Scene::loadNode(const ghoul::Dictionary& nodeDictionary) { return rawNodePointer; } -std::chrono::steady_clock::time_point Scene::currentTimeForInterpolation() { - if (global::sessionRecording->isSavingFramesDuringPlayback()) { - return global::sessionRecording->currentPlaybackInterpolationTime(); - } - else { - return std::chrono::steady_clock::now(); - } -} - void Scene::addPropertyInterpolation(properties::Property* prop, float durationSeconds, std::string postScript, ghoul::EasingFunction easingFunction) @@ -469,7 +469,7 @@ void Scene::addPropertyInterpolation(properties::Property* prop, float durationS ghoul::easingFunction(easingFunction); // First check if the current property already has an interpolation information - std::chrono::steady_clock::time_point now = currentTimeForInterpolation(); + const std::chrono::steady_clock::time_point now = currentTimeForInterpolation(); for (PropertyInterpolationInfo& info : _propertyInterpolationInfos) { if (info.prop == prop) { info.beginTime = now; @@ -520,10 +520,10 @@ void Scene::updateInterpolations() { using namespace std::chrono; - steady_clock::time_point now = currentTimeForInterpolation(); + const steady_clock::time_point now = currentTimeForInterpolation(); // First, let's update the properties for (PropertyInterpolationInfo& i : _propertyInterpolationInfos) { - long long us = + const long long us = duration_cast(now - i.beginTime).count(); const float t = glm::clamp( @@ -615,7 +615,7 @@ void Scene::propertyPushProfileValueToLua(ghoul::lua::LuaState& L, _valueIsTable = false; ProfilePropertyLua elem = propertyProcessValue(L, value); if (!_valueIsTable) { - std::visit(overloaded{ + std::visit(overloaded { [&L](bool v) { ghoul::lua::push(L, v); }, @@ -636,7 +636,7 @@ ProfilePropertyLua Scene::propertyProcessValue(ghoul::lua::LuaState& L, const std::string& value) { ProfilePropertyLua result; - PropertyValueType pType = propertyValueType(value); + const PropertyValueType pType = propertyValueType(value); switch (pType) { case PropertyValueType::Boolean: @@ -648,27 +648,31 @@ ProfilePropertyLua Scene::propertyProcessValue(ghoul::lua::LuaState& L, case PropertyValueType::Nil: result = ghoul::lua::nil_t(); break; - case PropertyValueType::Table: - ghoul::trimSurroundingCharacters(const_cast(value), '{'); - ghoul::trimSurroundingCharacters(const_cast(value), '}'); - handlePropertyLuaTableEntry(L, value); + case PropertyValueType::Table: { + std::string val = value; + ghoul::trimSurroundingCharacters(val, '{'); + ghoul::trimSurroundingCharacters(val, '}'); + handlePropertyLuaTableEntry(L, val); _valueIsTable = true; break; + } case PropertyValueType::String: - default: - ghoul::trimSurroundingCharacters(const_cast(value), '\"'); - ghoul::trimSurroundingCharacters(const_cast(value), '['); - ghoul::trimSurroundingCharacters(const_cast(value), ']'); - result = value; + default: { + std::string val = value; + ghoul::trimSurroundingCharacters(val, '\"'); + ghoul::trimSurroundingCharacters(val, '['); + ghoul::trimSurroundingCharacters(val, ']'); + result = val; break; + } } return result; } void Scene::handlePropertyLuaTableEntry(ghoul::lua::LuaState& L, const std::string& value) { - PropertyValueType enclosedType; - size_t commaPos = value.find(',', 0); + PropertyValueType enclosedType = PropertyValueType::Nil; + const size_t commaPos = value.find(',', 0); if (commaPos != std::string::npos) { enclosedType = propertyValueType(value.substr(0, commaPos)); } @@ -678,30 +682,30 @@ void Scene::handlePropertyLuaTableEntry(ghoul::lua::LuaState& L, const std::stri switch (enclosedType) { case PropertyValueType::Boolean: - LERROR(fmt::format( - "A lua table of bool values is not supported. (processing property {})", - _profilePropertyName) - ); + LERROR(std::format( + "A Lua table of bool values is not supported. (processing property '{}')", + _profilePropertyName + )); break; case PropertyValueType::Float: { - std::vector valsF; - processPropertyValueTableEntries(L, value, valsF); - ghoul::lua::push(L, valsF); + std::vector vals; + processPropertyValueTableEntries(L, value, vals); + ghoul::lua::push(L, vals); } break; case PropertyValueType::String: { - std::vector valsS; - processPropertyValueTableEntries(L, value, valsS); - ghoul::lua::push(L, valsS); + std::vector vals; + processPropertyValueTableEntries(L, value, vals); + ghoul::lua::push(L, vals); } break; case PropertyValueType::Table: default: - LERROR(fmt::format( + LERROR(std::format( "Table-within-a-table values are not supported for profile a " - "property (processing property {})", _profilePropertyName + "property (processing property '{}')", _profilePropertyName )); break; } @@ -729,9 +733,9 @@ void Scene::processPropertyValueTableEntries(ghoul::lua::LuaState& L, table.push_back(std::get(tableElement)); } catch (std::bad_variant_access&) { - LERROR(fmt::format( - "Error attempting to parse profile property setting for " - "{} using value = {}", _profilePropertyName, value + LERROR(std::format( + "Error attempting to parse profile property setting for '{}' using " + "value = {}", _profilePropertyName, value )); } } @@ -767,7 +771,7 @@ PropertyValueType Scene::propertyValueType(const std::string& value) { } std::vector Scene::propertiesMatchingRegex( - std::string propertyString) + const std::string& propertyString) { return findMatchesInAllProperties(propertyString, allProperties(), ""); } @@ -875,19 +879,19 @@ scripting::LuaLibrary Scene::luaLibrary() { }; } -std::string makeIdentifier(std::string s) { +std::string makeIdentifier(std::string str) { // Note that we want to preserve '-' and '_', but replace any other punctuation // marks. Hence, we first convert '_' to whitespaces to avoid them being replaced // in the puncutation check - std::replace(s.begin(), s.end(), '_', ' '); + std::replace(str.begin(), str.end(), '_', ' '); std::replace_if( - s.begin(), - s.end(), + str.begin(), + str.end(), [](unsigned char c) { return std::ispunct(c) != 0; }, '-' ); - std::replace(s.begin(), s.end(), ' ', '_'); - return s; + std::replace(str.begin(), str.end(), ' ', '_'); + return str; } } // namespace openspace diff --git a/src/scene/scene_lua.inl b/src/scene/scene_lua.inl index 5241f7b2f1..765193ab7c 100644 --- a/src/scene/scene_lua.inl +++ b/src/scene/scene_lua.inl @@ -109,7 +109,7 @@ std::vector findMatchesInAllProperties( if (propertyName.empty() && nodeName.empty()) { LERRORC( "findMatchesInAllProperties", - fmt::format( + std::format( "Malformed regular expression: '{}': Empty both before and after '*'", regex ) @@ -121,7 +121,7 @@ std::vector findMatchesInAllProperties( if (regex.find_first_of("*", wildPos + 1) != std::string::npos) { LERRORC( "findMatchesInAllProperties", - fmt::format( + std::format( "Malformed regular expression: '{}': Currently only one '*' is " "supported", regex ) @@ -224,9 +224,9 @@ void applyRegularExpression(lua_State* L, const std::string& regex, if (type != prop->typeLua()) { LERRORC( "property_setValue", - fmt::format( + std::format( "{}: Property '{}' does not accept input of type '{}'. Requested " - "type: '{}'", + "type: {}", errorLocation(L), prop->fullyQualifiedIdentifier(), luaTypeToString(type), luaTypeToString(prop->typeLua()) ) @@ -253,7 +253,7 @@ void applyRegularExpression(lua_State* L, const std::string& regex, global::renderEngine->scene()->addPropertyInterpolation( prop, static_cast(interpolationDuration), - std::move(postScript), + postScript, easingFunction ); } @@ -263,7 +263,7 @@ void applyRegularExpression(lua_State* L, const std::string& regex, if (!foundMatching) { LERRORC( "property_setValue", - fmt::format( + std::format( "{}: No property matched the requested URI '{}'", errorLocation(L), regex ) ); @@ -303,9 +303,9 @@ int setPropertyCallSingle(properties::Property& prop, const std::string& uri, if (type != prop.typeLua()) { LERRORC( "property_setValue", - fmt::format( + std::format( "{}: Property '{}' does not accept input of type '{}'. " - "Requested type: '{}'", + "Requested type: {}", errorLocation(L), uri, luaTypeToString(type), luaTypeToString(prop.typeLua()) ) @@ -363,8 +363,8 @@ int propertySetValue(lua_State* L) { ghoul::lua::value(L, 3, ghoul::lua::PopValue::No); } else { - std::string msg = fmt::format( - "Unexpected type {} in argument 3", + std::string msg = std::format( + "Unexpected type '{}' in argument 3", ghoul::lua::luaTypeToString(lua_type(L, 3)) ); return ghoul::lua::luaError(L, msg); @@ -376,8 +376,8 @@ int propertySetValue(lua_State* L) { ghoul::lua::value(L, 4, ghoul::lua::PopValue::No); } else { - std::string msg = fmt::format( - "Unexpected type {} in argument 4", + std::string msg = std::format( + "Unexpected type '{}' in argument 4", ghoul::lua::luaTypeToString(lua_type(L, 4)) ); return ghoul::lua::luaError(L, msg); @@ -389,8 +389,8 @@ int propertySetValue(lua_State* L) { ghoul::lua::value(L, 5, ghoul::lua::PopValue::No); } else { - std::string msg = fmt::format( - "Unexpected type {} in argument 5", + std::string msg = std::format( + "Unexpected type '{}' in argument 5", ghoul::lua::luaTypeToString(lua_type(L, 5)) ); return ghoul::lua::luaError(L, msg); @@ -402,7 +402,7 @@ int propertySetValue(lua_State* L) { if (!correctName) { LWARNINGC( "propertySetValue", - fmt::format("{} is not a valid easing method", easingMethodName) + std::format("'{}' is not a valid easing method", easingMethodName) ); } else { @@ -415,7 +415,7 @@ int propertySetValue(lua_State* L) { if (!prop) { LERRORC( "property_setValue", - fmt::format( + std::format( "{}: Property with URI '{}' was not found", ghoul::lua::errorLocation(L), uriOrRegex ) @@ -459,7 +459,7 @@ int propertyGetValue(lua_State* L) { if (!prop) { LERRORC( "propertyGetValue", - fmt::format( + std::format( "{}: Property with URI '{}' was not found", ghoul::lua::errorLocation(L), uri ) @@ -517,7 +517,7 @@ namespace { // If none then malformed regular expression if (propertyName.empty() && nodeName.empty()) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Malformed regular expression: '{}': Empty both before and after '*'", regex )); @@ -525,7 +525,7 @@ namespace { // Currently do not support several wildcards if (regex.find_first_of("*", wildPos + 1) != std::string::npos) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Malformed regular expression: '{}': Currently only one '*' is supported", regex )); @@ -578,7 +578,6 @@ namespace { else if (!nodeName.empty()) { size_t nodePos = id.find(nodeName); if (nodePos != std::string::npos) { - // Check tag if (!groupName.empty()) { properties::PropertyOwner* matchingTaggedOwner = @@ -638,12 +637,12 @@ namespace { logError(e, cat); throw ghoul::lua::LuaError( - fmt::format("Error loading scene graph node: {}", e.what()) + std::format("Error loading scene graph node: {}", e.what()) ); } catch (const ghoul::RuntimeError& e) { throw ghoul::lua::LuaError( - fmt::format("Error loading scene graph node: {}", e.what()) + std::format("Error loading scene graph node: {}", e.what()) ); } } @@ -677,7 +676,7 @@ namespace { SceneGraphNode* foundNode = sceneGraphNode(identifier); if (!foundNode) { throw ghoul::lua::LuaError( - fmt::format("Did not find a match for identifier: {} ", identifier) + std::format("Did not find a match for identifier: {}", identifier) ); } @@ -739,7 +738,7 @@ namespace { // If none then malformed regular expression if (propertyName.empty() && nodeName.empty()) { throw ghoul::lua::LuaError( - fmt::format( + std::format( "Malformed regular expression: '{}': Empty both before and after '*'", name ) @@ -749,7 +748,7 @@ namespace { // Currently do not support several wildcards if (name.find_first_of("*", wildPos + 1) != std::string::npos) { throw ghoul::lua::LuaError( - fmt::format( + std::format( "Malformed regular expression: '{}': " "Currently only one '*' is supported", name @@ -813,7 +812,7 @@ namespace { if (!foundMatch) { throw ghoul::lua::LuaError( - fmt::format("Did not find a match for identifier: {}", name) + std::format("Did not find a match for identifier: {}", name) ); } @@ -932,7 +931,7 @@ namespace { SceneGraphNode* node = sceneGraphNode(identifier); if (!node) { throw ghoul::lua::LuaError( - fmt::format("Did not find a match for identifier: {} ", identifier) + std::format("Did not find a match for identifier: {} ", identifier) ); } @@ -949,7 +948,7 @@ namespace { SceneGraphNode* node = sceneGraphNode(identifier); if (!node) { throw ghoul::lua::LuaError( - fmt::format("Did not find a match for identifier: {} ", identifier) + std::format("Did not find a match for identifier: {} ", identifier) ); } @@ -965,14 +964,14 @@ namespace { using namespace openspace; SceneGraphNode* node = sceneGraphNode(identifier); if (!node) { - throw ghoul::lua::LuaError(fmt::format( - "Did not find a match for identifier: {} ", identifier + throw ghoul::lua::LuaError(std::format( + "Did not find a match for identifier: {}", identifier )); } SceneGraphNode* newParentNode = sceneGraphNode(newParent); if (!newParentNode) { - throw ghoul::lua::LuaError(fmt::format( - "Did not find a match for new parent identifier: {} ", newParent + throw ghoul::lua::LuaError(std::format( + "Did not find a match for new parent identifier: {}", newParent )); } @@ -988,8 +987,8 @@ namespace { using namespace openspace; SceneGraphNode* node = sceneGraphNode(identifier); if (!node) { - throw ghoul::lua::LuaError(fmt::format( - "Did not find a match for identifier: {} ", identifier + throw ghoul::lua::LuaError(std::format( + "Did not find a match for identifier: {}", identifier )); } @@ -1005,8 +1004,8 @@ namespace { using namespace openspace; SceneGraphNode* node = sceneGraphNode(identifier); if (!node) { - throw ghoul::lua::LuaError(fmt::format( - "Did not find a match for identifier: {} ", identifier + throw ghoul::lua::LuaError(std::format( + "Did not find a match for identifier: {}", identifier )); } @@ -1097,7 +1096,7 @@ enum class [[codegen::enum]] CustomPropertyType { } if (global::userPropertyOwner->hasProperty(identifier)) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Failed to register property '{}' since a user-defined property with that " "name already exists", identifier @@ -1219,7 +1218,7 @@ enum class [[codegen::enum]] CustomPropertyType { delete p; } else { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Could not find user-defined property '{}'", identifier )); } diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index c67685baab..e35d569367 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -380,16 +380,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( *p.transform->translation ); - // @TODO(abock, 2021-03-05) I don't think this is necessary anymore as we - // transitioned to throwing exceptions when the construction fails - if (result->_transform.translation == nullptr) { - LERROR(fmt::format( - "Failed to create ephemeris for SceneGraphNode '{}'", - result->identifier() - )); - return nullptr; - } - LDEBUG(fmt::format( + LDEBUG(std::format( "Successfully created ephemeris for '{}'", result->identifier() )); } @@ -399,16 +390,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( *p.transform->rotation ); - // @TODO(abock, 2021-03-05) I don't think this is necessary anymore as we - // transitioned to throwing exceptions when the construction fails - if (result->_transform.rotation == nullptr) { - LERROR(fmt::format( - "Failed to create rotation for SceneGraphNode '{}'", - result->identifier() - )); - return nullptr; - } - LDEBUG(fmt::format( + LDEBUG(std::format( "Successfully created rotation for '{}'", result->identifier() )); } @@ -416,16 +398,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( if (p.transform->scale.has_value()) { result->_transform.scale = Scale::createFromDictionary(*p.transform->scale); - // @TODO(abock, 2021-03-05) I don't think this is necessary anymore as we - // transitioned to throwing exceptions when the construction fails - if (result->_transform.scale == nullptr) { - LERROR(fmt::format( - "Failed to create scale for SceneGraphNode '{}'", - result->identifier() - )); - return nullptr; - } - LDEBUG(fmt::format( + LDEBUG(std::format( "Successfully created scale for '{}'", result->identifier() )); } @@ -438,16 +411,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( if (p.timeFrame.has_value()) { result->_timeFrame = TimeFrame::createFromDictionary(*p.timeFrame); - // @TODO(abock, 2021-03-05) I don't think this is necessary anymore as we - // transitioned to throwing exceptions when the construction fails - if (result->_timeFrame == nullptr) { - LERROR(fmt::format( - "Failed to create time frame for SceneGraphNode '{}'", - result->identifier() - )); - return nullptr; - } - LDEBUG(fmt::format( + LDEBUG(std::format( "Successfully created time frame for '{}'", result->identifier() )); result->addPropertySubOwner(result->_timeFrame.get()); @@ -459,7 +423,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( ghoul_assert(result->_renderable, "Failed to create Renderable"); result->_renderable->_parent = result.get(); result->addPropertySubOwner(result->_renderable.get()); - LDEBUG(fmt::format( + LDEBUG(std::format( "Successfully created renderable for '{}'", result->identifier() )); } @@ -517,7 +481,7 @@ ghoul::mm_unique_ptr SceneGraphNode::createFromDictionary( } } - LDEBUG(fmt::format("Successfully created SceneGraphNode '{}'", result->identifier())); + LDEBUG(std::format("Successfully created SceneGraphNode '{}'", result->identifier())); result->_lastScreenSpaceUpdateTime = std::chrono::high_resolution_clock::now(); result->_type = "SceneGraphNode"; @@ -620,7 +584,7 @@ void SceneGraphNode::initialize() { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - LDEBUG(fmt::format("Initializing: {}", identifier())); + LDEBUG(std::format("Initializing: {}", identifier())); if (_renderable) { _renderable->initialize(); @@ -641,14 +605,14 @@ void SceneGraphNode::initialize() { _evaluatedBoundingSphere = boundingSphere(); _evaluatedInteractionSphere = interactionSphere(); - LDEBUG(fmt::format("Finished initializing: {}", identifier())); + LDEBUG(std::format("Finished initializing: {}", identifier())); } void SceneGraphNode::initializeGL() { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - LDEBUG(fmt::format("Initializing GL: {}", identifier())); + LDEBUG(std::format("Initializing GL: {}", identifier())); if (_renderable) { _renderable->initializeGL(); @@ -674,14 +638,14 @@ void SceneGraphNode::initializeGL() { _state = State::GLInitialized; - LDEBUG(fmt::format("Finished initializating GL: {}", identifier())); + LDEBUG(std::format("Finished initializating GL: {}", identifier())); } void SceneGraphNode::deinitialize() { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - LDEBUG(fmt::format("Deinitializing: {}", identifier())); + LDEBUG(std::format("Deinitializing: {}", identifier())); setScene(nullptr); @@ -691,20 +655,20 @@ void SceneGraphNode::deinitialize() { clearChildren(); _parent = nullptr; - LDEBUG(fmt::format("Finished deinitializing: {}", identifier())); + LDEBUG(std::format("Finished deinitializing: {}", identifier())); } void SceneGraphNode::deinitializeGL() { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - LDEBUG(fmt::format("Deinitializing GL: {}", identifier())); + LDEBUG(std::format("Deinitializing GL: {}", identifier())); if (_renderable) { _renderable->deinitializeGL(); } - LDEBUG(fmt::format("Finished deinitializing GL: {}", identifier())); + LDEBUG(std::format("Finished deinitializing GL: {}", identifier())); } void SceneGraphNode::traversePreOrder(const std::function& fn) { @@ -725,8 +689,7 @@ void SceneGraphNode::update(const UpdateData& data) { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - State s = _state; - if (s != State::Initialized && _state != State::GLInitialized) { + if (_state != State::Initialized && _state != State::GLInitialized) { return; } if (!isTimeFrameActive(data.time)) { @@ -755,12 +718,13 @@ void SceneGraphNode::update(const UpdateData& data) { newUpdateData.modelTransform.rotation = _worldRotationCached; newUpdateData.modelTransform.scale = _worldScaleCached; - glm::dmat4 translation = glm::translate( + const glm::dmat4 translation = glm::translate( glm::dmat4(1.0), newUpdateData.modelTransform.translation ); - glm::dmat4 rotation = glm::dmat4(newUpdateData.modelTransform.rotation); - glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), newUpdateData.modelTransform.scale); + const glm::dmat4 rotation = glm::dmat4(newUpdateData.modelTransform.rotation); + const glm::dmat4 scaling = + glm::scale(glm::dmat4(1.0), newUpdateData.modelTransform.scale); _modelTransformCached = translation * rotation * scaling; @@ -816,7 +780,7 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { } } - bool isInStickerBin = + const bool isInStickerBin = data.renderBinMask & static_cast(Renderable::RenderBin::Sticker); if (_showDebugSphere && isInStickerBin) { @@ -830,15 +794,17 @@ void SceneGraphNode::render(const RenderData& data, RendererTasks& tasks) { } } -void SceneGraphNode::renderDebugSphere(const Camera& camera, double size, glm::vec4 color) +void SceneGraphNode::renderDebugSphere(const Camera& camera, double size, + const glm::vec4& color) { - glm::dvec3 scaleVec = _worldScaleCached * size; - glm::dmat4 modelTransform = + const glm::dvec3 scaleVec = _worldScaleCached * size; + const glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), _worldPositionCached) * glm::dmat4(_worldRotationCached) * glm::scale(glm::dmat4(1.0), scaleVec); - glm::mat4 modelViewProjection = camera.projectionMatrix() * + + const glm::mat4 modelViewProjection = camera.projectionMatrix() * glm::mat4(camera.combinedViewMatrix() * modelTransform); _debugSphereProgram->activate(); @@ -1018,13 +984,14 @@ void SceneGraphNode::computeScreenSpaceData(RenderData& newData) { return; } - glm::ivec2 res = global::windowDelegate->currentSubwindowSize(); + const glm::ivec2 res = global::windowDelegate->currentSubwindowSize(); // Get the radius of node - double nodeRadius = boundingSphere(); + const double nodeRadius = boundingSphere(); // Distance from the camera to the node - double distFromCamToNode = glm::distance(cam.positionVec3(), worldPos) - nodeRadius; + const double distFromCamToNode = + glm::distance(cam.positionVec3(), worldPos) - nodeRadius; // Fix to limit the update of properties if (distFromCamToNode >= _visibilityDistance) { @@ -1218,6 +1185,7 @@ void SceneGraphNode::setScene(Scene* scene) { std::vector SceneGraphNode::children() const { std::vector nodes; + nodes.reserve(_children.size()); for (const ghoul::mm_unique_ptr& child : _children) { nodes.push_back(child.get()); } diff --git a/src/scene/sceneinitializer.cpp b/src/scene/sceneinitializer.cpp index 387b61618f..9425a13e99 100644 --- a/src/scene/sceneinitializer.cpp +++ b/src/scene/sceneinitializer.cpp @@ -71,7 +71,7 @@ void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) { catch (const ghoul::RuntimeError& e) { LERRORC(e.component, e.message); } - std::lock_guard g(_mutex); + const std::lock_guard g(_mutex); _initializedNodes.push_back(node); _initializingNodes.erase(node); @@ -98,7 +98,7 @@ void MultiThreadedSceneInitializer::initializeNode(SceneGraphNode* node) { ); } - std::lock_guard g(_mutex); + const std::lock_guard g(_mutex); _initializingNodes.insert(node); _threadPool.enqueue(initFunction); } @@ -111,13 +111,13 @@ std::vector MultiThreadedSceneInitializer::takeInitializedNodes std::this_thread::sleep_for(std::chrono::milliseconds(1)); } - std::lock_guard g(_mutex); + const std::lock_guard g(_mutex); std::vector nodes = std::move(_initializedNodes); return nodes; } bool MultiThreadedSceneInitializer::isInitializing() const { - std::lock_guard g(_mutex); + const std::lock_guard g(_mutex); return !_initializingNodes.empty(); } diff --git a/src/scripting/lualibrary.cpp b/src/scripting/lualibrary.cpp index c3c77999ca..2c4045a4bb 100644 --- a/src/scripting/lualibrary.cpp +++ b/src/scripting/lualibrary.cpp @@ -46,7 +46,7 @@ void LuaLibrary::merge(LuaLibrary rhs) { // want to overwrite it LERRORC( "LuaLibrary", - fmt::format( + std::format( "Lua function '{}' in library '{}' has been defined twice", fun.name, rhs.name ) diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index f29b555162..1fbadf409f 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -163,7 +163,7 @@ bool ScriptEngine::hasLibrary(const std::string& name) { return (it != _registeredLibraries.end()); } -bool ScriptEngine::runScript(const std::string& script, ScriptCallback callback) { +bool ScriptEngine::runScript(const std::string& script, const ScriptCallback& callback) { ZoneScoped; ghoul_assert(!script.empty(), "Script must not be empty"); @@ -212,7 +212,7 @@ bool ScriptEngine::runScriptFile(const std::filesystem::path& filename) { ZoneScoped; if (!std::filesystem::is_regular_file(filename)) { - LERROR(fmt::format("Script with name {} did not exist", filename)); + LERROR(std::format("Script with name {} did not exist", filename)); return false; } @@ -247,35 +247,35 @@ bool ScriptEngine::isLibraryNameAllowed(lua_State* state, const std::string& nam result = true; break; case LUA_TBOOLEAN: - LERROR(fmt::format("Library name '{}' specifies a boolean", name)); + LERROR(std::format("Library name '{}' specifies a boolean", name)); break; case LUA_TLIGHTUSERDATA: - LERROR(fmt::format("Library name '{}' specifies a light user data", name)); + LERROR(std::format("Library name '{}' specifies a light user data", name)); break; case LUA_TNUMBER: - LERROR(fmt::format("Library name '{}' specifies a number", name)); + LERROR(std::format("Library name '{}' specifies a number", name)); break; case LUA_TSTRING: - LERROR(fmt::format("Library name '{}' specifies a string", name)); + LERROR(std::format("Library name '{}' specifies a string", name)); break; case LUA_TTABLE: if (hasLibrary(name)) { - LERROR(fmt::format( + LERROR(std::format( "Library with name '{}' has been registered before", name )); } else { - LERROR(fmt::format("Library name '{}' specifies a table", name)); + LERROR(std::format("Library name '{}' specifies a table", name)); } break; case LUA_TFUNCTION: - LERROR(fmt::format("Library name '{}' specifies a function", name)); + LERROR(std::format("Library name '{}' specifies a function", name)); break; case LUA_TUSERDATA: - LERROR(fmt::format("Library name '{}' specifies a user data", name)); + LERROR(std::format("Library name '{}' specifies a user data", name)); break; case LUA_TTHREAD: - LERROR(fmt::format("Library name '{}' specifies a thread", name)); + LERROR(std::format("Library name '{}' specifies a thread", name)); break; } @@ -294,7 +294,7 @@ void ScriptEngine::addLibraryFunctions(lua_State* state, LuaLibrary& library, lua_getfield(state, -1, p.name.c_str()); const bool isNil = lua_isnil(state, -1); if (!isNil) { - LERROR(fmt::format("Function name '{}' was already assigned", p.name)); + LERROR(std::format("Function name '{}' was already assigned", p.name)); return; } lua_pop(state, 1); @@ -330,7 +330,7 @@ void ScriptEngine::addLibraryFunctions(lua_State* state, LuaLibrary& library, ghoul::lua::push(state, "documentation"); lua_gettable(state, -2); if (lua_isnil(state, -1)) { - LERROR(fmt::format( + LERROR(std::format( "Module '{}' did not provide a documentation in script file {}", library.name, script )); @@ -432,7 +432,7 @@ void ScriptEngine::writeLog(const std::string& script) { _logFilename = absPath(global::configuration->scriptLog).string(); _logFileExists = true; - LDEBUG(fmt::format( + LDEBUG(std::format( "Using script log file {}", std::filesystem::path(_logFilename) )); @@ -440,7 +440,7 @@ void ScriptEngine::writeLog(const std::string& script) { std::ofstream file(_logFilename, std::ofstream::out | std::ofstream::trunc); if (!file.good()) { - LERROR(fmt::format( + LERROR(std::format( "Could not open file {} for logging scripts", std::filesystem::path(_logFilename) )); @@ -457,7 +457,7 @@ void ScriptEngine::writeLog(const std::string& script) { // Simple text output to logfile std::ofstream file(_logFilename, std::ofstream::app); if (!file.good()) { - LERROR(fmt::format("Could not open file '{}' for logging scripts", _logFilename)); + LERROR(std::format("Could not open file '{}' for logging scripts", _logFilename)); return; } diff --git a/src/scripting/scriptengine_lua.inl b/src/scripting/scriptengine_lua.inl index ef8da626e9..64b6e60d9b 100644 --- a/src/scripting/scriptengine_lua.inl +++ b/src/scripting/scriptengine_lua.inl @@ -93,7 +93,7 @@ namespace { [[codegen::luawrap]] std::string readFile(std::filesystem::path file) { std::filesystem::path p = absPath(file); if (!std::filesystem::is_regular_file(p)) { - throw ghoul::lua::LuaError(fmt::format("Could not open file '{}'", file)); + throw ghoul::lua::LuaError(std::format("Could not open file '{}'", file)); } std::ifstream f(p); @@ -224,15 +224,15 @@ std::vector walkCommon(std::string path, bool recursive, bool sorte zip_close(z); if (is64) { - throw ghoul::lua::LuaError(fmt::format( - "Error while unzipping {}: Zip64 archives are not supported", source + throw ghoul::lua::LuaError(std::format( + "Error while unzipping '{}': Zip64 archives are not supported", source )); } int ret = zip_extract(source.c_str(), destination.c_str(), nullptr, nullptr); if (ret != 0) { - throw ghoul::lua::LuaError(fmt::format( - "Error {} while unzipping {}", ret, source + throw ghoul::lua::LuaError(std::format( + "Error while unzipping '{}': {}", source, ret )); } diff --git a/src/scripting/scriptscheduler.cpp b/src/scripting/scriptscheduler.cpp index daba62dc55..5024fd1ba1 100644 --- a/src/scripting/scriptscheduler.cpp +++ b/src/scripting/scriptscheduler.cpp @@ -120,7 +120,7 @@ void ScriptScheduler::loadScripts(std::vector scheduledScripts) ); for (ScheduledScript& script : scheduledScripts) { - _scripts.push_back(script); + _scripts.push_back(std::move(script)); } // Re-sort so it is always in sorted order in regards to time @@ -150,7 +150,7 @@ void ScriptScheduler::clearSchedule(std::optional group) { it = _scripts.erase(it); } else { - ++it; + it++; } } @@ -176,7 +176,7 @@ std::vector ScriptScheduler::progressTo(double newTime) { if (newTime > _currentTime) { // Moving forward in time; we need to find the highest entry in the timings // vector that is still smaller than the newTime - size_t prevIndex = _currentIndex; + const size_t prevIndex = _currentIndex; const auto it = std::upper_bound( _scripts.begin() + prevIndex, // We only need to start at the previous time _scripts.end(), @@ -196,12 +196,12 @@ std::vector ScriptScheduler::progressTo(double newTime) { // Construct result for (auto iter = _scripts.begin() + prevIndex; iter < (_scripts.begin() + _currentIndex); - ++iter) + iter++) { std::string script = iter->universalScript.empty() ? iter->forwardScript : iter->universalScript + "; " + iter->forwardScript; - result.push_back(script); + result.push_back(std::move(script)); } return result; @@ -234,7 +234,7 @@ std::vector ScriptScheduler::progressTo(double newTime) { std::string script = iter->universalScript.empty() ? iter->backwardScript : iter->universalScript + "; " + iter->backwardScript; - result.push_back(script); + result.push_back(std::move(script)); if (iter == _scripts.begin()) { break; @@ -255,7 +255,7 @@ double ScriptScheduler::currentTime() const { void ScriptScheduler::setCurrentTime(double time) { // Ensure _currentIndex and _currentTime is accurate after time jump - std::vector scheduledScripts = progressTo(time); + const std::vector scheduledScripts = progressTo(time); if (_shouldRunAllTimeJump) { // Queue all scripts for the time jump diff --git a/src/scripting/scriptscheduler_lua.inl b/src/scripting/scriptscheduler_lua.inl index 64d45eba2d..66d7598b0a 100644 --- a/src/scripting/scriptscheduler_lua.inl +++ b/src/scripting/scriptscheduler_lua.inl @@ -41,7 +41,7 @@ namespace { ); std::vector scripts; - for (size_t i = 1; i <= scriptsDict.size(); ++i) { + for (size_t i = 1; i <= scriptsDict.size(); i++) { ghoul::Dictionary d = scriptsDict.value(std::to_string(i)); scripting::ScriptScheduler::ScheduledScript script = diff --git a/src/util/blockplaneintersectiongeometry.cpp b/src/util/blockplaneintersectiongeometry.cpp index 5b73618863..888c826c3d 100644 --- a/src/util/blockplaneintersectiongeometry.cpp +++ b/src/util/blockplaneintersectiongeometry.cpp @@ -37,8 +37,8 @@ namespace openspace { BlockPlaneIntersectionGeometry::BlockPlaneIntersectionGeometry(glm::vec3 blockSize, glm::vec3 planeNormal, float planeDistance) - : _size(blockSize) - , _normal(planeNormal) + : _size(std::move(blockSize)) + , _normal(std::move(planeNormal)) , _planeDistance(planeDistance) {} @@ -52,7 +52,7 @@ void BlockPlaneIntersectionGeometry::setBlockSize(glm::vec3 size) { updateVertices(); } -void BlockPlaneIntersectionGeometry::setPlane(glm::vec3 normal, float distance) { +void BlockPlaneIntersectionGeometry::setPlane(const glm::vec3& normal, float distance) { _normal = glm::normalize(normal); _planeDistance = distance; updateVertices(); @@ -61,7 +61,7 @@ void BlockPlaneIntersectionGeometry::setPlane(glm::vec3 normal, float distance) void BlockPlaneIntersectionGeometry::updateVertices() { _vertices.clear(); - const int cornersInLines[24] = { + constexpr std::array CornersInLines = { 0, 1, 1, 5, 5, 4, @@ -84,23 +84,24 @@ void BlockPlaneIntersectionGeometry::updateVertices() { int nIntersections = 0; for (int i = 0; i < 12; i++) { - int iCorner0 = cornersInLines[i * 2]; - int iCorner1 = cornersInLines[i * 2 + 1]; + const int iCorner0 = CornersInLines[i * 2]; + const int iCorner1 = CornersInLines[i * 2 + 1]; - glm::vec3 corner0 = glm::vec3( + const glm::vec3 corner0 = glm::vec3( iCorner0 % 2, (iCorner0 / 2) % 2, iCorner0 / 4 ) - halfSize; - glm::vec3 corner1 = glm::vec3( + const glm::vec3 corner1 = glm::vec3( iCorner1 % 2, (iCorner1 / 2) % 2, iCorner1 / 4 ) - halfSize; - glm::vec3 line = corner1 - corner0; + const glm::vec3 line = corner1 - corner0; - float t = (_planeDistance - glm::dot(corner0, _normal)) / glm::dot(line, _normal); + const float t = + (_planeDistance - glm::dot(corner0, _normal)) / glm::dot(line, _normal); if (t >= 0.0 && t <= 1.0) { intersections[nIntersections++] = corner0 + t * line; } @@ -115,13 +116,13 @@ void BlockPlaneIntersectionGeometry::updateVertices() { std::vector> angles(nIntersections - 1); - glm::vec3 vector1 = glm::normalize(intersections[1] - intersections[0]); - angles[0] = std::pair(1, 0.0f); + const glm::vec3 vec1 = glm::normalize(intersections[1] - intersections[0]); + angles[0] = std::pair(1, 0.f); for (int i = 2; i < nIntersections; i++) { - glm::vec3 vectorI = glm::normalize(intersections[i] - intersections[0]); - float sinA = glm::dot(glm::cross(vector1, vectorI), _normal); - float cosA = glm::dot(vector1, vectorI); + const glm::vec3 vectorI = glm::normalize(intersections[i] - intersections[0]); + const float sinA = glm::dot(glm::cross(vec1, vectorI), _normal); + const float cosA = glm::dot(vec1, vectorI); angles[i - 1] = { i, glm::sign(sinA) * (1.f - cosA) }; } @@ -137,7 +138,7 @@ void BlockPlaneIntersectionGeometry::updateVertices() { _vertices.push_back(intersections[0].z); //_vertices.push_back(_w); for (int i = 0; i < nIntersections - 1; i++) { - int j = angles[i].first; + const int j = angles[i].first; _vertices.push_back(intersections[j].x); _vertices.push_back(intersections[j].y); _vertices.push_back(intersections[j].z); diff --git a/src/util/boxgeometry.cpp b/src/util/boxgeometry.cpp index 6c06e54b89..335eefb264 100644 --- a/src/util/boxgeometry.cpp +++ b/src/util/boxgeometry.cpp @@ -47,27 +47,27 @@ bool BoxGeometry::initialize() { const float y = _size.y * 0.5f; const float z = _size.z * 0.5f; - const GLfloat vertices[] = { + const std::array vertices = { -x, -y, z, // blue corner - x, y, z, // white corner + x, y, z, // white corner -x, y, z, // cyan corner -x, -y, z, // blue corner - x, -y, z, // magenta corner - x, y, z, // white corner + x, -y, z, // magenta corner + x, y, z, // white corner -x, -y, -z, // black corner -x, y, -z, // green - x, y, -z, // yellow corner + x, y, -z, // yellow corner -x, -y, -z, // black - x, y, -z, // yellow - x, -y, -z, // red + x, y, -z, // yellow + x, -y, -z, // red - x, -y, -z, // red - x, y, z, // yellow - x, -y, z, // magenta - x, -y, -z, // red - x, y, -z, // yellow - x, y, z, // white + x, -y, -z, // red + x, y, z, // yellow + x, -y, z, // magenta + x, -y, -z, // red + x, y, -z, // yellow + x, y, z, // white -x, -y, -z, // black -x, -y, z, // blue @@ -76,19 +76,19 @@ bool BoxGeometry::initialize() { -x, y, z, // cyan -x, y, -z, // green - x, y, z, // white + x, y, z, // white -x, y, -z, // green -x, y, z, // cyan -x, y, -z, // green - x, y, z, // white - x, y, -z, // yellow + x, y, z, // white + x, y, -z, // yellow -x, -y, -z, // black - x, -y, z, // magenta + x, -y, z, // magenta -x, -y, z, // blue -x, -y, -z, // black - x, -y, -z, // red - x, -y, z // magenta + x, -y, -z, // red + x, -y, z // magenta }; if (_vaoId == 0) { @@ -97,18 +97,12 @@ bool BoxGeometry::initialize() { if (_vBufferId == 0) { glGenBuffers(1, &_vBufferId); - - if (_vBufferId == 0) { - LERROR("Could not create vertex buffer"); - return false; - } } - // First VAO setup glBindVertexArray(_vaoId); glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 3, nullptr); @@ -117,7 +111,7 @@ bool BoxGeometry::initialize() { return true; } -void BoxGeometry::render() { +void BoxGeometry::render() const { glBindVertexArray(_vaoId); // select first VAO glDrawArrays(GL_TRIANGLES, 0, 6*6); glBindVertexArray(0); diff --git a/src/util/collisionhelper.cpp b/src/util/collisionhelper.cpp index af74c2df77..3e7f727313 100644 --- a/src/util/collisionhelper.cpp +++ b/src/util/collisionhelper.cpp @@ -29,21 +29,21 @@ namespace openspace::collision { // Source: http://paulbourke.net/geometry/circlesphere/raysphere.c -bool lineSphereIntersection(glm::dvec3 p1, glm::dvec3 p2, glm::dvec3 center, - double r, glm::dvec3& intersectionPoint) +bool lineSphereIntersection(const glm::dvec3& p1, const glm::dvec3& p2, + const glm::dvec3& center, double r, + glm::dvec3& intersectionPoint) { - double a, b, c; const glm::dvec3 diffp = p2 - p1; - a = diffp.x * diffp.x + diffp.y * diffp.y + diffp.z * diffp.z; - b = 2.0 * (diffp.x * (p1.x - center.x) + diffp.y * (p1.y - center.y) + + const double a = diffp.x * diffp.x + diffp.y * diffp.y + diffp.z * diffp.z; + const double b = 2.0 * (diffp.x * (p1.x - center.x) + diffp.y * (p1.y - center.y) + diffp.z * (p1.z - center.z)); - c = center.x * center.x + center.y * center.y + center.z * center.z; + double c = center.x * center.x + center.y * center.y + center.z * center.z; c += p1.x * p1.x + p1.y * p1.y + p1.z * p1.z; c -= 2.0 * (center.x * p1.x + center.y * p1.y + center.z * p1.z); c -= r * r; - double intersectionTest = b * b - 4.0 * a * c; + const double intersectionTest = b * b - 4.0 * a * c; // No intersection if (std::abs(a) < 0 || intersectionTest < 0.0) { diff --git a/src/util/coordinateconversion.cpp b/src/util/coordinateconversion.cpp index 0f700060b3..f7638aa095 100644 --- a/src/util/coordinateconversion.cpp +++ b/src/util/coordinateconversion.cpp @@ -42,30 +42,30 @@ namespace { double& seconds) { // Find hms or dms indicies - size_t hOrDIndex = + const size_t hOrDIndex = (str.find('h') != std::string::npos) ? str.find('h') : str.find('d'); - size_t mIndex = str.find('m'); - size_t sIndex = str.find('s'); + const size_t mIndex = str.find('m'); + const size_t sIndex = str.find('s'); if (hOrDIndex == std::string::npos || mIndex == std::string::npos || sIndex == std::string::npos) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra or Dec '{}' format is incorrect. Correct format is: Ra 'XhYmZs', " "and Dec 'XdYmZs'", str )); } // Construct the number strings - std::string sHoursOrDegrees = str.substr(0, hOrDIndex); - std::string sMinutes = str.substr(hOrDIndex + 1, mIndex - hOrDIndex - 1); - std::string sSeconds = str.substr(mIndex + 1, sIndex - mIndex - 1); + const std::string sHoursOrDegrees = str.substr(0, hOrDIndex); + const std::string sMinutes = str.substr(hOrDIndex + 1, mIndex - hOrDIndex - 1); + const std::string sSeconds = str.substr(mIndex + 1, sIndex - mIndex - 1); // Convert the strings to numbers try { // Hours or degrees must be an integer double temp = std::stod(sHoursOrDegrees); if (std::floor(temp) != temp) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra or Dec '{}' format is incorrect. Correct format is: Ra 'XhYmZs', " "and Dec 'XdYmZs', where X must be an integer", str )); @@ -75,7 +75,7 @@ namespace { // Minutes must be an integer temp = std::stod(sMinutes); if (std::floor(temp) != temp) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra or Dec '{}' format is incorrect. Correct format is: Ra 'XhYmZs', " "and Dec 'XdYmZs', where Y must be an integer", str )); @@ -86,7 +86,7 @@ namespace { seconds = std::stod(sSeconds); } catch (const std::invalid_argument&) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra or Dec '{}' format is incorrect. Correct format is: Ra 'XhYmZs', " "and Dec 'XdYmZs'", str )); @@ -95,7 +95,7 @@ namespace { void parseRa(const std::string& ra, int& hours, int& minutes, double& seconds) { if (ra.find('d') != std::string::npos) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra '{}' format is incorrect. Correct format is: 'XhYmZs'", ra )); } @@ -104,7 +104,7 @@ namespace { void parseDec(const std::string& dec, int& degrees, int& minutes, double& seconds) { if (dec.find('h') != std::string::npos) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Dec '{}' format is incorrect. Correct format is: 'XdYmZs'", dec )); } @@ -114,21 +114,21 @@ namespace { bool isRaDecValid(int raH, int raM, double raS, int decD, int decM, double decS) { // Ra if (raH < 0.0 || raH >= 24.0) { - LWARNING(fmt::format( + LWARNING(std::format( "Right ascension hours '{}' is outside the allowed range of 0 to 24 " "hours (exclusive)", raH )); return false; } if (raM < 0.0 || raM >= 60.0) { - LWARNING(fmt::format( + LWARNING(std::format( "Right ascension minutes '{}' is outside the allowed range of 0 to 60 " "minutes (exclusive)", raM )); return false; } if (raS < 0.0 || raS >= 60.0) { - LWARNING(fmt::format( + LWARNING(std::format( "Right ascension seconds '{}' is outside the allowed " "range of 0 to 60 seconds (exclusive)", raS )); @@ -137,7 +137,7 @@ namespace { // Dec if (decD < -90.0 || decD > 90.0) { - LWARNING(fmt::format("Declination degrees '{}' is outside the allowed range " + LWARNING(std::format("Declination degrees '{}' is outside the allowed range " "of -90 to 90 degrees (inclusive)", decD )); return false; @@ -150,14 +150,14 @@ namespace { return false; } if (decM < 0.0 || decM >= 60.0) { - LWARNING(fmt::format( + LWARNING(std::format( "Declination minutes '{}' is outside the allowed range of 0 to 60 " "minutes (exclusive)", decM )); return false; } if (decS < 0.0 || decS >= 60.0) { - LWARNING(fmt::format( + LWARNING(std::format( "Declination seconds '{}' is outside the allowed range of 0 to 60 " "seconds (exclusive)", decS )); @@ -176,21 +176,23 @@ namespace openspace { // https://www.atnf.csiro.au/people/Tobias.Westmeier/tools_coords.php glm::dvec3 icrsToGalacticCartesian(double ra, double dec, double distance) { // (Ra, Dec) -> (a, d) - double a = glm::radians(ra); - double d = glm::radians(dec); + const double a = glm::radians(ra); + const double d = glm::radians(dec); // Convert to galactic reference frame - double l = L0 - atan2( - cos(d) * sin(a - A0), - sin(d) * cos(D0) - cos(d) * sin(D0) * cos(a - A0) + const double l = L0 - std::atan2( + std::cos(d) * std::sin(a - A0), + std::sin(d) * std::cos(D0) - std::cos(d) * std::sin(D0) * std::cos(a - A0) + ); + const double b = std::asin( + std::sin(d) * std::sin(D0) + std::cos(d) * std::cos(D0) * std::cos(a - A0) ); - double b = asin(sin(d) * sin(D0) + cos(d) * cos(D0) * cos(a - A0)); // Convert to cartesian - glm::dvec3 rGalactic = glm::dvec3( - cos(b) * cos(l), - cos(b) * sin(l), - sin(b) + const glm::dvec3 rGalactic = glm::dvec3( + std::cos(b) * std::cos(l), + std::cos(b) * std::sin(l), + std::sin(b) ); return distance * rGalactic; @@ -204,20 +206,22 @@ glm::dvec3 icrsToGalacticCartesian(double ra, double dec, double distance) { // coordinates-of-stars glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) { if (ra.size() < 6 || dec.size() < 6) { - throw ghoul::lua::LuaRuntimeException(fmt::format( + throw ghoul::lua::LuaRuntimeException(std::format( "Ra '{}' or Dec '{}' format is incorrect. Correct format is: Ra 'XhYmZs', " "and Dec 'XdYmZs'", ra, dec )); } // Parse right ascension - int raHours, raMinutes; - double raSeconds; + int raHours = 0; + int raMinutes = 0; + double raSeconds = 0.0; parseRa(ra, raHours, raMinutes, raSeconds); // Parse declination - int decDegrees, decMinutes; - double decSeconds; + int decDegrees = 0; + int decMinutes = 0; + double decSeconds = 0.0; parseDec(dec, decDegrees, decMinutes, decSeconds); const bool isValid = isRaDecValid(raHours, @@ -229,19 +233,19 @@ glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) { ); if (!isValid) { - LWARNING(fmt::format( + LWARNING(std::format( "Ra '{}' or Dec '{}' is outside the allowed range, result may be incorrect", ra, dec )); } // Convert from hours/degrees, minutes, seconds to decimal degrees - double sign = std::signbit(static_cast(decDegrees)) ? -1.0 : 1.0; - double raDeg = (raHours * 15.0) + + const double sign = std::signbit(static_cast(decDegrees)) ? -1.0 : 1.0; + const double raDeg = (raHours * 15.0) + (raMinutes * 15.0 / 60.0) + (raSeconds * 15.0 / 3600.0); - double decDeg = (abs(decDegrees) + + const double decDeg = (std::abs(decDegrees) + (decMinutes / 60.0) + (decSeconds / 3600.0)) * sign; @@ -255,22 +259,24 @@ glm::dvec2 icrsToDecimalDegrees(const std::string& ra, const std::string& dec) { // https://en.wikipedia.org/wiki/Celestial_coordinate_system glm::dvec3 galacticCartesianToIcrs(double x, double y, double z) { // Normalize - double distance = sqrt(x*x + y*y + z*z); - double nX = x / distance; - double nY = y / distance; - double nZ = z / distance; + const double distance = std::sqrt(x*x + y*y + z*z); + double const nX = x / distance; + const double nY = y / distance; + const double nZ = z / distance; // Convert from cartesian // (x, y, z) -> (l, b) - double l = atan2(nY, nX); - double b = asin(nZ); + const double l = std::atan2(nY, nX); + const double b = std::asin(nZ); // Convert to equatorial reference frame - double a = atan2( - cos(b) * sin(L0 - l), - sin(b) * cos(D0) - cos(b) * sin(D0) * cos(L0 - l) + const double a = std::atan2( + std::cos(b) * std::sin(L0 - l), + std::sin(b) * std::cos(D0) - std::cos(b) * std::sin(D0) * std::cos(L0 - l) ) + A0; - double d = asin(sin(b) * sin(D0) + cos(b) * cos(D0) * cos(L0 - l)); + const double d = std::asin( + std::sin(b) * std::sin(D0) + std::cos(b) * std::cos(D0) * std::cos(L0 - l) + ); return glm::dvec3(glm::degrees(a), glm::degrees(d), distance); } @@ -281,29 +287,25 @@ glm::dvec3 galacticCartesianToIcrs(double x, double y, double z) { // https://math.stackexchange.com/questions/15323/how-do-i-calculate-the-cartesian- // coordinates-of-stars std::pair decimalDegreesToIcrs(double ra, double dec) { - // Radians to degrees - double raDeg = ra; - double decDeg = dec; - // Check input - if (raDeg < 0 || raDeg > 360 || decDeg < -90 || decDeg > 90) { - LWARNING(fmt::format( + if (ra < 0.0 || ra > 360.0 || dec < -90.0 || dec > 90.0) { + LWARNING(std::format( "Ra '{}' or Dec '{}' is outside the allowed range, result may be incorrect", ra, dec )); } // Calculate Ra - int raHours = static_cast(std::trunc(raDeg) / 15.0); - double raMinutesFull = (raDeg - raHours * 15.0) * 60.0 / 15.0; - int raMinutes = static_cast(std::trunc(raMinutesFull)); - double raSeconds = (raMinutesFull - raMinutes) * 60.0; + const int raHours = static_cast(std::trunc(ra) / 15.0); + const double raMinutesFull = (ra - raHours * 15.0) * 60.0 / 15.0; + const int raMinutes = static_cast(std::trunc(raMinutesFull)); + const double raSeconds = (raMinutesFull - raMinutes) * 60.0; // Calculate Dec - int decDegrees = static_cast(std::trunc(decDeg)); - double decMinutesFull = (std::abs(decDeg) - std::abs(decDegrees)) * 60.0; - int decMinutes = static_cast(std::trunc(decMinutesFull)); - double decSeconds = (decMinutesFull - decMinutes) * 60.0; + const int decDegrees = static_cast(std::trunc(dec)); + const double decMinutesFull = (std::abs(dec) - std::abs(decDegrees)) * 60.0; + const int decMinutes = static_cast(std::trunc(decMinutesFull)); + const double decSeconds = (decMinutesFull - decMinutes) * 60.0; // Construct strings std::pair result; @@ -325,7 +327,7 @@ std::pair decimalDegreesToIcrs(double ra, double dec) ); if (!isValid) { - LWARNING(fmt::format( + LWARNING(std::format( "Resulting Ra '{}' or Dec '{}' is outside the allowed range, result may be " "incorrect", result.first, result.second )); diff --git a/src/util/distanceconversion.cpp b/src/util/distanceconversion.cpp index 31eb085530..0767890fa9 100644 --- a/src/util/distanceconversion.cpp +++ b/src/util/distanceconversion.cpp @@ -99,11 +99,11 @@ std::pair simplifyDistance(double meters, } float convertMasPerYearToMeterPerSecond(float masPerYear, float parallax) { - double degreeFromMas = 1.0 / 3600000.0; - double radiusInMeter = (distanceconstants::Parsec * 1000.0) / parallax; - double perYearToPerSecond = 1.0 / SecondsPerYear; - double meterPerSecond = masPerYear * degreeFromMas * radiusInMeter * - perYearToPerSecond; + const double degreeFromMas = 1.0 / 3600000.0; + const double radiusInMeter = (distanceconstants::Parsec * 1000.0) / parallax; + const double perYearToPerSecond = 1.0 / SecondsPerYear; + const double meterPerSecond = + masPerYear * degreeFromMas * radiusInMeter * perYearToPerSecond; return static_cast(meterPerSecond); } diff --git a/src/util/histogram.cpp b/src/util/histogram.cpp index 762c944be8..3f96709933 100644 --- a/src/util/histogram.cpp +++ b/src/util/histogram.cpp @@ -42,7 +42,7 @@ Histogram::Histogram(float minValue, float maxValue, int numBins, float* data) { if (!data) { _data = new float[numBins]; - for (int i = 0; i < numBins; ++i) { + for (int i = 0; i < numBins; i++) { _data[i] = 0.0; } } @@ -76,7 +76,7 @@ bool Histogram::add(float value, float repeat) { const float normalizedValue = (value - _minValue) / (_maxValue - _minValue); const int binIndex = static_cast(std::min( - static_cast(floor(normalizedValue * _numBins)), + static_cast(std::floor(normalizedValue * _numBins)), _numBins - 1.f )); // [0, _numBins - 1] @@ -92,16 +92,16 @@ void Histogram::changeRange(float minValue, float maxValue){ } float* oldData = _data; - float oldMin = _minValue; - float oldMax = _maxValue; + const float oldMin = _minValue; + const float oldMax = _maxValue; float* newData = new float[_numBins]{0.0}; for(int i=0; i<_numBins; i++){ - float unNormalizedValue = i*(oldMax-oldMin)+oldMin; - float normalizedValue = (unNormalizedValue - _minValue) / - (_maxValue - _minValue); // [0.0, 1.0] - int binIndex = static_cast(std::min( - static_cast(floor(normalizedValue * _numBins)), + const float unNormalizedValue = i * (oldMax - oldMin) + oldMin; + const float normalizedValue = (unNormalizedValue - _minValue) / + (_maxValue - _minValue); // [0.0, 1.0] + const int binIndex = static_cast(std::min( + static_cast(std::floor(normalizedValue * _numBins)), _numBins - 1.f )); // [0, _numBins - 1] @@ -153,8 +153,8 @@ bool Histogram::addRectangle(float lowBin, float highBin, float value) { const float lowBinIndex = normalizedLowBin * _numBins; const float highBinIndex = normalizedHighBin * _numBins; - const int fillLow = static_cast(floor(lowBinIndex)); - const int fillHigh = static_cast(ceil(highBinIndex)); + const int fillLow = static_cast(std::floor(lowBinIndex)); + const int fillHigh = static_cast(std::ceil(highBinIndex)); for (int i = fillLow; i < fillHigh; i++) { _data[i] += value; @@ -176,9 +176,9 @@ float Histogram::interpolate(float bin) const { const float normalizedBin = (bin - _minValue) / (_maxValue - _minValue); const float binIndex = normalizedBin * _numBins - 0.5f; // Center - const float interpolator = binIndex - floor(binIndex); - int binLow = static_cast(floor(binIndex)); - int binHigh = static_cast(ceil(binIndex)); + const float interpolator = binIndex - std::floor(binIndex); + int binLow = static_cast(std::floor(binIndex)); + int binHigh = static_cast(std::ceil(binIndex)); // Clamp bins if (binLow < 0) { @@ -222,11 +222,11 @@ void Histogram::normalize() { * value will be the value at the index. */ void Histogram::generateEqualizer() { - float previousCdf = 0.0f; - _equalizer = std::vector(_numBins, 0.0f); + float previousCdf = 0.f; + _equalizer = std::vector(_numBins, 0.f); for (int i = 0; i < _numBins; i++) { const float probability = _data[i] / static_cast(_numValues); - const float cdf = std::min(1.0f, previousCdf + probability); + const float cdf = std::min(1.f, previousCdf + probability); _equalizer[i] = cdf * (_numBins-1); previousCdf = cdf; } @@ -257,8 +257,8 @@ float Histogram::equalize(float value) const { // " val: " + std::to_string(value) // ); // } - float normalizedValue = (value-_minValue)/(_maxValue-_minValue); - int bin = static_cast(floor(normalizedValue * _numBins)); + const float normalizedValue = (value - _minValue) / (_maxValue - _minValue); + int bin = static_cast(std::floor(normalizedValue * _numBins)); // If value == _maxValues then bin == _numBins, which is a invalid index. bin = std::min(_numBins-1, bin); bin = std::max(0, bin); @@ -268,10 +268,10 @@ float Histogram::equalize(float value) const { float Histogram::entropy() { float entropy = 0.f; - for (int i = 0; i < _numBins; ++i) { + for (int i = 0; i < _numBins; i++) { if (_data[i] != 0) { entropy -= (_data[i] / static_cast(_numValues)) * - (log2(_data[i]) / static_cast(_numValues)); + (std::log2(_data[i]) / static_cast(_numValues)); } } return entropy; @@ -326,9 +326,9 @@ float Histogram::highestBinValue(bool equalized, int overBins){ if (!equalized) { - float low = _minValue + static_cast(highestBin) / - _numBins * (_maxValue - _minValue); - float high = low + (_maxValue - _minValue) / static_cast(_numBins); + const float low = _minValue + static_cast(highestBin) / + _numBins * (_maxValue - _minValue); + const float high = low + (_maxValue - _minValue) / static_cast(_numBins); return (high+low) / 2.f; } else { @@ -337,7 +337,7 @@ float Histogram::highestBinValue(bool equalized, int overBins){ } } -float Histogram::binWidth() { +float Histogram::binWidth() const { return (_maxValue - _minValue) / _numBins; } diff --git a/src/util/httprequest.cpp b/src/util/httprequest.cpp index 263120b8ff..6861cca777 100644 --- a/src/util/httprequest.cpp +++ b/src/util/httprequest.cpp @@ -72,7 +72,8 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) { CURLOPT_HEADERFUNCTION, +[](char* ptr, size_t size, size_t nmemb, void* userData) { HttpRequest* r = reinterpret_cast(userData); - bool shouldContinue = r->_onHeader ? r->_onHeader(ptr, size * nmemb) : true; + const bool shouldContinue = + r->_onHeader ? r->_onHeader(ptr, size * nmemb) : true; return shouldContinue ? size * nmemb : 0; } ); @@ -83,7 +84,7 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) { CURLOPT_WRITEFUNCTION, +[](char* ptr, size_t size, size_t nmemb, void* userData) { HttpRequest* r = reinterpret_cast(userData); - bool shouldContinue = r->_onData ? r->_onData(ptr, size * nmemb) : true; + const bool shouldContinue = r->_onData ? r->_onData(ptr, size * nmemb) : true; return shouldContinue ? size * nmemb : 0; } ); @@ -103,7 +104,8 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) { totalBytes = nTotalDownloadBytes; } - bool shouldContinue = r->_onProgress ? + const bool shouldContinue = + r->_onProgress ? r->_onProgress(nDownloadedBytes, totalBytes) : true; return shouldContinue ? 0 : 1; @@ -112,16 +114,16 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) { curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, static_cast(timeout.count())); - CURLcode res = curl_easy_perform(curl); + const CURLcode res = curl_easy_perform(curl); bool success = false; if (res == CURLE_OK) { - long responseCode; + long responseCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responseCode); if (responseCode >= 400) { LERRORC( "HttpRequest", - fmt::format("Failed download {} with code {}", _url, responseCode) + std::format("Failed download '{}' with code {}", _url, responseCode) ); success = false; } @@ -132,8 +134,8 @@ bool HttpRequest::perform(std::chrono::milliseconds timeout) { else { LERRORC( "HttpRequest", - fmt::format( - "Failed download {} with error {}", _url, curl_easy_strerror(res) + std::format( + "Failed download '{}' with error {}", _url, curl_easy_strerror(res) ) ); } @@ -156,8 +158,8 @@ HttpDownload::HttpDownload(std::string url) }); _httpRequest.onProgress( - [this](int64_t downloadedBytes, std::optional totalBytes) { - bool cont = _onProgress ? _onProgress(downloadedBytes, totalBytes) : true; + [this](int64_t nDownloaded, std::optional nTotal) { + const bool cont =_onProgress ? _onProgress(nDownloaded, nTotal) : true; return cont && !_shouldCancel; } ); @@ -187,7 +189,7 @@ void HttpDownload::start(std::chrono::milliseconds timeout) { _isDownloading = true; _downloadThread = std::thread([this, timeout]() { _isFinished = false; - LTRACEC("HttpDownload", fmt::format("Start download '{}'", _httpRequest.url())); + LTRACEC("HttpDownload", std::format("Start download '{}'", _httpRequest.url())); const bool setupSuccess = setup(); if (setupSuccess) { @@ -204,13 +206,13 @@ void HttpDownload::start(std::chrono::milliseconds timeout) { if (_isSuccessful) { LTRACEC( "HttpDownload", - fmt::format("Finished async download '{}'", _httpRequest.url()) + std::format("Finished async download '{}'", _httpRequest.url()) ); } else { LTRACEC( "HttpDownload", - fmt::format("Failed async download '{}'", _httpRequest.url()) + std::format("Failed async download '{}'", _httpRequest.url()) ); } @@ -256,14 +258,14 @@ HttpFileDownload::HttpFileDownload(std::string url, std::filesystem::path destin , _destination(std::move(destination)) { if (!overwrite && std::filesystem::is_regular_file(_destination)) { - throw ghoul::RuntimeError(fmt::format("File {} already exists", _destination)); + throw ghoul::RuntimeError(std::format("File '{}' already exists", _destination)); } } bool HttpFileDownload::setup() { { - std::lock_guard g(_directoryCreationMutex); - std::filesystem::path d = _destination.parent_path(); + const std::lock_guard g(_directoryCreationMutex); + const std::filesystem::path d = _destination.parent_path(); if (!std::filesystem::is_directory(d)) { std::filesystem::create_directories(d); } @@ -286,7 +288,7 @@ bool HttpFileDownload::setup() { // GetLastError() gives more details than errno. DWORD errorId = GetLastError(); if (errorId == 0) { - LERRORC("HttpFileDownload", fmt::format("Cannot open file {}", _destination)); + LERRORC("HttpFileDownload", std::format("Cannot open file '{}'", _destination)); return false; } std::array Buffer; @@ -304,25 +306,26 @@ bool HttpFileDownload::setup() { std::string message(Buffer.data(), size); LERRORC( "HttpFileDownload", - fmt::format("Cannot open file {}: {}", _destination, message) + std::format("Cannot open file '{}': {}", _destination, message) ); return false; #else // ^^^ WIN32 / !WIN32 vvv if (errno) { #ifdef __unix__ - char buffer[256]; + std::array buffer; LERRORC( "HttpFileDownload", - fmt::format( + std::format( "Cannot open file '{}': {}", - _destination, std::string(strerror_r(errno, buffer, sizeof(buffer))) + _destination, + std::string(strerror_r(errno, buffer.data(), sizeof(buffer))) ) ); return false; #else // ^^^ __unix__ / !__unix__ vvv LERRORC( "HttpFileDownload", - fmt::format( + std::format( "Cannot open file '{}': {}", _destination, std::string(strerror(errno)) ) ); @@ -330,7 +333,7 @@ bool HttpFileDownload::setup() { #endif // __unix__ } - LERRORC("HttpFileDownload", fmt::format("Cannot open file {}", _destination)); + LERRORC("HttpFileDownload", std::format("Cannot open file '{}'", _destination)); return false; #endif // WIN32 } diff --git a/src/util/json_helper.cpp b/src/util/json_helper.cpp index 8515ab0a04..4d32fb52b3 100644 --- a/src/util/json_helper.cpp +++ b/src/util/json_helper.cpp @@ -91,8 +91,8 @@ void sortJson(nlohmann::json& json, const std::string& key) { json.begin(), json.end(), [&key](const nlohmann::json& lhs, const nlohmann::json& rhs) { - std::string lhsString = ghoul::toLowerCase(lhs[key]); - std::string rhsString = ghoul::toLowerCase(rhs[key]); + const std::string lhsString = ghoul::toLowerCase(lhs[key]); + const std::string rhsString = ghoul::toLowerCase(rhs[key]); return rhsString > lhsString; } @@ -116,7 +116,7 @@ ghoul::Dictionary jsonToDictionary(const nlohmann::json& json) { break; case nlohmann::json::value_t::object: { ghoul::Dictionary subDict = jsonToDictionary(j); - dict.setValue(key, std::move(subDict)); + dict.setValue(std::move(key), std::move(subDict)); break; } case nlohmann::json::value_t::array: { @@ -126,21 +126,21 @@ ghoul::Dictionary jsonToDictionary(const nlohmann::json& json) { for (int i = 0; i < j.size(); i++) { const nlohmann::json& value = j[i]; // We add 1 to the key to make Lua happy :-/ - addToDict(subDict, fmt::format("{}", i + 1), value); + addToDict(subDict, std::format("{}", i + 1), value); } - dict.setValue(key, std::move(subDict)); + dict.setValue(std::move(key), std::move(subDict)); break; } case nlohmann::json::value_t::string: - dict.setValue(key, j.get()); + dict.setValue(std::move(key), j.get()); break; case nlohmann::json::value_t::boolean: - dict.setValue(key, j.get()); + dict.setValue(std::move(key), j.get()); break; case nlohmann::json::value_t::number_integer: case nlohmann::json::value_t::number_unsigned: case nlohmann::json::value_t::number_float: - dict.setValue(key, j.get()); + dict.setValue(std::move(key), j.get()); break; case nlohmann::json::value_t::binary: throw ghoul::RuntimeError( diff --git a/src/util/keys.cpp b/src/util/keys.cpp index 1e97dcce4a..52dbfda6f7 100644 --- a/src/util/keys.cpp +++ b/src/util/keys.cpp @@ -34,7 +34,7 @@ namespace openspace { -KeyWithModifier stringToKey(std::string str) { +KeyWithModifier stringToKey(const std::string& str) { std::vector tokens = ghoul::tokenizeString(str, '+'); // "Keypad +" will tokenize into "Keypad " + "" if (tokens.size() == 2 && tokens[0] == "Keypad " && tokens[1].empty()) { @@ -49,7 +49,7 @@ KeyWithModifier stringToKey(std::string str) { // default is unknown Key key = Key::Unknown; std::string keyName = tokens.back(); - std::string keyNameOriginal = originalTokens.back(); + const std::string keyNameOriginal = originalTokens.back(); for (const KeyInfo& ki : KeyInfos) { if (ki.identifier == keyName || ki.name == keyName || ki.identifier == keyNameOriginal || ki.name == keyNameOriginal) @@ -59,7 +59,7 @@ KeyWithModifier stringToKey(std::string str) { } } if (key == Key::Unknown) { - throw ghoul::RuntimeError(fmt::format("Could not find key for '{}'", keyName)); + throw ghoul::RuntimeError(std::format("Could not find key for '{}'", keyName)); } KeyModifier m = KeyModifier::None; @@ -77,7 +77,7 @@ KeyWithModifier stringToKey(std::string str) { } } if (!found) { - throw ghoul::RuntimeError(fmt::format("Unknown modifier key '{}'", s)); + throw ghoul::RuntimeError(std::format("Unknown modifier key '{}'", s)); } } ); @@ -98,7 +98,7 @@ std::string keyToString(KeyWithModifier keyWithModifier) { // checks internally against != 0 if (hasKeyModifier(keyWithModifier.modifier, kmi.modifier)) { - modifier += fmt::format("{}+", kmi.identifier); + modifier += std::format("{}+", kmi.identifier); } } } @@ -120,9 +120,9 @@ std::string keyToString(KeyWithModifier keyWithModifier) { namespace ghoul { template <> -std::string to_string(const openspace::Key& key) { +std::string to_string(const openspace::Key& value) { for (const openspace::KeyInfo& ki : openspace::KeyInfos) { - if (ki.key == key) { + if (ki.key == value) { return std::string(ki.name); } } @@ -131,21 +131,21 @@ std::string to_string(const openspace::Key& key) { } template <> -std::string to_string(const openspace::KeyModifier& mod) { +std::string to_string(const openspace::KeyModifier& value) { using namespace openspace; - if (mod == KeyModifier::None) { + if (value == KeyModifier::None) { return ""; } std::string result; - for (const openspace::KeyModifierInfo& kmi : openspace::KeyModifierInfos) { + for (const KeyModifierInfo& kmi : KeyModifierInfos) { // No need for an extra check for the empty modifier since that is mapped to 0, // meaning that the `hasKeyModifier` will always fail for it since it checks // internally against != 0 - if (hasKeyModifier(mod, kmi.modifier)) { - result += fmt::format("{}+", kmi.name); + if (hasKeyModifier(value, kmi.modifier)) { + result += std::format("{}+", kmi.name); } } @@ -156,12 +156,12 @@ std::string to_string(const openspace::KeyModifier& mod) { } template <> -std::string to_string(const openspace::KeyWithModifier& key) { - if (key.modifier == openspace::KeyModifier::None) { - return to_string(key.key); +std::string to_string(const openspace::KeyWithModifier& value) { + if (value.modifier == openspace::KeyModifier::None) { + return to_string(value.key); } else { - return fmt::format("{}+{}", to_string(key.modifier), to_string(key.key)); + return std::format("{}+{}", to_string(value.modifier), to_string(value.key)); } } diff --git a/src/util/openspacemodule.cpp b/src/util/openspacemodule.cpp index 771a9b82bb..ab736d235e 100644 --- a/src/util/openspacemodule.cpp +++ b/src/util/openspacemodule.cpp @@ -50,14 +50,14 @@ void OpenSpaceModule::initialize(const ghoul::Dictionary& configuration) { ZoneScoped; ZoneName(identifier().c_str(), identifier().size()); - std::string upperIdentifier = ghoul::toUpperCase(identifier()); + const std::string upperIdentifier = ghoul::toUpperCase(identifier()); std::string moduleToken = "${" + std::string(ModuleBaseToken) + upperIdentifier + "}"; std::filesystem::path path = modulePath(); if (!path.empty()) { - LDEBUG(fmt::format("Registering module path {}: {}", moduleToken, path)); - FileSys.registerPathToken(moduleToken, std::move(path)); + LDEBUG(std::format("Registering module path '{}' -> {}", moduleToken, path)); + FileSys.registerPathToken(std::move(moduleToken), std::move(path)); } internalInitialize(configuration); @@ -105,10 +105,10 @@ std::vector OpenSpaceModule::requiredOpenGLExtensions() const { } std::filesystem::path OpenSpaceModule::modulePath() const { - std::string moduleIdentifier = ghoul::toLowerCase(identifier()); + const std::string moduleIdentifier = ghoul::toLowerCase(identifier()); // First try the internal module directory - std::filesystem::path path = absPath("${MODULES}/" + moduleIdentifier); + const std::filesystem::path path = absPath("${MODULES}/" + moduleIdentifier); return std::filesystem::is_directory(path) ? path : ""; } diff --git a/src/util/planegeometry.cpp b/src/util/planegeometry.cpp index fa139d54be..5212c7bbe3 100644 --- a/src/util/planegeometry.cpp +++ b/src/util/planegeometry.cpp @@ -53,7 +53,7 @@ void PlaneGeometry::deinitialize() { _vBufferId = 0; } -void PlaneGeometry::render() { +void PlaneGeometry::render() const { glBindVertexArray(_vaoId); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); @@ -77,18 +77,18 @@ void PlaneGeometry::updateGeometry() { GLfloat t; }; - VertexData vertices[] = { - { -size.x, -size.y, 0.f, 0.f }, - { size.x, size.y, 1.f, 1.f }, - { -size.x, size.y, 0.f, 1.f }, - { -size.x, -size.y, 0.f, 0.f }, - { size.x, -size.y, 1.f, 0.f }, - { size.x, size.y, 1.f, 1.f } + const std::array vertices = { + VertexData{ -size.x, -size.y, 0.f, 0.f }, + VertexData{ size.x, size.y, 1.f, 1.f }, + VertexData{ -size.x, size.y, 0.f, 1.f }, + VertexData{ -size.x, -size.y, 0.f, 0.f }, + VertexData{ size.x, -size.y, 1.f, 0.f }, + VertexData{ size.x, size.y, 1.f, 1.f } }; glBindVertexArray(_vaoId); glBindBuffer(GL_ARRAY_BUFFER, _vBufferId); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(VertexData), nullptr); glEnableVertexAttribArray(1); diff --git a/src/util/progressbar.cpp b/src/util/progressbar.cpp index eb8c84f639..b078b9f957 100644 --- a/src/util/progressbar.cpp +++ b/src/util/progressbar.cpp @@ -42,7 +42,7 @@ ProgressBar::~ProgressBar() { void ProgressBar::print(int current) { const float progress = static_cast(current) / static_cast(_end); - const int iprogress = static_cast(progress * 100.0f); + const int iprogress = static_cast(progress * 100.f); if (iprogress != _previous) { const int pos = static_cast(static_cast(_width)* progress); const int eqWidth = pos + 1; diff --git a/src/util/screenlog.cpp b/src/util/screenlog.cpp index a5a24aff49..ba70dba597 100644 --- a/src/util/screenlog.cpp +++ b/src/util/screenlog.cpp @@ -29,14 +29,14 @@ namespace openspace { ScreenLog::ScreenLog(std::chrono::seconds timeToLive, LogLevel logLevel) - : _timeToLive(std::move(timeToLive)) + : _timeToLive(timeToLive) , _logLevel(logLevel) { _entries.reserve(64); } void ScreenLog::removeExpiredEntries() { - std::lock_guard guard(_mutex); + const std::lock_guard guard(_mutex); const auto t = std::chrono::steady_clock::now(); const auto rit = std::remove_if( @@ -49,7 +49,7 @@ void ScreenLog::removeExpiredEntries() { } void ScreenLog::log(LogLevel level, std::string_view category, std::string_view message) { - std::lock_guard guard(_mutex); + const std::lock_guard guard(_mutex); if (level >= _logLevel) { _entries.push_back({ level, diff --git a/src/util/sphere.cpp b/src/util/sphere.cpp index 882c734615..224708684f 100644 --- a/src/util/sphere.cpp +++ b/src/util/sphere.cpp @@ -61,9 +61,10 @@ Sphere::Sphere(glm::vec3 radius, int segments) // Spherical coordinates based on ISO standard. // https://en.wikipedia.org/wiki/Spherical_coordinate_system - const float x = radius[0] * sin(theta) * cos(phi); - const float y = radius[1] * sin(theta) * sin(phi); - const float z = radius[2] * cos(theta); // Z points towards pole (theta = 0) + // Z points towards pole (theta = 0) + const float x = radius[0] * std::sin(theta) * std::cos(phi); + const float y = radius[1] * std::sin(theta) * std::sin(phi); + const float z = radius[2] * std::cos(theta); _varray[nr].location[0] = x; _varray[nr].location[1] = y; @@ -71,7 +72,7 @@ Sphere::Sphere(glm::vec3 radius, int segments) _varray[nr].location[3] = 0.0; glm::vec3 normal = glm::vec3(x, y, z); - if (!(x == 0.f && y == 0.f && z == 0.f)) { + if (x != 0.f || y != 0.f || z != 0.f) { normal = glm::vec3(glm::normalize(glm::dvec3(normal))); } @@ -90,8 +91,8 @@ Sphere::Sphere(glm::vec3 radius, int segments) nr = 0; // define indices for all triangles - for (int i = 1; i <= segments; ++i) { - for (int j = 0; j < segments; ++j) { + for (int i = 1; i <= segments; i++) { + for (int j = 0; j < segments; j++) { const int t = segments + 1; _iarray[nr] = t * (i - 1) + j + 0; //1 ++nr; @@ -197,8 +198,8 @@ bool Sphere::initialize() { return true; } -void Sphere::render() { - glBindVertexArray(_vaoID); // select first VAO +void Sphere::render() const { + glBindVertexArray(_vaoID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _iBufferID); glDrawElements(GL_TRIANGLES, _isize, GL_UNSIGNED_INT, nullptr); glBindVertexArray(0); diff --git a/src/util/spicemanager.cpp b/src/util/spicemanager.cpp index 454b263ffe..b1766b6f44 100644 --- a/src/util/spicemanager.cpp +++ b/src/util/spicemanager.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include #include @@ -34,6 +33,7 @@ #include #include #include +#include #include "SpiceUsr.h" #include "SpiceZpr.h" @@ -100,7 +100,7 @@ SpiceManager::AberrationCorrection::AberrationCorrection(const std::string& iden auto it = Mapping.find(identifier); ghoul_assert(!identifier.empty(), "Identifier may not be empty"); - ghoul_assert(it != Mapping.end(), fmt::format("Invalid identifer '{}'", identifier)); + ghoul_assert(it != Mapping.end(), std::format("Invalid identifer '{}'", identifier)); type = it->second.first; direction = it->second.second; @@ -150,12 +150,22 @@ SpiceManager::TerminatorType SpiceManager::terminatorTypeFromString( } SpiceManager::SpiceManager() { + // The third parameter for the erract_c function is a SpiceChar*, not ConstSpiceChar* + // so we have to do this weird memory copying trick + std::array buffer; + // Set the SPICE library to not exit the program if an error occurs - erract_c("SET", 0, const_cast("REPORT")); + std::memset(buffer.data(), 0, buffer.size()); + std::strcpy(buffer.data(), "REPORT"); + erract_c("SET", 0, buffer.data()); + // But we do not want SPICE to print the errors, we will fetch them ourselves - errprt_c("SET", 0, const_cast("NONE")); + std::memset(buffer.data(), 0, buffer.size()); + std::strcpy(buffer.data(), "NONE"); + errprt_c("SET", 0, buffer.data()); loadLeapSecondsSpiceKernel(); + loadGeophysicalConstantsKernel(); } SpiceManager::~SpiceManager() { @@ -193,8 +203,9 @@ SpiceManager& SpiceManager::ref() { // If an error occurred, true is returned, otherwise, false void throwSpiceError(const std::string& errorMessage) { if (openspace::SpiceManager::ref().exceptionHandling()) { - char buffer[SpiceErrorBufferSize]; - getmsg_c("LONG", SpiceErrorBufferSize, buffer); + std::string buffer; + buffer.resize(SpiceErrorBufferSize); + getmsg_c("LONG", SpiceErrorBufferSize, buffer.data()); reset_c(); throw openspace::SpiceManager::SpiceException(errorMessage + ": " + buffer); } @@ -207,17 +218,17 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) { ghoul_assert(!filePath.empty(), "Empty file path"); ghoul_assert( std::filesystem::is_regular_file(filePath), - fmt::format("File '{}' ({}) does not exist", filePath, absPath(filePath)) + std::format("File '{}' ({}) does not exist", filePath, absPath(filePath)) ); ghoul_assert( std::filesystem::is_directory(std::filesystem::path(filePath).parent_path()), - fmt::format( - "File {} exists, but directory {} does not", + std::format( + "File '{}' exists, but directory '{}' does not", absPath(filePath), std::filesystem::path(filePath).parent_path() ) ); - std::filesystem::path path = absPath(std::move(filePath)); + const std::filesystem::path path = absPath(std::move(filePath)); const auto it = std::find_if( _loadedKernels.begin(), _loadedKernels.end(), @@ -232,12 +243,12 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) { // We need to set the current directory as meta-kernels are usually defined relative // to the directory they reside in. The directory change is not necessary for regular // kernels - std::filesystem::path currentDirectory = std::filesystem::current_path(); + const std::filesystem::path currentDirectory = std::filesystem::current_path(); - std::filesystem::path p = path.parent_path(); + const std::filesystem::path p = path.parent_path(); std::filesystem::current_path(p); - LINFO(fmt::format("Loading SPICE kernel {}", path)); + LINFO(std::format("Loading SPICE kernel '{}'", path)); // Load the kernel furnsh_c(path.string().c_str()); @@ -248,7 +259,7 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) { throwSpiceError("Kernel loading"); } - std::filesystem::path fileExtension = path.extension(); + const std::filesystem::path fileExtension = path.extension(); if (fileExtension == ".bc" || fileExtension == ".BC") { findCkCoverage(path.string()); // binary ck kernel } @@ -256,8 +267,8 @@ SpiceManager::KernelHandle SpiceManager::loadKernel(std::string filePath) { findSpkCoverage(path.string()); // binary spk kernel } - KernelHandle kernelId = ++_lastAssignedKernel; - ghoul_assert(kernelId != 0, fmt::format("Kernel Handle wrapped around to 0")); + const KernelHandle kernelId = ++_lastAssignedKernel; + ghoul_assert(kernelId != 0, "Kernel Handle wrapped around to 0"); _loadedKernels.push_back({ path.string(), kernelId, 1 }); return kernelId; } @@ -276,14 +287,14 @@ void SpiceManager::unloadKernel(KernelHandle kernelId) { // If there was only one part interested in the kernel, we can unload it if (it->refCount == 1) { // No need to check for errors as we do not allow empty path names - LINFO(fmt::format("Unloading SPICE kernel {}", it->path)); + LINFO(std::format("Unloading SPICE kernel '{}'", it->path)); unload_c(it->path.c_str()); _loadedKernels.erase(it); } // Otherwise, we hold on to it, but reduce the reference counter by 1 else { it->refCount--; - LDEBUG(fmt::format("Reducing reference counter to: {}", it->refCount)); + LDEBUG(std::format("Reducing reference counter to: {}", it->refCount)); } } } @@ -291,7 +302,7 @@ void SpiceManager::unloadKernel(KernelHandle kernelId) { void SpiceManager::unloadKernel(std::string filePath) { ghoul_assert(!filePath.empty(), "Empty filename"); - std::filesystem::path path = absPath(std::move(filePath)); + const std::filesystem::path path = absPath(std::move(filePath)); const auto it = std::find_if( _loadedKernels.begin(), @@ -302,7 +313,7 @@ void SpiceManager::unloadKernel(std::string filePath) { if (it == _loadedKernels.end()) { if (_useExceptions) { throw SpiceException( - fmt::format("{} did not correspond to a loaded kernel", path) + std::format("'{}' did not correspond to a loaded kernel", path) ); } else { @@ -312,14 +323,14 @@ void SpiceManager::unloadKernel(std::string filePath) { else { // If there was only one part interested in the kernel, we can unload it if (it->refCount == 1) { - LINFO(fmt::format("Unloading SPICE kernel {}", path)); + LINFO(std::format("Unloading SPICE kernel '{}'", path)); unload_c(path.string().c_str()); _loadedKernels.erase(it); } else { // Otherwise, we hold on to it, but reduce the reference counter by 1 it->refCount--; - LDEBUG(fmt::format("Reducing reference counter to: {}", it->refCount)); + LDEBUG(std::format("Reducing reference counter to: {}", it->refCount)); } } } @@ -415,8 +426,7 @@ std::vector> SpiceManager::spiceBodies( { std::vector> bodies; - constexpr int Frnmln = 33; - static SpiceInt idsetBuffer[SPICE_CELL_CTRLSZ + 8192]; + static std::array idsetBuffer; static SpiceCell idset = { SPICE_INT, 0, @@ -425,11 +435,12 @@ std::vector> SpiceManager::spiceBodies( SPICETRUE, SPICEFALSE, SPICEFALSE, - &idsetBuffer, - &(idsetBuffer[SPICE_CELL_CTRLSZ]) + idsetBuffer.data(), + idsetBuffer.data() + SPICE_CELL_CTRLSZ }; - SpiceChar frname[Frnmln]; + constexpr int Frnmln = 33; + std::array frname; for (SpiceInt i = 1; i <= 6; i++) { if (i < 6) { @@ -453,13 +464,11 @@ std::vector> SpiceManager::spiceBodies( frmnam_c( (reinterpret_cast(idset.data))[j], Frnmln, - frname + frname.data() ); - bodies.push_back( - std::make_pair( - static_cast(reinterpret_cast(idset.data)[j]), - frname - ) + bodies.emplace_back( + static_cast(reinterpret_cast(idset.data)[j]), + frname.data() ); } } @@ -474,18 +483,18 @@ bool SpiceManager::hasValue(const std::string& body, const std::string& item) co ghoul_assert(!body.empty(), "Empty body"); ghoul_assert(!item.empty(), "Empty item"); - int id = naifId(body); + const int id = naifId(body); return hasValue(id, item); } int SpiceManager::naifId(const std::string& body) const { ghoul_assert(!body.empty(), "Empty body"); - SpiceBoolean success; - SpiceInt id; + SpiceBoolean success = SPICEFALSE; + SpiceInt id = 0; bods2c_c(body.c_str(), &id, &success); if (!success && _useExceptions) { - throw SpiceException(fmt::format("Could not find NAIF ID of body '{}'", body)); + throw SpiceException(std::format("Could not find NAIF ID of body '{}'", body)); } return id; } @@ -493,8 +502,8 @@ int SpiceManager::naifId(const std::string& body) const { bool SpiceManager::hasNaifId(const std::string& body) const { ghoul_assert(!body.empty(), "Empty body"); - SpiceBoolean success; - SpiceInt id; + SpiceBoolean success = SPICEFALSE; + SpiceInt id = 0; bods2c_c(body.c_str(), &id, &success); reset_c(); return success; @@ -503,10 +512,10 @@ bool SpiceManager::hasNaifId(const std::string& body) const { int SpiceManager::frameId(const std::string& frame) const { ghoul_assert(!frame.empty(), "Empty frame"); - SpiceInt id; + SpiceInt id = 0; namfrm_c(frame.c_str(), &id); if (id == 0 && _useExceptions) { - throw SpiceException(fmt::format("Could not find NAIF ID of frame '{}'", frame)); + throw SpiceException(std::format("Could not find NAIF ID of frame '{}'", frame)); } return id; } @@ -514,7 +523,7 @@ int SpiceManager::frameId(const std::string& frame) const { bool SpiceManager::hasFrameId(const std::string& frame) const { ghoul_assert(!frame.empty(), "Empty frame"); - SpiceInt id; + SpiceInt id = 0; namfrm_c(frame.c_str(), &id); return id != 0; } @@ -526,12 +535,12 @@ void getValueInternal(const std::string& body, const std::string& value, int siz ghoul_assert(!value.empty(), "Empty value"); ghoul_assert(v != nullptr, "Empty value pointer"); - SpiceInt n; + SpiceInt n = 0; bodvrd_c(body.c_str(), value.c_str(), size, &n, v); if (failed_c()) { throwSpiceError( - fmt::format("Error getting value '{}' for body '{}'", value, body) + std::format("Error getting value '{}' for body '{}'", value, body) ); } } @@ -568,14 +577,16 @@ void SpiceManager::getValue(const std::string& body, const std::string& value, getValueInternal(body, value, static_cast(v.size()), v.data()); } -double SpiceManager::spacecraftClockToET(const std::string& craft, double craftTicks) { +double SpiceManager::spacecraftClockToET(const std::string& craft, + double craftTicks) const +{ ghoul_assert(!craft.empty(), "Empty craft"); - int craftId = naifId(craft); - double et; + const int craftId = naifId(craft); + double et = 0.0; sct2e_c(craftId, craftTicks, &et); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error transforming spacecraft clock of '{}' at time {}", craft, craftTicks )); } @@ -589,10 +600,10 @@ double SpiceManager::ephemerisTimeFromDate(const std::string& timeString) const } double SpiceManager::ephemerisTimeFromDate(const char* timeString) const { - double et; + double et = 0.0; str2et_c(timeString, &et); if (failed_c()) { - throwSpiceError(fmt::format("Error converting date '{}'", timeString)); + throwSpiceError(std::format("Error converting date '{}'", timeString)); } return et; } @@ -600,12 +611,12 @@ double SpiceManager::ephemerisTimeFromDate(const char* timeString) const { std::string SpiceManager::dateFromEphemerisTime(double ephemerisTime, const char* format) { constexpr int BufferSize = 128; - char Buffer[BufferSize]; - std::memset(Buffer, char(0), BufferSize); + std::array Buffer; + std::memset(Buffer.data(), char(0), BufferSize); - timout_c(ephemerisTime, format, BufferSize, Buffer); + timout_c(ephemerisTime, format, BufferSize, Buffer.data()); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error converting ephemeris time '{}' to date with format '{}'", ephemerisTime, format )); @@ -613,11 +624,11 @@ std::string SpiceManager::dateFromEphemerisTime(double ephemerisTime, const char if (Buffer[0] == '*') { // The conversion failed and we need to use et2utc constexpr int SecondsPrecision = 3; - et2utc_c(ephemerisTime, "C", SecondsPrecision, BufferSize, Buffer); + et2utc_c(ephemerisTime, "C", SecondsPrecision, BufferSize, Buffer.data()); } - return std::string(Buffer); + return std::string(Buffer.data()); } glm::dvec3 SpiceManager::targetPosition(const std::string& target, @@ -630,13 +641,13 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target, ghoul_assert(!observer.empty(), "Observer is not empty"); ghoul_assert(!referenceFrame.empty(), "Reference frame is not empty"); - bool targetHasCoverage = hasSpkCoverage(target, ephemerisTime); - bool observerHasCoverage = hasSpkCoverage(observer, ephemerisTime); + const bool targetHasCoverage = hasSpkCoverage(target, ephemerisTime); + const bool observerHasCoverage = hasSpkCoverage(observer, ephemerisTime); if (!targetHasCoverage && !observerHasCoverage) { if (_useExceptions) { throw SpiceException( - fmt::format( - "Neither target '{}' nor observer '{}' has SPK coverage at time {}", + std::format( + "Neither target '{}' nor observer '{}' has SPK coverage at time '{}'", target, observer, ephemerisTime ) ); @@ -657,18 +668,20 @@ glm::dvec3 SpiceManager::targetPosition(const std::string& target, &lightTime ); if (failed_c()) { - throwSpiceError(fmt::format( - "Error getting position from '{}' to '{}' in frame '{}' at time {}", + throwSpiceError(std::format( + "Error getting position from '{}' to '{}' in frame '{}' at time '{}'", target, observer, referenceFrame, ephemerisTime )); } return position; } else if (targetHasCoverage) { - // observer has no coverage + // observer has no coverage, so we try getting position from the reverse + const std::string& invObserver = target; + const std::string& invTarget = observer; return getEstimatedPosition( - observer, - target, + invTarget, + invObserver, referenceFrame, aberrationCorrection, ephemerisTime, @@ -723,7 +736,7 @@ glm::dmat3 SpiceManager::frameTransformationMatrix(const std::string& from, if (failed_c()) { throwSpiceError( - fmt::format("Error converting from frame '{}' to frame '{}' at time '{}'", + std::format("Error converting from frame '{}' to frame '{}' at time '{}'", from, to, ephemerisTime ) ); @@ -754,7 +767,7 @@ SpiceManager::SurfaceInterceptResult SpiceManager::surfaceIntercept( SurfaceInterceptResult result; - SpiceBoolean found; + SpiceBoolean found = SPICEFALSE; sincpt_c(ComputationMethod.c_str(), target.c_str(), ephemerisTime, @@ -771,7 +784,7 @@ SpiceManager::SurfaceInterceptResult SpiceManager::surfaceIntercept( result.interceptFound = (found == SPICETRUE); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error retrieving surface intercept on target '{}' viewed from observer '{}' " "in reference frame '{}' at time '{}'", target, observer, referenceFrame, ephemerisTime @@ -795,8 +808,9 @@ bool SpiceManager::isTargetInFieldOfView(const std::string& target, ghoul_assert(!referenceFrame.empty(), "Reference frame must not be empty"); ghoul_assert(!instrument.empty(), "Instrument must not be empty"); - int visible; - fovtrg_c(instrument.c_str(), + int visible = 0; + fovtrg_c( + instrument.c_str(), target.c_str(), toString(method), referenceFrame.c_str(), @@ -807,7 +821,7 @@ bool SpiceManager::isTargetInFieldOfView(const std::string& target, ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Checking if target '{}' is in view of instrument '{}' failed", target, instrument )); @@ -842,7 +856,7 @@ SpiceManager::TargetStateResult SpiceManager::targetState(const std::string& tar ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error retrieving state of target '{}' viewed from observer '{}' in " "reference frame '{}' at time '{}'", target, observer, referenceFrame, ephemerisTime @@ -870,7 +884,7 @@ SpiceManager::TransformMatrix SpiceManager::stateTransformMatrix( reinterpret_cast(m.data()) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error retrieved state transform matrix from frame '{}' to frame '{}' at " "time '{}'", sourceFrame, destinationFrame, ephemerisTime @@ -897,7 +911,7 @@ glm::dmat3 SpiceManager::positionTransformMatrix(const std::string& sourceFrame, if (failed_c()) { throwSpiceError(""); } - SpiceBoolean success = !(failed_c()); + const SpiceBoolean success = !(failed_c()); reset_c(); if (!success) { result = getEstimatedTransformMatrix( @@ -928,7 +942,7 @@ glm::dmat3 SpiceManager::positionTransformMatrix(const std::string& sourceFrame, reinterpret_cast(glm::value_ptr(result)) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error retrieving position transform matrix from '{}' at time '{}' to frame " "'{}' at time '{}'", sourceFrame, ephemerisTimeFrom, destinationFrame, ephemerisTimeTo @@ -950,7 +964,7 @@ SpiceManager::FieldOfViewResult SpiceManager::fieldOfView(int instrument) const FieldOfViewResult res; - SpiceInt nrReturned; + SpiceInt nrReturned = 0; double boundsArr[MaxBoundsSize][3]; char fovShapeBuffer[BufferSize]; char frameNameBuffer[BufferSize]; @@ -966,18 +980,18 @@ SpiceManager::FieldOfViewResult SpiceManager::fieldOfView(int instrument) const ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error getting field-of-view parameters for instrument '{}'", instrument )); return res; } res.bounds.reserve(nrReturned); - for (int i = 0; i < nrReturned; ++i) { + for (int i = 0; i < nrReturned; i++) { res.bounds.emplace_back(boundsArr[i][0], boundsArr[i][1], boundsArr[i][2]); } - std::string shape = std::string(fovShapeBuffer); + const std::string shape = std::string(fovShapeBuffer); static const std::map Map = { { "POLYGON", FieldOfViewResult::Shape::Polygon }, { "RECTANGLE" , FieldOfViewResult::Shape::Rectangle }, @@ -1025,7 +1039,7 @@ SpiceManager::TerminatorEllipseResult SpiceManager::terminatorEllipse( reinterpret_cast(res.terminatorPoints.data()) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error getting terminator ellipse for target '{}' from observer '{}' in " "frame '{}' with light source '{}' at time '{}'", target, observer, frame, lightSource, ephemerisTime @@ -1038,7 +1052,7 @@ void SpiceManager::findCkCoverage(const std::string& path) { ghoul_assert(!path.empty(), "Empty file path"); ghoul_assert( std::filesystem::is_regular_file(path), - fmt::format("File '{}' does not exist", path) + std::format("File '{}' does not exist", path) ); constexpr unsigned int MaxObj = 1024; @@ -1060,7 +1074,7 @@ void SpiceManager::findCkCoverage(const std::string& path) { throwSpiceError("Error finding Ck Coverage"); } - for (SpiceInt i = 0; i < card_c(&ids); ++i) { + for (SpiceInt i = 0; i < card_c(&ids); i++) { const SpiceInt frame = SPICE_CELL_ELEM_I(&ids, i); #if defined __clang__ @@ -1078,9 +1092,10 @@ void SpiceManager::findCkCoverage(const std::string& path) { // Get the number of intervals in the coverage window. const SpiceInt numberOfIntervals = wncard_c(&cover); - for (SpiceInt j = 0; j < numberOfIntervals; ++j) { + for (SpiceInt j = 0; j < numberOfIntervals; j++) { // Get the endpoints of the jth interval. - SpiceDouble b, e; + SpiceDouble b = 0.0; + SpiceDouble e = 0.0; wnfetd_c(&cover, j, &b, &e); if (failed_c()) { throwSpiceError("Error finding Ck Coverage"); @@ -1097,7 +1112,7 @@ void SpiceManager::findSpkCoverage(const std::string& path) { ghoul_assert(!path.empty(), "Empty file path"); ghoul_assert( std::filesystem::is_regular_file(path), - fmt::format("File '{}' does not exist", path) + std::format("File '{}' does not exist", path) ); constexpr unsigned int MaxObj = 1024; @@ -1119,7 +1134,7 @@ void SpiceManager::findSpkCoverage(const std::string& path) { throwSpiceError("Error finding Spk ID for coverage"); } - for (SpiceInt i = 0; i < card_c(&ids); ++i) { + for (SpiceInt i = 0; i < card_c(&ids); i++) { const SpiceInt obj = SPICE_CELL_ELEM_I(&ids, i); #if defined __clang__ @@ -1137,9 +1152,10 @@ void SpiceManager::findSpkCoverage(const std::string& path) { // Get the number of intervals in the coverage window. const SpiceInt numberOfIntervals = wncard_c(&cover); - for (SpiceInt j = 0; j < numberOfIntervals; ++j) { + for (SpiceInt j = 0; j < numberOfIntervals; j++) { //Get the endpoints of the jth interval. - SpiceDouble b, e; + SpiceDouble b = 0.0; + SpiceDouble e = 0.0; wnfetd_c(&cover, j, &b, &e); if (failed_c()) { throwSpiceError("Error finding Spk coverage"); @@ -1167,7 +1183,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, ghoul_assert(!referenceFrame.empty(), "Reference frame must not be empty"); ghoul_assert(target != observer, "Target and observer must be different"); - int targetId = naifId(target); + const int targetId = naifId(target); if (targetId == 0) { // SOLAR SYSTEM BARYCENTER special case, no definition in kernels @@ -1177,7 +1193,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, if (_spkCoverageTimes.find(targetId) == _spkCoverageTimes.end()) { if (_useExceptions) { // no coverage - throw SpiceException(fmt::format("No position for '{}' at any time", target)); + throw SpiceException(std::format("No position for '{}' at any time", target)); } else { return glm::dvec3(0.0); @@ -1199,7 +1215,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, &lightTime ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating position for '{}' with observer '{}' in frame '{}'", target, observer, referenceFrame )); @@ -1218,7 +1234,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, &lightTime ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating position for '{}' with observer '{}' in frame '{}'", target, observer, referenceFrame )); @@ -1227,8 +1243,8 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, else { // coverage both earlier and later, interpolate these positions glm::dvec3 posEarlier = glm::dvec3(0.0); - double ltEarlier; - double timeEarlier = *std::prev((coveredTimes.lower_bound(ephemerisTime))); + double ltEarlier = 0.0; + const double timeEarlier = *std::prev((coveredTimes.lower_bound(ephemerisTime))); spkpos_c( target.c_str(), timeEarlier, @@ -1240,8 +1256,8 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, ); glm::dvec3 posLater = glm::dvec3(0.0); - double ltLater; - double timeLater = *(coveredTimes.upper_bound(ephemerisTime)); + double ltLater = 0.0; + const double timeLater = *(coveredTimes.upper_bound(ephemerisTime)); spkpos_c( target.c_str(), timeLater, @@ -1253,7 +1269,7 @@ glm::dvec3 SpiceManager::getEstimatedPosition(const std::string& target, ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating position for '{}' with observer '{}' in frame '{}'", target, observer, referenceFrame )); @@ -1278,7 +1294,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram if (_ckCoverageTimes.find(idFrame) == _ckCoverageTimes.end()) { if (_useExceptions) { // no coverage - throw SpiceException(fmt::format( + throw SpiceException(std::format( "No data available for transform matrix from '{}' to '{}' at any time", fromFrame, toFrame )); @@ -1299,7 +1315,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram reinterpret_cast(glm::value_ptr(result)) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating transform matrix from '{}' to from '{}' at time '{}'", fromFrame, toFrame, time )); @@ -1314,7 +1330,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram reinterpret_cast(glm::value_ptr(result)) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating transform matrix from frame '{}' to '{}' at time '{}'", fromFrame, toFrame, time )); @@ -1322,8 +1338,8 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram } else { // coverage both earlier and later, interpolate these transformations - double earlier = *std::prev((coveredTimes.lower_bound(time))); - double later = *(coveredTimes.upper_bound(time)); + const double earlier = *std::prev((coveredTimes.lower_bound(time))); + const double later = *(coveredTimes.upper_bound(time)); glm::dmat3 earlierTransform = glm::dmat3(1.0); pxform_c( @@ -1333,7 +1349,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram reinterpret_cast(glm::value_ptr(earlierTransform)) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating transform matrix from frame '{}' to '{}' at time '{}'", fromFrame, toFrame, time )); @@ -1347,7 +1363,7 @@ glm::dmat3 SpiceManager::getEstimatedTransformMatrix(const std::string& fromFram reinterpret_cast(glm::value_ptr(laterTransform)) ); if (failed_c()) { - throwSpiceError(fmt::format( + throwSpiceError(std::format( "Error estimating transform matrix from frame '{}' to '{}' at time '{}'", fromFrame, toFrame, time )); @@ -1515,8 +1531,8 @@ DELTET/DELTA_AT = ( 10, @1972-JAN-1 )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "naif0012.tls"; +const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "naif0012.tls"; { std::ofstream f(file); f << Naif00012tlsSource; @@ -1525,6 +1541,140 @@ DELTET/DELTA_AT = ( 10, @1972-JAN-1 std::filesystem::remove(file); } +void SpiceManager::loadGeophysicalConstantsKernel() { + constexpr std::string_view GeoPhysicalConstantsKernelSource = R"( +KPL/PCK + + The SPK creations applications (mkspk, mkspk_c) require the data in + this kernel to produce Type 10 SPK segments based upon the Two-Line + element sets available from NORAD/SPACETRACK. The data applies ONLY + to the Two-Line Element sets and only to the SGP4 implementations + included in the SPICE library [1][2]. The SPK application copies + this data to the constants partition of the Type 10 segment, so the + user has no need for the kernel after creation of the corresponding + SPK. + + Bill Taber (JPL) + Edward Wright (JPL) + + The assigned values are taken from the Spacetrack #3 report, referred + to as WGS721 in Vallado [2]. It is possible to edit this file + to use the high accuracy WGS-72 values (WGS72) or the WGS-84 + values (WGS84). The KE parameter value for WGS72 and WGS84 + is calculated from the MU and ER values. The lists include MU only + for the calculation of KE. + + MU, the standard gravitational parameter, in cubic kilometer per + second squared. + + WGS721 (STR#3 values) [1] + + ER = 6378.135 + + J2 = 0.001082616 + J3 = -0.00000253881 + J4 = -0.00000165597 + + KE = 0.0743669161 + + + WGS72 [2] + + MU = 398600.8 + ER = 6378.135 + + J2 = 0.001082616 + J3 = -0.00000253881 + J4 = -0.00000165597 + + KE = 60.0D0/DSQRT(ER**3/MU) + = 0.074366916133173 + + + WGS84 [2] + + MU = 398600.5 + ER = 6378.137 + + J2 = 0.00108262998905 + J3 = -0.00000253215306 + J4 = -0.00000161098761 + + KE = 60.0D0/DSQRT(ER**3/MU) + = 0.074366853168714 + + + The BODY399_Jn values are un-normalized zonal harmonic values + for the earth. These numbers are dimensionless. + +\begindata + + BODY399_J2 = 1.082616D-3 + BODY399_J3 = -2.53881D-6 + BODY399_J4 = -1.65597D-6 + +\begintext + + The next item is the square root of GM for the earth given + in units of earth-radii**1.5/Minute + +\begindata + + BODY399_KE = 7.43669161D-2 + +\begintext + + The next two items define the top and bottom of the atmospheric + drag model, distance above the surface in kilometers, used by + the type 10 ephemeris type. + +\begindata + + BODY399_QO = 120.0D0 + BODY399_SO = 78.0D0 + +\begintext + + The equatorial radius of the earth in kilometers as used by + the TLE propagator. + +\begindata + + BODY399_ER = 6378.135D0 + +\begintext + + The value of AE is the number of distance units per earth + radii used by the NORAD state propagation software. Don't + change this value. + +\begindata + + BODY399_AE = 1.0D0 + +\begintext + +References: + + [1] Hoots, F. R., and Roehrich, R., l. 1980. "Spacetrack Report #3, Models + for Propagation of the NORAD Element Sets." U.S. Air Force, CO. + + [2] Vallado, David, Crawford, Paul, Hujsak, Richard, + and Kelso, T.S. 2006. Revisiting Spacetrack Report #3. Paper + AIAA 2006-6753 presented at the AIAA/AAS Astrodynamics + Specialist Conference, August 21-24, 2006. Keystone, CO. +)"; + + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "geophysical.ker"; + { + std::ofstream f(file); + f << GeoPhysicalConstantsKernelSource; + } + loadKernel(file.string()); + std::filesystem::remove(file); +} + void SpiceManager::setExceptionHandling(UseException useException) { _useExceptions = useException; } @@ -1543,6 +1693,7 @@ scripting::LuaLibrary SpiceManager::luaLibrary() { codegen::lua::SpiceBodies, codegen::lua::RotationMatrix, codegen::lua::Position, + codegen::lua::ConvertTLEtoSPK } }; } diff --git a/src/util/spicemanager_lua.inl b/src/util/spicemanager_lua.inl index b08c9af17e..dec8e0df24 100644 --- a/src/util/spicemanager_lua.inl +++ b/src/util/spicemanager_lua.inl @@ -22,6 +22,8 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#include + namespace { /** @@ -34,7 +36,7 @@ namespace { if (std::holds_alternative(kernel)) { std::string k = std::get(kernel); if (!std::filesystem::is_regular_file(k)) { - throw ghoul::lua::LuaError(fmt::format("Kernel file '{}' did not exist", k)); + throw ghoul::lua::LuaError(std::format("Kernel file '{}' did not exist", k)); } openspace::SpiceManager::ref().loadKernel(k); } @@ -42,7 +44,7 @@ namespace { std::vector ks = std::get>(kernel); for (const std::string& k : ks) { if (!std::filesystem::is_regular_file(k)) { - throw ghoul::lua::LuaError(fmt::format( + throw ghoul::lua::LuaError(std::format( "Kernel file '{}' did not exist", k )); } @@ -131,6 +133,151 @@ namespace { return position; } +/** + * This function converts a TLE file into SPK format and saves it at the provided path. + * The last parameter is only used if there are multiple craft specified in the provided + * TLE file and is selecting which (0-based index) of the list to create a kernel from. + * + * This function returns the SPICE ID of the object for which the kernel was created + */ +[[codegen::luawrap]] int convertTLEtoSPK(std::filesystem::path tle, + std::filesystem::path spk, + int elementToExtract = 0) +{ + // Code adopted from + // https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/getelm_c.html + SpiceInt n = 0; + + // + // First exact the constants required by a type 10 SPK kernel. + // + + std::array constants; + // J2 gravitational harmonic for Earth + bodvcd_c(399, "J2", 1, &n, &constants[0]); + + // J3 gravitational harmonic for Earth + bodvcd_c(399, "J3", 1, &n, &constants[1]); + + // J4 gravitational harmonic for Earth + bodvcd_c(399, "J4", 1, &n, &constants[2]); + + // Square root of the GM for Earth + bodvcd_c(399, "KE", 1, &n, &constants[3]); + + // High altitude bound for atmospheric model + bodvcd_c(399, "QO", 1, &n, &constants[4]); + + // Low altitude bound for atmospheric model + bodvcd_c(399, "SO", 1, &n, &constants[5]); + + // Equatorial radius of the Earth + bodvcd_c(399, "ER", 1, &n, &constants[6]); + + // Distance units/earth radius + bodvcd_c(399, "AE", 1, &n, &constants[7]); + + // + // Load the TLE file + // + std::ifstream f = std::ifstream(tle); + std::string contents = std::string( + std::istreambuf_iterator(f), + std::istreambuf_iterator() + ); + + // The TLE files returned by Celestrak are of the 3-line variant where the first line + // contains a human-readable name for the spacecraft + + std::vector lines = ghoul::tokenizeString(contents, '\n'); + const size_t nElements = lines.size() / 3; + if (elementToExtract > nElements) { + throw ghoul::RuntimeError(std::format( + "Error loading {}. Element number {} requested, but only {} found", + tle, nElements, elementToExtract + )); + } + + constexpr int TLEColumnWidth = 70; + + // It should be 70, but we're removing the \n character at the end in the tokenization + std::string line1 = lines[3 * elementToExtract + 1]; + if (line1.size() != TLEColumnWidth - 1) { + throw ghoul::RuntimeError(std::format( + "Illformed TLE file {}, expected {} characters per line, got {}", + tle, TLEColumnWidth, line1.size() + )); + } + std::string line2 = lines[3 * elementToExtract + 2]; + if (line2.size() != TLEColumnWidth - 1) { + throw ghoul::RuntimeError(std::format( + "Illformed TLE file {}, expected {} characters per line, got {}", + tle, TLEColumnWidth, line2.size() + )); + } + + // Copy the lines into a format that SPICE understands + SpiceChar spiceLines[2][TLEColumnWidth]; + std::strcpy(spiceLines[0], line1.c_str()); + std::strcpy(spiceLines[1], line2.c_str()); + + + // Convert the Two Line Elements lines to the element sets + SpiceDouble epoch; + std::array elems; + getelm_c(1950, TLEColumnWidth, spiceLines, &epoch, elems.data()); + + // The size of a type SPK10 spice kernel is not affected by the time validity, so we + // just pick the greatest one + SpiceDouble first = -std::numeric_limits::max(); + SpiceDouble last = std::numeric_limits::max(); + + // Extract the body id + std::vector tokens = ghoul::tokenizeString(line2, ' '); + if (tokens.size() < 2) { + throw ghoul::RuntimeError(std::format( + "Error parsing TLE file {}. Expected 8-9 elements in the second row, got {}", + tle, tokens.size() + )); + } + // Earth-orbiting spacecraft usually lack a DSN identification code, so the NAIF ID + // is derived from the tracking ID assigned to it by NORAD via: + // NAIF ID = -100000 - NORAD ID + int bodyId = -100000 - std::stoi(tokens[1]); + + + // Write the elements to a new SPK file + const SpiceInt nCommentCharacters = 0; + std::string internalFileName = std::format("Type 10 SPK for {}", tle); + std::string segmentId = "Segment"; + + if (std::filesystem::exists(spk)) { + std::filesystem::remove(spk); + } + + std::string outFile = spk.string(); + SpiceInt handle; + spkopn_c(outFile.c_str(), internalFileName.c_str(), nCommentCharacters, &handle); + + spkw10_c( + handle, + bodyId, + 399, + "J2000", + first, + last, + segmentId.c_str(), + constants.data(), + 1, + elems.data(), + &epoch + ); + + spkcls_c(handle); + + return bodyId; +} + #include "spicemanager_lua_codegen.cpp" } // namespace diff --git a/src/util/syncbuffer.cpp b/src/util/syncbuffer.cpp index bef545df42..7fc24d91e4 100644 --- a/src/util/syncbuffer.cpp +++ b/src/util/syncbuffer.cpp @@ -34,12 +34,10 @@ SyncBuffer::SyncBuffer(size_t n) _dataStream.resize(_n); } -SyncBuffer::~SyncBuffer() {} - void SyncBuffer::encode(const std::string& s) { ZoneScoped; - int32_t anticpatedBufferSize = static_cast( + const int32_t anticpatedBufferSize = static_cast( _encodeOffset + (sizeof(char) * s.size()) + sizeof(int32_t) ); if (anticpatedBufferSize >= static_cast(_n)) { @@ -60,8 +58,8 @@ void SyncBuffer::encode(const std::string& s) { std::string SyncBuffer::decode() { ZoneScoped; - int32_t length; - memcpy( + int32_t length = 0; + std::memcpy( reinterpret_cast(&length), _dataStream.data() + _decodeOffset, sizeof(int32_t) diff --git a/src/util/taskloader.cpp b/src/util/taskloader.cpp index 5d633915bf..045e4680ce 100644 --- a/src/util/taskloader.cpp +++ b/src/util/taskloader.cpp @@ -42,23 +42,23 @@ namespace { namespace openspace { std::vector> TaskLoader::tasksFromDictionary( - const ghoul::Dictionary& tasksDictionary) + const ghoul::Dictionary& dictionary) { std::vector> tasks; - for (std::string_view key : tasksDictionary.keys()) { - if (tasksDictionary.hasValue(key)) { - std::string taskName = tasksDictionary.value(key); + for (const std::string_view key : dictionary.keys()) { + if (dictionary.hasValue(key)) { + const std::string taskName = dictionary.value(key); const std::string path = taskName + ".task"; std::vector> subTasks = tasksFromFile(path); std::move(subTasks.begin(), subTasks.end(), std::back_inserter(tasks)); } - else if (tasksDictionary.hasValue(key)) { - ghoul::Dictionary subTask = tasksDictionary.value(key); + else if (dictionary.hasValue(key)) { + const ghoul::Dictionary subTask = dictionary.value(key); const std::string& taskType = subTask.value("Type"); std::unique_ptr task = Task::createFromDictionary(subTask); if (!task) { - LERROR(fmt::format( + LERROR(std::format( "Failed to create a Task object of type '{}'", taskType )); } @@ -71,7 +71,9 @@ std::vector> TaskLoader::tasksFromDictionary( std::vector> TaskLoader::tasksFromFile(const std::string& path) { std::filesystem::path absTasksFile = absPath(path); if (!std::filesystem::is_regular_file(absTasksFile)) { - LERROR(fmt::format("Could not load tasks file {}. File not found", absTasksFile)); + LERROR(std::format( + "Could not load tasks file '{}'. File not found", absTasksFile + )); return std::vector>(); } @@ -80,8 +82,8 @@ std::vector> TaskLoader::tasksFromFile(const std::string& ghoul::lua::loadDictionaryFromFile(absTasksFile.string(), tasksDictionary); } catch (const ghoul::RuntimeError& e) { - LERROR(fmt::format( - "Could not load tasks file {}. Lua error: {}: {}", + LERROR(std::format( + "Could not load tasks file '{}'. Lua error: ({}) {}", absTasksFile, e.message, e.component )); return std::vector>(); @@ -91,7 +93,7 @@ std::vector> TaskLoader::tasksFromFile(const std::string& return tasksFromDictionary(tasksDictionary); } catch (const documentation::SpecificationError& e) { - LERROR(fmt::format("Could not load tasks file {}. {}", absTasksFile, e.what())); + LERROR(std::format("Could not load tasks file '{}': {}", absTasksFile, e.what())); logError(e); return std::vector>(); diff --git a/src/util/threadpool.cpp b/src/util/threadpool.cpp index 7606ae7d92..3b426c1422 100644 --- a/src/util/threadpool.cpp +++ b/src/util/threadpool.cpp @@ -31,9 +31,8 @@ Worker::Worker(ThreadPool& p) : pool(p) {} void Worker::operator()() { std::function task; while (true) { - // acquire lock { - std::unique_lock lock(pool.queue_mutex); + std::unique_lock lock(pool.queue_mutex); // look for a work item while (!pool.stop && pool.tasks.empty()) { @@ -48,8 +47,7 @@ void Worker::operator()() { // get the task from the queue task = pool.tasks.front(); pool.tasks.pop_front(); - - } // release lock + } // execute the task task(); @@ -57,8 +55,8 @@ void Worker::operator()() { } ThreadPool::ThreadPool(size_t numThreads) : stop(false) { - for (size_t i = 0; i < numThreads; ++i) { - workers.emplace_back(std::thread(Worker(*this))); + for (size_t i = 0; i < numThreads; i++) { + workers.emplace_back(Worker(*this)); } } @@ -68,7 +66,7 @@ ThreadPool::ThreadPool(const ThreadPool& toCopy) : ThreadPool(toCopy.workers.siz ThreadPool::~ThreadPool() { // stop all threads { - std::unique_lock lock(queue_mutex); + const std::unique_lock lock(queue_mutex); stop = true; } condition.notify_all(); @@ -81,22 +79,20 @@ ThreadPool::~ThreadPool() { // add new work item to the pool void ThreadPool::enqueue(std::function f) { - { // acquire lock - std::unique_lock lock(queue_mutex); + { + const std::unique_lock lock(queue_mutex); // add the task tasks.push_back(std::move(f)); - } // release lock + } // wake up one thread condition.notify_one(); } void ThreadPool::clearTasks() { - { // acquire lock - std::unique_lock lock(queue_mutex); - tasks.clear(); - } // release lock + const std::unique_lock lock(queue_mutex); + tasks.clear(); } bool ThreadPool::hasOutstandingTasks() const { diff --git a/src/util/time.cpp b/src/util/time.cpp index d5b682939f..51419dcc90 100644 --- a/src/util/time.cpp +++ b/src/util/time.cpp @@ -61,10 +61,9 @@ double Time::convertTime(const char* time) { } std::string Time::currentWallTime() { - std::time_t t = std::time(nullptr); + const std::time_t t = std::time(nullptr); std::tm* utcTime = std::gmtime(&t); - - std::string time = fmt::format( + const std::string time = std::format( "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}", utcTime->tm_year + 1900, utcTime->tm_mon + 1, utcTime->tm_mday, utcTime->tm_hour, utcTime->tm_min, utcTime->tm_sec @@ -79,28 +78,27 @@ Time::Time(const std::string& time) : {} Time Time::now() { - Time now; - time_t secondsSince1970; - secondsSince1970 = time(nullptr); + const time_t secondsSince1970 = time(nullptr); const time_t secondsInAYear = static_cast(365.25 * 24 * 60 * 60); const double secondsSince2000 = static_cast( secondsSince1970 - 30 * secondsInAYear ); + Time now; now.setTime(secondsSince2000); return now; } -void Time::setTime(double value) { - _time = value; +void Time::setTime(double j2000Seconds) { + _time = j2000Seconds; } double Time::j2000Seconds() const { return _time; } -double Time::advanceTime(double delta) { - _time += delta; +double Time::advanceTime(double deltaTime) { + _time += deltaTime; return _time; } @@ -144,8 +142,8 @@ void Time::ISO8601(char* buffer) const { SpiceManager::ref().dateFromEphemerisTime(_time, buffer, S, Format); } -std::string Time::advancedTime(std::string base, std::string change) { - double j2000Seconds = Time::convertTime(base); +std::string Time::advancedTime(const std::string& base, std::string change) { + const double j2000Seconds = Time::convertTime(base); double dt = 0.0; if (change.empty()) { @@ -168,8 +166,8 @@ std::string Time::advancedTime(std::string base, std::string change) { ); try { - double value = std::stod(std::string(change.begin(), it)); - std::string uName = std::string(it, change.end()); + const double value = std::stod(std::string(change.begin(), it)); + const std::string_view uName = std::string_view(it, change.end()); TimeUnit unit = TimeUnit::Second; if (uName == "s") { unit = TimeUnit::Second; } @@ -179,7 +177,7 @@ std::string Time::advancedTime(std::string base, std::string change) { else if (uName == "M") { unit = TimeUnit::Month; } else if (uName == "y") { unit = TimeUnit::Year; } else { - throw ghoul::RuntimeError(fmt::format("Unknown unit '{}'", uName)); + throw ghoul::RuntimeError(std::format("Unknown unit '{}'", uName)); } dt = openspace::convertTime(value, unit, TimeUnit::Second); @@ -188,12 +186,12 @@ std::string Time::advancedTime(std::string base, std::string change) { } } catch (...) { - throw ghoul::RuntimeError(fmt::format( + throw ghoul::RuntimeError(std::format( "Error parsing relative time offset '{}'", change )); } - std::string_view ret = Time(j2000Seconds + dt).ISO8601(); + const std::string_view ret = Time(j2000Seconds + dt).ISO8601(); return std::string(ret); } diff --git a/src/util/time_lua.inl b/src/util/time_lua.inl index 5cbd3c942d..811c808a13 100644 --- a/src/util/time_lua.inl +++ b/src/util/time_lua.inl @@ -329,7 +329,7 @@ namespace { } else { double v = std::get(change); - c = fmt::format("{}s", v); + c = std::format("{}s", v); } std::string res = openspace::Time::advancedTime(std::move(b), std::move(c)); diff --git a/src/util/timeconversion.cpp b/src/util/timeconversion.cpp index cea0ebc87d..63e0178662 100644 --- a/src/util/timeconversion.cpp +++ b/src/util/timeconversion.cpp @@ -78,9 +78,8 @@ namespace { namespace openspace { std::pair simplifyTime(double seconds, bool forceSingularForm) { - std::pair p = extractUnit(seconds); - - bool pluralForm = (p.first != 1.0 && !forceSingularForm); + const std::pair p = extractUnit(seconds); + const bool pluralForm = (p.first != 1.0 && !forceSingularForm); return { p.first, nameForTimeUnit(p.second, pluralForm) }; } @@ -92,21 +91,21 @@ std::vector> splitTime(double seconds, double secondsVal = std::abs(seconds); do { - std::pair p = extractUnit(secondsVal); + const std::pair p = extractUnit(secondsVal); if (p.second == TimeUnit::Nanosecond) { // We have reached the lowest supported time unit - bool pluralForm = (p.first != 1.0 && !forceSingularForm); - res.push_back({ p.first, nameForTimeUnit(p.second, pluralForm) }); + const bool pluralForm = (p.first != 1.0 && !forceSingularForm); + res.emplace_back(p.first, nameForTimeUnit(p.second, pluralForm)); break; } - double pt = std::floor(p.first); + const double pt = std::floor(p.first); // Add the unit the list - bool pluralForm = (p.first != 1.0 && !forceSingularForm); - res.push_back({ pt, nameForTimeUnit(p.second, pluralForm) }); + const bool pluralForm = (p.first != 1.0 && !forceSingularForm); + res.emplace_back(pt, nameForTimeUnit(p.second, pluralForm)); // Adjust the remaining time secondsVal -= convertTime(pt, p.second, TimeUnit::Second); diff --git a/src/util/timeline.cpp b/src/util/timeline.cpp index 8d9e3e2a49..e326cb492d 100644 --- a/src/util/timeline.cpp +++ b/src/util/timeline.cpp @@ -26,6 +26,11 @@ namespace openspace { +KeyframeBase::KeyframeBase(size_t id_, double timestamp_) + : id(id_) + , timestamp(timestamp_) +{} + bool compareKeyframeTimes(const KeyframeBase& a, const KeyframeBase& b) { return a.timestamp < b.timestamp; } @@ -42,4 +47,4 @@ bool compareKeyframeTimeWithTime_playbackWithFrames(const KeyframeBase& a, doubl return a.timestamp <= b; } -} // namespace +} // namespace openspace diff --git a/src/util/timemanager.cpp b/src/util/timemanager.cpp index 7140359766..2f704f39a4 100644 --- a/src/util/timemanager.cpp +++ b/src/util/timemanager.cpp @@ -81,8 +81,6 @@ namespace { namespace openspace { -using datamessagestructures::TimeKeyframe; - TimeManager::TimeManager() : properties::PropertyOwner({ "TimeManager", "Time Manager" }) , _defaultTimeInterpolationDuration(DefaultTimeInterpolationDurationInfo, @@ -118,7 +116,7 @@ TimeManager::TimeManager() void TimeManager::interpolateTime(double targetTime, double durationSeconds) { ghoul_precondition(durationSeconds > 0.f, "durationSeconds must be positive"); - OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); if (m == OpenSpaceEngine::Mode::CameraPath) { LERROR("Cannot change simulation time during camera path"); return; @@ -240,7 +238,7 @@ TimeKeyframeData TimeManager::interpolate(double applicationTime) { else if (hasPastKeyframes) { // Extrapolate based on last past keyframe const double deltaApplicationTime = applicationTime - lastPastKeyframe->timestamp; - Time predictedTime( + const Time predictedTime = Time( lastPastKeyframe->data.time.j2000Seconds() + deltaApplicationTime * (lastPastKeyframe->data.pause ? 0.0 : lastPastKeyframe->data.delta) @@ -259,7 +257,7 @@ TimeKeyframeData TimeManager::interpolate(double applicationTime) { void TimeManager::progressTime(double dt) { ZoneScoped; - OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); if (m == OpenSpaceEngine::Mode::CameraPath) { // We don't want to progress time when a camera path is playing, so return return; @@ -298,7 +296,7 @@ void TimeManager::progressTime(double dt) { const double now = currentApplicationTimeForInterpolation(); const std::deque>& keyframes = _timeline.keyframes(); - std::function comparisonFunc = + const std::function comparisonFunc = (isPlayingBackSessionRecording()) ? &compareKeyframeTimeWithTime_playbackWithFrames : &compareKeyframeTimeWithTime; @@ -323,7 +321,7 @@ void TimeManager::progressTime(double dt) { if (hasFutureKeyframes && hasPastKeyframes && !firstFutureKeyframe->data.jump) { // If keyframes exist before and after this frame, // interpolate between those. - TimeKeyframeData interpolated = interpolate( + const TimeKeyframeData interpolated = interpolate( *lastPastKeyframe, *firstFutureKeyframe, now @@ -349,7 +347,7 @@ void TimeManager::progressTime(double dt) { TimeKeyframeData TimeManager::interpolate(const Keyframe& past, const Keyframe& future, - double appTime) + double time) { // https://en.wikipedia.org/wiki/Spline_interpolation // interpolatedTime = (1 - t)y1 + t*y2 + t(1 - t)(a(1 - t) + bt), where @@ -365,7 +363,7 @@ TimeKeyframeData TimeManager::interpolate(const Keyframe& past const double deltaAppTime = future.timestamp - past.timestamp; const double deltaSimTime = futureSimTime - pastSimTime; - const double t = (appTime - past.timestamp) / deltaAppTime; + const double t = (time - past.timestamp) / deltaAppTime; const double a = pastDerivative * deltaAppTime - deltaSimTime; const double b = -futureDerivative * deltaAppTime + deltaSimTime; @@ -389,8 +387,8 @@ TimeKeyframeData TimeManager::interpolate(const Keyframe& past return data; } -void TimeManager::applyKeyframeData(const TimeKeyframeData& keyframeData, double dt) { - const Time& currentTime = keyframeData.time; +void TimeManager::applyKeyframeData(const TimeKeyframeData& keyframe, double dt) { + const Time& currentTime = keyframe.time; _deltaTime = _timePaused ? 0.0 : _targetDeltaTime; if (isPlayingBackSessionRecording()) { _currentTime.data().advanceTime(dt * _deltaTime); @@ -398,8 +396,8 @@ void TimeManager::applyKeyframeData(const TimeKeyframeData& keyframeData, double else { _currentTime.data().setTime(currentTime.j2000Seconds()); } - _timePaused = keyframeData.pause; - _targetDeltaTime = keyframeData.delta; + _timePaused = keyframe.pause; + _targetDeltaTime = keyframe.delta; _deltaTime = _timePaused ? 0.0 : _targetDeltaTime; } @@ -409,7 +407,7 @@ void TimeManager::addKeyframe(double timestamp, TimeKeyframeData time) { } void TimeManager::removeKeyframesAfter(double timestamp, bool inclusive) { - size_t nKeyframes = _timeline.nKeyframes(); + const size_t nKeyframes = _timeline.nKeyframes(); _timeline.removeKeyframesAfter(timestamp, inclusive); if (nKeyframes != _timeline.nKeyframes()) { _timelineChanged = true; @@ -417,7 +415,7 @@ void TimeManager::removeKeyframesAfter(double timestamp, bool inclusive) { } void TimeManager::removeKeyframesBefore(double timestamp, bool inclusive) { - size_t nKeyframes = _timeline.nKeyframes(); + const size_t nKeyframes = _timeline.nKeyframes(); _timeline.removeKeyframesBefore(timestamp, inclusive); if (nKeyframes != _timeline.nKeyframes()) { _timelineChanged = true; @@ -425,7 +423,7 @@ void TimeManager::removeKeyframesBefore(double timestamp, bool inclusive) { } void TimeManager::clearKeyframes() { - size_t nKeyframes = _timeline.nKeyframes(); + const size_t nKeyframes = _timeline.nKeyframes(); _timeline.clearKeyframes(); if (nKeyframes != _timeline.nKeyframes()) { _timelineChanged = true; @@ -433,7 +431,7 @@ void TimeManager::clearKeyframes() { } void TimeManager::setTimeNextFrame(Time t) { - OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode m = global::openSpaceEngine->currentMode(); if (m == OpenSpaceEngine::Mode::CameraPath) { LERROR("Cannot change simulation time during camera path"); return; @@ -455,7 +453,7 @@ void TimeManager::setDeltaTimeSteps(std::vector deltaTimes) { deltaTimes.begin(), deltaTimes.end(), std::back_inserter(negatives), - std::negate() + std::negate<>() ); deltaTimes.reserve(2 * deltaTimes.size()); @@ -501,16 +499,16 @@ void TimeManager::addDeltaTimesKeybindings() { ); auto addDeltaTimeKeybind = [this](Key key, KeyModifier mod, double step) { - const std::string s = fmt::format("{:.0f}", step); + const std::string s = std::format("{:.0f}", step); - std::string identifier = fmt::format("{}.{}", DeltaTimeActionPrefix, s); + std::string identifier = std::format("{}.{}", DeltaTimeActionPrefix, s); interaction::Action action; action.identifier = identifier; - action.command = fmt::format("openspace.time.interpolateDeltaTime({})", s); - action.documentation = fmt::format( + action.command = std::format("openspace.time.interpolateDeltaTime({})", s); + action.documentation = std::format( "Setting the simulation speed to {} seconds per realtime second", s ); - action.name = fmt::format("Set: {}", s); + action.name = std::format("Set: {}", s); action.guiPath = DeltaTimeStepsGuiPath; action.isLocal = interaction::Action::IsLocal::Yes; global::actionManager->registerAction(std::move(action)); @@ -523,7 +521,7 @@ void TimeManager::addDeltaTimesKeybindings() { // For each key, add upp to three keybinds (no modifier, then SHIFT and then CTRL), // plus inverted version of each time step one using the ALT modifier - for (int i = 0; i < nSteps; ++i) { + for (int i = 0; i < nSteps; i++) { const Key key = Keys[i % nKeys]; const double deltaTimeStep = steps[i]; @@ -535,7 +533,7 @@ void TimeManager::addDeltaTimesKeybindings() { modifier = KeyModifier::Control; } - KeyModifier negativeModifier = modifier | KeyModifier::Alt; + const KeyModifier negativeModifier = modifier | KeyModifier::Alt; addDeltaTimeKeybind(key, modifier, deltaTimeStep); addDeltaTimeKeybind(key, negativeModifier, -deltaTimeStep); @@ -544,7 +542,7 @@ void TimeManager::addDeltaTimesKeybindings() { LINFO("Added keybindings for specified delta time steps"); const int maxKeyBinds = 3 * nKeys; if (nSteps > maxKeyBinds) { - LWARNING(fmt::format( + LWARNING(std::format( "Error settings delta time keys: Too many delta times, so not all could be " "mapped to a key. Total: {} steps, which is {} more than the number of " "available keybindings", @@ -556,7 +554,7 @@ void TimeManager::addDeltaTimesKeybindings() { void TimeManager::clearDeltaTimesKeybindings() { // Iterate over all of the registered actions with the common prefix that we created // in the addDeltaTimesKeybindings function - std::vector actions = global::actionManager->actions(); + const std::vector actions = global::actionManager->actions(); for (const interaction::Action& action : actions) { if (action.identifier.starts_with(DeltaTimeActionPrefix)) { global::actionManager->removeAction(action.identifier); @@ -569,9 +567,9 @@ void TimeManager::clearDeltaTimesKeybindings() { if (bindings.size() > 1) { std::string names; for (auto& b : bindings) { - names += fmt::format("'{}' ", b.second); + names += std::format("'{}' ", b.second); } - LWARNING(fmt::format( + LWARNING(std::format( "Updating keybindings for new delta time steps: More than one action " "was bound to key '{}'. The following actions are removed: {}", ghoul::to_string(kb), names @@ -603,14 +601,14 @@ std::vector TimeManager::syncables() { } TimeManager::CallbackHandle TimeManager::addTimeChangeCallback(TimeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _timeChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _deltaTimeChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } @@ -618,21 +616,21 @@ TimeManager::CallbackHandle TimeManager::addDeltaTimeChangeCallback(TimeChangeCa TimeManager::CallbackHandle TimeManager::addDeltaTimeStepsChangeCallback(TimeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _deltaTimeStepsChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } TimeManager::CallbackHandle TimeManager::addTimeJumpCallback(TimeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; + const CallbackHandle handle = _nextCallbackHandle++; _timeJumpCallbacks.emplace_back(handle, std::move(cb)); return handle; } TimeManager::CallbackHandle TimeManager::addTimelineChangeCallback(TimeChangeCallback cb) { - CallbackHandle handle = _nextCallbackHandle++; - _timelineChangeCallbacks.push_back({ handle, std::move(cb) }); + const CallbackHandle handle = _nextCallbackHandle++; + _timelineChangeCallbacks.emplace_back(handle, std::move(cb)); return handle; } @@ -766,17 +764,17 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation return; } - Time newTime( + const Time newTime = Time( time().j2000Seconds() + (_deltaTime + newDeltaTime) * 0.5 * interpolationDuration ); - TimeKeyframeData currentKeyframe = { + const TimeKeyframeData currentKeyframe = { .time = time(), .delta = _deltaTime, .pause = false, .jump = false }; - TimeKeyframeData futureKeyframe = { + const TimeKeyframeData futureKeyframe = { .time = newTime, .delta = newDeltaTime, .pause = false, @@ -785,7 +783,7 @@ void TimeManager::interpolateDeltaTime(double newDeltaTime, double interpolation _targetDeltaTime = newDeltaTime; - double now = isPlayingBackSessionRecording() ? + const double now = isPlayingBackSessionRecording() ? previousApplicationTimeForInterpolation() : currentApplicationTimeForInterpolation(); @@ -797,7 +795,8 @@ std::optional TimeManager::nextDeltaTimeStep() { if (!hasNextDeltaTimeStep()) { return std::nullopt; } - std::vector::iterator nextStepIterator = std::upper_bound( + + const std::vector::iterator nextStepIterator = std::upper_bound( _deltaTimeSteps.begin(), _deltaTimeSteps.end(), _targetDeltaTime @@ -814,7 +813,7 @@ std::optional TimeManager::previousDeltaTimeStep() { if (!hasPreviousDeltaTimeStep()) { return std::nullopt; } - std::vector::iterator lowerBoundIterator = std::lower_bound( + const std::vector::iterator lowerBoundIterator = std::lower_bound( _deltaTimeSteps.begin(), _deltaTimeSteps.end(), _targetDeltaTime @@ -824,20 +823,22 @@ std::optional TimeManager::previousDeltaTimeStep() { return std::nullopt; // should not get here } - std::vector::iterator prevStepIterator = lowerBoundIterator - 1; + const std::vector::iterator prevStepIterator = lowerBoundIterator - 1; return *prevStepIterator; } bool TimeManager::hasNextDeltaTimeStep() const { - if (_deltaTimeSteps.empty()) + if (_deltaTimeSteps.empty()) { return false; + } return _targetDeltaTime < _deltaTimeSteps.back(); } bool TimeManager::hasPreviousDeltaTimeStep() const { - if (_deltaTimeSteps.empty()) + if (_deltaTimeSteps.empty()) { return false; + } return _targetDeltaTime > _deltaTimeSteps.front(); } @@ -851,18 +852,20 @@ void TimeManager::setPreviousDeltaTimeStep() { } void TimeManager::interpolateNextDeltaTimeStep(double durationSeconds) { - if (!hasNextDeltaTimeStep()) + if (!hasNextDeltaTimeStep()) { return; + } - double nextDeltaTime = nextDeltaTimeStep().value(); + const double nextDeltaTime = nextDeltaTimeStep().value(); interpolateDeltaTime(nextDeltaTime, durationSeconds); } void TimeManager::interpolatePreviousDeltaTimeStep(double durationSeconds) { - if (!hasPreviousDeltaTimeStep()) + if (!hasPreviousDeltaTimeStep()) { return; + } - double previousDeltaTime = previousDeltaTimeStep().value(); + const double previousDeltaTime = previousDeltaTimeStep().value(); interpolateDeltaTime(previousDeltaTime, durationSeconds); } @@ -875,24 +878,24 @@ void TimeManager::interpolatePause(bool pause, double interpolationDuration) { return; } - OpenSpaceEngine::Mode engineMode = global::openSpaceEngine->currentMode(); + const OpenSpaceEngine::Mode engineMode = global::openSpaceEngine->currentMode(); if (!pause && engineMode == OpenSpaceEngine::Mode::CameraPath) { LERROR("Cannot unpause simulation time during camera path"); return; } - double targetDelta = pause ? 0.0 : _targetDeltaTime; - Time newTime( + const double targetDelta = pause ? 0.0 : _targetDeltaTime; + const Time newTime = Time( time().j2000Seconds() + (_deltaTime + targetDelta) * 0.5 * interpolationDuration ); - TimeKeyframeData currentKeyframe = { + const TimeKeyframeData currentKeyframe = { .time = time(), .delta = _deltaTime, .pause = false, .jump = false }; - TimeKeyframeData futureKeyframe = { + const TimeKeyframeData futureKeyframe = { .time = newTime, .delta = _targetDeltaTime, .pause = pause, @@ -900,7 +903,7 @@ void TimeManager::interpolatePause(bool pause, double interpolationDuration) { }; _timePaused = pause; - double now = isPlayingBackSessionRecording() ? + const double now = isPlayingBackSessionRecording() ? previousApplicationTimeForInterpolation() : currentApplicationTimeForInterpolation(); @@ -942,7 +945,7 @@ void TimeManager::setTimeFromProfile(const Profile& p) { switch (p.time->type) { case Profile::Time::Type::Relative: { - std::string t = Time::currentWallTime(); + const std::string t = Time::currentWallTime(); std::variant t2 = Time::advancedTime(t, p.time->value); ghoul_assert(std::holds_alternative(t2), "Wrong type"); diff --git a/src/util/touch.cpp b/src/util/touch.cpp index f4297bbe3e..e24e5ac33e 100644 --- a/src/util/touch.cpp +++ b/src/util/touch.cpp @@ -39,12 +39,12 @@ TouchInput::TouchInput(size_t touchDeviceId_, size_t fingerId_, float x_, float , timestamp(timestamp_) {} -glm::vec2 TouchInput::screenCoordinates(glm::vec2 resolution) const { +glm::vec2 TouchInput::screenCoordinates(const glm::vec2& resolution) const { return { std::floor(x * resolution.x + 0.5f), std::floor(y * resolution.y + 0.5f) }; } glm::vec2 TouchInput::currentWindowCoordinates() const { - glm::vec2 res = global::windowDelegate->currentSubwindowSize(); + const glm::vec2 res = global::windowDelegate->currentSubwindowSize(); return { std::floor(x * res.x + 0.5f), std::floor(y * res.y + 0.5f) }; } diff --git a/src/util/tstring.cpp b/src/util/tstring.cpp index 6551a33e6e..6eafbdb2c4 100644 --- a/src/util/tstring.cpp +++ b/src/util/tstring.cpp @@ -42,7 +42,7 @@ tstring temporaryString(std::string_view str) { } tstring temporaryString(const char str[]) { - size_t size = strlen(str); + const size_t size = strlen(str); void* ptr = global::memoryManager->TemporaryMemory.do_allocate(size, 8); std::strcpy(reinterpret_cast(ptr), str); return tstring(reinterpret_cast(ptr), size); diff --git a/src/util/universalhelpers.cpp b/src/util/universalhelpers.cpp index 10ff42980d..2dbfd10117 100644 --- a/src/util/universalhelpers.cpp +++ b/src/util/universalhelpers.cpp @@ -32,7 +32,7 @@ double shiftAndScale(double t, double start, double end) { "Values must be 0.0 < start < end < 1.0" ); - double tScaled = t / (end - start) - start; + const double tScaled = t / (end - start) - start; return std::max(0.0, std::min(tScaled, 1.0)); } diff --git a/src/util/versionchecker.cpp b/src/util/versionchecker.cpp index df9a8d853c..bbe89433c0 100644 --- a/src/util/versionchecker.cpp +++ b/src/util/versionchecker.cpp @@ -47,7 +47,7 @@ void VersionChecker::requestLatestVersion(const std::string& url) { std::string operatingSystem = SysCap.component().operatingSystemString(); operatingSystem = ghoul::encodeUrl(operatingSystem); - std::string fullUrl = fmt::format( + std::string fullUrl = std::format( "{}?client_version={}&commit_hash={}&operating_system={}", url, OPENSPACE_VERSION_NUMBER, OPENSPACE_GIT_COMMIT, operatingSystem ); @@ -79,16 +79,16 @@ void VersionChecker::cancel() { if (_request->hasSucceeded()) { _request->wait(); std::vector data = _request->downloadedData(); - std::string versionString(data.begin(), data.end()); + const std::string versionString(data.begin(), data.end()); std::istringstream versionData(versionString); std::string token; std::getline(versionData, token, '.'); - int major = std::atoi(token.c_str()); + const int major = std::atoi(token.c_str()); std::getline(versionData, token, '.'); - int minor = std::atoi(token.c_str()); + const int minor = std::atoi(token.c_str()); std::getline(versionData, token, '.'); - int patch = std::atoi(token.c_str()); + const int patch = std::atoi(token.c_str()); _latestVersion = { major, minor, patch }; _request = nullptr; @@ -100,7 +100,7 @@ void VersionChecker::cancel() { }; if (currentVersion < _latestVersion) { - LINFO(fmt::format( + LINFO(std::format( "Newer OpenSpace version {}.{}.{} is available. " "Currently running {}.{}.{}", _latestVersion->major, @@ -112,7 +112,7 @@ void VersionChecker::cancel() { )); } else { - LINFO(fmt::format( + LINFO(std::format( "OpenSpace version {}.{}.{} is up to date", currentVersion.major, currentVersion.minor, @@ -125,10 +125,11 @@ void VersionChecker::cancel() { _request->cancel(); _request->wait(); std::vector data = _request->downloadedData(); - std::string response(data.begin(), data.end()); - LWARNING(fmt::format( - "Failed to get latest OpenSpace version information from {}", - _request->url() + const std::string response = std::string(data.begin(), data.end()); + LWARNING(std::format( + "Failed to get OpenSpace version information from {}. Response: {}", + _request->url(), + response )); _request = nullptr; return false; diff --git a/support/coding/codegen b/support/coding/codegen index 0a75d05d83..3ad0877c74 160000 --- a/support/coding/codegen +++ b/support/coding/codegen @@ -1 +1 @@ -Subproject commit 0a75d05d833e019bd4f143d932857493b2569681 +Subproject commit 3ad0877c74aa55a98ee24d18ba8335df9e1d4bcb diff --git a/tests/main.cpp b/tests/main.cpp index 64eece4647..7f918ca4d8 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -58,9 +58,9 @@ int main(int argc, char** argv) { ghoul::filesystem::FileSystem::Override::Yes ); - std::filesystem::path configFile = findConfiguration(); + const std::filesystem::path configFile = findConfiguration(); // Register the base path as the directory where 'filename' lives - std::filesystem::path base = configFile.parent_path(); + const std::filesystem::path base = configFile.parent_path(); FileSys.registerPathToken("${BASE}", base); *global::configuration = loadConfigurationFromFile( @@ -82,7 +82,8 @@ int main(int argc, char** argv) { // All of the relevant tests initialize the SpiceManager openspace::SpiceManager::deinitialize(); - int result = Catch::Session().run(argc, argv); + + const int result = Catch::Session().run(argc, argv); // And the deinitialization needs the SpiceManager to be initialized openspace::SpiceManager::initialize(); diff --git a/tests/property/test_property_listproperties.cpp b/tests/property/test_property_listproperties.cpp index 1939ebf17c..c3d95f47e9 100644 --- a/tests/property/test_property_listproperties.cpp +++ b/tests/property/test_property_listproperties.cpp @@ -35,10 +35,10 @@ #include TEST_CASE("StringListProperty: Class Name and Default Value", "[stringlistproperty]") { - openspace::properties::StringListProperty p({ "id", "gui", "desc" }); + const openspace::properties::StringListProperty p({ "id", "gui", "desc" }); CHECK(p.className() == "StringListProperty"); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("StringListProperty: Set Value", "[stringlistproperty]") { @@ -51,7 +51,7 @@ TEST_CASE("StringListProperty: Set Value", "[stringlistproperty]") { // Empty value p.setValue({}); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("StringListProperty: Get String Value", "[stringlistproperty]") { @@ -70,7 +70,7 @@ TEST_CASE("StringListProperty: Set Lua Value", "[stringlistproperty]") { const std::vector list{ "a", "b", "c" }; - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, list); p.setLuaValue(L); @@ -81,17 +81,17 @@ TEST_CASE("StringListProperty: Set Lua Value", "[stringlistproperty]") { TEST_CASE("StringListProperty: Set Lua Value - Empty", "[stringlistproperty]") { openspace::properties::StringListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{}); p.setLuaValue(L); - CHECK(p.value() == std::vector{}); + CHECK(p.value().empty()); } TEST_CASE("StringListProperty: Invalid Set Lua Value - Not List", "[stringlistproperty]") { openspace::properties::StringListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, 2); // Not a list CHECK_THROWS(p.setLuaValue(L)); @@ -103,7 +103,7 @@ TEST_CASE("StringListProperty: Get Lua Value", "[stringlistproperty]") { const std::vector list{ "a", "b", "c" }; p.setValue(list); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == @@ -112,9 +112,9 @@ TEST_CASE("StringListProperty: Get Lua Value", "[stringlistproperty]") { } TEST_CASE("StringListProperty: Get Empty Lua Value", "[stringlistproperty]") { - openspace::properties::StringListProperty p({ "id", "gui", "desc" }); + const openspace::properties::StringListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == "{}"); @@ -132,10 +132,10 @@ TEST_CASE("StringListProperty: Value From Copying Variable", "[stringlistpropert // IntListProperty TEST_CASE("IntListProperty: Class Name and Default Value", "[intlistproperty]") { - openspace::properties::IntListProperty p({ "id", "gui", "desc" }); + const openspace::properties::IntListProperty p({ "id", "gui", "desc" }); CHECK(p.className() == "IntListProperty"); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("IntListProperty: Set Value", "[intlistproperty]") { @@ -148,7 +148,7 @@ TEST_CASE("IntListProperty: Set Value", "[intlistproperty]") { // Empty value p.setValue({}); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("IntListProperty: Get String Value", "[intlistproperty]") { @@ -167,7 +167,7 @@ TEST_CASE("IntListProperty: Set Lua Value", "[intlistproperty]") { const std::vector list{ 1, 2, 3 }; - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, list); p.setLuaValue(L); @@ -178,26 +178,26 @@ TEST_CASE("IntListProperty: Set Lua Value", "[intlistproperty]") { TEST_CASE("IntListProperty: Set Lua Value - Empty", "[intlistproperty]") { openspace::properties::IntListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector()); p.setLuaValue(L); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("IntListProperty: Set Lua Value - Non-number", "[intlistproperty]") { openspace::properties::IntListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{ "not a number", "oops" }); CHECK_THROWS(p.setLuaValue(L)); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("IntListProperty: Invalid Set Lua Value - Not List", "[intlistproperty]") { openspace::properties::IntListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, 2); // Not a list CHECK_THROWS(p.setLuaValue(L)); @@ -209,7 +209,7 @@ TEST_CASE("IntListProperty: Get Lua Value", "[intlistproperty]") { const std::vector list{ 1, 2, 3 }; p.setValue(list); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == @@ -218,9 +218,9 @@ TEST_CASE("IntListProperty: Get Lua Value", "[intlistproperty]") { } TEST_CASE("IntListProperty: Get Empty Lua Value", "[intlistproperty]") { - openspace::properties::IntListProperty p({ "id", "gui", "desc" }); + const openspace::properties::IntListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == "{}"); @@ -238,10 +238,10 @@ TEST_CASE("IntListProperty: Value From Copying Variable", "[intlistproperty]") { // DoubleListProperty TEST_CASE("DoubleListProperty: Class Name and Default Value", "[doublelistproperty]") { - openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); + const openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); CHECK(p.className() == "DoubleListProperty"); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("DoubleListProperty: Set Value", "[doublelistproperty]") { @@ -254,7 +254,7 @@ TEST_CASE("DoubleListProperty: Set Value", "[doublelistproperty]") { // Empty value p.setValue({}); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("DoubleListProperty: Get String Value", "[doublelistproperty]") { @@ -273,7 +273,7 @@ TEST_CASE("DoubleListProperty: Set Lua Value", "[doublelistproperty]") { const std::vector list{ 1.0, 2.0, 3.0 }; - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, list); p.setLuaValue(L); @@ -284,26 +284,26 @@ TEST_CASE("DoubleListProperty: Set Lua Value", "[doublelistproperty]") { TEST_CASE("DoubleListProperty: Set Lua Value - Empty", "[doublelistproperty]") { openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector()); p.setLuaValue(L); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("DoubleListProperty: Set Lua Value - Non-number", "[doublelistproperty]") { openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{"not a number", "oops"}); CHECK_THROWS(p.setLuaValue(L)); - CHECK(p.value() == std::vector()); + CHECK(p.value().empty()); } TEST_CASE("DoubleListProperty: Invalid Set Lua Value - Not List", "[doublelistproperty]") { openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, 2); // Not a list CHECK_THROWS(p.setLuaValue(L)); @@ -315,7 +315,7 @@ TEST_CASE("DoubleListProperty: Get Lua Value", "[doublelistproperty]") { const std::vector list{ 1.0, 2.1, 3.2 }; p.setValue(list); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == @@ -324,9 +324,9 @@ TEST_CASE("DoubleListProperty: Get Lua Value", "[doublelistproperty]") { } TEST_CASE("DoubleListProperty: Get Empty Lua Value", "[doublelistproperty]") { - openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); + const openspace::properties::DoubleListProperty p({ "id", "gui", "desc" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); CHECK(ghoul::lua::luaValueToString(L, 1) == "{}"); diff --git a/tests/property/test_property_optionproperty.cpp b/tests/property/test_property_optionproperty.cpp index 1d52f2644e..061143c7de 100644 --- a/tests/property/test_property_optionproperty.cpp +++ b/tests/property/test_property_optionproperty.cpp @@ -27,7 +27,7 @@ #include TEST_CASE("OptionProperty: No Option", "[optionproperty]") { - openspace::properties::OptionProperty p({ "id", "gui", "desc" }); + const openspace::properties::OptionProperty p({ "id", "gui", "desc" }); CHECK_FALSE(p.hasOption()); } diff --git a/tests/property/test_property_selectionproperty.cpp b/tests/property/test_property_selectionproperty.cpp index 1f4b41654d..6aa34276a7 100644 --- a/tests/property/test_property_selectionproperty.cpp +++ b/tests/property/test_property_selectionproperty.cpp @@ -33,10 +33,10 @@ #include TEST_CASE("SelectionProperty: Class Name and Default Value", "[selectionproperty]") { - openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); + const openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); CHECK(p.className() == "SelectionProperty"); - CHECK(p.value() == std::set()); + CHECK(p.value().empty()); CHECK(p.options().empty()); } @@ -51,7 +51,7 @@ TEST_CASE("SelectionProperty: Set Value", "[selectionproperty]") { // Empty value p.setValue({}); - CHECK(p.value() == std::set()); + CHECK(p.value().empty()); } TEST_CASE("SelectionProperty: Set Value - Invalid Input", "[selectionproperty]") { @@ -133,7 +133,7 @@ TEST_CASE("SelectionProperty: Set Lua Value", "[selectionproperty]") { openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); p.setOptions({ "a", "b", "c" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{ "a", "b" }); p.setLuaValue(L); @@ -145,7 +145,7 @@ TEST_CASE("SelectionProperty: Set Lua Value - Duplicates", "[selectionproperty]" openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); p.setOptions({ "a", "b", "c" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{ "a", "a", "b" }); p.setLuaValue(L); @@ -157,7 +157,7 @@ TEST_CASE("SelectionProperty: Set Lua Value - Invalid Key", "[selectionproperty] openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); p.setOptions({ "a", "b", "c" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; ghoul::lua::push(L, std::vector{ "a", "d" }); p.setLuaValue(L); @@ -172,7 +172,7 @@ TEST_CASE("SelectionProperty: Get Lua Value", "[selectionproperty]") { const std::set list{ "a", "b" }; p.setValue(list); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); ghoul::Dictionary reference; @@ -193,7 +193,7 @@ TEST_CASE("SelectionProperty: Get Empty Lua Value", "[selectionproperty]") { openspace::properties::SelectionProperty p({ "id", "gui", "desc" }); p.setOptions({ "a", "b", "c" }); - ghoul::lua::LuaState L; + const ghoul::lua::LuaState L; p.getLuaValue(L); ghoul::Dictionary res = ghoul::lua::value(L); diff --git a/tests/test_assetloader.cpp b/tests/test_assetloader.cpp index 4856be28c1..c170b506e9 100644 --- a/tests/test_assetloader.cpp +++ b/tests/test_assetloader.cpp @@ -40,35 +40,32 @@ #include TEST_CASE("AssetLoader: Assertion", "[assetloader]") { - openspace::Scene scene(std::make_unique()); - ghoul::lua::LuaState* state = openspace::global::scriptEngine->luaState(); - openspace::AssetManager assetLoader( - state, - absPath("${TESTDIR}/AssetLoaderTest/").string() - ); + using namespace openspace; + + const Scene scene = Scene(std::make_unique()); + ghoul::lua::LuaState* state = global::scriptEngine->luaState(); + AssetManager assetLoader(state, absPath("${TESTDIR}/AssetLoaderTest/")); CHECK_NOTHROW(assetLoader.add("passassertion")); CHECK_NOTHROW(assetLoader.add("failassertion")); } TEST_CASE("AssetLoader: Basic Export Import", "[assetloader]") { - openspace::Scene scene(std::make_unique()); - ghoul::lua::LuaState* state = openspace::global::scriptEngine->luaState(); - openspace::AssetManager assetLoader( - state, - absPath("${TESTDIR}/AssetLoaderTest/").string() - ); + using namespace openspace; + + const Scene scene = Scene(std::make_unique()); + ghoul::lua::LuaState* state = global::scriptEngine->luaState(); + AssetManager assetLoader(state, absPath("${TESTDIR}/AssetLoaderTest/")); CHECK_NOTHROW(assetLoader.add("require")); } TEST_CASE("AssetLoader: Asset Functions", "[assetloader]") { - openspace::Scene scene(std::make_unique()); - ghoul::lua::LuaState* state = openspace::global::scriptEngine->luaState(); - openspace::AssetManager assetLoader( - state, - absPath("${TESTDIR}/AssetLoaderTest/").string() - ); + using namespace openspace; + + const Scene scene = Scene(std::make_unique()); + ghoul::lua::LuaState* state = global::scriptEngine->luaState(); + AssetManager assetLoader(state, absPath("${TESTDIR}/AssetLoaderTest/")); CHECK_NOTHROW(assetLoader.add("assetfunctionsexist")); } diff --git a/tests/test_concurrentqueue.cpp b/tests/test_concurrentqueue.cpp index 64f97e2d7a..36b94498fa 100644 --- a/tests/test_concurrentqueue.cpp +++ b/tests/test_concurrentqueue.cpp @@ -31,6 +31,6 @@ TEST_CASE("ConcurrentQueue: Basic", "[concurrentqueue]") { ConcurrentQueue q1; q1.push(4); - int val = q1.pop(); + const int val = q1.pop(); CHECK(val == 4); } diff --git a/tests/test_distanceconversion.cpp b/tests/test_distanceconversion.cpp index 7c9408d75b..b94bb42787 100644 --- a/tests/test_distanceconversion.cpp +++ b/tests/test_distanceconversion.cpp @@ -31,229 +31,229 @@ using namespace openspace; TEST_CASE("DistanceConversion: Convert to meters", "[distanceconversion]") { - const double unit = 1.0; - double res; + constexpr double Unit = 1.0; + double res = 0.0; - res = convertDistance(unit, DistanceUnit::Nanometer, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Nanometer, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-9)); - res = convertDistance(unit, DistanceUnit::Micrometer, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Micrometer, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-6)); - res = convertDistance(unit, DistanceUnit::Millimeter, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Millimeter, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-3)); - res = convertDistance(unit, DistanceUnit::Centimeter, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Centimeter, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-2)); - res = convertDistance(unit, DistanceUnit::Decimeter, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Decimeter, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-1)); - res = convertDistance(unit, DistanceUnit::Meter, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Meter, DistanceUnit::Meter); CHECK(res == Catch::Approx(1.0)); - res = convertDistance(unit, DistanceUnit::Kilometer, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Kilometer, DistanceUnit::Meter); CHECK(res == Catch::Approx(1000.0)); - res = convertDistance(unit, DistanceUnit::AU, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::AU, DistanceUnit::Meter); CHECK(res == Catch::Approx(1.495978707E11)); - res = convertDistance(unit, DistanceUnit::Lighthour, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Lighthour, DistanceUnit::Meter); CHECK(res == Catch::Approx(1.0799921E12)); - res = convertDistance(unit, DistanceUnit::Lightday, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Lightday, DistanceUnit::Meter); CHECK(res == Catch::Approx(2.591981E13)); - res = convertDistance(unit, DistanceUnit::Lightmonth, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Lightmonth, DistanceUnit::Meter); CHECK(res == Catch::Approx(7.8839421E14)); - res = convertDistance(unit, DistanceUnit::Lightyear, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Lightyear, DistanceUnit::Meter); CHECK(res == Catch::Approx(9.4607304725808E15)); - res = convertDistance(unit, DistanceUnit::Parsec, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Parsec, DistanceUnit::Meter); CHECK(res == Catch::Approx(3.0856776E16)); - res = convertDistance(unit, DistanceUnit::Kiloparsec, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Kiloparsec, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e3 * 3.0856776E16)); - res = convertDistance(unit, DistanceUnit::Megaparsec, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Megaparsec, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e6 * 3.0856776E16)); - res = convertDistance(unit, DistanceUnit::Gigaparsec, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Gigaparsec, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e9 * 3.0856776E16)); - res = convertDistance(unit, DistanceUnit::Thou, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Thou, DistanceUnit::Meter); CHECK(res == Catch::Approx(1e-3 * 0.0254)); - res = convertDistance(unit, DistanceUnit::Inch, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Inch, DistanceUnit::Meter); CHECK(res == Catch::Approx(0.0254)); - res = convertDistance(unit, DistanceUnit::Foot, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Foot, DistanceUnit::Meter); CHECK(res == Catch::Approx(0.3048)); - res = convertDistance(unit, DistanceUnit::Yard, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Yard, DistanceUnit::Meter); CHECK(res == Catch::Approx(0.9144)); - res = convertDistance(unit, DistanceUnit::Chain, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Chain, DistanceUnit::Meter); CHECK(res == Catch::Approx(20.1168)); - res = convertDistance(unit, DistanceUnit::Furlong, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Furlong, DistanceUnit::Meter); CHECK(res == Catch::Approx(10.0 * 20.1168)); - res = convertDistance(unit, DistanceUnit::Mile, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::Mile, DistanceUnit::Meter); CHECK(res == Catch::Approx(1609.344)); - res = convertDistance(unit, DistanceUnit::League, DistanceUnit::Meter); + res = convertDistance(Unit, DistanceUnit::League, DistanceUnit::Meter); CHECK(res == Catch::Approx(3.0 * 1609.344)); } TEST_CASE("DistanceConversion: Convert from meters", "[distanceconversion]") { - const double meters = 1.0; - double res; + constexpr double Meters = 1.0; + double res = 0.0; - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Nanometer); - CHECK(res == Catch::Approx(meters / 1e-9)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Nanometer); + CHECK(res == Catch::Approx(Meters / 1e-9)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Micrometer); - CHECK(res == Catch::Approx(meters / 1e-6)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Micrometer); + CHECK(res == Catch::Approx(Meters / 1e-6)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Millimeter); - CHECK(res == Catch::Approx(meters / 1e-3)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Millimeter); + CHECK(res == Catch::Approx(Meters / 1e-3)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Centimeter); - CHECK(res == Catch::Approx(meters / 1e-2)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Centimeter); + CHECK(res == Catch::Approx(Meters / 1e-2)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Decimeter); - CHECK(res == Catch::Approx(meters / 1e-1)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Decimeter); + CHECK(res == Catch::Approx(Meters / 1e-1)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Meter); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Meter); CHECK(res == Catch::Approx(1.0)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Kilometer); - CHECK(res == Catch::Approx(meters / 1000.0)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Kilometer); + CHECK(res == Catch::Approx(Meters / 1000.0)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::AU); - CHECK(res == Catch::Approx(meters / 1.495978707E11)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::AU); + CHECK(res == Catch::Approx(Meters / 1.495978707E11)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Lighthour); - CHECK(res == Catch::Approx(meters / 1.0799921E12)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Lighthour); + CHECK(res == Catch::Approx(Meters / 1.0799921E12)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Lightday); - CHECK(res == Catch::Approx(meters / 2.591981E13)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Lightday); + CHECK(res == Catch::Approx(Meters / 2.591981E13)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Lightmonth); - CHECK(res == Catch::Approx(meters / 7.8839421E14)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Lightmonth); + CHECK(res == Catch::Approx(Meters / 7.8839421E14)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Lightyear); - CHECK(res == Catch::Approx(meters / 9.4607304725808E15)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Lightyear); + CHECK(res == Catch::Approx(Meters / 9.4607304725808E15)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Parsec); - CHECK(res == Catch::Approx(meters / 3.0856776E16)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Parsec); + CHECK(res == Catch::Approx(Meters / 3.0856776E16)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Kiloparsec); - CHECK(res == Catch::Approx(meters / (1e3 * 3.0856776E16))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Kiloparsec); + CHECK(res == Catch::Approx(Meters / (1e3 * 3.0856776E16))); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Megaparsec); - CHECK(res == Catch::Approx(meters / (1e6 * 3.0856776E16))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Megaparsec); + CHECK(res == Catch::Approx(Meters / (1e6 * 3.0856776E16))); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Gigaparsec); - CHECK(res == Catch::Approx(meters / (1e9 * 3.0856776E16))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Gigaparsec); + CHECK(res == Catch::Approx(Meters / (1e9 * 3.0856776E16))); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Thou); - CHECK(res == Catch::Approx(meters / (1e-3 * 0.0254))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Thou); + CHECK(res == Catch::Approx(Meters / (1e-3 * 0.0254))); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Inch); - CHECK(res == Catch::Approx(meters / 0.0254)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Inch); + CHECK(res == Catch::Approx(Meters / 0.0254)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Foot); - CHECK(res == Catch::Approx(meters / 0.3048)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Foot); + CHECK(res == Catch::Approx(Meters / 0.3048)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Yard); - CHECK(res == Catch::Approx(meters / 0.9144)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Yard); + CHECK(res == Catch::Approx(Meters / 0.9144)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Chain); - CHECK(res == Catch::Approx(meters / 20.1168)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Chain); + CHECK(res == Catch::Approx(Meters / 20.1168)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Furlong); - CHECK(res == Catch::Approx(meters / (10.0 * 20.1168))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Furlong); + CHECK(res == Catch::Approx(Meters / (10.0 * 20.1168))); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::Mile); - CHECK(res == Catch::Approx(meters / 1609.344)); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::Mile); + CHECK(res == Catch::Approx(Meters / 1609.344)); - res = convertDistance(meters, DistanceUnit::Meter, DistanceUnit::League); - CHECK(res == Catch::Approx(meters / (3.0 * 1609.344))); + res = convertDistance(Meters, DistanceUnit::Meter, DistanceUnit::League); + CHECK(res == Catch::Approx(Meters / (3.0 * 1609.344))); } TEST_CASE("DistanceConversion: Cross conversion", "[distanceconversion]") { - const double unit = 1.0; - double res; + constexpr double Unit = 1.0; + double res = 0.0; - res = convertDistance(unit, DistanceUnit::Nanometer, DistanceUnit::Kilometer); + res = convertDistance(Unit, DistanceUnit::Nanometer, DistanceUnit::Kilometer); CHECK(res == Catch::Approx(1e-12)); - res = convertDistance(unit, DistanceUnit::Micrometer, DistanceUnit::Decimeter); + res = convertDistance(Unit, DistanceUnit::Micrometer, DistanceUnit::Decimeter); CHECK(res == Catch::Approx(1e-5)); - res = convertDistance(unit, DistanceUnit::Millimeter, DistanceUnit::Nanometer); + res = convertDistance(Unit, DistanceUnit::Millimeter, DistanceUnit::Nanometer); CHECK(res == Catch::Approx(1e6)); - res = convertDistance(unit, DistanceUnit::Centimeter, DistanceUnit::Micrometer); + res = convertDistance(Unit, DistanceUnit::Centimeter, DistanceUnit::Micrometer); CHECK(res == Catch::Approx(1e4)); - res = convertDistance(unit, DistanceUnit::Decimeter, DistanceUnit::Millimeter); + res = convertDistance(Unit, DistanceUnit::Decimeter, DistanceUnit::Millimeter); CHECK(res == Catch::Approx(1e2)); - res = convertDistance(unit, DistanceUnit::Kilometer, DistanceUnit::Centimeter); + res = convertDistance(Unit, DistanceUnit::Kilometer, DistanceUnit::Centimeter); CHECK(res == Catch::Approx(1e5)); - res = convertDistance(unit, DistanceUnit::AU, DistanceUnit::Parsec); + res = convertDistance(Unit, DistanceUnit::AU, DistanceUnit::Parsec); CHECK(res == Catch::Approx(4.84813681e-6)); - res = convertDistance(unit, DistanceUnit::Lighthour, DistanceUnit::Lightmonth); + res = convertDistance(Unit, DistanceUnit::Lighthour, DistanceUnit::Lightmonth); CHECK(res == Catch::Approx(1.36986305e-3)); - res = convertDistance(unit, DistanceUnit::Lightday, DistanceUnit::Kiloparsec); + res = convertDistance(Unit, DistanceUnit::Lightday, DistanceUnit::Kiloparsec); CHECK(res == Catch::Approx(8.40003829e-7)); - res = convertDistance(unit, DistanceUnit::Lightmonth, DistanceUnit::Lightday); + res = convertDistance(Unit, DistanceUnit::Lightmonth, DistanceUnit::Lightday); CHECK(res == Catch::Approx(30.4166662487)); - res = convertDistance(unit, DistanceUnit::Lightyear, DistanceUnit::Gigaparsec); + res = convertDistance(Unit, DistanceUnit::Lightyear, DistanceUnit::Gigaparsec); CHECK(res == Catch::Approx(3.0660139e-10)); - res = convertDistance(unit, DistanceUnit::Parsec, DistanceUnit::Lightyear); + res = convertDistance(Unit, DistanceUnit::Parsec, DistanceUnit::Lightyear); CHECK(res == Catch::Approx(3.26156379673)); - res = convertDistance(unit, DistanceUnit::Kiloparsec, DistanceUnit::AU); + res = convertDistance(Unit, DistanceUnit::Kiloparsec, DistanceUnit::AU); CHECK(res == Catch::Approx(2.06264806E8)); - res = convertDistance(unit, DistanceUnit::Megaparsec, DistanceUnit::Lighthour); + res = convertDistance(Unit, DistanceUnit::Megaparsec, DistanceUnit::Lighthour); CHECK(res == Catch::Approx(2.85712978826E10)); - res = convertDistance(unit, DistanceUnit::Gigaparsec, DistanceUnit::Megaparsec); + res = convertDistance(Unit, DistanceUnit::Gigaparsec, DistanceUnit::Megaparsec); CHECK(res == Catch::Approx(1e3)); - res = convertDistance(unit, DistanceUnit::Thou, DistanceUnit::Yard); + res = convertDistance(Unit, DistanceUnit::Thou, DistanceUnit::Yard); CHECK(res == Catch::Approx(2.77777778e-5)); - res = convertDistance(unit, DistanceUnit::Inch, DistanceUnit::Foot); + res = convertDistance(Unit, DistanceUnit::Inch, DistanceUnit::Foot); CHECK(res == Catch::Approx(8.33333333e-2)); - res = convertDistance(unit, DistanceUnit::Foot, DistanceUnit::Mile); + res = convertDistance(Unit, DistanceUnit::Foot, DistanceUnit::Mile); CHECK(res == Catch::Approx(1.89393939e-4)); - res = convertDistance(unit, DistanceUnit::Yard, DistanceUnit::Chain); + res = convertDistance(Unit, DistanceUnit::Yard, DistanceUnit::Chain); CHECK(res == Catch::Approx(4.54545455e-2)); - res = convertDistance(unit, DistanceUnit::Chain, DistanceUnit::League); + res = convertDistance(Unit, DistanceUnit::Chain, DistanceUnit::League); CHECK(res == Catch::Approx(4.16666666e-3)); - res = convertDistance(unit, DistanceUnit::Furlong, DistanceUnit::Thou); + res = convertDistance(Unit, DistanceUnit::Furlong, DistanceUnit::Thou); CHECK(res == Catch::Approx(7.92E6)); - res = convertDistance(unit, DistanceUnit::Mile, DistanceUnit::Inch); + res = convertDistance(Unit, DistanceUnit::Mile, DistanceUnit::Inch); CHECK(res == Catch::Approx(6.3360E4)); - res = convertDistance(unit, DistanceUnit::League, DistanceUnit::Furlong); + res = convertDistance(Unit, DistanceUnit::League, DistanceUnit::Furlong); CHECK(res == Catch::Approx(24.0)); } diff --git a/tests/test_documentation.cpp b/tests/test_documentation.cpp index f7bb1983be..d76b851dcd 100644 --- a/tests/test_documentation.cpp +++ b/tests/test_documentation.cpp @@ -277,66 +277,66 @@ TEST_CASE("Documentation: Constructor", "[documentation]") { TEST_CASE("Documentation: Initializer Constructor", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { // Basic Verifiers - {"BoolVerifier", new BoolVerifier, Optional::No }, - {"DoubleVerifier", new DoubleVerifier, Optional::No }, - {"IntVerifier", new IntVerifier, Optional::No }, - {"StringVerifier", new StringVerifier, Optional::No }, - {"IdentifierVerifier", new IdentifierVerifier, Optional::No }, - {"FileVerifier", new FileVerifier, Optional::No }, - {"DirectoryVerifier", new DirectoryVerifier, Optional::No }, - {"DateTimeVerifier", new DateTimeVerifier, Optional::No }, - {"TableVerifier", new TableVerifier, Optional::No }, + { "BoolVerifier", new BoolVerifier, Optional::No }, + { "DoubleVerifier", new DoubleVerifier, Optional::No }, + { "IntVerifier", new IntVerifier, Optional::No }, + { "StringVerifier", new StringVerifier, Optional::No }, + { "IdentifierVerifier", new IdentifierVerifier, Optional::No }, + { "FileVerifier", new FileVerifier, Optional::No }, + { "DirectoryVerifier", new DirectoryVerifier, Optional::No }, + { "DateTimeVerifier", new DateTimeVerifier, Optional::No }, + { "TableVerifier", new TableVerifier, Optional::No }, // Operator Verifiers { "LessDouble", new DoubleLessVerifier(0.0), Optional::No }, { "LessInt", new IntLessVerifier(0), Optional::No }, - {"LessEqualDouble", new DoubleLessEqualVerifier(0.0), Optional::No }, - {"LessEqualInt", new IntLessEqualVerifier(0), Optional::No }, + { "LessEqualDouble", new DoubleLessEqualVerifier(0.0), Optional::No }, + { "LessEqualInt", new IntLessEqualVerifier(0), Optional::No }, - {"GreaterDouble", new DoubleGreaterVerifier(0.0), Optional::No }, - {"GreaterInt", new IntGreaterVerifier(0), Optional::No }, + { "GreaterDouble", new DoubleGreaterVerifier(0.0), Optional::No }, + { "GreaterInt", new IntGreaterVerifier(0), Optional::No }, - {"GreaterEqualDouble", new DoubleGreaterEqualVerifier(0.0), Optional::No }, - {"GreaterEqualInt", new IntGreaterEqualVerifier(0), Optional::No }, + { "GreaterEqualDouble", new DoubleGreaterEqualVerifier(0.0), Optional::No }, + { "GreaterEqualInt", new IntGreaterEqualVerifier(0), Optional::No }, - {"EqualBool", new BoolEqualVerifier(false), Optional::No }, - {"EqualDouble", new DoubleEqualVerifier(0.0), Optional::No }, - {"EqualInt", new IntEqualVerifier(0), Optional::No }, - {"EqualString", new StringEqualVerifier(""), Optional::No }, + { "EqualBool", new BoolEqualVerifier(false), Optional::No }, + { "EqualDouble", new DoubleEqualVerifier(0.0), Optional::No }, + { "EqualInt", new IntEqualVerifier(0), Optional::No }, + { "EqualString", new StringEqualVerifier(""), Optional::No }, - {"UnequalBool", new BoolUnequalVerifier(false), Optional::No }, - {"UnequalDouble", new DoubleUnequalVerifier(0.0), Optional::No }, - {"UnequalInt", new IntUnequalVerifier(0), Optional::No }, - {"UnequalString", new StringUnequalVerifier(""), Optional::No }, + { "UnequalBool", new BoolUnequalVerifier(false), Optional::No }, + { "UnequalDouble", new DoubleUnequalVerifier(0.0), Optional::No }, + { "UnequalInt", new IntUnequalVerifier(0), Optional::No }, + { "UnequalString", new StringUnequalVerifier(""), Optional::No }, // List Verifiers - {"InListBool", new BoolInListVerifier({ true, false }), Optional::No }, - {"InListDouble", new DoubleInListVerifier({ 0.0, 1.0 }), Optional::No }, - {"InListInt", new IntInListVerifier({ 0, 1 }), Optional::No }, - {"InListString", new StringInListVerifier({ "", "a" }), Optional::No }, + { "InListBool", new BoolInListVerifier({ true, false }), Optional::No }, + { "InListDouble", new DoubleInListVerifier({ 0.0, 1.0 }), Optional::No }, + { "InListInt", new IntInListVerifier({ 0, 1 }), Optional::No }, + { "InListString", new StringInListVerifier({ "", "a" }), Optional::No }, - {"NotInListBool", new BoolNotInListVerifier({ true, false }), Optional::No }, - {"NotInListDouble", new DoubleNotInListVerifier({ 0.0, 1.0 }), Optional::No }, - {"NotInListInt", new IntNotInListVerifier({ 0, 1 }), Optional::No }, - {"NotInListString", new StringNotInListVerifier({ "", "a" }), Optional::No }, + { "NotInListBool", new BoolNotInListVerifier({ true, false }), Optional::No }, + { "NotInListDouble", new DoubleNotInListVerifier({ 0.0, 1.0 }), Optional::No }, + { "NotInListInt", new IntNotInListVerifier({ 0, 1 }), Optional::No }, + { "NotInListString", new StringNotInListVerifier({ "", "a" }), Optional::No }, // Range Verifiers - {"InRangeDouble", new DoubleInRangeVerifier(0.0, 1.0), Optional::No }, - {"InRangeInt", new IntInRangeVerifier(0, 1), Optional::No }, + { "InRangeDouble", new DoubleInRangeVerifier(0.0, 1.0), Optional::No }, + { "InRangeInt", new IntInRangeVerifier(0, 1), Optional::No }, - {"InRangeDouble", new DoubleNotInRangeVerifier(0.0, 1.0), Optional::No }, - {"InRangeInt", new IntNotInRangeVerifier(0, 1), Optional::No }, + { "InRangeDouble", new DoubleNotInRangeVerifier(0.0, 1.0), Optional::No }, + { "InRangeInt", new IntNotInRangeVerifier(0, 1), Optional::No }, // Misc Verifiers - {"AnnotationBool", new BoolAnnotationVerifier("Bool"), Optional::No }, - {"AnnotationDouble", new DoubleAnnotationVerifier("Double"), Optional::No }, - {"AnnotationInt", new IntAnnotationVerifier("Int"), Optional::No }, - {"AnnotationString", new StringAnnotationVerifier("String"), Optional::No }, - {"AnnotationTable", new TableAnnotationVerifier("Table"), Optional::No } + { "AnnotationBool", new BoolAnnotationVerifier("Bool"), Optional::No }, + { "AnnotationDouble", new DoubleAnnotationVerifier("Double"), Optional::No }, + { "AnnotationInt", new IntAnnotationVerifier("Int"), Optional::No }, + { "AnnotationString", new StringAnnotationVerifier("String"), Optional::No }, + { "AnnotationTable", new TableAnnotationVerifier("Table"), Optional::No } } }; } @@ -344,7 +344,7 @@ TEST_CASE("Documentation: Initializer Constructor", "[documentation]") { TEST_CASE("Documentation: BoolVerifier", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool", new BoolVerifier, Optional::No } } @@ -352,8 +352,7 @@ TEST_CASE("Documentation: BoolVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Bool", true); - - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -378,7 +377,7 @@ TEST_CASE("Documentation: BoolVerifier", "[documentation]") { TEST_CASE("Documentation: DoubleVerifier", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleVerifier, Optional::No } } @@ -386,8 +385,7 @@ TEST_CASE("Documentation: DoubleVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Double", 0.0); - - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -411,7 +409,7 @@ TEST_CASE("Documentation: DoubleVerifier", "[documentation]") { TEST_CASE("Documentation: IntVerifier", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntVerifier, Optional::No } } @@ -450,7 +448,7 @@ TEST_CASE("Documentation: StringVerifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String", new StringVerifier, Optional::No } } @@ -458,7 +456,7 @@ TEST_CASE("Documentation: StringVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("String", ""s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -483,7 +481,7 @@ TEST_CASE("Documentation: IdentifierVerifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "Identifier", new IdentifierVerifier, Optional::No } } @@ -491,7 +489,7 @@ TEST_CASE("Documentation: IdentifierVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Identifier", "abcdef"s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -548,7 +546,7 @@ TEST_CASE("Documentation: FileVerifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "File", new FileVerifier, Optional::No } } @@ -556,7 +554,7 @@ TEST_CASE("Documentation: FileVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("File", absPath("${TESTDIR}/verifier/dummyfile.txt").string()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -589,7 +587,7 @@ TEST_CASE("Documentation: DirectoryVerifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "Dir", new DirectoryVerifier, Optional::No } } @@ -597,7 +595,7 @@ TEST_CASE("Documentation: DirectoryVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Dir", absPath("${TESTDIR}/verifier").string()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -630,7 +628,7 @@ TEST_CASE("Documentation: DateTimeVerifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "DateTime", new DateTimeVerifier, Optional::No } } @@ -638,7 +636,7 @@ TEST_CASE("Documentation: DateTimeVerifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("DateTime", "1969 07 20 20:17:00"s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -670,7 +668,7 @@ TEST_CASE("Documentation: DateTimeVerifier", "[documentation]") { TEST_CASE("Documentation: TableVerifierType", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Table", new TableVerifier, Optional::No } } @@ -678,7 +676,7 @@ TEST_CASE("Documentation: TableVerifierType", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Table", ghoul::Dictionary()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -703,7 +701,7 @@ TEST_CASE("Documentation: StringListVerifierType", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "StringList", new StringListVerifier, Optional::No } } @@ -717,7 +715,7 @@ TEST_CASE("Documentation: StringListVerifierType", "[documentation]") { inner.setValue("3", "c"s); positive.setValue("StringList", inner); } - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -757,7 +755,7 @@ TEST_CASE("Documentation: IntListVerifierType", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "IntList", new IntListVerifier, Optional::No } } @@ -771,7 +769,7 @@ TEST_CASE("Documentation: IntListVerifierType", "[documentation]") { inner.setValue("3", 3); positive.setValue("IntList", inner); } - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -810,7 +808,7 @@ TEST_CASE("Documentation: MixedVerifiers", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool", new BoolVerifier, Optional::No }, { "Double", new DoubleVerifier, Optional::No }, @@ -826,7 +824,7 @@ TEST_CASE("Documentation: MixedVerifiers", "[documentation]") { positive.setValue("Int", 0); positive.setValue("String", ""s); positive.setValue("Table", ghoul::Dictionary()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -861,7 +859,7 @@ TEST_CASE("Documentation: NestedTables", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "Outer_Int", new IntVerifier, Optional::No }, { "Outer_Table", new TableVerifier({ @@ -899,7 +897,7 @@ TEST_CASE("Documentation: NestedTables", "[documentation]") { } positive.setValue("Outer_Table2", inner); } - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1040,7 +1038,7 @@ TEST_CASE("Documentation: NestedTables", "[documentation]") { TEST_CASE("Documentation: Optional", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool_Force", new BoolVerifier, Optional::No }, { "Bool_Optional", new BoolVerifier, Optional::Yes } @@ -1060,7 +1058,7 @@ TEST_CASE("Documentation: Optional", "[documentation]") { CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); - ghoul::Dictionary negative; + const ghoul::Dictionary negative; TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); @@ -1088,7 +1086,7 @@ TEST_CASE("Documentation: Optional", "[documentation]") { TEST_CASE("Documentation: Required In Optional", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "a", @@ -1130,7 +1128,7 @@ TEST_CASE("Documentation: Required In Optional", "[documentation]") { CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); - ghoul::Dictionary positive3; + const ghoul::Dictionary positive3; positiveRes = testSpecification(doc, positive3); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1141,7 +1139,7 @@ TEST_CASE("Documentation: Required In Optional", "[documentation]") { inner.setValue("c", 2); negative.setValue("a", inner); } - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "a.b"); @@ -1151,7 +1149,7 @@ TEST_CASE("Documentation: Required In Optional", "[documentation]") { TEST_CASE("Documentation: Exhaustive", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntVerifier, Optional::No } } @@ -1159,7 +1157,7 @@ TEST_CASE("Documentation: Exhaustive", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Int", 1); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1183,7 +1181,7 @@ TEST_CASE("Documentation: Exhaustive", "[documentation]") { TEST_CASE("Documentation: Nested Exhaustive", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Table", @@ -1199,7 +1197,7 @@ TEST_CASE("Documentation: Nested Exhaustive", "[documentation]") { inner.setValue("a", 1); positive.setValue("Table", inner); } - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1209,7 +1207,7 @@ TEST_CASE("Documentation: Nested Exhaustive", "[documentation]") { inner.setValue("b", 2.0); negative.setValue("Table", inner); } - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Table.a"); @@ -1219,9 +1217,9 @@ TEST_CASE("Documentation: Nested Exhaustive", "[documentation]") { TEST_CASE("Documentation: Empty Entries Non Exhaustive", "[documentation]") { using namespace openspace::documentation; - Documentation doc; + const Documentation doc; - ghoul::Dictionary positive {}; + const ghoul::Dictionary positive {}; TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1236,7 +1234,7 @@ TEST_CASE("Documentation: Empty Entries Non Exhaustive", "[documentation]") { TEST_CASE("Documentation: Empty Nested Exhaustive", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Table", new TableVerifier(), Optional::No } } @@ -1244,7 +1242,7 @@ TEST_CASE("Documentation: Empty Nested Exhaustive", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Table", ghoul::Dictionary()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -1254,7 +1252,7 @@ TEST_CASE("Documentation: Empty Nested Exhaustive", "[documentation]") { inner.setValue("a", 1); negative.setValue("Table", inner); } - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK(negativeRes.success); CHECK(negativeRes.offenses.empty()); } @@ -1262,7 +1260,7 @@ TEST_CASE("Documentation: Empty Nested Exhaustive", "[documentation]") { TEST_CASE("Documentation: Less Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntLessVerifier(5), Optional::No } } @@ -1270,13 +1268,13 @@ TEST_CASE("Documentation: Less Int", "[documentation]") { ghoul::Dictionary positive; positive.setValue("Int", 0.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Int", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1286,19 +1284,19 @@ TEST_CASE("Documentation: Less Int", "[documentation]") { TEST_CASE("Documentation: Less Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleLessVerifier(5.0), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Double", 0.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Double", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1308,7 +1306,7 @@ TEST_CASE("Documentation: Less Double", "[documentation]") { TEST_CASE("Documentation: LessEqual Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntLessEqualVerifier(5), Optional::No } } }; @@ -1326,7 +1324,7 @@ TEST_CASE("Documentation: LessEqual Int", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Int", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1336,7 +1334,7 @@ TEST_CASE("Documentation: LessEqual Int", "[documentation]") { TEST_CASE("Documentation: LessEqual Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleLessEqualVerifier(5.0), Optional::No } } }; @@ -1354,7 +1352,7 @@ TEST_CASE("Documentation: LessEqual Double", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Double", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1364,19 +1362,19 @@ TEST_CASE("Documentation: LessEqual Double", "[documentation]") { TEST_CASE("Documentation: Greater Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntGreaterVerifier(5), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Int", 10.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Int", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1386,19 +1384,19 @@ TEST_CASE("Documentation: Greater Int", "[documentation]") { TEST_CASE("Documentation: Greater Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleGreaterVerifier(5.0), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Double", 10.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Double", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1408,7 +1406,7 @@ TEST_CASE("Documentation: Greater Double", "[documentation]") { TEST_CASE("Documentation: GreaterEqual Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntGreaterEqualVerifier(5), Optional::No } } }; @@ -1426,7 +1424,7 @@ TEST_CASE("Documentation: GreaterEqual Int", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Int", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1436,7 +1434,7 @@ TEST_CASE("Documentation: GreaterEqual Int", "[documentation]") { TEST_CASE("Documentation: GreaterEqual Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleGreaterEqualVerifier(5.0), Optional::No } } }; @@ -1454,7 +1452,7 @@ TEST_CASE("Documentation: GreaterEqual Double", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Double", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1464,19 +1462,19 @@ TEST_CASE("Documentation: GreaterEqual Double", "[documentation]") { TEST_CASE("Documentation: Equal Bool", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool", new BoolEqualVerifier(true), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Bool", true); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Bool", false); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Bool"); @@ -1486,19 +1484,19 @@ TEST_CASE("Documentation: Equal Bool", "[documentation]") { TEST_CASE("Documentation: Equal Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntEqualVerifier(1), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Int", 1.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Int", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1508,19 +1506,19 @@ TEST_CASE("Documentation: Equal Int", "[documentation]") { TEST_CASE("Documentation: Equal Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleEqualVerifier(1.0), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Double", 1.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Double", 0.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1531,19 +1529,19 @@ TEST_CASE("Documentation: Equal String", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String", new StringEqualVerifier("string"s), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("String", "string"s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("String", "no_string"s); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "String"); @@ -1553,19 +1551,19 @@ TEST_CASE("Documentation: Equal String", "[documentation]") { TEST_CASE("Documentation: Unequal Bool", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool", new BoolUnequalVerifier(true), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Bool", false); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Bool", true); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Bool"); @@ -1575,19 +1573,19 @@ TEST_CASE("Documentation: Unequal Bool", "[documentation]") { TEST_CASE("Documentation: Unequal Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntUnequalVerifier(1), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Int", 0.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Int", 1.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1597,19 +1595,19 @@ TEST_CASE("Documentation: Unequal Int", "[documentation]") { TEST_CASE("Documentation: Unequal Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleUnequalVerifier(1.0), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Double", 0.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Double", 1.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1620,19 +1618,19 @@ TEST_CASE("Documentation: Unequal String", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String", new StringUnequalVerifier("string"s), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("String", "no_string"s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("String", "string"s); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "String"); @@ -1642,19 +1640,19 @@ TEST_CASE("Documentation: Unequal String", "[documentation]") { TEST_CASE("Documentation: List Bool", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool" , new BoolInListVerifier({ true }), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Bool", true); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Bool", false); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Bool"); @@ -1664,7 +1662,7 @@ TEST_CASE("Documentation: List Bool", "[documentation]") { TEST_CASE("Documentation: List Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int" , new IntInListVerifier({ 0, 1, 2 }), Optional::No } } }; @@ -1682,7 +1680,7 @@ TEST_CASE("Documentation: List Int", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Int", 5.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1692,7 +1690,7 @@ TEST_CASE("Documentation: List Int", "[documentation]") { TEST_CASE("Documentation: List Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double" , new DoubleInListVerifier({ 0.0, 1.0, 2.0 }), Optional::No } } @@ -1712,7 +1710,7 @@ TEST_CASE("Documentation: List Double", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Double", 5.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1723,7 +1721,7 @@ TEST_CASE("Documentation: List String", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String" , new StringInListVerifier({ "0"s, "1"s, "2"s }), Optional::No } } @@ -1753,19 +1751,19 @@ TEST_CASE("Documentation: List String", "[documentation]") { TEST_CASE("Documentation: NotList Bool", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool" , new BoolNotInListVerifier({ true }), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Bool", false); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Bool", true); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Bool"); @@ -1775,7 +1773,7 @@ TEST_CASE("Documentation: NotList Bool", "[documentation]") { TEST_CASE("Documentation: NotList Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int" , new IntNotInListVerifier({ 0, 1, 2 }), Optional::No } } }; @@ -1793,7 +1791,7 @@ TEST_CASE("Documentation: NotList Int", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Int", 2.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1803,7 +1801,7 @@ TEST_CASE("Documentation: NotList Int", "[documentation]") { TEST_CASE("Documentation: NotList Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double" , new DoubleNotInListVerifier({ 0.0, 1.0, 2.0 }), Optional::No } } @@ -1823,7 +1821,7 @@ TEST_CASE("Documentation: NotList Double", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Double", 1.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1834,7 +1832,7 @@ TEST_CASE("Documentation: NotList String", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String" , new StringNotInListVerifier({ "0"s, "1"s, "2"s }), Optional::No } } @@ -1854,7 +1852,7 @@ TEST_CASE("Documentation: NotList String", "[documentation]") { ghoul::Dictionary negative; negative.setValue("String", "1"s); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "String"); @@ -1864,19 +1862,19 @@ TEST_CASE("Documentation: NotList String", "[documentation]") { TEST_CASE("Documentation: Annotation Bool", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Bool", new BoolAnnotationVerifier("Bool"), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Bool", true); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Bool", 0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Bool"); @@ -1886,19 +1884,19 @@ TEST_CASE("Documentation: Annotation Bool", "[documentation]") { TEST_CASE("Documentation: Annotation Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new IntAnnotationVerifier("Int"), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Int", 1.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Int", 1.1); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -1908,19 +1906,19 @@ TEST_CASE("Documentation: Annotation Int", "[documentation]") { TEST_CASE("Documentation: Annotation Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new DoubleAnnotationVerifier("Double"), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Double", 0.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Double", true); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -1931,19 +1929,19 @@ TEST_CASE("Documentation: Annotation String", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "String", new StringAnnotationVerifier("String"), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("String", ""s); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("String", 1); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "String"); @@ -1953,19 +1951,19 @@ TEST_CASE("Documentation: Annotation String", "[documentation]") { TEST_CASE("Documentation: Annotation Table", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Table", new TableAnnotationVerifier("Table"), Optional::No } } }; ghoul::Dictionary positive; positive.setValue("Table", ghoul::Dictionary()); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); ghoul::Dictionary negative; negative.setValue("Table", 1); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Table"); @@ -1975,7 +1973,7 @@ TEST_CASE("Documentation: Annotation Table", "[documentation]") { TEST_CASE("Documentation: InRange Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new InRangeVerifier(0, 5), Optional::No } } }; @@ -1999,7 +1997,7 @@ TEST_CASE("Documentation: InRange Int", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Int", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Int"); @@ -2009,7 +2007,7 @@ TEST_CASE("Documentation: InRange Int", "[documentation]") { TEST_CASE("Documentation: InRange Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new InRangeVerifier(0.0, 5.0), Optional::No } } @@ -2041,7 +2039,7 @@ TEST_CASE("Documentation: InRange Double", "[documentation]") { ghoul::Dictionary negative; negative.setValue("Double", 10.0); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "Double"); @@ -2051,7 +2049,7 @@ TEST_CASE("Documentation: InRange Double", "[documentation]") { TEST_CASE("Documentation: NotInRange Int", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Int", new NotInRangeVerifier(0, 5), Optional::No } } }; @@ -2095,7 +2093,7 @@ TEST_CASE("Documentation: NotInRange Int", "[documentation]") { TEST_CASE("Documentation: NotInRange Double", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "Double", new NotInRangeVerifier(0.0, 5.0), Optional::No } } @@ -2141,7 +2139,7 @@ TEST_CASE("Documentation: NotInRange Double", "[documentation]") { TEST_CASE("Documentation: Wildcard", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { DocumentationEntry::Wildcard, new IntVerifier, Optional::No } } }; @@ -2149,7 +2147,7 @@ TEST_CASE("Documentation: Wildcard", "[documentation]") { positive.setValue("a", 1); positive.setValue("b", 2); positive.setValue("c", 3); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2193,7 +2191,7 @@ TEST_CASE("Documentation: Wildcard", "[documentation]") { TEST_CASE("Documentation: Wildcard Mixed", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { DocumentationEntry::Wildcard, new IntVerifier, Optional::No }, { "b", new IntGreaterVerifier(5), Optional::No } @@ -2204,7 +2202,7 @@ TEST_CASE("Documentation: Wildcard Mixed", "[documentation]") { positive.setValue("a", 1.0); positive.setValue("b", 8.0); positive.setValue("c", 3.0); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2262,7 +2260,7 @@ TEST_CASE("Documentation: Wildcard Mixed", "[documentation]") { TEST_CASE("Documentation: Referencing", "[documentation]") { using namespace openspace::documentation; - Documentation referenced = { + const Documentation referenced = { "Referenced Name", "referenced_id", "", @@ -2273,7 +2271,7 @@ TEST_CASE("Documentation: Referencing", "[documentation]") { }; DocEng.addDocumentation(referenced); - Documentation doc = { + const Documentation doc = { .entries = { { "Table", new ReferencingVerifier("referenced_id"), Optional::No } } @@ -2286,7 +2284,7 @@ TEST_CASE("Documentation: Referencing", "[documentation]") { inner.setValue("b", 2.0); positive.setValue("Table", inner); }; - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2312,7 +2310,7 @@ TEST_CASE("Documentation: Referencing", "[documentation]") { CHECK(negativeRes.offenses[0].reason == TestResult::Offense::Reason::WrongType); - Documentation wrongDoc = { + const Documentation wrongDoc = { .entries = { { "Table", new ReferencingVerifier("WRONG"), Optional::No } } @@ -2337,7 +2335,7 @@ TEST_CASE("Documentation: OrOperator", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new OrVerifier({ new StringVerifier, new IntVerifier }), Optional::No } } @@ -2357,7 +2355,7 @@ TEST_CASE("Documentation: OrOperator", "[documentation]") { ghoul::Dictionary negative; negative.setValue("a", false); - TestResult negativeRes = testSpecification(doc, negative); + const TestResult negativeRes = testSpecification(doc, negative); CHECK_FALSE(negativeRes.success); REQUIRE(negativeRes.offenses.size() == 1); CHECK(negativeRes.offenses[0].offender == "a"); @@ -2367,7 +2365,7 @@ TEST_CASE("Documentation: OrOperator", "[documentation]") { TEST_CASE("Documentation: IntVector2Verifier", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new IntVector2Verifier, Optional::No } } @@ -2375,7 +2373,7 @@ TEST_CASE("Documentation: IntVector2Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::ivec2(2)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2404,7 +2402,7 @@ TEST_CASE("Documentation: IntVector2Verifier", "[documentation]") { TEST_CASE("Documentation: DoubleVector2Verifier", "[documentation]") { using namespace openspace::documentation; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleVector2Verifier, Optional::No } } @@ -2412,7 +2410,7 @@ TEST_CASE("Documentation: DoubleVector2Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dvec2(2.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2442,7 +2440,7 @@ TEST_CASE("Documentation: IntVector3Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new IntVector3Verifier, Optional::No } } @@ -2450,7 +2448,7 @@ TEST_CASE("Documentation: IntVector3Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::ivec3(2)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2481,7 +2479,7 @@ TEST_CASE("Documentation: DoubleVector3Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleVector3Verifier, Optional::No } } @@ -2489,7 +2487,7 @@ TEST_CASE("Documentation: DoubleVector3Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dvec3(2.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2520,7 +2518,7 @@ TEST_CASE("Documentation: IntVector4Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new IntVector4Verifier, Optional::No } } @@ -2528,7 +2526,7 @@ TEST_CASE("Documentation: IntVector4Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::ivec4(2)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2560,7 +2558,7 @@ TEST_CASE("Documentation: DoubleVector4Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleVector4Verifier, Optional::No } } @@ -2568,7 +2566,7 @@ TEST_CASE("Documentation: DoubleVector4Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dvec4(2.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2600,7 +2598,7 @@ TEST_CASE("Documentation: DoubleMatrix2x2Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix2x2Verifier, Optional::No } } @@ -2608,7 +2606,7 @@ TEST_CASE("Documentation: DoubleMatrix2x2Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat2x2(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2639,7 +2637,7 @@ TEST_CASE("Documentation: DoubleMatrix2x3Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix2x3Verifier, Optional::No } } @@ -2647,7 +2645,7 @@ TEST_CASE("Documentation: DoubleMatrix2x3Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat2x3(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2678,7 +2676,7 @@ TEST_CASE("Documentation: DoubleMatrix2x4Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix2x4Verifier, Optional::No } } @@ -2686,7 +2684,7 @@ TEST_CASE("Documentation: DoubleMatrix2x4Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat2x4(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2717,7 +2715,7 @@ TEST_CASE("Documentation: DoubleMatrix3x2Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix3x2Verifier, Optional::No } } @@ -2725,7 +2723,7 @@ TEST_CASE("Documentation: DoubleMatrix3x2Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat3x2(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2756,7 +2754,7 @@ TEST_CASE("Documentation: DoubleMatrix3x3Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix3x3Verifier, Optional::No } } @@ -2764,7 +2762,7 @@ TEST_CASE("Documentation: DoubleMatrix3x3Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat3x3(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2795,7 +2793,7 @@ TEST_CASE("Documentation: DoubleMatrix3x4Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix3x4Verifier, Optional::No } } @@ -2803,7 +2801,7 @@ TEST_CASE("Documentation: DoubleMatrix3x4Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat3x4(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2834,7 +2832,7 @@ TEST_CASE("Documentation: DoubleMatrix4x2Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix4x2Verifier, Optional::No } } @@ -2842,7 +2840,7 @@ TEST_CASE("Documentation: DoubleMatrix4x2Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat4x2(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2873,7 +2871,7 @@ TEST_CASE("Documentation: DoubleMatrix4x3Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix4x3Verifier, Optional::No } } @@ -2881,7 +2879,7 @@ TEST_CASE("Documentation: DoubleMatrix4x3Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat4x3(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2912,7 +2910,7 @@ TEST_CASE("Documentation: DoubleMatrix4x4Verifier", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - Documentation doc = { + const Documentation doc = { .entries = { { "a", new DoubleMatrix4x4Verifier, Optional::No } } @@ -2920,7 +2918,7 @@ TEST_CASE("Documentation: DoubleMatrix4x4Verifier", "[documentation]") { ghoul::Dictionary positive; positive.setValue("a", glm::dmat4x4(1.0)); - TestResult positiveRes = testSpecification(doc, positive); + const TestResult positiveRes = testSpecification(doc, positive); CHECK(positiveRes.success); CHECK(positiveRes.offenses.empty()); @@ -2951,126 +2949,126 @@ TEST_CASE("Documentation: Verifier Type Post Conditions", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - CHECK(BoolVerifier().type() != ""); - CHECK(DoubleVerifier().type() != ""); - CHECK(IntVerifier().type() != ""); - CHECK(StringVerifier().type() != ""); - CHECK(TableVerifier().type() != ""); + CHECK(!BoolVerifier().type().empty()); + CHECK(!DoubleVerifier().type().empty()); + CHECK(!IntVerifier().type().empty()); + CHECK(!StringVerifier().type().empty()); + CHECK(!TableVerifier().type().empty()); - CHECK(IntVector2Verifier().type() != ""); - CHECK(DoubleVector2Verifier().type() != ""); - CHECK(IntVector3Verifier().type() != ""); - CHECK(DoubleVector3Verifier().type() != ""); - CHECK(IntVector4Verifier().type() != ""); - CHECK(DoubleVector4Verifier().type() != ""); + CHECK(!IntVector2Verifier().type().empty()); + CHECK(!DoubleVector2Verifier().type().empty()); + CHECK(!IntVector3Verifier().type().empty()); + CHECK(!DoubleVector3Verifier().type().empty()); + CHECK(!IntVector4Verifier().type().empty()); + CHECK(!DoubleVector4Verifier().type().empty()); - CHECK(IntLessVerifier(0).type() != ""); - CHECK(DoubleLessVerifier(0.0).type() != ""); - CHECK(IntLessEqualVerifier(0).type() != ""); - CHECK(DoubleLessEqualVerifier(0.0).type() != ""); - CHECK(IntGreaterVerifier(0).type() != ""); - CHECK(DoubleGreaterVerifier(0.0).type() != ""); - CHECK(IntGreaterEqualVerifier(0).type() != ""); - CHECK(DoubleGreaterEqualVerifier(0.0).type() != ""); + CHECK(!IntLessVerifier(0).type().empty()); + CHECK(!DoubleLessVerifier(0.0).type().empty()); + CHECK(!IntLessEqualVerifier(0).type().empty()); + CHECK(!DoubleLessEqualVerifier(0.0).type().empty()); + CHECK(!IntGreaterVerifier(0).type().empty()); + CHECK(!DoubleGreaterVerifier(0.0).type().empty()); + CHECK(!IntGreaterEqualVerifier(0).type().empty()); + CHECK(!DoubleGreaterEqualVerifier(0.0).type().empty()); - CHECK(BoolEqualVerifier(true).type() != ""); - CHECK(IntEqualVerifier(0).type() != ""); - CHECK(DoubleEqualVerifier(0.0).type() != ""); - CHECK(StringEqualVerifier(""s).type() != ""); - CHECK(BoolUnequalVerifier(true).type() != ""); - CHECK(IntUnequalVerifier(0).type() != ""); - CHECK(DoubleUnequalVerifier(0.0).type() != ""); - CHECK(StringUnequalVerifier(""s).type() != ""); + CHECK(!BoolEqualVerifier(true).type().empty()); + CHECK(!IntEqualVerifier(0).type().empty()); + CHECK(!DoubleEqualVerifier(0.0).type().empty()); + CHECK(!StringEqualVerifier(""s).type().empty()); + CHECK(!BoolUnequalVerifier(true).type().empty()); + CHECK(!IntUnequalVerifier(0).type().empty()); + CHECK(!DoubleUnequalVerifier(0.0).type().empty()); + CHECK(!StringUnequalVerifier(""s).type().empty()); - CHECK(BoolInListVerifier({ true }).type() != ""); - CHECK(IntInListVerifier({ 0 }).type() != ""); - CHECK(DoubleInListVerifier({ 0.0 }).type() != ""); - CHECK(StringInListVerifier({ ""s }).type() != ""); - CHECK(BoolNotInListVerifier({ true }).type() != ""); - CHECK(IntNotInListVerifier({ 0 }).type() != ""); - CHECK(DoubleNotInListVerifier({ 0.0 }).type() != ""); - CHECK(StringNotInListVerifier({ ""s }).type() != ""); + CHECK(!BoolInListVerifier({ true }).type().empty()); + CHECK(!IntInListVerifier({ 0 }).type().empty()); + CHECK(!DoubleInListVerifier({ 0.0 }).type().empty()); + CHECK(!StringInListVerifier({ ""s }).type().empty()); + CHECK(!BoolNotInListVerifier({ true }).type().empty()); + CHECK(!IntNotInListVerifier({ 0 }).type().empty()); + CHECK(!DoubleNotInListVerifier({ 0.0 }).type().empty()); + CHECK(!StringNotInListVerifier({ ""s }).type().empty()); - CHECK(IntInRangeVerifier({ 0, 1 }).type() != ""); - CHECK(DoubleInRangeVerifier({ 0.0, 1.0 }).type() != ""); - CHECK(IntNotInRangeVerifier({ 0, 1 }).type() != ""); - CHECK(DoubleNotInRangeVerifier({ 0.0, 1.0 }).type() != ""); + CHECK(!IntInRangeVerifier({ 0, 1 }).type().empty()); + CHECK(!DoubleInRangeVerifier({ 0.0, 1.0 }).type().empty()); + CHECK(!IntNotInRangeVerifier({ 0, 1 }).type().empty()); + CHECK(!DoubleNotInRangeVerifier({ 0.0, 1.0 }).type().empty()); - CHECK(BoolAnnotationVerifier("A"s).type() != ""); - CHECK(IntAnnotationVerifier("A"s).type() != ""); - CHECK(DoubleAnnotationVerifier("A"s).type() != ""); - CHECK(StringAnnotationVerifier("A"s).type() != ""); - CHECK(TableAnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); - CHECK(AnnotationVerifier("A"s).type() != ""); + CHECK(!BoolAnnotationVerifier("A"s).type().empty()); + CHECK(!IntAnnotationVerifier("A"s).type().empty()); + CHECK(!DoubleAnnotationVerifier("A"s).type().empty()); + CHECK(!StringAnnotationVerifier("A"s).type().empty()); + CHECK(!TableAnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); + CHECK(!AnnotationVerifier("A"s).type().empty()); - CHECK(ReferencingVerifier("identifier"s).type() != ""); + CHECK(!ReferencingVerifier("identifier"s).type().empty()); } TEST_CASE("Documentation: Verifier Documentation Post Conditions", "[documentation]") { using namespace openspace::documentation; using namespace std::string_literals; - CHECK(BoolVerifier().documentation() != ""); - CHECK(DoubleVerifier().documentation() != ""); - CHECK(IntVerifier().documentation() != ""); - CHECK(StringVerifier().documentation() != ""); - CHECK(TableVerifier().documentation() != ""); + CHECK(!BoolVerifier().documentation().empty()); + CHECK(!DoubleVerifier().documentation().empty()); + CHECK(!IntVerifier().documentation().empty()); + CHECK(!StringVerifier().documentation().empty()); + CHECK(!TableVerifier().documentation().empty()); - CHECK(IntVector2Verifier().documentation() != ""); - CHECK(DoubleVector2Verifier().documentation() != ""); - CHECK(IntVector3Verifier().documentation() != ""); - CHECK(DoubleVector3Verifier().documentation() != ""); - CHECK(IntVector4Verifier().documentation() != ""); - CHECK(DoubleVector4Verifier().documentation() != ""); + CHECK(!IntVector2Verifier().documentation().empty()); + CHECK(!DoubleVector2Verifier().documentation().empty()); + CHECK(!IntVector3Verifier().documentation().empty()); + CHECK(!DoubleVector3Verifier().documentation().empty()); + CHECK(!IntVector4Verifier().documentation().empty()); + CHECK(!DoubleVector4Verifier().documentation().empty()); - CHECK(IntLessVerifier(0).documentation() != ""); - CHECK(DoubleLessVerifier(0.0).documentation() != ""); - CHECK(IntLessEqualVerifier(0).documentation() != ""); - CHECK(DoubleLessEqualVerifier(0.0).documentation() != ""); - CHECK(IntGreaterVerifier(0).documentation() != ""); - CHECK(DoubleGreaterVerifier(0.0).documentation() != ""); - CHECK(IntGreaterEqualVerifier(0).documentation() != ""); - CHECK(DoubleGreaterEqualVerifier(0.0).documentation() != ""); + CHECK(!IntLessVerifier(0).documentation().empty()); + CHECK(!DoubleLessVerifier(0.0).documentation().empty()); + CHECK(!IntLessEqualVerifier(0).documentation().empty()); + CHECK(!DoubleLessEqualVerifier(0.0).documentation().empty()); + CHECK(!IntGreaterVerifier(0).documentation().empty()); + CHECK(!DoubleGreaterVerifier(0.0).documentation().empty()); + CHECK(!IntGreaterEqualVerifier(0).documentation().empty()); + CHECK(!DoubleGreaterEqualVerifier(0.0).documentation().empty()); - CHECK(BoolEqualVerifier(true).documentation() != ""); - CHECK(IntEqualVerifier(0).documentation() != ""); - CHECK(DoubleEqualVerifier(0.0).documentation() != ""); - CHECK(StringEqualVerifier(""s).documentation() != ""); - CHECK(BoolUnequalVerifier(true).documentation() != ""); - CHECK(IntUnequalVerifier(0).documentation() != ""); - CHECK(DoubleUnequalVerifier(0.0).documentation() != ""); - CHECK(StringUnequalVerifier(""s).documentation() != ""); + CHECK(!BoolEqualVerifier(true).documentation().empty()); + CHECK(!IntEqualVerifier(0).documentation().empty()); + CHECK(!DoubleEqualVerifier(0.0).documentation().empty()); + CHECK(!StringEqualVerifier(""s).documentation().empty()); + CHECK(!BoolUnequalVerifier(true).documentation().empty()); + CHECK(!IntUnequalVerifier(0).documentation().empty()); + CHECK(!DoubleUnequalVerifier(0.0).documentation().empty()); + CHECK(!StringUnequalVerifier(""s).documentation().empty()); - CHECK(BoolInListVerifier({ true }).documentation() != ""); - CHECK(IntInListVerifier({ 0 }).documentation() != ""); - CHECK(DoubleInListVerifier({ 0.0 }).documentation() != ""); - CHECK(StringInListVerifier({ ""s }).documentation() != ""); - CHECK(BoolNotInListVerifier({ true }).documentation() != ""); - CHECK(IntNotInListVerifier({ 0 }).documentation() != ""); - CHECK(DoubleNotInListVerifier({ 0.0 }).documentation() != ""); - CHECK(StringNotInListVerifier({ ""s }).documentation() != ""); + CHECK(!BoolInListVerifier({ true }).documentation().empty()); + CHECK(!IntInListVerifier({ 0 }).documentation().empty()); + CHECK(!DoubleInListVerifier({ 0.0 }).documentation().empty()); + CHECK(!StringInListVerifier({ ""s }).documentation().empty()); + CHECK(!BoolNotInListVerifier({ true }).documentation().empty()); + CHECK(!IntNotInListVerifier({ 0 }).documentation().empty()); + CHECK(!DoubleNotInListVerifier({ 0.0 }).documentation().empty()); + CHECK(!StringNotInListVerifier({ ""s }).documentation().empty()); - CHECK(IntInRangeVerifier({ 0, 1 }).documentation() != ""); - CHECK(DoubleInRangeVerifier({ 0.0, 1.0 }).documentation() != ""); - CHECK(IntNotInRangeVerifier({ 0, 1 }).documentation() != ""); - CHECK(DoubleNotInRangeVerifier({ 0.0, 1.0 }).documentation() != ""); + CHECK(!IntInRangeVerifier({ 0, 1 }).documentation().empty()); + CHECK(!DoubleInRangeVerifier({ 0.0, 1.0 }).documentation().empty()); + CHECK(!IntNotInRangeVerifier({ 0, 1 }).documentation().empty()); + CHECK(!DoubleNotInRangeVerifier({ 0.0, 1.0 }).documentation().empty()); - CHECK(BoolAnnotationVerifier("A"s).documentation() != ""); - CHECK(IntAnnotationVerifier("A"s).documentation() != ""); - CHECK(DoubleAnnotationVerifier("A"s).documentation() != ""); - CHECK(StringAnnotationVerifier("A"s).documentation() != ""); - CHECK(TableAnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); - CHECK(AnnotationVerifier("A"s).documentation() != ""); + CHECK(!BoolAnnotationVerifier("A"s).documentation().empty()); + CHECK(!IntAnnotationVerifier("A"s).documentation().empty()); + CHECK(!DoubleAnnotationVerifier("A"s).documentation().empty()); + CHECK(!StringAnnotationVerifier("A"s).documentation().empty()); + CHECK(!TableAnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); + CHECK(!AnnotationVerifier("A"s).documentation().empty()); - CHECK(ReferencingVerifier("identifier"s).documentation() != ""); + CHECK(!ReferencingVerifier("identifier"s).documentation().empty()); } diff --git a/tests/test_horizons.cpp b/tests/test_horizons.cpp index d9e37b206a..c87537e1d2 100644 --- a/tests/test_horizons.cpp +++ b/tests/test_horizons.cpp @@ -45,10 +45,10 @@ struct HorizonsTestData { // Avoid repetitive code by using these functions #ifdef OPENSPACE_MODULE_SPACE_ENABLED void testHorizonsAnswer(const HorizonsTestData& data, HorizonsType type, - std::filesystem::path filePath, + const std::filesystem::path& filePath, HorizonsResultCode expectedAnswerCode) { - std::string url = constructHorizonsUrl( + const std::string url = constructHorizonsUrl( type, data.target, data.observer, @@ -57,7 +57,7 @@ void testHorizonsAnswer(const HorizonsTestData& data, HorizonsType type, data.step, data.unit ); - json answer = sendHorizonsRequest(url, filePath); + const json answer = sendHorizonsRequest(url, filePath); HorizonsResultCode code = isValidHorizonsAnswer(answer); CHECK(code == expectedAnswerCode); @@ -67,12 +67,12 @@ void testHorizonsAnswer(const HorizonsTestData& data, HorizonsType type, } void testHorizonsAnswerAndResult(const HorizonsTestData& data, HorizonsType type, - std::filesystem::path filePath, + const std::filesystem::path& filePath, HorizonsResultCode expectedAnswerCode, HorizonsResultCode expectedResultCode, bool shouldDeleteFile = true) { - std::string url = constructHorizonsUrl( + const std::string url = constructHorizonsUrl( type, data.target, data.observer, @@ -89,7 +89,7 @@ void testHorizonsAnswerAndResult(const HorizonsTestData& data, HorizonsType type auto result = answer.find("result"); CHECK(result != answer.end()); - HorizonsFile horizonsFile(filePath, *result); + const HorizonsFile horizonsFile(filePath, *result); HorizonsResultCode resultCode = isValidHorizonsFile(horizonsFile.file()); CHECK(resultCode == expectedResultCode); @@ -100,13 +100,13 @@ void testHorizonsAnswerAndResult(const HorizonsTestData& data, HorizonsType type } } -void testReadingHorizons(HorizonsType type, std::filesystem::path filePath, +void testReadingHorizons(HorizonsType type, const std::filesystem::path& filePath, const double t0, const double x0, const double y0, const double z0, const double t1, const double x1, const double y1, const double z1, const double t2, const double x2, const double y2, const double z2) { // Get files and make sure they exist - std::filesystem::path kernel = absPath("${TESTDIR}/horizonsTest/naif0012.tls"); + const std::filesystem::path kernel = absPath("${TESTDIR}/horizonsTest/naif0012.tls"); CHECK(std::filesystem::is_regular_file(kernel)); CHECK(std::filesystem::is_regular_file(filePath)); @@ -169,8 +169,10 @@ TEST_CASE("HorizonsFile: File size too large", "[horizonsfile]") { data.stop = "2022-07-01 00:00:00"; data.step = "1"; data.unit = "m"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_1.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorSize; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_1.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorSize; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -191,8 +193,10 @@ TEST_CASE("HorizonsFile: Time steps too large", "[horizonsfile]") { data.stop = "2022-07-01 00:00:00"; data.step = "1111111111"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_2.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorSpan; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_2.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorSpan; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -213,8 +217,10 @@ TEST_CASE("HorizonsFile: Outside available time range", "[horizonsfile]") { data.stop = "2000-05-19 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_3.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorTimeRange; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_3.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorTimeRange; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -235,16 +241,18 @@ TEST_CASE("HorizonsFile: No observer", "[horizonsfile]") { data.stop = "2022-05-19 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_4.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorNoObserver; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_4.hrz" + ); + const HorizonsResultCode answer = HorizonsResultCode::ErrorNoObserver; // Test Vector format HorizonsType type = HorizonsType::Vector; - testHorizonsAnswer(data, type, filePath, expectedAnswerCode); + testHorizonsAnswer(data, type, filePath, answer); // Test Observer format type = HorizonsType::Observer; - testHorizonsAnswer(data, type, filePath, expectedAnswerCode); + testHorizonsAnswer(data, type, filePath, answer); #endif // OPENSPACE_MODULE_SPACE_ENABLED } @@ -257,12 +265,14 @@ TEST_CASE("HorizonsFile: Observer and target same", "[horizonsfile]") { data.stop = "2022-05-19 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_5.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::ErrorObserverTargetSame; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_5.hrz" + ); + const HorizonsResultCode answer = HorizonsResultCode::ErrorObserverTargetSame; // This test is only for Observer type format - HorizonsType type = HorizonsType::Observer; - testHorizonsAnswer(data, type, filePath, expectedAnswerCode); + const HorizonsType type = HorizonsType::Observer; + testHorizonsAnswer(data, type, filePath, answer); #endif // OPENSPACE_MODULE_SPACE_ENABLED } @@ -275,16 +285,18 @@ TEST_CASE("HorizonsFile: Multiple observer stations", "[horizonsfile]") { data.stop = "2022-05-19 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_6.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::MultipleObserverStations; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_6.hrz" + ); + const HorizonsResultCode answer = HorizonsResultCode::MultipleObserverStations; // Test Vector format HorizonsType type = HorizonsType::Vector; - testHorizonsAnswer(data, type, filePath, expectedAnswerCode); + testHorizonsAnswer(data, type, filePath, answer); // Test Observer format type = HorizonsType::Observer; - testHorizonsAnswer(data, type, filePath, expectedAnswerCode); + testHorizonsAnswer(data, type, filePath, answer); #endif // OPENSPACE_MODULE_SPACE_ENABLED } @@ -299,9 +311,11 @@ TEST_CASE("HorizonsFile: Multiple observers", "[horizonsfile]") { data.stop = "2022-05-19 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_7.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleObserver; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_7.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleObserver; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -334,9 +348,11 @@ TEST_CASE("HorizonsFile: No target", "[horizonsfile]") { data.stop = "2022-05-20 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_8.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::ErrorNoTarget; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_8.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::ErrorNoTarget; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -369,9 +385,11 @@ TEST_CASE("HorizonsFile: Multiple targets (major bodies)", "[horizonsfile]") { data.stop = "2022-05-20 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_9.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_9.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -404,9 +422,11 @@ TEST_CASE("HorizonsFile: Multiple targets (minor bodies case 1)", "[horizonsfile data.stop = "2022-05-20 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_10.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_10.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -439,9 +459,11 @@ TEST_CASE("HorizonsFile: Multiple targets (minor bodies case 2)", "[horizonsfile data.stop = "2022-05-20 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_11.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_11.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleTarget; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -474,9 +496,11 @@ TEST_CASE("HorizonsFile: Detect multiple observers or targets", "[horizonsfile]" data.stop = "2022-05-23 00:00:00"; data.step = "1"; data.unit = "d"; - std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/horizonstest_12.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleObserver; + const std::filesystem::path filePath = absPath( + "${TESTDIR}/horizonsTest/horizonstest_12.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::MultipleObserver; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -509,10 +533,14 @@ TEST_CASE("HorizonsFile: Valid request and response", "[horizonsfile]") { data.stop = "2022-05-23 00:00:00"; data.step = "12"; data.unit = "h"; - std::filesystem::path filePathVector = absPath("${TESTDIR}/horizonsTest/validVectorFile.hrz"); - std::filesystem::path filePathObserver = absPath("${TESTDIR}/horizonsTest/validObserverFile.hrz"); - HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; - HorizonsResultCode expectedResultCode = HorizonsResultCode::Valid; + const std::filesystem::path filePathVector = absPath( + "${TESTDIR}/horizonsTest/validVectorFile.hrz" + ); + const std::filesystem::path filePathObserver = absPath( + "${TESTDIR}/horizonsTest/validObserverFile.hrz" + ); + const HorizonsResultCode expectedAnswerCode = HorizonsResultCode::Valid; + const HorizonsResultCode expectedResultCode = HorizonsResultCode::Valid; // Test Vector format HorizonsType type = HorizonsType::Vector; @@ -543,12 +571,12 @@ TEST_CASE("HorizonsFile: Valid request and response", "[horizonsfile]") { // Since data can get updated this is tested towards stored files TEST_CASE("HorizonsFile: Parsing time range with time", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - std::filesystem::path filePath = + const std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/timerange_time.hrz"); - HorizonsFile horizonsFile(filePath); + const HorizonsFile horizonsFile(filePath); // Parse time range - std::pair timeRange = horizonsFile.parseValidTimeRange( + const std::pair timeRange = horizonsFile.parseValidTimeRange( "Trajectory files", "************", "Trajectory name" @@ -561,12 +589,12 @@ TEST_CASE("HorizonsFile: Parsing time range with time", "[horizonsfile]") { TEST_CASE("HorizonsFile: Parsing time range without time", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - std::filesystem::path filePath = + const std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/timerange_no_time.hrz"); - HorizonsFile horizonsFile(filePath); + const HorizonsFile horizonsFile(filePath); // Parse time range - std::pair timeRange = horizonsFile.parseValidTimeRange( + const std::pair timeRange = horizonsFile.parseValidTimeRange( "Trajectory files", "************", "Trajectory name", @@ -583,12 +611,12 @@ TEST_CASE("HorizonsFile: Parsing time range without time", "[horizonsfile]") { // Since data can get updated this is tested towards stored files TEST_CASE("HorizonsFile: Parsing multiple matching observers", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - std::filesystem::path filePath = + const std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/parse_multiple_observers.hrz"); - HorizonsFile horizonsFile(filePath); + const HorizonsFile horizonsFile(filePath); // Parse matches - std::vector matches = + const std::vector matches = horizonsFile.parseMatches("Name", "matches", ">MATCH NAME<"); REQUIRE(matches.size() == 3); @@ -606,12 +634,12 @@ TEST_CASE("HorizonsFile: Parsing multiple matching observers", "[horizonsfile]") TEST_CASE("HorizonsFile: Parsing multiple matching targets", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - std::filesystem::path filePath = + const std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/parse_multiple_targets.hrz"); - HorizonsFile horizonsFile(filePath); + const HorizonsFile horizonsFile(filePath); // Parse matches - std::vector matches = + const std::vector matches = horizonsFile.parseMatches("Name", "matches", ">MATCH NAME<"); REQUIRE(matches.size() == 11); @@ -653,13 +681,13 @@ TEST_CASE("HorizonsFile: Parsing multiple matching targets", "[horizonsfile]") { TEST_CASE("HorizonsFile: Parsing multiple matching stations", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - std::filesystem::path filePath = + const std::filesystem::path filePath = absPath("${TESTDIR}/horizonsTest/parse_multiple_stations.hrz"); CHECK(std::filesystem::is_regular_file(filePath)); - HorizonsFile horizonsFile(filePath); + const HorizonsFile horizonsFile(filePath); // Parse matches - std::vector matches = + const std::vector matches = horizonsFile.parseMatches("Observatory Name", "Multiple matching stations found"); REQUIRE(matches.size() == 11); @@ -703,8 +731,8 @@ TEST_CASE("HorizonsFile: Parsing multiple matching stations", "[horizonsfile]") // Test reading of data and compare a recent request with a stored file TEST_CASE("HorizonsFile: Reading Vector data from request", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - HorizonsType type = HorizonsType::Vector; - std::filesystem::path filePathVector = + const HorizonsType type = HorizonsType::Vector; + const std::filesystem::path filePathVector = absPath("${TESTDIR}/horizonsTest/validVectorFile.hrz"); const double t0 = 706449669.18513119; @@ -737,8 +765,8 @@ TEST_CASE("HorizonsFile: Reading Vector data from request", "[horizonsfile]") { TEST_CASE("HorizonsFile: Reading Observer data from request", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - HorizonsType type = HorizonsType::Observer; - std::filesystem::path filePathObserver = + const HorizonsType type = HorizonsType::Observer; + const std::filesystem::path filePathObserver = absPath("${TESTDIR}/horizonsTest/validObserverFile.hrz"); const double t0 = 706449669.18513119; @@ -772,8 +800,8 @@ TEST_CASE("HorizonsFile: Reading Observer data from request", "[horizonsfile]") TEST_CASE("HorizonsFile: Reading Vector data from file", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - HorizonsType type = HorizonsType::Vector; - std::filesystem::path filePathVector = + const HorizonsType type = HorizonsType::Vector; + const std::filesystem::path filePathVector = absPath("${TESTDIR}/horizonsTest/vectorFileTest.hrz"); const double t0 = 706449669.18513119; @@ -802,8 +830,8 @@ TEST_CASE("HorizonsFile: Reading Vector data from file", "[horizonsfile]") { TEST_CASE("HorizonsFile: Reading Observer data from file", "[horizonsfile]") { #ifdef OPENSPACE_MODULE_SPACE_ENABLED - HorizonsType type = HorizonsType::Observer; - std::filesystem::path filePathObserver = + const HorizonsType type = HorizonsType::Observer; + const std::filesystem::path filePathObserver = absPath("${TESTDIR}/horizonsTest/observerFileTest.hrz"); const double t0 = 706449669.18513119; diff --git a/tests/test_jsonformatting.cpp b/tests/test_jsonformatting.cpp index b65f7bbe48..e63a9acfa9 100644 --- a/tests/test_jsonformatting.cpp +++ b/tests/test_jsonformatting.cpp @@ -54,11 +54,11 @@ TEMPLATE_TEST_CASE("FormatJson", "[formatjson]", glm::vec2, glm::vec3, } TEST_CASE("FormatJson - Bool", "[formatjson]") { - bool trueVal = true; - bool falseVal = false; + constexpr bool TrueVal = true; + constexpr bool FalseVal = false; - CHECK(openspace::formatJson(trueVal) == "true"); - CHECK(openspace::formatJson(falseVal) == "false"); + CHECK(openspace::formatJson(TrueVal) == "true"); + CHECK(openspace::formatJson(FalseVal) == "false"); } TEST_CASE("FormatJson - Infinity & Nan", "[formatjson]") { diff --git a/tests/test_latlonpatch.cpp b/tests/test_latlonpatch.cpp index dc585e7187..02897bf3b2 100644 --- a/tests/test_latlonpatch.cpp +++ b/tests/test_latlonpatch.cpp @@ -31,22 +31,22 @@ TEST_CASE("LatLonPatch: findCenterControlPoint", "[latlonpatch]") { using namespace openspace::globebrowsing; - GeodeticPatch patch(0, 0, glm::pi() / 4.f, glm::pi() / 4.f); + const GeodeticPatch patch(0, 0, glm::pi() / 4.f, glm::pi() / 4.f); } TEST_CASE("LatLonPatch: Find Closest Corner", "[latlonpatch]") { using namespace openspace::globebrowsing; constexpr float piOver4 = glm::pi() / 4.f; - Geodetic2 halfSize { piOver4, piOver4 }; - Geodetic2 center { 0, 0 }; - GeodeticPatch patch(center, halfSize); + const Geodetic2 halfSize { piOver4, piOver4 }; + const Geodetic2 center { 0, 0 }; + const GeodeticPatch patch(center, halfSize); constexpr float piOver3 = glm::pi() / 3.f; - Geodetic2 point { piOver3, piOver3 }; + const Geodetic2 point { piOver3, piOver3 }; - Geodetic2 closestCorner = patch.closestCorner(point); - Geodetic2 northEastCorner = patch.corner(NORTH_EAST); + const Geodetic2 closestCorner = patch.closestCorner(point); + const Geodetic2 northEastCorner = patch.corner(NORTH_EAST); CHECK(closestCorner.lat == northEastCorner.lat); CHECK(closestCorner.lon == northEastCorner.lon); @@ -57,14 +57,14 @@ TEST_CASE("LatLonPatch: Find Closest Corner 2", "[latlonpatch]") { constexpr float piOver6 = glm::pi() / 4.f; - Geodetic2 halfSize { 1.1 * piOver6, 1.1 * piOver6 }; - Geodetic2 center { piOver6, piOver6 }; - GeodeticPatch patch(center, halfSize); + const Geodetic2 halfSize { 1.1 * piOver6, 1.1 * piOver6 }; + const Geodetic2 center { piOver6, piOver6 }; + const GeodeticPatch patch(center, halfSize); - Geodetic2 point { 0, 0 }; + constexpr Geodetic2 Point { 0, 0 }; - Geodetic2 closestCorner = patch.closestCorner(point); - Geodetic2 expectedCorner = patch.corner(SOUTH_WEST); + const Geodetic2 closestCorner = patch.closestCorner(Point); + const Geodetic2 expectedCorner = patch.corner(SOUTH_WEST); CHECK(closestCorner.lat == expectedCorner.lat); CHECK(closestCorner.lon == expectedCorner.lon); diff --git a/tests/test_lua_createsinglecolorimage.cpp b/tests/test_lua_createsinglecolorimage.cpp index 64696d47d5..bd0f518523 100644 --- a/tests/test_lua_createsinglecolorimage.cpp +++ b/tests/test_lua_createsinglecolorimage.cpp @@ -37,7 +37,7 @@ TEST_CASE("CreateSingleColorImage: Create image and check return value", "[createsinglecolorimage]") { - std::filesystem::path path = createSingleColorImage( + const std::filesystem::path path = createSingleColorImage( "colorFile", glm::dvec3(1.0, 0.0, 0.0) ); @@ -65,7 +65,7 @@ TEST_CASE("CreateSingleColorImage: Faulty color value (invalid values)", TEST_CASE("CreateSingleColorImage: Check if file was created", "[createsinglecolorimage]") { - std::filesystem::path path = createSingleColorImage( + const std::filesystem::path path = createSingleColorImage( "colorFile2", glm::dvec3(0.0, 1.0, 0.0) ); @@ -73,19 +73,19 @@ TEST_CASE("CreateSingleColorImage: Check if file was created", } TEST_CASE("CreateSingleColorImage: Load created image", "[createsinglecolorimage]") { - std::filesystem::path path = createSingleColorImage( + const std::filesystem::path path = createSingleColorImage( "colorFile", glm::dvec3(1.0, 0.0, 0.0) ); // Read the PPM file and check the image dimensions // (maybe too hard coded, but cannot load a texture here...) - std::ifstream ppmFile(path, std::ifstream::binary); + std::ifstream ppmFile = std::ifstream(path, std::ifstream::binary); REQUIRE(ppmFile.is_open()); std::string version; - unsigned int width; - unsigned int height; + unsigned int width = 0; + unsigned int height = 0; ppmFile >> version >> width >> height; diff --git a/tests/test_profile.cpp b/tests/test_profile.cpp index 7f28f11e43..19255ebe4e 100644 --- a/tests/test_profile.cpp +++ b/tests/test_profile.cpp @@ -36,6 +36,11 @@ #include #include +// clang-tidy is convinced that it is possible to use emplace_back instead of push_back +// for the profiole types, but I haven't been able to convince the Visual Studio +// compiler to agree +// NOLINTBEGIN(modernize-use-emplace) + namespace openspace { bool operator==(const openspace::Profile::Version& lhs, const openspace::Profile::Version& rhs) noexcept @@ -169,15 +174,14 @@ TEST_CASE("Basic Meta (full)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.description = "description"; - meta.author = "author"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; + ref.meta = { + .name = "name", + .version = "version", + .description = "description", + .author = "author", + .url = "url", + .license = "license" + }; CHECK(profile == ref); } @@ -188,9 +192,7 @@ TEST_CASE("Basic Meta (empty)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - ref.meta = meta; + ref.meta = Profile::Meta(); CHECK(profile == ref); } @@ -201,14 +203,14 @@ TEST_CASE("Basic Meta (no name)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; + ref.meta = { + .version = "version", + .description = "description", + .author = "author", + .url = "url", + .license = "license" + }; - Profile::Meta meta; - meta.version = "version"; - meta.description = "description"; - meta.author = "author"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; CHECK(profile == ref); } @@ -219,14 +221,13 @@ TEST_CASE("Basic Meta (no version)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.description = "description"; - meta.author = "author"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; + ref.meta = { + .name = "name", + .description = "description", + .author = "author", + .url = "url", + .license = "license" + }; CHECK(profile == ref); } @@ -237,14 +238,13 @@ TEST_CASE("Basic Meta (no description)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.author = "author"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; + ref.meta = { + .name = "name", + .version = "version", + .author = "author", + .url = "url", + .license = "license" + }; CHECK(profile == ref); } @@ -255,14 +255,13 @@ TEST_CASE("Basic Meta (no author)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.description = "description"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; + ref.meta = { + .name = "name", + .version = "version", + .description = "description", + .url = "url", + .license = "license" + }; CHECK(profile == ref); } @@ -273,14 +272,13 @@ TEST_CASE("Basic Meta (no url)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.description = "description"; - meta.author = "author"; - meta.license = "license"; - ref.meta = meta; + ref.meta = { + .name = "name", + .version = "version", + .description = "description", + .author = "author", + .license = "license" + }; CHECK(profile == ref); } @@ -291,14 +289,13 @@ TEST_CASE("Basic Meta (no license)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.description = "description"; - meta.author = "author"; - meta.url = "url"; - ref.meta = meta; + ref.meta = { + .name = "name", + .version = "version", + .description = "description", + .author = "author", + .url = "url" + }; CHECK(profile == ref); } @@ -309,31 +306,22 @@ TEST_CASE("Basic Module", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - { - Profile::Module m; - m.name = "abs-module"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "def-module"; - m.loadedInstruction = "instr"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "ghi-module"; - m.notLoadedInstruction = "not_instr"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "jkl-module"; - m.loadedInstruction = "instr"; - m.notLoadedInstruction = "not_instr"; - ref.modules.push_back(m); - } + ref.modules.push_back({ + .name = "abs-module" + }); + ref.modules.push_back({ + .name = "def-module", + .loadedInstruction = "instr" + }); + ref.modules.push_back({ + .name = "ghi-module", + .notLoadedInstruction = "not_instr" + }); + ref.modules.push_back({ + .name = "jkl-module", + .loadedInstruction = "instr", + .notLoadedInstruction = "not_instr" + }); CHECK(profile == ref); } @@ -344,10 +332,9 @@ TEST_CASE("Basic Assets", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - ref.assets.push_back("folder1/folder2/asset"); - ref.assets.push_back("folder3/folder4/asset2"); - ref.assets.push_back("folder5/folder6/asset3"); + ref.assets.emplace_back("folder1/folder2/asset"); + ref.assets.emplace_back("folder3/folder4/asset2"); + ref.assets.emplace_back("folder5/folder6/asset3"); CHECK(profile == ref); } @@ -358,49 +345,36 @@ TEST_CASE("Basic Properties", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_1"; - p.value = "property_value_1"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_2"; - p.value = "property_value_2"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_3"; - p.value = "property_value_3"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_4"; - p.value = "property_value_4"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_5"; - p.value = "property_value_5"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_6"; - p.value = "property_value_6"; - ref.properties.push_back(p); - } + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_1", + .value = "property_value_1" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_2", + .value = "property_value_2" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_3", + .value = "property_value_3" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_4", + .value = "property_value_4" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_5", + .value = "property_value_5" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_6", + .value = "property_value_6" + }); CHECK(profile == ref); } @@ -411,52 +385,44 @@ TEST_CASE("Basic Keybindings", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; + ref.actions.push_back({ + .identifier = "profile.keybind.0", + .documentation = "T documentation", + .name = "T name", + .guiPath = "T Gui-Path", + .isLocal = true, + .script = "T script" + }); + ref.keybindings.push_back({ + .key = { Key::T, KeyModifier::None }, + .action = "profile.keybind.0" + }); - { - Profile::Action a; - a.identifier = "profile.keybind.0"; - a.documentation = "T documentation"; - a.name = "T name"; - a.guiPath = "T Gui-Path"; - a.isLocal = true; - a.script = "T script"; - ref.actions.push_back(a); + ref.actions.push_back({ + .identifier = "profile.keybind.1", + .documentation = "U documentation", + .name = "U name", + .guiPath = "U Gui-Path", + .isLocal = false, + .script = "U script" + }); + ref.keybindings.push_back({ + .key = { Key::U, KeyModifier::None }, + .action = "profile.keybind.1" + }); - Profile::Keybinding k; - k.action = "profile.keybind.0"; - k.key = { Key::T, KeyModifier::None }; - ref.keybindings.push_back(k); - } - { - Profile::Action a; - a.identifier = "profile.keybind.1"; - a.documentation = "U documentation"; - a.name = "U name"; - a.guiPath = "U Gui-Path"; - a.isLocal = false; - a.script = "U script"; - ref.actions.push_back(a); - - Profile::Keybinding k; - k.action = "profile.keybind.1"; - k.key = { Key::U, KeyModifier::None }; - ref.keybindings.push_back(k); - } - { - Profile::Action a; - a.identifier = "profile.keybind.2"; - a.documentation = "CTRL+V documentation"; - a.name = "CTRL+V name"; - a.guiPath = "CTRL+V Gui-Path"; - a.isLocal = false; - a.script = "CTRL+V script"; - ref.actions.push_back(a); - - Profile::Keybinding k; - k.action = "profile.keybind.2"; - k.key = { Key::V, KeyModifier::Control }; - ref.keybindings.push_back(k); - } + ref.actions.push_back({ + .identifier = "profile.keybind.2", + .documentation = "CTRL+V documentation", + .name = "CTRL+V name", + .guiPath = "CTRL+V Gui-Path", + .isLocal = false, + .script = "CTRL+V script" + }); + ref.keybindings.push_back({ + .key = { Key::V, KeyModifier::Control }, + .action = "profile.keybind.2" + }); CHECK(profile == ref); } @@ -467,11 +433,10 @@ TEST_CASE("Basic Time Relative", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Time time; - time.type = Profile::Time::Type::Relative; - time.value = "-1d"; - ref.time = time; + ref.time = { + .type = Profile::Time::Type::Relative, + .value = "-1d" + }; CHECK(profile == ref); } @@ -482,11 +447,10 @@ TEST_CASE("Basic Time Absolute", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::Time time; - time.type = Profile::Time::Type::Absolute; - time.value = "2020-06-01T12:00:00"; - ref.time = time; + ref.time = { + .type = Profile::Time::Type::Absolute, + .value = "2020-06-01T12:00:00" + }; CHECK(profile == ref); } @@ -497,7 +461,6 @@ TEST_CASE("Basic Delta Times", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - ref.deltaTimes.push_back(1.0); ref.deltaTimes.push_back(30.0); ref.deltaTimes.push_back(60.0); @@ -513,16 +476,15 @@ TEST_CASE("Basic Camera NavState (full)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraNavState camera; - camera.anchor = "none"; - camera.aim = "aim"; - camera.referenceFrame = "root"; - camera.position = glm::dvec3(1.0, 2.0, 3.0); - camera.up = glm::dvec3(4.0, 5.0, 6.0); - camera.yaw = 10.0; - camera.pitch = -10.0; - ref.camera = camera; + ref.camera = Profile::CameraNavState { + .anchor = "none", + .aim = "aim", + .referenceFrame = "root", + .position = glm::dvec3(1.0, 2.0, 3.0), + .up = glm::dvec3(4.0, 5.0, 6.0), + .yaw = 10.0, + .pitch = -10.0 + }; CHECK(profile == ref); } @@ -534,15 +496,14 @@ TEST_CASE("Basic Camera NavState (no aim)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraNavState camera; - camera.anchor = "none"; - camera.referenceFrame = "root"; - camera.position = glm::dvec3(1.0, 2.0, 3.0); - camera.up = glm::dvec3(4.0, 5.0, 6.0); - camera.yaw = 10.0; - camera.pitch = -10.0; - ref.camera = camera; + ref.camera = Profile::CameraNavState { + .anchor = "none", + .referenceFrame = "root", + .position = glm::dvec3(1.0, 2.0, 3.0), + .up = glm::dvec3(4.0, 5.0, 6.0), + .yaw = 10.0, + .pitch = -10.0 + }; CHECK(profile == ref); } @@ -554,15 +515,14 @@ TEST_CASE("Basic Camera NavState (no pitch)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraNavState camera; - camera.anchor = "none"; - camera.aim = "aim"; - camera.referenceFrame = "root"; - camera.position = glm::dvec3(1.0, 2.0, 3.0); - camera.up = glm::dvec3(4.0, 5.0, 6.0); - camera.yaw = 10.0; - ref.camera = camera; + ref.camera = Profile::CameraNavState { + .anchor = "none", + .aim = "aim", + .referenceFrame = "root", + .position = glm::dvec3(1.0, 2.0, 3.0), + .up = glm::dvec3(4.0, 5.0, 6.0), + .yaw = 10.0 + }; CHECK(profile == ref); } @@ -574,15 +534,14 @@ TEST_CASE("Basic Camera NavState (no up)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraNavState camera; - camera.anchor = "none"; - camera.aim = "aim"; - camera.referenceFrame = "root"; - camera.position = glm::dvec3(1.0, 2.0, 3.0); - camera.yaw = 10.0; - camera.pitch = -10.0; - ref.camera = camera; + ref.camera = Profile::CameraNavState { + .anchor = "none", + .aim = "aim", + .referenceFrame = "root", + .position = glm::dvec3(1.0, 2.0, 3.0), + .yaw = 10.0, + .pitch = -10.0 + }; CHECK(profile == ref); } @@ -594,15 +553,14 @@ TEST_CASE("Basic Camera NavState (no yaw)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraNavState camera; - camera.anchor = "none"; - camera.aim = "aim"; - camera.referenceFrame = "root"; - camera.position = glm::dvec3(1.0, 2.0, 3.0); - camera.up = glm::dvec3(4.0, 5.0, 6.0); - camera.pitch = -10.0; - ref.camera = camera; + ref.camera = Profile::CameraNavState { + .anchor = "none", + .aim = "aim", + .referenceFrame = "root", + .position = glm::dvec3(1.0, 2.0, 3.0), + .up = glm::dvec3(4.0, 5.0, 6.0), + .pitch = -10.0, + }; CHECK(profile == ref); } @@ -613,12 +571,11 @@ TEST_CASE("Basic Camera GoToGeo (full)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraGoToGeo camera; - camera.anchor = "anchor"; - camera.latitude = 1.0; - camera.longitude = 2.0; - ref.camera = camera; + ref.camera = Profile::CameraGoToGeo { + .anchor = "anchor", + .latitude = 1.0, + .longitude = 2.0 + }; CHECK(profile == ref); } @@ -630,13 +587,12 @@ TEST_CASE("Basic Camera GoToGeo (with altitude)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraGoToGeo camera; - camera.anchor = "anchor"; - camera.latitude = 1.0; - camera.longitude = 2.0; - camera.altitude = 4.0; - ref.camera = camera; + ref.camera = Profile::CameraGoToGeo { + .anchor = "anchor", + .latitude = 1.0, + .longitude = 2.0, + .altitude = 4.0 + }; CHECK(profile == ref); } @@ -648,10 +604,9 @@ TEST_CASE("Basic Camera GoToNode", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraGoToNode camera; - camera.anchor = "anchor"; - ref.camera = camera; + ref.camera = Profile::CameraGoToNode { + .anchor = "anchor" + }; CHECK(profile == ref); } @@ -663,11 +618,10 @@ TEST_CASE("Basic Camera GoToNode (with height)", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - Profile::CameraGoToNode camera; - camera.anchor = "anchor"; - camera.height = 100.0; - ref.camera = camera; + ref.camera = Profile::CameraGoToNode { + .anchor = "anchor", + .height = 100.0 + }; CHECK(profile == ref); } @@ -678,10 +632,9 @@ TEST_CASE("Basic Mark Nodes", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - ref.markNodes.push_back("node-1"); - ref.markNodes.push_back("node-2"); - ref.markNodes.push_back("node-3"); + ref.markNodes.emplace_back("node-1"); + ref.markNodes.emplace_back("node-2"); + ref.markNodes.emplace_back("node-3"); CHECK(profile == ref); } @@ -693,10 +646,9 @@ TEST_CASE("Basic Additional Scripts", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; - - ref.additionalScripts.push_back("script-1"); - ref.additionalScripts.push_back("script-2"); - ref.additionalScripts.push_back("script-3"); + ref.additionalScripts.emplace_back("script-1"); + ref.additionalScripts.emplace_back("script-2"); + ref.additionalScripts.emplace_back("script-3"); CHECK(profile == ref); } @@ -710,163 +662,130 @@ TEST_CASE("Integration Full Test", "[profile]") { Profile ref; ref.version = Profile::CurrentVersion; + ref.meta = { + .name = "name", + .version = "version", + .description = "description", + .author = "author", + .url = "url", + .license = "license" + }; + ref.modules.push_back({ + .name = "abs-module" + }); + ref.modules.push_back({ + .name = "def-module", + .loadedInstruction = "instr" + }); + ref.modules.push_back({ + .name = "ghi-module", + .notLoadedInstruction = "not_instr" + }); + ref.modules.push_back({ + .name = "jkl-module", + .loadedInstruction = "instr", + .notLoadedInstruction = "not_instr" + }); + ref.assets.emplace_back("scene/solarsystem/planets/earth/earth"); + ref.assets.emplace_back("scene/solarsystem/planets/earth/satellites/satellites"); + ref.assets.emplace_back("folder1/folder2/asset"); + ref.assets.emplace_back("folder3/folder4/asset2"); + ref.assets.emplace_back("folder5/folder6/asset3"); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "{earth_satellites}.Renderable.Enabled", + .value = "false" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_1", + .value = "property_value_1" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_2", + .value = "property_value_2" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValue, + .name = "property_name_3", + .value = "property_value_3" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_4", + .value = "property_value_4" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_5", + .value = "property_value_5" + }); + ref.properties.push_back({ + .setType = Profile::Property::SetType::SetPropertyValueSingle, + .name = "property_name_6", + .value = "property_value_6" + }); - Profile::Meta meta; - meta.name = "name"; - meta.version = "version"; - meta.description = "description"; - meta.author = "author"; - meta.url = "url"; - meta.license = "license"; - ref.meta = meta; + ref.actions.push_back({ + .identifier = "profile.keybind.0", + .documentation = "T documentation", + .name = "T name", + .guiPath = "T Gui-Path", + .isLocal = true, + .script = "T script" + }); + ref.keybindings.push_back({ + .key = { Key::T, KeyModifier::None }, + .action = "profile.keybind.0" + }); - { - Profile::Module m; - m.name = "abs-module"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "def-module"; - m.loadedInstruction = "instr"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "ghi-module"; - m.notLoadedInstruction = "not_instr"; - ref.modules.push_back(m); - } - { - Profile::Module m; - m.name = "jkl-module"; - m.loadedInstruction = "instr"; - m.notLoadedInstruction = "not_instr"; - ref.modules.push_back(m); - } + ref.actions.push_back({ + .identifier = "profile.keybind.1", + .documentation = "U documentation", + .name = "U name", + .guiPath = "U Gui-Path", + .isLocal = false, + .script = "U script" + }); + ref.keybindings.push_back({ + .key = { Key::U, KeyModifier::None }, + .action = "profile.keybind.1" + }); - ref.assets.push_back("scene/solarsystem/planets/earth/earth"); - ref.assets.push_back("scene/solarsystem/planets/earth/satellites/satellites"); - ref.assets.push_back("folder1/folder2/asset"); - ref.assets.push_back("folder3/folder4/asset2"); - ref.assets.push_back("folder5/folder6/asset3"); + ref.actions.push_back({ + .identifier = "profile.keybind.2", + .documentation = "CTRL+V documentation", + .name = "CTRL+V name", + .guiPath = "CTRL+V Gui-Path", + .isLocal = false, + .script = "CTRL+V script" + }); + ref.keybindings.push_back({ + .key = { Key::V, KeyModifier::Control }, + .action = "profile.keybind.2" + }); - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "{earth_satellites}.Renderable.Enabled"; - p.value = "false"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_1"; - p.value = "property_value_1"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_2"; - p.value = "property_value_2"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValue; - p.name = "property_name_3"; - p.value = "property_value_3"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_4"; - p.value = "property_value_4"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_5"; - p.value = "property_value_5"; - ref.properties.push_back(p); - } - { - Profile::Property p; - p.setType = Profile::Property::SetType::SetPropertyValueSingle; - p.name = "property_name_6"; - p.value = "property_value_6"; - ref.properties.push_back(p); - } + ref.time = { + .type = Profile::Time::Type::Relative, + .value = "-1d" + }; - { - Profile::Action a; - a.identifier = "profile.keybind.0"; - a.documentation = "T documentation"; - a.name = "T name"; - a.guiPath = "T Gui-Path"; - a.isLocal = true; - a.script = "T script"; - ref.actions.push_back(a); + ref.camera = Profile::CameraGoToGeo { + .anchor = "Earth", + .latitude = 58.5877, + .longitude = 16.1924, + .altitude = 2.0e+07 + }; - Profile::Keybinding k; - k.action = "profile.keybind.0"; - k.key = { Key::T, KeyModifier::None }; - ref.keybindings.push_back(k); - } - { - Profile::Action a; - a.identifier = "profile.keybind.1"; - a.documentation = "U documentation"; - a.name = "U name"; - a.guiPath = "U Gui-Path"; - a.isLocal = false; - a.script = "U script"; - ref.actions.push_back(a); + ref.markNodes.emplace_back("Earth"); + ref.markNodes.emplace_back("Mars"); + ref.markNodes.emplace_back("Moon"); + ref.markNodes.emplace_back("Sun"); - Profile::Keybinding k; - k.action = "profile.keybind.1"; - k.key = { Key::U, KeyModifier::None }; - ref.keybindings.push_back(k); - } - { - Profile::Action a; - a.identifier = "profile.keybind.2"; - a.documentation = "CTRL+V documentation"; - a.name = "CTRL+V name"; - a.guiPath = "CTRL+V Gui-Path"; - a.isLocal = false; - a.script = "CTRL+V script"; - ref.actions.push_back(a); - - Profile::Keybinding k; - k.action = "profile.keybind.2"; - k.key = { Key::V, KeyModifier::Control }; - ref.keybindings.push_back(k); - } - - Profile::Time time; - time.type = Profile::Time::Type::Relative; - time.value = "-1d"; - ref.time = time; - - Profile::CameraGoToGeo camera; - camera.anchor = "Earth"; - camera.latitude = 58.5877; - camera.longitude = 16.1924; - camera.altitude = 2.0e+07; - ref.camera = camera; - - ref.markNodes.push_back("Earth"); - ref.markNodes.push_back("Mars"); - ref.markNodes.push_back("Moon"); - ref.markNodes.push_back("Sun"); - - ref.additionalScripts.push_back("script-1"); - ref.additionalScripts.push_back("script-2"); - ref.additionalScripts.push_back("script-3"); + ref.additionalScripts.emplace_back("script-1"); + ref.additionalScripts.emplace_back("script-2"); + ref.additionalScripts.emplace_back("script-3"); CHECK(profile == ref); } @@ -891,13 +810,13 @@ TEST_CASE("Add asset to empty Profile (ignored)", "[profile]") { profile.ignoreUpdates = true; profile.addAsset("new-asset"); - CHECK(profile.assets.size() == 0); + CHECK(profile.assets.empty()); } TEST_CASE("Add asset to not-empty Profile", "[profile]") { Profile profile; profile.version = Profile::CurrentVersion; - profile.assets.push_back("old-asset"); + profile.assets.emplace_back("old-asset"); profile.addAsset("new-asset"); @@ -909,7 +828,7 @@ TEST_CASE("Add asset to not-empty Profile", "[profile]") { TEST_CASE("Add asset to not-empty Profile (ignored)", "[profile]") { Profile profile; profile.version = Profile::CurrentVersion; - profile.assets.push_back("old-asset"); + profile.assets.emplace_back("old-asset"); profile.ignoreUpdates = true; profile.addAsset("new-asset"); @@ -974,8 +893,8 @@ TEST_CASE("Removing non-exisiting asset", "[profile]") { Profile profile; profile.version = Profile::CurrentVersion; - profile.assets.push_back("asset1"); - profile.assets.push_back("asset3"); + profile.assets.emplace_back("asset1"); + profile.assets.emplace_back("asset3"); CHECK_NOTHROW(profile.removeAsset("unknown-asset")); } @@ -984,8 +903,8 @@ TEST_CASE("Removing non-exisiting asset (ignored)", "[profile]") { Profile profile; profile.version = Profile::CurrentVersion; - profile.assets.push_back("asset1"); - profile.assets.push_back("asset3"); + profile.assets.emplace_back("asset1"); + profile.assets.emplace_back("asset3"); profile.ignoreUpdates = true; CHECK_NOTHROW(profile.removeAsset("unknown-asset")); @@ -1673,3 +1592,5 @@ TEST_CASE("(Error) Camera (GoToNode): Missing value 'anchor'", "[profile]") { // Catch::Matchers::Equals("(profile) 'camera.height' must be a larger than zero") // ); //} + +// NOLINTEND(modernize-use-emplace) diff --git a/tests/test_rawvolumeio.cpp b/tests/test_rawvolumeio.cpp index 4370ce1554..6aa574be19 100644 --- a/tests/test_rawvolumeio.cpp +++ b/tests/test_rawvolumeio.cpp @@ -35,15 +35,15 @@ TEST_CASE("RawVolumeIO: TinyInputOutput", "[rawvolumeio]") { using namespace openspace::volume; - glm::uvec3 dims(1); - float value = 0.5f; + const glm::uvec3 dims = glm::uvec3(1, 1, 1); + const float value = 0.5f; RawVolume vol(dims); vol.set({ 0, 0, 0 }, value); CHECK(vol.get({ 0, 0, 0 }) == value); - std::filesystem::path volumePath = absPath("${TESTDIR}/tinyvolume.rawvolume"); + const std::filesystem::path volumePath = absPath("${TESTDIR}/tinyvolume.rawvolume"); // Write the 1x1x1 volume to disk RawVolumeWriter writer(volumePath.string()); @@ -58,17 +58,18 @@ TEST_CASE("RawVolumeIO: TinyInputOutput", "[rawvolumeio]") { TEST_CASE("RawVolumeIO: BasicInputOutput", "[rawvolumeio]") { using namespace openspace::volume; - glm::uvec3 dims(2, 4, 8); - auto value = [dims](glm::uvec3 v) { + const glm::uvec3 dims = glm::uvec3(2, 4, 8); + auto value = [dims](const glm::uvec3& v) { return static_cast(v.z * dims.z * dims.y + v.y * dims.y + v.x); }; RawVolume vol(dims); - vol.forEachVoxel([&vol, &value](glm::uvec3 x, float) { vol.set(x, value(x)); }); + vol.forEachVoxel( + [&vol, &value](const glm::uvec3& x, float) { vol.set(x, value(x)); } + ); + vol.forEachVoxel([&value](const glm::uvec3& x, float v) { CHECK(v == value(x)); }); - vol.forEachVoxel([&value](glm::uvec3 x, float v) { CHECK(v == value(x)); }); - - std::filesystem::path volumePath = absPath("${TESTDIR}/basicvolume.rawvolume"); + const std::filesystem::path volumePath = absPath("${TESTDIR}/basicvolume.rawvolume"); // Write the 2x4x8 volume to disk RawVolumeWriter writer(volumePath.string()); @@ -76,8 +77,8 @@ TEST_CASE("RawVolumeIO: BasicInputOutput", "[rawvolumeio]") { // Read the 2x4x8 volume and make sure the value is the same. RawVolumeReader reader(volumePath.string(), dims); - std::unique_ptr> storedVolume = reader.read(); - vol.forEachVoxel([&value](glm::uvec3 x, float v) { + const std::unique_ptr> storedVolume = reader.read(); + vol.forEachVoxel([&value](const glm::uvec3& x, float v) { CHECK(v == value(x)); }); } diff --git a/tests/test_scriptscheduler.cpp b/tests/test_scriptscheduler.cpp index 2a7cc2ee9c..0288c26e96 100644 --- a/tests/test_scriptscheduler.cpp +++ b/tests/test_scriptscheduler.cpp @@ -280,16 +280,16 @@ TEST_CASE("ScriptScheduler: Empty", "[scriptscheduler]") { }; // First test if a new ScriptScheduler will return an empty list - for (double t : TestTimes) { + for (const double t : TestTimes) { ScriptScheduler scheduler; - std::vector res = scheduler.progressTo(t); + const std::vector res = scheduler.progressTo(t); CHECK(res.empty()); } // Then test the same thing but keeping the same ScriptScheduler ScriptScheduler scheduler; - for (double t : TestTimes) { - std::vector res = scheduler.progressTo(t); + for (const double t : TestTimes) { + const std::vector res = scheduler.progressTo(t); CHECK(res.empty()); } @@ -398,7 +398,7 @@ TEST_CASE("ScriptScheduler: CurrentTime", "[scriptscheduler]") { -std::numeric_limits::max(), std::numeric_limits::max() }; - for (double t : TestValues) { + for (const double t : TestValues) { ScriptScheduler scheduler; scheduler.progressTo(t); CHECK(t == scheduler.currentTime()); diff --git a/tests/test_settings.cpp b/tests/test_settings.cpp index ade6863421..de869f6988 100644 --- a/tests/test_settings.cpp +++ b/tests/test_settings.cpp @@ -40,14 +40,14 @@ TEST_CASE("Settings Load: Empty", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_empty.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_empty.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -67,14 +67,14 @@ TEST_CASE("Settings Load: Really Empty", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_really-empty.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_really-empty.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -89,13 +89,13 @@ TEST_CASE("Settings Load: Really Empty", "[settings]") { } TEST_CASE("Settings Save: Empty", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_empty.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_empty.json"; - Settings srcSettings; + const Settings srcSettings; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -107,14 +107,14 @@ TEST_CASE("Settings Load: Started Before", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_started-before.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_started-before.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); REQUIRE(settings.hasStartedBefore.has_value()); CHECK(*settings.hasStartedBefore == false); @@ -130,15 +130,15 @@ TEST_CASE("Settings Load: Started Before", "[settings]") { } TEST_CASE("Settings Save: Started Before", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_started-before.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_started-before.json"; - Settings srcSettings = { + const Settings srcSettings = { .hasStartedBefore = false }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -150,14 +150,14 @@ TEST_CASE("Settings Load: Configuration", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_config.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_config.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); REQUIRE(settings.configuration.has_value()); @@ -173,15 +173,15 @@ TEST_CASE("Settings Load: Configuration", "[settings]") { } TEST_CASE("Settings Save: Configuration", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_config.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_config.json"; - Settings srcSettings = { + const Settings srcSettings = { .configuration = "abc" }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -193,14 +193,14 @@ TEST_CASE("Settings Load: Configuration Remember", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_config_remember.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_config_remember.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -216,15 +216,15 @@ TEST_CASE("Settings Load: Configuration Remember", "[settings]") { } TEST_CASE("Settings Save: Configuration Remember", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_config_remember.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_config_remember.json"; - Settings srcSettings = { + const Settings srcSettings = { .rememberLastConfiguration = true }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -236,14 +236,14 @@ TEST_CASE("Settings Load: Profile", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_profile.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_profile.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -259,15 +259,15 @@ TEST_CASE("Settings Load: Profile", "[settings]") { } TEST_CASE("Settings Save: Profile", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_profile.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_profile.json"; - Settings srcSettings = { + const Settings srcSettings = { .profile = "def" }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -279,14 +279,14 @@ TEST_CASE("Settings Load: Profile Remember", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_profile_remember.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_profile_remember.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -302,15 +302,15 @@ TEST_CASE("Settings Load: Profile Remember", "[settings]") { } TEST_CASE("Settings Save: Profile Remember", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_profile.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_profile.json"; - Settings srcSettings = { + const Settings srcSettings = { .rememberLastProfile = false }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -322,14 +322,14 @@ TEST_CASE("Settings Load: Visibility/NoviceUser", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_visibility_novice.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_visibility_novice.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -345,15 +345,15 @@ TEST_CASE("Settings Load: Visibility/NoviceUser", "[settings]") { } TEST_CASE("Settings Save: Visibility/NoviceUser", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_noviceuser.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_noviceuser.json"; - Settings srcSettings = { + const Settings srcSettings = { .visibility = openspace::properties::Property::Visibility::NoviceUser }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -365,14 +365,14 @@ TEST_CASE("Settings Load: Visibility/User", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_visibility_user.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_visibility_user.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -388,15 +388,15 @@ TEST_CASE("Settings Load: Visibility/User", "[settings]") { } TEST_CASE("Settings Save: Visibility/User", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_user.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_user.json"; - Settings srcSettings = { + const Settings srcSettings = { .visibility = openspace::properties::Property::Visibility::User }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -408,14 +408,14 @@ TEST_CASE("Settings Load: Visibility/AdvancedUser", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_visibility_advanced.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_vis_advanced.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -431,15 +431,15 @@ TEST_CASE("Settings Load: Visibility/AdvancedUser", "[settings]") { } TEST_CASE("Settings Save: Visibility/AdvancedUser", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_advanceduser.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_advanceduser.json"; - Settings srcSettings = { + const Settings srcSettings = { .visibility = openspace::properties::Property::Visibility::AdvancedUser }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -451,14 +451,14 @@ TEST_CASE("Settings Load: Visibility/Developer", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_visibility_developer.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_vis_developer.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -474,15 +474,15 @@ TEST_CASE("Settings Load: Visibility/Developer", "[settings]") { } TEST_CASE("Settings Save: Visibility/Developer", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_developer.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_developer.json"; - Settings srcSettings = { + const Settings srcSettings = { .visibility = openspace::properties::Property::Visibility::Developer }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -494,14 +494,14 @@ TEST_CASE("Settings Load: Bypass Launcher", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_bypass.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_bypass.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -517,15 +517,15 @@ TEST_CASE("Settings Load: Bypass Launcher", "[settings]") { } TEST_CASE("Settings Save: Bypass Launcher", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_bypass.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_bypass.json"; - Settings srcSettings = { + const Settings srcSettings = { .bypassLauncher = false }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -537,14 +537,14 @@ TEST_CASE("Settings Load: LayerServer/All", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_layerserver_all.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_layerserver_all.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -560,15 +560,15 @@ TEST_CASE("Settings Load: LayerServer/All", "[settings]") { } TEST_CASE("Settings Save: LayerServer/All", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_layerserver_all.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_layerserver_all.json"; - Settings srcSettings = { + const Settings srcSettings = { .layerServer = openspace::Configuration::LayerServer::All }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -580,14 +580,14 @@ TEST_CASE("Settings Load: LayerServer/NewYork", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_layerserver_newyork.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_layerserver_nyc.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -603,15 +603,15 @@ TEST_CASE("Settings Load: LayerServer/NewYork", "[settings]") { } TEST_CASE("Settings Save: LayerServer/NewYork", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_layerserver_newyork.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_layerserver_nyc.json"; - Settings srcSettings = { + const Settings srcSettings = { .layerServer = openspace::Configuration::LayerServer::NewYork }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -623,14 +623,15 @@ TEST_CASE("Settings Load: LayerServer/Sweden", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_layerserver_sweden.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = + path / "test_settings_load_layerserver_sweden.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -646,15 +647,15 @@ TEST_CASE("Settings Load: LayerServer/Sweden", "[settings]") { } TEST_CASE("Settings Save: LayerServer/Sweden", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_layerserver_sweden.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_layers_sweden.json"; - Settings srcSettings = { + const Settings srcSettings = { .layerServer = openspace::Configuration::LayerServer::Sweden }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -666,14 +667,14 @@ TEST_CASE("Settings Load: LayerServer/Utah", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_layerserver_utah.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_layerserver_utah.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -689,15 +690,15 @@ TEST_CASE("Settings Load: LayerServer/Utah", "[settings]") { } TEST_CASE("Settings Save: LayerServer/Utah", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_layerserver_utah.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_layerserver_utah.json"; - Settings srcSettings = { + const Settings srcSettings = { .layerServer = openspace::Configuration::LayerServer::Utah }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -709,14 +710,14 @@ TEST_CASE("Settings Load: LayerServer/None", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_layerserver_none.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_layerserver_none.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -732,15 +733,15 @@ TEST_CASE("Settings Load: LayerServer/None", "[settings]") { } TEST_CASE("Settings Save: LayerServer/None", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_layerserver_none.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_layerserver_none.json"; - Settings srcSettings = { + const Settings srcSettings = { .layerServer = openspace::Configuration::LayerServer::None }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -754,14 +755,14 @@ TEST_CASE("Settings Load: MRF IsEnabled", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_mrf_isenabled.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_mrf_isenabled.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -777,17 +778,17 @@ TEST_CASE("Settings Load: MRF IsEnabled", "[settings]") { } TEST_CASE("Settings Save: MRF IsEnabled", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_mrf_isenabled.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_mrf_isenabled.json"; - Settings srcSettings = { + const Settings srcSettings = { .mrf = Settings::MRF { .isEnabled = true } }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -801,14 +802,14 @@ TEST_CASE("Settings Load: MRF Location", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_mrf_location.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_mrf_location.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); CHECK(!settings.hasStartedBefore.has_value()); CHECK(!settings.configuration.has_value()); @@ -824,17 +825,17 @@ TEST_CASE("Settings Load: MRF Location", "[settings]") { } TEST_CASE("Settings Save: MRF Location", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_mrf_location.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_mrf_location.json"; - Settings srcSettings = { + const Settings srcSettings = { .mrf = Settings::MRF { .location = "ghi" } }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -857,14 +858,14 @@ TEST_CASE("Settings Load: Full", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_full.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_full.json"; { std::ofstream f(file); f << Source; } - Settings settings = loadSettings(file); + const Settings settings = loadSettings(file); REQUIRE(settings.hasStartedBefore.has_value()); CHECK(*settings.hasStartedBefore == false); @@ -889,10 +890,10 @@ TEST_CASE("Settings Load: Full", "[settings]") { } TEST_CASE("Settings Save: Full", "[settings]") { - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_save_full.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_save_full.json"; - Settings srcSettings = { + const Settings srcSettings = { .hasStartedBefore = false, .configuration = "abc", .rememberLastConfiguration = true, @@ -908,7 +909,7 @@ TEST_CASE("Settings Save: Full", "[settings]") { }; saveSettings(srcSettings, file); - Settings cmpSettings = loadSettings(file); + const Settings cmpSettings = loadSettings(file); CHECK(srcSettings == cmpSettings); } @@ -919,8 +920,8 @@ TEST_CASE("Settings Load Fail: Illegal version", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_illegal_version.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_illegal_ver.json"; { std::ofstream f(file); f << Source; @@ -937,8 +938,8 @@ TEST_CASE("Settings Load Fail: Started before", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_started-before.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_start-before.json"; { std::ofstream f(file); f << Source; @@ -955,8 +956,8 @@ TEST_CASE("Settings Load Fail: Config", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_config.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_config.json"; { std::ofstream f(file); f << Source; @@ -973,8 +974,8 @@ TEST_CASE("Settings Load Fail: Profile", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_profile.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_profile.json"; { std::ofstream f(file); f << Source; @@ -991,8 +992,8 @@ TEST_CASE("Settings Load Fail: Visibility type", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_visibility_type.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_vis_type.json"; { std::ofstream f(file); f << Source; @@ -1009,8 +1010,8 @@ TEST_CASE("Settings Load Fail: Visibility value", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_visibility_value.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_vis_value.json"; { std::ofstream f(file); f << Source; @@ -1027,8 +1028,8 @@ TEST_CASE("Settings Load Fail: Bypass Launcher", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_bypass.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_bypass.json"; { std::ofstream f(file); f << Source; @@ -1045,8 +1046,9 @@ TEST_CASE("Settings Load Fail: LayerServer type", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_layerserver_type.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = + path / "test_settings_load_fail_layerserver_type.json"; { std::ofstream f(file); f << Source; @@ -1063,8 +1065,8 @@ TEST_CASE("Settings Load Fail: LayerServer value", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_layerserver_value.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_layer_value.json"; { std::ofstream f(file); f << Source; @@ -1081,8 +1083,8 @@ TEST_CASE("Settings Load Fail: MRF", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_mrf.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_mrf.json"; { std::ofstream f(file); f << Source; @@ -1101,8 +1103,8 @@ TEST_CASE("Settings Load Fail: MRF/enabled", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_mrf_enabled.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_mrf_enabled.json"; { std::ofstream f(file); f << Source; @@ -1121,8 +1123,8 @@ TEST_CASE("Settings Load Fail: MRF/location", "[settings]") { } )"; - std::filesystem::path path = std::filesystem::temp_directory_path(); - std::filesystem::path file = path / "test_settings_load_fail_mrf_location.json"; + const std::filesystem::path path = std::filesystem::temp_directory_path(); + const std::filesystem::path file = path / "test_settings_load_fail_mrf_location.json"; { std::ofstream f(file); f << Source; diff --git a/tests/test_sgctedit.cpp b/tests/test_sgctedit.cpp index 3e56f0da30..283cbcf3ac 100644 --- a/tests/test_sgctedit.cpp +++ b/tests/test_sgctedit.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include #include @@ -38,17 +37,16 @@ using namespace openspace; namespace { - std::string stringify(const std::string filename) { - std::ifstream myfile; - myfile.open(filename); + std::string stringify(const std::string& filename) { + const std::ifstream myfile = std::ifstream(filename); std::stringstream buffer; buffer << myfile.rdbuf(); return buffer.str(); } - void attemptValidation(const std::string cfgString) { - std::filesystem::path schemaDir = absPath("${TESTDIR}/../config/schema"); - std::string schemaString = stringify( + void attemptValidation(const std::string& cfgString) { + const std::filesystem::path schemaDir = absPath("${TESTDIR}/../config/schema"); + const std::string schemaString = stringify( schemaDir.string() + "/sgcteditor.schema.json" ); sgct::validateConfigAgainstSchema(cfgString, schemaString, schemaDir); @@ -452,9 +450,9 @@ R"({ TEST_CASE("SgctEdit: minimumVersion", "[sgctedit]") { const sgct::config::GeneratorVersion minVersion { "SgctWindowConfig", 1, 1 }; - std::string inputCfg = + const std::string inputCfg = absPath("${TESTDIR}/sgctedit/fails_minimum_version.json").string(); - sgct::config::GeneratorVersion ver = sgct::readConfigGenerator(inputCfg); + const sgct::config::GeneratorVersion ver = sgct::readConfigGenerator(inputCfg); CHECK_FALSE(ver.versionCheck(minVersion)); } diff --git a/tests/test_spicemanager.cpp b/tests/test_spicemanager.cpp index 2312a1ead5..0b9d8f72ab 100644 --- a/tests/test_spicemanager.cpp +++ b/tests/test_spicemanager.cpp @@ -30,69 +30,60 @@ #include "SpiceUsr.h" #include "SpiceZpr.h" +using namespace openspace; + namespace { - constexpr int FILLEN = 128; - constexpr int TYPLEN = 32; - constexpr int SRCLEN = 128; - - namespace spicemanager_constants { - SpiceInt handle; - char file[FILLEN], filtyp[TYPLEN], source[SRCLEN]; - } // namespace spicemanager_constants - - - // In this testclass only a handset of the testfunctions require a single kernel. // The remaining methods rely on multiple kernels, loaded as a SPICE 'meta-kernel' void loadMetaKernel() { - const int k1 = openspace::SpiceManager::ref().loadKernel( + const int k1 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/naif0008.tls").string() ); CHECK(k1 == 1); - const int k2 = openspace::SpiceManager::ref().loadKernel( + const int k2 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/cas00084.tsc").string() ); CHECK(k2 == 2); - const int k3 = openspace::SpiceManager::ref().loadKernel( + const int k3 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/981005_PLTEPH-DE405S.bsp").string() ); CHECK(k3 == 3); - const int k4 = openspace::SpiceManager::ref().loadKernel( + const int k4 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/020514_SE_SAT105.bsp").string() ); CHECK(k4 == 4); - const int k5 = openspace::SpiceManager::ref().loadKernel( + const int k5 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/030201AP_SK_SM546_T45.bsp").string() ); CHECK(k5 == 5); - const int k6 = openspace::SpiceManager::ref().loadKernel( + const int k6 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/cas_v37.tf").string() ); CHECK(k6 == 6); - const int k7 = openspace::SpiceManager::ref().loadKernel( + const int k7 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/04135_04171pc_psiv2.bc").string() ); CHECK(k7 == 7); - const int k8 = openspace::SpiceManager::ref().loadKernel( + const int k8 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/cpck05Mar2004.tpc").string() ); CHECK(k8 == 8); - const int k9 = openspace::SpiceManager::ref().loadKernel( + const int k9 = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/cas_iss_v09.ti").string() ); CHECK(k9 == 9); } int loadLSKKernel() { - int kernelID = openspace::SpiceManager::ref().loadKernel( + const int kernelID = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/naif0008.tls").string() ); CHECK(kernelID == 1); @@ -100,7 +91,7 @@ namespace { } int loadPCKKernel() { - int kernelID = openspace::SpiceManager::ref().loadKernel( + const int kernelID = SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/cpck05Mar2004.tpc").string() ); CHECK(kernelID == 1); @@ -109,51 +100,66 @@ namespace { } // namespace TEST_CASE("SpiceManager: Load Single Kernel", "[spicemanager]") { - openspace::SpiceManager::initialize(); + constexpr int FileLength = 128; + constexpr int TypeLength = 32; + constexpr int SourceLength = 128; + + SpiceManager::initialize(); loadLSKKernel(); - // naif0008.tls is a text file, check if loaded. - SpiceBoolean found; + + SpiceInt handle = 0; + std::array file; + std::array filtyp; + std::array source; + SpiceBoolean found = SPICEFALSE; kdata_c( 0, "text", - FILLEN, - TYPLEN, - SRCLEN, - spicemanager_constants::file, - spicemanager_constants::filtyp, - spicemanager_constants::source, - &spicemanager_constants::handle, + FileLength, + TypeLength, + SourceLength, + file.data(), + filtyp.data(), + source.data(), + &handle, &found ); - CHECK(found == SPICETRUE); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Unload Kernel String", "[spicemanager]") { - openspace::SpiceManager::initialize(); + constexpr int FileLength = 128; + constexpr int TypeLength = 32; + constexpr int SourceLength = 128; + + SpiceManager::initialize(); loadLSKKernel(); - // naif0008.tls is a text file, check if loaded. - SpiceBoolean found; + + SpiceInt handle = 0; + std::array file; + std::array filtyp; + std::array source; + SpiceBoolean found = SPICEFALSE; kdata_c( 0, "text", - FILLEN, - TYPLEN, - SRCLEN, - spicemanager_constants::file, - spicemanager_constants::filtyp, - spicemanager_constants::source, - &spicemanager_constants::handle, + FileLength, + TypeLength, + SourceLength, + file.data(), + filtyp.data(), + source.data(), + &handle, &found ); CHECK(found == SPICETRUE); // unload using string keyword - openspace::SpiceManager::ref().unloadKernel( + SpiceManager::ref().unloadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/naif0008.tls").string() ); @@ -161,167 +167,168 @@ TEST_CASE("SpiceManager: Unload Kernel String", "[spicemanager]") { kdata_c( 0, "text", - FILLEN, - TYPLEN, - SRCLEN, - spicemanager_constants::file, - spicemanager_constants::filtyp, - spicemanager_constants::source, - &spicemanager_constants::handle, + FileLength, + TypeLength, + SourceLength, + file.data(), + filtyp.data(), + source.data(), + &handle, &found ); CHECK(found != SPICETRUE); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Unload Kernel Integer", "[spicemanager]") { - openspace::SpiceManager::initialize(); + constexpr int FileLength = 128; + constexpr int TypeLength = 32; + constexpr int SourceLength = 128; - int kernelID = loadLSKKernel(); - // naif0008.tls is a text file, check if loaded. - SpiceBoolean found; + SpiceManager::initialize(); + + const int kernelID = loadLSKKernel(); + + SpiceInt handle = 0; + std::array file; + std::array filtyp; + std::array source; + SpiceBoolean found = SPICEFALSE; kdata_c( 0, "text", - FILLEN, - TYPLEN, - SRCLEN, - spicemanager_constants::file, - spicemanager_constants::filtyp, - spicemanager_constants::source, - &spicemanager_constants::handle, + FileLength, + TypeLength, + SourceLength, + file.data(), + filtyp.data(), + source.data(), + &handle, &found ); CHECK(found == SPICETRUE); // unload using unique int ID - openspace::SpiceManager::ref().unloadKernel(kernelID); + SpiceManager::ref().unloadKernel(kernelID); found = SPICEFALSE; kdata_c( 0, "text", - FILLEN, - TYPLEN, - SRCLEN, - spicemanager_constants::file, - spicemanager_constants::filtyp, - spicemanager_constants::source, - &spicemanager_constants::handle, + FileLength, + TypeLength, + SourceLength, + file.data(), + filtyp.data(), + source.data(), + &handle, &found ); CHECK(found != SPICETRUE); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Has Value", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); loadPCKKernel(); - int naifId = 399; // Earth - - std::string kernelPoolValue = "RADII"; - - const bool found = openspace::SpiceManager::ref().hasValue(naifId, kernelPoolValue); + const int naifId = 399; // Earth + const std::string kernelPoolValue = "RADII"; + const bool found = SpiceManager::ref().hasValue(naifId, kernelPoolValue); CHECK(found); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Value From ID 1D", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); loadPCKKernel(); - std::string target = "EARTH"; - std::string value1D = "MAG_NORTH_POLE_LAT"; - + const std::string target = "EARTH"; + const std::string value1D = "MAG_NORTH_POLE_LAT"; double return1D = 0.0; - CHECK_NOTHROW(openspace::SpiceManager::ref().getValue(target, value1D, return1D)); + CHECK_NOTHROW(SpiceManager::ref().getValue(target, value1D, return1D)); CHECK(return1D == 78.565); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Value From ID 3D", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); loadPCKKernel(); - std::string target = "EARTH"; - std::string value3D = "RADII"; - + const std::string target = "EARTH"; + const std::string value3D = "RADII"; glm::dvec3 return3D = glm::dvec3(0.0); - CHECK_NOTHROW(openspace::SpiceManager::ref().getValue(target, value3D, return3D)); + CHECK_NOTHROW(SpiceManager::ref().getValue(target, value3D, return3D)); CHECK(return3D.x == 6378.14); CHECK(return3D.y == 6378.14); CHECK(return3D.z == 6356.75); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Value From ID ND", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); loadPCKKernel(); - std::string target = "SATURN"; - std::string valueND = "RING6_A"; + const std::string target = "SATURN"; + const std::string valueND = "RING6_A"; + std::vector returnND; + returnND.resize(5); + CHECK_NOTHROW(SpiceManager::ref().getValue(target, valueND, returnND)); - std::vector returnND(5); - CHECK_NOTHROW(openspace::SpiceManager::ref().getValue(target, valueND, returnND)); - - std::vector controlVec{ 189870.0, 256900.0, 9000.0, 9000.0, 0.000003 }; + std::vector controlVec = { 189870.0, 256900.0, 9000.0, 9000.0, 0.000003 }; CHECK(controlVec.size() == returnND.size()); - for (unsigned int i = 0; i < returnND.size(); ++i){ + for (unsigned int i = 0; i < returnND.size(); i++) { CHECK(controlVec[i] == returnND[i]); } - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: String To Ephemeris Time", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); loadLSKKernel(); - double ephemerisTime = -1.0; double control_ephemerisTime = 0.0; - char date[SRCLEN] = "Thu Mar 20 12:53:29 PST 1997"; - str2et_c(date, &control_ephemerisTime); + const std::string date = "Thu Mar 20 12:53:29 PST 1997"; + str2et_c(date.c_str(), &control_ephemerisTime); - CHECK_NOTHROW( - ephemerisTime = openspace::SpiceManager::ref().ephemerisTimeFromDate(date) - ); + double ephemerisTime = -1.0; + CHECK_NOTHROW(ephemerisTime = SpiceManager::ref().ephemerisTimeFromDate(date)); CHECK(ephemerisTime == control_ephemerisTime); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Target Position", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); - using openspace::SpiceManager; loadMetaKernel(); + const std::string utctime = "2004 JUN 11 19:32:00"; double et = 0.0; - double pos[3] = { 0.0, 0.0, 0.0 }; - double lt = 0.0; - char utctime[SRCLEN] = "2004 jun 11 19:32:00"; + str2et_c(utctime.c_str(), &et); - str2et_c(utctime, &et); - spkpos_c("EARTH", et, "J2000", "LT+S", "CASSINI", pos, <); + std::array pos = { 0.0, 0.0, 0.0 }; + double lt = 0.0; + spkpos_c("EARTH", et, "J2000", "LT+S", "CASSINI", pos.data(), <); glm::dvec3 targetPosition = glm::dvec3(0.0); double lightTime = 0.0; - SpiceManager::AberrationCorrection corr = { + const SpiceManager::AberrationCorrection corr = { SpiceManager::AberrationCorrection::Type::LightTimeStellar, SpiceManager::AberrationCorrection::Direction::Reception }; @@ -329,7 +336,12 @@ TEST_CASE("SpiceManager: Get Target Position", "[spicemanager]") { CHECK_NOTHROW( [&]() { targetPosition = SpiceManager::ref().targetPosition( - "EARTH", "CASSINI", "J2000", corr, et, lightTime + "EARTH", + "CASSINI", + "J2000", + corr, + et, + lightTime ); }() ); @@ -337,24 +349,23 @@ TEST_CASE("SpiceManager: Get Target Position", "[spicemanager]") { CHECK(pos[1] == Catch::Approx(targetPosition[1])); CHECK(pos[2] == Catch::Approx(targetPosition[2])); - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Target State", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); - using openspace::SpiceManager; loadMetaKernel(); - double et; - double state[6]; - double lt; - char utctime[SRCLEN] = "2004 jun 11 19:32:00"; + double et = 0.0; + const std::string utctime = "2004 JUN 11 19:32:00"; + str2et_c(utctime.c_str(), &et); - str2et_c(utctime, &et); - spkezr_c("EARTH", et, "J2000", "LT+S", "CASSINI", state, <); + std::array state; + double lt = 0.0; + spkezr_c("EARTH", et, "J2000", "LT+S", "CASSINI", state.data(), <); - SpiceManager::AberrationCorrection corr = { + const SpiceManager::AberrationCorrection corr = { SpiceManager::AberrationCorrection::Type::LightTimeStellar, SpiceManager::AberrationCorrection::Direction::Reception }; @@ -364,33 +375,37 @@ TEST_CASE("SpiceManager: Get Target State", "[spicemanager]") { res = SpiceManager::ref().targetState("EARTH", "CASSINI", "J2000", corr, et) ); - // x,y,z for (int i = 0; i < 3; i++){ CHECK(state[i] == Catch::Approx(res.position[i])); CHECK(state[i+3] == Catch::Approx(res.velocity[i])); } - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Transform matrix", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); - loadMetaKernel(); + loadMetaKernel(); - double et; - double state[6]; - double lt; - double referenceMatrix[6][6]; - str2et_c("2004 jun 11 19:32:00", &et); - spkezr_c("PHOEBE", et, "J2000", "LT+S", "CASSINI", state, <); - sxform_c("J2000", "IAU_PHOEBE", et, referenceMatrix); + double et = 0.0; + str2et_c("2004 JUN 11 19:32:00", &et); - openspace::SpiceManager::TransformMatrix stateMatrix; - CHECK_NOTHROW( - stateMatrix = openspace::SpiceManager::ref().stateTransformMatrix( - "J2000", "IAU_PHOEBE", et) + std::array state; + double lt = 0.0; + spkezr_c("PHOEBE", et, "J2000", "LT+S", "CASSINI", state.data(), <); + + std::array referenceMatrix; + sxform_c("J2000", "IAU_PHOEBE", et, referenceMatrix.data()); + + SpiceManager::TransformMatrix stateMatrix; + CHECK_NOTHROW( + stateMatrix = SpiceManager::ref().stateTransformMatrix( + "J2000", + "IAU_PHOEBE", + et + ) ); // check for matrix consistency @@ -400,24 +415,23 @@ TEST_CASE("SpiceManager: Transform matrix", "[spicemanager]") { } } - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Position Transform Matrix", "[spicemanager]") { - openspace::SpiceManager::initialize(); + SpiceManager::initialize(); - using openspace::SpiceManager; loadMetaKernel(); - double et; - double state[3] = { 1.0, 1.0, 1.0 }; - double state_t[3]; - double referenceMatrix[3][3]; - str2et_c("2004 jun 11 19:32:00", &et); - pxform_c("CASSINI_HGA", "J2000", et, referenceMatrix); + double et = 0.0; + str2et_c("2004 JUN 11 19:32:00", &et); + + std::array referenceMatrix; + pxform_c("CASSINI_HGA", "J2000", et, referenceMatrix.data()); glm::dmat3 positionMatrix = glm::dmat3(1.0); + std::array state = { 1.0, 1.0, 1.0 }; glm::dvec3 position(state[0], state[1], state[2]); CHECK_NOTHROW( [&]() { @@ -443,7 +457,8 @@ TEST_CASE("SpiceManager: Get Position Transform Matrix", "[spicemanager]") { #endif // transform reference position into new frame - mxvg_c(referenceMatrix, state, 3, 3, state_t); + std::array stateTransformed; + mxvg_c(referenceMatrix.data(), state.data(), 3, 3, stateTransformed.data()); #if defined __clang__ #pragma clang diagnostic pop @@ -454,32 +469,45 @@ TEST_CASE("SpiceManager: Get Position Transform Matrix", "[spicemanager]") { position = positionMatrix * position; // check transformed values match for (int i = 0; i < 3; i++) { - CHECK(position[i] == Catch::Approx(state_t[i])); + CHECK(position[i] == Catch::Approx(stateTransformed[i])); } - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } TEST_CASE("SpiceManager: Get Field Of View", "[spicemanager]") { - openspace::SpiceManager::initialize(); + constexpr int NameLength = 128; + constexpr int ShapeLength = 32; + + SpiceManager::initialize(); - using openspace::SpiceManager; loadMetaKernel(); - SpiceInt n; - SpiceInt cassini_ID; - double et; - double bounds_ref[5][3]; - char shape_ref[TYPLEN]; - char name_ref[FILLEN]; - double boresightVec[3]; - str2et_c("2004 jun 11 19:32:00", &et); - SpiceBoolean found; - bodn2c_c("CASSINI_ISS_NAC", &cassini_ID, &found); + double et = 0.0; + str2et_c("2004 JUN 11 19:32:00", &et); + + SpiceInt id = 0; + SpiceBoolean found = SPICETRUE; + bodn2c_c("CASSINI_ISS_NAC", &id, &found); CHECK(found == SPICETRUE); - getfov_c(cassini_ID, 5, TYPLEN, TYPLEN, shape_ref, name_ref, boresightVec, &n, bounds_ref); + std::array shapeRef; + std::array nameRef; + std::array boresightVec; + SpiceInt n = 0; + std::array boundsRef; + getfov_c( + id, + 5, + ShapeLength, + NameLength, + shapeRef.data(), + nameRef.data(), + boresightVec.data(), + &n, + boundsRef.data() + ); SpiceManager::FieldOfViewResult res; @@ -490,10 +518,11 @@ TEST_CASE("SpiceManager: Get Field Of View", "[spicemanager]") { for (size_t i = 0; i < res.bounds.size(); i++) { for (size_t j = 0; j < 3; j++) { CHECK( - bounds_ref[i][j] == Catch::Approx(res.bounds[i][static_cast(j)]) + boundsRef[i][j] == + Catch::Approx(res.bounds[i][static_cast(j)]) ); } } - openspace::SpiceManager::deinitialize(); + SpiceManager::deinitialize(); } diff --git a/tests/test_timequantizer.cpp b/tests/test_timequantizer.cpp index 594bfcada6..1a82d0137e 100644 --- a/tests/test_timequantizer.cpp +++ b/tests/test_timequantizer.cpp @@ -35,7 +35,7 @@ using namespace openspace; namespace { int loadLSKKernel() { - int kernelID = openspace::SpiceManager::ref().loadKernel( + const int kernelID = openspace::SpiceManager::ref().loadKernel( absPath("${TESTDIR}/SpiceTest/spicekernels/naif0008.tls").string() ); CHECK(kernelID == 1); @@ -50,8 +50,9 @@ namespace { CHECK(t.ISO8601() == expected); } - void singleResolutionTest(globebrowsing::TimeQuantizer& tq, std::string resolution, - std::string expectedType, bool expectFailure) + void singleResolutionTest(globebrowsing::TimeQuantizer& tq, + const std::string& resolution, + const std::string& expectedType, bool expectFailure) { std::string res; try { @@ -69,8 +70,9 @@ namespace { } } - void singleStartTimeTest(globebrowsing::TimeQuantizer& tq, std::string startTime, - std::string expectedErrSubstring, bool expectFailure) + void singleStartTimeTest(globebrowsing::TimeQuantizer& tq, + const std::string& startTime, + const std::string& expectedErrSubstring, bool expectFailure) { std::string res; try { @@ -88,12 +90,12 @@ namespace { } } - void singleStartTimeTest(std::string startTime, std::string expectedErrSubstring, - bool expectFailure) + void singleStartTimeTest(const std::string& startTime, + const std::string& expectedErrSubstring, bool expectFailure) { std::string res; try { - globebrowsing::TimeQuantizer tq(startTime, startTime, "1d"); + const globebrowsing::TimeQuantizer tq(startTime, startTime, "1d"); } catch (const ghoul::RuntimeError & e) { res = e.message;